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.

277242 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. #else
  51. #define JUCE_MAC 1
  52. #endif
  53. #else
  54. #error "Unknown platform!"
  55. #endif
  56. #if JUCE_WINDOWS
  57. #ifdef _MSC_VER
  58. #ifdef _WIN64
  59. #define JUCE_64BIT 1
  60. #else
  61. #define JUCE_32BIT 1
  62. #endif
  63. #endif
  64. #ifdef _DEBUG
  65. #define JUCE_DEBUG 1
  66. #endif
  67. #ifdef __MINGW32__
  68. #define JUCE_MINGW 1
  69. #endif
  70. /** If defined, this indicates that the processor is little-endian. */
  71. #define JUCE_LITTLE_ENDIAN 1
  72. #define JUCE_INTEL 1
  73. #endif
  74. #if JUCE_MAC
  75. #ifndef NDEBUG
  76. #define JUCE_DEBUG 1
  77. #endif
  78. #ifdef __LITTLE_ENDIAN__
  79. #define JUCE_LITTLE_ENDIAN 1
  80. #else
  81. #define JUCE_BIG_ENDIAN 1
  82. #endif
  83. #if defined (__ppc__) || defined (__ppc64__)
  84. #define JUCE_PPC 1
  85. #else
  86. #define JUCE_INTEL 1
  87. #endif
  88. #ifdef __LP64__
  89. #define JUCE_64BIT 1
  90. #else
  91. #define JUCE_32BIT 1
  92. #endif
  93. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4
  94. #error "Building for OSX 10.3 is no longer supported!"
  95. #endif
  96. #ifndef MAC_OS_X_VERSION_10_5
  97. #error "To build with 10.4 compatibility, use a 10.5 or 10.6 SDK and set the deployment target to 10.4"
  98. #endif
  99. #endif
  100. #if JUCE_IPHONE
  101. #ifndef NDEBUG
  102. #define JUCE_DEBUG 1
  103. #endif
  104. #ifdef __LITTLE_ENDIAN__
  105. #define JUCE_LITTLE_ENDIAN 1
  106. #else
  107. #define JUCE_BIG_ENDIAN 1
  108. #endif
  109. #endif
  110. #if JUCE_LINUX
  111. #ifdef _DEBUG
  112. #define JUCE_DEBUG 1
  113. #endif
  114. // Allow override for big-endian Linux platforms
  115. #ifndef JUCE_BIG_ENDIAN
  116. #define JUCE_LITTLE_ENDIAN 1
  117. #endif
  118. #if defined (__LP64__) || defined (_LP64)
  119. #define JUCE_64BIT 1
  120. #else
  121. #define JUCE_32BIT 1
  122. #endif
  123. #define JUCE_INTEL 1
  124. #endif
  125. // Compiler type macros.
  126. #ifdef __GNUC__
  127. #define JUCE_GCC 1
  128. #elif defined (_MSC_VER)
  129. #define JUCE_MSVC 1
  130. #if _MSC_VER >= 1400
  131. #define JUCE_USE_INTRINSICS 1
  132. #endif
  133. #else
  134. #error unknown compiler
  135. #endif
  136. #endif // __JUCE_TARGETPLATFORM_JUCEHEADER__
  137. /*** End of inlined file: juce_TargetPlatform.h ***/
  138. // FORCE_AMALGAMATOR_INCLUDE
  139. /*** Start of inlined file: juce_Config.h ***/
  140. #ifndef __JUCE_CONFIG_JUCEHEADER__
  141. #define __JUCE_CONFIG_JUCEHEADER__
  142. /*
  143. This file contains macros that enable/disable various JUCE features.
  144. */
  145. /** The name of the namespace that all Juce classes and functions will be
  146. put inside. If this is not defined, no namespace will be used.
  147. */
  148. #ifndef JUCE_NAMESPACE
  149. #define JUCE_NAMESPACE juce
  150. #endif
  151. /** JUCE_FORCE_DEBUG: Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and
  152. project settings, but if you define this value, you can override this to force
  153. it to be true or false.
  154. */
  155. #ifndef JUCE_FORCE_DEBUG
  156. //#define JUCE_FORCE_DEBUG 0
  157. #endif
  158. /** JUCE_LOG_ASSERTIONS: If this flag is enabled, the the jassert and jassertfalse
  159. macros will always use Logger::writeToLog() to write a message when an assertion happens.
  160. Enabling it will also leave this turned on in release builds. When it's disabled,
  161. however, the jassert and jassertfalse macros will not be compiled in a
  162. release build.
  163. @see jassert, jassertfalse, Logger
  164. */
  165. #ifndef JUCE_LOG_ASSERTIONS
  166. #define JUCE_LOG_ASSERTIONS 0
  167. #endif
  168. /** JUCE_ASIO: Enables ASIO audio devices (MS Windows only).
  169. Turning this on means that you'll need to have the Steinberg ASIO SDK installed
  170. on your Windows build machine.
  171. See the comments in the ASIOAudioIODevice class's header file for more
  172. info about this.
  173. */
  174. #ifndef JUCE_ASIO
  175. #define JUCE_ASIO 0
  176. #endif
  177. /** JUCE_WASAPI: Enables WASAPI audio devices (Windows Vista and above).
  178. */
  179. #ifndef JUCE_WASAPI
  180. #define JUCE_WASAPI 0
  181. #endif
  182. /** JUCE_DIRECTSOUND: Enables DirectSound audio (MS Windows only).
  183. */
  184. #ifndef JUCE_DIRECTSOUND
  185. #define JUCE_DIRECTSOUND 1
  186. #endif
  187. /** JUCE_ALSA: Enables ALSA audio devices (Linux only). */
  188. #ifndef JUCE_ALSA
  189. #define JUCE_ALSA 1
  190. #endif
  191. /** JUCE_JACK: Enables JACK audio devices (Linux only). */
  192. #ifndef JUCE_JACK
  193. #define JUCE_JACK 0
  194. #endif
  195. /** JUCE_QUICKTIME: Enables the QuickTimeMovieComponent class (Mac and Windows).
  196. If you're building on Windows, you'll need to have the Apple QuickTime SDK
  197. installed, and its header files will need to be on your include path.
  198. */
  199. #if ! (defined (JUCE_QUICKTIME) || JUCE_LINUX || JUCE_IPHONE || (JUCE_WINDOWS && ! JUCE_MSVC))
  200. #define JUCE_QUICKTIME 0
  201. #endif
  202. #if (JUCE_IPHONE || JUCE_LINUX) && JUCE_QUICKTIME
  203. #undef JUCE_QUICKTIME
  204. #endif
  205. /** JUCE_OPENGL: Enables the OpenGLComponent class (available on all platforms).
  206. If you're not using OpenGL, you might want to turn this off to reduce your binary's size.
  207. */
  208. #ifndef JUCE_OPENGL
  209. #define JUCE_OPENGL 1
  210. #endif
  211. /** JUCE_USE_FLAC: Enables the FLAC audio codec classes (available on all platforms).
  212. If your app doesn't need to read FLAC files, you might want to disable this to
  213. reduce the size of your codebase and build time.
  214. */
  215. #ifndef JUCE_USE_FLAC
  216. #define JUCE_USE_FLAC 1
  217. #endif
  218. /** JUCE_USE_OGGVORBIS: Enables the Ogg-Vorbis audio codec classes (available on all platforms).
  219. If your app doesn't need to read Ogg-Vorbis files, you might want to disable this to
  220. reduce the size of your codebase and build time.
  221. */
  222. #ifndef JUCE_USE_OGGVORBIS
  223. #define JUCE_USE_OGGVORBIS 1
  224. #endif
  225. /** JUCE_USE_CDBURNER: Enables the audio CD reader code (Mac and Windows only).
  226. Unless you're using CD-burning, you should probably turn this flag off to
  227. reduce code size.
  228. */
  229. #if (! defined (JUCE_USE_CDBURNER)) && ! (JUCE_WINDOWS && ! JUCE_MSVC)
  230. #define JUCE_USE_CDBURNER 0
  231. #endif
  232. /** JUCE_USE_CDREADER: Enables the audio CD reader code (Mac and Windows only).
  233. Unless you're using CD-reading, you should probably turn this flag off to
  234. reduce code size.
  235. */
  236. #ifndef JUCE_USE_CDREADER
  237. #define JUCE_USE_CDREADER 0
  238. #endif
  239. /** JUCE_USE_CAMERA: Enables web-cam support using the CameraDevice class (Mac and Windows).
  240. */
  241. #if (JUCE_QUICKTIME || JUCE_WINDOWS) && ! defined (JUCE_USE_CAMERA)
  242. #define JUCE_USE_CAMERA 0
  243. #endif
  244. /** JUCE_ENABLE_REPAINT_DEBUGGING: If this option is turned on, each area of the screen that
  245. gets repainted will flash in a random colour, so that you can check exactly how much and how
  246. often your components are being drawn.
  247. */
  248. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  249. #define JUCE_ENABLE_REPAINT_DEBUGGING 0
  250. #endif
  251. /** JUCE_USE_XINERAMA: Enables Xinerama multi-monitor support (Linux only).
  252. Unless you specifically want to disable this, it's best to leave this option turned on.
  253. */
  254. #ifndef JUCE_USE_XINERAMA
  255. #define JUCE_USE_XINERAMA 1
  256. #endif
  257. /** JUCE_USE_XSHM: Enables X shared memory for faster rendering on Linux. This is best left
  258. turned on unless you have a good reason to disable it.
  259. */
  260. #ifndef JUCE_USE_XSHM
  261. #define JUCE_USE_XSHM 1
  262. #endif
  263. /** JUCE_USE_XRENDER: Uses XRender to allow semi-transparent windowing on Linux.
  264. */
  265. #ifndef JUCE_USE_XRENDER
  266. #define JUCE_USE_XRENDER 0
  267. #endif
  268. /** JUCE_USE_XCURSOR: Uses XCursor to allow ARGB cursor on Linux. This is best left turned on
  269. unless you have a good reason to disable it.
  270. */
  271. #ifndef JUCE_USE_XCURSOR
  272. #define JUCE_USE_XCURSOR 1
  273. #endif
  274. /** JUCE_PLUGINHOST_VST: Enables the VST audio plugin hosting classes. This requires the
  275. Steinberg VST SDK to be installed on your machine, and should be left turned off unless
  276. you're building a plugin hosting app.
  277. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  278. */
  279. #ifndef JUCE_PLUGINHOST_VST
  280. #define JUCE_PLUGINHOST_VST 0
  281. #endif
  282. /** JUCE_PLUGINHOST_AU: Enables the AudioUnit plugin hosting classes. This is Mac-only,
  283. of course, and should only be enabled if you're building a plugin hosting app.
  284. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  285. */
  286. #ifndef JUCE_PLUGINHOST_AU
  287. #define JUCE_PLUGINHOST_AU 0
  288. #endif
  289. /** JUCE_ONLY_BUILD_CORE_LIBRARY: Enabling this will avoid including any UI classes in the build.
  290. This should be enabled if you're writing a console application.
  291. */
  292. #ifndef JUCE_ONLY_BUILD_CORE_LIBRARY
  293. #define JUCE_ONLY_BUILD_CORE_LIBRARY 0
  294. #endif
  295. /** JUCE_WEB_BROWSER: This lets you disable the WebBrowserComponent class (Mac and Windows).
  296. If you're not using any embedded web-pages, turning this off may reduce your code size.
  297. */
  298. #ifndef JUCE_WEB_BROWSER
  299. #define JUCE_WEB_BROWSER 1
  300. #endif
  301. /** JUCE_SUPPORT_CARBON: Enabling this allows the Mac code to use old Carbon library functions.
  302. Carbon isn't required for a normal app, but may be needed by specialised classes like
  303. plugin-hosts, which support older APIs.
  304. */
  305. #ifndef JUCE_SUPPORT_CARBON
  306. #define JUCE_SUPPORT_CARBON 1
  307. #endif
  308. /* JUCE_INCLUDE_ZLIB_CODE: Can be used to disable Juce's embedded 3rd-party zlib code.
  309. You might need to tweak this if you're linking to an external zlib library in your app,
  310. but for normal apps, this option should be left alone.
  311. */
  312. #ifndef JUCE_INCLUDE_ZLIB_CODE
  313. #define JUCE_INCLUDE_ZLIB_CODE 1
  314. #endif
  315. #ifndef JUCE_INCLUDE_FLAC_CODE
  316. #define JUCE_INCLUDE_FLAC_CODE 1
  317. #endif
  318. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  319. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  320. #endif
  321. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  322. #define JUCE_INCLUDE_PNGLIB_CODE 1
  323. #endif
  324. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  325. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  326. #endif
  327. /** JUCE_CHECK_MEMORY_LEAKS: Enables a memory-leak check when an app terminates.
  328. (Currently, this only affects Windows builds in debug mode).
  329. */
  330. #ifndef JUCE_CHECK_MEMORY_LEAKS
  331. #define JUCE_CHECK_MEMORY_LEAKS 1
  332. #endif
  333. /** JUCE_CATCH_UNHANDLED_EXCEPTIONS: Turn on juce's internal catching of exceptions
  334. that are thrown by the message dispatch loop. With it enabled, any unhandled exceptions
  335. are passed to the JUCEApplication::unhandledException() callback for logging.
  336. */
  337. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  338. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  339. #endif
  340. // If only building the core classes, we can explicitly turn off some features to avoid including them:
  341. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  342. #undef JUCE_QUICKTIME
  343. #define JUCE_QUICKTIME 0
  344. #undef JUCE_OPENGL
  345. #define JUCE_OPENGL 0
  346. #undef JUCE_USE_CDBURNER
  347. #define JUCE_USE_CDBURNER 0
  348. #undef JUCE_USE_CDREADER
  349. #define JUCE_USE_CDREADER 0
  350. #undef JUCE_WEB_BROWSER
  351. #define JUCE_WEB_BROWSER 0
  352. #undef JUCE_PLUGINHOST_AU
  353. #define JUCE_PLUGINHOST_AU 0
  354. #undef JUCE_PLUGINHOST_VST
  355. #define JUCE_PLUGINHOST_VST 0
  356. #endif
  357. #endif
  358. /*** End of inlined file: juce_Config.h ***/
  359. // FORCE_AMALGAMATOR_INCLUDE
  360. #ifndef JUCE_BUILD_CORE
  361. #define JUCE_BUILD_CORE 1
  362. #endif
  363. #ifndef JUCE_BUILD_MISC
  364. #define JUCE_BUILD_MISC 1
  365. #endif
  366. #ifndef JUCE_BUILD_GUI
  367. #define JUCE_BUILD_GUI 1
  368. #endif
  369. #ifndef JUCE_BUILD_NATIVE
  370. #define JUCE_BUILD_NATIVE 1
  371. #endif
  372. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  373. #undef JUCE_BUILD_MISC
  374. #undef JUCE_BUILD_GUI
  375. #endif
  376. //==============================================================================
  377. #if JUCE_BUILD_NATIVE || JUCE_BUILD_CORE || (JUCE_BUILD_MISC && (JUCE_PLUGINHOST_VST || JUCE_PLUGINHOST_AU))
  378. #if JUCE_WINDOWS
  379. /*** Start of inlined file: juce_win32_NativeIncludes.h ***/
  380. #ifndef __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  381. #define __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  382. #ifndef STRICT
  383. #define STRICT 1
  384. #endif
  385. #undef WIN32_LEAN_AND_MEAN
  386. #define WIN32_LEAN_AND_MEAN 1
  387. #if JUCE_MSVC
  388. #pragma warning (push)
  389. #pragma warning (disable : 4100 4201 4514 4312 4995)
  390. #endif
  391. #define _WIN32_WINNT 0x0500
  392. #define _UNICODE 1
  393. #define UNICODE 1
  394. #ifndef _WIN32_IE
  395. #define _WIN32_IE 0x0400
  396. #endif
  397. #include <windows.h>
  398. #include <windowsx.h>
  399. #include <commdlg.h>
  400. #include <shellapi.h>
  401. #include <mmsystem.h>
  402. #include <vfw.h>
  403. #include <tchar.h>
  404. #include <stddef.h>
  405. #include <ctime>
  406. #include <wininet.h>
  407. #include <nb30.h>
  408. #include <iphlpapi.h>
  409. #include <mapi.h>
  410. #include <float.h>
  411. #include <process.h>
  412. #include <Exdisp.h>
  413. #include <exdispid.h>
  414. #include <shlobj.h>
  415. #if ! JUCE_MINGW
  416. #include <crtdbg.h>
  417. #include <comutil.h>
  418. #endif
  419. #if JUCE_OPENGL
  420. #include <gl/gl.h>
  421. #endif
  422. #undef PACKED
  423. #if JUCE_ASIO
  424. /*
  425. This is very frustrating - we only need to use a handful of definitions from
  426. a couple of the header files in Steinberg's ASIO SDK, and it'd be easy to copy
  427. about 30 lines of code into this cpp file to create a fully stand-alone ASIO
  428. implementation...
  429. ..unfortunately that would break Steinberg's license agreement for use of
  430. their SDK, so I'm not allowed to do this.
  431. This means that anyone who wants to use JUCE's ASIO abilities will have to:
  432. 1) Agree to Steinberg's licensing terms and download the ASIO SDK
  433. (see www.steinberg.net/Steinberg/Developers.asp).
  434. 2) Rebuild the whole of JUCE, setting the global definition JUCE_ASIO (you
  435. can un-comment the "#define JUCE_ASIO" line in juce_Config.h
  436. if you prefer). Make sure that your header search path will find the
  437. iasiodrv.h file that comes with the SDK. (Only about 2-3 of the SDK header
  438. files are actually needed - so to simplify things, you could just copy
  439. these into your JUCE directory).
  440. If you're compiling and you get an error here because you don't have the
  441. ASIO SDK installed, you can disable ASIO support by commenting-out the
  442. "#define JUCE_ASIO" line in juce_Config.h, and rebuild your Juce library.
  443. */
  444. #include "iasiodrv.h"
  445. #endif
  446. #if JUCE_USE_CDBURNER
  447. /* You'll need the Platform SDK for these headers - if you don't have it and don't
  448. need to use CD-burning, then you might just want to disable the JUCE_USE_CDBURNER
  449. flag in juce_Config.h to avoid these includes.
  450. */
  451. #include <imapi.h>
  452. #include <imapierror.h>
  453. #endif
  454. #if JUCE_USE_CAMERA
  455. /* If you're using the camera classes, you'll need access to a few DirectShow headers.
  456. These files are provided in the normal Windows SDK, but some Microsoft plonker
  457. didn't realise that qedit.h doesn't actually compile without the rest of the DirectShow SDK..
  458. Microsoft's suggested fix for this is to hack their qedit.h file! See:
  459. http://social.msdn.microsoft.com/Forums/en-US/windowssdk/thread/ed097d2c-3d68-4f48-8448-277eaaf68252
  460. .. which is a bit of a bodge, but a lot less hassle than installing the full DShow SDK.
  461. An alternative workaround is to create a dummy dxtrans.h file and put it in your include path.
  462. The dummy file just needs to contain the following content:
  463. #define __IDxtCompositor_INTERFACE_DEFINED__
  464. #define __IDxtAlphaSetter_INTERFACE_DEFINED__
  465. #define __IDxtJpeg_INTERFACE_DEFINED__
  466. #define __IDxtKey_INTERFACE_DEFINED__
  467. ..and that should be enough to convince qedit.h that you have the SDK!
  468. */
  469. #include <dshow.h>
  470. #include <qedit.h>
  471. #include <dshowasf.h>
  472. #endif
  473. #if JUCE_WASAPI
  474. #include <MMReg.h>
  475. #include <mmdeviceapi.h>
  476. #include <Audioclient.h>
  477. #include <Avrt.h>
  478. #include <functiondiscoverykeys.h>
  479. #endif
  480. #if JUCE_QUICKTIME
  481. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  482. add its header directory to your include path.
  483. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  484. flag in juce_Config.h
  485. */
  486. #include <Movies.h>
  487. #include <QTML.h>
  488. #include <QuickTimeComponents.h>
  489. #include <MediaHandlers.h>
  490. #include <ImageCodec.h>
  491. /* If you've got QuickTime 7 installed, then these COM objects should be found in
  492. the "\Program Files\Quicktime" directory. You'll need to add this directory to
  493. your include search path to make these import statements work.
  494. */
  495. #import <QTOLibrary.dll>
  496. #import <QTOControl.dll>
  497. #endif
  498. #if JUCE_MSVC
  499. #pragma warning (pop)
  500. #endif
  501. /** A simple COM smart pointer.
  502. Avoids having to include ATL just to get one of these.
  503. */
  504. template <class ComClass>
  505. class ComSmartPtr
  506. {
  507. public:
  508. ComSmartPtr() throw() : p (0) {}
  509. ComSmartPtr (ComClass* const p_) : p (p_) { if (p_ != 0) p_->AddRef(); }
  510. ComSmartPtr (const ComSmartPtr<ComClass>& p_) : p (p_.p) { if (p != 0) p->AddRef(); }
  511. ~ComSmartPtr() { if (p != 0) p->Release(); }
  512. operator ComClass*() const throw() { return p; }
  513. ComClass& operator*() const throw() { return *p; }
  514. ComClass** operator&() throw() { return &p; }
  515. ComClass* operator->() const throw() { return p; }
  516. ComClass* operator= (ComClass* const newP)
  517. {
  518. if (newP != 0) newP->AddRef();
  519. if (p != 0) p->Release();
  520. p = newP;
  521. return newP;
  522. }
  523. ComClass* operator= (const ComSmartPtr<ComClass>& newP) { return operator= (newP.p); }
  524. HRESULT CoCreateInstance (REFCLSID rclsid, DWORD dwClsContext = CLSCTX_INPROC_SERVER)
  525. {
  526. #ifndef __MINGW32__
  527. operator= (0);
  528. return ::CoCreateInstance (rclsid, 0, dwClsContext, __uuidof (ComClass), (void**) &p);
  529. #else
  530. return S_FALSE;
  531. #endif
  532. }
  533. private:
  534. ComClass* p;
  535. };
  536. /** Handy base class for writing COM objects, providing ref-counting and a basic QueryInterface method.
  537. */
  538. template <class ComClass>
  539. class ComBaseClassHelper : public ComClass
  540. {
  541. public:
  542. ComBaseClassHelper() : refCount (1) {}
  543. virtual ~ComBaseClassHelper() {}
  544. HRESULT __stdcall QueryInterface (REFIID refId, void __RPC_FAR* __RPC_FAR* result)
  545. {
  546. if (refId == __uuidof (ComClass)) { AddRef(); *result = dynamic_cast <ComClass*> (this); return S_OK; }
  547. if (refId == IID_IUnknown) { AddRef(); *result = dynamic_cast <IUnknown*> (this); return S_OK; }
  548. *result = 0;
  549. return E_NOINTERFACE;
  550. }
  551. ULONG __stdcall AddRef() { return ++refCount; }
  552. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  553. protected:
  554. int refCount;
  555. };
  556. #endif // __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  557. /*** End of inlined file: juce_win32_NativeIncludes.h ***/
  558. #elif JUCE_LINUX
  559. /*** Start of inlined file: juce_linux_NativeIncludes.h ***/
  560. #ifndef __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  561. #define __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  562. /*
  563. This file wraps together all the linux-specific headers, so
  564. that we can include them all just once, and compile all our
  565. platform-specific stuff in one big lump, keeping it out of the
  566. way of the rest of the codebase.
  567. */
  568. #include <sched.h>
  569. #include <pthread.h>
  570. #include <sys/time.h>
  571. #include <errno.h>
  572. #include <sys/stat.h>
  573. #include <sys/dir.h>
  574. #include <sys/ptrace.h>
  575. #include <sys/vfs.h>
  576. #include <sys/wait.h>
  577. #include <fnmatch.h>
  578. #include <utime.h>
  579. #include <pwd.h>
  580. #include <fcntl.h>
  581. #include <dlfcn.h>
  582. #include <netdb.h>
  583. #include <arpa/inet.h>
  584. #include <netinet/in.h>
  585. #include <sys/types.h>
  586. #include <sys/ioctl.h>
  587. #include <sys/socket.h>
  588. #include <linux/if.h>
  589. #include <sys/sysinfo.h>
  590. #include <sys/file.h>
  591. #include <signal.h>
  592. /* Got a build error here? You'll need to install the freetype library...
  593. The name of the package to install is "libfreetype6-dev".
  594. */
  595. #include <ft2build.h>
  596. #include FT_FREETYPE_H
  597. #include <X11/Xlib.h>
  598. #include <X11/Xatom.h>
  599. #include <X11/Xresource.h>
  600. #include <X11/Xutil.h>
  601. #include <X11/Xmd.h>
  602. #include <X11/keysym.h>
  603. #include <X11/cursorfont.h>
  604. #if JUCE_USE_XINERAMA
  605. /* If you're trying to use Xinerama, you'll need to install the "libxinerama-dev" package.. */
  606. #include <X11/extensions/Xinerama.h>
  607. #endif
  608. #if JUCE_USE_XSHM
  609. #include <X11/extensions/XShm.h>
  610. #include <sys/shm.h>
  611. #include <sys/ipc.h>
  612. #endif
  613. #if JUCE_USE_XRENDER
  614. // If you're missing these headers, try installing the libxrender-dev and libxcomposite-dev
  615. #include <X11/extensions/Xrender.h>
  616. #include <X11/extensions/Xcomposite.h>
  617. #endif
  618. #if JUCE_USE_XCURSOR
  619. // If you're missing this header, try installing the libxcursor-dev package
  620. #include <X11/Xcursor/Xcursor.h>
  621. #endif
  622. #if JUCE_OPENGL
  623. /* Got an include error here?
  624. If you want to install OpenGL support, the packages to get are "mesa-common-dev"
  625. and "freeglut3-dev".
  626. Alternatively, you can turn off the JUCE_OPENGL flag in juce_Config.h if you
  627. want to disable it.
  628. */
  629. #include <GL/glx.h>
  630. #endif
  631. #undef KeyPress
  632. #if JUCE_ALSA
  633. /* Got an include error here? If so, you've either not got ALSA installed, or you've
  634. not got your paths set up correctly to find its header files.
  635. The package you need to install to get ASLA support is "libasound2-dev".
  636. If you don't have the ALSA library and don't want to build Juce with audio support,
  637. just disable the JUCE_ALSA flag in juce_Config.h
  638. */
  639. #include <alsa/asoundlib.h>
  640. #endif
  641. #if JUCE_JACK
  642. /* Got an include error here? If so, you've either not got jack-audio-connection-kit
  643. installed, or you've not got your paths set up correctly to find its header files.
  644. The package you need to install to get JACK support is "libjack-dev".
  645. If you don't have the jack-audio-connection-kit library and don't want to build
  646. Juce with low latency audio support, just disable the JUCE_JACK flag in juce_Config.h
  647. */
  648. #include <jack/jack.h>
  649. //#include <jack/transport.h>
  650. #endif
  651. #undef SIZEOF
  652. #endif // __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  653. /*** End of inlined file: juce_linux_NativeIncludes.h ***/
  654. #elif JUCE_MAC || JUCE_IPHONE
  655. /*** Start of inlined file: juce_mac_NativeIncludes.h ***/
  656. #ifndef __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  657. #define __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  658. /*
  659. This file wraps together all the mac-specific code, so that
  660. we can include all the native headers just once, and compile all our
  661. platform-specific stuff in one big lump, keeping it out of the way of
  662. the rest of the codebase.
  663. */
  664. #define USE_COREGRAPHICS_RENDERING 1
  665. #if JUCE_IPHONE
  666. #import <Foundation/Foundation.h>
  667. #import <UIKit/UIKit.h>
  668. #import <AudioToolbox/AudioToolbox.h>
  669. #import <AVFoundation/AVFoundation.h>
  670. #import <CoreData/CoreData.h>
  671. #import <MobileCoreServices/MobileCoreServices.h>
  672. #import <QuartzCore/QuartzCore.h>
  673. #include <sys/fcntl.h>
  674. #if JUCE_OPENGL
  675. #include <OpenGLES/ES1/gl.h>
  676. #include <OpenGLES/ES1/glext.h>
  677. #endif
  678. #else
  679. #import <Cocoa/Cocoa.h>
  680. #import <CoreAudio/HostTime.h>
  681. #import <CoreAudio/AudioHardware.h>
  682. #import <CoreMIDI/MIDIServices.h>
  683. #import <QTKit/QTKit.h>
  684. #import <WebKit/WebKit.h>
  685. #import <DiscRecording/DiscRecording.h>
  686. #import <IOKit/IOKitLib.h>
  687. #import <IOKit/IOCFPlugIn.h>
  688. #import <IOKit/hid/IOHIDLib.h>
  689. #import <IOKit/hid/IOHIDKeys.h>
  690. #import <IOKit/pwr_mgt/IOPMLib.h>
  691. #include <Carbon/Carbon.h>
  692. #include <sys/dir.h>
  693. #endif
  694. #include <sys/socket.h>
  695. #include <sys/sysctl.h>
  696. #include <sys/stat.h>
  697. #include <sys/param.h>
  698. #include <sys/mount.h>
  699. #include <fnmatch.h>
  700. #include <utime.h>
  701. #include <dlfcn.h>
  702. #include <ifaddrs.h>
  703. #include <net/if_dl.h>
  704. #include <mach/mach_time.h>
  705. #if MACOS_10_4_OR_EARLIER
  706. #include <GLUT/glut.h>
  707. #endif
  708. #if ! CGFLOAT_DEFINED
  709. #define CGFloat float
  710. #endif
  711. #endif // __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  712. /*** End of inlined file: juce_mac_NativeIncludes.h ***/
  713. #else
  714. #error "Unknown platform!"
  715. #endif
  716. #endif
  717. //==============================================================================
  718. #define DONT_SET_USING_JUCE_NAMESPACE 1
  719. #undef max
  720. #undef min
  721. #define NO_DUMMY_DECL
  722. #if JUCE_BUILD_NATIVE
  723. #include "juce_amalgamated.h" // FORCE_AMALGAMATOR_INCLUDE
  724. #endif
  725. #if (defined(_MSC_VER) && (_MSC_VER <= 1200))
  726. #pragma warning (disable: 4309 4305)
  727. #endif
  728. #if JUCE_MAC && JUCE_32BIT && JUCE_SUPPORT_CARBON && JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  729. BEGIN_JUCE_NAMESPACE
  730. /*** Start of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  731. #ifndef __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  732. #define __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  733. /**
  734. Creates a floating carbon window that can be used to hold a carbon UI.
  735. This is a handy class that's designed to be inlined where needed, e.g.
  736. in the audio plugin hosting code.
  737. */
  738. class CarbonViewWrapperComponent : public Component,
  739. public ComponentMovementWatcher,
  740. public Timer
  741. {
  742. public:
  743. CarbonViewWrapperComponent()
  744. : ComponentMovementWatcher (this),
  745. wrapperWindow (0),
  746. embeddedView (0),
  747. recursiveResize (false)
  748. {
  749. }
  750. virtual ~CarbonViewWrapperComponent()
  751. {
  752. jassert (embeddedView == 0); // must call deleteWindow() in the subclass's destructor!
  753. }
  754. virtual HIViewRef attachView (WindowRef windowRef, HIViewRef rootView) = 0;
  755. virtual void removeView (HIViewRef embeddedView) = 0;
  756. virtual void mouseDown (int, int) {}
  757. virtual void paint() {}
  758. virtual bool getEmbeddedViewSize (int& w, int& h)
  759. {
  760. if (embeddedView == 0)
  761. return false;
  762. HIRect bounds;
  763. HIViewGetBounds (embeddedView, &bounds);
  764. w = jmax (1, roundToInt (bounds.size.width));
  765. h = jmax (1, roundToInt (bounds.size.height));
  766. return true;
  767. }
  768. void createWindow()
  769. {
  770. if (wrapperWindow == 0)
  771. {
  772. Rect r;
  773. r.left = getScreenX();
  774. r.top = getScreenY();
  775. r.right = r.left + getWidth();
  776. r.bottom = r.top + getHeight();
  777. CreateNewWindow (kDocumentWindowClass,
  778. (WindowAttributes) (kWindowStandardHandlerAttribute | kWindowCompositingAttribute
  779. | kWindowNoShadowAttribute | kWindowNoTitleBarAttribute),
  780. &r, &wrapperWindow);
  781. jassert (wrapperWindow != 0);
  782. if (wrapperWindow == 0)
  783. return;
  784. NSWindow* carbonWindow = [[NSWindow alloc] initWithWindowRef: wrapperWindow];
  785. NSWindow* ownerWindow = [((NSView*) getWindowHandle()) window];
  786. [ownerWindow addChildWindow: carbonWindow
  787. ordered: NSWindowAbove];
  788. embeddedView = attachView (wrapperWindow, HIViewGetRoot (wrapperWindow));
  789. EventTypeSpec windowEventTypes[] =
  790. {
  791. { kEventClassWindow, kEventWindowGetClickActivation },
  792. { kEventClassWindow, kEventWindowHandleDeactivate },
  793. { kEventClassWindow, kEventWindowBoundsChanging },
  794. { kEventClassMouse, kEventMouseDown },
  795. { kEventClassMouse, kEventMouseMoved },
  796. { kEventClassMouse, kEventMouseDragged },
  797. { kEventClassMouse, kEventMouseUp},
  798. { kEventClassWindow, kEventWindowDrawContent },
  799. { kEventClassWindow, kEventWindowShown },
  800. { kEventClassWindow, kEventWindowHidden }
  801. };
  802. EventHandlerUPP upp = NewEventHandlerUPP (carbonEventCallback);
  803. InstallWindowEventHandler (wrapperWindow, upp,
  804. sizeof (windowEventTypes) / sizeof (EventTypeSpec),
  805. windowEventTypes, this, &eventHandlerRef);
  806. setOurSizeToEmbeddedViewSize();
  807. setEmbeddedWindowToOurSize();
  808. creationTime = Time::getCurrentTime();
  809. }
  810. }
  811. void deleteWindow()
  812. {
  813. removeView (embeddedView);
  814. embeddedView = 0;
  815. if (wrapperWindow != 0)
  816. {
  817. RemoveEventHandler (eventHandlerRef);
  818. DisposeWindow (wrapperWindow);
  819. wrapperWindow = 0;
  820. }
  821. }
  822. void setOurSizeToEmbeddedViewSize()
  823. {
  824. int w, h;
  825. if (getEmbeddedViewSize (w, h))
  826. {
  827. if (w != getWidth() || h != getHeight())
  828. {
  829. startTimer (50);
  830. setSize (w, h);
  831. if (getParentComponent() != 0)
  832. getParentComponent()->setSize (w, h);
  833. }
  834. else
  835. {
  836. startTimer (jlimit (50, 500, getTimerInterval() + 20));
  837. }
  838. }
  839. else
  840. {
  841. stopTimer();
  842. }
  843. }
  844. void setEmbeddedWindowToOurSize()
  845. {
  846. if (! recursiveResize)
  847. {
  848. recursiveResize = true;
  849. if (embeddedView != 0)
  850. {
  851. HIRect r;
  852. r.origin.x = 0;
  853. r.origin.y = 0;
  854. r.size.width = (float) getWidth();
  855. r.size.height = (float) getHeight();
  856. HIViewSetFrame (embeddedView, &r);
  857. }
  858. if (wrapperWindow != 0)
  859. {
  860. Rect wr;
  861. wr.left = getScreenX();
  862. wr.top = getScreenY();
  863. wr.right = wr.left + getWidth();
  864. wr.bottom = wr.top + getHeight();
  865. SetWindowBounds (wrapperWindow, kWindowContentRgn, &wr);
  866. ShowWindow (wrapperWindow);
  867. }
  868. recursiveResize = false;
  869. }
  870. }
  871. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  872. {
  873. setEmbeddedWindowToOurSize();
  874. }
  875. void componentPeerChanged()
  876. {
  877. deleteWindow();
  878. createWindow();
  879. }
  880. void componentVisibilityChanged (Component&)
  881. {
  882. if (isShowing())
  883. createWindow();
  884. else
  885. deleteWindow();
  886. setEmbeddedWindowToOurSize();
  887. }
  888. static void recursiveHIViewRepaint (HIViewRef view)
  889. {
  890. HIViewSetNeedsDisplay (view, true);
  891. HIViewRef child = HIViewGetFirstSubview (view);
  892. while (child != 0)
  893. {
  894. recursiveHIViewRepaint (child);
  895. child = HIViewGetNextView (child);
  896. }
  897. }
  898. void timerCallback()
  899. {
  900. setOurSizeToEmbeddedViewSize();
  901. // To avoid strange overpainting problems when the UI is first opened, we'll
  902. // repaint it a few times during the first second that it's on-screen..
  903. if ((Time::getCurrentTime() - creationTime).inMilliseconds() < 1000)
  904. recursiveHIViewRepaint (HIViewGetRoot (wrapperWindow));
  905. }
  906. OSStatus carbonEventHandler (EventHandlerCallRef /*nextHandlerRef*/,
  907. EventRef event)
  908. {
  909. switch (GetEventKind (event))
  910. {
  911. case kEventWindowHandleDeactivate:
  912. ActivateWindow (wrapperWindow, TRUE);
  913. break;
  914. case kEventWindowGetClickActivation:
  915. {
  916. getTopLevelComponent()->toFront (false);
  917. ClickActivationResult howToHandleClick = kActivateAndHandleClick;
  918. SetEventParameter (event, kEventParamClickActivation, typeClickActivationResult,
  919. sizeof (ClickActivationResult), &howToHandleClick);
  920. HIViewSetNeedsDisplay (embeddedView, true);
  921. }
  922. break;
  923. }
  924. return noErr;
  925. }
  926. static pascal OSStatus carbonEventCallback (EventHandlerCallRef nextHandlerRef,
  927. EventRef event, void* userData)
  928. {
  929. return ((CarbonViewWrapperComponent*) userData)->carbonEventHandler (nextHandlerRef, event);
  930. }
  931. protected:
  932. WindowRef wrapperWindow;
  933. HIViewRef embeddedView;
  934. bool recursiveResize;
  935. Time creationTime;
  936. EventHandlerRef eventHandlerRef;
  937. };
  938. #endif // __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  939. /*** End of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  940. END_JUCE_NAMESPACE
  941. #endif
  942. #define JUCE_AMALGAMATED_TEMPLATE 1
  943. //==============================================================================
  944. #if JUCE_BUILD_CORE
  945. /*** Start of inlined file: juce_FileLogger.cpp ***/
  946. BEGIN_JUCE_NAMESPACE
  947. FileLogger::FileLogger (const File& logFile_,
  948. const String& welcomeMessage,
  949. const int maxInitialFileSizeBytes)
  950. : logFile (logFile_)
  951. {
  952. if (maxInitialFileSizeBytes >= 0)
  953. trimFileSize (maxInitialFileSizeBytes);
  954. if (! logFile_.exists())
  955. {
  956. // do this so that the parent directories get created..
  957. logFile_.create();
  958. }
  959. logStream = logFile_.createOutputStream (256);
  960. jassert (logStream != 0);
  961. String welcome;
  962. welcome << "\r\n**********************************************************\r\n"
  963. << welcomeMessage
  964. << "\r\nLog started: " << Time::getCurrentTime().toString (true, true)
  965. << "\r\n";
  966. logMessage (welcome);
  967. }
  968. FileLogger::~FileLogger()
  969. {
  970. }
  971. void FileLogger::logMessage (const String& message)
  972. {
  973. if (logStream != 0)
  974. {
  975. DBG (message);
  976. const ScopedLock sl (logLock);
  977. (*logStream) << message << "\r\n";
  978. logStream->flush();
  979. }
  980. }
  981. void FileLogger::trimFileSize (int maxFileSizeBytes) const
  982. {
  983. if (maxFileSizeBytes <= 0)
  984. {
  985. logFile.deleteFile();
  986. }
  987. else
  988. {
  989. const int64 fileSize = logFile.getSize();
  990. if (fileSize > maxFileSizeBytes)
  991. {
  992. ScopedPointer <FileInputStream> in (logFile.createInputStream());
  993. jassert (in != 0);
  994. if (in != 0)
  995. {
  996. in->setPosition (fileSize - maxFileSizeBytes);
  997. String content;
  998. {
  999. MemoryBlock contentToSave;
  1000. contentToSave.setSize (maxFileSizeBytes + 4);
  1001. contentToSave.fillWith (0);
  1002. in->read (contentToSave.getData(), maxFileSizeBytes);
  1003. in = 0;
  1004. content = contentToSave.toString();
  1005. }
  1006. int newStart = 0;
  1007. while (newStart < fileSize
  1008. && content[newStart] != '\n'
  1009. && content[newStart] != '\r')
  1010. ++newStart;
  1011. logFile.deleteFile();
  1012. logFile.appendText (content.substring (newStart), false, false);
  1013. }
  1014. }
  1015. }
  1016. }
  1017. FileLogger* FileLogger::createDefaultAppLogger (const String& logFileSubDirectoryName,
  1018. const String& logFileName,
  1019. const String& welcomeMessage,
  1020. const int maxInitialFileSizeBytes)
  1021. {
  1022. #if JUCE_MAC
  1023. File logFile ("~/Library/Logs");
  1024. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1025. .getChildFile (logFileName);
  1026. #else
  1027. File logFile (File::getSpecialLocation (File::userApplicationDataDirectory));
  1028. if (logFile.isDirectory())
  1029. {
  1030. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1031. .getChildFile (logFileName);
  1032. }
  1033. #endif
  1034. return new FileLogger (logFile, welcomeMessage, maxInitialFileSizeBytes);
  1035. }
  1036. END_JUCE_NAMESPACE
  1037. /*** End of inlined file: juce_FileLogger.cpp ***/
  1038. /*** Start of inlined file: juce_Logger.cpp ***/
  1039. BEGIN_JUCE_NAMESPACE
  1040. Logger::Logger()
  1041. {
  1042. }
  1043. Logger::~Logger()
  1044. {
  1045. }
  1046. Logger* Logger::currentLogger = 0;
  1047. void Logger::setCurrentLogger (Logger* const newLogger,
  1048. const bool deleteOldLogger)
  1049. {
  1050. Logger* const oldLogger = currentLogger;
  1051. currentLogger = newLogger;
  1052. if (deleteOldLogger)
  1053. delete oldLogger;
  1054. }
  1055. void Logger::writeToLog (const String& message)
  1056. {
  1057. if (currentLogger != 0)
  1058. currentLogger->logMessage (message);
  1059. else
  1060. outputDebugString (message);
  1061. }
  1062. #if JUCE_LOG_ASSERTIONS
  1063. void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw()
  1064. {
  1065. String m ("JUCE Assertion failure in ");
  1066. m << filename << ", line " << lineNum;
  1067. Logger::writeToLog (m);
  1068. }
  1069. #endif
  1070. END_JUCE_NAMESPACE
  1071. /*** End of inlined file: juce_Logger.cpp ***/
  1072. /*** Start of inlined file: juce_Random.cpp ***/
  1073. BEGIN_JUCE_NAMESPACE
  1074. Random::Random (const int64 seedValue) throw()
  1075. : seed (seedValue)
  1076. {
  1077. }
  1078. Random::~Random() throw()
  1079. {
  1080. }
  1081. void Random::setSeed (const int64 newSeed) throw()
  1082. {
  1083. seed = newSeed;
  1084. }
  1085. void Random::combineSeed (const int64 seedValue) throw()
  1086. {
  1087. seed ^= nextInt64() ^ seedValue;
  1088. }
  1089. void Random::setSeedRandomly()
  1090. {
  1091. combineSeed ((int64) (pointer_sized_int) this);
  1092. combineSeed (Time::getMillisecondCounter());
  1093. combineSeed (Time::getHighResolutionTicks());
  1094. combineSeed (Time::getHighResolutionTicksPerSecond());
  1095. combineSeed (Time::currentTimeMillis());
  1096. }
  1097. int Random::nextInt() throw()
  1098. {
  1099. seed = (seed * literal64bit (0x5deece66d) + 11) & literal64bit (0xffffffffffff);
  1100. return (int) (seed >> 16);
  1101. }
  1102. int Random::nextInt (const int maxValue) throw()
  1103. {
  1104. jassert (maxValue > 0);
  1105. return (nextInt() & 0x7fffffff) % maxValue;
  1106. }
  1107. int64 Random::nextInt64() throw()
  1108. {
  1109. return (((int64) nextInt()) << 32) | (int64) (uint64) (uint32) nextInt();
  1110. }
  1111. bool Random::nextBool() throw()
  1112. {
  1113. return (nextInt() & 0x80000000) != 0;
  1114. }
  1115. float Random::nextFloat() throw()
  1116. {
  1117. return static_cast <uint32> (nextInt()) / (float) 0xffffffff;
  1118. }
  1119. double Random::nextDouble() throw()
  1120. {
  1121. return static_cast <uint32> (nextInt()) / (double) 0xffffffff;
  1122. }
  1123. const BigInteger Random::nextLargeNumber (const BigInteger& maximumValue)
  1124. {
  1125. BigInteger n;
  1126. do
  1127. {
  1128. fillBitsRandomly (n, 0, maximumValue.getHighestBit() + 1);
  1129. }
  1130. while (n >= maximumValue);
  1131. return n;
  1132. }
  1133. void Random::fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits)
  1134. {
  1135. arrayToChange.setBit (startBit + numBits - 1, true); // to force the array to pre-allocate space
  1136. while ((startBit & 31) != 0 && numBits > 0)
  1137. {
  1138. arrayToChange.setBit (startBit++, nextBool());
  1139. --numBits;
  1140. }
  1141. while (numBits >= 32)
  1142. {
  1143. arrayToChange.setBitRangeAsInt (startBit, 32, (unsigned int) nextInt());
  1144. startBit += 32;
  1145. numBits -= 32;
  1146. }
  1147. while (--numBits >= 0)
  1148. arrayToChange.setBit (startBit + numBits, nextBool());
  1149. }
  1150. Random& Random::getSystemRandom() throw()
  1151. {
  1152. static Random sysRand (1);
  1153. return sysRand;
  1154. }
  1155. END_JUCE_NAMESPACE
  1156. /*** End of inlined file: juce_Random.cpp ***/
  1157. /*** Start of inlined file: juce_RelativeTime.cpp ***/
  1158. BEGIN_JUCE_NAMESPACE
  1159. RelativeTime::RelativeTime (const double seconds_) throw()
  1160. : seconds (seconds_)
  1161. {
  1162. }
  1163. RelativeTime::RelativeTime (const RelativeTime& other) throw()
  1164. : seconds (other.seconds)
  1165. {
  1166. }
  1167. RelativeTime::~RelativeTime() throw()
  1168. {
  1169. }
  1170. const RelativeTime RelativeTime::milliseconds (const int milliseconds) throw()
  1171. {
  1172. return RelativeTime (milliseconds * 0.001);
  1173. }
  1174. const RelativeTime RelativeTime::milliseconds (const int64 milliseconds) throw()
  1175. {
  1176. return RelativeTime (milliseconds * 0.001);
  1177. }
  1178. const RelativeTime RelativeTime::minutes (const double numberOfMinutes) throw()
  1179. {
  1180. return RelativeTime (numberOfMinutes * 60.0);
  1181. }
  1182. const RelativeTime RelativeTime::hours (const double numberOfHours) throw()
  1183. {
  1184. return RelativeTime (numberOfHours * (60.0 * 60.0));
  1185. }
  1186. const RelativeTime RelativeTime::days (const double numberOfDays) throw()
  1187. {
  1188. return RelativeTime (numberOfDays * (60.0 * 60.0 * 24.0));
  1189. }
  1190. const RelativeTime RelativeTime::weeks (const double numberOfWeeks) throw()
  1191. {
  1192. return RelativeTime (numberOfWeeks * (60.0 * 60.0 * 24.0 * 7.0));
  1193. }
  1194. int64 RelativeTime::inMilliseconds() const throw()
  1195. {
  1196. return (int64)(seconds * 1000.0);
  1197. }
  1198. double RelativeTime::inMinutes() const throw()
  1199. {
  1200. return seconds / 60.0;
  1201. }
  1202. double RelativeTime::inHours() const throw()
  1203. {
  1204. return seconds / (60.0 * 60.0);
  1205. }
  1206. double RelativeTime::inDays() const throw()
  1207. {
  1208. return seconds / (60.0 * 60.0 * 24.0);
  1209. }
  1210. double RelativeTime::inWeeks() const throw()
  1211. {
  1212. return seconds / (60.0 * 60.0 * 24.0 * 7.0);
  1213. }
  1214. const String RelativeTime::getDescription (const String& returnValueForZeroTime) const throw()
  1215. {
  1216. if (seconds < 0.001 && seconds > -0.001)
  1217. return returnValueForZeroTime;
  1218. String result;
  1219. if (seconds < 0)
  1220. result = "-";
  1221. int fieldsShown = 0;
  1222. int n = abs ((int) inWeeks());
  1223. if (n > 0)
  1224. {
  1225. result << n << ((n == 1) ? TRANS(" week ")
  1226. : TRANS(" weeks "));
  1227. ++fieldsShown;
  1228. }
  1229. n = abs ((int) inDays()) % 7;
  1230. if (n > 0)
  1231. {
  1232. result << n << ((n == 1) ? TRANS(" day ")
  1233. : TRANS(" days "));
  1234. ++fieldsShown;
  1235. }
  1236. if (fieldsShown < 2)
  1237. {
  1238. n = abs ((int) inHours()) % 24;
  1239. if (n > 0)
  1240. {
  1241. result << n << ((n == 1) ? TRANS(" hr ")
  1242. : TRANS(" hrs "));
  1243. ++fieldsShown;
  1244. }
  1245. if (fieldsShown < 2)
  1246. {
  1247. n = abs ((int) inMinutes()) % 60;
  1248. if (n > 0)
  1249. {
  1250. result << n << ((n == 1) ? TRANS(" min ")
  1251. : TRANS(" mins "));
  1252. ++fieldsShown;
  1253. }
  1254. if (fieldsShown < 2)
  1255. {
  1256. n = abs ((int) inSeconds()) % 60;
  1257. if (n > 0)
  1258. {
  1259. result << n << ((n == 1) ? TRANS(" sec ")
  1260. : TRANS(" secs "));
  1261. ++fieldsShown;
  1262. }
  1263. if (fieldsShown < 1)
  1264. {
  1265. n = abs ((int) inMilliseconds()) % 1000;
  1266. if (n > 0)
  1267. {
  1268. result << n << TRANS(" ms");
  1269. ++fieldsShown;
  1270. }
  1271. }
  1272. }
  1273. }
  1274. }
  1275. return result.trimEnd();
  1276. }
  1277. RelativeTime& RelativeTime::operator= (const RelativeTime& other) throw()
  1278. {
  1279. seconds = other.seconds;
  1280. return *this;
  1281. }
  1282. bool RelativeTime::operator== (const RelativeTime& other) const throw()
  1283. {
  1284. return seconds == other.seconds;
  1285. }
  1286. bool RelativeTime::operator!= (const RelativeTime& other) const throw()
  1287. {
  1288. return seconds != other.seconds;
  1289. }
  1290. bool RelativeTime::operator> (const RelativeTime& other) const throw()
  1291. {
  1292. return seconds > other.seconds;
  1293. }
  1294. bool RelativeTime::operator< (const RelativeTime& other) const throw()
  1295. {
  1296. return seconds < other.seconds;
  1297. }
  1298. bool RelativeTime::operator>= (const RelativeTime& other) const throw()
  1299. {
  1300. return seconds >= other.seconds;
  1301. }
  1302. bool RelativeTime::operator<= (const RelativeTime& other) const throw()
  1303. {
  1304. return seconds <= other.seconds;
  1305. }
  1306. const RelativeTime RelativeTime::operator+ (const RelativeTime& timeToAdd) const throw()
  1307. {
  1308. return RelativeTime (seconds + timeToAdd.seconds);
  1309. }
  1310. const RelativeTime RelativeTime::operator- (const RelativeTime& timeToSubtract) const throw()
  1311. {
  1312. return RelativeTime (seconds - timeToSubtract.seconds);
  1313. }
  1314. const RelativeTime RelativeTime::operator+ (const double secondsToAdd) const throw()
  1315. {
  1316. return RelativeTime (seconds + secondsToAdd);
  1317. }
  1318. const RelativeTime RelativeTime::operator- (const double secondsToSubtract) const throw()
  1319. {
  1320. return RelativeTime (seconds - secondsToSubtract);
  1321. }
  1322. const RelativeTime& RelativeTime::operator+= (const RelativeTime& timeToAdd) throw()
  1323. {
  1324. seconds += timeToAdd.seconds;
  1325. return *this;
  1326. }
  1327. const RelativeTime& RelativeTime::operator-= (const RelativeTime& timeToSubtract) throw()
  1328. {
  1329. seconds -= timeToSubtract.seconds;
  1330. return *this;
  1331. }
  1332. const RelativeTime& RelativeTime::operator+= (const double secondsToAdd) throw()
  1333. {
  1334. seconds += secondsToAdd;
  1335. return *this;
  1336. }
  1337. const RelativeTime& RelativeTime::operator-= (const double secondsToSubtract) throw()
  1338. {
  1339. seconds -= secondsToSubtract;
  1340. return *this;
  1341. }
  1342. END_JUCE_NAMESPACE
  1343. /*** End of inlined file: juce_RelativeTime.cpp ***/
  1344. /*** Start of inlined file: juce_SystemStats.cpp ***/
  1345. BEGIN_JUCE_NAMESPACE
  1346. SystemStats::CPUFlags SystemStats::cpuFlags;
  1347. const String SystemStats::getJUCEVersion()
  1348. {
  1349. return "JUCE v" + String (JUCE_MAJOR_VERSION)
  1350. + "." + String (JUCE_MINOR_VERSION)
  1351. + "." + String (JUCE_BUILDNUMBER);
  1352. }
  1353. const StringArray SystemStats::getMACAddressStrings()
  1354. {
  1355. int64 macAddresses [16];
  1356. const int numAddresses = getMACAddresses (macAddresses, numElementsInArray (macAddresses), false);
  1357. StringArray s;
  1358. for (int i = 0; i < numAddresses; ++i)
  1359. {
  1360. s.add (String::toHexString (0xff & (int) (macAddresses [i] >> 40)).paddedLeft ('0', 2)
  1361. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 32)).paddedLeft ('0', 2)
  1362. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 24)).paddedLeft ('0', 2)
  1363. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 16)).paddedLeft ('0', 2)
  1364. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 8)).paddedLeft ('0', 2)
  1365. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 0)).paddedLeft ('0', 2));
  1366. }
  1367. return s;
  1368. }
  1369. static bool juceInitialisedNonGUI = false;
  1370. #if JUCE_DEBUG
  1371. template <typename Type>
  1372. static void juce_testAtomicType (Type)
  1373. {
  1374. Atomic<Type> a, b;
  1375. a.set ((Type) 10);
  1376. a += (Type) 15;
  1377. a.memoryBarrier();
  1378. a -= (Type) 5;
  1379. ++a;
  1380. ++a;
  1381. --a;
  1382. a.memoryBarrier();
  1383. /* These are some simple test cases to check the atomics - let me know
  1384. if any of these assertions fail on your system!
  1385. */
  1386. jassert (a.get() == (Type) 21);
  1387. jassert (a.compareAndSetValue ((Type) 100, (Type) 50) == (Type) 21);
  1388. jassert (a.get() == (Type) 21);
  1389. jassert (a.compareAndSetValue ((Type) 101, a.get()) == (Type) 21);
  1390. jassert (a.get() == (Type) 101);
  1391. jassert (! a.compareAndSetBool ((Type) 300, (Type) 200));
  1392. jassert (a.get() == (Type) 101);
  1393. jassert (a.compareAndSetBool ((Type) 200, a.get()));
  1394. jassert (a.get() == (Type) 200);
  1395. jassert (a.exchange ((Type) 300) == (Type) 200);
  1396. jassert (a.get() == (Type) 300);
  1397. b = a;
  1398. jassert (b.get() == a.get());
  1399. }
  1400. static void juce_testAtomics()
  1401. {
  1402. juce_testAtomicType ((int) 0);
  1403. juce_testAtomicType ((unsigned int) 0);
  1404. juce_testAtomicType ((int32) 0);
  1405. juce_testAtomicType ((uint32) 0);
  1406. juce_testAtomicType ((long) 0);
  1407. juce_testAtomicType ((void*) 0);
  1408. juce_testAtomicType ((int*) 0);
  1409. #if ! JUCE_64BIT_ATOMICS_UNAVAILABLE // 64-bit intrinsics aren't available on some old platforms
  1410. juce_testAtomicType ((int64) 0);
  1411. juce_testAtomicType ((uint64) 0);
  1412. #endif
  1413. }
  1414. #endif
  1415. void JUCE_PUBLIC_FUNCTION initialiseJuce_NonGUI()
  1416. {
  1417. if (! juceInitialisedNonGUI)
  1418. {
  1419. #if JUCE_MAC || JUCE_IPHONE
  1420. const ScopedAutoReleasePool pool;
  1421. #endif
  1422. #if JUCE_DEBUG
  1423. {
  1424. // Some simple test code to keep an eye on things and make sure these functions
  1425. // work ok on all platforms. Let me know if any of these assertions fail!
  1426. static_jassert (sizeof (pointer_sized_int) == sizeof (void*));
  1427. static_jassert (sizeof (int8) == 1);
  1428. static_jassert (sizeof (uint8) == 1);
  1429. static_jassert (sizeof (int16) == 2);
  1430. static_jassert (sizeof (uint16) == 2);
  1431. static_jassert (sizeof (int32) == 4);
  1432. static_jassert (sizeof (uint32) == 4);
  1433. static_jassert (sizeof (int64) == 8);
  1434. static_jassert (sizeof (uint64) == 8);
  1435. char a1[7];
  1436. jassert (numElementsInArray(a1) == 7);
  1437. int a2[3];
  1438. jassert (numElementsInArray(a2) == 3);
  1439. juce_testAtomics();
  1440. jassert (ByteOrder::swap ((uint16) 0x1122) == 0x2211);
  1441. jassert (ByteOrder::swap ((uint32) 0x11223344) == 0x44332211);
  1442. // Some quick stream tests..
  1443. int randomInt = Random::getSystemRandom().nextInt();
  1444. int64 randomInt64 = Random::getSystemRandom().nextInt64();
  1445. double randomDouble = Random::getSystemRandom().nextDouble();
  1446. String randomString;
  1447. for (int i = 50; --i >= 0;)
  1448. randomString << (juce_wchar) (Random::getSystemRandom().nextInt() & 0xffff);
  1449. MemoryOutputStream mo;
  1450. mo.writeInt (randomInt);
  1451. mo.writeIntBigEndian (randomInt);
  1452. mo.writeCompressedInt (randomInt);
  1453. mo.writeString (randomString);
  1454. mo.writeInt64 (randomInt64);
  1455. mo.writeInt64BigEndian (randomInt64);
  1456. mo.writeDouble (randomDouble);
  1457. mo.writeDoubleBigEndian (randomDouble);
  1458. MemoryInputStream mi (mo.getData(), mo.getDataSize(), false);
  1459. jassert (mi.readInt() == randomInt);
  1460. jassert (mi.readIntBigEndian() == randomInt);
  1461. jassert (mi.readCompressedInt() == randomInt);
  1462. jassert (mi.readString() == randomString);
  1463. jassert (mi.readInt64() == randomInt64);
  1464. jassert (mi.readInt64BigEndian() == randomInt64);
  1465. jassert (mi.readDouble() == randomDouble);
  1466. jassert (mi.readDoubleBigEndian() == randomDouble);
  1467. }
  1468. #endif
  1469. // Now the real initialisation..
  1470. juceInitialisedNonGUI = true;
  1471. DBG (SystemStats::getJUCEVersion());
  1472. SystemStats::initialiseStats();
  1473. Random::getSystemRandom().setSeedRandomly(); // (mustn't call this before initialiseStats() because it relies on the time being set up)
  1474. }
  1475. }
  1476. #if JUCE_WINDOWS
  1477. extern void juce_shutdownWin32Sockets(); // (defined in the sockets code)
  1478. #endif
  1479. #if JUCE_DEBUG
  1480. extern void juce_CheckForDanglingStreams();
  1481. #endif
  1482. void JUCE_PUBLIC_FUNCTION shutdownJuce_NonGUI()
  1483. {
  1484. if (juceInitialisedNonGUI)
  1485. {
  1486. #if JUCE_MAC || JUCE_IPHONE
  1487. const ScopedAutoReleasePool pool;
  1488. #endif
  1489. #if JUCE_WINDOWS
  1490. // need to shut down sockets if they were used..
  1491. juce_shutdownWin32Sockets();
  1492. #endif
  1493. LocalisedStrings::setCurrentMappings (0);
  1494. Thread::stopAllThreads (3000);
  1495. #if JUCE_DEBUG
  1496. juce_CheckForDanglingStreams();
  1497. #endif
  1498. juceInitialisedNonGUI = false;
  1499. }
  1500. }
  1501. #ifdef JUCE_DLL
  1502. void* juce_Malloc (const int size)
  1503. {
  1504. return malloc (size);
  1505. }
  1506. void* juce_Calloc (const int size)
  1507. {
  1508. return calloc (1, size);
  1509. }
  1510. void* juce_Realloc (void* const block, const int size)
  1511. {
  1512. return realloc (block, size);
  1513. }
  1514. void juce_Free (void* const block)
  1515. {
  1516. free (block);
  1517. }
  1518. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  1519. void* juce_DebugMalloc (const int size, const char* file, const int line)
  1520. {
  1521. return _malloc_dbg (size, _NORMAL_BLOCK, file, line);
  1522. }
  1523. void* juce_DebugCalloc (const int size, const char* file, const int line)
  1524. {
  1525. return _calloc_dbg (1, size, _NORMAL_BLOCK, file, line);
  1526. }
  1527. void* juce_DebugRealloc (void* const block, const int size, const char* file, const int line)
  1528. {
  1529. return _realloc_dbg (block, size, _NORMAL_BLOCK, file, line);
  1530. }
  1531. void juce_DebugFree (void* const block)
  1532. {
  1533. _free_dbg (block, _NORMAL_BLOCK);
  1534. }
  1535. #endif
  1536. #endif
  1537. END_JUCE_NAMESPACE
  1538. /*** End of inlined file: juce_SystemStats.cpp ***/
  1539. /*** Start of inlined file: juce_Time.cpp ***/
  1540. #if JUCE_MSVC
  1541. #pragma warning (push)
  1542. #pragma warning (disable: 4514)
  1543. #endif
  1544. #ifndef JUCE_WINDOWS
  1545. #include <sys/time.h>
  1546. #else
  1547. #include <ctime>
  1548. #endif
  1549. #include <sys/timeb.h>
  1550. #if JUCE_MSVC
  1551. #pragma warning (pop)
  1552. #ifdef _INC_TIME_INL
  1553. #define USE_NEW_SECURE_TIME_FNS
  1554. #endif
  1555. #endif
  1556. BEGIN_JUCE_NAMESPACE
  1557. namespace TimeHelpers
  1558. {
  1559. static struct tm millisToLocal (const int64 millis) throw()
  1560. {
  1561. struct tm result;
  1562. const int64 seconds = millis / 1000;
  1563. if (seconds < literal64bit (86400) || seconds >= literal64bit (2145916800))
  1564. {
  1565. // use extended maths for dates beyond 1970 to 2037..
  1566. const int timeZoneAdjustment = 31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000);
  1567. const int64 jdm = seconds + timeZoneAdjustment + literal64bit (210866803200);
  1568. const int days = (int) (jdm / literal64bit (86400));
  1569. const int a = 32044 + days;
  1570. const int b = (4 * a + 3) / 146097;
  1571. const int c = a - (b * 146097) / 4;
  1572. const int d = (4 * c + 3) / 1461;
  1573. const int e = c - (d * 1461) / 4;
  1574. const int m = (5 * e + 2) / 153;
  1575. result.tm_mday = e - (153 * m + 2) / 5 + 1;
  1576. result.tm_mon = m + 2 - 12 * (m / 10);
  1577. result.tm_year = b * 100 + d - 6700 + (m / 10);
  1578. result.tm_wday = (days + 1) % 7;
  1579. result.tm_yday = -1;
  1580. int t = (int) (jdm % literal64bit (86400));
  1581. result.tm_hour = t / 3600;
  1582. t %= 3600;
  1583. result.tm_min = t / 60;
  1584. result.tm_sec = t % 60;
  1585. result.tm_isdst = -1;
  1586. }
  1587. else
  1588. {
  1589. time_t now = static_cast <time_t> (seconds);
  1590. #if JUCE_WINDOWS
  1591. #ifdef USE_NEW_SECURE_TIME_FNS
  1592. if (now >= 0 && now <= 0x793406fff)
  1593. localtime_s (&result, &now);
  1594. else
  1595. zeromem (&result, sizeof (result));
  1596. #else
  1597. result = *localtime (&now);
  1598. #endif
  1599. #else
  1600. // more thread-safe
  1601. localtime_r (&now, &result);
  1602. #endif
  1603. }
  1604. return result;
  1605. }
  1606. static int extendedModulo (const int64 value, const int modulo) throw()
  1607. {
  1608. return (int) (value >= 0 ? (value % modulo)
  1609. : (value - ((value / modulo) + 1) * modulo));
  1610. }
  1611. static uint32 lastMSCounterValue = 0;
  1612. }
  1613. Time::Time() throw()
  1614. : millisSinceEpoch (0)
  1615. {
  1616. }
  1617. Time::Time (const Time& other) throw()
  1618. : millisSinceEpoch (other.millisSinceEpoch)
  1619. {
  1620. }
  1621. Time::Time (const int64 ms) throw()
  1622. : millisSinceEpoch (ms)
  1623. {
  1624. }
  1625. Time::Time (const int year,
  1626. const int month,
  1627. const int day,
  1628. const int hours,
  1629. const int minutes,
  1630. const int seconds,
  1631. const int milliseconds,
  1632. const bool useLocalTime) throw()
  1633. {
  1634. jassert (year > 100); // year must be a 4-digit version
  1635. if (year < 1971 || year >= 2038 || ! useLocalTime)
  1636. {
  1637. // use extended maths for dates beyond 1970 to 2037..
  1638. const int timeZoneAdjustment = useLocalTime ? (31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000))
  1639. : 0;
  1640. const int a = (13 - month) / 12;
  1641. const int y = year + 4800 - a;
  1642. const int jd = day + (153 * (month + 12 * a - 2) + 2) / 5
  1643. + (y * 365) + (y / 4) - (y / 100) + (y / 400)
  1644. - 32045;
  1645. const int64 s = ((int64) jd) * literal64bit (86400) - literal64bit (210866803200);
  1646. millisSinceEpoch = 1000 * (s + (hours * 3600 + minutes * 60 + seconds - timeZoneAdjustment))
  1647. + milliseconds;
  1648. }
  1649. else
  1650. {
  1651. struct tm t;
  1652. t.tm_year = year - 1900;
  1653. t.tm_mon = month;
  1654. t.tm_mday = day;
  1655. t.tm_hour = hours;
  1656. t.tm_min = minutes;
  1657. t.tm_sec = seconds;
  1658. t.tm_isdst = -1;
  1659. millisSinceEpoch = 1000 * (int64) mktime (&t);
  1660. if (millisSinceEpoch < 0)
  1661. millisSinceEpoch = 0;
  1662. else
  1663. millisSinceEpoch += milliseconds;
  1664. }
  1665. }
  1666. Time::~Time() throw()
  1667. {
  1668. }
  1669. Time& Time::operator= (const Time& other) throw()
  1670. {
  1671. millisSinceEpoch = other.millisSinceEpoch;
  1672. return *this;
  1673. }
  1674. int64 Time::currentTimeMillis() throw()
  1675. {
  1676. static uint32 lastCounterResult = 0xffffffff;
  1677. static int64 correction = 0;
  1678. const uint32 now = getMillisecondCounter();
  1679. // check the counter hasn't wrapped (also triggered the first time this function is called)
  1680. if (now < lastCounterResult)
  1681. {
  1682. // double-check it's actually wrapped, in case multi-cpu machines have timers that drift a bit.
  1683. if (lastCounterResult == 0xffffffff || now < lastCounterResult - 10)
  1684. {
  1685. // get the time once using normal library calls, and store the difference needed to
  1686. // turn the millisecond counter into a real time.
  1687. #if JUCE_WINDOWS
  1688. struct _timeb t;
  1689. #ifdef USE_NEW_SECURE_TIME_FNS
  1690. _ftime_s (&t);
  1691. #else
  1692. _ftime (&t);
  1693. #endif
  1694. correction = (((int64) t.time) * 1000 + t.millitm) - now;
  1695. #else
  1696. struct timeval tv;
  1697. struct timezone tz;
  1698. gettimeofday (&tv, &tz);
  1699. correction = (((int64) tv.tv_sec) * 1000 + tv.tv_usec / 1000) - now;
  1700. #endif
  1701. }
  1702. }
  1703. lastCounterResult = now;
  1704. return correction + now;
  1705. }
  1706. uint32 juce_millisecondsSinceStartup() throw();
  1707. uint32 Time::getMillisecondCounter() throw()
  1708. {
  1709. const uint32 now = juce_millisecondsSinceStartup();
  1710. if (now < TimeHelpers::lastMSCounterValue)
  1711. {
  1712. // in multi-threaded apps this might be called concurrently, so
  1713. // make sure that our last counter value only increases and doesn't
  1714. // go backwards..
  1715. if (now < TimeHelpers::lastMSCounterValue - 1000)
  1716. TimeHelpers::lastMSCounterValue = now;
  1717. }
  1718. else
  1719. {
  1720. TimeHelpers::lastMSCounterValue = now;
  1721. }
  1722. return now;
  1723. }
  1724. uint32 Time::getApproximateMillisecondCounter() throw()
  1725. {
  1726. jassert (TimeHelpers::lastMSCounterValue != 0);
  1727. return TimeHelpers::lastMSCounterValue;
  1728. }
  1729. void Time::waitForMillisecondCounter (const uint32 targetTime) throw()
  1730. {
  1731. for (;;)
  1732. {
  1733. const uint32 now = getMillisecondCounter();
  1734. if (now >= targetTime)
  1735. break;
  1736. const int toWait = targetTime - now;
  1737. if (toWait > 2)
  1738. {
  1739. Thread::sleep (jmin (20, toWait >> 1));
  1740. }
  1741. else
  1742. {
  1743. // xxx should consider using mutex_pause on the mac as it apparently
  1744. // makes it seem less like a spinlock and avoids lowering the thread pri.
  1745. for (int i = 10; --i >= 0;)
  1746. Thread::yield();
  1747. }
  1748. }
  1749. }
  1750. double Time::highResolutionTicksToSeconds (const int64 ticks) throw()
  1751. {
  1752. return ticks / (double) getHighResolutionTicksPerSecond();
  1753. }
  1754. int64 Time::secondsToHighResolutionTicks (const double seconds) throw()
  1755. {
  1756. return (int64) (seconds * (double) getHighResolutionTicksPerSecond());
  1757. }
  1758. const Time JUCE_CALLTYPE Time::getCurrentTime() throw()
  1759. {
  1760. return Time (currentTimeMillis());
  1761. }
  1762. const String Time::toString (const bool includeDate,
  1763. const bool includeTime,
  1764. const bool includeSeconds,
  1765. const bool use24HourClock) const throw()
  1766. {
  1767. String result;
  1768. if (includeDate)
  1769. {
  1770. result << getDayOfMonth() << ' '
  1771. << getMonthName (true) << ' '
  1772. << getYear();
  1773. if (includeTime)
  1774. result << ' ';
  1775. }
  1776. if (includeTime)
  1777. {
  1778. const int mins = getMinutes();
  1779. result << (use24HourClock ? getHours() : getHoursInAmPmFormat())
  1780. << (mins < 10 ? ":0" : ":") << mins;
  1781. if (includeSeconds)
  1782. {
  1783. const int secs = getSeconds();
  1784. result << (secs < 10 ? ":0" : ":") << secs;
  1785. }
  1786. if (! use24HourClock)
  1787. result << (isAfternoon() ? "pm" : "am");
  1788. }
  1789. return result.trimEnd();
  1790. }
  1791. const String Time::formatted (const String& format) const throw()
  1792. {
  1793. String buffer;
  1794. int bufferSize = 128;
  1795. buffer.preallocateStorage (bufferSize);
  1796. struct tm t (TimeHelpers::millisToLocal (millisSinceEpoch));
  1797. while (CharacterFunctions::ftime (static_cast <juce_wchar*> (buffer), bufferSize, format, &t) <= 0)
  1798. {
  1799. bufferSize += 128;
  1800. buffer.preallocateStorage (bufferSize);
  1801. }
  1802. return buffer;
  1803. }
  1804. int Time::getYear() const throw()
  1805. {
  1806. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_year + 1900;
  1807. }
  1808. int Time::getMonth() const throw()
  1809. {
  1810. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mon;
  1811. }
  1812. int Time::getDayOfMonth() const throw()
  1813. {
  1814. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mday;
  1815. }
  1816. int Time::getDayOfWeek() const throw()
  1817. {
  1818. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_wday;
  1819. }
  1820. int Time::getHours() const throw()
  1821. {
  1822. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_hour;
  1823. }
  1824. int Time::getHoursInAmPmFormat() const throw()
  1825. {
  1826. const int hours = getHours();
  1827. if (hours == 0)
  1828. return 12;
  1829. else if (hours <= 12)
  1830. return hours;
  1831. else
  1832. return hours - 12;
  1833. }
  1834. bool Time::isAfternoon() const throw()
  1835. {
  1836. return getHours() >= 12;
  1837. }
  1838. int Time::getMinutes() const throw()
  1839. {
  1840. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_min;
  1841. }
  1842. int Time::getSeconds() const throw()
  1843. {
  1844. return TimeHelpers::extendedModulo (millisSinceEpoch / 1000, 60);
  1845. }
  1846. int Time::getMilliseconds() const throw()
  1847. {
  1848. return TimeHelpers::extendedModulo (millisSinceEpoch, 1000);
  1849. }
  1850. bool Time::isDaylightSavingTime() const throw()
  1851. {
  1852. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_isdst != 0;
  1853. }
  1854. const String Time::getTimeZone() const throw()
  1855. {
  1856. String zone[2];
  1857. #if JUCE_WINDOWS
  1858. _tzset();
  1859. #ifdef USE_NEW_SECURE_TIME_FNS
  1860. {
  1861. char name [128];
  1862. size_t length;
  1863. for (int i = 0; i < 2; ++i)
  1864. {
  1865. zeromem (name, sizeof (name));
  1866. _get_tzname (&length, name, 127, i);
  1867. zone[i] = name;
  1868. }
  1869. }
  1870. #else
  1871. const char** const zonePtr = (const char**) _tzname;
  1872. zone[0] = zonePtr[0];
  1873. zone[1] = zonePtr[1];
  1874. #endif
  1875. #else
  1876. tzset();
  1877. const char** const zonePtr = (const char**) tzname;
  1878. zone[0] = zonePtr[0];
  1879. zone[1] = zonePtr[1];
  1880. #endif
  1881. if (isDaylightSavingTime())
  1882. {
  1883. zone[0] = zone[1];
  1884. if (zone[0].length() > 3
  1885. && zone[0].containsIgnoreCase ("daylight")
  1886. && zone[0].contains ("GMT"))
  1887. zone[0] = "BST";
  1888. }
  1889. return zone[0].substring (0, 3);
  1890. }
  1891. const String Time::getMonthName (const bool threeLetterVersion) const throw()
  1892. {
  1893. return getMonthName (getMonth(), threeLetterVersion);
  1894. }
  1895. const String Time::getWeekdayName (const bool threeLetterVersion) const throw()
  1896. {
  1897. return getWeekdayName (getDayOfWeek(), threeLetterVersion);
  1898. }
  1899. const String Time::getMonthName (int monthNumber, const bool threeLetterVersion) throw()
  1900. {
  1901. const char* const shortMonthNames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  1902. const char* const longMonthNames[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
  1903. monthNumber %= 12;
  1904. return TRANS (threeLetterVersion ? shortMonthNames [monthNumber]
  1905. : longMonthNames [monthNumber]);
  1906. }
  1907. const String Time::getWeekdayName (int day, const bool threeLetterVersion) throw()
  1908. {
  1909. const char* const shortDayNames[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  1910. const char* const longDayNames[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  1911. day %= 7;
  1912. return TRANS (threeLetterVersion ? shortDayNames [day]
  1913. : longDayNames [day]);
  1914. }
  1915. END_JUCE_NAMESPACE
  1916. /*** End of inlined file: juce_Time.cpp ***/
  1917. /*** Start of inlined file: juce_BigInteger.cpp ***/
  1918. BEGIN_JUCE_NAMESPACE
  1919. BigInteger::BigInteger()
  1920. : numValues (4),
  1921. highestBit (-1),
  1922. negative (false)
  1923. {
  1924. values.calloc (numValues + 1);
  1925. }
  1926. BigInteger::BigInteger (const int value)
  1927. : numValues (4),
  1928. highestBit (31),
  1929. negative (value < 0)
  1930. {
  1931. values.calloc (numValues + 1);
  1932. values[0] = abs (value);
  1933. highestBit = getHighestBit();
  1934. }
  1935. BigInteger::BigInteger (int64 value)
  1936. : numValues (4),
  1937. highestBit (63),
  1938. negative (value < 0)
  1939. {
  1940. values.calloc (numValues + 1);
  1941. if (value < 0)
  1942. value = -value;
  1943. values[0] = (unsigned int) value;
  1944. values[1] = (unsigned int) (value >> 32);
  1945. highestBit = getHighestBit();
  1946. }
  1947. BigInteger::BigInteger (const unsigned int value)
  1948. : numValues (4),
  1949. highestBit (31),
  1950. negative (false)
  1951. {
  1952. values.calloc (numValues + 1);
  1953. values[0] = value;
  1954. highestBit = getHighestBit();
  1955. }
  1956. BigInteger::BigInteger (const BigInteger& other)
  1957. : numValues (jmax (4, (other.highestBit >> 5) + 1)),
  1958. highestBit (other.getHighestBit()),
  1959. negative (other.negative)
  1960. {
  1961. values.malloc (numValues + 1);
  1962. memcpy (values, other.values, sizeof (unsigned int) * (numValues + 1));
  1963. }
  1964. BigInteger::~BigInteger()
  1965. {
  1966. }
  1967. void BigInteger::swapWith (BigInteger& other) throw()
  1968. {
  1969. values.swapWith (other.values);
  1970. swapVariables (numValues, other.numValues);
  1971. swapVariables (highestBit, other.highestBit);
  1972. swapVariables (negative, other.negative);
  1973. }
  1974. BigInteger& BigInteger::operator= (const BigInteger& other)
  1975. {
  1976. if (this != &other)
  1977. {
  1978. highestBit = other.getHighestBit();
  1979. numValues = jmax (4, (highestBit >> 5) + 1);
  1980. negative = other.negative;
  1981. values.malloc (numValues + 1);
  1982. memcpy (values, other.values, sizeof (unsigned int) * (numValues + 1));
  1983. }
  1984. return *this;
  1985. }
  1986. void BigInteger::ensureSize (const int numVals)
  1987. {
  1988. if (numVals + 2 >= numValues)
  1989. {
  1990. int oldSize = numValues;
  1991. numValues = ((numVals + 2) * 3) / 2;
  1992. values.realloc (numValues + 1);
  1993. while (oldSize < numValues)
  1994. values [oldSize++] = 0;
  1995. }
  1996. }
  1997. bool BigInteger::operator[] (const int bit) const throw()
  1998. {
  1999. return bit <= highestBit && bit >= 0
  2000. && ((values [bit >> 5] & (1 << (bit & 31))) != 0);
  2001. }
  2002. int BigInteger::toInteger() const throw()
  2003. {
  2004. const int n = (int) (values[0] & 0x7fffffff);
  2005. return negative ? -n : n;
  2006. }
  2007. const BigInteger BigInteger::getBitRange (int startBit, int numBits) const
  2008. {
  2009. BigInteger r;
  2010. numBits = jmin (numBits, getHighestBit() + 1 - startBit);
  2011. r.ensureSize (numBits >> 5);
  2012. r.highestBit = numBits;
  2013. int i = 0;
  2014. while (numBits > 0)
  2015. {
  2016. r.values[i++] = getBitRangeAsInt (startBit, jmin (32, numBits));
  2017. numBits -= 32;
  2018. startBit += 32;
  2019. }
  2020. r.highestBit = r.getHighestBit();
  2021. return r;
  2022. }
  2023. int BigInteger::getBitRangeAsInt (const int startBit, int numBits) const throw()
  2024. {
  2025. if (numBits > 32)
  2026. {
  2027. jassertfalse; // use getBitRange() if you need more than 32 bits..
  2028. numBits = 32;
  2029. }
  2030. numBits = jmin (numBits, highestBit + 1 - startBit);
  2031. if (numBits <= 0)
  2032. return 0;
  2033. const int pos = startBit >> 5;
  2034. const int offset = startBit & 31;
  2035. const int endSpace = 32 - numBits;
  2036. uint32 n = ((uint32) values [pos]) >> offset;
  2037. if (offset > endSpace)
  2038. n |= ((uint32) values [pos + 1]) << (32 - offset);
  2039. return (int) (n & (((uint32) 0xffffffff) >> endSpace));
  2040. }
  2041. void BigInteger::setBitRangeAsInt (const int startBit, int numBits, unsigned int valueToSet)
  2042. {
  2043. if (numBits > 32)
  2044. {
  2045. jassertfalse;
  2046. numBits = 32;
  2047. }
  2048. for (int i = 0; i < numBits; ++i)
  2049. {
  2050. setBit (startBit + i, (valueToSet & 1) != 0);
  2051. valueToSet >>= 1;
  2052. }
  2053. }
  2054. void BigInteger::clear()
  2055. {
  2056. if (numValues > 16)
  2057. {
  2058. numValues = 4;
  2059. values.calloc (numValues + 1);
  2060. }
  2061. else
  2062. {
  2063. zeromem (values, sizeof (unsigned int) * (numValues + 1));
  2064. }
  2065. highestBit = -1;
  2066. negative = false;
  2067. }
  2068. void BigInteger::setBit (const int bit)
  2069. {
  2070. if (bit >= 0)
  2071. {
  2072. if (bit > highestBit)
  2073. {
  2074. ensureSize (bit >> 5);
  2075. highestBit = bit;
  2076. }
  2077. values [bit >> 5] |= (1 << (bit & 31));
  2078. }
  2079. }
  2080. void BigInteger::setBit (const int bit, const bool shouldBeSet)
  2081. {
  2082. if (shouldBeSet)
  2083. setBit (bit);
  2084. else
  2085. clearBit (bit);
  2086. }
  2087. void BigInteger::clearBit (const int bit) throw()
  2088. {
  2089. if (bit >= 0 && bit <= highestBit)
  2090. values [bit >> 5] &= ~(1 << (bit & 31));
  2091. }
  2092. void BigInteger::setRange (int startBit, int numBits, const bool shouldBeSet)
  2093. {
  2094. while (--numBits >= 0)
  2095. setBit (startBit++, shouldBeSet);
  2096. }
  2097. void BigInteger::insertBit (const int bit, const bool shouldBeSet)
  2098. {
  2099. if (bit >= 0)
  2100. shiftBits (1, bit);
  2101. setBit (bit, shouldBeSet);
  2102. }
  2103. bool BigInteger::isZero() const throw()
  2104. {
  2105. return getHighestBit() < 0;
  2106. }
  2107. bool BigInteger::isOne() const throw()
  2108. {
  2109. return getHighestBit() == 0 && ! negative;
  2110. }
  2111. bool BigInteger::isNegative() const throw()
  2112. {
  2113. return negative && ! isZero();
  2114. }
  2115. void BigInteger::setNegative (const bool neg) throw()
  2116. {
  2117. negative = neg;
  2118. }
  2119. void BigInteger::negate() throw()
  2120. {
  2121. negative = (! negative) && ! isZero();
  2122. }
  2123. int BigInteger::countNumberOfSetBits() const throw()
  2124. {
  2125. int total = 0;
  2126. for (int i = (highestBit >> 5) + 1; --i >= 0;)
  2127. {
  2128. unsigned int n = values[i];
  2129. if (n == 0xffffffff)
  2130. {
  2131. total += 32;
  2132. }
  2133. else
  2134. {
  2135. while (n != 0)
  2136. {
  2137. total += (n & 1);
  2138. n >>= 1;
  2139. }
  2140. }
  2141. }
  2142. return total;
  2143. }
  2144. int BigInteger::getHighestBit() const throw()
  2145. {
  2146. for (int i = highestBit + 1; --i >= 0;)
  2147. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  2148. return i;
  2149. return -1;
  2150. }
  2151. int BigInteger::findNextSetBit (int i) const throw()
  2152. {
  2153. for (; i <= highestBit; ++i)
  2154. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  2155. return i;
  2156. return -1;
  2157. }
  2158. int BigInteger::findNextClearBit (int i) const throw()
  2159. {
  2160. for (; i <= highestBit; ++i)
  2161. if ((values [i >> 5] & (1 << (i & 31))) == 0)
  2162. break;
  2163. return i;
  2164. }
  2165. BigInteger& BigInteger::operator+= (const BigInteger& other)
  2166. {
  2167. if (other.isNegative())
  2168. return operator-= (-other);
  2169. if (isNegative())
  2170. {
  2171. if (compareAbsolute (other) < 0)
  2172. {
  2173. BigInteger temp (*this);
  2174. temp.negate();
  2175. *this = other;
  2176. operator-= (temp);
  2177. }
  2178. else
  2179. {
  2180. negate();
  2181. operator-= (other);
  2182. negate();
  2183. }
  2184. }
  2185. else
  2186. {
  2187. if (other.highestBit > highestBit)
  2188. highestBit = other.highestBit;
  2189. ++highestBit;
  2190. const int numInts = (highestBit >> 5) + 1;
  2191. ensureSize (numInts);
  2192. int64 remainder = 0;
  2193. for (int i = 0; i <= numInts; ++i)
  2194. {
  2195. if (i < numValues)
  2196. remainder += values[i];
  2197. if (i < other.numValues)
  2198. remainder += other.values[i];
  2199. values[i] = (unsigned int) remainder;
  2200. remainder >>= 32;
  2201. }
  2202. jassert (remainder == 0);
  2203. highestBit = getHighestBit();
  2204. }
  2205. return *this;
  2206. }
  2207. BigInteger& BigInteger::operator-= (const BigInteger& other)
  2208. {
  2209. if (other.isNegative())
  2210. return operator+= (-other);
  2211. if (! isNegative())
  2212. {
  2213. if (compareAbsolute (other) < 0)
  2214. {
  2215. BigInteger temp (other);
  2216. swapWith (temp);
  2217. operator-= (temp);
  2218. negate();
  2219. return *this;
  2220. }
  2221. }
  2222. else
  2223. {
  2224. negate();
  2225. operator+= (other);
  2226. negate();
  2227. return *this;
  2228. }
  2229. const int numInts = (highestBit >> 5) + 1;
  2230. const int maxOtherInts = (other.highestBit >> 5) + 1;
  2231. int64 amountToSubtract = 0;
  2232. for (int i = 0; i <= numInts; ++i)
  2233. {
  2234. if (i <= maxOtherInts)
  2235. amountToSubtract += (int64) other.values[i];
  2236. if (values[i] >= amountToSubtract)
  2237. {
  2238. values[i] = (unsigned int) (values[i] - amountToSubtract);
  2239. amountToSubtract = 0;
  2240. }
  2241. else
  2242. {
  2243. const int64 n = ((int64) values[i] + (((int64) 1) << 32)) - amountToSubtract;
  2244. values[i] = (unsigned int) n;
  2245. amountToSubtract = 1;
  2246. }
  2247. }
  2248. return *this;
  2249. }
  2250. BigInteger& BigInteger::operator*= (const BigInteger& other)
  2251. {
  2252. BigInteger total;
  2253. highestBit = getHighestBit();
  2254. const bool wasNegative = isNegative();
  2255. setNegative (false);
  2256. for (int i = 0; i <= highestBit; ++i)
  2257. {
  2258. if (operator[](i))
  2259. {
  2260. BigInteger n (other);
  2261. n.setNegative (false);
  2262. n <<= i;
  2263. total += n;
  2264. }
  2265. }
  2266. total.setNegative (wasNegative ^ other.isNegative());
  2267. swapWith (total);
  2268. return *this;
  2269. }
  2270. void BigInteger::divideBy (const BigInteger& divisor, BigInteger& remainder)
  2271. {
  2272. jassert (this != &remainder); // (can't handle passing itself in to get the remainder)
  2273. const int divHB = divisor.getHighestBit();
  2274. const int ourHB = getHighestBit();
  2275. if (divHB < 0 || ourHB < 0)
  2276. {
  2277. // division by zero
  2278. remainder.clear();
  2279. clear();
  2280. }
  2281. else
  2282. {
  2283. const bool wasNegative = isNegative();
  2284. swapWith (remainder);
  2285. remainder.setNegative (false);
  2286. clear();
  2287. BigInteger temp (divisor);
  2288. temp.setNegative (false);
  2289. int leftShift = ourHB - divHB;
  2290. temp <<= leftShift;
  2291. while (leftShift >= 0)
  2292. {
  2293. if (remainder.compareAbsolute (temp) >= 0)
  2294. {
  2295. remainder -= temp;
  2296. setBit (leftShift);
  2297. }
  2298. if (--leftShift >= 0)
  2299. temp >>= 1;
  2300. }
  2301. negative = wasNegative ^ divisor.isNegative();
  2302. remainder.setNegative (wasNegative);
  2303. }
  2304. }
  2305. BigInteger& BigInteger::operator/= (const BigInteger& other)
  2306. {
  2307. BigInteger remainder;
  2308. divideBy (other, remainder);
  2309. return *this;
  2310. }
  2311. BigInteger& BigInteger::operator|= (const BigInteger& other)
  2312. {
  2313. // this operation doesn't take into account negative values..
  2314. jassert (isNegative() == other.isNegative());
  2315. if (other.highestBit >= 0)
  2316. {
  2317. ensureSize (other.highestBit >> 5);
  2318. int n = (other.highestBit >> 5) + 1;
  2319. while (--n >= 0)
  2320. values[n] |= other.values[n];
  2321. if (other.highestBit > highestBit)
  2322. highestBit = other.highestBit;
  2323. highestBit = getHighestBit();
  2324. }
  2325. return *this;
  2326. }
  2327. BigInteger& BigInteger::operator&= (const BigInteger& other)
  2328. {
  2329. // this operation doesn't take into account negative values..
  2330. jassert (isNegative() == other.isNegative());
  2331. int n = numValues;
  2332. while (n > other.numValues)
  2333. values[--n] = 0;
  2334. while (--n >= 0)
  2335. values[n] &= other.values[n];
  2336. if (other.highestBit < highestBit)
  2337. highestBit = other.highestBit;
  2338. highestBit = getHighestBit();
  2339. return *this;
  2340. }
  2341. BigInteger& BigInteger::operator^= (const BigInteger& other)
  2342. {
  2343. // this operation will only work with the absolute values
  2344. jassert (isNegative() == other.isNegative());
  2345. if (other.highestBit >= 0)
  2346. {
  2347. ensureSize (other.highestBit >> 5);
  2348. int n = (other.highestBit >> 5) + 1;
  2349. while (--n >= 0)
  2350. values[n] ^= other.values[n];
  2351. if (other.highestBit > highestBit)
  2352. highestBit = other.highestBit;
  2353. highestBit = getHighestBit();
  2354. }
  2355. return *this;
  2356. }
  2357. BigInteger& BigInteger::operator%= (const BigInteger& divisor)
  2358. {
  2359. BigInteger remainder;
  2360. divideBy (divisor, remainder);
  2361. swapWith (remainder);
  2362. return *this;
  2363. }
  2364. BigInteger& BigInteger::operator<<= (int numBitsToShift)
  2365. {
  2366. shiftBits (numBitsToShift, 0);
  2367. return *this;
  2368. }
  2369. BigInteger& BigInteger::operator>>= (int numBitsToShift)
  2370. {
  2371. return operator<<= (-numBitsToShift);
  2372. }
  2373. BigInteger& BigInteger::operator++() { return operator+= (1); }
  2374. BigInteger& BigInteger::operator--() { return operator-= (1); }
  2375. const BigInteger BigInteger::operator++ (int) { const BigInteger old (*this); operator+= (1); return old; }
  2376. const BigInteger BigInteger::operator-- (int) { const BigInteger old (*this); operator-= (1); return old; }
  2377. const BigInteger BigInteger::operator+ (const BigInteger& other) const { BigInteger b (*this); return b += other; }
  2378. const BigInteger BigInteger::operator- (const BigInteger& other) const { BigInteger b (*this); return b -= other; }
  2379. const BigInteger BigInteger::operator* (const BigInteger& other) const { BigInteger b (*this); return b *= other; }
  2380. const BigInteger BigInteger::operator/ (const BigInteger& other) const { BigInteger b (*this); return b /= other; }
  2381. const BigInteger BigInteger::operator| (const BigInteger& other) const { BigInteger b (*this); return b |= other; }
  2382. const BigInteger BigInteger::operator& (const BigInteger& other) const { BigInteger b (*this); return b &= other; }
  2383. const BigInteger BigInteger::operator^ (const BigInteger& other) const { BigInteger b (*this); return b ^= other; }
  2384. const BigInteger BigInteger::operator% (const BigInteger& other) const { BigInteger b (*this); return b %= other; }
  2385. const BigInteger BigInteger::operator<< (const int numBits) const { BigInteger b (*this); return b <<= numBits; }
  2386. const BigInteger BigInteger::operator>> (const int numBits) const { BigInteger b (*this); return b >>= numBits; }
  2387. const BigInteger BigInteger::operator-() const { BigInteger b (*this); b.negate(); return b; }
  2388. int BigInteger::compare (const BigInteger& other) const throw()
  2389. {
  2390. if (isNegative() == other.isNegative())
  2391. {
  2392. const int absComp = compareAbsolute (other);
  2393. return isNegative() ? -absComp : absComp;
  2394. }
  2395. else
  2396. {
  2397. return isNegative() ? -1 : 1;
  2398. }
  2399. }
  2400. int BigInteger::compareAbsolute (const BigInteger& other) const throw()
  2401. {
  2402. const int h1 = getHighestBit();
  2403. const int h2 = other.getHighestBit();
  2404. if (h1 > h2)
  2405. return 1;
  2406. else if (h1 < h2)
  2407. return -1;
  2408. for (int i = (h1 >> 5) + 1; --i >= 0;)
  2409. if (values[i] != other.values[i])
  2410. return (values[i] > other.values[i]) ? 1 : -1;
  2411. return 0;
  2412. }
  2413. bool BigInteger::operator== (const BigInteger& other) const throw() { return compare (other) == 0; }
  2414. bool BigInteger::operator!= (const BigInteger& other) const throw() { return compare (other) != 0; }
  2415. bool BigInteger::operator< (const BigInteger& other) const throw() { return compare (other) < 0; }
  2416. bool BigInteger::operator<= (const BigInteger& other) const throw() { return compare (other) <= 0; }
  2417. bool BigInteger::operator> (const BigInteger& other) const throw() { return compare (other) > 0; }
  2418. bool BigInteger::operator>= (const BigInteger& other) const throw() { return compare (other) >= 0; }
  2419. void BigInteger::shiftBits (int bits, const int startBit)
  2420. {
  2421. if (highestBit < 0)
  2422. return;
  2423. if (startBit > 0)
  2424. {
  2425. if (bits < 0)
  2426. {
  2427. // right shift
  2428. for (int i = startBit; i <= highestBit; ++i)
  2429. setBit (i, operator[] (i - bits));
  2430. highestBit = getHighestBit();
  2431. }
  2432. else if (bits > 0)
  2433. {
  2434. // left shift
  2435. for (int i = highestBit + 1; --i >= startBit;)
  2436. setBit (i + bits, operator[] (i));
  2437. while (--bits >= 0)
  2438. clearBit (bits + startBit);
  2439. }
  2440. }
  2441. else
  2442. {
  2443. if (bits < 0)
  2444. {
  2445. // right shift
  2446. bits = -bits;
  2447. if (bits > highestBit)
  2448. {
  2449. clear();
  2450. }
  2451. else
  2452. {
  2453. const int wordsToMove = bits >> 5;
  2454. int top = 1 + (highestBit >> 5) - wordsToMove;
  2455. highestBit -= bits;
  2456. if (wordsToMove > 0)
  2457. {
  2458. int i;
  2459. for (i = 0; i < top; ++i)
  2460. values [i] = values [i + wordsToMove];
  2461. for (i = 0; i < wordsToMove; ++i)
  2462. values [top + i] = 0;
  2463. bits &= 31;
  2464. }
  2465. if (bits != 0)
  2466. {
  2467. const int invBits = 32 - bits;
  2468. --top;
  2469. for (int i = 0; i < top; ++i)
  2470. values[i] = (values[i] >> bits) | (values [i + 1] << invBits);
  2471. values[top] = (values[top] >> bits);
  2472. }
  2473. highestBit = getHighestBit();
  2474. }
  2475. }
  2476. else if (bits > 0)
  2477. {
  2478. // left shift
  2479. ensureSize (((highestBit + bits) >> 5) + 1);
  2480. const int wordsToMove = bits >> 5;
  2481. int top = 1 + (highestBit >> 5);
  2482. highestBit += bits;
  2483. if (wordsToMove > 0)
  2484. {
  2485. int i;
  2486. for (i = top; --i >= 0;)
  2487. values [i + wordsToMove] = values [i];
  2488. for (i = 0; i < wordsToMove; ++i)
  2489. values [i] = 0;
  2490. bits &= 31;
  2491. }
  2492. if (bits != 0)
  2493. {
  2494. const int invBits = 32 - bits;
  2495. for (int i = top + 1 + wordsToMove; --i > wordsToMove;)
  2496. values[i] = (values[i] << bits) | (values [i - 1] >> invBits);
  2497. values [wordsToMove] = values [wordsToMove] << bits;
  2498. }
  2499. highestBit = getHighestBit();
  2500. }
  2501. }
  2502. }
  2503. const BigInteger BigInteger::simpleGCD (BigInteger* m, BigInteger* n)
  2504. {
  2505. while (! m->isZero())
  2506. {
  2507. if (n->compareAbsolute (*m) > 0)
  2508. swapVariables (m, n);
  2509. *m -= *n;
  2510. }
  2511. return *n;
  2512. }
  2513. const BigInteger BigInteger::findGreatestCommonDivisor (BigInteger n) const
  2514. {
  2515. BigInteger m (*this);
  2516. while (! n.isZero())
  2517. {
  2518. if (abs (m.getHighestBit() - n.getHighestBit()) <= 16)
  2519. return simpleGCD (&m, &n);
  2520. BigInteger temp1 (m), temp2;
  2521. temp1.divideBy (n, temp2);
  2522. m = n;
  2523. n = temp2;
  2524. }
  2525. return m;
  2526. }
  2527. void BigInteger::exponentModulo (const BigInteger& exponent, const BigInteger& modulus)
  2528. {
  2529. BigInteger exp (exponent);
  2530. exp %= modulus;
  2531. BigInteger value (1);
  2532. swapWith (value);
  2533. value %= modulus;
  2534. while (! exp.isZero())
  2535. {
  2536. if (exp [0])
  2537. {
  2538. operator*= (value);
  2539. operator%= (modulus);
  2540. }
  2541. value *= value;
  2542. value %= modulus;
  2543. exp >>= 1;
  2544. }
  2545. }
  2546. void BigInteger::inverseModulo (const BigInteger& modulus)
  2547. {
  2548. if (modulus.isOne() || modulus.isNegative())
  2549. {
  2550. clear();
  2551. return;
  2552. }
  2553. if (isNegative() || compareAbsolute (modulus) >= 0)
  2554. operator%= (modulus);
  2555. if (isOne())
  2556. return;
  2557. if (! (*this)[0])
  2558. {
  2559. // not invertible
  2560. clear();
  2561. return;
  2562. }
  2563. BigInteger a1 (modulus);
  2564. BigInteger a2 (*this);
  2565. BigInteger b1 (modulus);
  2566. BigInteger b2 (1);
  2567. while (! a2.isOne())
  2568. {
  2569. BigInteger temp1, temp2, multiplier (a1);
  2570. multiplier.divideBy (a2, temp1);
  2571. temp1 = a2;
  2572. temp1 *= multiplier;
  2573. temp2 = a1;
  2574. temp2 -= temp1;
  2575. a1 = a2;
  2576. a2 = temp2;
  2577. temp1 = b2;
  2578. temp1 *= multiplier;
  2579. temp2 = b1;
  2580. temp2 -= temp1;
  2581. b1 = b2;
  2582. b2 = temp2;
  2583. }
  2584. while (b2.isNegative())
  2585. b2 += modulus;
  2586. b2 %= modulus;
  2587. swapWith (b2);
  2588. }
  2589. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value)
  2590. {
  2591. return stream << value.toString (10);
  2592. }
  2593. const String BigInteger::toString (const int base, const int minimumNumCharacters) const
  2594. {
  2595. String s;
  2596. BigInteger v (*this);
  2597. if (base == 2 || base == 8 || base == 16)
  2598. {
  2599. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2600. static const char* const hexDigits = "0123456789abcdef";
  2601. for (;;)
  2602. {
  2603. const int remainder = v.getBitRangeAsInt (0, bits);
  2604. v >>= bits;
  2605. if (remainder == 0 && v.isZero())
  2606. break;
  2607. s = String::charToString (hexDigits [remainder]) + s;
  2608. }
  2609. }
  2610. else if (base == 10)
  2611. {
  2612. const BigInteger ten (10);
  2613. BigInteger remainder;
  2614. for (;;)
  2615. {
  2616. v.divideBy (ten, remainder);
  2617. if (remainder.isZero() && v.isZero())
  2618. break;
  2619. s = String (remainder.getBitRangeAsInt (0, 8)) + s;
  2620. }
  2621. }
  2622. else
  2623. {
  2624. jassertfalse; // can't do the specified base!
  2625. return String::empty;
  2626. }
  2627. s = s.paddedLeft ('0', minimumNumCharacters);
  2628. return isNegative() ? "-" + s : s;
  2629. }
  2630. void BigInteger::parseString (const String& text, const int base)
  2631. {
  2632. clear();
  2633. const juce_wchar* t = text;
  2634. if (base == 2 || base == 8 || base == 16)
  2635. {
  2636. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2637. for (;;)
  2638. {
  2639. const juce_wchar c = *t++;
  2640. const int digit = CharacterFunctions::getHexDigitValue (c);
  2641. if (((unsigned int) digit) < (unsigned int) base)
  2642. {
  2643. operator<<= (bits);
  2644. operator+= (digit);
  2645. }
  2646. else if (c == 0)
  2647. {
  2648. break;
  2649. }
  2650. }
  2651. }
  2652. else if (base == 10)
  2653. {
  2654. const BigInteger ten ((unsigned int) 10);
  2655. for (;;)
  2656. {
  2657. const juce_wchar c = *t++;
  2658. if (c >= '0' && c <= '9')
  2659. {
  2660. operator*= (ten);
  2661. operator+= ((int) (c - '0'));
  2662. }
  2663. else if (c == 0)
  2664. {
  2665. break;
  2666. }
  2667. }
  2668. }
  2669. setNegative (text.trimStart().startsWithChar ('-'));
  2670. }
  2671. const MemoryBlock BigInteger::toMemoryBlock() const
  2672. {
  2673. const int numBytes = (getHighestBit() + 8) >> 3;
  2674. MemoryBlock mb ((size_t) numBytes);
  2675. for (int i = 0; i < numBytes; ++i)
  2676. mb[i] = (uint8) getBitRangeAsInt (i << 3, 8);
  2677. return mb;
  2678. }
  2679. void BigInteger::loadFromMemoryBlock (const MemoryBlock& data)
  2680. {
  2681. clear();
  2682. for (int i = (int) data.getSize(); --i >= 0;)
  2683. this->setBitRangeAsInt ((int) (i << 3), 8, data [i]);
  2684. }
  2685. END_JUCE_NAMESPACE
  2686. /*** End of inlined file: juce_BigInteger.cpp ***/
  2687. /*** Start of inlined file: juce_MemoryBlock.cpp ***/
  2688. BEGIN_JUCE_NAMESPACE
  2689. MemoryBlock::MemoryBlock() throw()
  2690. : size (0)
  2691. {
  2692. }
  2693. MemoryBlock::MemoryBlock (const size_t initialSize,
  2694. const bool initialiseToZero) throw()
  2695. {
  2696. if (initialSize > 0)
  2697. {
  2698. size = initialSize;
  2699. data.allocate (initialSize, initialiseToZero);
  2700. }
  2701. else
  2702. {
  2703. size = 0;
  2704. }
  2705. }
  2706. MemoryBlock::MemoryBlock (const MemoryBlock& other) throw()
  2707. : size (other.size)
  2708. {
  2709. if (size > 0)
  2710. {
  2711. jassert (other.data != 0);
  2712. data.malloc (size);
  2713. memcpy (data, other.data, size);
  2714. }
  2715. }
  2716. MemoryBlock::MemoryBlock (const void* const dataToInitialiseFrom,
  2717. const size_t sizeInBytes) throw()
  2718. : size (jmax ((size_t) 0, sizeInBytes))
  2719. {
  2720. jassert (sizeInBytes >= 0);
  2721. if (size > 0)
  2722. {
  2723. jassert (dataToInitialiseFrom != 0); // non-zero size, but a zero pointer passed-in?
  2724. data.malloc (size);
  2725. if (dataToInitialiseFrom != 0)
  2726. memcpy (data, dataToInitialiseFrom, size);
  2727. }
  2728. }
  2729. MemoryBlock::~MemoryBlock() throw()
  2730. {
  2731. jassert (size >= 0); // should never happen
  2732. jassert (size == 0 || data != 0); // non-zero size but no data allocated?
  2733. }
  2734. MemoryBlock& MemoryBlock::operator= (const MemoryBlock& other) throw()
  2735. {
  2736. if (this != &other)
  2737. {
  2738. setSize (other.size, false);
  2739. memcpy (data, other.data, size);
  2740. }
  2741. return *this;
  2742. }
  2743. bool MemoryBlock::operator== (const MemoryBlock& other) const throw()
  2744. {
  2745. return matches (other.data, other.size);
  2746. }
  2747. bool MemoryBlock::operator!= (const MemoryBlock& other) const throw()
  2748. {
  2749. return ! operator== (other);
  2750. }
  2751. bool MemoryBlock::matches (const void* dataToCompare, size_t dataSize) const throw()
  2752. {
  2753. return size == dataSize
  2754. && memcmp (data, dataToCompare, size) == 0;
  2755. }
  2756. // this will resize the block to this size
  2757. void MemoryBlock::setSize (const size_t newSize,
  2758. const bool initialiseToZero) throw()
  2759. {
  2760. if (size != newSize)
  2761. {
  2762. if (newSize <= 0)
  2763. {
  2764. data.free();
  2765. size = 0;
  2766. }
  2767. else
  2768. {
  2769. if (data != 0)
  2770. {
  2771. data.realloc (newSize);
  2772. if (initialiseToZero && (newSize > size))
  2773. zeromem (data + size, newSize - size);
  2774. }
  2775. else
  2776. {
  2777. data.allocate (newSize, initialiseToZero);
  2778. }
  2779. size = newSize;
  2780. }
  2781. }
  2782. }
  2783. void MemoryBlock::ensureSize (const size_t minimumSize,
  2784. const bool initialiseToZero) throw()
  2785. {
  2786. if (size < minimumSize)
  2787. setSize (minimumSize, initialiseToZero);
  2788. }
  2789. void MemoryBlock::swapWith (MemoryBlock& other) throw()
  2790. {
  2791. swapVariables (size, other.size);
  2792. data.swapWith (other.data);
  2793. }
  2794. void MemoryBlock::fillWith (const uint8 value) throw()
  2795. {
  2796. memset (data, (int) value, size);
  2797. }
  2798. void MemoryBlock::append (const void* const srcData,
  2799. const size_t numBytes) throw()
  2800. {
  2801. if (numBytes > 0)
  2802. {
  2803. const size_t oldSize = size;
  2804. setSize (size + numBytes);
  2805. memcpy (data + oldSize, srcData, numBytes);
  2806. }
  2807. }
  2808. void MemoryBlock::copyFrom (const void* const src, int offset, size_t num) throw()
  2809. {
  2810. const char* d = static_cast<const char*> (src);
  2811. if (offset < 0)
  2812. {
  2813. d -= offset;
  2814. num -= offset;
  2815. offset = 0;
  2816. }
  2817. if (offset + num > size)
  2818. num = size - offset;
  2819. if (num > 0)
  2820. memcpy (data + offset, d, num);
  2821. }
  2822. void MemoryBlock::copyTo (void* const dst, int offset, size_t num) const throw()
  2823. {
  2824. char* d = static_cast<char*> (dst);
  2825. if (offset < 0)
  2826. {
  2827. zeromem (d, -offset);
  2828. d -= offset;
  2829. num += offset;
  2830. offset = 0;
  2831. }
  2832. if (offset + num > size)
  2833. {
  2834. const size_t newNum = size - offset;
  2835. zeromem (d + newNum, num - newNum);
  2836. num = newNum;
  2837. }
  2838. if (num > 0)
  2839. memcpy (d, data + offset, num);
  2840. }
  2841. void MemoryBlock::removeSection (size_t startByte, size_t numBytesToRemove) throw()
  2842. {
  2843. if (startByte < 0)
  2844. {
  2845. numBytesToRemove += startByte;
  2846. startByte = 0;
  2847. }
  2848. if (startByte + numBytesToRemove >= size)
  2849. {
  2850. setSize (startByte);
  2851. }
  2852. else if (numBytesToRemove > 0)
  2853. {
  2854. memmove (data + startByte,
  2855. data + startByte + numBytesToRemove,
  2856. size - (startByte + numBytesToRemove));
  2857. setSize (size - numBytesToRemove);
  2858. }
  2859. }
  2860. const String MemoryBlock::toString() const throw()
  2861. {
  2862. return String (static_cast <const char*> (getData()), size);
  2863. }
  2864. int MemoryBlock::getBitRange (const size_t bitRangeStart, size_t numBits) const throw()
  2865. {
  2866. int res = 0;
  2867. size_t byte = bitRangeStart >> 3;
  2868. int offsetInByte = (int) bitRangeStart & 7;
  2869. size_t bitsSoFar = 0;
  2870. while (numBits > 0 && (size_t) byte < size)
  2871. {
  2872. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2873. const int mask = (0xff >> (8 - bitsThisTime)) << offsetInByte;
  2874. res |= (((data[byte] & mask) >> offsetInByte) << bitsSoFar);
  2875. bitsSoFar += bitsThisTime;
  2876. numBits -= bitsThisTime;
  2877. ++byte;
  2878. offsetInByte = 0;
  2879. }
  2880. return res;
  2881. }
  2882. void MemoryBlock::setBitRange (const size_t bitRangeStart, size_t numBits, int bitsToSet) throw()
  2883. {
  2884. size_t byte = bitRangeStart >> 3;
  2885. int offsetInByte = (int) bitRangeStart & 7;
  2886. unsigned int mask = ~((((unsigned int) 0xffffffff) << (32 - numBits)) >> (32 - numBits));
  2887. while (numBits > 0 && (size_t) byte < size)
  2888. {
  2889. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2890. const unsigned int tempMask = (mask << offsetInByte) | ~((((unsigned int) 0xffffffff) >> offsetInByte) << offsetInByte);
  2891. const unsigned int tempBits = bitsToSet << offsetInByte;
  2892. data[byte] = (char) ((data[byte] & tempMask) | tempBits);
  2893. ++byte;
  2894. numBits -= bitsThisTime;
  2895. bitsToSet >>= bitsThisTime;
  2896. mask >>= bitsThisTime;
  2897. offsetInByte = 0;
  2898. }
  2899. }
  2900. void MemoryBlock::loadFromHexString (const String& hex) throw()
  2901. {
  2902. ensureSize (hex.length() >> 1);
  2903. char* dest = data;
  2904. int i = 0;
  2905. for (;;)
  2906. {
  2907. int byte = 0;
  2908. for (int loop = 2; --loop >= 0;)
  2909. {
  2910. byte <<= 4;
  2911. for (;;)
  2912. {
  2913. const juce_wchar c = hex [i++];
  2914. if (c >= '0' && c <= '9')
  2915. {
  2916. byte |= c - '0';
  2917. break;
  2918. }
  2919. else if (c >= 'a' && c <= 'z')
  2920. {
  2921. byte |= c - ('a' - 10);
  2922. break;
  2923. }
  2924. else if (c >= 'A' && c <= 'Z')
  2925. {
  2926. byte |= c - ('A' - 10);
  2927. break;
  2928. }
  2929. else if (c == 0)
  2930. {
  2931. setSize (static_cast <size_t> (dest - data));
  2932. return;
  2933. }
  2934. }
  2935. }
  2936. *dest++ = (char) byte;
  2937. }
  2938. }
  2939. const char* const MemoryBlock::encodingTable = ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+";
  2940. const String MemoryBlock::toBase64Encoding() const throw()
  2941. {
  2942. const size_t numChars = ((size << 3) + 5) / 6;
  2943. String destString ((unsigned int) size); // store the length, followed by a '.', and then the data.
  2944. const int initialLen = destString.length();
  2945. destString.preallocateStorage (initialLen + 2 + numChars);
  2946. juce_wchar* d = destString;
  2947. d += initialLen;
  2948. *d++ = '.';
  2949. for (size_t i = 0; i < numChars; ++i)
  2950. *d++ = encodingTable [getBitRange (i * 6, 6)];
  2951. *d++ = 0;
  2952. return destString;
  2953. }
  2954. bool MemoryBlock::fromBase64Encoding (const String& s) throw()
  2955. {
  2956. const int startPos = s.indexOfChar ('.') + 1;
  2957. if (startPos <= 0)
  2958. return false;
  2959. const int numBytesNeeded = s.substring (0, startPos - 1).getIntValue();
  2960. setSize (numBytesNeeded, true);
  2961. const int numChars = s.length() - startPos;
  2962. const juce_wchar* srcChars = s;
  2963. srcChars += startPos;
  2964. int pos = 0;
  2965. for (int i = 0; i < numChars; ++i)
  2966. {
  2967. const char c = (char) srcChars[i];
  2968. for (int j = 0; j < 64; ++j)
  2969. {
  2970. if (encodingTable[j] == c)
  2971. {
  2972. setBitRange (pos, 6, j);
  2973. pos += 6;
  2974. break;
  2975. }
  2976. }
  2977. }
  2978. return true;
  2979. }
  2980. END_JUCE_NAMESPACE
  2981. /*** End of inlined file: juce_MemoryBlock.cpp ***/
  2982. /*** Start of inlined file: juce_PropertySet.cpp ***/
  2983. BEGIN_JUCE_NAMESPACE
  2984. PropertySet::PropertySet (const bool ignoreCaseOfKeyNames) throw()
  2985. : properties (ignoreCaseOfKeyNames),
  2986. fallbackProperties (0),
  2987. ignoreCaseOfKeys (ignoreCaseOfKeyNames)
  2988. {
  2989. }
  2990. PropertySet::PropertySet (const PropertySet& other) throw()
  2991. : properties (other.properties),
  2992. fallbackProperties (other.fallbackProperties),
  2993. ignoreCaseOfKeys (other.ignoreCaseOfKeys)
  2994. {
  2995. }
  2996. PropertySet& PropertySet::operator= (const PropertySet& other) throw()
  2997. {
  2998. properties = other.properties;
  2999. fallbackProperties = other.fallbackProperties;
  3000. ignoreCaseOfKeys = other.ignoreCaseOfKeys;
  3001. propertyChanged();
  3002. return *this;
  3003. }
  3004. PropertySet::~PropertySet()
  3005. {
  3006. }
  3007. void PropertySet::clear()
  3008. {
  3009. const ScopedLock sl (lock);
  3010. if (properties.size() > 0)
  3011. {
  3012. properties.clear();
  3013. propertyChanged();
  3014. }
  3015. }
  3016. const String PropertySet::getValue (const String& keyName,
  3017. const String& defaultValue) const throw()
  3018. {
  3019. const ScopedLock sl (lock);
  3020. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3021. if (index >= 0)
  3022. return properties.getAllValues() [index];
  3023. return fallbackProperties != 0 ? fallbackProperties->getValue (keyName, defaultValue)
  3024. : defaultValue;
  3025. }
  3026. int PropertySet::getIntValue (const String& keyName,
  3027. const int defaultValue) const throw()
  3028. {
  3029. const ScopedLock sl (lock);
  3030. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3031. if (index >= 0)
  3032. return properties.getAllValues() [index].getIntValue();
  3033. return fallbackProperties != 0 ? fallbackProperties->getIntValue (keyName, defaultValue)
  3034. : defaultValue;
  3035. }
  3036. double PropertySet::getDoubleValue (const String& keyName,
  3037. const double defaultValue) const throw()
  3038. {
  3039. const ScopedLock sl (lock);
  3040. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3041. if (index >= 0)
  3042. return properties.getAllValues()[index].getDoubleValue();
  3043. return fallbackProperties != 0 ? fallbackProperties->getDoubleValue (keyName, defaultValue)
  3044. : defaultValue;
  3045. }
  3046. bool PropertySet::getBoolValue (const String& keyName,
  3047. const bool defaultValue) const throw()
  3048. {
  3049. const ScopedLock sl (lock);
  3050. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3051. if (index >= 0)
  3052. return properties.getAllValues() [index].getIntValue() != 0;
  3053. return fallbackProperties != 0 ? fallbackProperties->getBoolValue (keyName, defaultValue)
  3054. : defaultValue;
  3055. }
  3056. XmlElement* PropertySet::getXmlValue (const String& keyName) const
  3057. {
  3058. XmlDocument doc (getValue (keyName));
  3059. return doc.getDocumentElement();
  3060. }
  3061. void PropertySet::setValue (const String& keyName,
  3062. const String& value) throw()
  3063. {
  3064. jassert (keyName.isNotEmpty()); // shouldn't use an empty key name!
  3065. if (keyName.isNotEmpty())
  3066. {
  3067. const ScopedLock sl (lock);
  3068. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3069. if (index < 0 || properties.getAllValues() [index] != value)
  3070. {
  3071. properties.set (keyName, value);
  3072. propertyChanged();
  3073. }
  3074. }
  3075. }
  3076. void PropertySet::removeValue (const String& keyName) throw()
  3077. {
  3078. if (keyName.isNotEmpty())
  3079. {
  3080. const ScopedLock sl (lock);
  3081. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3082. if (index >= 0)
  3083. {
  3084. properties.remove (keyName);
  3085. propertyChanged();
  3086. }
  3087. }
  3088. }
  3089. void PropertySet::setValue (const String& keyName, const int value) throw()
  3090. {
  3091. setValue (keyName, String (value));
  3092. }
  3093. void PropertySet::setValue (const String& keyName, const double value) throw()
  3094. {
  3095. setValue (keyName, String (value));
  3096. }
  3097. void PropertySet::setValue (const String& keyName, const bool value) throw()
  3098. {
  3099. setValue (keyName, String (value ? "1" : "0"));
  3100. }
  3101. void PropertySet::setValue (const String& keyName, const XmlElement* const xml)
  3102. {
  3103. setValue (keyName, (xml == 0) ? String::empty
  3104. : xml->createDocument (String::empty, true));
  3105. }
  3106. bool PropertySet::containsKey (const String& keyName) const throw()
  3107. {
  3108. const ScopedLock sl (lock);
  3109. return properties.getAllKeys().contains (keyName, ignoreCaseOfKeys);
  3110. }
  3111. void PropertySet::setFallbackPropertySet (PropertySet* fallbackProperties_) throw()
  3112. {
  3113. const ScopedLock sl (lock);
  3114. fallbackProperties = fallbackProperties_;
  3115. }
  3116. XmlElement* PropertySet::createXml (const String& nodeName) const throw()
  3117. {
  3118. const ScopedLock sl (lock);
  3119. XmlElement* const xml = new XmlElement (nodeName);
  3120. for (int i = 0; i < properties.getAllKeys().size(); ++i)
  3121. {
  3122. XmlElement* const e = xml->createNewChildElement ("VALUE");
  3123. e->setAttribute ("name", properties.getAllKeys()[i]);
  3124. e->setAttribute ("val", properties.getAllValues()[i]);
  3125. }
  3126. return xml;
  3127. }
  3128. void PropertySet::restoreFromXml (const XmlElement& xml) throw()
  3129. {
  3130. const ScopedLock sl (lock);
  3131. clear();
  3132. forEachXmlChildElementWithTagName (xml, e, "VALUE")
  3133. {
  3134. if (e->hasAttribute ("name")
  3135. && e->hasAttribute ("val"))
  3136. {
  3137. properties.set (e->getStringAttribute ("name"),
  3138. e->getStringAttribute ("val"));
  3139. }
  3140. }
  3141. if (properties.size() > 0)
  3142. propertyChanged();
  3143. }
  3144. void PropertySet::propertyChanged()
  3145. {
  3146. }
  3147. END_JUCE_NAMESPACE
  3148. /*** End of inlined file: juce_PropertySet.cpp ***/
  3149. /*** Start of inlined file: juce_Identifier.cpp ***/
  3150. BEGIN_JUCE_NAMESPACE
  3151. StringPool& Identifier::getPool()
  3152. {
  3153. static StringPool pool;
  3154. return pool;
  3155. }
  3156. Identifier::Identifier() throw()
  3157. : name (0)
  3158. {
  3159. }
  3160. Identifier::Identifier (const Identifier& other) throw()
  3161. : name (other.name)
  3162. {
  3163. }
  3164. Identifier& Identifier::operator= (const Identifier& other) throw()
  3165. {
  3166. name = other.name;
  3167. return *this;
  3168. }
  3169. Identifier::Identifier (const String& name_)
  3170. : name (Identifier::getPool().getPooledString (name_))
  3171. {
  3172. /* An Identifier string must be suitable for use as a script variable or XML
  3173. attribute, so it can only contain this limited set of characters.. */
  3174. jassert (name_.containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && name_.isNotEmpty());
  3175. }
  3176. Identifier::Identifier (const char* const name_)
  3177. : name (Identifier::getPool().getPooledString (name_))
  3178. {
  3179. /* An Identifier string must be suitable for use as a script variable or XML
  3180. attribute, so it can only contain this limited set of characters.. */
  3181. jassert (toString().containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && toString().isNotEmpty());
  3182. }
  3183. Identifier::~Identifier()
  3184. {
  3185. }
  3186. END_JUCE_NAMESPACE
  3187. /*** End of inlined file: juce_Identifier.cpp ***/
  3188. /*** Start of inlined file: juce_Variant.cpp ***/
  3189. BEGIN_JUCE_NAMESPACE
  3190. var::var() throw()
  3191. : type (voidType)
  3192. {
  3193. value.doubleValue = 0;
  3194. }
  3195. var::~var() throw()
  3196. {
  3197. if (type == stringType)
  3198. delete value.stringValue;
  3199. else if (type == objectType && value.objectValue != 0)
  3200. value.objectValue->decReferenceCount();
  3201. }
  3202. const var var::null;
  3203. var::var (const var& valueToCopy)
  3204. : type (valueToCopy.type),
  3205. value (valueToCopy.value)
  3206. {
  3207. if (type == stringType)
  3208. value.stringValue = new String (*(value.stringValue));
  3209. else if (type == objectType && value.objectValue != 0)
  3210. value.objectValue->incReferenceCount();
  3211. }
  3212. var::var (const int value_) throw()
  3213. : type (intType)
  3214. {
  3215. value.intValue = value_;
  3216. }
  3217. var::var (const bool value_) throw()
  3218. : type (boolType)
  3219. {
  3220. value.boolValue = value_;
  3221. }
  3222. var::var (const double value_) throw()
  3223. : type (doubleType)
  3224. {
  3225. value.doubleValue = value_;
  3226. }
  3227. var::var (const String& value_)
  3228. : type (stringType)
  3229. {
  3230. value.stringValue = new String (value_);
  3231. }
  3232. var::var (const char* const value_)
  3233. : type (stringType)
  3234. {
  3235. value.stringValue = new String (value_);
  3236. }
  3237. var::var (const juce_wchar* const value_)
  3238. : type (stringType)
  3239. {
  3240. value.stringValue = new String (value_);
  3241. }
  3242. var::var (DynamicObject* const object)
  3243. : type (objectType)
  3244. {
  3245. value.objectValue = object;
  3246. if (object != 0)
  3247. object->incReferenceCount();
  3248. }
  3249. var::var (MethodFunction method_) throw()
  3250. : type (methodType)
  3251. {
  3252. value.methodValue = method_;
  3253. }
  3254. void var::swapWith (var& other) throw()
  3255. {
  3256. swapVariables (type, other.type);
  3257. swapVariables (value, other.value);
  3258. }
  3259. var& var::operator= (const var& value_) { var newValue (value_); swapWith (newValue); return *this; }
  3260. var& var::operator= (int value_) { var newValue (value_); swapWith (newValue); return *this; }
  3261. var& var::operator= (bool value_) { var newValue (value_); swapWith (newValue); return *this; }
  3262. var& var::operator= (double value_) { var newValue (value_); swapWith (newValue); return *this; }
  3263. var& var::operator= (const char* value_) { var newValue (value_); swapWith (newValue); return *this; }
  3264. var& var::operator= (const juce_wchar* value_) { var newValue (value_); swapWith (newValue); return *this; }
  3265. var& var::operator= (const String& value_) { var newValue (value_); swapWith (newValue); return *this; }
  3266. var& var::operator= (DynamicObject* value_) { var newValue (value_); swapWith (newValue); return *this; }
  3267. var& var::operator= (MethodFunction value_) { var newValue (value_); swapWith (newValue); return *this; }
  3268. var::operator int() const
  3269. {
  3270. switch (type)
  3271. {
  3272. case voidType: break;
  3273. case intType: return value.intValue;
  3274. case boolType: return value.boolValue ? 1 : 0;
  3275. case doubleType: return static_cast <int> (value.doubleValue);
  3276. case stringType: return value.stringValue->getIntValue();
  3277. case objectType: break;
  3278. default: jassertfalse; break;
  3279. }
  3280. return 0;
  3281. }
  3282. var::operator bool() const
  3283. {
  3284. switch (type)
  3285. {
  3286. case voidType: break;
  3287. case intType: return value.intValue != 0;
  3288. case boolType: return value.boolValue;
  3289. case doubleType: return value.doubleValue != 0;
  3290. case stringType: return value.stringValue->getIntValue() != 0
  3291. || value.stringValue->trim().equalsIgnoreCase ("true")
  3292. || value.stringValue->trim().equalsIgnoreCase ("yes");
  3293. case objectType: return value.objectValue != 0;
  3294. default: jassertfalse; break;
  3295. }
  3296. return false;
  3297. }
  3298. var::operator float() const
  3299. {
  3300. return (float) operator double();
  3301. }
  3302. var::operator double() const
  3303. {
  3304. switch (type)
  3305. {
  3306. case voidType: break;
  3307. case intType: return value.intValue;
  3308. case boolType: return value.boolValue ? 1.0 : 0.0;
  3309. case doubleType: return value.doubleValue;
  3310. case stringType: return value.stringValue->getDoubleValue();
  3311. case objectType: break;
  3312. default: jassertfalse; break;
  3313. }
  3314. return 0.0;
  3315. }
  3316. const String var::toString() const
  3317. {
  3318. switch (type)
  3319. {
  3320. case voidType: return String::empty;
  3321. case intType: return String (value.intValue);
  3322. case boolType: return String::charToString (value.boolValue ? '1' : '0');
  3323. case doubleType: return String (value.doubleValue);
  3324. case stringType: return *(value.stringValue);
  3325. case objectType: return "Object 0x" + String::toHexString ((int) (pointer_sized_int) value.objectValue);
  3326. case methodType: return "Method";
  3327. default: jassertfalse; break;
  3328. }
  3329. return String::empty;
  3330. }
  3331. var::operator const String() const
  3332. {
  3333. return toString();
  3334. }
  3335. DynamicObject* var::getObject() const
  3336. {
  3337. return type == objectType ? value.objectValue : 0;
  3338. }
  3339. bool var::equals (const var& other) const throw()
  3340. {
  3341. switch (type)
  3342. {
  3343. case voidType: return other.isVoid();
  3344. case intType: return value.intValue == static_cast <int> (other);
  3345. case boolType: return value.boolValue == static_cast <bool> (other);
  3346. case doubleType: return value.doubleValue == static_cast <double> (other);
  3347. case stringType: return (*(value.stringValue)) == other.toString();
  3348. case objectType: return value.objectValue == other.getObject();
  3349. case methodType: return value.methodValue == other.value.methodValue && other.isMethod();
  3350. default: jassertfalse; break;
  3351. }
  3352. return false;
  3353. }
  3354. bool operator== (const var& v1, const var& v2) throw() { return v1.equals (v2); }
  3355. bool operator!= (const var& v1, const var& v2) throw() { return ! v1.equals (v2); }
  3356. bool operator== (const var& v1, const String& v2) throw() { return v1.toString() == v2; }
  3357. bool operator!= (const var& v1, const String& v2) throw() { return v1.toString() != v2; }
  3358. void var::writeToStream (OutputStream& output) const
  3359. {
  3360. switch (type)
  3361. {
  3362. case voidType: output.writeCompressedInt (0); break;
  3363. case intType: output.writeCompressedInt (5); output.writeByte (1); output.writeInt (value.intValue); break;
  3364. case boolType: output.writeCompressedInt (1); output.writeByte (value.boolValue ? 2 : 3); break;
  3365. case doubleType: output.writeCompressedInt (9); output.writeByte (4); output.writeDouble (value.doubleValue); break;
  3366. case stringType:
  3367. {
  3368. const int len = value.stringValue->getNumBytesAsUTF8() + 1;
  3369. output.writeCompressedInt (len + 1);
  3370. output.writeByte (5);
  3371. HeapBlock<char> temp (len);
  3372. value.stringValue->copyToUTF8 (temp, len);
  3373. output.write (temp, len);
  3374. break;
  3375. }
  3376. case objectType:
  3377. case methodType: output.writeCompressedInt (0); jassertfalse; break; // Can't write an object to a stream!
  3378. default: jassertfalse; break; // Is this a corrupted object?
  3379. }
  3380. }
  3381. const var var::readFromStream (InputStream& input)
  3382. {
  3383. const int numBytes = input.readCompressedInt();
  3384. if (numBytes > 0)
  3385. {
  3386. switch (input.readByte())
  3387. {
  3388. case 1: return var (input.readInt());
  3389. case 2: return var (true);
  3390. case 3: return var (false);
  3391. case 4: return var (input.readDouble());
  3392. case 5:
  3393. {
  3394. MemoryBlock mb;
  3395. input.readIntoMemoryBlock (mb, numBytes - 1);
  3396. return var (String::fromUTF8 (static_cast <const char*> (mb.getData()), (int) mb.getSize()));
  3397. }
  3398. default: input.skipNextBytes (numBytes - 1); break;
  3399. }
  3400. }
  3401. return var::null;
  3402. }
  3403. const var var::operator[] (const Identifier& propertyName) const
  3404. {
  3405. if (type == objectType && value.objectValue != 0)
  3406. return value.objectValue->getProperty (propertyName);
  3407. return var::null;
  3408. }
  3409. const var var::invoke (const Identifier& method, const var* arguments, int numArguments) const
  3410. {
  3411. if (type == objectType && value.objectValue != 0)
  3412. return value.objectValue->invokeMethod (method, arguments, numArguments);
  3413. return var::null;
  3414. }
  3415. const var var::invoke (const var& targetObject, const var* arguments, int numArguments) const
  3416. {
  3417. if (isMethod())
  3418. {
  3419. DynamicObject* const target = targetObject.getObject();
  3420. if (target != 0)
  3421. return (target->*(value.methodValue)) (arguments, numArguments);
  3422. }
  3423. return var::null;
  3424. }
  3425. const var var::call (const Identifier& method) const
  3426. {
  3427. return invoke (method, 0, 0);
  3428. }
  3429. const var var::call (const Identifier& method, const var& arg1) const
  3430. {
  3431. return invoke (method, &arg1, 1);
  3432. }
  3433. const var var::call (const Identifier& method, const var& arg1, const var& arg2) const
  3434. {
  3435. var args[] = { arg1, arg2 };
  3436. return invoke (method, args, 2);
  3437. }
  3438. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3)
  3439. {
  3440. var args[] = { arg1, arg2, arg3 };
  3441. return invoke (method, args, 3);
  3442. }
  3443. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const
  3444. {
  3445. var args[] = { arg1, arg2, arg3, arg4 };
  3446. return invoke (method, args, 4);
  3447. }
  3448. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const
  3449. {
  3450. var args[] = { arg1, arg2, arg3, arg4, arg5 };
  3451. return invoke (method, args, 5);
  3452. }
  3453. END_JUCE_NAMESPACE
  3454. /*** End of inlined file: juce_Variant.cpp ***/
  3455. /*** Start of inlined file: juce_NamedValueSet.cpp ***/
  3456. BEGIN_JUCE_NAMESPACE
  3457. NamedValueSet::NamedValue::NamedValue() throw()
  3458. {
  3459. }
  3460. inline NamedValueSet::NamedValue::NamedValue (const Identifier& name_, const var& value_)
  3461. : name (name_), value (value_)
  3462. {
  3463. }
  3464. bool NamedValueSet::NamedValue::operator== (const NamedValueSet::NamedValue& other) const throw()
  3465. {
  3466. return name == other.name && value == other.value;
  3467. }
  3468. NamedValueSet::NamedValueSet() throw()
  3469. {
  3470. }
  3471. NamedValueSet::NamedValueSet (const NamedValueSet& other)
  3472. : values (other.values)
  3473. {
  3474. }
  3475. NamedValueSet& NamedValueSet::operator= (const NamedValueSet& other)
  3476. {
  3477. values = other.values;
  3478. return *this;
  3479. }
  3480. NamedValueSet::~NamedValueSet()
  3481. {
  3482. }
  3483. bool NamedValueSet::operator== (const NamedValueSet& other) const
  3484. {
  3485. return values == other.values;
  3486. }
  3487. bool NamedValueSet::operator!= (const NamedValueSet& other) const
  3488. {
  3489. return ! operator== (other);
  3490. }
  3491. int NamedValueSet::size() const throw()
  3492. {
  3493. return values.size();
  3494. }
  3495. const var& NamedValueSet::operator[] (const Identifier& name) const
  3496. {
  3497. for (int i = values.size(); --i >= 0;)
  3498. {
  3499. const NamedValue& v = values.getReference(i);
  3500. if (v.name == name)
  3501. return v.value;
  3502. }
  3503. return var::null;
  3504. }
  3505. const var NamedValueSet::getWithDefault (const Identifier& name, const var& defaultReturnValue) const
  3506. {
  3507. const var* v = getItem (name);
  3508. return v != 0 ? *v : defaultReturnValue;
  3509. }
  3510. var* NamedValueSet::getItem (const Identifier& name) const
  3511. {
  3512. for (int i = values.size(); --i >= 0;)
  3513. {
  3514. NamedValue& v = values.getReference(i);
  3515. if (v.name == name)
  3516. return &(v.value);
  3517. }
  3518. return 0;
  3519. }
  3520. bool NamedValueSet::set (const Identifier& name, const var& newValue)
  3521. {
  3522. for (int i = values.size(); --i >= 0;)
  3523. {
  3524. NamedValue& v = values.getReference(i);
  3525. if (v.name == name)
  3526. {
  3527. if (v.value == newValue)
  3528. return false;
  3529. v.value = newValue;
  3530. return true;
  3531. }
  3532. }
  3533. values.add (NamedValue (name, newValue));
  3534. return true;
  3535. }
  3536. bool NamedValueSet::contains (const Identifier& name) const
  3537. {
  3538. return getItem (name) != 0;
  3539. }
  3540. bool NamedValueSet::remove (const Identifier& name)
  3541. {
  3542. for (int i = values.size(); --i >= 0;)
  3543. {
  3544. if (values.getReference(i).name == name)
  3545. {
  3546. values.remove (i);
  3547. return true;
  3548. }
  3549. }
  3550. return false;
  3551. }
  3552. const Identifier NamedValueSet::getName (const int index) const
  3553. {
  3554. jassert (((unsigned int) index) < (unsigned int) values.size());
  3555. return values [index].name;
  3556. }
  3557. const var NamedValueSet::getValueAt (const int index) const
  3558. {
  3559. jassert (((unsigned int) index) < (unsigned int) values.size());
  3560. return values [index].value;
  3561. }
  3562. void NamedValueSet::clear()
  3563. {
  3564. values.clear();
  3565. }
  3566. END_JUCE_NAMESPACE
  3567. /*** End of inlined file: juce_NamedValueSet.cpp ***/
  3568. /*** Start of inlined file: juce_DynamicObject.cpp ***/
  3569. BEGIN_JUCE_NAMESPACE
  3570. DynamicObject::DynamicObject()
  3571. {
  3572. }
  3573. DynamicObject::~DynamicObject()
  3574. {
  3575. }
  3576. bool DynamicObject::hasProperty (const Identifier& propertyName) const
  3577. {
  3578. var* const v = properties.getItem (propertyName);
  3579. return v != 0 && ! v->isMethod();
  3580. }
  3581. const var DynamicObject::getProperty (const Identifier& propertyName) const
  3582. {
  3583. return properties [propertyName];
  3584. }
  3585. void DynamicObject::setProperty (const Identifier& propertyName, const var& newValue)
  3586. {
  3587. properties.set (propertyName, newValue);
  3588. }
  3589. void DynamicObject::removeProperty (const Identifier& propertyName)
  3590. {
  3591. properties.remove (propertyName);
  3592. }
  3593. bool DynamicObject::hasMethod (const Identifier& methodName) const
  3594. {
  3595. return getProperty (methodName).isMethod();
  3596. }
  3597. const var DynamicObject::invokeMethod (const Identifier& methodName,
  3598. const var* parameters,
  3599. int numParameters)
  3600. {
  3601. return properties [methodName].invoke (var (this), parameters, numParameters);
  3602. }
  3603. void DynamicObject::setMethod (const Identifier& name,
  3604. var::MethodFunction methodFunction)
  3605. {
  3606. properties.set (name, var (methodFunction));
  3607. }
  3608. void DynamicObject::clear()
  3609. {
  3610. properties.clear();
  3611. }
  3612. END_JUCE_NAMESPACE
  3613. /*** End of inlined file: juce_DynamicObject.cpp ***/
  3614. /*** Start of inlined file: juce_BlowFish.cpp ***/
  3615. BEGIN_JUCE_NAMESPACE
  3616. BlowFish::BlowFish (const void* const keyData, const int keyBytes)
  3617. {
  3618. jassert (keyData != 0);
  3619. jassert (keyBytes > 0);
  3620. static const uint32 initialPValues [18] =
  3621. {
  3622. 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
  3623. 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
  3624. 0x9216d5d9, 0x8979fb1b
  3625. };
  3626. static const uint32 initialSValues [4 * 256] =
  3627. {
  3628. 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
  3629. 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
  3630. 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
  3631. 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
  3632. 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
  3633. 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
  3634. 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
  3635. 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
  3636. 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
  3637. 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
  3638. 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
  3639. 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
  3640. 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
  3641. 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
  3642. 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
  3643. 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
  3644. 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
  3645. 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
  3646. 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
  3647. 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
  3648. 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
  3649. 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
  3650. 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
  3651. 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
  3652. 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
  3653. 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
  3654. 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
  3655. 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
  3656. 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
  3657. 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
  3658. 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
  3659. 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
  3660. 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
  3661. 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
  3662. 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
  3663. 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
  3664. 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
  3665. 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
  3666. 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
  3667. 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
  3668. 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
  3669. 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
  3670. 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
  3671. 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
  3672. 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
  3673. 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
  3674. 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
  3675. 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
  3676. 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
  3677. 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
  3678. 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
  3679. 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
  3680. 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
  3681. 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
  3682. 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
  3683. 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
  3684. 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
  3685. 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
  3686. 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
  3687. 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
  3688. 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
  3689. 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
  3690. 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
  3691. 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
  3692. 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
  3693. 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
  3694. 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
  3695. 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
  3696. 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
  3697. 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
  3698. 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
  3699. 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
  3700. 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
  3701. 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
  3702. 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
  3703. 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
  3704. 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
  3705. 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
  3706. 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
  3707. 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
  3708. 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
  3709. 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
  3710. 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
  3711. 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
  3712. 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
  3713. 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
  3714. 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
  3715. 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
  3716. 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
  3717. 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
  3718. 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
  3719. 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
  3720. 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
  3721. 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
  3722. 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
  3723. 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
  3724. 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
  3725. 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
  3726. 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
  3727. 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
  3728. 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
  3729. 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
  3730. 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
  3731. 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
  3732. 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
  3733. 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
  3734. 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
  3735. 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
  3736. 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
  3737. 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
  3738. 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
  3739. 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
  3740. 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
  3741. 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
  3742. 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
  3743. 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
  3744. 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
  3745. 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
  3746. 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
  3747. 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
  3748. 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
  3749. 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
  3750. 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
  3751. 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
  3752. 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
  3753. 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
  3754. 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
  3755. 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
  3756. };
  3757. memcpy (p, initialPValues, sizeof (p));
  3758. int i, j = 0;
  3759. for (i = 4; --i >= 0;)
  3760. {
  3761. s[i].malloc (256);
  3762. memcpy (s[i], initialSValues + i * 256, 256 * sizeof (uint32));
  3763. }
  3764. for (i = 0; i < 18; ++i)
  3765. {
  3766. uint32 d = 0;
  3767. for (int k = 0; k < 4; ++k)
  3768. {
  3769. d = (d << 8) | static_cast <const uint8*> (keyData)[j];
  3770. if (++j >= keyBytes)
  3771. j = 0;
  3772. }
  3773. p[i] = initialPValues[i] ^ d;
  3774. }
  3775. uint32 l = 0, r = 0;
  3776. for (i = 0; i < 18; i += 2)
  3777. {
  3778. encrypt (l, r);
  3779. p[i] = l;
  3780. p[i + 1] = r;
  3781. }
  3782. for (i = 0; i < 4; ++i)
  3783. {
  3784. for (j = 0; j < 256; j += 2)
  3785. {
  3786. encrypt (l, r);
  3787. s[i][j] = l;
  3788. s[i][j + 1] = r;
  3789. }
  3790. }
  3791. }
  3792. BlowFish::BlowFish (const BlowFish& other)
  3793. {
  3794. for (int i = 4; --i >= 0;)
  3795. s[i].malloc (256);
  3796. operator= (other);
  3797. }
  3798. BlowFish& BlowFish::operator= (const BlowFish& other)
  3799. {
  3800. memcpy (p, other.p, sizeof (p));
  3801. for (int i = 4; --i >= 0;)
  3802. memcpy (s[i], other.s[i], 256 * sizeof (uint32));
  3803. return *this;
  3804. }
  3805. BlowFish::~BlowFish()
  3806. {
  3807. }
  3808. uint32 BlowFish::F (const uint32 x) const throw()
  3809. {
  3810. return ((s[0][(x >> 24) & 0xff] + s[1][(x >> 16) & 0xff])
  3811. ^ s[2][(x >> 8) & 0xff]) + s[3][x & 0xff];
  3812. }
  3813. void BlowFish::encrypt (uint32& data1, uint32& data2) const throw()
  3814. {
  3815. uint32 l = data1;
  3816. uint32 r = data2;
  3817. for (int i = 0; i < 16; ++i)
  3818. {
  3819. l ^= p[i];
  3820. r ^= F(l);
  3821. swapVariables (l, r);
  3822. }
  3823. data1 = r ^ p[17];
  3824. data2 = l ^ p[16];
  3825. }
  3826. void BlowFish::decrypt (uint32& data1, uint32& data2) const throw()
  3827. {
  3828. uint32 l = data1;
  3829. uint32 r = data2;
  3830. for (int i = 17; i > 1; --i)
  3831. {
  3832. l ^= p[i];
  3833. r ^= F(l);
  3834. swapVariables (l, r);
  3835. }
  3836. data1 = r ^ p[0];
  3837. data2 = l ^ p[1];
  3838. }
  3839. END_JUCE_NAMESPACE
  3840. /*** End of inlined file: juce_BlowFish.cpp ***/
  3841. /*** Start of inlined file: juce_MD5.cpp ***/
  3842. BEGIN_JUCE_NAMESPACE
  3843. MD5::MD5()
  3844. {
  3845. zerostruct (result);
  3846. }
  3847. MD5::MD5 (const MD5& other)
  3848. {
  3849. memcpy (result, other.result, sizeof (result));
  3850. }
  3851. MD5& MD5::operator= (const MD5& other)
  3852. {
  3853. memcpy (result, other.result, sizeof (result));
  3854. return *this;
  3855. }
  3856. MD5::MD5 (const MemoryBlock& data)
  3857. {
  3858. ProcessContext context;
  3859. context.processBlock (data.getData(), data.getSize());
  3860. context.finish (result);
  3861. }
  3862. MD5::MD5 (const void* data, const size_t numBytes)
  3863. {
  3864. ProcessContext context;
  3865. context.processBlock (data, numBytes);
  3866. context.finish (result);
  3867. }
  3868. MD5::MD5 (const String& text)
  3869. {
  3870. ProcessContext context;
  3871. const int len = text.length();
  3872. const juce_wchar* const t = text;
  3873. for (int i = 0; i < len; ++i)
  3874. {
  3875. // force the string into integer-sized unicode characters, to try to make it
  3876. // get the same results on all platforms + compilers.
  3877. uint32 unicodeChar = ByteOrder::swapIfBigEndian ((uint32) t[i]);
  3878. context.processBlock (&unicodeChar, sizeof (unicodeChar));
  3879. }
  3880. context.finish (result);
  3881. }
  3882. void MD5::processStream (InputStream& input, int64 numBytesToRead)
  3883. {
  3884. ProcessContext context;
  3885. if (numBytesToRead < 0)
  3886. numBytesToRead = std::numeric_limits<int64>::max();
  3887. while (numBytesToRead > 0)
  3888. {
  3889. uint8 tempBuffer [512];
  3890. const int bytesRead = input.read (tempBuffer, (int) jmin (numBytesToRead, (int64) sizeof (tempBuffer)));
  3891. if (bytesRead <= 0)
  3892. break;
  3893. numBytesToRead -= bytesRead;
  3894. context.processBlock (tempBuffer, bytesRead);
  3895. }
  3896. context.finish (result);
  3897. }
  3898. MD5::MD5 (InputStream& input, int64 numBytesToRead)
  3899. {
  3900. processStream (input, numBytesToRead);
  3901. }
  3902. MD5::MD5 (const File& file)
  3903. {
  3904. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  3905. if (fin != 0)
  3906. processStream (*fin, -1);
  3907. else
  3908. zerostruct (result);
  3909. }
  3910. MD5::~MD5()
  3911. {
  3912. }
  3913. namespace MD5Functions
  3914. {
  3915. static void encode (void* const output, const void* const input, const int numBytes) throw()
  3916. {
  3917. for (int i = 0; i < (numBytes >> 2); ++i)
  3918. static_cast<uint32*> (output)[i] = ByteOrder::swapIfBigEndian (static_cast<const uint32*> (input) [i]);
  3919. }
  3920. static inline uint32 F (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & y) | (~x & z); }
  3921. static inline uint32 G (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & z) | (y & ~z); }
  3922. static inline uint32 H (const uint32 x, const uint32 y, const uint32 z) throw() { return x ^ y ^ z; }
  3923. static inline uint32 I (const uint32 x, const uint32 y, const uint32 z) throw() { return y ^ (x | ~z); }
  3924. static inline uint32 rotateLeft (const uint32 x, const uint32 n) throw() { return (x << n) | (x >> (32 - n)); }
  3925. static void FF (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  3926. {
  3927. a += F (b, c, d) + x + ac;
  3928. a = rotateLeft (a, s) + b;
  3929. }
  3930. static void GG (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  3931. {
  3932. a += G (b, c, d) + x + ac;
  3933. a = rotateLeft (a, s) + b;
  3934. }
  3935. static void HH (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  3936. {
  3937. a += H (b, c, d) + x + ac;
  3938. a = rotateLeft (a, s) + b;
  3939. }
  3940. static void II (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  3941. {
  3942. a += I (b, c, d) + x + ac;
  3943. a = rotateLeft (a, s) + b;
  3944. }
  3945. }
  3946. MD5::ProcessContext::ProcessContext()
  3947. {
  3948. state[0] = 0x67452301;
  3949. state[1] = 0xefcdab89;
  3950. state[2] = 0x98badcfe;
  3951. state[3] = 0x10325476;
  3952. count[0] = 0;
  3953. count[1] = 0;
  3954. }
  3955. void MD5::ProcessContext::processBlock (const void* const data, const size_t dataSize)
  3956. {
  3957. int bufferPos = ((count[0] >> 3) & 0x3F);
  3958. count[0] += (uint32) (dataSize << 3);
  3959. if (count[0] < ((uint32) dataSize << 3))
  3960. count[1]++;
  3961. count[1] += (uint32) (dataSize >> 29);
  3962. const size_t spaceLeft = 64 - bufferPos;
  3963. size_t i = 0;
  3964. if (dataSize >= spaceLeft)
  3965. {
  3966. memcpy (buffer + bufferPos, data, spaceLeft);
  3967. transform (buffer);
  3968. for (i = spaceLeft; i + 64 <= dataSize; i += 64)
  3969. transform (static_cast <const char*> (data) + i);
  3970. bufferPos = 0;
  3971. }
  3972. memcpy (buffer + bufferPos, static_cast <const char*> (data) + i, dataSize - i);
  3973. }
  3974. void MD5::ProcessContext::finish (void* const result)
  3975. {
  3976. unsigned char encodedLength[8];
  3977. MD5Functions::encode (encodedLength, count, 8);
  3978. // Pad out to 56 mod 64.
  3979. const int index = (uint32) ((count[0] >> 3) & 0x3f);
  3980. const int paddingLength = (index < 56) ? (56 - index)
  3981. : (120 - index);
  3982. uint8 paddingBuffer [64];
  3983. zeromem (paddingBuffer, paddingLength);
  3984. paddingBuffer [0] = 0x80;
  3985. processBlock (paddingBuffer, paddingLength);
  3986. processBlock (encodedLength, 8);
  3987. MD5Functions::encode (result, state, 16);
  3988. zerostruct (buffer);
  3989. }
  3990. void MD5::ProcessContext::transform (const void* const bufferToTransform)
  3991. {
  3992. using namespace MD5Functions;
  3993. uint32 a = state[0];
  3994. uint32 b = state[1];
  3995. uint32 c = state[2];
  3996. uint32 d = state[3];
  3997. uint32 x[16];
  3998. encode (x, bufferToTransform, 64);
  3999. enum Constants
  4000. {
  4001. S11 = 7, S12 = 12, S13 = 17, S14 = 22, S21 = 5, S22 = 9, S23 = 14, S24 = 20,
  4002. S31 = 4, S32 = 11, S33 = 16, S34 = 23, S41 = 6, S42 = 10, S43 = 15, S44 = 21
  4003. };
  4004. FF (a, b, c, d, x[ 0], S11, 0xd76aa478); FF (d, a, b, c, x[ 1], S12, 0xe8c7b756);
  4005. FF (c, d, a, b, x[ 2], S13, 0x242070db); FF (b, c, d, a, x[ 3], S14, 0xc1bdceee);
  4006. FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); FF (d, a, b, c, x[ 5], S12, 0x4787c62a);
  4007. FF (c, d, a, b, x[ 6], S13, 0xa8304613); FF (b, c, d, a, x[ 7], S14, 0xfd469501);
  4008. FF (a, b, c, d, x[ 8], S11, 0x698098d8); FF (d, a, b, c, x[ 9], S12, 0x8b44f7af);
  4009. FF (c, d, a, b, x[10], S13, 0xffff5bb1); FF (b, c, d, a, x[11], S14, 0x895cd7be);
  4010. FF (a, b, c, d, x[12], S11, 0x6b901122); FF (d, a, b, c, x[13], S12, 0xfd987193);
  4011. FF (c, d, a, b, x[14], S13, 0xa679438e); FF (b, c, d, a, x[15], S14, 0x49b40821);
  4012. GG (a, b, c, d, x[ 1], S21, 0xf61e2562); GG (d, a, b, c, x[ 6], S22, 0xc040b340);
  4013. GG (c, d, a, b, x[11], S23, 0x265e5a51); GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa);
  4014. GG (a, b, c, d, x[ 5], S21, 0xd62f105d); GG (d, a, b, c, x[10], S22, 0x02441453);
  4015. GG (c, d, a, b, x[15], S23, 0xd8a1e681); GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8);
  4016. GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); GG (d, a, b, c, x[14], S22, 0xc33707d6);
  4017. GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); GG (b, c, d, a, x[ 8], S24, 0x455a14ed);
  4018. GG (a, b, c, d, x[13], S21, 0xa9e3e905); GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8);
  4019. GG (c, d, a, b, x[ 7], S23, 0x676f02d9); GG (b, c, d, a, x[12], S24, 0x8d2a4c8a);
  4020. HH (a, b, c, d, x[ 5], S31, 0xfffa3942); HH (d, a, b, c, x[ 8], S32, 0x8771f681);
  4021. HH (c, d, a, b, x[11], S33, 0x6d9d6122); HH (b, c, d, a, x[14], S34, 0xfde5380c);
  4022. HH (a, b, c, d, x[ 1], S31, 0xa4beea44); HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9);
  4023. HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); HH (b, c, d, a, x[10], S34, 0xbebfbc70);
  4024. HH (a, b, c, d, x[13], S31, 0x289b7ec6); HH (d, a, b, c, x[ 0], S32, 0xeaa127fa);
  4025. HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); HH (b, c, d, a, x[ 6], S34, 0x04881d05);
  4026. HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); HH (d, a, b, c, x[12], S32, 0xe6db99e5);
  4027. HH (c, d, a, b, x[15], S33, 0x1fa27cf8); HH (b, c, d, a, x[ 2], S34, 0xc4ac5665);
  4028. II (a, b, c, d, x[ 0], S41, 0xf4292244); II (d, a, b, c, x[ 7], S42, 0x432aff97);
  4029. II (c, d, a, b, x[14], S43, 0xab9423a7); II (b, c, d, a, x[ 5], S44, 0xfc93a039);
  4030. II (a, b, c, d, x[12], S41, 0x655b59c3); II (d, a, b, c, x[ 3], S42, 0x8f0ccc92);
  4031. II (c, d, a, b, x[10], S43, 0xffeff47d); II (b, c, d, a, x[ 1], S44, 0x85845dd1);
  4032. II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); II (d, a, b, c, x[15], S42, 0xfe2ce6e0);
  4033. II (c, d, a, b, x[ 6], S43, 0xa3014314); II (b, c, d, a, x[13], S44, 0x4e0811a1);
  4034. II (a, b, c, d, x[ 4], S41, 0xf7537e82); II (d, a, b, c, x[11], S42, 0xbd3af235);
  4035. II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); II (b, c, d, a, x[ 9], S44, 0xeb86d391);
  4036. state[0] += a;
  4037. state[1] += b;
  4038. state[2] += c;
  4039. state[3] += d;
  4040. zerostruct (x);
  4041. }
  4042. const MemoryBlock MD5::getRawChecksumData() const
  4043. {
  4044. return MemoryBlock (result, sizeof (result));
  4045. }
  4046. const String MD5::toHexString() const
  4047. {
  4048. return String::toHexString (result, sizeof (result), 0);
  4049. }
  4050. bool MD5::operator== (const MD5& other) const
  4051. {
  4052. return memcmp (result, other.result, sizeof (result)) == 0;
  4053. }
  4054. bool MD5::operator!= (const MD5& other) const
  4055. {
  4056. return ! operator== (other);
  4057. }
  4058. END_JUCE_NAMESPACE
  4059. /*** End of inlined file: juce_MD5.cpp ***/
  4060. /*** Start of inlined file: juce_Primes.cpp ***/
  4061. BEGIN_JUCE_NAMESPACE
  4062. namespace PrimesHelpers
  4063. {
  4064. static void createSmallSieve (const int numBits, BigInteger& result)
  4065. {
  4066. result.setBit (numBits);
  4067. result.clearBit (numBits); // to enlarge the array
  4068. result.setBit (0);
  4069. int n = 2;
  4070. do
  4071. {
  4072. for (int i = n + n; i < numBits; i += n)
  4073. result.setBit (i);
  4074. n = result.findNextClearBit (n + 1);
  4075. }
  4076. while (n <= (numBits >> 1));
  4077. }
  4078. static void bigSieve (const BigInteger& base, const int numBits, BigInteger& result,
  4079. const BigInteger& smallSieve, const int smallSieveSize)
  4080. {
  4081. jassert (! base[0]); // must be even!
  4082. result.setBit (numBits);
  4083. result.clearBit (numBits); // to enlarge the array
  4084. int index = smallSieve.findNextClearBit (0);
  4085. do
  4086. {
  4087. const int prime = (index << 1) + 1;
  4088. BigInteger r (base), remainder;
  4089. r.divideBy (prime, remainder);
  4090. int i = prime - remainder.getBitRangeAsInt (0, 32);
  4091. if (r.isZero())
  4092. i += prime;
  4093. if ((i & 1) == 0)
  4094. i += prime;
  4095. i = (i - 1) >> 1;
  4096. while (i < numBits)
  4097. {
  4098. result.setBit (i);
  4099. i += prime;
  4100. }
  4101. index = smallSieve.findNextClearBit (index + 1);
  4102. }
  4103. while (index < smallSieveSize);
  4104. }
  4105. static bool findCandidate (const BigInteger& base, const BigInteger& sieve,
  4106. const int numBits, BigInteger& result, const int certainty)
  4107. {
  4108. for (int i = 0; i < numBits; ++i)
  4109. {
  4110. if (! sieve[i])
  4111. {
  4112. result = base + (unsigned int) ((i << 1) + 1);
  4113. if (Primes::isProbablyPrime (result, certainty))
  4114. return true;
  4115. }
  4116. }
  4117. return false;
  4118. }
  4119. static bool passesMillerRabin (const BigInteger& n, int iterations)
  4120. {
  4121. const BigInteger one (1), two (2);
  4122. const BigInteger nMinusOne (n - one);
  4123. BigInteger d (nMinusOne);
  4124. const int s = d.findNextSetBit (0);
  4125. d >>= s;
  4126. BigInteger smallPrimes;
  4127. int numBitsInSmallPrimes = 0;
  4128. for (;;)
  4129. {
  4130. numBitsInSmallPrimes += 256;
  4131. createSmallSieve (numBitsInSmallPrimes, smallPrimes);
  4132. const int numPrimesFound = numBitsInSmallPrimes - smallPrimes.countNumberOfSetBits();
  4133. if (numPrimesFound > iterations + 1)
  4134. break;
  4135. }
  4136. int smallPrime = 2;
  4137. while (--iterations >= 0)
  4138. {
  4139. smallPrime = smallPrimes.findNextClearBit (smallPrime + 1);
  4140. BigInteger r (smallPrime);
  4141. r.exponentModulo (d, n);
  4142. if (r != one && r != nMinusOne)
  4143. {
  4144. for (int j = 0; j < s; ++j)
  4145. {
  4146. r.exponentModulo (two, n);
  4147. if (r == nMinusOne)
  4148. break;
  4149. }
  4150. if (r != nMinusOne)
  4151. return false;
  4152. }
  4153. }
  4154. return true;
  4155. }
  4156. }
  4157. const BigInteger Primes::createProbablePrime (const int bitLength,
  4158. const int certainty,
  4159. const int* randomSeeds,
  4160. int numRandomSeeds)
  4161. {
  4162. using namespace PrimesHelpers;
  4163. int defaultSeeds [16];
  4164. if (numRandomSeeds <= 0)
  4165. {
  4166. randomSeeds = defaultSeeds;
  4167. numRandomSeeds = numElementsInArray (defaultSeeds);
  4168. Random r (0);
  4169. for (int j = 10; --j >= 0;)
  4170. {
  4171. r.setSeedRandomly();
  4172. for (int i = numRandomSeeds; --i >= 0;)
  4173. defaultSeeds[i] ^= r.nextInt() ^ Random::getSystemRandom().nextInt();
  4174. }
  4175. }
  4176. BigInteger smallSieve;
  4177. const int smallSieveSize = 15000;
  4178. createSmallSieve (smallSieveSize, smallSieve);
  4179. BigInteger p;
  4180. for (int i = numRandomSeeds; --i >= 0;)
  4181. {
  4182. BigInteger p2;
  4183. Random r (randomSeeds[i]);
  4184. r.fillBitsRandomly (p2, 0, bitLength);
  4185. p ^= p2;
  4186. }
  4187. p.setBit (bitLength - 1);
  4188. p.clearBit (0);
  4189. const int searchLen = jmax (1024, (bitLength / 20) * 64);
  4190. while (p.getHighestBit() < bitLength)
  4191. {
  4192. p += 2 * searchLen;
  4193. BigInteger sieve;
  4194. bigSieve (p, searchLen, sieve,
  4195. smallSieve, smallSieveSize);
  4196. BigInteger candidate;
  4197. if (findCandidate (p, sieve, searchLen, candidate, certainty))
  4198. return candidate;
  4199. }
  4200. jassertfalse;
  4201. return BigInteger();
  4202. }
  4203. bool Primes::isProbablyPrime (const BigInteger& number, const int certainty)
  4204. {
  4205. using namespace PrimesHelpers;
  4206. if (! number[0])
  4207. return false;
  4208. if (number.getHighestBit() <= 10)
  4209. {
  4210. const int num = number.getBitRangeAsInt (0, 10);
  4211. for (int i = num / 2; --i > 1;)
  4212. if (num % i == 0)
  4213. return false;
  4214. return true;
  4215. }
  4216. else
  4217. {
  4218. if (number.findGreatestCommonDivisor (2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23) != 1)
  4219. return false;
  4220. return passesMillerRabin (number, certainty);
  4221. }
  4222. }
  4223. END_JUCE_NAMESPACE
  4224. /*** End of inlined file: juce_Primes.cpp ***/
  4225. /*** Start of inlined file: juce_RSAKey.cpp ***/
  4226. BEGIN_JUCE_NAMESPACE
  4227. RSAKey::RSAKey()
  4228. {
  4229. }
  4230. RSAKey::RSAKey (const String& s)
  4231. {
  4232. if (s.containsChar (','))
  4233. {
  4234. part1.parseString (s.upToFirstOccurrenceOf (",", false, false), 16);
  4235. part2.parseString (s.fromFirstOccurrenceOf (",", false, false), 16);
  4236. }
  4237. else
  4238. {
  4239. // the string needs to be two hex numbers, comma-separated..
  4240. jassertfalse;
  4241. }
  4242. }
  4243. RSAKey::~RSAKey()
  4244. {
  4245. }
  4246. bool RSAKey::operator== (const RSAKey& other) const throw()
  4247. {
  4248. return part1 == other.part1 && part2 == other.part2;
  4249. }
  4250. bool RSAKey::operator!= (const RSAKey& other) const throw()
  4251. {
  4252. return ! operator== (other);
  4253. }
  4254. const String RSAKey::toString() const
  4255. {
  4256. return part1.toString (16) + "," + part2.toString (16);
  4257. }
  4258. bool RSAKey::applyToValue (BigInteger& value) const
  4259. {
  4260. if (part1.isZero() || part2.isZero() || value <= 0)
  4261. {
  4262. jassertfalse; // using an uninitialised key
  4263. value.clear();
  4264. return false;
  4265. }
  4266. BigInteger result;
  4267. while (! value.isZero())
  4268. {
  4269. result *= part2;
  4270. BigInteger remainder;
  4271. value.divideBy (part2, remainder);
  4272. remainder.exponentModulo (part1, part2);
  4273. result += remainder;
  4274. }
  4275. value.swapWith (result);
  4276. return true;
  4277. }
  4278. const BigInteger RSAKey::findBestCommonDivisor (const BigInteger& p, const BigInteger& q)
  4279. {
  4280. // try 3, 5, 9, 17, etc first because these only contain 2 bits and so
  4281. // are fast to divide + multiply
  4282. for (int i = 2; i <= 65536; i *= 2)
  4283. {
  4284. const BigInteger e (1 + i);
  4285. if (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne())
  4286. return e;
  4287. }
  4288. BigInteger e (4);
  4289. while (! (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne()))
  4290. ++e;
  4291. return e;
  4292. }
  4293. void RSAKey::createKeyPair (RSAKey& publicKey, RSAKey& privateKey,
  4294. const int numBits, const int* randomSeeds, const int numRandomSeeds)
  4295. {
  4296. jassert (numBits > 16); // not much point using less than this..
  4297. BigInteger p (Primes::createProbablePrime (numBits / 2, 30, randomSeeds, numRandomSeeds));
  4298. BigInteger q (Primes::createProbablePrime (numBits - numBits / 2, 30, randomSeeds, numRandomSeeds));
  4299. const BigInteger n (p * q);
  4300. const BigInteger m (--p * --q);
  4301. const BigInteger e (findBestCommonDivisor (p, q));
  4302. BigInteger d (e);
  4303. d.inverseModulo (m);
  4304. publicKey.part1 = e;
  4305. publicKey.part2 = n;
  4306. privateKey.part1 = d;
  4307. privateKey.part2 = n;
  4308. }
  4309. END_JUCE_NAMESPACE
  4310. /*** End of inlined file: juce_RSAKey.cpp ***/
  4311. /*** Start of inlined file: juce_InputStream.cpp ***/
  4312. BEGIN_JUCE_NAMESPACE
  4313. char InputStream::readByte()
  4314. {
  4315. char temp = 0;
  4316. read (&temp, 1);
  4317. return temp;
  4318. }
  4319. bool InputStream::readBool()
  4320. {
  4321. return readByte() != 0;
  4322. }
  4323. short InputStream::readShort()
  4324. {
  4325. char temp[2];
  4326. if (read (temp, 2) == 2)
  4327. return (short) ByteOrder::littleEndianShort (temp);
  4328. return 0;
  4329. }
  4330. short InputStream::readShortBigEndian()
  4331. {
  4332. char temp[2];
  4333. if (read (temp, 2) == 2)
  4334. return (short) ByteOrder::bigEndianShort (temp);
  4335. return 0;
  4336. }
  4337. int InputStream::readInt()
  4338. {
  4339. char temp[4];
  4340. if (read (temp, 4) == 4)
  4341. return (int) ByteOrder::littleEndianInt (temp);
  4342. return 0;
  4343. }
  4344. int InputStream::readIntBigEndian()
  4345. {
  4346. char temp[4];
  4347. if (read (temp, 4) == 4)
  4348. return (int) ByteOrder::bigEndianInt (temp);
  4349. return 0;
  4350. }
  4351. int InputStream::readCompressedInt()
  4352. {
  4353. const unsigned char sizeByte = readByte();
  4354. if (sizeByte == 0)
  4355. return 0;
  4356. const int numBytes = (sizeByte & 0x7f);
  4357. if (numBytes > 4)
  4358. {
  4359. jassertfalse; // trying to read corrupt data - this method must only be used
  4360. // to read data that was written by OutputStream::writeCompressedInt()
  4361. return 0;
  4362. }
  4363. char bytes[4] = { 0, 0, 0, 0 };
  4364. if (read (bytes, numBytes) != numBytes)
  4365. return 0;
  4366. const int num = (int) ByteOrder::littleEndianInt (bytes);
  4367. return (sizeByte >> 7) ? -num : num;
  4368. }
  4369. int64 InputStream::readInt64()
  4370. {
  4371. union { uint8 asBytes[8]; uint64 asInt64; } n;
  4372. if (read (n.asBytes, 8) == 8)
  4373. return (int64) ByteOrder::swapIfBigEndian (n.asInt64);
  4374. return 0;
  4375. }
  4376. int64 InputStream::readInt64BigEndian()
  4377. {
  4378. union { uint8 asBytes[8]; uint64 asInt64; } n;
  4379. if (read (n.asBytes, 8) == 8)
  4380. return (int64) ByteOrder::swapIfLittleEndian (n.asInt64);
  4381. return 0;
  4382. }
  4383. float InputStream::readFloat()
  4384. {
  4385. // the union below relies on these types being the same size...
  4386. static_jassert (sizeof (int32) == sizeof (float));
  4387. union { int32 asInt; float asFloat; } n;
  4388. n.asInt = (int32) readInt();
  4389. return n.asFloat;
  4390. }
  4391. float InputStream::readFloatBigEndian()
  4392. {
  4393. union { int32 asInt; float asFloat; } n;
  4394. n.asInt = (int32) readIntBigEndian();
  4395. return n.asFloat;
  4396. }
  4397. double InputStream::readDouble()
  4398. {
  4399. union { int64 asInt; double asDouble; } n;
  4400. n.asInt = readInt64();
  4401. return n.asDouble;
  4402. }
  4403. double InputStream::readDoubleBigEndian()
  4404. {
  4405. union { int64 asInt; double asDouble; } n;
  4406. n.asInt = readInt64BigEndian();
  4407. return n.asDouble;
  4408. }
  4409. const String InputStream::readString()
  4410. {
  4411. MemoryBlock buffer (256);
  4412. char* data = static_cast<char*> (buffer.getData());
  4413. size_t i = 0;
  4414. while ((data[i] = readByte()) != 0)
  4415. {
  4416. if (++i >= buffer.getSize())
  4417. {
  4418. buffer.setSize (buffer.getSize() + 512);
  4419. data = static_cast<char*> (buffer.getData());
  4420. }
  4421. }
  4422. return String::fromUTF8 (data, (int) i);
  4423. }
  4424. const String InputStream::readNextLine()
  4425. {
  4426. MemoryBlock buffer (256);
  4427. char* data = static_cast<char*> (buffer.getData());
  4428. size_t i = 0;
  4429. while ((data[i] = readByte()) != 0)
  4430. {
  4431. if (data[i] == '\n')
  4432. break;
  4433. if (data[i] == '\r')
  4434. {
  4435. const int64 lastPos = getPosition();
  4436. if (readByte() != '\n')
  4437. setPosition (lastPos);
  4438. break;
  4439. }
  4440. if (++i >= buffer.getSize())
  4441. {
  4442. buffer.setSize (buffer.getSize() + 512);
  4443. data = static_cast<char*> (buffer.getData());
  4444. }
  4445. }
  4446. return String::fromUTF8 (data, (int) i);
  4447. }
  4448. int InputStream::readIntoMemoryBlock (MemoryBlock& block, int numBytes)
  4449. {
  4450. const int64 totalLength = getTotalLength();
  4451. if (totalLength >= 0)
  4452. {
  4453. const int totalBytesRemaining = (int) jmin ((int64) 0x7fffffff,
  4454. totalLength - getPosition());
  4455. if (numBytes < 0)
  4456. numBytes = totalBytesRemaining;
  4457. else if (numBytes > 0)
  4458. numBytes = jmin (numBytes, totalBytesRemaining);
  4459. else
  4460. return 0;
  4461. }
  4462. const size_t originalBlockSize = block.getSize();
  4463. int totalBytesRead = 0;
  4464. if (numBytes > 0)
  4465. {
  4466. // know how many bytes we want, so we can resize the block first..
  4467. block.setSize (originalBlockSize + numBytes, false);
  4468. totalBytesRead = read (static_cast<char*> (block.getData()) + originalBlockSize, numBytes);
  4469. }
  4470. else
  4471. {
  4472. // read until end of stram..
  4473. const int chunkSize = 32768;
  4474. for (;;)
  4475. {
  4476. block.ensureSize (originalBlockSize + totalBytesRead + chunkSize, false);
  4477. const int bytesJustIn = read (static_cast<char*> (block.getData())
  4478. + originalBlockSize
  4479. + totalBytesRead,
  4480. chunkSize);
  4481. if (bytesJustIn == 0)
  4482. break;
  4483. totalBytesRead += bytesJustIn;
  4484. }
  4485. }
  4486. // trim off any excess left at the end
  4487. block.setSize (originalBlockSize + totalBytesRead, false);
  4488. return totalBytesRead;
  4489. }
  4490. const String InputStream::readEntireStreamAsString()
  4491. {
  4492. MemoryBlock mb;
  4493. const int size = readIntoMemoryBlock (mb);
  4494. return String::createStringFromData (static_cast<const char*> (mb.getData()), size);
  4495. }
  4496. void InputStream::skipNextBytes (int64 numBytesToSkip)
  4497. {
  4498. if (numBytesToSkip > 0)
  4499. {
  4500. const int skipBufferSize = (int) jmin (numBytesToSkip, (int64) 16384);
  4501. HeapBlock<char> temp (skipBufferSize);
  4502. while (numBytesToSkip > 0 && ! isExhausted())
  4503. numBytesToSkip -= read (temp, (int) jmin (numBytesToSkip, (int64) skipBufferSize));
  4504. }
  4505. }
  4506. END_JUCE_NAMESPACE
  4507. /*** End of inlined file: juce_InputStream.cpp ***/
  4508. /*** Start of inlined file: juce_OutputStream.cpp ***/
  4509. BEGIN_JUCE_NAMESPACE
  4510. #if JUCE_DEBUG
  4511. static CriticalSection activeStreamLock;
  4512. static Array<void*> activeStreams;
  4513. void juce_CheckForDanglingStreams()
  4514. {
  4515. /*
  4516. It's always a bad idea to leak any object, but if you're leaking output
  4517. streams, then there's a good chance that you're failing to flush a file
  4518. to disk properly, which could result in corrupted data and other similar
  4519. nastiness..
  4520. */
  4521. jassert (activeStreams.size() == 0);
  4522. };
  4523. #endif
  4524. OutputStream::OutputStream()
  4525. {
  4526. #if JUCE_DEBUG
  4527. const ScopedLock sl (activeStreamLock);
  4528. activeStreams.add (this);
  4529. #endif
  4530. }
  4531. OutputStream::~OutputStream()
  4532. {
  4533. #if JUCE_DEBUG
  4534. const ScopedLock sl (activeStreamLock);
  4535. activeStreams.removeValue (this);
  4536. #endif
  4537. }
  4538. void OutputStream::writeBool (const bool b)
  4539. {
  4540. writeByte (b ? (char) 1
  4541. : (char) 0);
  4542. }
  4543. void OutputStream::writeByte (char byte)
  4544. {
  4545. write (&byte, 1);
  4546. }
  4547. void OutputStream::writeShort (short value)
  4548. {
  4549. const unsigned short v = ByteOrder::swapIfBigEndian ((unsigned short) value);
  4550. write (&v, 2);
  4551. }
  4552. void OutputStream::writeShortBigEndian (short value)
  4553. {
  4554. const unsigned short v = ByteOrder::swapIfLittleEndian ((unsigned short) value);
  4555. write (&v, 2);
  4556. }
  4557. void OutputStream::writeInt (int value)
  4558. {
  4559. const unsigned int v = ByteOrder::swapIfBigEndian ((unsigned int) value);
  4560. write (&v, 4);
  4561. }
  4562. void OutputStream::writeIntBigEndian (int value)
  4563. {
  4564. const unsigned int v = ByteOrder::swapIfLittleEndian ((unsigned int) value);
  4565. write (&v, 4);
  4566. }
  4567. void OutputStream::writeCompressedInt (int value)
  4568. {
  4569. unsigned int un = (value < 0) ? (unsigned int) -value
  4570. : (unsigned int) value;
  4571. uint8 data[5];
  4572. int num = 0;
  4573. while (un > 0)
  4574. {
  4575. data[++num] = (uint8) un;
  4576. un >>= 8;
  4577. }
  4578. data[0] = (uint8) num;
  4579. if (value < 0)
  4580. data[0] |= 0x80;
  4581. write (data, num + 1);
  4582. }
  4583. void OutputStream::writeInt64 (int64 value)
  4584. {
  4585. const uint64 v = ByteOrder::swapIfBigEndian ((uint64) value);
  4586. write (&v, 8);
  4587. }
  4588. void OutputStream::writeInt64BigEndian (int64 value)
  4589. {
  4590. const uint64 v = ByteOrder::swapIfLittleEndian ((uint64) value);
  4591. write (&v, 8);
  4592. }
  4593. void OutputStream::writeFloat (float value)
  4594. {
  4595. union { int asInt; float asFloat; } n;
  4596. n.asFloat = value;
  4597. writeInt (n.asInt);
  4598. }
  4599. void OutputStream::writeFloatBigEndian (float value)
  4600. {
  4601. union { int asInt; float asFloat; } n;
  4602. n.asFloat = value;
  4603. writeIntBigEndian (n.asInt);
  4604. }
  4605. void OutputStream::writeDouble (double value)
  4606. {
  4607. union { int64 asInt; double asDouble; } n;
  4608. n.asDouble = value;
  4609. writeInt64 (n.asInt);
  4610. }
  4611. void OutputStream::writeDoubleBigEndian (double value)
  4612. {
  4613. union { int64 asInt; double asDouble; } n;
  4614. n.asDouble = value;
  4615. writeInt64BigEndian (n.asInt);
  4616. }
  4617. void OutputStream::writeString (const String& text)
  4618. {
  4619. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  4620. // if lots of large, persistent strings were to be written to streams).
  4621. const int numBytes = text.getNumBytesAsUTF8() + 1;
  4622. HeapBlock<char> temp (numBytes);
  4623. text.copyToUTF8 (temp, numBytes);
  4624. write (temp, numBytes);
  4625. }
  4626. void OutputStream::writeText (const String& text, const bool asUnicode,
  4627. const bool writeUnicodeHeaderBytes)
  4628. {
  4629. if (asUnicode)
  4630. {
  4631. if (writeUnicodeHeaderBytes)
  4632. write ("\x0ff\x0fe", 2);
  4633. const juce_wchar* src = text;
  4634. bool lastCharWasReturn = false;
  4635. while (*src != 0)
  4636. {
  4637. if (*src == L'\n' && ! lastCharWasReturn)
  4638. writeShort ((short) L'\r');
  4639. lastCharWasReturn = (*src == L'\r');
  4640. writeShort ((short) *src++);
  4641. }
  4642. }
  4643. else
  4644. {
  4645. const char* src = text.toUTF8();
  4646. const char* t = src;
  4647. for (;;)
  4648. {
  4649. if (*t == '\n')
  4650. {
  4651. if (t > src)
  4652. write (src, (int) (t - src));
  4653. write ("\r\n", 2);
  4654. src = t + 1;
  4655. }
  4656. else if (*t == '\r')
  4657. {
  4658. if (t[1] == '\n')
  4659. ++t;
  4660. }
  4661. else if (*t == 0)
  4662. {
  4663. if (t > src)
  4664. write (src, (int) (t - src));
  4665. break;
  4666. }
  4667. ++t;
  4668. }
  4669. }
  4670. }
  4671. int OutputStream::writeFromInputStream (InputStream& source, int64 numBytesToWrite)
  4672. {
  4673. if (numBytesToWrite < 0)
  4674. numBytesToWrite = std::numeric_limits<int64>::max();
  4675. int numWritten = 0;
  4676. while (numBytesToWrite > 0 && ! source.isExhausted())
  4677. {
  4678. char buffer [8192];
  4679. const int num = source.read (buffer, (int) jmin (numBytesToWrite, (int64) sizeof (buffer)));
  4680. if (num <= 0)
  4681. break;
  4682. write (buffer, num);
  4683. numBytesToWrite -= num;
  4684. numWritten += num;
  4685. }
  4686. return numWritten;
  4687. }
  4688. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const int number)
  4689. {
  4690. return stream << String (number);
  4691. }
  4692. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const double number)
  4693. {
  4694. return stream << String (number);
  4695. }
  4696. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char character)
  4697. {
  4698. stream.writeByte (character);
  4699. return stream;
  4700. }
  4701. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* const text)
  4702. {
  4703. stream.write (text, (int) strlen (text));
  4704. return stream;
  4705. }
  4706. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data)
  4707. {
  4708. stream.write (data.getData(), (int) data.getSize());
  4709. return stream;
  4710. }
  4711. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead)
  4712. {
  4713. const ScopedPointer<FileInputStream> in (fileToRead.createInputStream());
  4714. if (in != 0)
  4715. stream.writeFromInputStream (*in, -1);
  4716. return stream;
  4717. }
  4718. END_JUCE_NAMESPACE
  4719. /*** End of inlined file: juce_OutputStream.cpp ***/
  4720. /*** Start of inlined file: juce_DirectoryIterator.cpp ***/
  4721. BEGIN_JUCE_NAMESPACE
  4722. DirectoryIterator::DirectoryIterator (const File& directory,
  4723. bool isRecursive_,
  4724. const String& wildCard_,
  4725. const int whatToLookFor_)
  4726. : fileFinder (directory, isRecursive_ ? "*" : wildCard_),
  4727. wildCard (wildCard_),
  4728. path (File::addTrailingSeparator (directory.getFullPathName())),
  4729. index (-1),
  4730. totalNumFiles (-1),
  4731. whatToLookFor (whatToLookFor_),
  4732. isRecursive (isRecursive_)
  4733. {
  4734. // you have to specify the type of files you're looking for!
  4735. jassert ((whatToLookFor_ & (File::findFiles | File::findDirectories)) != 0);
  4736. jassert (whatToLookFor_ > 0 && whatToLookFor_ <= 7);
  4737. }
  4738. DirectoryIterator::~DirectoryIterator()
  4739. {
  4740. }
  4741. bool DirectoryIterator::next()
  4742. {
  4743. return next (0, 0, 0, 0, 0, 0);
  4744. }
  4745. bool DirectoryIterator::next (bool* const isDirResult, bool* const isHiddenResult, int64* const fileSize,
  4746. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  4747. {
  4748. if (subIterator != 0)
  4749. {
  4750. if (subIterator->next (isDirResult, isHiddenResult, fileSize, modTime, creationTime, isReadOnly))
  4751. return true;
  4752. subIterator = 0;
  4753. }
  4754. String filename;
  4755. bool isDirectory, isHidden;
  4756. while (fileFinder.next (filename, &isDirectory, &isHidden, fileSize, modTime, creationTime, isReadOnly))
  4757. {
  4758. ++index;
  4759. if (! filename.containsOnly ("."))
  4760. {
  4761. const File fileFound (path + filename, 0);
  4762. bool matches = false;
  4763. if (isDirectory)
  4764. {
  4765. if (isRecursive && ((whatToLookFor & File::ignoreHiddenFiles) == 0 || ! isHidden))
  4766. subIterator = new DirectoryIterator (fileFound, true, wildCard, whatToLookFor);
  4767. matches = (whatToLookFor & File::findDirectories) != 0;
  4768. }
  4769. else
  4770. {
  4771. matches = (whatToLookFor & File::findFiles) != 0;
  4772. }
  4773. // if recursive, we're not relying on the OS iterator to do the wildcard match, so do it now..
  4774. if (matches && isRecursive)
  4775. matches = filename.matchesWildcard (wildCard, ! File::areFileNamesCaseSensitive());
  4776. if (matches && (whatToLookFor & File::ignoreHiddenFiles) != 0)
  4777. matches = ! isHidden;
  4778. if (matches)
  4779. {
  4780. currentFile = fileFound;
  4781. if (isHiddenResult != 0) *isHiddenResult = isHidden;
  4782. if (isDirResult != 0) *isDirResult = isDirectory;
  4783. return true;
  4784. }
  4785. else if (subIterator != 0)
  4786. {
  4787. return next();
  4788. }
  4789. }
  4790. }
  4791. return false;
  4792. }
  4793. const File DirectoryIterator::getFile() const
  4794. {
  4795. if (subIterator != 0)
  4796. return subIterator->getFile();
  4797. return currentFile;
  4798. }
  4799. float DirectoryIterator::getEstimatedProgress() const
  4800. {
  4801. if (totalNumFiles < 0)
  4802. totalNumFiles = File (path).getNumberOfChildFiles (File::findFilesAndDirectories);
  4803. if (totalNumFiles <= 0)
  4804. return 0.0f;
  4805. const float detailedIndex = (subIterator != 0) ? index + subIterator->getEstimatedProgress()
  4806. : (float) index;
  4807. return detailedIndex / totalNumFiles;
  4808. }
  4809. END_JUCE_NAMESPACE
  4810. /*** End of inlined file: juce_DirectoryIterator.cpp ***/
  4811. /*** Start of inlined file: juce_File.cpp ***/
  4812. #if ! JUCE_WINDOWS
  4813. #include <pwd.h>
  4814. #endif
  4815. BEGIN_JUCE_NAMESPACE
  4816. File::File (const String& fullPathName)
  4817. : fullPath (parseAbsolutePath (fullPathName))
  4818. {
  4819. }
  4820. File::File (const String& path, int)
  4821. : fullPath (path)
  4822. {
  4823. }
  4824. const File File::createFileWithoutCheckingPath (const String& path)
  4825. {
  4826. return File (path, 0);
  4827. }
  4828. File::File (const File& other)
  4829. : fullPath (other.fullPath)
  4830. {
  4831. }
  4832. File& File::operator= (const String& newPath)
  4833. {
  4834. fullPath = parseAbsolutePath (newPath);
  4835. return *this;
  4836. }
  4837. File& File::operator= (const File& other)
  4838. {
  4839. fullPath = other.fullPath;
  4840. return *this;
  4841. }
  4842. const File File::nonexistent;
  4843. const String File::parseAbsolutePath (const String& p)
  4844. {
  4845. if (p.isEmpty())
  4846. return String::empty;
  4847. #if JUCE_WINDOWS
  4848. // Windows..
  4849. String path (p.replaceCharacter ('/', '\\'));
  4850. if (path.startsWithChar (File::separator))
  4851. {
  4852. if (path[1] != File::separator)
  4853. {
  4854. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  4855. If you're trying to parse a string that may be either a relative path or an absolute path,
  4856. you MUST provide a context against which the partial path can be evaluated - you can do
  4857. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  4858. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  4859. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  4860. */
  4861. jassertfalse;
  4862. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  4863. }
  4864. }
  4865. else if (! path.containsChar (':'))
  4866. {
  4867. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  4868. If you're trying to parse a string that may be either a relative path or an absolute path,
  4869. you MUST provide a context against which the partial path can be evaluated - you can do
  4870. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  4871. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  4872. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  4873. */
  4874. jassertfalse;
  4875. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  4876. }
  4877. #else
  4878. // Mac or Linux..
  4879. String path (p.replaceCharacter ('\\', '/'));
  4880. if (path.startsWithChar ('~'))
  4881. {
  4882. if (path[1] == File::separator || path[1] == 0)
  4883. {
  4884. // expand a name of the form "~/abc"
  4885. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  4886. + path.substring (1);
  4887. }
  4888. else
  4889. {
  4890. // expand a name of type "~dave/abc"
  4891. const String userName (path.substring (1).upToFirstOccurrenceOf ("/", false, false));
  4892. struct passwd* const pw = getpwnam (userName.toUTF8());
  4893. if (pw != 0)
  4894. path = addTrailingSeparator (pw->pw_dir) + path.fromFirstOccurrenceOf ("/", false, false);
  4895. }
  4896. }
  4897. else if (! path.startsWithChar (File::separator))
  4898. {
  4899. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  4900. If you're trying to parse a string that may be either a relative path or an absolute path,
  4901. you MUST provide a context against which the partial path can be evaluated - you can do
  4902. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  4903. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  4904. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  4905. */
  4906. jassert (path.startsWith ("./") || path.startsWith ("../")); // (assume that a path "./xyz" is deliberately intended to be relative to the CWD)
  4907. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  4908. }
  4909. #endif
  4910. return path.trimCharactersAtEnd (separatorString);
  4911. }
  4912. const String File::addTrailingSeparator (const String& path)
  4913. {
  4914. return path.endsWithChar (File::separator) ? path
  4915. : path + File::separator;
  4916. }
  4917. #if JUCE_LINUX
  4918. #define NAMES_ARE_CASE_SENSITIVE 1
  4919. #endif
  4920. bool File::areFileNamesCaseSensitive()
  4921. {
  4922. #if NAMES_ARE_CASE_SENSITIVE
  4923. return true;
  4924. #else
  4925. return false;
  4926. #endif
  4927. }
  4928. bool File::operator== (const File& other) const
  4929. {
  4930. #if NAMES_ARE_CASE_SENSITIVE
  4931. return fullPath == other.fullPath;
  4932. #else
  4933. return fullPath.equalsIgnoreCase (other.fullPath);
  4934. #endif
  4935. }
  4936. bool File::operator!= (const File& other) const
  4937. {
  4938. return ! operator== (other);
  4939. }
  4940. bool File::operator< (const File& other) const
  4941. {
  4942. #if NAMES_ARE_CASE_SENSITIVE
  4943. return fullPath < other.fullPath;
  4944. #else
  4945. return fullPath.compareIgnoreCase (other.fullPath) < 0;
  4946. #endif
  4947. }
  4948. bool File::operator> (const File& other) const
  4949. {
  4950. #if NAMES_ARE_CASE_SENSITIVE
  4951. return fullPath > other.fullPath;
  4952. #else
  4953. return fullPath.compareIgnoreCase (other.fullPath) > 0;
  4954. #endif
  4955. }
  4956. bool File::setReadOnly (const bool shouldBeReadOnly,
  4957. const bool applyRecursively) const
  4958. {
  4959. bool worked = true;
  4960. if (applyRecursively && isDirectory())
  4961. {
  4962. Array <File> subFiles;
  4963. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  4964. for (int i = subFiles.size(); --i >= 0;)
  4965. worked = subFiles.getReference(i).setReadOnly (shouldBeReadOnly, true) && worked;
  4966. }
  4967. return setFileReadOnlyInternal (shouldBeReadOnly) && worked;
  4968. }
  4969. bool File::deleteRecursively() const
  4970. {
  4971. bool worked = true;
  4972. if (isDirectory())
  4973. {
  4974. Array<File> subFiles;
  4975. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  4976. for (int i = subFiles.size(); --i >= 0;)
  4977. worked = subFiles.getReference(i).deleteRecursively() && worked;
  4978. }
  4979. return deleteFile() && worked;
  4980. }
  4981. bool File::moveFileTo (const File& newFile) const
  4982. {
  4983. if (newFile.fullPath == fullPath)
  4984. return true;
  4985. #if ! NAMES_ARE_CASE_SENSITIVE
  4986. if (*this != newFile)
  4987. #endif
  4988. if (! newFile.deleteFile())
  4989. return false;
  4990. return moveInternal (newFile);
  4991. }
  4992. bool File::copyFileTo (const File& newFile) const
  4993. {
  4994. return (*this == newFile)
  4995. || (exists() && newFile.deleteFile() && copyInternal (newFile));
  4996. }
  4997. bool File::copyDirectoryTo (const File& newDirectory) const
  4998. {
  4999. if (isDirectory() && newDirectory.createDirectory())
  5000. {
  5001. Array<File> subFiles;
  5002. findChildFiles (subFiles, File::findFiles, false);
  5003. int i;
  5004. for (i = 0; i < subFiles.size(); ++i)
  5005. if (! subFiles.getReference(i).copyFileTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5006. return false;
  5007. subFiles.clear();
  5008. findChildFiles (subFiles, File::findDirectories, false);
  5009. for (i = 0; i < subFiles.size(); ++i)
  5010. if (! subFiles.getReference(i).copyDirectoryTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5011. return false;
  5012. return true;
  5013. }
  5014. return false;
  5015. }
  5016. const String File::getPathUpToLastSlash() const
  5017. {
  5018. const int lastSlash = fullPath.lastIndexOfChar (separator);
  5019. if (lastSlash > 0)
  5020. return fullPath.substring (0, lastSlash);
  5021. else if (lastSlash == 0)
  5022. return separatorString;
  5023. else
  5024. return fullPath;
  5025. }
  5026. const File File::getParentDirectory() const
  5027. {
  5028. return File (getPathUpToLastSlash(), (int) 0);
  5029. }
  5030. const String File::getFileName() const
  5031. {
  5032. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  5033. }
  5034. int File::hashCode() const
  5035. {
  5036. return fullPath.hashCode();
  5037. }
  5038. int64 File::hashCode64() const
  5039. {
  5040. return fullPath.hashCode64();
  5041. }
  5042. const String File::getFileNameWithoutExtension() const
  5043. {
  5044. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  5045. const int lastDot = fullPath.lastIndexOfChar ('.');
  5046. if (lastDot > lastSlash)
  5047. return fullPath.substring (lastSlash, lastDot);
  5048. else
  5049. return fullPath.substring (lastSlash);
  5050. }
  5051. bool File::isAChildOf (const File& potentialParent) const
  5052. {
  5053. if (potentialParent == File::nonexistent)
  5054. return false;
  5055. const String ourPath (getPathUpToLastSlash());
  5056. #if NAMES_ARE_CASE_SENSITIVE
  5057. if (potentialParent.fullPath == ourPath)
  5058. #else
  5059. if (potentialParent.fullPath.equalsIgnoreCase (ourPath))
  5060. #endif
  5061. {
  5062. return true;
  5063. }
  5064. else if (potentialParent.fullPath.length() >= ourPath.length())
  5065. {
  5066. return false;
  5067. }
  5068. else
  5069. {
  5070. return getParentDirectory().isAChildOf (potentialParent);
  5071. }
  5072. }
  5073. bool File::isAbsolutePath (const String& path)
  5074. {
  5075. return path.startsWithChar ('/') || path.startsWithChar ('\\')
  5076. #if JUCE_WINDOWS
  5077. || (path.isNotEmpty() && path[1] == ':');
  5078. #else
  5079. || path.startsWithChar ('~');
  5080. #endif
  5081. }
  5082. const File File::getChildFile (String relativePath) const
  5083. {
  5084. if (isAbsolutePath (relativePath))
  5085. {
  5086. // the path is really absolute..
  5087. return File (relativePath);
  5088. }
  5089. else
  5090. {
  5091. // it's relative, so remove any ../ or ./ bits at the start.
  5092. String path (fullPath);
  5093. if (relativePath[0] == '.')
  5094. {
  5095. #if JUCE_WINDOWS
  5096. relativePath = relativePath.replaceCharacter ('/', '\\').trimStart();
  5097. #else
  5098. relativePath = relativePath.replaceCharacter ('\\', '/').trimStart();
  5099. #endif
  5100. while (relativePath[0] == '.')
  5101. {
  5102. if (relativePath[1] == '.')
  5103. {
  5104. if (relativePath [2] == 0 || relativePath[2] == separator)
  5105. {
  5106. const int lastSlash = path.lastIndexOfChar (separator);
  5107. if (lastSlash >= 0)
  5108. path = path.substring (0, lastSlash);
  5109. relativePath = relativePath.substring (3);
  5110. }
  5111. else
  5112. {
  5113. break;
  5114. }
  5115. }
  5116. else if (relativePath[1] == separator)
  5117. {
  5118. relativePath = relativePath.substring (2);
  5119. }
  5120. else
  5121. {
  5122. break;
  5123. }
  5124. }
  5125. }
  5126. return File (addTrailingSeparator (path) + relativePath);
  5127. }
  5128. }
  5129. const File File::getSiblingFile (const String& fileName) const
  5130. {
  5131. return getParentDirectory().getChildFile (fileName);
  5132. }
  5133. const String File::descriptionOfSizeInBytes (const int64 bytes)
  5134. {
  5135. if (bytes == 1)
  5136. {
  5137. return "1 byte";
  5138. }
  5139. else if (bytes < 1024)
  5140. {
  5141. return String ((int) bytes) + " bytes";
  5142. }
  5143. else if (bytes < 1024 * 1024)
  5144. {
  5145. return String (bytes / 1024.0, 1) + " KB";
  5146. }
  5147. else if (bytes < 1024 * 1024 * 1024)
  5148. {
  5149. return String (bytes / (1024.0 * 1024.0), 1) + " MB";
  5150. }
  5151. else
  5152. {
  5153. return String (bytes / (1024.0 * 1024.0 * 1024.0), 1) + " GB";
  5154. }
  5155. }
  5156. bool File::create() const
  5157. {
  5158. if (exists())
  5159. return true;
  5160. {
  5161. const File parentDir (getParentDirectory());
  5162. if (parentDir == *this || ! parentDir.createDirectory())
  5163. return false;
  5164. FileOutputStream fo (*this, 8);
  5165. }
  5166. return exists();
  5167. }
  5168. bool File::createDirectory() const
  5169. {
  5170. if (! isDirectory())
  5171. {
  5172. const File parentDir (getParentDirectory());
  5173. if (parentDir == *this || ! parentDir.createDirectory())
  5174. return false;
  5175. createDirectoryInternal (fullPath.trimCharactersAtEnd (separatorString));
  5176. return isDirectory();
  5177. }
  5178. return true;
  5179. }
  5180. const Time File::getCreationTime() const
  5181. {
  5182. int64 m, a, c;
  5183. getFileTimesInternal (m, a, c);
  5184. return Time (c);
  5185. }
  5186. const Time File::getLastModificationTime() const
  5187. {
  5188. int64 m, a, c;
  5189. getFileTimesInternal (m, a, c);
  5190. return Time (m);
  5191. }
  5192. const Time File::getLastAccessTime() const
  5193. {
  5194. int64 m, a, c;
  5195. getFileTimesInternal (m, a, c);
  5196. return Time (a);
  5197. }
  5198. bool File::setLastModificationTime (const Time& t) const { return setFileTimesInternal (t.toMilliseconds(), 0, 0); }
  5199. bool File::setLastAccessTime (const Time& t) const { return setFileTimesInternal (0, t.toMilliseconds(), 0); }
  5200. bool File::setCreationTime (const Time& t) const { return setFileTimesInternal (0, 0, t.toMilliseconds()); }
  5201. bool File::loadFileAsData (MemoryBlock& destBlock) const
  5202. {
  5203. if (! existsAsFile())
  5204. return false;
  5205. FileInputStream in (*this);
  5206. return getSize() == in.readIntoMemoryBlock (destBlock);
  5207. }
  5208. const String File::loadFileAsString() const
  5209. {
  5210. if (! existsAsFile())
  5211. return String::empty;
  5212. FileInputStream in (*this);
  5213. return in.readEntireStreamAsString();
  5214. }
  5215. bool File::fileTypeMatches (const int whatToLookFor, const bool isDir, const bool isHidden)
  5216. {
  5217. return (whatToLookFor & (isDir ? findDirectories
  5218. : findFiles)) != 0
  5219. && ((! isHidden) || (whatToLookFor & File::ignoreHiddenFiles) == 0);
  5220. }
  5221. int File::findChildFiles (Array<File>& results,
  5222. const int whatToLookFor,
  5223. const bool searchRecursively,
  5224. const String& wildCardPattern) const
  5225. {
  5226. // you have to specify the type of files you're looking for!
  5227. jassert ((whatToLookFor & (findFiles | findDirectories)) != 0);
  5228. int total = 0;
  5229. if (isDirectory())
  5230. {
  5231. // find child files or directories in this directory first..
  5232. String path (addTrailingSeparator (fullPath)), filename;
  5233. bool itemIsDirectory, itemIsHidden;
  5234. DirectoryIterator::NativeIterator i (path, wildCardPattern);
  5235. while (i.next (filename, &itemIsDirectory, &itemIsHidden, 0, 0, 0, 0))
  5236. {
  5237. if (! filename.containsOnly ("."))
  5238. {
  5239. const File fileFound (path + filename, 0);
  5240. if (fileTypeMatches (whatToLookFor, itemIsDirectory, itemIsHidden))
  5241. {
  5242. results.add (fileFound);
  5243. ++total;
  5244. }
  5245. if (searchRecursively && itemIsDirectory
  5246. && fileTypeMatches (whatToLookFor | findDirectories, true, itemIsHidden))
  5247. {
  5248. total += fileFound.findChildFiles (results, whatToLookFor, true, wildCardPattern);
  5249. }
  5250. }
  5251. }
  5252. }
  5253. return total;
  5254. }
  5255. int File::getNumberOfChildFiles (const int whatToLookFor,
  5256. const String& wildCardPattern) const
  5257. {
  5258. // you have to specify the type of files you're looking for!
  5259. jassert (whatToLookFor > 0 && whatToLookFor <= 3);
  5260. int count = 0;
  5261. if (isDirectory())
  5262. {
  5263. String filename;
  5264. bool itemIsDirectory, itemIsHidden;
  5265. DirectoryIterator::NativeIterator i (*this, wildCardPattern);
  5266. while (i.next (filename, &itemIsDirectory, &itemIsHidden, 0, 0, 0, 0))
  5267. if (fileTypeMatches (whatToLookFor, itemIsDirectory, itemIsHidden)
  5268. && ! filename.containsOnly ("."))
  5269. ++count;
  5270. }
  5271. else
  5272. {
  5273. // trying to search for files inside a non-directory?
  5274. jassertfalse;
  5275. }
  5276. return count;
  5277. }
  5278. bool File::containsSubDirectories() const
  5279. {
  5280. if (isDirectory())
  5281. {
  5282. String filename;
  5283. bool itemIsDirectory;
  5284. DirectoryIterator::NativeIterator i (*this, "*");
  5285. while (i.next (filename, &itemIsDirectory, 0, 0, 0, 0, 0))
  5286. if (itemIsDirectory)
  5287. return true;
  5288. }
  5289. return false;
  5290. }
  5291. const File File::getNonexistentChildFile (const String& prefix_,
  5292. const String& suffix,
  5293. bool putNumbersInBrackets) const
  5294. {
  5295. File f (getChildFile (prefix_ + suffix));
  5296. if (f.exists())
  5297. {
  5298. int num = 2;
  5299. String prefix (prefix_);
  5300. // remove any bracketed numbers that may already be on the end..
  5301. if (prefix.trim().endsWithChar (')'))
  5302. {
  5303. putNumbersInBrackets = true;
  5304. const int openBracks = prefix.lastIndexOfChar ('(');
  5305. const int closeBracks = prefix.lastIndexOfChar (')');
  5306. if (openBracks > 0
  5307. && closeBracks > openBracks
  5308. && prefix.substring (openBracks + 1, closeBracks).containsOnly ("0123456789"))
  5309. {
  5310. num = prefix.substring (openBracks + 1, closeBracks).getIntValue() + 1;
  5311. prefix = prefix.substring (0, openBracks);
  5312. }
  5313. }
  5314. // also use brackets if it ends in a digit.
  5315. putNumbersInBrackets = putNumbersInBrackets
  5316. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  5317. do
  5318. {
  5319. if (putNumbersInBrackets)
  5320. f = getChildFile (prefix + '(' + String (num++) + ')' + suffix);
  5321. else
  5322. f = getChildFile (prefix + String (num++) + suffix);
  5323. } while (f.exists());
  5324. }
  5325. return f;
  5326. }
  5327. const File File::getNonexistentSibling (const bool putNumbersInBrackets) const
  5328. {
  5329. if (exists())
  5330. {
  5331. return getParentDirectory()
  5332. .getNonexistentChildFile (getFileNameWithoutExtension(),
  5333. getFileExtension(),
  5334. putNumbersInBrackets);
  5335. }
  5336. else
  5337. {
  5338. return *this;
  5339. }
  5340. }
  5341. const String File::getFileExtension() const
  5342. {
  5343. String ext;
  5344. if (! isDirectory())
  5345. {
  5346. const int indexOfDot = fullPath.lastIndexOfChar ('.');
  5347. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  5348. ext = fullPath.substring (indexOfDot);
  5349. }
  5350. return ext;
  5351. }
  5352. bool File::hasFileExtension (const String& possibleSuffix) const
  5353. {
  5354. if (possibleSuffix.isEmpty())
  5355. return fullPath.lastIndexOfChar ('.') <= fullPath.lastIndexOfChar (separator);
  5356. const int semicolon = possibleSuffix.indexOfChar (0, ';');
  5357. if (semicolon >= 0)
  5358. {
  5359. return hasFileExtension (possibleSuffix.substring (0, semicolon).trimEnd())
  5360. || hasFileExtension (possibleSuffix.substring (semicolon + 1).trimStart());
  5361. }
  5362. else
  5363. {
  5364. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  5365. {
  5366. if (possibleSuffix.startsWithChar ('.'))
  5367. return true;
  5368. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  5369. if (dotPos >= 0)
  5370. return fullPath [dotPos] == '.';
  5371. }
  5372. }
  5373. return false;
  5374. }
  5375. const File File::withFileExtension (const String& newExtension) const
  5376. {
  5377. if (fullPath.isEmpty())
  5378. return File::nonexistent;
  5379. String filePart (getFileName());
  5380. int i = filePart.lastIndexOfChar ('.');
  5381. if (i >= 0)
  5382. filePart = filePart.substring (0, i);
  5383. if (newExtension.isNotEmpty() && ! newExtension.startsWithChar ('.'))
  5384. filePart << '.';
  5385. return getSiblingFile (filePart + newExtension);
  5386. }
  5387. bool File::startAsProcess (const String& parameters) const
  5388. {
  5389. return exists() && PlatformUtilities::openDocument (fullPath, parameters);
  5390. }
  5391. FileInputStream* File::createInputStream() const
  5392. {
  5393. if (existsAsFile())
  5394. return new FileInputStream (*this);
  5395. return 0;
  5396. }
  5397. FileOutputStream* File::createOutputStream (const int bufferSize) const
  5398. {
  5399. ScopedPointer <FileOutputStream> out (new FileOutputStream (*this, bufferSize));
  5400. if (out->failedToOpen())
  5401. return 0;
  5402. return out.release();
  5403. }
  5404. bool File::appendData (const void* const dataToAppend,
  5405. const int numberOfBytes) const
  5406. {
  5407. if (numberOfBytes > 0)
  5408. {
  5409. const ScopedPointer <FileOutputStream> out (createOutputStream());
  5410. if (out == 0)
  5411. return false;
  5412. out->write (dataToAppend, numberOfBytes);
  5413. }
  5414. return true;
  5415. }
  5416. bool File::replaceWithData (const void* const dataToWrite,
  5417. const int numberOfBytes) const
  5418. {
  5419. jassert (numberOfBytes >= 0); // a negative number of bytes??
  5420. if (numberOfBytes <= 0)
  5421. return deleteFile();
  5422. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  5423. tempFile.getFile().appendData (dataToWrite, numberOfBytes);
  5424. return tempFile.overwriteTargetFileWithTemporary();
  5425. }
  5426. bool File::appendText (const String& text,
  5427. const bool asUnicode,
  5428. const bool writeUnicodeHeaderBytes) const
  5429. {
  5430. const ScopedPointer <FileOutputStream> out (createOutputStream());
  5431. if (out != 0)
  5432. {
  5433. out->writeText (text, asUnicode, writeUnicodeHeaderBytes);
  5434. return true;
  5435. }
  5436. return false;
  5437. }
  5438. bool File::replaceWithText (const String& textToWrite,
  5439. const bool asUnicode,
  5440. const bool writeUnicodeHeaderBytes) const
  5441. {
  5442. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  5443. tempFile.getFile().appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes);
  5444. return tempFile.overwriteTargetFileWithTemporary();
  5445. }
  5446. bool File::hasIdenticalContentTo (const File& other) const
  5447. {
  5448. if (other == *this)
  5449. return true;
  5450. if (getSize() == other.getSize() && existsAsFile() && other.existsAsFile())
  5451. {
  5452. FileInputStream in1 (*this), in2 (other);
  5453. const int bufferSize = 4096;
  5454. HeapBlock <char> buffer1, buffer2;
  5455. buffer1.malloc (bufferSize);
  5456. buffer2.malloc (bufferSize);
  5457. for (;;)
  5458. {
  5459. const int num1 = in1.read (buffer1, bufferSize);
  5460. const int num2 = in2.read (buffer2, bufferSize);
  5461. if (num1 != num2)
  5462. break;
  5463. if (num1 <= 0)
  5464. return true;
  5465. if (memcmp (buffer1, buffer2, num1) != 0)
  5466. break;
  5467. }
  5468. }
  5469. return false;
  5470. }
  5471. const String File::createLegalPathName (const String& original)
  5472. {
  5473. String s (original);
  5474. String start;
  5475. if (s[1] == ':')
  5476. {
  5477. start = s.substring (0, 2);
  5478. s = s.substring (2);
  5479. }
  5480. return start + s.removeCharacters ("\"#@,;:<>*^|?")
  5481. .substring (0, 1024);
  5482. }
  5483. const String File::createLegalFileName (const String& original)
  5484. {
  5485. String s (original.removeCharacters ("\"#@,;:<>*^|?\\/"));
  5486. const int maxLength = 128; // only the length of the filename, not the whole path
  5487. const int len = s.length();
  5488. if (len > maxLength)
  5489. {
  5490. const int lastDot = s.lastIndexOfChar ('.');
  5491. if (lastDot > jmax (0, len - 12))
  5492. {
  5493. s = s.substring (0, maxLength - (len - lastDot))
  5494. + s.substring (lastDot);
  5495. }
  5496. else
  5497. {
  5498. s = s.substring (0, maxLength);
  5499. }
  5500. }
  5501. return s;
  5502. }
  5503. const String File::getRelativePathFrom (const File& dir) const
  5504. {
  5505. String thisPath (fullPath);
  5506. {
  5507. int len = thisPath.length();
  5508. while (--len >= 0 && thisPath [len] == File::separator)
  5509. thisPath [len] = 0;
  5510. }
  5511. String dirPath (addTrailingSeparator (dir.existsAsFile() ? dir.getParentDirectory().getFullPathName()
  5512. : dir.fullPath));
  5513. const int len = jmin (thisPath.length(), dirPath.length());
  5514. int commonBitLength = 0;
  5515. for (int i = 0; i < len; ++i)
  5516. {
  5517. #if NAMES_ARE_CASE_SENSITIVE
  5518. if (thisPath[i] != dirPath[i])
  5519. #else
  5520. if (CharacterFunctions::toLowerCase (thisPath[i])
  5521. != CharacterFunctions::toLowerCase (dirPath[i]))
  5522. #endif
  5523. {
  5524. break;
  5525. }
  5526. ++commonBitLength;
  5527. }
  5528. while (commonBitLength > 0 && thisPath [commonBitLength - 1] != File::separator)
  5529. --commonBitLength;
  5530. // if the only common bit is the root, then just return the full path..
  5531. if (commonBitLength <= 0
  5532. || (commonBitLength == 1 && thisPath [1] == File::separator))
  5533. return fullPath;
  5534. thisPath = thisPath.substring (commonBitLength);
  5535. dirPath = dirPath.substring (commonBitLength);
  5536. while (dirPath.isNotEmpty())
  5537. {
  5538. #if JUCE_WINDOWS
  5539. thisPath = "..\\" + thisPath;
  5540. #else
  5541. thisPath = "../" + thisPath;
  5542. #endif
  5543. const int sep = dirPath.indexOfChar (separator);
  5544. if (sep >= 0)
  5545. dirPath = dirPath.substring (sep + 1);
  5546. else
  5547. dirPath = String::empty;
  5548. }
  5549. return thisPath;
  5550. }
  5551. const File File::createTempFile (const String& fileNameEnding)
  5552. {
  5553. const File tempFile (getSpecialLocation (tempDirectory)
  5554. .getChildFile ("temp_" + String (Random::getSystemRandom().nextInt()))
  5555. .withFileExtension (fileNameEnding));
  5556. if (tempFile.exists())
  5557. return createTempFile (fileNameEnding);
  5558. else
  5559. return tempFile;
  5560. }
  5561. END_JUCE_NAMESPACE
  5562. /*** End of inlined file: juce_File.cpp ***/
  5563. /*** Start of inlined file: juce_FileInputStream.cpp ***/
  5564. BEGIN_JUCE_NAMESPACE
  5565. void* juce_fileOpen (const File& file, bool forWriting);
  5566. void juce_fileClose (void* handle);
  5567. int juce_fileRead (void* handle, void* buffer, int size);
  5568. int64 juce_fileSetPosition (void* handle, int64 pos);
  5569. FileInputStream::FileInputStream (const File& f)
  5570. : file (f),
  5571. currentPosition (0),
  5572. needToSeek (true)
  5573. {
  5574. totalSize = f.getSize();
  5575. fileHandle = juce_fileOpen (f, false);
  5576. }
  5577. FileInputStream::~FileInputStream()
  5578. {
  5579. juce_fileClose (fileHandle);
  5580. }
  5581. int64 FileInputStream::getTotalLength()
  5582. {
  5583. return totalSize;
  5584. }
  5585. int FileInputStream::read (void* buffer, int bytesToRead)
  5586. {
  5587. int num = 0;
  5588. if (needToSeek)
  5589. {
  5590. if (juce_fileSetPosition (fileHandle, currentPosition) < 0)
  5591. return 0;
  5592. needToSeek = false;
  5593. }
  5594. num = juce_fileRead (fileHandle, buffer, bytesToRead);
  5595. currentPosition += num;
  5596. return num;
  5597. }
  5598. bool FileInputStream::isExhausted()
  5599. {
  5600. return currentPosition >= totalSize;
  5601. }
  5602. int64 FileInputStream::getPosition()
  5603. {
  5604. return currentPosition;
  5605. }
  5606. bool FileInputStream::setPosition (int64 pos)
  5607. {
  5608. pos = jlimit ((int64) 0, totalSize, pos);
  5609. needToSeek |= (currentPosition != pos);
  5610. currentPosition = pos;
  5611. return true;
  5612. }
  5613. END_JUCE_NAMESPACE
  5614. /*** End of inlined file: juce_FileInputStream.cpp ***/
  5615. /*** Start of inlined file: juce_FileOutputStream.cpp ***/
  5616. BEGIN_JUCE_NAMESPACE
  5617. void* juce_fileOpen (const File& file, bool forWriting);
  5618. void juce_fileClose (void* handle);
  5619. int juce_fileWrite (void* handle, const void* buffer, int size);
  5620. int64 juce_fileSetPosition (void* handle, int64 pos);
  5621. FileOutputStream::FileOutputStream (const File& f,
  5622. const int bufferSize_)
  5623. : file (f),
  5624. bufferSize (bufferSize_),
  5625. bytesInBuffer (0)
  5626. {
  5627. fileHandle = juce_fileOpen (f, true);
  5628. if (fileHandle != 0)
  5629. {
  5630. currentPosition = getPositionInternal();
  5631. if (currentPosition < 0)
  5632. {
  5633. jassertfalse;
  5634. juce_fileClose (fileHandle);
  5635. fileHandle = 0;
  5636. }
  5637. }
  5638. buffer.malloc (jmax (bufferSize_, 16));
  5639. }
  5640. FileOutputStream::~FileOutputStream()
  5641. {
  5642. flush();
  5643. juce_fileClose (fileHandle);
  5644. }
  5645. int64 FileOutputStream::getPosition()
  5646. {
  5647. return currentPosition;
  5648. }
  5649. bool FileOutputStream::setPosition (int64 newPosition)
  5650. {
  5651. if (newPosition != currentPosition)
  5652. {
  5653. flush();
  5654. currentPosition = juce_fileSetPosition (fileHandle, newPosition);
  5655. }
  5656. return newPosition == currentPosition;
  5657. }
  5658. void FileOutputStream::flush()
  5659. {
  5660. if (bytesInBuffer > 0)
  5661. {
  5662. juce_fileWrite (fileHandle, buffer, bytesInBuffer);
  5663. bytesInBuffer = 0;
  5664. }
  5665. flushInternal();
  5666. }
  5667. bool FileOutputStream::write (const void* const src, const int numBytes)
  5668. {
  5669. if (bytesInBuffer + numBytes < bufferSize)
  5670. {
  5671. memcpy (buffer + bytesInBuffer, src, numBytes);
  5672. bytesInBuffer += numBytes;
  5673. currentPosition += numBytes;
  5674. }
  5675. else
  5676. {
  5677. if (bytesInBuffer > 0)
  5678. {
  5679. // flush the reservoir
  5680. const bool wroteOk = (juce_fileWrite (fileHandle, buffer, bytesInBuffer) == bytesInBuffer);
  5681. bytesInBuffer = 0;
  5682. if (! wroteOk)
  5683. return false;
  5684. }
  5685. if (numBytes < bufferSize)
  5686. {
  5687. memcpy (buffer + bytesInBuffer, src, numBytes);
  5688. bytesInBuffer += numBytes;
  5689. currentPosition += numBytes;
  5690. }
  5691. else
  5692. {
  5693. const int bytesWritten = juce_fileWrite (fileHandle, src, numBytes);
  5694. currentPosition += bytesWritten;
  5695. return bytesWritten == numBytes;
  5696. }
  5697. }
  5698. return true;
  5699. }
  5700. END_JUCE_NAMESPACE
  5701. /*** End of inlined file: juce_FileOutputStream.cpp ***/
  5702. /*** Start of inlined file: juce_FileSearchPath.cpp ***/
  5703. BEGIN_JUCE_NAMESPACE
  5704. FileSearchPath::FileSearchPath()
  5705. {
  5706. }
  5707. FileSearchPath::FileSearchPath (const String& path)
  5708. {
  5709. init (path);
  5710. }
  5711. FileSearchPath::FileSearchPath (const FileSearchPath& other)
  5712. : directories (other.directories)
  5713. {
  5714. }
  5715. FileSearchPath::~FileSearchPath()
  5716. {
  5717. }
  5718. FileSearchPath& FileSearchPath::operator= (const String& path)
  5719. {
  5720. init (path);
  5721. return *this;
  5722. }
  5723. void FileSearchPath::init (const String& path)
  5724. {
  5725. directories.clear();
  5726. directories.addTokens (path, ";", "\"");
  5727. directories.trim();
  5728. directories.removeEmptyStrings();
  5729. for (int i = directories.size(); --i >= 0;)
  5730. directories.set (i, directories[i].unquoted());
  5731. }
  5732. int FileSearchPath::getNumPaths() const
  5733. {
  5734. return directories.size();
  5735. }
  5736. const File FileSearchPath::operator[] (const int index) const
  5737. {
  5738. return File (directories [index]);
  5739. }
  5740. const String FileSearchPath::toString() const
  5741. {
  5742. StringArray directories2 (directories);
  5743. for (int i = directories2.size(); --i >= 0;)
  5744. if (directories2[i].containsChar (';'))
  5745. directories2.set (i, directories2[i].quoted());
  5746. return directories2.joinIntoString (";");
  5747. }
  5748. void FileSearchPath::add (const File& dir, const int insertIndex)
  5749. {
  5750. directories.insert (insertIndex, dir.getFullPathName());
  5751. }
  5752. void FileSearchPath::addIfNotAlreadyThere (const File& dir)
  5753. {
  5754. for (int i = 0; i < directories.size(); ++i)
  5755. if (File (directories[i]) == dir)
  5756. return;
  5757. add (dir);
  5758. }
  5759. void FileSearchPath::remove (const int index)
  5760. {
  5761. directories.remove (index);
  5762. }
  5763. void FileSearchPath::addPath (const FileSearchPath& other)
  5764. {
  5765. for (int i = 0; i < other.getNumPaths(); ++i)
  5766. addIfNotAlreadyThere (other[i]);
  5767. }
  5768. void FileSearchPath::removeRedundantPaths()
  5769. {
  5770. for (int i = directories.size(); --i >= 0;)
  5771. {
  5772. const File d1 (directories[i]);
  5773. for (int j = directories.size(); --j >= 0;)
  5774. {
  5775. const File d2 (directories[j]);
  5776. if ((i != j) && (d1.isAChildOf (d2) || d1 == d2))
  5777. {
  5778. directories.remove (i);
  5779. break;
  5780. }
  5781. }
  5782. }
  5783. }
  5784. void FileSearchPath::removeNonExistentPaths()
  5785. {
  5786. for (int i = directories.size(); --i >= 0;)
  5787. if (! File (directories[i]).isDirectory())
  5788. directories.remove (i);
  5789. }
  5790. int FileSearchPath::findChildFiles (Array<File>& results,
  5791. const int whatToLookFor,
  5792. const bool searchRecursively,
  5793. const String& wildCardPattern) const
  5794. {
  5795. int total = 0;
  5796. for (int i = 0; i < directories.size(); ++i)
  5797. total += operator[] (i).findChildFiles (results,
  5798. whatToLookFor,
  5799. searchRecursively,
  5800. wildCardPattern);
  5801. return total;
  5802. }
  5803. bool FileSearchPath::isFileInPath (const File& fileToCheck,
  5804. const bool checkRecursively) const
  5805. {
  5806. for (int i = directories.size(); --i >= 0;)
  5807. {
  5808. const File d (directories[i]);
  5809. if (checkRecursively)
  5810. {
  5811. if (fileToCheck.isAChildOf (d))
  5812. return true;
  5813. }
  5814. else
  5815. {
  5816. if (fileToCheck.getParentDirectory() == d)
  5817. return true;
  5818. }
  5819. }
  5820. return false;
  5821. }
  5822. END_JUCE_NAMESPACE
  5823. /*** End of inlined file: juce_FileSearchPath.cpp ***/
  5824. /*** Start of inlined file: juce_NamedPipe.cpp ***/
  5825. BEGIN_JUCE_NAMESPACE
  5826. NamedPipe::NamedPipe()
  5827. : internal (0)
  5828. {
  5829. }
  5830. NamedPipe::~NamedPipe()
  5831. {
  5832. close();
  5833. }
  5834. bool NamedPipe::openExisting (const String& pipeName)
  5835. {
  5836. currentPipeName = pipeName;
  5837. return openInternal (pipeName, false);
  5838. }
  5839. bool NamedPipe::createNewPipe (const String& pipeName)
  5840. {
  5841. currentPipeName = pipeName;
  5842. return openInternal (pipeName, true);
  5843. }
  5844. bool NamedPipe::isOpen() const
  5845. {
  5846. return internal != 0;
  5847. }
  5848. const String NamedPipe::getName() const
  5849. {
  5850. return currentPipeName;
  5851. }
  5852. // other methods for this class are implemented in the platform-specific files
  5853. END_JUCE_NAMESPACE
  5854. /*** End of inlined file: juce_NamedPipe.cpp ***/
  5855. /*** Start of inlined file: juce_TemporaryFile.cpp ***/
  5856. BEGIN_JUCE_NAMESPACE
  5857. TemporaryFile::TemporaryFile (const String& suffix, const int optionFlags)
  5858. {
  5859. createTempFile (File::getSpecialLocation (File::tempDirectory),
  5860. "temp_" + String (Random::getSystemRandom().nextInt()),
  5861. suffix,
  5862. optionFlags);
  5863. }
  5864. TemporaryFile::TemporaryFile (const File& targetFile_, const int optionFlags)
  5865. : targetFile (targetFile_)
  5866. {
  5867. // If you use this constructor, you need to give it a valid target file!
  5868. jassert (targetFile != File::nonexistent);
  5869. createTempFile (targetFile.getParentDirectory(),
  5870. targetFile.getFileNameWithoutExtension() + "_temp" + String (Random::getSystemRandom().nextInt()),
  5871. targetFile.getFileExtension(),
  5872. optionFlags);
  5873. }
  5874. void TemporaryFile::createTempFile (const File& parentDirectory, String name,
  5875. const String& suffix, const int optionFlags)
  5876. {
  5877. if ((optionFlags & useHiddenFile) != 0)
  5878. name = "." + name;
  5879. temporaryFile = parentDirectory.getNonexistentChildFile (name, suffix, (optionFlags & putNumbersInBrackets) != 0);
  5880. }
  5881. TemporaryFile::~TemporaryFile()
  5882. {
  5883. // Have a few attempts at deleting the file before giving up..
  5884. for (int i = 5; --i >= 0;)
  5885. {
  5886. if (temporaryFile.deleteFile())
  5887. return;
  5888. Thread::sleep (50);
  5889. }
  5890. // Failed to delete our temporary file! Check that you've deleted all the
  5891. // file output streams that were using it!
  5892. jassertfalse;
  5893. }
  5894. bool TemporaryFile::overwriteTargetFileWithTemporary() const
  5895. {
  5896. // This method only works if you created this object with the constructor
  5897. // that takes a target file!
  5898. jassert (targetFile != File::nonexistent);
  5899. if (temporaryFile.exists())
  5900. {
  5901. // Have a few attempts at overwriting the file before giving up..
  5902. for (int i = 5; --i >= 0;)
  5903. {
  5904. if (temporaryFile.moveFileTo (targetFile))
  5905. return true;
  5906. Thread::sleep (100);
  5907. }
  5908. }
  5909. else
  5910. {
  5911. // There's no temporary file to use. If your write failed, you should
  5912. // probably check, and not bother calling this method.
  5913. jassertfalse;
  5914. }
  5915. return false;
  5916. }
  5917. END_JUCE_NAMESPACE
  5918. /*** End of inlined file: juce_TemporaryFile.cpp ***/
  5919. /*** Start of inlined file: juce_Socket.cpp ***/
  5920. #if JUCE_WINDOWS
  5921. #include <winsock2.h>
  5922. #if JUCE_MSVC
  5923. #pragma warning (push)
  5924. #pragma warning (disable : 4127 4389 4018)
  5925. #endif
  5926. #else
  5927. #if JUCE_LINUX
  5928. #include <sys/types.h>
  5929. #include <sys/socket.h>
  5930. #include <sys/errno.h>
  5931. #include <unistd.h>
  5932. #include <netinet/in.h>
  5933. #elif (MACOSX_DEPLOYMENT_TARGET <= MAC_OS_X_VERSION_10_4) && ! JUCE_IPHONE
  5934. #include <CoreServices/CoreServices.h>
  5935. #endif
  5936. #include <fcntl.h>
  5937. #include <netdb.h>
  5938. #include <arpa/inet.h>
  5939. #include <netinet/tcp.h>
  5940. #endif
  5941. BEGIN_JUCE_NAMESPACE
  5942. #if defined (JUCE_LINUX) || defined (JUCE_MAC) || defined (JUCE_IPHONE)
  5943. typedef socklen_t juce_socklen_t;
  5944. #else
  5945. typedef int juce_socklen_t;
  5946. #endif
  5947. #if JUCE_WINDOWS
  5948. namespace SocketHelpers
  5949. {
  5950. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  5951. static juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib = 0;
  5952. }
  5953. static void initWin32Sockets()
  5954. {
  5955. static CriticalSection lock;
  5956. const ScopedLock sl (lock);
  5957. if (SocketHelpers::juce_CloseWin32SocketLib == 0)
  5958. {
  5959. WSADATA wsaData;
  5960. const WORD wVersionRequested = MAKEWORD (1, 1);
  5961. WSAStartup (wVersionRequested, &wsaData);
  5962. SocketHelpers::juce_CloseWin32SocketLib = &WSACleanup;
  5963. }
  5964. }
  5965. void juce_shutdownWin32Sockets()
  5966. {
  5967. if (SocketHelpers::juce_CloseWin32SocketLib != 0)
  5968. (*SocketHelpers::juce_CloseWin32SocketLib)();
  5969. }
  5970. #endif
  5971. namespace SocketHelpers
  5972. {
  5973. static bool resetSocketOptions (const int handle, const bool isDatagram, const bool allowBroadcast) throw()
  5974. {
  5975. const int sndBufSize = 65536;
  5976. const int rcvBufSize = 65536;
  5977. const int one = 1;
  5978. return handle > 0
  5979. && setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (rcvBufSize)) == 0
  5980. && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (sndBufSize)) == 0
  5981. && (isDatagram ? ((! allowBroadcast) || setsockopt (handle, SOL_SOCKET, SO_BROADCAST, (const char*) &one, sizeof (one)) == 0)
  5982. : (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (one)) == 0));
  5983. }
  5984. static bool bindSocketToPort (const int handle, const int port) throw()
  5985. {
  5986. if (handle <= 0 || port <= 0)
  5987. return false;
  5988. struct sockaddr_in servTmpAddr;
  5989. zerostruct (servTmpAddr);
  5990. servTmpAddr.sin_family = PF_INET;
  5991. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  5992. servTmpAddr.sin_port = htons ((uint16) port);
  5993. return bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) >= 0;
  5994. }
  5995. static int readSocket (const int handle,
  5996. void* const destBuffer, const int maxBytesToRead,
  5997. bool volatile& connected,
  5998. const bool blockUntilSpecifiedAmountHasArrived) throw()
  5999. {
  6000. int bytesRead = 0;
  6001. while (bytesRead < maxBytesToRead)
  6002. {
  6003. int bytesThisTime;
  6004. #if JUCE_WINDOWS
  6005. bytesThisTime = recv (handle, ((char*) destBuffer) + bytesRead, maxBytesToRead - bytesRead, 0);
  6006. #else
  6007. while ((bytesThisTime = (int) ::read (handle, ((char*) destBuffer) + bytesRead, maxBytesToRead - bytesRead)) < 0
  6008. && errno == EINTR
  6009. && connected)
  6010. {
  6011. }
  6012. #endif
  6013. if (bytesThisTime <= 0 || ! connected)
  6014. {
  6015. if (bytesRead == 0)
  6016. bytesRead = -1;
  6017. break;
  6018. }
  6019. bytesRead += bytesThisTime;
  6020. if (! blockUntilSpecifiedAmountHasArrived)
  6021. break;
  6022. }
  6023. return bytesRead;
  6024. }
  6025. static int waitForReadiness (const int handle, const bool forReading,
  6026. const int timeoutMsecs) throw()
  6027. {
  6028. struct timeval timeout;
  6029. struct timeval* timeoutp;
  6030. if (timeoutMsecs >= 0)
  6031. {
  6032. timeout.tv_sec = timeoutMsecs / 1000;
  6033. timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
  6034. timeoutp = &timeout;
  6035. }
  6036. else
  6037. {
  6038. timeoutp = 0;
  6039. }
  6040. fd_set rset, wset;
  6041. FD_ZERO (&rset);
  6042. FD_SET (handle, &rset);
  6043. FD_ZERO (&wset);
  6044. FD_SET (handle, &wset);
  6045. fd_set* const prset = forReading ? &rset : 0;
  6046. fd_set* const pwset = forReading ? 0 : &wset;
  6047. #if JUCE_WINDOWS
  6048. if (select (handle + 1, prset, pwset, 0, timeoutp) < 0)
  6049. return -1;
  6050. #else
  6051. {
  6052. int result;
  6053. while ((result = select (handle + 1, prset, pwset, 0, timeoutp)) < 0
  6054. && errno == EINTR)
  6055. {
  6056. }
  6057. if (result < 0)
  6058. return -1;
  6059. }
  6060. #endif
  6061. {
  6062. int opt;
  6063. juce_socklen_t len = sizeof (opt);
  6064. if (getsockopt (handle, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0
  6065. || opt != 0)
  6066. return -1;
  6067. }
  6068. if ((forReading && FD_ISSET (handle, &rset))
  6069. || ((! forReading) && FD_ISSET (handle, &wset)))
  6070. return 1;
  6071. return 0;
  6072. }
  6073. static bool setSocketBlockingState (const int handle, const bool shouldBlock) throw()
  6074. {
  6075. #if JUCE_WINDOWS
  6076. u_long nonBlocking = shouldBlock ? 0 : 1;
  6077. if (ioctlsocket (handle, FIONBIO, &nonBlocking) != 0)
  6078. return false;
  6079. #else
  6080. int socketFlags = fcntl (handle, F_GETFL, 0);
  6081. if (socketFlags == -1)
  6082. return false;
  6083. if (shouldBlock)
  6084. socketFlags &= ~O_NONBLOCK;
  6085. else
  6086. socketFlags |= O_NONBLOCK;
  6087. if (fcntl (handle, F_SETFL, socketFlags) != 0)
  6088. return false;
  6089. #endif
  6090. return true;
  6091. }
  6092. static bool connectSocket (int volatile& handle,
  6093. const bool isDatagram,
  6094. void** serverAddress,
  6095. const String& hostName,
  6096. const int portNumber,
  6097. const int timeOutMillisecs) throw()
  6098. {
  6099. struct hostent* const hostEnt = gethostbyname (hostName.toUTF8());
  6100. if (hostEnt == 0)
  6101. return false;
  6102. struct in_addr targetAddress;
  6103. memcpy (&targetAddress.s_addr,
  6104. *(hostEnt->h_addr_list),
  6105. sizeof (targetAddress.s_addr));
  6106. struct sockaddr_in servTmpAddr;
  6107. zerostruct (servTmpAddr);
  6108. servTmpAddr.sin_family = PF_INET;
  6109. servTmpAddr.sin_addr = targetAddress;
  6110. servTmpAddr.sin_port = htons ((uint16) portNumber);
  6111. if (handle < 0)
  6112. handle = (int) socket (AF_INET, isDatagram ? SOCK_DGRAM : SOCK_STREAM, 0);
  6113. if (handle < 0)
  6114. return false;
  6115. if (isDatagram)
  6116. {
  6117. *serverAddress = new struct sockaddr_in();
  6118. *((struct sockaddr_in*) *serverAddress) = servTmpAddr;
  6119. return true;
  6120. }
  6121. setSocketBlockingState (handle, false);
  6122. const int result = ::connect (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in));
  6123. if (result < 0)
  6124. {
  6125. #if JUCE_WINDOWS
  6126. if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
  6127. #else
  6128. if (errno == EINPROGRESS)
  6129. #endif
  6130. {
  6131. if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
  6132. {
  6133. setSocketBlockingState (handle, true);
  6134. return false;
  6135. }
  6136. }
  6137. }
  6138. setSocketBlockingState (handle, true);
  6139. resetSocketOptions (handle, false, false);
  6140. return true;
  6141. }
  6142. }
  6143. StreamingSocket::StreamingSocket()
  6144. : portNumber (0),
  6145. handle (-1),
  6146. connected (false),
  6147. isListener (false)
  6148. {
  6149. #if JUCE_WINDOWS
  6150. initWin32Sockets();
  6151. #endif
  6152. }
  6153. StreamingSocket::StreamingSocket (const String& hostName_,
  6154. const int portNumber_,
  6155. const int handle_)
  6156. : hostName (hostName_),
  6157. portNumber (portNumber_),
  6158. handle (handle_),
  6159. connected (true),
  6160. isListener (false)
  6161. {
  6162. #if JUCE_WINDOWS
  6163. initWin32Sockets();
  6164. #endif
  6165. SocketHelpers::resetSocketOptions (handle_, false, false);
  6166. }
  6167. StreamingSocket::~StreamingSocket()
  6168. {
  6169. close();
  6170. }
  6171. int StreamingSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  6172. {
  6173. return (connected && ! isListener) ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  6174. : -1;
  6175. }
  6176. int StreamingSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  6177. {
  6178. if (isListener || ! connected)
  6179. return -1;
  6180. #if JUCE_WINDOWS
  6181. return send (handle, (const char*) sourceBuffer, numBytesToWrite, 0);
  6182. #else
  6183. int result;
  6184. while ((result = (int) ::write (handle, sourceBuffer, numBytesToWrite)) < 0
  6185. && errno == EINTR)
  6186. {
  6187. }
  6188. return result;
  6189. #endif
  6190. }
  6191. int StreamingSocket::waitUntilReady (const bool readyForReading,
  6192. const int timeoutMsecs) const
  6193. {
  6194. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  6195. : -1;
  6196. }
  6197. bool StreamingSocket::bindToPort (const int port)
  6198. {
  6199. return SocketHelpers::bindSocketToPort (handle, port);
  6200. }
  6201. bool StreamingSocket::connect (const String& remoteHostName,
  6202. const int remotePortNumber,
  6203. const int timeOutMillisecs)
  6204. {
  6205. if (isListener)
  6206. {
  6207. jassertfalse; // a listener socket can't connect to another one!
  6208. return false;
  6209. }
  6210. if (connected)
  6211. close();
  6212. hostName = remoteHostName;
  6213. portNumber = remotePortNumber;
  6214. isListener = false;
  6215. connected = SocketHelpers::connectSocket (handle, false, 0, remoteHostName,
  6216. remotePortNumber, timeOutMillisecs);
  6217. if (! (connected && SocketHelpers::resetSocketOptions (handle, false, false)))
  6218. {
  6219. close();
  6220. return false;
  6221. }
  6222. return true;
  6223. }
  6224. void StreamingSocket::close()
  6225. {
  6226. #if JUCE_WINDOWS
  6227. if (handle != SOCKET_ERROR || connected)
  6228. closesocket (handle);
  6229. connected = false;
  6230. #else
  6231. if (connected)
  6232. {
  6233. connected = false;
  6234. if (isListener)
  6235. {
  6236. // need to do this to interrupt the accept() function..
  6237. StreamingSocket temp;
  6238. temp.connect ("localhost", portNumber, 1000);
  6239. }
  6240. }
  6241. if (handle != -1)
  6242. ::close (handle);
  6243. #endif
  6244. hostName = String::empty;
  6245. portNumber = 0;
  6246. handle = -1;
  6247. isListener = false;
  6248. }
  6249. bool StreamingSocket::createListener (const int newPortNumber, const String& localHostName)
  6250. {
  6251. if (connected)
  6252. close();
  6253. hostName = "listener";
  6254. portNumber = newPortNumber;
  6255. isListener = true;
  6256. struct sockaddr_in servTmpAddr;
  6257. zerostruct (servTmpAddr);
  6258. servTmpAddr.sin_family = PF_INET;
  6259. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  6260. if (localHostName.isNotEmpty())
  6261. servTmpAddr.sin_addr.s_addr = ::inet_addr (localHostName.toUTF8());
  6262. servTmpAddr.sin_port = htons ((uint16) portNumber);
  6263. handle = (int) socket (AF_INET, SOCK_STREAM, 0);
  6264. if (handle < 0)
  6265. return false;
  6266. const int reuse = 1;
  6267. setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));
  6268. if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
  6269. || listen (handle, SOMAXCONN) < 0)
  6270. {
  6271. close();
  6272. return false;
  6273. }
  6274. connected = true;
  6275. return true;
  6276. }
  6277. StreamingSocket* StreamingSocket::waitForNextConnection() const
  6278. {
  6279. jassert (isListener || ! connected); // to call this method, you first have to use createListener() to
  6280. // prepare this socket as a listener.
  6281. if (connected && isListener)
  6282. {
  6283. struct sockaddr address;
  6284. juce_socklen_t len = sizeof (sockaddr);
  6285. const int newSocket = (int) accept (handle, &address, &len);
  6286. if (newSocket >= 0 && connected)
  6287. return new StreamingSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  6288. portNumber, newSocket);
  6289. }
  6290. return 0;
  6291. }
  6292. bool StreamingSocket::isLocal() const throw()
  6293. {
  6294. return hostName == "127.0.0.1";
  6295. }
  6296. DatagramSocket::DatagramSocket (const int localPortNumber, const bool allowBroadcast_)
  6297. : portNumber (0),
  6298. handle (-1),
  6299. connected (true),
  6300. allowBroadcast (allowBroadcast_),
  6301. serverAddress (0)
  6302. {
  6303. #if JUCE_WINDOWS
  6304. initWin32Sockets();
  6305. #endif
  6306. handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
  6307. bindToPort (localPortNumber);
  6308. }
  6309. DatagramSocket::DatagramSocket (const String& hostName_, const int portNumber_,
  6310. const int handle_, const int localPortNumber)
  6311. : hostName (hostName_),
  6312. portNumber (portNumber_),
  6313. handle (handle_),
  6314. connected (true),
  6315. allowBroadcast (false),
  6316. serverAddress (0)
  6317. {
  6318. #if JUCE_WINDOWS
  6319. initWin32Sockets();
  6320. #endif
  6321. SocketHelpers::resetSocketOptions (handle_, true, allowBroadcast);
  6322. bindToPort (localPortNumber);
  6323. }
  6324. DatagramSocket::~DatagramSocket()
  6325. {
  6326. close();
  6327. delete ((struct sockaddr_in*) serverAddress);
  6328. serverAddress = 0;
  6329. }
  6330. void DatagramSocket::close()
  6331. {
  6332. #if JUCE_WINDOWS
  6333. closesocket (handle);
  6334. connected = false;
  6335. #else
  6336. connected = false;
  6337. ::close (handle);
  6338. #endif
  6339. hostName = String::empty;
  6340. portNumber = 0;
  6341. handle = -1;
  6342. }
  6343. bool DatagramSocket::bindToPort (const int port)
  6344. {
  6345. return SocketHelpers::bindSocketToPort (handle, port);
  6346. }
  6347. bool DatagramSocket::connect (const String& remoteHostName,
  6348. const int remotePortNumber,
  6349. const int timeOutMillisecs)
  6350. {
  6351. if (connected)
  6352. close();
  6353. hostName = remoteHostName;
  6354. portNumber = remotePortNumber;
  6355. connected = SocketHelpers::connectSocket (handle, true, &serverAddress,
  6356. remoteHostName, remotePortNumber,
  6357. timeOutMillisecs);
  6358. if (! (connected && SocketHelpers::resetSocketOptions (handle, true, allowBroadcast)))
  6359. {
  6360. close();
  6361. return false;
  6362. }
  6363. return true;
  6364. }
  6365. DatagramSocket* DatagramSocket::waitForNextConnection() const
  6366. {
  6367. struct sockaddr address;
  6368. juce_socklen_t len = sizeof (sockaddr);
  6369. while (waitUntilReady (true, -1) == 1)
  6370. {
  6371. char buf[1];
  6372. if (recvfrom (handle, buf, 0, 0, &address, &len) > 0)
  6373. {
  6374. return new DatagramSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  6375. ntohs (((struct sockaddr_in*) &address)->sin_port),
  6376. -1, -1);
  6377. }
  6378. }
  6379. return 0;
  6380. }
  6381. int DatagramSocket::waitUntilReady (const bool readyForReading,
  6382. const int timeoutMsecs) const
  6383. {
  6384. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  6385. : -1;
  6386. }
  6387. int DatagramSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  6388. {
  6389. return connected ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  6390. : -1;
  6391. }
  6392. int DatagramSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  6393. {
  6394. // You need to call connect() first to set the server address..
  6395. jassert (serverAddress != 0 && connected);
  6396. return connected ? (int) sendto (handle, (const char*) sourceBuffer,
  6397. numBytesToWrite, 0,
  6398. (const struct sockaddr*) serverAddress,
  6399. sizeof (struct sockaddr_in))
  6400. : -1;
  6401. }
  6402. bool DatagramSocket::isLocal() const throw()
  6403. {
  6404. return hostName == "127.0.0.1";
  6405. }
  6406. #if JUCE_MSVC
  6407. #pragma warning (pop)
  6408. #endif
  6409. END_JUCE_NAMESPACE
  6410. /*** End of inlined file: juce_Socket.cpp ***/
  6411. /*** Start of inlined file: juce_URL.cpp ***/
  6412. BEGIN_JUCE_NAMESPACE
  6413. URL::URL()
  6414. {
  6415. }
  6416. URL::URL (const String& url_)
  6417. : url (url_)
  6418. {
  6419. int i = url.indexOfChar ('?');
  6420. if (i >= 0)
  6421. {
  6422. do
  6423. {
  6424. const int nextAmp = url.indexOfChar (i + 1, '&');
  6425. const int equalsPos = url.indexOfChar (i + 1, '=');
  6426. if (equalsPos > i + 1)
  6427. {
  6428. if (nextAmp < 0)
  6429. {
  6430. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  6431. removeEscapeChars (url.substring (equalsPos + 1)));
  6432. }
  6433. else if (nextAmp > 0 && equalsPos < nextAmp)
  6434. {
  6435. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  6436. removeEscapeChars (url.substring (equalsPos + 1, nextAmp)));
  6437. }
  6438. }
  6439. i = nextAmp;
  6440. }
  6441. while (i >= 0);
  6442. url = url.upToFirstOccurrenceOf ("?", false, false);
  6443. }
  6444. }
  6445. URL::URL (const URL& other)
  6446. : url (other.url),
  6447. postData (other.postData),
  6448. parameters (other.parameters),
  6449. filesToUpload (other.filesToUpload),
  6450. mimeTypes (other.mimeTypes)
  6451. {
  6452. }
  6453. URL& URL::operator= (const URL& other)
  6454. {
  6455. url = other.url;
  6456. postData = other.postData;
  6457. parameters = other.parameters;
  6458. filesToUpload = other.filesToUpload;
  6459. mimeTypes = other.mimeTypes;
  6460. return *this;
  6461. }
  6462. URL::~URL()
  6463. {
  6464. }
  6465. static const String getMangledParameters (const StringPairArray& parameters)
  6466. {
  6467. String p;
  6468. for (int i = 0; i < parameters.size(); ++i)
  6469. {
  6470. if (i > 0)
  6471. p += '&';
  6472. p << URL::addEscapeChars (parameters.getAllKeys() [i], true)
  6473. << '='
  6474. << URL::addEscapeChars (parameters.getAllValues() [i], true);
  6475. }
  6476. return p;
  6477. }
  6478. const String URL::toString (const bool includeGetParameters) const
  6479. {
  6480. if (includeGetParameters && parameters.size() > 0)
  6481. return url + "?" + getMangledParameters (parameters);
  6482. else
  6483. return url;
  6484. }
  6485. bool URL::isWellFormed() const
  6486. {
  6487. //xxx TODO
  6488. return url.isNotEmpty();
  6489. }
  6490. static int findStartOfDomain (const String& url)
  6491. {
  6492. int i = 0;
  6493. while (CharacterFunctions::isLetterOrDigit (url[i])
  6494. || CharacterFunctions::indexOfChar (L"+-.", url[i], false) >= 0)
  6495. ++i;
  6496. return url[i] == ':' ? i + 1 : 0;
  6497. }
  6498. const String URL::getDomain() const
  6499. {
  6500. int start = findStartOfDomain (url);
  6501. while (url[start] == '/')
  6502. ++start;
  6503. const int end1 = url.indexOfChar (start, '/');
  6504. const int end2 = url.indexOfChar (start, ':');
  6505. const int end = (end1 < 0 || end2 < 0) ? jmax (end1, end2)
  6506. : jmin (end1, end2);
  6507. return url.substring (start, end);
  6508. }
  6509. const String URL::getSubPath() const
  6510. {
  6511. int start = findStartOfDomain (url);
  6512. while (url[start] == '/')
  6513. ++start;
  6514. const int startOfPath = url.indexOfChar (start, '/') + 1;
  6515. return startOfPath <= 0 ? String::empty
  6516. : url.substring (startOfPath);
  6517. }
  6518. const String URL::getScheme() const
  6519. {
  6520. return url.substring (0, findStartOfDomain (url) - 1);
  6521. }
  6522. const URL URL::withNewSubPath (const String& newPath) const
  6523. {
  6524. int start = findStartOfDomain (url);
  6525. while (url[start] == '/')
  6526. ++start;
  6527. const int startOfPath = url.indexOfChar (start, '/') + 1;
  6528. URL u (*this);
  6529. if (startOfPath > 0)
  6530. u.url = url.substring (0, startOfPath);
  6531. if (! u.url.endsWithChar ('/'))
  6532. u.url << '/';
  6533. if (newPath.startsWithChar ('/'))
  6534. u.url << newPath.substring (1);
  6535. else
  6536. u.url << newPath;
  6537. return u;
  6538. }
  6539. bool URL::isProbablyAWebsiteURL (const String& possibleURL)
  6540. {
  6541. if (possibleURL.startsWithIgnoreCase ("http:")
  6542. || possibleURL.startsWithIgnoreCase ("ftp:"))
  6543. return true;
  6544. if (possibleURL.startsWithIgnoreCase ("file:")
  6545. || possibleURL.containsChar ('@')
  6546. || possibleURL.endsWithChar ('.')
  6547. || (! possibleURL.containsChar ('.')))
  6548. return false;
  6549. if (possibleURL.startsWithIgnoreCase ("www.")
  6550. && possibleURL.substring (5).containsChar ('.'))
  6551. return true;
  6552. const char* commonTLDs[] = { "com", "net", "org", "uk", "de", "fr", "jp" };
  6553. for (int i = 0; i < numElementsInArray (commonTLDs); ++i)
  6554. if ((possibleURL + "/").containsIgnoreCase ("." + String (commonTLDs[i]) + "/"))
  6555. return true;
  6556. return false;
  6557. }
  6558. bool URL::isProbablyAnEmailAddress (const String& possibleEmailAddress)
  6559. {
  6560. const int atSign = possibleEmailAddress.indexOfChar ('@');
  6561. return atSign > 0
  6562. && possibleEmailAddress.lastIndexOfChar ('.') > (atSign + 1)
  6563. && (! possibleEmailAddress.endsWithChar ('.'));
  6564. }
  6565. void* juce_openInternetFile (const String& url,
  6566. const String& headers,
  6567. const MemoryBlock& optionalPostData,
  6568. const bool isPost,
  6569. URL::OpenStreamProgressCallback* callback,
  6570. void* callbackContext,
  6571. int timeOutMs);
  6572. void juce_closeInternetFile (void* handle);
  6573. int juce_readFromInternetFile (void* handle, void* dest, int bytesToRead);
  6574. int juce_seekInInternetFile (void* handle, int newPosition);
  6575. int64 juce_getInternetFileContentLength (void* handle);
  6576. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers);
  6577. class WebInputStream : public InputStream
  6578. {
  6579. public:
  6580. WebInputStream (const URL& url,
  6581. const bool isPost_,
  6582. URL::OpenStreamProgressCallback* const progressCallback_,
  6583. void* const progressCallbackContext_,
  6584. const String& extraHeaders,
  6585. const int timeOutMs_,
  6586. StringPairArray* const responseHeaders)
  6587. : position (0),
  6588. finished (false),
  6589. isPost (isPost_),
  6590. progressCallback (progressCallback_),
  6591. progressCallbackContext (progressCallbackContext_),
  6592. timeOutMs (timeOutMs_)
  6593. {
  6594. server = url.toString (! isPost);
  6595. if (isPost_)
  6596. createHeadersAndPostData (url);
  6597. headers += extraHeaders;
  6598. if (! headers.endsWithChar ('\n'))
  6599. headers << "\r\n";
  6600. handle = juce_openInternetFile (server, headers, postData, isPost,
  6601. progressCallback_, progressCallbackContext_,
  6602. timeOutMs);
  6603. if (responseHeaders != 0)
  6604. juce_getInternetFileHeaders (handle, *responseHeaders);
  6605. }
  6606. ~WebInputStream()
  6607. {
  6608. juce_closeInternetFile (handle);
  6609. }
  6610. bool isError() const { return handle == 0; }
  6611. int64 getTotalLength() { return juce_getInternetFileContentLength (handle); }
  6612. bool isExhausted() { return finished; }
  6613. int64 getPosition() { return position; }
  6614. int read (void* dest, int bytes)
  6615. {
  6616. if (finished || isError())
  6617. {
  6618. return 0;
  6619. }
  6620. else
  6621. {
  6622. const int bytesRead = juce_readFromInternetFile (handle, dest, bytes);
  6623. position += bytesRead;
  6624. if (bytesRead == 0)
  6625. finished = true;
  6626. return bytesRead;
  6627. }
  6628. }
  6629. bool setPosition (int64 wantedPos)
  6630. {
  6631. if (wantedPos != position)
  6632. {
  6633. finished = false;
  6634. const int actualPos = juce_seekInInternetFile (handle, (int) wantedPos);
  6635. if (actualPos == wantedPos)
  6636. {
  6637. position = wantedPos;
  6638. }
  6639. else
  6640. {
  6641. if (wantedPos < position)
  6642. {
  6643. juce_closeInternetFile (handle);
  6644. position = 0;
  6645. finished = false;
  6646. handle = juce_openInternetFile (server, headers, postData, isPost,
  6647. progressCallback, progressCallbackContext,
  6648. timeOutMs);
  6649. }
  6650. skipNextBytes (wantedPos - position);
  6651. }
  6652. }
  6653. return true;
  6654. }
  6655. juce_UseDebuggingNewOperator
  6656. private:
  6657. String server, headers;
  6658. MemoryBlock postData;
  6659. int64 position;
  6660. bool finished;
  6661. const bool isPost;
  6662. void* handle;
  6663. URL::OpenStreamProgressCallback* const progressCallback;
  6664. void* const progressCallbackContext;
  6665. const int timeOutMs;
  6666. void createHeadersAndPostData (const URL& url)
  6667. {
  6668. MemoryOutputStream data (256, 256, &postData);
  6669. if (url.getFilesToUpload().size() > 0)
  6670. {
  6671. // need to upload some files, so do it as multi-part...
  6672. const String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
  6673. headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
  6674. data << "--" << boundary;
  6675. int i;
  6676. for (i = 0; i < url.getParameters().size(); ++i)
  6677. {
  6678. data << "\r\nContent-Disposition: form-data; name=\""
  6679. << url.getParameters().getAllKeys() [i]
  6680. << "\"\r\n\r\n"
  6681. << url.getParameters().getAllValues() [i]
  6682. << "\r\n--"
  6683. << boundary;
  6684. }
  6685. for (i = 0; i < url.getFilesToUpload().size(); ++i)
  6686. {
  6687. const File file (url.getFilesToUpload().getAllValues() [i]);
  6688. const String paramName (url.getFilesToUpload().getAllKeys() [i]);
  6689. data << "\r\nContent-Disposition: form-data; name=\"" << paramName
  6690. << "\"; filename=\"" << file.getFileName() << "\"\r\n";
  6691. const String mimeType (url.getMimeTypesOfUploadFiles()
  6692. .getValue (paramName, String::empty));
  6693. if (mimeType.isNotEmpty())
  6694. data << "Content-Type: " << mimeType << "\r\n";
  6695. data << "Content-Transfer-Encoding: binary\r\n\r\n"
  6696. << file << "\r\n--" << boundary;
  6697. }
  6698. data << "--\r\n";
  6699. data.flush();
  6700. }
  6701. else
  6702. {
  6703. data << getMangledParameters (url.getParameters())
  6704. << url.getPostData();
  6705. data.flush();
  6706. // just a short text attachment, so use simple url encoding..
  6707. headers = "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
  6708. + String ((unsigned int) postData.getSize())
  6709. + "\r\n";
  6710. }
  6711. }
  6712. WebInputStream (const WebInputStream&);
  6713. WebInputStream& operator= (const WebInputStream&);
  6714. };
  6715. InputStream* URL::createInputStream (const bool usePostCommand,
  6716. OpenStreamProgressCallback* const progressCallback,
  6717. void* const progressCallbackContext,
  6718. const String& extraHeaders,
  6719. const int timeOutMs,
  6720. StringPairArray* const responseHeaders) const
  6721. {
  6722. ScopedPointer <WebInputStream> wi (new WebInputStream (*this, usePostCommand,
  6723. progressCallback, progressCallbackContext,
  6724. extraHeaders, timeOutMs, responseHeaders));
  6725. return wi->isError() ? 0 : wi.release();
  6726. }
  6727. bool URL::readEntireBinaryStream (MemoryBlock& destData,
  6728. const bool usePostCommand) const
  6729. {
  6730. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  6731. if (in != 0)
  6732. {
  6733. in->readIntoMemoryBlock (destData, -1);
  6734. return true;
  6735. }
  6736. return false;
  6737. }
  6738. const String URL::readEntireTextStream (const bool usePostCommand) const
  6739. {
  6740. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  6741. if (in != 0)
  6742. return in->readEntireStreamAsString();
  6743. return String::empty;
  6744. }
  6745. XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
  6746. {
  6747. XmlDocument doc (readEntireTextStream (usePostCommand));
  6748. return doc.getDocumentElement();
  6749. }
  6750. const URL URL::withParameter (const String& parameterName,
  6751. const String& parameterValue) const
  6752. {
  6753. URL u (*this);
  6754. u.parameters.set (parameterName, parameterValue);
  6755. return u;
  6756. }
  6757. const URL URL::withFileToUpload (const String& parameterName,
  6758. const File& fileToUpload,
  6759. const String& mimeType) const
  6760. {
  6761. jassert (mimeType.isNotEmpty()); // You need to supply a mime type!
  6762. URL u (*this);
  6763. u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
  6764. u.mimeTypes.set (parameterName, mimeType);
  6765. return u;
  6766. }
  6767. const URL URL::withPOSTData (const String& postData_) const
  6768. {
  6769. URL u (*this);
  6770. u.postData = postData_;
  6771. return u;
  6772. }
  6773. const StringPairArray& URL::getParameters() const
  6774. {
  6775. return parameters;
  6776. }
  6777. const StringPairArray& URL::getFilesToUpload() const
  6778. {
  6779. return filesToUpload;
  6780. }
  6781. const StringPairArray& URL::getMimeTypesOfUploadFiles() const
  6782. {
  6783. return mimeTypes;
  6784. }
  6785. const String URL::removeEscapeChars (const String& s)
  6786. {
  6787. String result (s.replaceCharacter ('+', ' '));
  6788. int nextPercent = 0;
  6789. for (;;)
  6790. {
  6791. nextPercent = result.indexOfChar (nextPercent, '%');
  6792. if (nextPercent < 0)
  6793. break;
  6794. juce_wchar replacementChar = (juce_wchar) result.substring (nextPercent + 1, nextPercent + 3).getHexValue32();
  6795. result = result.replaceSection (nextPercent, 3, String::charToString (replacementChar));
  6796. ++nextPercent;
  6797. }
  6798. return result;
  6799. }
  6800. const String URL::addEscapeChars (const String& s, const bool isParameter)
  6801. {
  6802. String result;
  6803. result.preallocateStorage (s.length() + 8);
  6804. const char* utf8 = s.toUTF8();
  6805. const char* legalChars = isParameter ? "_-.*!'()"
  6806. : "_-$.*!'(),";
  6807. while (*utf8 != 0)
  6808. {
  6809. const char c = *utf8++;
  6810. if (CharacterFunctions::isLetterOrDigit (c)
  6811. || CharacterFunctions::indexOfChar (legalChars, c, false) >= 0)
  6812. {
  6813. result << c;
  6814. }
  6815. else
  6816. {
  6817. const int v = (int) (uint8) c;
  6818. result << (v < 0x10 ? "%0" : "%") << String::toHexString (v);
  6819. }
  6820. }
  6821. return result;
  6822. }
  6823. bool URL::launchInDefaultBrowser() const
  6824. {
  6825. String u (toString (true));
  6826. if (u.containsChar ('@') && ! u.containsChar (':'))
  6827. u = "mailto:" + u;
  6828. return PlatformUtilities::openDocument (u, String::empty);
  6829. }
  6830. END_JUCE_NAMESPACE
  6831. /*** End of inlined file: juce_URL.cpp ***/
  6832. /*** Start of inlined file: juce_BufferedInputStream.cpp ***/
  6833. BEGIN_JUCE_NAMESPACE
  6834. BufferedInputStream::BufferedInputStream (InputStream* const source_,
  6835. const int bufferSize_,
  6836. const bool deleteSourceWhenDestroyed)
  6837. : source (source_),
  6838. sourceToDelete (deleteSourceWhenDestroyed ? source_ : 0),
  6839. bufferSize (jmax (256, bufferSize_)),
  6840. position (source_->getPosition()),
  6841. lastReadPos (0),
  6842. bufferOverlap (128)
  6843. {
  6844. const int sourceSize = (int) source_->getTotalLength();
  6845. if (sourceSize >= 0)
  6846. bufferSize = jmin (jmax (32, sourceSize), bufferSize);
  6847. bufferStart = position;
  6848. buffer.malloc (bufferSize);
  6849. }
  6850. BufferedInputStream::~BufferedInputStream()
  6851. {
  6852. }
  6853. int64 BufferedInputStream::getTotalLength()
  6854. {
  6855. return source->getTotalLength();
  6856. }
  6857. int64 BufferedInputStream::getPosition()
  6858. {
  6859. return position;
  6860. }
  6861. bool BufferedInputStream::setPosition (int64 newPosition)
  6862. {
  6863. position = jmax ((int64) 0, newPosition);
  6864. return true;
  6865. }
  6866. bool BufferedInputStream::isExhausted()
  6867. {
  6868. return (position >= lastReadPos)
  6869. && source->isExhausted();
  6870. }
  6871. void BufferedInputStream::ensureBuffered()
  6872. {
  6873. const int64 bufferEndOverlap = lastReadPos - bufferOverlap;
  6874. if (position < bufferStart || position >= bufferEndOverlap)
  6875. {
  6876. int bytesRead;
  6877. if (position < lastReadPos
  6878. && position >= bufferEndOverlap
  6879. && position >= bufferStart)
  6880. {
  6881. const int bytesToKeep = (int) (lastReadPos - position);
  6882. memmove (buffer, buffer + (int) (position - bufferStart), bytesToKeep);
  6883. bufferStart = position;
  6884. bytesRead = source->read (buffer + bytesToKeep,
  6885. bufferSize - bytesToKeep);
  6886. lastReadPos += bytesRead;
  6887. bytesRead += bytesToKeep;
  6888. }
  6889. else
  6890. {
  6891. bufferStart = position;
  6892. source->setPosition (bufferStart);
  6893. bytesRead = source->read (buffer, bufferSize);
  6894. lastReadPos = bufferStart + bytesRead;
  6895. }
  6896. while (bytesRead < bufferSize)
  6897. buffer [bytesRead++] = 0;
  6898. }
  6899. }
  6900. int BufferedInputStream::read (void* destBuffer, int maxBytesToRead)
  6901. {
  6902. if (position >= bufferStart
  6903. && position + maxBytesToRead <= lastReadPos)
  6904. {
  6905. memcpy (destBuffer, buffer + (int) (position - bufferStart), maxBytesToRead);
  6906. position += maxBytesToRead;
  6907. return maxBytesToRead;
  6908. }
  6909. else
  6910. {
  6911. if (position < bufferStart || position >= lastReadPos)
  6912. ensureBuffered();
  6913. int bytesRead = 0;
  6914. while (maxBytesToRead > 0)
  6915. {
  6916. const int bytesAvailable = jmin (maxBytesToRead, (int) (lastReadPos - position));
  6917. if (bytesAvailable > 0)
  6918. {
  6919. memcpy (destBuffer, buffer + (int) (position - bufferStart), bytesAvailable);
  6920. maxBytesToRead -= bytesAvailable;
  6921. bytesRead += bytesAvailable;
  6922. position += bytesAvailable;
  6923. destBuffer = static_cast <char*> (destBuffer) + bytesAvailable;
  6924. }
  6925. const int64 oldLastReadPos = lastReadPos;
  6926. ensureBuffered();
  6927. if (oldLastReadPos == lastReadPos)
  6928. break; // if ensureBuffered() failed to read any more data, bail out
  6929. if (isExhausted())
  6930. break;
  6931. }
  6932. return bytesRead;
  6933. }
  6934. }
  6935. const String BufferedInputStream::readString()
  6936. {
  6937. if (position >= bufferStart
  6938. && position < lastReadPos)
  6939. {
  6940. const int maxChars = (int) (lastReadPos - position);
  6941. const char* const src = buffer + (int) (position - bufferStart);
  6942. for (int i = 0; i < maxChars; ++i)
  6943. {
  6944. if (src[i] == 0)
  6945. {
  6946. position += i + 1;
  6947. return String::fromUTF8 (src, i);
  6948. }
  6949. }
  6950. }
  6951. return InputStream::readString();
  6952. }
  6953. END_JUCE_NAMESPACE
  6954. /*** End of inlined file: juce_BufferedInputStream.cpp ***/
  6955. /*** Start of inlined file: juce_FileInputSource.cpp ***/
  6956. BEGIN_JUCE_NAMESPACE
  6957. FileInputSource::FileInputSource (const File& file_)
  6958. : file (file_)
  6959. {
  6960. }
  6961. FileInputSource::~FileInputSource()
  6962. {
  6963. }
  6964. InputStream* FileInputSource::createInputStream()
  6965. {
  6966. return file.createInputStream();
  6967. }
  6968. InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPath)
  6969. {
  6970. return file.getSiblingFile (relatedItemPath).createInputStream();
  6971. }
  6972. int64 FileInputSource::hashCode() const
  6973. {
  6974. return file.hashCode();
  6975. }
  6976. END_JUCE_NAMESPACE
  6977. /*** End of inlined file: juce_FileInputSource.cpp ***/
  6978. /*** Start of inlined file: juce_MemoryInputStream.cpp ***/
  6979. BEGIN_JUCE_NAMESPACE
  6980. MemoryInputStream::MemoryInputStream (const void* const sourceData,
  6981. const size_t sourceDataSize,
  6982. const bool keepInternalCopy)
  6983. : data (static_cast <const char*> (sourceData)),
  6984. dataSize (sourceDataSize),
  6985. position (0)
  6986. {
  6987. if (keepInternalCopy)
  6988. {
  6989. internalCopy.append (data, sourceDataSize);
  6990. data = static_cast <const char*> (internalCopy.getData());
  6991. }
  6992. }
  6993. MemoryInputStream::MemoryInputStream (const MemoryBlock& sourceData,
  6994. const bool keepInternalCopy)
  6995. : data (static_cast <const char*> (sourceData.getData())),
  6996. dataSize (sourceData.getSize()),
  6997. position (0)
  6998. {
  6999. if (keepInternalCopy)
  7000. {
  7001. internalCopy = sourceData;
  7002. data = static_cast <const char*> (internalCopy.getData());
  7003. }
  7004. }
  7005. MemoryInputStream::~MemoryInputStream()
  7006. {
  7007. }
  7008. int64 MemoryInputStream::getTotalLength()
  7009. {
  7010. return dataSize;
  7011. }
  7012. int MemoryInputStream::read (void* const buffer, const int howMany)
  7013. {
  7014. jassert (howMany >= 0);
  7015. const int num = jmin (howMany, (int) (dataSize - position));
  7016. memcpy (buffer, data + position, num);
  7017. position += num;
  7018. return (int) num;
  7019. }
  7020. bool MemoryInputStream::isExhausted()
  7021. {
  7022. return (position >= dataSize);
  7023. }
  7024. bool MemoryInputStream::setPosition (const int64 pos)
  7025. {
  7026. position = (int) jlimit ((int64) 0, (int64) dataSize, pos);
  7027. return true;
  7028. }
  7029. int64 MemoryInputStream::getPosition()
  7030. {
  7031. return position;
  7032. }
  7033. END_JUCE_NAMESPACE
  7034. /*** End of inlined file: juce_MemoryInputStream.cpp ***/
  7035. /*** Start of inlined file: juce_MemoryOutputStream.cpp ***/
  7036. BEGIN_JUCE_NAMESPACE
  7037. MemoryOutputStream::MemoryOutputStream (const size_t initialSize,
  7038. const size_t blockSizeToIncreaseBy,
  7039. MemoryBlock* const memoryBlockToWriteTo)
  7040. : data (memoryBlockToWriteTo),
  7041. position (0),
  7042. size (0),
  7043. blockSize (jmax ((size_t) 16, blockSizeToIncreaseBy))
  7044. {
  7045. if (data == 0)
  7046. dataToDelete = data = new MemoryBlock (initialSize);
  7047. else
  7048. data->setSize (initialSize, false);
  7049. }
  7050. MemoryOutputStream::~MemoryOutputStream()
  7051. {
  7052. flush();
  7053. }
  7054. void MemoryOutputStream::flush()
  7055. {
  7056. if (dataToDelete == 0)
  7057. data->setSize (size, false);
  7058. }
  7059. void MemoryOutputStream::reset() throw()
  7060. {
  7061. position = 0;
  7062. size = 0;
  7063. }
  7064. bool MemoryOutputStream::write (const void* const buffer, int howMany)
  7065. {
  7066. if (howMany > 0)
  7067. {
  7068. size_t storageNeeded = position + howMany;
  7069. if (storageNeeded >= data->getSize())
  7070. {
  7071. // if we need more space, increase the block by at least 10%..
  7072. storageNeeded += jmax (blockSize, storageNeeded / 10);
  7073. storageNeeded = storageNeeded - (storageNeeded % blockSize) + blockSize;
  7074. data->ensureSize (storageNeeded);
  7075. }
  7076. data->copyFrom (buffer, (int) position, howMany);
  7077. position += howMany;
  7078. size = jmax (size, position);
  7079. }
  7080. return true;
  7081. }
  7082. const char* MemoryOutputStream::getData() const throw()
  7083. {
  7084. char* const d = static_cast <char*> (data->getData());
  7085. if (data->getSize() > size)
  7086. d [size] = 0;
  7087. return d;
  7088. }
  7089. bool MemoryOutputStream::setPosition (int64 newPosition)
  7090. {
  7091. if (newPosition <= (int64) size)
  7092. {
  7093. // ok to seek backwards
  7094. position = jlimit ((size_t) 0, size, (size_t) newPosition);
  7095. return true;
  7096. }
  7097. else
  7098. {
  7099. // trying to make it bigger isn't a good thing to do..
  7100. return false;
  7101. }
  7102. }
  7103. const String MemoryOutputStream::toUTF8() const
  7104. {
  7105. return String (getData(), getDataSize());
  7106. }
  7107. END_JUCE_NAMESPACE
  7108. /*** End of inlined file: juce_MemoryOutputStream.cpp ***/
  7109. /*** Start of inlined file: juce_SubregionStream.cpp ***/
  7110. BEGIN_JUCE_NAMESPACE
  7111. SubregionStream::SubregionStream (InputStream* const sourceStream,
  7112. const int64 startPositionInSourceStream_,
  7113. const int64 lengthOfSourceStream_,
  7114. const bool deleteSourceWhenDestroyed)
  7115. : source (sourceStream),
  7116. startPositionInSourceStream (startPositionInSourceStream_),
  7117. lengthOfSourceStream (lengthOfSourceStream_)
  7118. {
  7119. if (deleteSourceWhenDestroyed)
  7120. sourceToDelete = source;
  7121. setPosition (0);
  7122. }
  7123. SubregionStream::~SubregionStream()
  7124. {
  7125. }
  7126. int64 SubregionStream::getTotalLength()
  7127. {
  7128. const int64 srcLen = source->getTotalLength() - startPositionInSourceStream;
  7129. return (lengthOfSourceStream >= 0) ? jmin (lengthOfSourceStream, srcLen)
  7130. : srcLen;
  7131. }
  7132. int64 SubregionStream::getPosition()
  7133. {
  7134. return source->getPosition() - startPositionInSourceStream;
  7135. }
  7136. bool SubregionStream::setPosition (int64 newPosition)
  7137. {
  7138. return source->setPosition (jmax ((int64) 0, newPosition + startPositionInSourceStream));
  7139. }
  7140. int SubregionStream::read (void* destBuffer, int maxBytesToRead)
  7141. {
  7142. if (lengthOfSourceStream < 0)
  7143. {
  7144. return source->read (destBuffer, maxBytesToRead);
  7145. }
  7146. else
  7147. {
  7148. maxBytesToRead = (int) jmin ((int64) maxBytesToRead, lengthOfSourceStream - getPosition());
  7149. if (maxBytesToRead <= 0)
  7150. return 0;
  7151. return source->read (destBuffer, maxBytesToRead);
  7152. }
  7153. }
  7154. bool SubregionStream::isExhausted()
  7155. {
  7156. if (lengthOfSourceStream >= 0)
  7157. return (getPosition() >= lengthOfSourceStream) || source->isExhausted();
  7158. else
  7159. return source->isExhausted();
  7160. }
  7161. END_JUCE_NAMESPACE
  7162. /*** End of inlined file: juce_SubregionStream.cpp ***/
  7163. /*** Start of inlined file: juce_PerformanceCounter.cpp ***/
  7164. BEGIN_JUCE_NAMESPACE
  7165. PerformanceCounter::PerformanceCounter (const String& name_,
  7166. int runsPerPrintout,
  7167. const File& loggingFile)
  7168. : name (name_),
  7169. numRuns (0),
  7170. runsPerPrint (runsPerPrintout),
  7171. totalTime (0),
  7172. outputFile (loggingFile)
  7173. {
  7174. if (outputFile != File::nonexistent)
  7175. {
  7176. String s ("**** Counter for \"");
  7177. s << name_ << "\" started at: "
  7178. << Time::getCurrentTime().toString (true, true)
  7179. << "\r\n";
  7180. outputFile.appendText (s, false, false);
  7181. }
  7182. }
  7183. PerformanceCounter::~PerformanceCounter()
  7184. {
  7185. printStatistics();
  7186. }
  7187. void PerformanceCounter::start()
  7188. {
  7189. started = Time::getHighResolutionTicks();
  7190. }
  7191. void PerformanceCounter::stop()
  7192. {
  7193. const int64 now = Time::getHighResolutionTicks();
  7194. totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started);
  7195. if (++numRuns == runsPerPrint)
  7196. printStatistics();
  7197. }
  7198. void PerformanceCounter::printStatistics()
  7199. {
  7200. if (numRuns > 0)
  7201. {
  7202. String s ("Performance count for \"");
  7203. s << name << "\" - average over " << numRuns << " run(s) = ";
  7204. const int micros = (int) (totalTime * (1000.0 / numRuns));
  7205. if (micros > 10000)
  7206. s << (micros/1000) << " millisecs";
  7207. else
  7208. s << micros << " microsecs";
  7209. s << ", total = " << String (totalTime / 1000, 5) << " seconds";
  7210. Logger::outputDebugString (s);
  7211. s << "\r\n";
  7212. if (outputFile != File::nonexistent)
  7213. outputFile.appendText (s, false, false);
  7214. numRuns = 0;
  7215. totalTime = 0;
  7216. }
  7217. }
  7218. END_JUCE_NAMESPACE
  7219. /*** End of inlined file: juce_PerformanceCounter.cpp ***/
  7220. /*** Start of inlined file: juce_Uuid.cpp ***/
  7221. BEGIN_JUCE_NAMESPACE
  7222. Uuid::Uuid()
  7223. {
  7224. // Mix up any available MAC addresses with some time-based pseudo-random numbers
  7225. // to make it very very unlikely that two UUIDs will ever be the same..
  7226. static int64 macAddresses[2];
  7227. static bool hasCheckedMacAddresses = false;
  7228. if (! hasCheckedMacAddresses)
  7229. {
  7230. hasCheckedMacAddresses = true;
  7231. SystemStats::getMACAddresses (macAddresses, 2);
  7232. }
  7233. value.asInt64[0] = macAddresses[0];
  7234. value.asInt64[1] = macAddresses[1];
  7235. // We'll use both a local RNG that is re-seeded, plus the shared RNG,
  7236. // whose seed will carry over between calls to this method.
  7237. Random r (macAddresses[0] ^ macAddresses[1]
  7238. ^ Random::getSystemRandom().nextInt64());
  7239. for (int i = 4; --i >= 0;)
  7240. {
  7241. r.setSeedRandomly(); // calling this repeatedly improves randomness
  7242. value.asInt[i] ^= r.nextInt();
  7243. value.asInt[i] ^= Random::getSystemRandom().nextInt();
  7244. }
  7245. }
  7246. Uuid::~Uuid() throw()
  7247. {
  7248. }
  7249. Uuid::Uuid (const Uuid& other)
  7250. : value (other.value)
  7251. {
  7252. }
  7253. Uuid& Uuid::operator= (const Uuid& other)
  7254. {
  7255. value = other.value;
  7256. return *this;
  7257. }
  7258. bool Uuid::operator== (const Uuid& other) const
  7259. {
  7260. return value.asInt64[0] == other.value.asInt64[0]
  7261. && value.asInt64[1] == other.value.asInt64[1];
  7262. }
  7263. bool Uuid::operator!= (const Uuid& other) const
  7264. {
  7265. return ! operator== (other);
  7266. }
  7267. bool Uuid::isNull() const throw()
  7268. {
  7269. return (value.asInt64 [0] == 0) && (value.asInt64 [1] == 0);
  7270. }
  7271. const String Uuid::toString() const
  7272. {
  7273. return String::toHexString (value.asBytes, sizeof (value.asBytes), 0);
  7274. }
  7275. Uuid::Uuid (const String& uuidString)
  7276. {
  7277. operator= (uuidString);
  7278. }
  7279. Uuid& Uuid::operator= (const String& uuidString)
  7280. {
  7281. MemoryBlock mb;
  7282. mb.loadFromHexString (uuidString);
  7283. mb.ensureSize (sizeof (value.asBytes), true);
  7284. mb.copyTo (value.asBytes, 0, sizeof (value.asBytes));
  7285. return *this;
  7286. }
  7287. Uuid::Uuid (const uint8* const rawData)
  7288. {
  7289. operator= (rawData);
  7290. }
  7291. Uuid& Uuid::operator= (const uint8* const rawData)
  7292. {
  7293. if (rawData != 0)
  7294. memcpy (value.asBytes, rawData, sizeof (value.asBytes));
  7295. else
  7296. zeromem (value.asBytes, sizeof (value.asBytes));
  7297. return *this;
  7298. }
  7299. END_JUCE_NAMESPACE
  7300. /*** End of inlined file: juce_Uuid.cpp ***/
  7301. /*** Start of inlined file: juce_ZipFile.cpp ***/
  7302. BEGIN_JUCE_NAMESPACE
  7303. class ZipFile::ZipEntryInfo
  7304. {
  7305. public:
  7306. ZipFile::ZipEntry entry;
  7307. int streamOffset;
  7308. int compressedSize;
  7309. bool compressed;
  7310. };
  7311. class ZipFile::ZipInputStream : public InputStream
  7312. {
  7313. public:
  7314. ZipInputStream (ZipFile& file_, ZipFile::ZipEntryInfo& zei)
  7315. : file (file_),
  7316. zipEntryInfo (zei),
  7317. pos (0),
  7318. headerSize (0),
  7319. inputStream (0)
  7320. {
  7321. inputStream = file_.inputStream;
  7322. if (file_.inputSource != 0)
  7323. {
  7324. inputStream = file.inputSource->createInputStream();
  7325. }
  7326. else
  7327. {
  7328. #if JUCE_DEBUG
  7329. file_.numOpenStreams++;
  7330. #endif
  7331. }
  7332. char buffer [30];
  7333. if (inputStream != 0
  7334. && inputStream->setPosition (zei.streamOffset)
  7335. && inputStream->read (buffer, 30) == 30
  7336. && ByteOrder::littleEndianInt (buffer) == 0x04034b50)
  7337. {
  7338. headerSize = 30 + ByteOrder::littleEndianShort (buffer + 26)
  7339. + ByteOrder::littleEndianShort (buffer + 28);
  7340. }
  7341. }
  7342. ~ZipInputStream() throw()
  7343. {
  7344. #if JUCE_DEBUG
  7345. if (inputStream != 0 && inputStream == file.inputStream)
  7346. file.numOpenStreams--;
  7347. #endif
  7348. if (inputStream != file.inputStream)
  7349. delete inputStream;
  7350. }
  7351. int64 getTotalLength() throw()
  7352. {
  7353. return zipEntryInfo.compressedSize;
  7354. }
  7355. int read (void* buffer, int howMany) throw()
  7356. {
  7357. if (headerSize <= 0)
  7358. return 0;
  7359. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  7360. if (inputStream == 0)
  7361. return 0;
  7362. int num;
  7363. if (inputStream == file.inputStream)
  7364. {
  7365. const ScopedLock sl (file.lock);
  7366. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  7367. num = inputStream->read (buffer, howMany);
  7368. }
  7369. else
  7370. {
  7371. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  7372. num = inputStream->read (buffer, howMany);
  7373. }
  7374. pos += num;
  7375. return num;
  7376. }
  7377. bool isExhausted() throw()
  7378. {
  7379. return headerSize <= 0 || pos >= zipEntryInfo.compressedSize;
  7380. }
  7381. int64 getPosition() throw()
  7382. {
  7383. return pos;
  7384. }
  7385. bool setPosition (int64 newPos) throw()
  7386. {
  7387. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  7388. return true;
  7389. }
  7390. private:
  7391. ZipFile& file;
  7392. ZipEntryInfo zipEntryInfo;
  7393. int64 pos;
  7394. int headerSize;
  7395. InputStream* inputStream;
  7396. ZipInputStream (const ZipInputStream&);
  7397. ZipInputStream& operator= (const ZipInputStream&);
  7398. };
  7399. ZipFile::ZipFile (InputStream* const source_,
  7400. const bool deleteStreamWhenDestroyed) throw()
  7401. : inputStream (source_)
  7402. #if JUCE_DEBUG
  7403. , numOpenStreams (0)
  7404. #endif
  7405. {
  7406. if (deleteStreamWhenDestroyed)
  7407. streamToDelete = inputStream;
  7408. init();
  7409. }
  7410. ZipFile::ZipFile (const File& file)
  7411. : inputStream (0)
  7412. #if JUCE_DEBUG
  7413. , numOpenStreams (0)
  7414. #endif
  7415. {
  7416. inputSource = new FileInputSource (file);
  7417. init();
  7418. }
  7419. ZipFile::ZipFile (InputSource* const inputSource_)
  7420. : inputStream (0),
  7421. inputSource (inputSource_)
  7422. #if JUCE_DEBUG
  7423. , numOpenStreams (0)
  7424. #endif
  7425. {
  7426. init();
  7427. }
  7428. ZipFile::~ZipFile() throw()
  7429. {
  7430. #if JUCE_DEBUG
  7431. entries.clear();
  7432. // If you hit this assertion, it means you've created a stream to read
  7433. // one of the items in the zipfile, but you've forgotten to delete that
  7434. // stream object before deleting the file.. Streams can't be kept open
  7435. // after the file is deleted because they need to share the input
  7436. // stream that the file uses to read itself.
  7437. jassert (numOpenStreams == 0);
  7438. #endif
  7439. }
  7440. int ZipFile::getNumEntries() const throw()
  7441. {
  7442. return entries.size();
  7443. }
  7444. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const throw()
  7445. {
  7446. ZipEntryInfo* const zei = entries [index];
  7447. return zei != 0 ? &(zei->entry) : 0;
  7448. }
  7449. int ZipFile::getIndexOfFileName (const String& fileName) const throw()
  7450. {
  7451. for (int i = 0; i < entries.size(); ++i)
  7452. if (entries.getUnchecked (i)->entry.filename == fileName)
  7453. return i;
  7454. return -1;
  7455. }
  7456. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const throw()
  7457. {
  7458. return getEntry (getIndexOfFileName (fileName));
  7459. }
  7460. InputStream* ZipFile::createStreamForEntry (const int index)
  7461. {
  7462. ZipEntryInfo* const zei = entries[index];
  7463. InputStream* stream = 0;
  7464. if (zei != 0)
  7465. {
  7466. stream = new ZipInputStream (*this, *zei);
  7467. if (zei->compressed)
  7468. {
  7469. stream = new GZIPDecompressorInputStream (stream, true, true,
  7470. zei->entry.uncompressedSize);
  7471. // (much faster to unzip in big blocks using a buffer..)
  7472. stream = new BufferedInputStream (stream, 32768, true);
  7473. }
  7474. }
  7475. return stream;
  7476. }
  7477. class ZipFile::ZipFilenameComparator
  7478. {
  7479. public:
  7480. int compareElements (const ZipFile::ZipEntryInfo* first, const ZipFile::ZipEntryInfo* second)
  7481. {
  7482. return first->entry.filename.compare (second->entry.filename);
  7483. }
  7484. };
  7485. void ZipFile::sortEntriesByFilename()
  7486. {
  7487. ZipFilenameComparator sorter;
  7488. entries.sort (sorter);
  7489. }
  7490. void ZipFile::init()
  7491. {
  7492. ScopedPointer <InputStream> toDelete;
  7493. InputStream* in = inputStream;
  7494. if (inputSource != 0)
  7495. {
  7496. in = inputSource->createInputStream();
  7497. toDelete = in;
  7498. }
  7499. if (in != 0)
  7500. {
  7501. int numEntries = 0;
  7502. int pos = findEndOfZipEntryTable (in, numEntries);
  7503. if (pos >= 0 && pos < in->getTotalLength())
  7504. {
  7505. const int size = (int) (in->getTotalLength() - pos);
  7506. in->setPosition (pos);
  7507. MemoryBlock headerData;
  7508. if (in->readIntoMemoryBlock (headerData, size) == size)
  7509. {
  7510. pos = 0;
  7511. for (int i = 0; i < numEntries; ++i)
  7512. {
  7513. if (pos + 46 > size)
  7514. break;
  7515. const char* const buffer = static_cast <const char*> (headerData.getData()) + pos;
  7516. const int fileNameLen = ByteOrder::littleEndianShort (buffer + 28);
  7517. if (pos + 46 + fileNameLen > size)
  7518. break;
  7519. ZipEntryInfo* const zei = new ZipEntryInfo();
  7520. zei->entry.filename = String::fromUTF8 (buffer + 46, fileNameLen);
  7521. const int time = ByteOrder::littleEndianShort (buffer + 12);
  7522. const int date = ByteOrder::littleEndianShort (buffer + 14);
  7523. const int year = 1980 + (date >> 9);
  7524. const int month = ((date >> 5) & 15) - 1;
  7525. const int day = date & 31;
  7526. const int hours = time >> 11;
  7527. const int minutes = (time >> 5) & 63;
  7528. const int seconds = (time & 31) << 1;
  7529. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  7530. zei->compressed = ByteOrder::littleEndianShort (buffer + 10) != 0;
  7531. zei->compressedSize = ByteOrder::littleEndianInt (buffer + 20);
  7532. zei->entry.uncompressedSize = ByteOrder::littleEndianInt (buffer + 24);
  7533. zei->streamOffset = ByteOrder::littleEndianInt (buffer + 42);
  7534. entries.add (zei);
  7535. pos += 46 + fileNameLen
  7536. + ByteOrder::littleEndianShort (buffer + 30)
  7537. + ByteOrder::littleEndianShort (buffer + 32);
  7538. }
  7539. }
  7540. }
  7541. }
  7542. }
  7543. int ZipFile::findEndOfZipEntryTable (InputStream* input, int& numEntries)
  7544. {
  7545. BufferedInputStream in (input, 8192, false);
  7546. in.setPosition (in.getTotalLength());
  7547. int64 pos = in.getPosition();
  7548. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  7549. char buffer [32];
  7550. zeromem (buffer, sizeof (buffer));
  7551. while (pos > lowestPos)
  7552. {
  7553. in.setPosition (pos - 22);
  7554. pos = in.getPosition();
  7555. memcpy (buffer + 22, buffer, 4);
  7556. if (in.read (buffer, 22) != 22)
  7557. return 0;
  7558. for (int i = 0; i < 22; ++i)
  7559. {
  7560. if (ByteOrder::littleEndianInt (buffer + i) == 0x06054b50)
  7561. {
  7562. in.setPosition (pos + i);
  7563. in.read (buffer, 22);
  7564. numEntries = ByteOrder::littleEndianShort (buffer + 10);
  7565. return ByteOrder::littleEndianInt (buffer + 16);
  7566. }
  7567. }
  7568. }
  7569. return 0;
  7570. }
  7571. void ZipFile::uncompressTo (const File& targetDirectory,
  7572. const bool shouldOverwriteFiles)
  7573. {
  7574. for (int i = 0; i < entries.size(); ++i)
  7575. {
  7576. const ZipEntry& zei = entries.getUnchecked(i)->entry;
  7577. const File targetFile (targetDirectory.getChildFile (zei.filename));
  7578. if (zei.filename.endsWithChar ('/'))
  7579. {
  7580. targetFile.createDirectory(); // (entry is a directory, not a file)
  7581. }
  7582. else
  7583. {
  7584. ScopedPointer <InputStream> in (createStreamForEntry (i));
  7585. if (in != 0)
  7586. {
  7587. if (shouldOverwriteFiles)
  7588. targetFile.deleteFile();
  7589. if ((! targetFile.exists())
  7590. && targetFile.getParentDirectory().createDirectory())
  7591. {
  7592. ScopedPointer <FileOutputStream> out (targetFile.createOutputStream());
  7593. if (out != 0)
  7594. {
  7595. out->writeFromInputStream (*in, -1);
  7596. out = 0;
  7597. targetFile.setCreationTime (zei.fileTime);
  7598. targetFile.setLastModificationTime (zei.fileTime);
  7599. targetFile.setLastAccessTime (zei.fileTime);
  7600. }
  7601. }
  7602. }
  7603. }
  7604. }
  7605. }
  7606. END_JUCE_NAMESPACE
  7607. /*** End of inlined file: juce_ZipFile.cpp ***/
  7608. /*** Start of inlined file: juce_CharacterFunctions.cpp ***/
  7609. #if JUCE_MSVC
  7610. #pragma warning (push)
  7611. #pragma warning (disable: 4514 4996)
  7612. #endif
  7613. #include <cwctype>
  7614. #include <cctype>
  7615. #include <ctime>
  7616. BEGIN_JUCE_NAMESPACE
  7617. int CharacterFunctions::length (const char* const s) throw()
  7618. {
  7619. return (int) strlen (s);
  7620. }
  7621. int CharacterFunctions::length (const juce_wchar* const s) throw()
  7622. {
  7623. return (int) wcslen (s);
  7624. }
  7625. void CharacterFunctions::copy (char* dest, const char* src, const int maxChars) throw()
  7626. {
  7627. strncpy (dest, src, maxChars);
  7628. }
  7629. void CharacterFunctions::copy (juce_wchar* dest, const juce_wchar* src, int maxChars) throw()
  7630. {
  7631. wcsncpy (dest, src, maxChars);
  7632. }
  7633. void CharacterFunctions::copy (juce_wchar* dest, const char* src, const int maxChars) throw()
  7634. {
  7635. mbstowcs (dest, src, maxChars);
  7636. }
  7637. void CharacterFunctions::copy (char* dest, const juce_wchar* src, const int maxChars) throw()
  7638. {
  7639. wcstombs (dest, src, maxChars);
  7640. }
  7641. int CharacterFunctions::bytesRequiredForCopy (const juce_wchar* src) throw()
  7642. {
  7643. return (int) wcstombs (0, src, 0);
  7644. }
  7645. void CharacterFunctions::append (char* dest, const char* src) throw()
  7646. {
  7647. strcat (dest, src);
  7648. }
  7649. void CharacterFunctions::append (juce_wchar* dest, const juce_wchar* src) throw()
  7650. {
  7651. wcscat (dest, src);
  7652. }
  7653. int CharacterFunctions::compare (const char* const s1, const char* const s2) throw()
  7654. {
  7655. return strcmp (s1, s2);
  7656. }
  7657. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2) throw()
  7658. {
  7659. jassert (s1 != 0 && s2 != 0);
  7660. return wcscmp (s1, s2);
  7661. }
  7662. int CharacterFunctions::compare (const char* const s1, const char* const s2, const int maxChars) throw()
  7663. {
  7664. jassert (s1 != 0 && s2 != 0);
  7665. return strncmp (s1, s2, maxChars);
  7666. }
  7667. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  7668. {
  7669. jassert (s1 != 0 && s2 != 0);
  7670. return wcsncmp (s1, s2, maxChars);
  7671. }
  7672. int CharacterFunctions::compare (const juce_wchar* s1, const char* s2) throw()
  7673. {
  7674. jassert (s1 != 0 && s2 != 0);
  7675. for (;;)
  7676. {
  7677. const int diff = (int) (*s1 - (juce_wchar) (unsigned char) *s2);
  7678. if (diff != 0)
  7679. return diff;
  7680. else if (*s1 == 0)
  7681. break;
  7682. ++s1;
  7683. ++s2;
  7684. }
  7685. return 0;
  7686. }
  7687. int CharacterFunctions::compare (const char* s1, const juce_wchar* s2) throw()
  7688. {
  7689. return -compare (s2, s1);
  7690. }
  7691. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2) throw()
  7692. {
  7693. jassert (s1 != 0 && s2 != 0);
  7694. #if JUCE_WINDOWS
  7695. return stricmp (s1, s2);
  7696. #else
  7697. return strcasecmp (s1, s2);
  7698. #endif
  7699. }
  7700. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw()
  7701. {
  7702. jassert (s1 != 0 && s2 != 0);
  7703. #if JUCE_WINDOWS
  7704. return _wcsicmp (s1, s2);
  7705. #else
  7706. for (;;)
  7707. {
  7708. if (*s1 != *s2)
  7709. {
  7710. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  7711. if (diff != 0)
  7712. return diff < 0 ? -1 : 1;
  7713. }
  7714. else if (*s1 == 0)
  7715. break;
  7716. ++s1;
  7717. ++s2;
  7718. }
  7719. return 0;
  7720. #endif
  7721. }
  7722. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const char* s2) throw()
  7723. {
  7724. jassert (s1 != 0 && s2 != 0);
  7725. for (;;)
  7726. {
  7727. if (*s1 != *s2)
  7728. {
  7729. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  7730. if (diff != 0)
  7731. return diff < 0 ? -1 : 1;
  7732. }
  7733. else if (*s1 == 0)
  7734. break;
  7735. ++s1;
  7736. ++s2;
  7737. }
  7738. return 0;
  7739. }
  7740. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw()
  7741. {
  7742. jassert (s1 != 0 && s2 != 0);
  7743. #if JUCE_WINDOWS
  7744. return strnicmp (s1, s2, maxChars);
  7745. #else
  7746. return strncasecmp (s1, s2, maxChars);
  7747. #endif
  7748. }
  7749. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  7750. {
  7751. jassert (s1 != 0 && s2 != 0);
  7752. #if JUCE_WINDOWS
  7753. return _wcsnicmp (s1, s2, maxChars);
  7754. #else
  7755. while (--maxChars >= 0)
  7756. {
  7757. if (*s1 != *s2)
  7758. {
  7759. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  7760. if (diff != 0)
  7761. return diff < 0 ? -1 : 1;
  7762. }
  7763. else if (*s1 == 0)
  7764. break;
  7765. ++s1;
  7766. ++s2;
  7767. }
  7768. return 0;
  7769. #endif
  7770. }
  7771. const char* CharacterFunctions::find (const char* const haystack, const char* const needle) throw()
  7772. {
  7773. return strstr (haystack, needle);
  7774. }
  7775. const juce_wchar* CharacterFunctions::find (const juce_wchar* haystack, const juce_wchar* const needle) throw()
  7776. {
  7777. return wcsstr (haystack, needle);
  7778. }
  7779. int CharacterFunctions::indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw()
  7780. {
  7781. if (haystack != 0)
  7782. {
  7783. int i = 0;
  7784. if (ignoreCase)
  7785. {
  7786. const char n1 = toLowerCase (needle);
  7787. const char n2 = toUpperCase (needle);
  7788. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  7789. {
  7790. while (haystack[i] != 0)
  7791. {
  7792. if (haystack[i] == n1 || haystack[i] == n2)
  7793. return i;
  7794. ++i;
  7795. }
  7796. return -1;
  7797. }
  7798. jassert (n1 == needle);
  7799. }
  7800. while (haystack[i] != 0)
  7801. {
  7802. if (haystack[i] == needle)
  7803. return i;
  7804. ++i;
  7805. }
  7806. }
  7807. return -1;
  7808. }
  7809. int CharacterFunctions::indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw()
  7810. {
  7811. if (haystack != 0)
  7812. {
  7813. int i = 0;
  7814. if (ignoreCase)
  7815. {
  7816. const juce_wchar n1 = toLowerCase (needle);
  7817. const juce_wchar n2 = toUpperCase (needle);
  7818. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  7819. {
  7820. while (haystack[i] != 0)
  7821. {
  7822. if (haystack[i] == n1 || haystack[i] == n2)
  7823. return i;
  7824. ++i;
  7825. }
  7826. return -1;
  7827. }
  7828. jassert (n1 == needle);
  7829. }
  7830. while (haystack[i] != 0)
  7831. {
  7832. if (haystack[i] == needle)
  7833. return i;
  7834. ++i;
  7835. }
  7836. }
  7837. return -1;
  7838. }
  7839. int CharacterFunctions::indexOfCharFast (const char* const haystack, const char needle) throw()
  7840. {
  7841. jassert (haystack != 0);
  7842. int i = 0;
  7843. while (haystack[i] != 0)
  7844. {
  7845. if (haystack[i] == needle)
  7846. return i;
  7847. ++i;
  7848. }
  7849. return -1;
  7850. }
  7851. int CharacterFunctions::indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw()
  7852. {
  7853. jassert (haystack != 0);
  7854. int i = 0;
  7855. while (haystack[i] != 0)
  7856. {
  7857. if (haystack[i] == needle)
  7858. return i;
  7859. ++i;
  7860. }
  7861. return -1;
  7862. }
  7863. int CharacterFunctions::getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw()
  7864. {
  7865. return allowedChars == 0 ? 0 : (int) strspn (text, allowedChars);
  7866. }
  7867. int CharacterFunctions::getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw()
  7868. {
  7869. if (allowedChars == 0)
  7870. return 0;
  7871. int i = 0;
  7872. for (;;)
  7873. {
  7874. if (indexOfCharFast (allowedChars, text[i]) < 0)
  7875. break;
  7876. ++i;
  7877. }
  7878. return i;
  7879. }
  7880. int CharacterFunctions::ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw()
  7881. {
  7882. return (int) strftime (dest, maxChars, format, tm);
  7883. }
  7884. int CharacterFunctions::ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw()
  7885. {
  7886. return (int) wcsftime (dest, maxChars, format, tm);
  7887. }
  7888. int CharacterFunctions::getIntValue (const char* const s) throw()
  7889. {
  7890. return atoi (s);
  7891. }
  7892. int CharacterFunctions::getIntValue (const juce_wchar* s) throw()
  7893. {
  7894. #if JUCE_WINDOWS
  7895. return _wtoi (s);
  7896. #else
  7897. int v = 0;
  7898. while (isWhitespace (*s))
  7899. ++s;
  7900. const bool isNeg = *s == '-';
  7901. if (isNeg)
  7902. ++s;
  7903. for (;;)
  7904. {
  7905. const wchar_t c = *s++;
  7906. if (c >= '0' && c <= '9')
  7907. v = v * 10 + (int) (c - '0');
  7908. else
  7909. break;
  7910. }
  7911. return isNeg ? -v : v;
  7912. #endif
  7913. }
  7914. int64 CharacterFunctions::getInt64Value (const char* s) throw()
  7915. {
  7916. #if JUCE_LINUX
  7917. return atoll (s);
  7918. #elif JUCE_WINDOWS
  7919. return _atoi64 (s);
  7920. #else
  7921. int64 v = 0;
  7922. while (isWhitespace (*s))
  7923. ++s;
  7924. const bool isNeg = *s == '-';
  7925. if (isNeg)
  7926. ++s;
  7927. for (;;)
  7928. {
  7929. const char c = *s++;
  7930. if (c >= '0' && c <= '9')
  7931. v = v * 10 + (int64) (c - '0');
  7932. else
  7933. break;
  7934. }
  7935. return isNeg ? -v : v;
  7936. #endif
  7937. }
  7938. int64 CharacterFunctions::getInt64Value (const juce_wchar* s) throw()
  7939. {
  7940. #if JUCE_WINDOWS
  7941. return _wtoi64 (s);
  7942. #else
  7943. int64 v = 0;
  7944. while (isWhitespace (*s))
  7945. ++s;
  7946. const bool isNeg = *s == '-';
  7947. if (isNeg)
  7948. ++s;
  7949. for (;;)
  7950. {
  7951. const juce_wchar c = *s++;
  7952. if (c >= '0' && c <= '9')
  7953. v = v * 10 + (int64) (c - '0');
  7954. else
  7955. break;
  7956. }
  7957. return isNeg ? -v : v;
  7958. #endif
  7959. }
  7960. static double juce_mulexp10 (const double value, int exponent) throw()
  7961. {
  7962. if (exponent == 0)
  7963. return value;
  7964. if (value == 0)
  7965. return 0;
  7966. const bool negative = (exponent < 0);
  7967. if (negative)
  7968. exponent = -exponent;
  7969. double result = 1.0, power = 10.0;
  7970. for (int bit = 1; exponent != 0; bit <<= 1)
  7971. {
  7972. if ((exponent & bit) != 0)
  7973. {
  7974. exponent ^= bit;
  7975. result *= power;
  7976. if (exponent == 0)
  7977. break;
  7978. }
  7979. power *= power;
  7980. }
  7981. return negative ? (value / result) : (value * result);
  7982. }
  7983. template <class CharType>
  7984. double juce_atof (const CharType* const original) throw()
  7985. {
  7986. double result[3] = { 0, 0, 0 }, accumulator[2] = { 0, 0 };
  7987. int exponentAdjustment[2] = { 0, 0 }, exponentAccumulator[2] = { -1, -1 };
  7988. int exponent = 0, decPointIndex = 0, digit = 0;
  7989. int lastDigit = 0, numSignificantDigits = 0;
  7990. bool isNegative = false, digitsFound = false;
  7991. const int maxSignificantDigits = 15 + 2;
  7992. const CharType* s = original;
  7993. while (CharacterFunctions::isWhitespace (*s))
  7994. ++s;
  7995. switch (*s)
  7996. {
  7997. case '-': isNegative = true; // fall-through..
  7998. case '+': ++s;
  7999. }
  8000. if (*s == 'n' || *s == 'N' || *s == 'i' || *s == 'I')
  8001. return atof (String (original).toUTF8()); // Let the c library deal with NAN and INF
  8002. for (;;)
  8003. {
  8004. if (CharacterFunctions::isDigit (*s))
  8005. {
  8006. lastDigit = digit;
  8007. digit = *s++ - '0';
  8008. digitsFound = true;
  8009. if (decPointIndex != 0)
  8010. exponentAdjustment[1]++;
  8011. if (numSignificantDigits == 0 && digit == 0)
  8012. continue;
  8013. if (++numSignificantDigits > maxSignificantDigits)
  8014. {
  8015. if (digit > 5)
  8016. ++accumulator [decPointIndex];
  8017. else if (digit == 5 && (lastDigit & 1) != 0)
  8018. ++accumulator [decPointIndex];
  8019. if (decPointIndex > 0)
  8020. exponentAdjustment[1]--;
  8021. else
  8022. exponentAdjustment[0]++;
  8023. while (CharacterFunctions::isDigit (*s))
  8024. {
  8025. ++s;
  8026. if (decPointIndex == 0)
  8027. exponentAdjustment[0]++;
  8028. }
  8029. }
  8030. else
  8031. {
  8032. const double maxAccumulatorValue = (double) ((std::numeric_limits<unsigned int>::max() - 9) / 10);
  8033. if (accumulator [decPointIndex] > maxAccumulatorValue)
  8034. {
  8035. result [decPointIndex] = juce_mulexp10 (result [decPointIndex], exponentAccumulator [decPointIndex])
  8036. + accumulator [decPointIndex];
  8037. accumulator [decPointIndex] = 0;
  8038. exponentAccumulator [decPointIndex] = 0;
  8039. }
  8040. accumulator [decPointIndex] = accumulator[decPointIndex] * 10 + digit;
  8041. exponentAccumulator [decPointIndex]++;
  8042. }
  8043. }
  8044. else if (decPointIndex == 0 && *s == '.')
  8045. {
  8046. ++s;
  8047. decPointIndex = 1;
  8048. if (numSignificantDigits > maxSignificantDigits)
  8049. {
  8050. while (CharacterFunctions::isDigit (*s))
  8051. ++s;
  8052. break;
  8053. }
  8054. }
  8055. else
  8056. {
  8057. break;
  8058. }
  8059. }
  8060. result[0] = juce_mulexp10 (result[0], exponentAccumulator[0]) + accumulator[0];
  8061. if (decPointIndex != 0)
  8062. result[1] = juce_mulexp10 (result[1], exponentAccumulator[1]) + accumulator[1];
  8063. if ((*s == 'e' || *s == 'E') && digitsFound)
  8064. {
  8065. bool negativeExponent = false;
  8066. switch (*++s)
  8067. {
  8068. case '-': negativeExponent = true; // fall-through..
  8069. case '+': ++s;
  8070. }
  8071. while (CharacterFunctions::isDigit (*s))
  8072. exponent = (exponent * 10) + (*s++ - '0');
  8073. if (negativeExponent)
  8074. exponent = -exponent;
  8075. }
  8076. double r = juce_mulexp10 (result[0], exponent + exponentAdjustment[0]);
  8077. if (decPointIndex != 0)
  8078. r += juce_mulexp10 (result[1], exponent - exponentAdjustment[1]);
  8079. return isNegative ? -r : r;
  8080. }
  8081. double CharacterFunctions::getDoubleValue (const char* const s) throw()
  8082. {
  8083. return juce_atof <char> (s);
  8084. }
  8085. double CharacterFunctions::getDoubleValue (const juce_wchar* const s) throw()
  8086. {
  8087. return juce_atof <juce_wchar> (s);
  8088. }
  8089. char CharacterFunctions::toUpperCase (const char character) throw()
  8090. {
  8091. return (char) toupper (character);
  8092. }
  8093. juce_wchar CharacterFunctions::toUpperCase (const juce_wchar character) throw()
  8094. {
  8095. return towupper (character);
  8096. }
  8097. void CharacterFunctions::toUpperCase (char* s) throw()
  8098. {
  8099. #if JUCE_WINDOWS
  8100. strupr (s);
  8101. #else
  8102. while (*s != 0)
  8103. {
  8104. *s = toUpperCase (*s);
  8105. ++s;
  8106. }
  8107. #endif
  8108. }
  8109. void CharacterFunctions::toUpperCase (juce_wchar* s) throw()
  8110. {
  8111. #if JUCE_WINDOWS
  8112. _wcsupr (s);
  8113. #else
  8114. while (*s != 0)
  8115. {
  8116. *s = toUpperCase (*s);
  8117. ++s;
  8118. }
  8119. #endif
  8120. }
  8121. bool CharacterFunctions::isUpperCase (const char character) throw()
  8122. {
  8123. return isupper (character) != 0;
  8124. }
  8125. bool CharacterFunctions::isUpperCase (const juce_wchar character) throw()
  8126. {
  8127. #if JUCE_WINDOWS
  8128. return iswupper (character) != 0;
  8129. #else
  8130. return toLowerCase (character) != character;
  8131. #endif
  8132. }
  8133. char CharacterFunctions::toLowerCase (const char character) throw()
  8134. {
  8135. return (char) tolower (character);
  8136. }
  8137. juce_wchar CharacterFunctions::toLowerCase (const juce_wchar character) throw()
  8138. {
  8139. return towlower (character);
  8140. }
  8141. void CharacterFunctions::toLowerCase (char* s) throw()
  8142. {
  8143. #if JUCE_WINDOWS
  8144. strlwr (s);
  8145. #else
  8146. while (*s != 0)
  8147. {
  8148. *s = toLowerCase (*s);
  8149. ++s;
  8150. }
  8151. #endif
  8152. }
  8153. void CharacterFunctions::toLowerCase (juce_wchar* s) throw()
  8154. {
  8155. #if JUCE_WINDOWS
  8156. _wcslwr (s);
  8157. #else
  8158. while (*s != 0)
  8159. {
  8160. *s = toLowerCase (*s);
  8161. ++s;
  8162. }
  8163. #endif
  8164. }
  8165. bool CharacterFunctions::isLowerCase (const char character) throw()
  8166. {
  8167. return islower (character) != 0;
  8168. }
  8169. bool CharacterFunctions::isLowerCase (const juce_wchar character) throw()
  8170. {
  8171. #if JUCE_WINDOWS
  8172. return iswlower (character) != 0;
  8173. #else
  8174. return toUpperCase (character) != character;
  8175. #endif
  8176. }
  8177. bool CharacterFunctions::isWhitespace (const char character) throw()
  8178. {
  8179. return character == ' ' || (character <= 13 && character >= 9);
  8180. }
  8181. bool CharacterFunctions::isWhitespace (const juce_wchar character) throw()
  8182. {
  8183. return iswspace (character) != 0;
  8184. }
  8185. bool CharacterFunctions::isDigit (const char character) throw()
  8186. {
  8187. return (character >= '0' && character <= '9');
  8188. }
  8189. bool CharacterFunctions::isDigit (const juce_wchar character) throw()
  8190. {
  8191. return iswdigit (character) != 0;
  8192. }
  8193. bool CharacterFunctions::isLetter (const char character) throw()
  8194. {
  8195. return (character >= 'a' && character <= 'z')
  8196. || (character >= 'A' && character <= 'Z');
  8197. }
  8198. bool CharacterFunctions::isLetter (const juce_wchar character) throw()
  8199. {
  8200. return iswalpha (character) != 0;
  8201. }
  8202. bool CharacterFunctions::isLetterOrDigit (const char character) throw()
  8203. {
  8204. return (character >= 'a' && character <= 'z')
  8205. || (character >= 'A' && character <= 'Z')
  8206. || (character >= '0' && character <= '9');
  8207. }
  8208. bool CharacterFunctions::isLetterOrDigit (const juce_wchar character) throw()
  8209. {
  8210. return iswalnum (character) != 0;
  8211. }
  8212. int CharacterFunctions::getHexDigitValue (const juce_wchar digit) throw()
  8213. {
  8214. unsigned int d = digit - '0';
  8215. if (d < (unsigned int) 10)
  8216. return (int) d;
  8217. d += (unsigned int) ('0' - 'a');
  8218. if (d < (unsigned int) 6)
  8219. return (int) d + 10;
  8220. d += (unsigned int) ('a' - 'A');
  8221. if (d < (unsigned int) 6)
  8222. return (int) d + 10;
  8223. return -1;
  8224. }
  8225. #if JUCE_MSVC
  8226. #pragma warning (pop)
  8227. #endif
  8228. END_JUCE_NAMESPACE
  8229. /*** End of inlined file: juce_CharacterFunctions.cpp ***/
  8230. /*** Start of inlined file: juce_LocalisedStrings.cpp ***/
  8231. BEGIN_JUCE_NAMESPACE
  8232. LocalisedStrings::LocalisedStrings (const String& fileContents)
  8233. {
  8234. loadFromText (fileContents);
  8235. }
  8236. LocalisedStrings::LocalisedStrings (const File& fileToLoad)
  8237. {
  8238. loadFromText (fileToLoad.loadFileAsString());
  8239. }
  8240. LocalisedStrings::~LocalisedStrings()
  8241. {
  8242. }
  8243. const String LocalisedStrings::translate (const String& text) const
  8244. {
  8245. return translations.getValue (text, text);
  8246. }
  8247. static int findCloseQuote (const String& text, int startPos)
  8248. {
  8249. juce_wchar lastChar = 0;
  8250. for (;;)
  8251. {
  8252. const juce_wchar c = text [startPos];
  8253. if (c == 0 || (c == '"' && lastChar != '\\'))
  8254. break;
  8255. lastChar = c;
  8256. ++startPos;
  8257. }
  8258. return startPos;
  8259. }
  8260. static const String unescapeString (const String& s)
  8261. {
  8262. return s.replace ("\\\"", "\"")
  8263. .replace ("\\\'", "\'")
  8264. .replace ("\\t", "\t")
  8265. .replace ("\\r", "\r")
  8266. .replace ("\\n", "\n");
  8267. }
  8268. void LocalisedStrings::loadFromText (const String& fileContents)
  8269. {
  8270. StringArray lines;
  8271. lines.addLines (fileContents);
  8272. for (int i = 0; i < lines.size(); ++i)
  8273. {
  8274. String line (lines[i].trim());
  8275. if (line.startsWithChar ('"'))
  8276. {
  8277. int closeQuote = findCloseQuote (line, 1);
  8278. const String originalText (unescapeString (line.substring (1, closeQuote)));
  8279. if (originalText.isNotEmpty())
  8280. {
  8281. const int openingQuote = findCloseQuote (line, closeQuote + 1);
  8282. closeQuote = findCloseQuote (line, openingQuote + 1);
  8283. const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));
  8284. if (newText.isNotEmpty())
  8285. translations.set (originalText, newText);
  8286. }
  8287. }
  8288. else if (line.startsWithIgnoreCase ("language:"))
  8289. {
  8290. languageName = line.substring (9).trim();
  8291. }
  8292. else if (line.startsWithIgnoreCase ("countries:"))
  8293. {
  8294. countryCodes.addTokens (line.substring (10).trim(), true);
  8295. countryCodes.trim();
  8296. countryCodes.removeEmptyStrings();
  8297. }
  8298. }
  8299. }
  8300. void LocalisedStrings::setIgnoresCase (const bool shouldIgnoreCase)
  8301. {
  8302. translations.setIgnoresCase (shouldIgnoreCase);
  8303. }
  8304. static CriticalSection currentMappingsLock;
  8305. static LocalisedStrings* currentMappings = 0;
  8306. void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations)
  8307. {
  8308. const ScopedLock sl (currentMappingsLock);
  8309. delete currentMappings;
  8310. currentMappings = newTranslations;
  8311. }
  8312. LocalisedStrings* LocalisedStrings::getCurrentMappings()
  8313. {
  8314. return currentMappings;
  8315. }
  8316. const String LocalisedStrings::translateWithCurrentMappings (const String& text)
  8317. {
  8318. const ScopedLock sl (currentMappingsLock);
  8319. if (currentMappings != 0)
  8320. return currentMappings->translate (text);
  8321. return text;
  8322. }
  8323. const String LocalisedStrings::translateWithCurrentMappings (const char* text)
  8324. {
  8325. return translateWithCurrentMappings (String (text));
  8326. }
  8327. END_JUCE_NAMESPACE
  8328. /*** End of inlined file: juce_LocalisedStrings.cpp ***/
  8329. /*** Start of inlined file: juce_String.cpp ***/
  8330. #if JUCE_MSVC
  8331. #pragma warning (push)
  8332. #pragma warning (disable: 4514)
  8333. #endif
  8334. #include <locale>
  8335. BEGIN_JUCE_NAMESPACE
  8336. #if JUCE_MSVC
  8337. #pragma warning (pop)
  8338. #endif
  8339. #if defined (JUCE_STRINGS_ARE_UNICODE) && ! JUCE_STRINGS_ARE_UNICODE
  8340. #error "JUCE_STRINGS_ARE_UNICODE is deprecated! All strings are now unicode by default."
  8341. #endif
  8342. class StringHolder
  8343. {
  8344. public:
  8345. StringHolder()
  8346. : refCount (0x3fffffff), allocatedNumChars (0)
  8347. {
  8348. text[0] = 0;
  8349. }
  8350. static juce_wchar* createUninitialised (const size_t numChars)
  8351. {
  8352. StringHolder* const s = reinterpret_cast <StringHolder*> (new char [sizeof (StringHolder) + numChars * sizeof (juce_wchar)]);
  8353. s->refCount.value = 0;
  8354. s->allocatedNumChars = numChars;
  8355. return &(s->text[0]);
  8356. }
  8357. static juce_wchar* createCopy (const juce_wchar* const src, const size_t numChars)
  8358. {
  8359. juce_wchar* const dest = createUninitialised (numChars);
  8360. copyChars (dest, src, numChars);
  8361. return dest;
  8362. }
  8363. static juce_wchar* createCopy (const char* const src, const size_t numChars)
  8364. {
  8365. juce_wchar* const dest = createUninitialised (numChars);
  8366. CharacterFunctions::copy (dest, src, (int) numChars);
  8367. dest [numChars] = 0;
  8368. return dest;
  8369. }
  8370. static inline juce_wchar* getEmpty() throw()
  8371. {
  8372. return &(empty.text[0]);
  8373. }
  8374. static void retain (juce_wchar* const text) throw()
  8375. {
  8376. ++(bufferFromText (text)->refCount);
  8377. }
  8378. static inline void release (StringHolder* const b) throw()
  8379. {
  8380. if (--(b->refCount) == -1 && b != &empty)
  8381. delete[] reinterpret_cast <char*> (b);
  8382. }
  8383. static void release (juce_wchar* const text) throw()
  8384. {
  8385. release (bufferFromText (text));
  8386. }
  8387. static juce_wchar* makeUnique (juce_wchar* const text)
  8388. {
  8389. StringHolder* const b = bufferFromText (text);
  8390. if (b->refCount.get() <= 0)
  8391. return text;
  8392. juce_wchar* const newText = createCopy (text, b->allocatedNumChars);
  8393. release (b);
  8394. return newText;
  8395. }
  8396. static juce_wchar* makeUniqueWithSize (juce_wchar* const text, size_t numChars)
  8397. {
  8398. StringHolder* const b = bufferFromText (text);
  8399. if (b->refCount.get() <= 0 && b->allocatedNumChars >= numChars)
  8400. return text;
  8401. juce_wchar* const newText = createUninitialised (jmax (b->allocatedNumChars, numChars));
  8402. copyChars (newText, text, b->allocatedNumChars);
  8403. release (b);
  8404. return newText;
  8405. }
  8406. static size_t getAllocatedNumChars (juce_wchar* const text) throw()
  8407. {
  8408. return bufferFromText (text)->allocatedNumChars;
  8409. }
  8410. static void copyChars (juce_wchar* const dest, const juce_wchar* const src, const size_t numChars) throw()
  8411. {
  8412. memcpy (dest, src, numChars * sizeof (juce_wchar));
  8413. dest [numChars] = 0;
  8414. }
  8415. Atomic<int> refCount;
  8416. size_t allocatedNumChars;
  8417. juce_wchar text[1];
  8418. static StringHolder empty;
  8419. private:
  8420. static inline StringHolder* bufferFromText (void* const text) throw()
  8421. {
  8422. // (Can't use offsetof() here because of warnings about this not being a POD)
  8423. return reinterpret_cast <StringHolder*> (static_cast <char*> (text)
  8424. - (reinterpret_cast <size_t> (reinterpret_cast <StringHolder*> (1)->text) - 1));
  8425. }
  8426. };
  8427. StringHolder StringHolder::empty;
  8428. const String String::empty;
  8429. void String::createInternal (const juce_wchar* const t, const size_t numChars)
  8430. {
  8431. jassert (t[numChars] == 0); // must have a null terminator
  8432. text = StringHolder::createCopy (t, numChars);
  8433. }
  8434. void String::appendInternal (const juce_wchar* const newText, const int numExtraChars)
  8435. {
  8436. if (numExtraChars > 0)
  8437. {
  8438. const int oldLen = length();
  8439. const int newTotalLen = oldLen + numExtraChars;
  8440. text = StringHolder::makeUniqueWithSize (text, newTotalLen);
  8441. StringHolder::copyChars (text + oldLen, newText, numExtraChars);
  8442. }
  8443. }
  8444. void String::preallocateStorage (const size_t numChars)
  8445. {
  8446. text = StringHolder::makeUniqueWithSize (text, numChars);
  8447. }
  8448. String::String() throw()
  8449. : text (StringHolder::getEmpty())
  8450. {
  8451. }
  8452. String::~String() throw()
  8453. {
  8454. StringHolder::release (text);
  8455. }
  8456. String::String (const String& other) throw()
  8457. : text (other.text)
  8458. {
  8459. StringHolder::retain (text);
  8460. }
  8461. void String::swapWith (String& other) throw()
  8462. {
  8463. swapVariables (text, other.text);
  8464. }
  8465. String& String::operator= (const String& other) throw()
  8466. {
  8467. juce_wchar* const newText = other.text;
  8468. StringHolder::retain (newText);
  8469. StringHolder::release (reinterpret_cast <Atomic<juce_wchar*>*> (&text)->exchange (newText));
  8470. return *this;
  8471. }
  8472. String::String (const size_t numChars, const int /*dummyVariable*/)
  8473. : text (StringHolder::createUninitialised (numChars))
  8474. {
  8475. }
  8476. String::String (const String& stringToCopy, const size_t charsToAllocate)
  8477. {
  8478. const size_t otherSize = StringHolder::getAllocatedNumChars (stringToCopy.text);
  8479. text = StringHolder::createUninitialised (jmax (charsToAllocate, otherSize));
  8480. StringHolder::copyChars (text, stringToCopy.text, otherSize);
  8481. }
  8482. String::String (const char* const t)
  8483. {
  8484. if (t != 0 && *t != 0)
  8485. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  8486. else
  8487. text = StringHolder::getEmpty();
  8488. }
  8489. String::String (const juce_wchar* const t)
  8490. {
  8491. if (t != 0 && *t != 0)
  8492. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  8493. else
  8494. text = StringHolder::getEmpty();
  8495. }
  8496. String::String (const char* const t, const size_t maxChars)
  8497. {
  8498. int i;
  8499. for (i = 0; (size_t) i < maxChars; ++i)
  8500. if (t[i] == 0)
  8501. break;
  8502. if (i > 0)
  8503. text = StringHolder::createCopy (t, i);
  8504. else
  8505. text = StringHolder::getEmpty();
  8506. }
  8507. String::String (const juce_wchar* const t, const size_t maxChars)
  8508. {
  8509. int i;
  8510. for (i = 0; (size_t) i < maxChars; ++i)
  8511. if (t[i] == 0)
  8512. break;
  8513. if (i > 0)
  8514. text = StringHolder::createCopy (t, i);
  8515. else
  8516. text = StringHolder::getEmpty();
  8517. }
  8518. const String String::charToString (const juce_wchar character)
  8519. {
  8520. String result ((size_t) 1, (int) 0);
  8521. result.text[0] = character;
  8522. result.text[1] = 0;
  8523. return result;
  8524. }
  8525. namespace NumberToStringConverters
  8526. {
  8527. // pass in a pointer to the END of a buffer..
  8528. static juce_wchar* int64ToString (juce_wchar* t, const int64 n) throw()
  8529. {
  8530. *--t = 0;
  8531. int64 v = (n >= 0) ? n : -n;
  8532. do
  8533. {
  8534. *--t = (juce_wchar) ('0' + (int) (v % 10));
  8535. v /= 10;
  8536. } while (v > 0);
  8537. if (n < 0)
  8538. *--t = '-';
  8539. return t;
  8540. }
  8541. static juce_wchar* uint64ToString (juce_wchar* t, int64 v) throw()
  8542. {
  8543. *--t = 0;
  8544. do
  8545. {
  8546. *--t = (juce_wchar) ('0' + (int) (v % 10));
  8547. v /= 10;
  8548. } while (v > 0);
  8549. return t;
  8550. }
  8551. static juce_wchar* intToString (juce_wchar* t, const int n) throw()
  8552. {
  8553. if (n == (int) 0x80000000) // (would cause an overflow)
  8554. return int64ToString (t, n);
  8555. *--t = 0;
  8556. int v = abs (n);
  8557. do
  8558. {
  8559. *--t = (juce_wchar) ('0' + (v % 10));
  8560. v /= 10;
  8561. } while (v > 0);
  8562. if (n < 0)
  8563. *--t = '-';
  8564. return t;
  8565. }
  8566. static juce_wchar* uintToString (juce_wchar* t, unsigned int v) throw()
  8567. {
  8568. *--t = 0;
  8569. do
  8570. {
  8571. *--t = (juce_wchar) ('0' + (v % 10));
  8572. v /= 10;
  8573. } while (v > 0);
  8574. return t;
  8575. }
  8576. static juce_wchar getDecimalPoint()
  8577. {
  8578. #if JUCE_WINDOWS && _MSC_VER < 1400
  8579. static juce_wchar dp = std::_USE (std::locale(), std::numpunct <wchar_t>).decimal_point();
  8580. #else
  8581. static juce_wchar dp = std::use_facet <std::numpunct <wchar_t> > (std::locale()).decimal_point();
  8582. #endif
  8583. return dp;
  8584. }
  8585. static juce_wchar* doubleToString (juce_wchar* buffer, int numChars, double n, int numDecPlaces, size_t& len) throw()
  8586. {
  8587. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  8588. {
  8589. juce_wchar* const end = buffer + numChars;
  8590. juce_wchar* t = end;
  8591. int64 v = (int64) (pow (10.0, numDecPlaces) * std::abs (n) + 0.5);
  8592. *--t = (juce_wchar) 0;
  8593. while (numDecPlaces >= 0 || v > 0)
  8594. {
  8595. if (numDecPlaces == 0)
  8596. *--t = getDecimalPoint();
  8597. *--t = (juce_wchar) ('0' + (v % 10));
  8598. v /= 10;
  8599. --numDecPlaces;
  8600. }
  8601. if (n < 0)
  8602. *--t = '-';
  8603. len = end - t - 1;
  8604. return t;
  8605. }
  8606. else
  8607. {
  8608. #if JUCE_WINDOWS
  8609. #if _MSC_VER <= 1400
  8610. len = _snwprintf (buffer, numChars, L"%.9g", n);
  8611. #else
  8612. len = _snwprintf_s (buffer, numChars, _TRUNCATE, L"%.9g", n);
  8613. #endif
  8614. #else
  8615. len = swprintf (buffer, numChars, L"%.9g", n);
  8616. #endif
  8617. return buffer;
  8618. }
  8619. }
  8620. }
  8621. String::String (const int number)
  8622. {
  8623. juce_wchar buffer [16];
  8624. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8625. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  8626. createInternal (start, end - start - 1);
  8627. }
  8628. String::String (const unsigned int number)
  8629. {
  8630. juce_wchar buffer [16];
  8631. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8632. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  8633. createInternal (start, end - start - 1);
  8634. }
  8635. String::String (const short number)
  8636. {
  8637. juce_wchar buffer [16];
  8638. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8639. juce_wchar* const start = NumberToStringConverters::intToString (end, (int) number);
  8640. createInternal (start, end - start - 1);
  8641. }
  8642. String::String (const unsigned short number)
  8643. {
  8644. juce_wchar buffer [16];
  8645. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8646. juce_wchar* const start = NumberToStringConverters::uintToString (end, (unsigned int) number);
  8647. createInternal (start, end - start - 1);
  8648. }
  8649. String::String (const int64 number)
  8650. {
  8651. juce_wchar buffer [32];
  8652. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8653. juce_wchar* const start = NumberToStringConverters::int64ToString (end, number);
  8654. createInternal (start, end - start - 1);
  8655. }
  8656. String::String (const uint64 number)
  8657. {
  8658. juce_wchar buffer [32];
  8659. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8660. juce_wchar* const start = NumberToStringConverters::uint64ToString (end, number);
  8661. createInternal (start, end - start - 1);
  8662. }
  8663. String::String (const float number, const int numberOfDecimalPlaces)
  8664. {
  8665. juce_wchar buffer [48];
  8666. size_t len;
  8667. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), (double) number, numberOfDecimalPlaces, len);
  8668. createInternal (start, len);
  8669. }
  8670. String::String (const double number, const int numberOfDecimalPlaces)
  8671. {
  8672. juce_wchar buffer [48];
  8673. size_t len;
  8674. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), number, numberOfDecimalPlaces, len);
  8675. createInternal (start, len);
  8676. }
  8677. int String::length() const throw()
  8678. {
  8679. return CharacterFunctions::length (text);
  8680. }
  8681. int String::hashCode() const throw()
  8682. {
  8683. const juce_wchar* t = text;
  8684. int result = 0;
  8685. while (*t != (juce_wchar) 0)
  8686. result = 31 * result + *t++;
  8687. return result;
  8688. }
  8689. int64 String::hashCode64() const throw()
  8690. {
  8691. const juce_wchar* t = text;
  8692. int64 result = 0;
  8693. while (*t != (juce_wchar) 0)
  8694. result = 101 * result + *t++;
  8695. return result;
  8696. }
  8697. bool JUCE_CALLTYPE operator== (const String& string1, const String& string2) throw()
  8698. {
  8699. return string1.compare (string2) == 0;
  8700. }
  8701. bool JUCE_CALLTYPE operator== (const String& string1, const char* string2) throw()
  8702. {
  8703. return string1.compare (string2) == 0;
  8704. }
  8705. bool JUCE_CALLTYPE operator== (const String& string1, const juce_wchar* string2) throw()
  8706. {
  8707. return string1.compare (string2) == 0;
  8708. }
  8709. bool JUCE_CALLTYPE operator!= (const String& string1, const String& string2) throw()
  8710. {
  8711. return string1.compare (string2) != 0;
  8712. }
  8713. bool JUCE_CALLTYPE operator!= (const String& string1, const char* string2) throw()
  8714. {
  8715. return string1.compare (string2) != 0;
  8716. }
  8717. bool JUCE_CALLTYPE operator!= (const String& string1, const juce_wchar* string2) throw()
  8718. {
  8719. return string1.compare (string2) != 0;
  8720. }
  8721. bool JUCE_CALLTYPE operator> (const String& string1, const String& string2) throw()
  8722. {
  8723. return string1.compare (string2) > 0;
  8724. }
  8725. bool JUCE_CALLTYPE operator< (const String& string1, const String& string2) throw()
  8726. {
  8727. return string1.compare (string2) < 0;
  8728. }
  8729. bool JUCE_CALLTYPE operator>= (const String& string1, const String& string2) throw()
  8730. {
  8731. return string1.compare (string2) >= 0;
  8732. }
  8733. bool JUCE_CALLTYPE operator<= (const String& string1, const String& string2) throw()
  8734. {
  8735. return string1.compare (string2) <= 0;
  8736. }
  8737. bool String::equalsIgnoreCase (const juce_wchar* t) const throw()
  8738. {
  8739. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  8740. : isEmpty();
  8741. }
  8742. bool String::equalsIgnoreCase (const char* t) const throw()
  8743. {
  8744. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  8745. : isEmpty();
  8746. }
  8747. bool String::equalsIgnoreCase (const String& other) const throw()
  8748. {
  8749. return text == other.text
  8750. || CharacterFunctions::compareIgnoreCase (text, other.text) == 0;
  8751. }
  8752. int String::compare (const String& other) const throw()
  8753. {
  8754. return (text == other.text) ? 0 : CharacterFunctions::compare (text, other.text);
  8755. }
  8756. int String::compare (const char* other) const throw()
  8757. {
  8758. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  8759. }
  8760. int String::compare (const juce_wchar* other) const throw()
  8761. {
  8762. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  8763. }
  8764. int String::compareIgnoreCase (const String& other) const throw()
  8765. {
  8766. return (text == other.text) ? 0 : CharacterFunctions::compareIgnoreCase (text, other.text);
  8767. }
  8768. int String::compareLexicographically (const String& other) const throw()
  8769. {
  8770. const juce_wchar* s1 = text;
  8771. while (*s1 != 0 && ! CharacterFunctions::isLetterOrDigit (*s1))
  8772. ++s1;
  8773. const juce_wchar* s2 = other.text;
  8774. while (*s2 != 0 && ! CharacterFunctions::isLetterOrDigit (*s2))
  8775. ++s2;
  8776. return CharacterFunctions::compareIgnoreCase (s1, s2);
  8777. }
  8778. String& String::operator+= (const juce_wchar* const t)
  8779. {
  8780. if (t != 0)
  8781. appendInternal (t, CharacterFunctions::length (t));
  8782. return *this;
  8783. }
  8784. String& String::operator+= (const String& other)
  8785. {
  8786. if (isEmpty())
  8787. operator= (other);
  8788. else
  8789. appendInternal (other.text, other.length());
  8790. return *this;
  8791. }
  8792. String& String::operator+= (const char ch)
  8793. {
  8794. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  8795. return operator+= (static_cast <const juce_wchar*> (asString));
  8796. }
  8797. String& String::operator+= (const juce_wchar ch)
  8798. {
  8799. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  8800. return operator+= (static_cast <const juce_wchar*> (asString));
  8801. }
  8802. String& String::operator+= (const int number)
  8803. {
  8804. juce_wchar buffer [16];
  8805. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8806. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  8807. appendInternal (start, (int) (end - start));
  8808. return *this;
  8809. }
  8810. String& String::operator+= (const unsigned int number)
  8811. {
  8812. juce_wchar buffer [16];
  8813. juce_wchar* const end = buffer + numElementsInArray (buffer);
  8814. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  8815. appendInternal (start, (int) (end - start));
  8816. return *this;
  8817. }
  8818. void String::append (const juce_wchar* const other, const int howMany)
  8819. {
  8820. if (howMany > 0)
  8821. {
  8822. int i;
  8823. for (i = 0; i < howMany; ++i)
  8824. if (other[i] == 0)
  8825. break;
  8826. appendInternal (other, i);
  8827. }
  8828. }
  8829. const String JUCE_CALLTYPE operator+ (const char* const string1, const String& string2)
  8830. {
  8831. String s (string1);
  8832. return s += string2;
  8833. }
  8834. const String JUCE_CALLTYPE operator+ (const juce_wchar* const string1, const String& string2)
  8835. {
  8836. String s (string1);
  8837. return s += string2;
  8838. }
  8839. const String JUCE_CALLTYPE operator+ (const char string1, const String& string2)
  8840. {
  8841. return String::charToString (string1) + string2;
  8842. }
  8843. const String JUCE_CALLTYPE operator+ (const juce_wchar string1, const String& string2)
  8844. {
  8845. return String::charToString (string1) + string2;
  8846. }
  8847. const String JUCE_CALLTYPE operator+ (String string1, const String& string2)
  8848. {
  8849. return string1 += string2;
  8850. }
  8851. const String JUCE_CALLTYPE operator+ (String string1, const char* const string2)
  8852. {
  8853. return string1 += string2;
  8854. }
  8855. const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar* const string2)
  8856. {
  8857. return string1 += string2;
  8858. }
  8859. const String JUCE_CALLTYPE operator+ (String string1, const char string2)
  8860. {
  8861. return string1 += string2;
  8862. }
  8863. const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar string2)
  8864. {
  8865. return string1 += string2;
  8866. }
  8867. String& JUCE_CALLTYPE operator<< (String& string1, const char characterToAppend)
  8868. {
  8869. return string1 += characterToAppend;
  8870. }
  8871. String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar characterToAppend)
  8872. {
  8873. return string1 += characterToAppend;
  8874. }
  8875. String& JUCE_CALLTYPE operator<< (String& string1, const char* const string2)
  8876. {
  8877. return string1 += string2;
  8878. }
  8879. String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar* const string2)
  8880. {
  8881. return string1 += string2;
  8882. }
  8883. String& JUCE_CALLTYPE operator<< (String& string1, const String& string2)
  8884. {
  8885. return string1 += string2;
  8886. }
  8887. String& JUCE_CALLTYPE operator<< (String& string1, const short number)
  8888. {
  8889. return string1 += (int) number;
  8890. }
  8891. String& JUCE_CALLTYPE operator<< (String& string1, const int number)
  8892. {
  8893. return string1 += number;
  8894. }
  8895. String& JUCE_CALLTYPE operator<< (String& string1, const unsigned int number)
  8896. {
  8897. return string1 += number;
  8898. }
  8899. String& JUCE_CALLTYPE operator<< (String& string1, const long number)
  8900. {
  8901. return string1 += (int) number;
  8902. }
  8903. String& JUCE_CALLTYPE operator<< (String& string1, const unsigned long number)
  8904. {
  8905. return string1 += (unsigned int) number;
  8906. }
  8907. String& JUCE_CALLTYPE operator<< (String& string1, const float number)
  8908. {
  8909. return string1 += String (number);
  8910. }
  8911. String& JUCE_CALLTYPE operator<< (String& string1, const double number)
  8912. {
  8913. return string1 += String (number);
  8914. }
  8915. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const String& text)
  8916. {
  8917. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  8918. // if lots of large, persistent strings were to be written to streams).
  8919. const int numBytes = text.getNumBytesAsUTF8();
  8920. HeapBlock<char> temp (numBytes + 1);
  8921. text.copyToUTF8 (temp, numBytes + 1);
  8922. stream.write (temp, numBytes);
  8923. return stream;
  8924. }
  8925. int String::indexOfChar (const juce_wchar character) const throw()
  8926. {
  8927. const juce_wchar* t = text;
  8928. for (;;)
  8929. {
  8930. if (*t == character)
  8931. return (int) (t - text);
  8932. if (*t++ == 0)
  8933. return -1;
  8934. }
  8935. }
  8936. int String::lastIndexOfChar (const juce_wchar character) const throw()
  8937. {
  8938. for (int i = length(); --i >= 0;)
  8939. if (text[i] == character)
  8940. return i;
  8941. return -1;
  8942. }
  8943. int String::indexOf (const String& t) const throw()
  8944. {
  8945. const juce_wchar* const r = CharacterFunctions::find (text, t.text);
  8946. return r == 0 ? -1 : (int) (r - text);
  8947. }
  8948. int String::indexOfChar (const int startIndex,
  8949. const juce_wchar character) const throw()
  8950. {
  8951. if (startIndex > 0 && startIndex >= length())
  8952. return -1;
  8953. const juce_wchar* t = text + jmax (0, startIndex);
  8954. for (;;)
  8955. {
  8956. if (*t == character)
  8957. return (int) (t - text);
  8958. if (*t == 0)
  8959. return -1;
  8960. ++t;
  8961. }
  8962. }
  8963. int String::indexOfAnyOf (const String& charactersToLookFor,
  8964. const int startIndex,
  8965. const bool ignoreCase) const throw()
  8966. {
  8967. if (startIndex > 0 && startIndex >= length())
  8968. return -1;
  8969. const juce_wchar* t = text + jmax (0, startIndex);
  8970. while (*t != 0)
  8971. {
  8972. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, *t, ignoreCase) >= 0)
  8973. return (int) (t - text);
  8974. ++t;
  8975. }
  8976. return -1;
  8977. }
  8978. int String::indexOf (const int startIndex, const String& other) const throw()
  8979. {
  8980. if (startIndex > 0 && startIndex >= length())
  8981. return -1;
  8982. const juce_wchar* const found = CharacterFunctions::find (text + jmax (0, startIndex), other.text);
  8983. return found == 0 ? -1 : (int) (found - text);
  8984. }
  8985. int String::indexOfIgnoreCase (const String& other) const throw()
  8986. {
  8987. if (other.isNotEmpty())
  8988. {
  8989. const int len = other.length();
  8990. const int end = length() - len;
  8991. for (int i = 0; i <= end; ++i)
  8992. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  8993. return i;
  8994. }
  8995. return -1;
  8996. }
  8997. int String::indexOfIgnoreCase (const int startIndex, const String& other) const throw()
  8998. {
  8999. if (other.isNotEmpty())
  9000. {
  9001. const int len = other.length();
  9002. const int end = length() - len;
  9003. for (int i = jmax (0, startIndex); i <= end; ++i)
  9004. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  9005. return i;
  9006. }
  9007. return -1;
  9008. }
  9009. int String::lastIndexOf (const String& other) const throw()
  9010. {
  9011. if (other.isNotEmpty())
  9012. {
  9013. const int len = other.length();
  9014. int i = length() - len;
  9015. if (i >= 0)
  9016. {
  9017. const juce_wchar* n = text + i;
  9018. while (i >= 0)
  9019. {
  9020. if (CharacterFunctions::compare (n--, other.text, len) == 0)
  9021. return i;
  9022. --i;
  9023. }
  9024. }
  9025. }
  9026. return -1;
  9027. }
  9028. int String::lastIndexOfIgnoreCase (const String& other) const throw()
  9029. {
  9030. if (other.isNotEmpty())
  9031. {
  9032. const int len = other.length();
  9033. int i = length() - len;
  9034. if (i >= 0)
  9035. {
  9036. const juce_wchar* n = text + i;
  9037. while (i >= 0)
  9038. {
  9039. if (CharacterFunctions::compareIgnoreCase (n--, other.text, len) == 0)
  9040. return i;
  9041. --i;
  9042. }
  9043. }
  9044. }
  9045. return -1;
  9046. }
  9047. int String::lastIndexOfAnyOf (const String& charactersToLookFor, const bool ignoreCase) const throw()
  9048. {
  9049. for (int i = length(); --i >= 0;)
  9050. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, text[i], ignoreCase) >= 0)
  9051. return i;
  9052. return -1;
  9053. }
  9054. bool String::contains (const String& other) const throw()
  9055. {
  9056. return indexOf (other) >= 0;
  9057. }
  9058. bool String::containsChar (const juce_wchar character) const throw()
  9059. {
  9060. const juce_wchar* t = text;
  9061. for (;;)
  9062. {
  9063. if (*t == 0)
  9064. return false;
  9065. if (*t == character)
  9066. return true;
  9067. ++t;
  9068. }
  9069. }
  9070. bool String::containsIgnoreCase (const String& t) const throw()
  9071. {
  9072. return indexOfIgnoreCase (t) >= 0;
  9073. }
  9074. int String::indexOfWholeWord (const String& word) const throw()
  9075. {
  9076. if (word.isNotEmpty())
  9077. {
  9078. const int wordLen = word.length();
  9079. const int end = length() - wordLen;
  9080. const juce_wchar* t = text;
  9081. for (int i = 0; i <= end; ++i)
  9082. {
  9083. if (CharacterFunctions::compare (t, word.text, wordLen) == 0
  9084. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  9085. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  9086. {
  9087. return i;
  9088. }
  9089. ++t;
  9090. }
  9091. }
  9092. return -1;
  9093. }
  9094. int String::indexOfWholeWordIgnoreCase (const String& word) const throw()
  9095. {
  9096. if (word.isNotEmpty())
  9097. {
  9098. const int wordLen = word.length();
  9099. const int end = length() - wordLen;
  9100. const juce_wchar* t = text;
  9101. for (int i = 0; i <= end; ++i)
  9102. {
  9103. if (CharacterFunctions::compareIgnoreCase (t, word.text, wordLen) == 0
  9104. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  9105. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  9106. {
  9107. return i;
  9108. }
  9109. ++t;
  9110. }
  9111. }
  9112. return -1;
  9113. }
  9114. bool String::containsWholeWord (const String& wordToLookFor) const throw()
  9115. {
  9116. return indexOfWholeWord (wordToLookFor) >= 0;
  9117. }
  9118. bool String::containsWholeWordIgnoreCase (const String& wordToLookFor) const throw()
  9119. {
  9120. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  9121. }
  9122. static int indexOfMatch (const juce_wchar* const wildcard,
  9123. const juce_wchar* const test,
  9124. const bool ignoreCase) throw()
  9125. {
  9126. int start = 0;
  9127. while (test [start] != 0)
  9128. {
  9129. int i = 0;
  9130. for (;;)
  9131. {
  9132. const juce_wchar wc = wildcard [i];
  9133. const juce_wchar c = test [i + start];
  9134. if (wc == c
  9135. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  9136. || (wc == '?' && c != 0))
  9137. {
  9138. if (wc == 0)
  9139. return start;
  9140. ++i;
  9141. }
  9142. else
  9143. {
  9144. if (wc == '*' && (wildcard [i + 1] == 0
  9145. || indexOfMatch (wildcard + i + 1, test + start + i, ignoreCase) >= 0))
  9146. {
  9147. return start;
  9148. }
  9149. break;
  9150. }
  9151. }
  9152. ++start;
  9153. }
  9154. return -1;
  9155. }
  9156. bool String::matchesWildcard (const String& wildcard, const bool ignoreCase) const throw()
  9157. {
  9158. int i = 0;
  9159. for (;;)
  9160. {
  9161. const juce_wchar wc = wildcard.text [i];
  9162. const juce_wchar c = text [i];
  9163. if (wc == c
  9164. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  9165. || (wc == '?' && c != 0))
  9166. {
  9167. if (wc == 0)
  9168. return true;
  9169. ++i;
  9170. }
  9171. else
  9172. {
  9173. return wc == '*' && (wildcard [i + 1] == 0
  9174. || indexOfMatch (wildcard.text + i + 1, text + i, ignoreCase) >= 0);
  9175. }
  9176. }
  9177. }
  9178. const String String::repeatedString (const String& stringToRepeat, int numberOfTimesToRepeat)
  9179. {
  9180. const int len = stringToRepeat.length();
  9181. String result ((size_t) (len * numberOfTimesToRepeat + 1), (int) 0);
  9182. juce_wchar* n = result.text;
  9183. *n = 0;
  9184. while (--numberOfTimesToRepeat >= 0)
  9185. {
  9186. StringHolder::copyChars (n, stringToRepeat.text, len);
  9187. n += len;
  9188. }
  9189. return result;
  9190. }
  9191. const String String::paddedLeft (const juce_wchar padCharacter, int minimumLength) const
  9192. {
  9193. jassert (padCharacter != 0);
  9194. const int len = length();
  9195. if (len >= minimumLength || padCharacter == 0)
  9196. return *this;
  9197. String result ((size_t) minimumLength + 1, (int) 0);
  9198. juce_wchar* n = result.text;
  9199. minimumLength -= len;
  9200. while (--minimumLength >= 0)
  9201. *n++ = padCharacter;
  9202. StringHolder::copyChars (n, text, len);
  9203. return result;
  9204. }
  9205. const String String::paddedRight (const juce_wchar padCharacter, int minimumLength) const
  9206. {
  9207. jassert (padCharacter != 0);
  9208. const int len = length();
  9209. if (len >= minimumLength || padCharacter == 0)
  9210. return *this;
  9211. String result (*this, (size_t) minimumLength);
  9212. juce_wchar* n = result.text + len;
  9213. minimumLength -= len;
  9214. while (--minimumLength >= 0)
  9215. *n++ = padCharacter;
  9216. *n = 0;
  9217. return result;
  9218. }
  9219. const String String::replaceSection (int index, int numCharsToReplace, const String& stringToInsert) const
  9220. {
  9221. if (index < 0)
  9222. {
  9223. // a negative index to replace from?
  9224. jassertfalse;
  9225. index = 0;
  9226. }
  9227. if (numCharsToReplace < 0)
  9228. {
  9229. // replacing a negative number of characters?
  9230. numCharsToReplace = 0;
  9231. jassertfalse;
  9232. }
  9233. const int len = length();
  9234. if (index + numCharsToReplace > len)
  9235. {
  9236. if (index > len)
  9237. {
  9238. // replacing beyond the end of the string?
  9239. index = len;
  9240. jassertfalse;
  9241. }
  9242. numCharsToReplace = len - index;
  9243. }
  9244. const int newStringLen = stringToInsert.length();
  9245. const int newTotalLen = len + newStringLen - numCharsToReplace;
  9246. if (newTotalLen <= 0)
  9247. return String::empty;
  9248. String result ((size_t) newTotalLen, (int) 0);
  9249. StringHolder::copyChars (result.text, text, index);
  9250. if (newStringLen > 0)
  9251. StringHolder::copyChars (result.text + index, stringToInsert.text, newStringLen);
  9252. const int endStringLen = newTotalLen - (index + newStringLen);
  9253. if (endStringLen > 0)
  9254. StringHolder::copyChars (result.text + (index + newStringLen),
  9255. text + (index + numCharsToReplace),
  9256. endStringLen);
  9257. return result;
  9258. }
  9259. const String String::replace (const String& stringToReplace, const String& stringToInsert, const bool ignoreCase) const
  9260. {
  9261. const int stringToReplaceLen = stringToReplace.length();
  9262. const int stringToInsertLen = stringToInsert.length();
  9263. int i = 0;
  9264. String result (*this);
  9265. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  9266. : result.indexOf (i, stringToReplace))) >= 0)
  9267. {
  9268. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  9269. i += stringToInsertLen;
  9270. }
  9271. return result;
  9272. }
  9273. const String String::replaceCharacter (const juce_wchar charToReplace, const juce_wchar charToInsert) const
  9274. {
  9275. const int index = indexOfChar (charToReplace);
  9276. if (index < 0)
  9277. return *this;
  9278. String result (*this, size_t());
  9279. juce_wchar* t = result.text + index;
  9280. while (*t != 0)
  9281. {
  9282. if (*t == charToReplace)
  9283. *t = charToInsert;
  9284. ++t;
  9285. }
  9286. return result;
  9287. }
  9288. const String String::replaceCharacters (const String& charactersToReplace,
  9289. const String& charactersToInsertInstead) const
  9290. {
  9291. String result (*this, size_t());
  9292. juce_wchar* t = result.text;
  9293. const int len2 = charactersToInsertInstead.length();
  9294. // the two strings passed in are supposed to be the same length!
  9295. jassert (len2 == charactersToReplace.length());
  9296. while (*t != 0)
  9297. {
  9298. const int index = charactersToReplace.indexOfChar (*t);
  9299. if (((unsigned int) index) < (unsigned int) len2)
  9300. *t = charactersToInsertInstead [index];
  9301. ++t;
  9302. }
  9303. return result;
  9304. }
  9305. bool String::startsWith (const String& other) const throw()
  9306. {
  9307. return CharacterFunctions::compare (text, other.text, other.length()) == 0;
  9308. }
  9309. bool String::startsWithIgnoreCase (const String& other) const throw()
  9310. {
  9311. return CharacterFunctions::compareIgnoreCase (text, other.text, other.length()) == 0;
  9312. }
  9313. bool String::startsWithChar (const juce_wchar character) const throw()
  9314. {
  9315. jassert (character != 0); // strings can't contain a null character!
  9316. return text[0] == character;
  9317. }
  9318. bool String::endsWithChar (const juce_wchar character) const throw()
  9319. {
  9320. jassert (character != 0); // strings can't contain a null character!
  9321. return text[0] != 0
  9322. && text [length() - 1] == character;
  9323. }
  9324. bool String::endsWith (const String& other) const throw()
  9325. {
  9326. const int thisLen = length();
  9327. const int otherLen = other.length();
  9328. return thisLen >= otherLen
  9329. && CharacterFunctions::compare (text + thisLen - otherLen, other.text) == 0;
  9330. }
  9331. bool String::endsWithIgnoreCase (const String& other) const throw()
  9332. {
  9333. const int thisLen = length();
  9334. const int otherLen = other.length();
  9335. return thisLen >= otherLen
  9336. && CharacterFunctions::compareIgnoreCase (text + thisLen - otherLen, other.text) == 0;
  9337. }
  9338. const String String::toUpperCase() const
  9339. {
  9340. String result (*this, size_t());
  9341. CharacterFunctions::toUpperCase (result.text);
  9342. return result;
  9343. }
  9344. const String String::toLowerCase() const
  9345. {
  9346. String result (*this, size_t());
  9347. CharacterFunctions::toLowerCase (result.text);
  9348. return result;
  9349. }
  9350. juce_wchar& String::operator[] (const int index)
  9351. {
  9352. jassert (((unsigned int) index) <= (unsigned int) length());
  9353. text = StringHolder::makeUnique (text);
  9354. return text [index];
  9355. }
  9356. juce_wchar String::getLastCharacter() const throw()
  9357. {
  9358. return isEmpty() ? juce_wchar() : text [length() - 1];
  9359. }
  9360. const String String::substring (int start, int end) const
  9361. {
  9362. if (start < 0)
  9363. start = 0;
  9364. else if (end <= start)
  9365. return empty;
  9366. int len = 0;
  9367. while (len <= end && text [len] != 0)
  9368. ++len;
  9369. if (end >= len)
  9370. {
  9371. if (start == 0)
  9372. return *this;
  9373. end = len;
  9374. }
  9375. return String (text + start, end - start);
  9376. }
  9377. const String String::substring (const int start) const
  9378. {
  9379. if (start <= 0)
  9380. return *this;
  9381. const int len = length();
  9382. if (start >= len)
  9383. return empty;
  9384. return String (text + start, len - start);
  9385. }
  9386. const String String::dropLastCharacters (const int numberToDrop) const
  9387. {
  9388. return String (text, jmax (0, length() - numberToDrop));
  9389. }
  9390. const String String::getLastCharacters (const int numCharacters) const
  9391. {
  9392. return String (text + jmax (0, length() - jmax (0, numCharacters)));
  9393. }
  9394. const String String::fromFirstOccurrenceOf (const String& sub,
  9395. const bool includeSubString,
  9396. const bool ignoreCase) const
  9397. {
  9398. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  9399. : indexOf (sub);
  9400. if (i < 0)
  9401. return empty;
  9402. return substring (includeSubString ? i : i + sub.length());
  9403. }
  9404. const String String::fromLastOccurrenceOf (const String& sub,
  9405. const bool includeSubString,
  9406. const bool ignoreCase) const
  9407. {
  9408. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  9409. : lastIndexOf (sub);
  9410. if (i < 0)
  9411. return *this;
  9412. return substring (includeSubString ? i : i + sub.length());
  9413. }
  9414. const String String::upToFirstOccurrenceOf (const String& sub,
  9415. const bool includeSubString,
  9416. const bool ignoreCase) const
  9417. {
  9418. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  9419. : indexOf (sub);
  9420. if (i < 0)
  9421. return *this;
  9422. return substring (0, includeSubString ? i + sub.length() : i);
  9423. }
  9424. const String String::upToLastOccurrenceOf (const String& sub,
  9425. const bool includeSubString,
  9426. const bool ignoreCase) const
  9427. {
  9428. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  9429. : lastIndexOf (sub);
  9430. if (i < 0)
  9431. return *this;
  9432. return substring (0, includeSubString ? i + sub.length() : i);
  9433. }
  9434. bool String::isQuotedString() const
  9435. {
  9436. const String trimmed (trimStart());
  9437. return trimmed[0] == '"'
  9438. || trimmed[0] == '\'';
  9439. }
  9440. const String String::unquoted() const
  9441. {
  9442. String s (*this);
  9443. if (s.text[0] == '"' || s.text[0] == '\'')
  9444. s = s.substring (1);
  9445. const int lastCharIndex = s.length() - 1;
  9446. if (lastCharIndex >= 0
  9447. && (s [lastCharIndex] == '"' || s[lastCharIndex] == '\''))
  9448. s [lastCharIndex] = 0;
  9449. return s;
  9450. }
  9451. const String String::quoted (const juce_wchar quoteCharacter) const
  9452. {
  9453. if (isEmpty())
  9454. return charToString (quoteCharacter) + quoteCharacter;
  9455. String t (*this);
  9456. if (! t.startsWithChar (quoteCharacter))
  9457. t = charToString (quoteCharacter) + t;
  9458. if (! t.endsWithChar (quoteCharacter))
  9459. t += quoteCharacter;
  9460. return t;
  9461. }
  9462. const String String::trim() const
  9463. {
  9464. if (isEmpty())
  9465. return empty;
  9466. int start = 0;
  9467. while (CharacterFunctions::isWhitespace (text [start]))
  9468. ++start;
  9469. const int len = length();
  9470. int end = len - 1;
  9471. while ((end >= start) && CharacterFunctions::isWhitespace (text [end]))
  9472. --end;
  9473. ++end;
  9474. if (end <= start)
  9475. return empty;
  9476. else if (start > 0 || end < len)
  9477. return String (text + start, end - start);
  9478. return *this;
  9479. }
  9480. const String String::trimStart() const
  9481. {
  9482. if (isEmpty())
  9483. return empty;
  9484. const juce_wchar* t = text;
  9485. while (CharacterFunctions::isWhitespace (*t))
  9486. ++t;
  9487. if (t == text)
  9488. return *this;
  9489. return String (t);
  9490. }
  9491. const String String::trimEnd() const
  9492. {
  9493. if (isEmpty())
  9494. return empty;
  9495. const juce_wchar* endT = text + (length() - 1);
  9496. while ((endT >= text) && CharacterFunctions::isWhitespace (*endT))
  9497. --endT;
  9498. return String (text, (int) (++endT - text));
  9499. }
  9500. const String String::trimCharactersAtStart (const String& charactersToTrim) const
  9501. {
  9502. const juce_wchar* t = text;
  9503. while (charactersToTrim.containsChar (*t))
  9504. ++t;
  9505. return t == text ? *this : String (t);
  9506. }
  9507. const String String::trimCharactersAtEnd (const String& charactersToTrim) const
  9508. {
  9509. if (isEmpty())
  9510. return empty;
  9511. const int len = length();
  9512. const juce_wchar* endT = text + (len - 1);
  9513. int numToRemove = 0;
  9514. while (numToRemove < len && charactersToTrim.containsChar (*endT))
  9515. {
  9516. ++numToRemove;
  9517. --endT;
  9518. }
  9519. return numToRemove > 0 ? String (text, len - numToRemove) : *this;
  9520. }
  9521. const String String::retainCharacters (const String& charactersToRetain) const
  9522. {
  9523. if (isEmpty())
  9524. return empty;
  9525. String result (StringHolder::getAllocatedNumChars (text), (int) 0);
  9526. juce_wchar* dst = result.text;
  9527. const juce_wchar* src = text;
  9528. while (*src != 0)
  9529. {
  9530. if (charactersToRetain.containsChar (*src))
  9531. *dst++ = *src;
  9532. ++src;
  9533. }
  9534. *dst = 0;
  9535. return result;
  9536. }
  9537. const String String::removeCharacters (const String& charactersToRemove) const
  9538. {
  9539. if (isEmpty())
  9540. return empty;
  9541. String result (StringHolder::getAllocatedNumChars (text), (int) 0);
  9542. juce_wchar* dst = result.text;
  9543. const juce_wchar* src = text;
  9544. while (*src != 0)
  9545. {
  9546. if (! charactersToRemove.containsChar (*src))
  9547. *dst++ = *src;
  9548. ++src;
  9549. }
  9550. *dst = 0;
  9551. return result;
  9552. }
  9553. const String String::initialSectionContainingOnly (const String& permittedCharacters) const
  9554. {
  9555. int i = 0;
  9556. for (;;)
  9557. {
  9558. if (! permittedCharacters.containsChar (text[i]))
  9559. break;
  9560. ++i;
  9561. }
  9562. return substring (0, i);
  9563. }
  9564. const String String::initialSectionNotContaining (const String& charactersToStopAt) const
  9565. {
  9566. const juce_wchar* const t = text;
  9567. int i = 0;
  9568. while (t[i] != 0)
  9569. {
  9570. if (charactersToStopAt.containsChar (t[i]))
  9571. return String (text, i);
  9572. ++i;
  9573. }
  9574. return empty;
  9575. }
  9576. bool String::containsOnly (const String& chars) const throw()
  9577. {
  9578. const juce_wchar* t = text;
  9579. while (*t != 0)
  9580. if (! chars.containsChar (*t++))
  9581. return false;
  9582. return true;
  9583. }
  9584. bool String::containsAnyOf (const String& chars) const throw()
  9585. {
  9586. const juce_wchar* t = text;
  9587. while (*t != 0)
  9588. if (chars.containsChar (*t++))
  9589. return true;
  9590. return false;
  9591. }
  9592. bool String::containsNonWhitespaceChars() const throw()
  9593. {
  9594. const juce_wchar* t = text;
  9595. while (*t != 0)
  9596. if (! CharacterFunctions::isWhitespace (*t++))
  9597. return true;
  9598. return false;
  9599. }
  9600. const String String::formatted (const juce_wchar* const pf, ... )
  9601. {
  9602. jassert (pf != 0);
  9603. va_list args;
  9604. va_start (args, pf);
  9605. size_t bufferSize = 256;
  9606. String result (bufferSize, (int) 0);
  9607. result.text[0] = 0;
  9608. for (;;)
  9609. {
  9610. #if JUCE_LINUX && JUCE_64BIT
  9611. va_list tempArgs;
  9612. va_copy (tempArgs, args);
  9613. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, tempArgs);
  9614. va_end (tempArgs);
  9615. #elif JUCE_WINDOWS
  9616. #if JUCE_MSVC
  9617. #pragma warning (push)
  9618. #pragma warning (disable: 4996)
  9619. #endif
  9620. const int num = (int) _vsnwprintf (result.text, bufferSize - 1, pf, args);
  9621. #if JUCE_MSVC
  9622. #pragma warning (pop)
  9623. #endif
  9624. #else
  9625. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, args);
  9626. #endif
  9627. if (num > 0)
  9628. return result;
  9629. bufferSize += 256;
  9630. if (num == 0 || bufferSize > 65536) // the upper limit is a sanity check to avoid situations where vprintf repeatedly
  9631. break; // returns -1 because of an error rather than because it needs more space.
  9632. result.preallocateStorage (bufferSize);
  9633. }
  9634. return empty;
  9635. }
  9636. int String::getIntValue() const throw()
  9637. {
  9638. return CharacterFunctions::getIntValue (text);
  9639. }
  9640. int String::getTrailingIntValue() const throw()
  9641. {
  9642. int n = 0;
  9643. int mult = 1;
  9644. const juce_wchar* t = text + length();
  9645. while (--t >= text)
  9646. {
  9647. const juce_wchar c = *t;
  9648. if (! CharacterFunctions::isDigit (c))
  9649. {
  9650. if (c == '-')
  9651. n = -n;
  9652. break;
  9653. }
  9654. n += mult * (c - '0');
  9655. mult *= 10;
  9656. }
  9657. return n;
  9658. }
  9659. int64 String::getLargeIntValue() const throw()
  9660. {
  9661. return CharacterFunctions::getInt64Value (text);
  9662. }
  9663. float String::getFloatValue() const throw()
  9664. {
  9665. return (float) CharacterFunctions::getDoubleValue (text);
  9666. }
  9667. double String::getDoubleValue() const throw()
  9668. {
  9669. return CharacterFunctions::getDoubleValue (text);
  9670. }
  9671. static const juce_wchar* const hexDigits = JUCE_T("0123456789abcdef");
  9672. const String String::toHexString (const int number)
  9673. {
  9674. juce_wchar buffer[32];
  9675. juce_wchar* const end = buffer + 32;
  9676. juce_wchar* t = end;
  9677. *--t = 0;
  9678. unsigned int v = (unsigned int) number;
  9679. do
  9680. {
  9681. *--t = hexDigits [v & 15];
  9682. v >>= 4;
  9683. } while (v != 0);
  9684. return String (t, (int) (((char*) end) - (char*) t) - 1);
  9685. }
  9686. const String String::toHexString (const int64 number)
  9687. {
  9688. juce_wchar buffer[32];
  9689. juce_wchar* const end = buffer + 32;
  9690. juce_wchar* t = end;
  9691. *--t = 0;
  9692. uint64 v = (uint64) number;
  9693. do
  9694. {
  9695. *--t = hexDigits [(int) (v & 15)];
  9696. v >>= 4;
  9697. } while (v != 0);
  9698. return String (t, (int) (((char*) end) - (char*) t));
  9699. }
  9700. const String String::toHexString (const short number)
  9701. {
  9702. return toHexString ((int) (unsigned short) number);
  9703. }
  9704. const String String::toHexString (const unsigned char* data,
  9705. const int size,
  9706. const int groupSize)
  9707. {
  9708. if (size <= 0)
  9709. return empty;
  9710. int numChars = (size * 2) + 2;
  9711. if (groupSize > 0)
  9712. numChars += size / groupSize;
  9713. String s ((size_t) numChars, (int) 0);
  9714. juce_wchar* d = s.text;
  9715. for (int i = 0; i < size; ++i)
  9716. {
  9717. *d++ = hexDigits [(*data) >> 4];
  9718. *d++ = hexDigits [(*data) & 0xf];
  9719. ++data;
  9720. if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1))
  9721. *d++ = ' ';
  9722. }
  9723. *d = 0;
  9724. return s;
  9725. }
  9726. int String::getHexValue32() const throw()
  9727. {
  9728. int result = 0;
  9729. const juce_wchar* c = text;
  9730. for (;;)
  9731. {
  9732. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  9733. if (hexValue >= 0)
  9734. result = (result << 4) | hexValue;
  9735. else if (*c == 0)
  9736. break;
  9737. ++c;
  9738. }
  9739. return result;
  9740. }
  9741. int64 String::getHexValue64() const throw()
  9742. {
  9743. int64 result = 0;
  9744. const juce_wchar* c = text;
  9745. for (;;)
  9746. {
  9747. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  9748. if (hexValue >= 0)
  9749. result = (result << 4) | hexValue;
  9750. else if (*c == 0)
  9751. break;
  9752. ++c;
  9753. }
  9754. return result;
  9755. }
  9756. const String String::createStringFromData (const void* const data_, const int size)
  9757. {
  9758. const char* const data = static_cast <const char*> (data_);
  9759. if (size <= 0 || data == 0)
  9760. {
  9761. return empty;
  9762. }
  9763. else if (size < 2)
  9764. {
  9765. return charToString (data[0]);
  9766. }
  9767. else if ((data[0] == (char)-2 && data[1] == (char)-1)
  9768. || (data[0] == (char)-1 && data[1] == (char)-2))
  9769. {
  9770. // assume it's 16-bit unicode
  9771. const bool bigEndian = (data[0] == (char)-2);
  9772. const int numChars = size / 2 - 1;
  9773. String result;
  9774. result.preallocateStorage (numChars + 2);
  9775. const uint16* const src = (const uint16*) (data + 2);
  9776. juce_wchar* const dst = const_cast <juce_wchar*> (static_cast <const juce_wchar*> (result));
  9777. if (bigEndian)
  9778. {
  9779. for (int i = 0; i < numChars; ++i)
  9780. dst[i] = (juce_wchar) ByteOrder::swapIfLittleEndian (src[i]);
  9781. }
  9782. else
  9783. {
  9784. for (int i = 0; i < numChars; ++i)
  9785. dst[i] = (juce_wchar) ByteOrder::swapIfBigEndian (src[i]);
  9786. }
  9787. dst [numChars] = 0;
  9788. return result;
  9789. }
  9790. else
  9791. {
  9792. return String::fromUTF8 (data, size);
  9793. }
  9794. }
  9795. const char* String::toUTF8() const
  9796. {
  9797. if (isEmpty())
  9798. {
  9799. return reinterpret_cast <const char*> (text);
  9800. }
  9801. else
  9802. {
  9803. const int currentLen = length() + 1;
  9804. const int utf8BytesNeeded = getNumBytesAsUTF8();
  9805. String* const mutableThis = const_cast <String*> (this);
  9806. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, currentLen + 1 + utf8BytesNeeded / sizeof (juce_wchar));
  9807. char* const otherCopy = reinterpret_cast <char*> (mutableThis->text + currentLen);
  9808. copyToUTF8 (otherCopy, std::numeric_limits<int>::max());
  9809. return otherCopy;
  9810. }
  9811. }
  9812. int String::copyToUTF8 (char* const buffer, const int maxBufferSizeBytes) const throw()
  9813. {
  9814. jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
  9815. int num = 0, index = 0;
  9816. for (;;)
  9817. {
  9818. const uint32 c = (uint32) text [index++];
  9819. if (c >= 0x80)
  9820. {
  9821. int numExtraBytes = 1;
  9822. if (c >= 0x800)
  9823. {
  9824. ++numExtraBytes;
  9825. if (c >= 0x10000)
  9826. {
  9827. ++numExtraBytes;
  9828. if (c >= 0x200000)
  9829. {
  9830. ++numExtraBytes;
  9831. if (c >= 0x4000000)
  9832. ++numExtraBytes;
  9833. }
  9834. }
  9835. }
  9836. if (buffer != 0)
  9837. {
  9838. if (num + numExtraBytes >= maxBufferSizeBytes)
  9839. {
  9840. buffer [num++] = 0;
  9841. break;
  9842. }
  9843. else
  9844. {
  9845. buffer [num++] = (uint8) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  9846. while (--numExtraBytes >= 0)
  9847. buffer [num++] = (uint8) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  9848. }
  9849. }
  9850. else
  9851. {
  9852. num += numExtraBytes + 1;
  9853. }
  9854. }
  9855. else
  9856. {
  9857. if (buffer != 0)
  9858. {
  9859. if (num + 1 >= maxBufferSizeBytes)
  9860. {
  9861. buffer [num++] = 0;
  9862. break;
  9863. }
  9864. buffer [num] = (uint8) c;
  9865. }
  9866. ++num;
  9867. }
  9868. if (c == 0)
  9869. break;
  9870. }
  9871. return num;
  9872. }
  9873. int String::getNumBytesAsUTF8() const throw()
  9874. {
  9875. int num = 0;
  9876. const juce_wchar* t = text;
  9877. for (;;)
  9878. {
  9879. const uint32 c = (uint32) *t;
  9880. if (c >= 0x80)
  9881. {
  9882. ++num;
  9883. if (c >= 0x800)
  9884. {
  9885. ++num;
  9886. if (c >= 0x10000)
  9887. {
  9888. ++num;
  9889. if (c >= 0x200000)
  9890. {
  9891. ++num;
  9892. if (c >= 0x4000000)
  9893. ++num;
  9894. }
  9895. }
  9896. }
  9897. }
  9898. else if (c == 0)
  9899. break;
  9900. ++num;
  9901. ++t;
  9902. }
  9903. return num;
  9904. }
  9905. const String String::fromUTF8 (const char* const buffer, int bufferSizeBytes)
  9906. {
  9907. if (buffer == 0)
  9908. return empty;
  9909. if (bufferSizeBytes < 0)
  9910. bufferSizeBytes = std::numeric_limits<int>::max();
  9911. size_t numBytes;
  9912. for (numBytes = 0; numBytes < (size_t) bufferSizeBytes; ++numBytes)
  9913. if (buffer [numBytes] == 0)
  9914. break;
  9915. String result ((size_t) numBytes + 1, (int) 0);
  9916. juce_wchar* dest = result.text;
  9917. size_t i = 0;
  9918. while (i < numBytes)
  9919. {
  9920. const char c = buffer [i++];
  9921. if (c < 0)
  9922. {
  9923. unsigned int mask = 0x7f;
  9924. int bit = 0x40;
  9925. int numExtraValues = 0;
  9926. while (bit != 0 && (c & bit) != 0)
  9927. {
  9928. bit >>= 1;
  9929. mask >>= 1;
  9930. ++numExtraValues;
  9931. }
  9932. int n = (mask & (unsigned char) c);
  9933. while (--numExtraValues >= 0 && i < (size_t) bufferSizeBytes)
  9934. {
  9935. const char nextByte = buffer[i];
  9936. if ((nextByte & 0xc0) != 0x80)
  9937. break;
  9938. n <<= 6;
  9939. n |= (nextByte & 0x3f);
  9940. ++i;
  9941. }
  9942. *dest++ = (juce_wchar) n;
  9943. }
  9944. else
  9945. {
  9946. *dest++ = (juce_wchar) c;
  9947. }
  9948. }
  9949. *dest = 0;
  9950. return result;
  9951. }
  9952. const char* String::toCString() const
  9953. {
  9954. if (isEmpty())
  9955. {
  9956. return reinterpret_cast <const char*> (text);
  9957. }
  9958. else
  9959. {
  9960. const int len = length();
  9961. String* const mutableThis = const_cast <String*> (this);
  9962. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, (len + 1) * 2);
  9963. char* otherCopy = reinterpret_cast <char*> (mutableThis->text + len + 1);
  9964. CharacterFunctions::copy (otherCopy, text, len);
  9965. otherCopy [len] = 0;
  9966. return otherCopy;
  9967. }
  9968. }
  9969. #if JUCE_MSVC
  9970. #pragma warning (push)
  9971. #pragma warning (disable: 4514 4996)
  9972. #endif
  9973. int String::getNumBytesAsCString() const throw()
  9974. {
  9975. return (int) wcstombs (0, text, 0);
  9976. }
  9977. int String::copyToCString (char* destBuffer, const int maxBufferSizeBytes) const throw()
  9978. {
  9979. const int numBytes = (int) wcstombs (destBuffer, text, maxBufferSizeBytes);
  9980. if (destBuffer != 0 && numBytes >= 0)
  9981. destBuffer [numBytes] = 0;
  9982. return numBytes;
  9983. }
  9984. #if JUCE_MSVC
  9985. #pragma warning (pop)
  9986. #endif
  9987. void String::copyToUnicode (juce_wchar* const destBuffer, const int maxCharsToCopy) const throw()
  9988. {
  9989. StringHolder::copyChars (destBuffer, text, jmin (maxCharsToCopy, length()));
  9990. }
  9991. String::Concatenator::Concatenator (String& stringToAppendTo)
  9992. : result (stringToAppendTo),
  9993. nextIndex (stringToAppendTo.length())
  9994. {
  9995. }
  9996. String::Concatenator::~Concatenator()
  9997. {
  9998. }
  9999. void String::Concatenator::append (const String& s)
  10000. {
  10001. const int len = s.length();
  10002. if (len > 0)
  10003. {
  10004. result.preallocateStorage (nextIndex + len);
  10005. s.copyToUnicode (static_cast <juce_wchar*> (result) + nextIndex, len);
  10006. nextIndex += len;
  10007. }
  10008. }
  10009. END_JUCE_NAMESPACE
  10010. /*** End of inlined file: juce_String.cpp ***/
  10011. /*** Start of inlined file: juce_StringArray.cpp ***/
  10012. BEGIN_JUCE_NAMESPACE
  10013. StringArray::StringArray() throw()
  10014. {
  10015. }
  10016. StringArray::StringArray (const StringArray& other)
  10017. : strings (other.strings)
  10018. {
  10019. }
  10020. StringArray::StringArray (const String& firstValue)
  10021. {
  10022. strings.add (firstValue);
  10023. }
  10024. StringArray::StringArray (const juce_wchar* const* const initialStrings,
  10025. const int numberOfStrings)
  10026. {
  10027. for (int i = 0; i < numberOfStrings; ++i)
  10028. strings.add (initialStrings [i]);
  10029. }
  10030. StringArray::StringArray (const char* const* const initialStrings,
  10031. const int numberOfStrings)
  10032. {
  10033. for (int i = 0; i < numberOfStrings; ++i)
  10034. strings.add (initialStrings [i]);
  10035. }
  10036. StringArray::StringArray (const juce_wchar* const* const initialStrings)
  10037. {
  10038. int i = 0;
  10039. while (initialStrings[i] != 0)
  10040. strings.add (initialStrings [i++]);
  10041. }
  10042. StringArray::StringArray (const char* const* const initialStrings)
  10043. {
  10044. int i = 0;
  10045. while (initialStrings[i] != 0)
  10046. strings.add (initialStrings [i++]);
  10047. }
  10048. StringArray& StringArray::operator= (const StringArray& other)
  10049. {
  10050. strings = other.strings;
  10051. return *this;
  10052. }
  10053. StringArray::~StringArray()
  10054. {
  10055. }
  10056. bool StringArray::operator== (const StringArray& other) const throw()
  10057. {
  10058. if (other.size() != size())
  10059. return false;
  10060. for (int i = size(); --i >= 0;)
  10061. if (other.strings.getReference(i) != strings.getReference(i))
  10062. return false;
  10063. return true;
  10064. }
  10065. bool StringArray::operator!= (const StringArray& other) const throw()
  10066. {
  10067. return ! operator== (other);
  10068. }
  10069. void StringArray::clear()
  10070. {
  10071. strings.clear();
  10072. }
  10073. const String& StringArray::operator[] (const int index) const throw()
  10074. {
  10075. if (((unsigned int) index) < (unsigned int) strings.size())
  10076. return strings.getReference (index);
  10077. return String::empty;
  10078. }
  10079. String& StringArray::getReference (const int index) throw()
  10080. {
  10081. jassert (((unsigned int) index) < (unsigned int) strings.size());
  10082. return strings.getReference (index);
  10083. }
  10084. void StringArray::add (const String& newString)
  10085. {
  10086. strings.add (newString);
  10087. }
  10088. void StringArray::insert (const int index, const String& newString)
  10089. {
  10090. strings.insert (index, newString);
  10091. }
  10092. void StringArray::addIfNotAlreadyThere (const String& newString, const bool ignoreCase)
  10093. {
  10094. if (! contains (newString, ignoreCase))
  10095. add (newString);
  10096. }
  10097. void StringArray::addArray (const StringArray& otherArray, int startIndex, int numElementsToAdd)
  10098. {
  10099. if (startIndex < 0)
  10100. {
  10101. jassertfalse;
  10102. startIndex = 0;
  10103. }
  10104. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > otherArray.size())
  10105. numElementsToAdd = otherArray.size() - startIndex;
  10106. while (--numElementsToAdd >= 0)
  10107. strings.add (otherArray.strings.getReference (startIndex++));
  10108. }
  10109. void StringArray::set (const int index, const String& newString)
  10110. {
  10111. strings.set (index, newString);
  10112. }
  10113. bool StringArray::contains (const String& stringToLookFor, const bool ignoreCase) const
  10114. {
  10115. if (ignoreCase)
  10116. {
  10117. for (int i = size(); --i >= 0;)
  10118. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  10119. return true;
  10120. }
  10121. else
  10122. {
  10123. for (int i = size(); --i >= 0;)
  10124. if (stringToLookFor == strings.getReference(i))
  10125. return true;
  10126. }
  10127. return false;
  10128. }
  10129. int StringArray::indexOf (const String& stringToLookFor, const bool ignoreCase, int i) const
  10130. {
  10131. if (i < 0)
  10132. i = 0;
  10133. const int numElements = size();
  10134. if (ignoreCase)
  10135. {
  10136. while (i < numElements)
  10137. {
  10138. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  10139. return i;
  10140. ++i;
  10141. }
  10142. }
  10143. else
  10144. {
  10145. while (i < numElements)
  10146. {
  10147. if (stringToLookFor == strings.getReference (i))
  10148. return i;
  10149. ++i;
  10150. }
  10151. }
  10152. return -1;
  10153. }
  10154. void StringArray::remove (const int index)
  10155. {
  10156. strings.remove (index);
  10157. }
  10158. void StringArray::removeString (const String& stringToRemove,
  10159. const bool ignoreCase)
  10160. {
  10161. if (ignoreCase)
  10162. {
  10163. for (int i = size(); --i >= 0;)
  10164. if (strings.getReference(i).equalsIgnoreCase (stringToRemove))
  10165. strings.remove (i);
  10166. }
  10167. else
  10168. {
  10169. for (int i = size(); --i >= 0;)
  10170. if (stringToRemove == strings.getReference (i))
  10171. strings.remove (i);
  10172. }
  10173. }
  10174. void StringArray::removeRange (int startIndex, int numberToRemove)
  10175. {
  10176. strings.removeRange (startIndex, numberToRemove);
  10177. }
  10178. void StringArray::removeEmptyStrings (const bool removeWhitespaceStrings)
  10179. {
  10180. if (removeWhitespaceStrings)
  10181. {
  10182. for (int i = size(); --i >= 0;)
  10183. if (! strings.getReference(i).containsNonWhitespaceChars())
  10184. strings.remove (i);
  10185. }
  10186. else
  10187. {
  10188. for (int i = size(); --i >= 0;)
  10189. if (strings.getReference(i).isEmpty())
  10190. strings.remove (i);
  10191. }
  10192. }
  10193. void StringArray::trim()
  10194. {
  10195. for (int i = size(); --i >= 0;)
  10196. {
  10197. String& s = strings.getReference(i);
  10198. s = s.trim();
  10199. }
  10200. }
  10201. class InternalStringArrayComparator_CaseSensitive
  10202. {
  10203. public:
  10204. static int compareElements (String& first, String& second) { return first.compare (second); }
  10205. };
  10206. class InternalStringArrayComparator_CaseInsensitive
  10207. {
  10208. public:
  10209. static int compareElements (String& first, String& second) { return first.compareIgnoreCase (second); }
  10210. };
  10211. void StringArray::sort (const bool ignoreCase)
  10212. {
  10213. if (ignoreCase)
  10214. {
  10215. InternalStringArrayComparator_CaseInsensitive comp;
  10216. strings.sort (comp);
  10217. }
  10218. else
  10219. {
  10220. InternalStringArrayComparator_CaseSensitive comp;
  10221. strings.sort (comp);
  10222. }
  10223. }
  10224. void StringArray::move (const int currentIndex, int newIndex) throw()
  10225. {
  10226. strings.move (currentIndex, newIndex);
  10227. }
  10228. const String StringArray::joinIntoString (const String& separator, int start, int numberToJoin) const
  10229. {
  10230. const int last = (numberToJoin < 0) ? size()
  10231. : jmin (size(), start + numberToJoin);
  10232. if (start < 0)
  10233. start = 0;
  10234. if (start >= last)
  10235. return String::empty;
  10236. if (start == last - 1)
  10237. return strings.getReference (start);
  10238. const int separatorLen = separator.length();
  10239. int charsNeeded = separatorLen * (last - start - 1);
  10240. for (int i = start; i < last; ++i)
  10241. charsNeeded += strings.getReference(i).length();
  10242. String result;
  10243. result.preallocateStorage (charsNeeded);
  10244. juce_wchar* dest = result;
  10245. while (start < last)
  10246. {
  10247. const String& s = strings.getReference (start);
  10248. const int len = s.length();
  10249. if (len > 0)
  10250. {
  10251. s.copyToUnicode (dest, len);
  10252. dest += len;
  10253. }
  10254. if (++start < last && separatorLen > 0)
  10255. {
  10256. separator.copyToUnicode (dest, separatorLen);
  10257. dest += separatorLen;
  10258. }
  10259. }
  10260. *dest = 0;
  10261. return result;
  10262. }
  10263. int StringArray::addTokens (const String& text, const bool preserveQuotedStrings)
  10264. {
  10265. return addTokens (text, " \n\r\t", preserveQuotedStrings ? "\"" : "");
  10266. }
  10267. int StringArray::addTokens (const String& text, const String& breakCharacters, const String& quoteCharacters)
  10268. {
  10269. int num = 0;
  10270. if (text.isNotEmpty())
  10271. {
  10272. bool insideQuotes = false;
  10273. juce_wchar currentQuoteChar = 0;
  10274. int i = 0;
  10275. int tokenStart = 0;
  10276. for (;;)
  10277. {
  10278. const juce_wchar c = text[i];
  10279. const bool isBreak = (c == 0) || ((! insideQuotes) && breakCharacters.containsChar (c));
  10280. if (! isBreak)
  10281. {
  10282. if (quoteCharacters.containsChar (c))
  10283. {
  10284. if (insideQuotes)
  10285. {
  10286. // only break out of quotes-mode if we find a matching quote to the
  10287. // one that we opened with..
  10288. if (currentQuoteChar == c)
  10289. insideQuotes = false;
  10290. }
  10291. else
  10292. {
  10293. insideQuotes = true;
  10294. currentQuoteChar = c;
  10295. }
  10296. }
  10297. }
  10298. else
  10299. {
  10300. add (String (static_cast <const juce_wchar*> (text) + tokenStart, i - tokenStart));
  10301. ++num;
  10302. tokenStart = i + 1;
  10303. }
  10304. if (c == 0)
  10305. break;
  10306. ++i;
  10307. }
  10308. }
  10309. return num;
  10310. }
  10311. int StringArray::addLines (const String& sourceText)
  10312. {
  10313. int numLines = 0;
  10314. const juce_wchar* text = sourceText;
  10315. while (*text != 0)
  10316. {
  10317. const juce_wchar* const startOfLine = text;
  10318. while (*text != 0)
  10319. {
  10320. if (*text == '\r')
  10321. {
  10322. ++text;
  10323. if (*text == '\n')
  10324. ++text;
  10325. break;
  10326. }
  10327. if (*text == '\n')
  10328. {
  10329. ++text;
  10330. break;
  10331. }
  10332. ++text;
  10333. }
  10334. const juce_wchar* endOfLine = text;
  10335. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  10336. --endOfLine;
  10337. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  10338. --endOfLine;
  10339. add (String (startOfLine, jmax (0, (int) (endOfLine - startOfLine))));
  10340. ++numLines;
  10341. }
  10342. return numLines;
  10343. }
  10344. void StringArray::removeDuplicates (const bool ignoreCase)
  10345. {
  10346. for (int i = 0; i < size() - 1; ++i)
  10347. {
  10348. const String s (strings.getReference(i));
  10349. int nextIndex = i + 1;
  10350. for (;;)
  10351. {
  10352. nextIndex = indexOf (s, ignoreCase, nextIndex);
  10353. if (nextIndex < 0)
  10354. break;
  10355. strings.remove (nextIndex);
  10356. }
  10357. }
  10358. }
  10359. void StringArray::appendNumbersToDuplicates (const bool ignoreCase,
  10360. const bool appendNumberToFirstInstance,
  10361. const juce_wchar* preNumberString,
  10362. const juce_wchar* postNumberString)
  10363. {
  10364. if (preNumberString == 0)
  10365. preNumberString = L" (";
  10366. if (postNumberString == 0)
  10367. postNumberString = L")";
  10368. for (int i = 0; i < size() - 1; ++i)
  10369. {
  10370. String& s = strings.getReference(i);
  10371. int nextIndex = indexOf (s, ignoreCase, i + 1);
  10372. if (nextIndex >= 0)
  10373. {
  10374. const String original (s);
  10375. int number = 0;
  10376. if (appendNumberToFirstInstance)
  10377. s = original + preNumberString + String (++number) + postNumberString;
  10378. else
  10379. ++number;
  10380. while (nextIndex >= 0)
  10381. {
  10382. set (nextIndex, (*this)[nextIndex] + preNumberString + String (++number) + postNumberString);
  10383. nextIndex = indexOf (original, ignoreCase, nextIndex + 1);
  10384. }
  10385. }
  10386. }
  10387. }
  10388. void StringArray::minimiseStorageOverheads()
  10389. {
  10390. strings.minimiseStorageOverheads();
  10391. }
  10392. END_JUCE_NAMESPACE
  10393. /*** End of inlined file: juce_StringArray.cpp ***/
  10394. /*** Start of inlined file: juce_StringPairArray.cpp ***/
  10395. BEGIN_JUCE_NAMESPACE
  10396. StringPairArray::StringPairArray (const bool ignoreCase_)
  10397. : ignoreCase (ignoreCase_)
  10398. {
  10399. }
  10400. StringPairArray::StringPairArray (const StringPairArray& other)
  10401. : keys (other.keys),
  10402. values (other.values),
  10403. ignoreCase (other.ignoreCase)
  10404. {
  10405. }
  10406. StringPairArray::~StringPairArray()
  10407. {
  10408. }
  10409. StringPairArray& StringPairArray::operator= (const StringPairArray& other)
  10410. {
  10411. keys = other.keys;
  10412. values = other.values;
  10413. return *this;
  10414. }
  10415. bool StringPairArray::operator== (const StringPairArray& other) const
  10416. {
  10417. for (int i = keys.size(); --i >= 0;)
  10418. if (other [keys[i]] != values[i])
  10419. return false;
  10420. return true;
  10421. }
  10422. bool StringPairArray::operator!= (const StringPairArray& other) const
  10423. {
  10424. return ! operator== (other);
  10425. }
  10426. const String& StringPairArray::operator[] (const String& key) const
  10427. {
  10428. return values [keys.indexOf (key, ignoreCase)];
  10429. }
  10430. const String StringPairArray::getValue (const String& key, const String& defaultReturnValue) const
  10431. {
  10432. const int i = keys.indexOf (key, ignoreCase);
  10433. if (i >= 0)
  10434. return values[i];
  10435. return defaultReturnValue;
  10436. }
  10437. void StringPairArray::set (const String& key, const String& value)
  10438. {
  10439. const int i = keys.indexOf (key, ignoreCase);
  10440. if (i >= 0)
  10441. {
  10442. values.set (i, value);
  10443. }
  10444. else
  10445. {
  10446. keys.add (key);
  10447. values.add (value);
  10448. }
  10449. }
  10450. void StringPairArray::addArray (const StringPairArray& other)
  10451. {
  10452. for (int i = 0; i < other.size(); ++i)
  10453. set (other.keys[i], other.values[i]);
  10454. }
  10455. void StringPairArray::clear()
  10456. {
  10457. keys.clear();
  10458. values.clear();
  10459. }
  10460. void StringPairArray::remove (const String& key)
  10461. {
  10462. remove (keys.indexOf (key, ignoreCase));
  10463. }
  10464. void StringPairArray::remove (const int index)
  10465. {
  10466. keys.remove (index);
  10467. values.remove (index);
  10468. }
  10469. void StringPairArray::setIgnoresCase (const bool shouldIgnoreCase)
  10470. {
  10471. ignoreCase = shouldIgnoreCase;
  10472. }
  10473. const String StringPairArray::getDescription() const
  10474. {
  10475. String s;
  10476. for (int i = 0; i < keys.size(); ++i)
  10477. {
  10478. s << keys[i] << " = " << values[i];
  10479. if (i < keys.size())
  10480. s << ", ";
  10481. }
  10482. return s;
  10483. }
  10484. void StringPairArray::minimiseStorageOverheads()
  10485. {
  10486. keys.minimiseStorageOverheads();
  10487. values.minimiseStorageOverheads();
  10488. }
  10489. END_JUCE_NAMESPACE
  10490. /*** End of inlined file: juce_StringPairArray.cpp ***/
  10491. /*** Start of inlined file: juce_StringPool.cpp ***/
  10492. BEGIN_JUCE_NAMESPACE
  10493. StringPool::StringPool() throw() {}
  10494. StringPool::~StringPool() {}
  10495. template <class StringType>
  10496. static const juce_wchar* getPooledStringFromArray (Array<String>& strings, StringType newString)
  10497. {
  10498. int start = 0;
  10499. int end = strings.size();
  10500. for (;;)
  10501. {
  10502. if (start >= end)
  10503. {
  10504. jassert (start <= end);
  10505. strings.insert (start, newString);
  10506. return strings.getReference (start);
  10507. }
  10508. else
  10509. {
  10510. const String& startString = strings.getReference (start);
  10511. if (startString == newString)
  10512. return startString;
  10513. const int halfway = (start + end) >> 1;
  10514. if (halfway == start)
  10515. {
  10516. if (startString.compare (newString) < 0)
  10517. ++start;
  10518. strings.insert (start, newString);
  10519. return strings.getReference (start);
  10520. }
  10521. const int comp = strings.getReference (halfway).compare (newString);
  10522. if (comp == 0)
  10523. return strings.getReference (halfway);
  10524. else if (comp < 0)
  10525. start = halfway;
  10526. else
  10527. end = halfway;
  10528. }
  10529. }
  10530. }
  10531. const juce_wchar* StringPool::getPooledString (const String& s)
  10532. {
  10533. if (s.isEmpty())
  10534. return String::empty;
  10535. return getPooledStringFromArray (strings, s);
  10536. }
  10537. const juce_wchar* StringPool::getPooledString (const char* const s)
  10538. {
  10539. if (s == 0 || *s == 0)
  10540. return String::empty;
  10541. return getPooledStringFromArray (strings, s);
  10542. }
  10543. const juce_wchar* StringPool::getPooledString (const juce_wchar* const s)
  10544. {
  10545. if (s == 0 || *s == 0)
  10546. return String::empty;
  10547. return getPooledStringFromArray (strings, s);
  10548. }
  10549. int StringPool::size() const throw()
  10550. {
  10551. return strings.size();
  10552. }
  10553. const juce_wchar* StringPool::operator[] (const int index) const throw()
  10554. {
  10555. return strings [index];
  10556. }
  10557. END_JUCE_NAMESPACE
  10558. /*** End of inlined file: juce_StringPool.cpp ***/
  10559. /*** Start of inlined file: juce_XmlDocument.cpp ***/
  10560. BEGIN_JUCE_NAMESPACE
  10561. XmlDocument::XmlDocument (const String& documentText)
  10562. : originalText (documentText),
  10563. ignoreEmptyTextElements (true)
  10564. {
  10565. }
  10566. XmlDocument::XmlDocument (const File& file)
  10567. : ignoreEmptyTextElements (true)
  10568. {
  10569. inputSource = new FileInputSource (file);
  10570. }
  10571. XmlDocument::~XmlDocument()
  10572. {
  10573. }
  10574. void XmlDocument::setInputSource (InputSource* const newSource) throw()
  10575. {
  10576. inputSource = newSource;
  10577. }
  10578. void XmlDocument::setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw()
  10579. {
  10580. ignoreEmptyTextElements = shouldBeIgnored;
  10581. }
  10582. bool XmlDocument::isXmlIdentifierCharSlow (const juce_wchar c) throw()
  10583. {
  10584. return CharacterFunctions::isLetterOrDigit (c)
  10585. || c == '_' || c == '-' || c == ':' || c == '.';
  10586. }
  10587. inline bool XmlDocument::isXmlIdentifierChar (const juce_wchar c) const throw()
  10588. {
  10589. return (c > 0 && c <= 127) ? identifierLookupTable [(int) c]
  10590. : isXmlIdentifierCharSlow (c);
  10591. }
  10592. XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement)
  10593. {
  10594. String textToParse (originalText);
  10595. if (textToParse.isEmpty() && inputSource != 0)
  10596. {
  10597. ScopedPointer <InputStream> in (inputSource->createInputStream());
  10598. if (in != 0)
  10599. {
  10600. MemoryBlock data;
  10601. in->readIntoMemoryBlock (data, onlyReadOuterDocumentElement ? 8192 : -1);
  10602. if (data.getSize() >= 2
  10603. && ((data[0] == (char)-2 && data[1] == (char)-1)
  10604. || (data[0] == (char)-1 && data[1] == (char)-2)))
  10605. {
  10606. textToParse = String::createStringFromData (static_cast <const char*> (data.getData()), (int) data.getSize());
  10607. }
  10608. else
  10609. {
  10610. textToParse = String::fromUTF8 (static_cast <const char*> (data.getData()), (int) data.getSize());
  10611. }
  10612. if (! onlyReadOuterDocumentElement)
  10613. originalText = textToParse;
  10614. }
  10615. }
  10616. input = textToParse;
  10617. lastError = String::empty;
  10618. errorOccurred = false;
  10619. outOfData = false;
  10620. needToLoadDTD = true;
  10621. for (int i = 0; i < 128; ++i)
  10622. identifierLookupTable[i] = isXmlIdentifierCharSlow ((juce_wchar) i);
  10623. if (textToParse.isEmpty())
  10624. {
  10625. lastError = "not enough input";
  10626. }
  10627. else
  10628. {
  10629. skipHeader();
  10630. if (input != 0)
  10631. {
  10632. ScopedPointer <XmlElement> result (readNextElement (! onlyReadOuterDocumentElement));
  10633. if (! errorOccurred)
  10634. return result.release();
  10635. }
  10636. else
  10637. {
  10638. lastError = "incorrect xml header";
  10639. }
  10640. }
  10641. return 0;
  10642. }
  10643. const String& XmlDocument::getLastParseError() const throw()
  10644. {
  10645. return lastError;
  10646. }
  10647. void XmlDocument::setLastError (const String& desc, const bool carryOn)
  10648. {
  10649. lastError = desc;
  10650. errorOccurred = ! carryOn;
  10651. }
  10652. const String XmlDocument::getFileContents (const String& filename) const
  10653. {
  10654. if (inputSource != 0)
  10655. {
  10656. const ScopedPointer <InputStream> in (inputSource->createInputStreamFor (filename.trim().unquoted()));
  10657. if (in != 0)
  10658. return in->readEntireStreamAsString();
  10659. }
  10660. return String::empty;
  10661. }
  10662. juce_wchar XmlDocument::readNextChar() throw()
  10663. {
  10664. if (*input != 0)
  10665. {
  10666. return *input++;
  10667. }
  10668. else
  10669. {
  10670. outOfData = true;
  10671. return 0;
  10672. }
  10673. }
  10674. int XmlDocument::findNextTokenLength() throw()
  10675. {
  10676. int len = 0;
  10677. juce_wchar c = *input;
  10678. while (isXmlIdentifierChar (c))
  10679. c = input [++len];
  10680. return len;
  10681. }
  10682. void XmlDocument::skipHeader()
  10683. {
  10684. const juce_wchar* const found = CharacterFunctions::find (input, JUCE_T("<?xml"));
  10685. if (found != 0)
  10686. {
  10687. input = found;
  10688. input = CharacterFunctions::find (input, JUCE_T("?>"));
  10689. if (input == 0)
  10690. return;
  10691. input += 2;
  10692. }
  10693. skipNextWhiteSpace();
  10694. const juce_wchar* docType = CharacterFunctions::find (input, JUCE_T("<!DOCTYPE"));
  10695. if (docType == 0)
  10696. return;
  10697. input = docType + 9;
  10698. int n = 1;
  10699. while (n > 0)
  10700. {
  10701. const juce_wchar c = readNextChar();
  10702. if (outOfData)
  10703. return;
  10704. if (c == '<')
  10705. ++n;
  10706. else if (c == '>')
  10707. --n;
  10708. }
  10709. docType += 9;
  10710. dtdText = String (docType, (int) (input - (docType + 1))).trim();
  10711. }
  10712. void XmlDocument::skipNextWhiteSpace()
  10713. {
  10714. for (;;)
  10715. {
  10716. juce_wchar c = *input;
  10717. while (CharacterFunctions::isWhitespace (c))
  10718. c = *++input;
  10719. if (c == 0)
  10720. {
  10721. outOfData = true;
  10722. break;
  10723. }
  10724. else if (c == '<')
  10725. {
  10726. if (input[1] == '!'
  10727. && input[2] == '-'
  10728. && input[3] == '-')
  10729. {
  10730. const juce_wchar* const closeComment = CharacterFunctions::find (input, JUCE_T("-->"));
  10731. if (closeComment == 0)
  10732. {
  10733. outOfData = true;
  10734. break;
  10735. }
  10736. input = closeComment + 3;
  10737. continue;
  10738. }
  10739. else if (input[1] == '?')
  10740. {
  10741. const juce_wchar* const closeBracket = CharacterFunctions::find (input, JUCE_T("?>"));
  10742. if (closeBracket == 0)
  10743. {
  10744. outOfData = true;
  10745. break;
  10746. }
  10747. input = closeBracket + 2;
  10748. continue;
  10749. }
  10750. }
  10751. break;
  10752. }
  10753. }
  10754. void XmlDocument::readQuotedString (String& result)
  10755. {
  10756. const juce_wchar quote = readNextChar();
  10757. while (! outOfData)
  10758. {
  10759. const juce_wchar c = readNextChar();
  10760. if (c == quote)
  10761. break;
  10762. if (c == '&')
  10763. {
  10764. --input;
  10765. readEntity (result);
  10766. }
  10767. else
  10768. {
  10769. --input;
  10770. const juce_wchar* const start = input;
  10771. for (;;)
  10772. {
  10773. const juce_wchar character = *input;
  10774. if (character == quote)
  10775. {
  10776. result.append (start, (int) (input - start));
  10777. ++input;
  10778. return;
  10779. }
  10780. else if (character == '&')
  10781. {
  10782. result.append (start, (int) (input - start));
  10783. break;
  10784. }
  10785. else if (character == 0)
  10786. {
  10787. outOfData = true;
  10788. setLastError ("unmatched quotes", false);
  10789. break;
  10790. }
  10791. ++input;
  10792. }
  10793. }
  10794. }
  10795. }
  10796. XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements)
  10797. {
  10798. XmlElement* node = 0;
  10799. skipNextWhiteSpace();
  10800. if (outOfData)
  10801. return 0;
  10802. input = CharacterFunctions::find (input, JUCE_T("<"));
  10803. if (input != 0)
  10804. {
  10805. ++input;
  10806. int tagLen = findNextTokenLength();
  10807. if (tagLen == 0)
  10808. {
  10809. // no tag name - but allow for a gap after the '<' before giving an error
  10810. skipNextWhiteSpace();
  10811. tagLen = findNextTokenLength();
  10812. if (tagLen == 0)
  10813. {
  10814. setLastError ("tag name missing", false);
  10815. return node;
  10816. }
  10817. }
  10818. node = new XmlElement (String (input, tagLen));
  10819. input += tagLen;
  10820. XmlElement::XmlAttributeNode* lastAttribute = 0;
  10821. // look for attributes
  10822. for (;;)
  10823. {
  10824. skipNextWhiteSpace();
  10825. const juce_wchar c = *input;
  10826. // empty tag..
  10827. if (c == '/' && input[1] == '>')
  10828. {
  10829. input += 2;
  10830. break;
  10831. }
  10832. // parse the guts of the element..
  10833. if (c == '>')
  10834. {
  10835. ++input;
  10836. skipNextWhiteSpace();
  10837. if (alsoParseSubElements)
  10838. readChildElements (node);
  10839. break;
  10840. }
  10841. // get an attribute..
  10842. if (isXmlIdentifierChar (c))
  10843. {
  10844. const int attNameLen = findNextTokenLength();
  10845. if (attNameLen > 0)
  10846. {
  10847. const juce_wchar* attNameStart = input;
  10848. input += attNameLen;
  10849. skipNextWhiteSpace();
  10850. if (readNextChar() == '=')
  10851. {
  10852. skipNextWhiteSpace();
  10853. const juce_wchar nextChar = *input;
  10854. if (nextChar == '"' || nextChar == '\'')
  10855. {
  10856. XmlElement::XmlAttributeNode* const newAtt
  10857. = new XmlElement::XmlAttributeNode (String (attNameStart, attNameLen),
  10858. String::empty);
  10859. readQuotedString (newAtt->value);
  10860. if (lastAttribute == 0)
  10861. node->attributes = newAtt;
  10862. else
  10863. lastAttribute->next = newAtt;
  10864. lastAttribute = newAtt;
  10865. continue;
  10866. }
  10867. }
  10868. }
  10869. }
  10870. else
  10871. {
  10872. if (! outOfData)
  10873. setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false);
  10874. }
  10875. break;
  10876. }
  10877. }
  10878. return node;
  10879. }
  10880. void XmlDocument::readChildElements (XmlElement* parent)
  10881. {
  10882. XmlElement* lastChildNode = 0;
  10883. for (;;)
  10884. {
  10885. skipNextWhiteSpace();
  10886. if (outOfData)
  10887. {
  10888. setLastError ("unmatched tags", false);
  10889. break;
  10890. }
  10891. if (*input == '<')
  10892. {
  10893. if (input[1] == '/')
  10894. {
  10895. // our close tag..
  10896. input = CharacterFunctions::find (input, JUCE_T(">"));
  10897. ++input;
  10898. break;
  10899. }
  10900. else if (input[1] == '!'
  10901. && input[2] == '['
  10902. && input[3] == 'C'
  10903. && input[4] == 'D'
  10904. && input[5] == 'A'
  10905. && input[6] == 'T'
  10906. && input[7] == 'A'
  10907. && input[8] == '[')
  10908. {
  10909. input += 9;
  10910. const juce_wchar* const inputStart = input;
  10911. int len = 0;
  10912. for (;;)
  10913. {
  10914. if (*input == 0)
  10915. {
  10916. setLastError ("unterminated CDATA section", false);
  10917. outOfData = true;
  10918. break;
  10919. }
  10920. else if (input[0] == ']'
  10921. && input[1] == ']'
  10922. && input[2] == '>')
  10923. {
  10924. input += 3;
  10925. break;
  10926. }
  10927. ++input;
  10928. ++len;
  10929. }
  10930. XmlElement* const e = new XmlElement ((int) 0);
  10931. e->setText (String (inputStart, len));
  10932. if (lastChildNode != 0)
  10933. lastChildNode->nextElement = e;
  10934. else
  10935. parent->addChildElement (e);
  10936. lastChildNode = e;
  10937. }
  10938. else
  10939. {
  10940. // this is some other element, so parse and add it..
  10941. XmlElement* const n = readNextElement (true);
  10942. if (n != 0)
  10943. {
  10944. if (lastChildNode == 0)
  10945. parent->addChildElement (n);
  10946. else
  10947. lastChildNode->nextElement = n;
  10948. lastChildNode = n;
  10949. }
  10950. else
  10951. {
  10952. return;
  10953. }
  10954. }
  10955. }
  10956. else
  10957. {
  10958. // read character block..
  10959. XmlElement* const e = new XmlElement ((int)0);
  10960. if (lastChildNode != 0)
  10961. lastChildNode->nextElement = e;
  10962. else
  10963. parent->addChildElement (e);
  10964. lastChildNode = e;
  10965. String textElementContent;
  10966. for (;;)
  10967. {
  10968. const juce_wchar c = *input;
  10969. if (c == '<')
  10970. break;
  10971. if (c == 0)
  10972. {
  10973. setLastError ("unmatched tags", false);
  10974. outOfData = true;
  10975. return;
  10976. }
  10977. if (c == '&')
  10978. {
  10979. String entity;
  10980. readEntity (entity);
  10981. if (entity.startsWithChar ('<') && entity [1] != 0)
  10982. {
  10983. const juce_wchar* const oldInput = input;
  10984. const bool oldOutOfData = outOfData;
  10985. input = entity;
  10986. outOfData = false;
  10987. for (;;)
  10988. {
  10989. XmlElement* const n = readNextElement (true);
  10990. if (n == 0)
  10991. break;
  10992. if (lastChildNode == 0)
  10993. parent->addChildElement (n);
  10994. else
  10995. lastChildNode->nextElement = n;
  10996. lastChildNode = n;
  10997. }
  10998. input = oldInput;
  10999. outOfData = oldOutOfData;
  11000. }
  11001. else
  11002. {
  11003. textElementContent += entity;
  11004. }
  11005. }
  11006. else
  11007. {
  11008. const juce_wchar* start = input;
  11009. int len = 0;
  11010. for (;;)
  11011. {
  11012. const juce_wchar nextChar = *input;
  11013. if (nextChar == '<' || nextChar == '&')
  11014. {
  11015. break;
  11016. }
  11017. else if (nextChar == 0)
  11018. {
  11019. setLastError ("unmatched tags", false);
  11020. outOfData = true;
  11021. return;
  11022. }
  11023. ++input;
  11024. ++len;
  11025. }
  11026. textElementContent.append (start, len);
  11027. }
  11028. }
  11029. if (ignoreEmptyTextElements ? textElementContent.containsNonWhitespaceChars()
  11030. : textElementContent.isNotEmpty())
  11031. e->setText (textElementContent);
  11032. }
  11033. }
  11034. }
  11035. void XmlDocument::readEntity (String& result)
  11036. {
  11037. // skip over the ampersand
  11038. ++input;
  11039. if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("amp;"), 4) == 0)
  11040. {
  11041. input += 4;
  11042. result += '&';
  11043. }
  11044. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("quot;"), 5) == 0)
  11045. {
  11046. input += 5;
  11047. result += '"';
  11048. }
  11049. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("apos;"), 5) == 0)
  11050. {
  11051. input += 5;
  11052. result += '\'';
  11053. }
  11054. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("lt;"), 3) == 0)
  11055. {
  11056. input += 3;
  11057. result += '<';
  11058. }
  11059. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("gt;"), 3) == 0)
  11060. {
  11061. input += 3;
  11062. result += '>';
  11063. }
  11064. else if (*input == '#')
  11065. {
  11066. int charCode = 0;
  11067. ++input;
  11068. if (*input == 'x' || *input == 'X')
  11069. {
  11070. ++input;
  11071. int numChars = 0;
  11072. while (input[0] != ';')
  11073. {
  11074. const int hexValue = CharacterFunctions::getHexDigitValue (input[0]);
  11075. if (hexValue < 0 || ++numChars > 8)
  11076. {
  11077. setLastError ("illegal escape sequence", true);
  11078. break;
  11079. }
  11080. charCode = (charCode << 4) | hexValue;
  11081. ++input;
  11082. }
  11083. ++input;
  11084. }
  11085. else if (input[0] >= '0' && input[0] <= '9')
  11086. {
  11087. int numChars = 0;
  11088. while (input[0] != ';')
  11089. {
  11090. if (++numChars > 12)
  11091. {
  11092. setLastError ("illegal escape sequence", true);
  11093. break;
  11094. }
  11095. charCode = charCode * 10 + (input[0] - '0');
  11096. ++input;
  11097. }
  11098. ++input;
  11099. }
  11100. else
  11101. {
  11102. setLastError ("illegal escape sequence", true);
  11103. result += '&';
  11104. return;
  11105. }
  11106. result << (juce_wchar) charCode;
  11107. }
  11108. else
  11109. {
  11110. const juce_wchar* const entityNameStart = input;
  11111. const juce_wchar* const closingSemiColon = CharacterFunctions::find (input, JUCE_T(";"));
  11112. if (closingSemiColon == 0)
  11113. {
  11114. outOfData = true;
  11115. result += '&';
  11116. }
  11117. else
  11118. {
  11119. input = closingSemiColon + 1;
  11120. result += expandExternalEntity (String (entityNameStart,
  11121. (int) (closingSemiColon - entityNameStart)));
  11122. }
  11123. }
  11124. }
  11125. const String XmlDocument::expandEntity (const String& ent)
  11126. {
  11127. if (ent.equalsIgnoreCase ("amp"))
  11128. return String::charToString ('&');
  11129. if (ent.equalsIgnoreCase ("quot"))
  11130. return String::charToString ('"');
  11131. if (ent.equalsIgnoreCase ("apos"))
  11132. return String::charToString ('\'');
  11133. if (ent.equalsIgnoreCase ("lt"))
  11134. return String::charToString ('<');
  11135. if (ent.equalsIgnoreCase ("gt"))
  11136. return String::charToString ('>');
  11137. if (ent[0] == '#')
  11138. {
  11139. if (ent[1] == 'x' || ent[1] == 'X')
  11140. return String::charToString (static_cast <juce_wchar> (ent.substring (2).getHexValue32()));
  11141. if (ent[1] >= '0' && ent[1] <= '9')
  11142. return String::charToString (static_cast <juce_wchar> (ent.substring (1).getIntValue()));
  11143. setLastError ("illegal escape sequence", false);
  11144. return String::charToString ('&');
  11145. }
  11146. return expandExternalEntity (ent);
  11147. }
  11148. const String XmlDocument::expandExternalEntity (const String& entity)
  11149. {
  11150. if (needToLoadDTD)
  11151. {
  11152. if (dtdText.isNotEmpty())
  11153. {
  11154. dtdText = dtdText.trimCharactersAtEnd (">");
  11155. tokenisedDTD.addTokens (dtdText, true);
  11156. if (tokenisedDTD [tokenisedDTD.size() - 2].equalsIgnoreCase ("system")
  11157. && tokenisedDTD [tokenisedDTD.size() - 1].isQuotedString())
  11158. {
  11159. const String fn (tokenisedDTD [tokenisedDTD.size() - 1]);
  11160. tokenisedDTD.clear();
  11161. tokenisedDTD.addTokens (getFileContents (fn), true);
  11162. }
  11163. else
  11164. {
  11165. tokenisedDTD.clear();
  11166. const int openBracket = dtdText.indexOfChar ('[');
  11167. if (openBracket > 0)
  11168. {
  11169. const int closeBracket = dtdText.lastIndexOfChar (']');
  11170. if (closeBracket > openBracket)
  11171. tokenisedDTD.addTokens (dtdText.substring (openBracket + 1,
  11172. closeBracket), true);
  11173. }
  11174. }
  11175. for (int i = tokenisedDTD.size(); --i >= 0;)
  11176. {
  11177. if (tokenisedDTD[i].startsWithChar ('%')
  11178. && tokenisedDTD[i].endsWithChar (';'))
  11179. {
  11180. const String parsed (getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1)));
  11181. StringArray newToks;
  11182. newToks.addTokens (parsed, true);
  11183. tokenisedDTD.remove (i);
  11184. for (int j = newToks.size(); --j >= 0;)
  11185. tokenisedDTD.insert (i, newToks[j]);
  11186. }
  11187. }
  11188. }
  11189. needToLoadDTD = false;
  11190. }
  11191. for (int i = 0; i < tokenisedDTD.size(); ++i)
  11192. {
  11193. if (tokenisedDTD[i] == entity)
  11194. {
  11195. if (tokenisedDTD[i - 1].equalsIgnoreCase ("<!entity"))
  11196. {
  11197. String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">").trim().unquoted());
  11198. // check for sub-entities..
  11199. int ampersand = ent.indexOfChar ('&');
  11200. while (ampersand >= 0)
  11201. {
  11202. const int semiColon = ent.indexOf (i + 1, ";");
  11203. if (semiColon < 0)
  11204. {
  11205. setLastError ("entity without terminating semi-colon", false);
  11206. break;
  11207. }
  11208. const String resolved (expandEntity (ent.substring (i + 1, semiColon)));
  11209. ent = ent.substring (0, ampersand)
  11210. + resolved
  11211. + ent.substring (semiColon + 1);
  11212. ampersand = ent.indexOfChar (semiColon + 1, '&');
  11213. }
  11214. return ent;
  11215. }
  11216. }
  11217. }
  11218. setLastError ("unknown entity", true);
  11219. return entity;
  11220. }
  11221. const String XmlDocument::getParameterEntity (const String& entity)
  11222. {
  11223. for (int i = 0; i < tokenisedDTD.size(); ++i)
  11224. {
  11225. if (tokenisedDTD[i] == entity)
  11226. {
  11227. if (tokenisedDTD [i - 1] == "%"
  11228. && tokenisedDTD [i - 2].equalsIgnoreCase ("<!entity"))
  11229. {
  11230. const String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">"));
  11231. if (ent.equalsIgnoreCase ("system"))
  11232. return getFileContents (tokenisedDTD [i + 2].trimCharactersAtEnd (">"));
  11233. else
  11234. return ent.trim().unquoted();
  11235. }
  11236. }
  11237. }
  11238. return entity;
  11239. }
  11240. END_JUCE_NAMESPACE
  11241. /*** End of inlined file: juce_XmlDocument.cpp ***/
  11242. /*** Start of inlined file: juce_XmlElement.cpp ***/
  11243. BEGIN_JUCE_NAMESPACE
  11244. XmlElement::XmlAttributeNode::XmlAttributeNode (const XmlAttributeNode& other) throw()
  11245. : name (other.name),
  11246. value (other.value),
  11247. next (0)
  11248. {
  11249. }
  11250. XmlElement::XmlAttributeNode::XmlAttributeNode (const String& name_, const String& value_) throw()
  11251. : name (name_),
  11252. value (value_),
  11253. next (0)
  11254. {
  11255. }
  11256. XmlElement::XmlElement (const String& tagName_) throw()
  11257. : tagName (tagName_),
  11258. firstChildElement (0),
  11259. nextElement (0),
  11260. attributes (0)
  11261. {
  11262. // the tag name mustn't be empty, or it'll look like a text element!
  11263. jassert (tagName_.containsNonWhitespaceChars())
  11264. // The tag can't contain spaces or other characters that would create invalid XML!
  11265. jassert (! tagName_.containsAnyOf (" <>/&"));
  11266. }
  11267. XmlElement::XmlElement (int /*dummy*/) throw()
  11268. : firstChildElement (0),
  11269. nextElement (0),
  11270. attributes (0)
  11271. {
  11272. }
  11273. XmlElement::XmlElement (const XmlElement& other)
  11274. : tagName (other.tagName),
  11275. firstChildElement (0),
  11276. nextElement (0),
  11277. attributes (0)
  11278. {
  11279. copyChildrenAndAttributesFrom (other);
  11280. }
  11281. XmlElement& XmlElement::operator= (const XmlElement& other)
  11282. {
  11283. if (this != &other)
  11284. {
  11285. removeAllAttributes();
  11286. deleteAllChildElements();
  11287. tagName = other.tagName;
  11288. copyChildrenAndAttributesFrom (other);
  11289. }
  11290. return *this;
  11291. }
  11292. void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other)
  11293. {
  11294. XmlElement* child = other.firstChildElement;
  11295. XmlElement* lastChild = 0;
  11296. while (child != 0)
  11297. {
  11298. XmlElement* const copiedChild = new XmlElement (*child);
  11299. if (lastChild != 0)
  11300. lastChild->nextElement = copiedChild;
  11301. else
  11302. firstChildElement = copiedChild;
  11303. lastChild = copiedChild;
  11304. child = child->nextElement;
  11305. }
  11306. const XmlAttributeNode* att = other.attributes;
  11307. XmlAttributeNode* lastAtt = 0;
  11308. while (att != 0)
  11309. {
  11310. XmlAttributeNode* const newAtt = new XmlAttributeNode (*att);
  11311. if (lastAtt != 0)
  11312. lastAtt->next = newAtt;
  11313. else
  11314. attributes = newAtt;
  11315. lastAtt = newAtt;
  11316. att = att->next;
  11317. }
  11318. }
  11319. XmlElement::~XmlElement() throw()
  11320. {
  11321. XmlElement* child = firstChildElement;
  11322. while (child != 0)
  11323. {
  11324. XmlElement* const nextChild = child->nextElement;
  11325. delete child;
  11326. child = nextChild;
  11327. }
  11328. XmlAttributeNode* att = attributes;
  11329. while (att != 0)
  11330. {
  11331. XmlAttributeNode* const nextAtt = att->next;
  11332. delete att;
  11333. att = nextAtt;
  11334. }
  11335. }
  11336. namespace XmlOutputFunctions
  11337. {
  11338. /*static bool isLegalXmlCharSlow (const juce_wchar character) throw()
  11339. {
  11340. if ((character >= 'a' && character <= 'z')
  11341. || (character >= 'A' && character <= 'Z')
  11342. || (character >= '0' && character <= '9'))
  11343. return true;
  11344. const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}$|";
  11345. do
  11346. {
  11347. if (((juce_wchar) (uint8) *t) == character)
  11348. return true;
  11349. }
  11350. while (*++t != 0);
  11351. return false;
  11352. }
  11353. static void generateLegalCharConstants()
  11354. {
  11355. uint8 n[32];
  11356. zerostruct (n);
  11357. for (int i = 0; i < 256; ++i)
  11358. if (isLegalXmlCharSlow (i))
  11359. n[i >> 3] |= (1 << (i & 7));
  11360. String s;
  11361. for (int i = 0; i < 32; ++i)
  11362. s << (int) n[i] << ", ";
  11363. DBG (s);
  11364. }*/
  11365. static bool isLegalXmlChar (const uint32 c) throw()
  11366. {
  11367. static const unsigned char legalChars[] = { 0, 0, 0, 0, 187, 255, 255, 175, 255, 255, 255, 191, 254, 255, 255, 127 };
  11368. return c < sizeof (legalChars) * 8
  11369. && (legalChars [c >> 3] & (1 << (c & 7))) != 0;
  11370. }
  11371. static void escapeIllegalXmlChars (OutputStream& outputStream, const String& text, const bool changeNewLines)
  11372. {
  11373. const juce_wchar* t = text;
  11374. for (;;)
  11375. {
  11376. const juce_wchar character = *t++;
  11377. if (character == 0)
  11378. {
  11379. break;
  11380. }
  11381. else if (isLegalXmlChar ((uint32) character))
  11382. {
  11383. outputStream << (char) character;
  11384. }
  11385. else
  11386. {
  11387. switch (character)
  11388. {
  11389. case '&': outputStream << "&amp;"; break;
  11390. case '"': outputStream << "&quot;"; break;
  11391. case '>': outputStream << "&gt;"; break;
  11392. case '<': outputStream << "&lt;"; break;
  11393. case '\n':
  11394. if (changeNewLines)
  11395. outputStream << "&#10;";
  11396. else
  11397. outputStream << (char) character;
  11398. break;
  11399. case '\r':
  11400. if (changeNewLines)
  11401. outputStream << "&#13;";
  11402. else
  11403. outputStream << (char) character;
  11404. break;
  11405. default:
  11406. outputStream << "&#" << ((int) (unsigned int) character) << ';';
  11407. break;
  11408. }
  11409. }
  11410. }
  11411. }
  11412. static void writeSpaces (OutputStream& out, int numSpaces)
  11413. {
  11414. if (numSpaces > 0)
  11415. {
  11416. const char* const blanks = " ";
  11417. const int blankSize = (int) sizeof (blanks) - 1;
  11418. while (numSpaces > blankSize)
  11419. {
  11420. out.write (blanks, blankSize);
  11421. numSpaces -= blankSize;
  11422. }
  11423. out.write (blanks, numSpaces);
  11424. }
  11425. }
  11426. }
  11427. void XmlElement::writeElementAsText (OutputStream& outputStream,
  11428. const int indentationLevel,
  11429. const int lineWrapLength) const
  11430. {
  11431. using namespace XmlOutputFunctions;
  11432. writeSpaces (outputStream, indentationLevel);
  11433. if (! isTextElement())
  11434. {
  11435. outputStream.writeByte ('<');
  11436. outputStream << tagName;
  11437. const int attIndent = indentationLevel + tagName.length() + 1;
  11438. int lineLen = 0;
  11439. const XmlAttributeNode* att = attributes;
  11440. while (att != 0)
  11441. {
  11442. if (lineLen > lineWrapLength && indentationLevel >= 0)
  11443. {
  11444. outputStream.write ("\r\n", 2);
  11445. writeSpaces (outputStream, attIndent);
  11446. lineLen = 0;
  11447. }
  11448. const int64 startPos = outputStream.getPosition();
  11449. outputStream.writeByte (' ');
  11450. outputStream << att->name;
  11451. outputStream.write ("=\"", 2);
  11452. escapeIllegalXmlChars (outputStream, att->value, true);
  11453. outputStream.writeByte ('"');
  11454. lineLen += (int) (outputStream.getPosition() - startPos);
  11455. att = att->next;
  11456. }
  11457. if (firstChildElement != 0)
  11458. {
  11459. XmlElement* child = firstChildElement;
  11460. if (child->nextElement == 0 && child->isTextElement())
  11461. {
  11462. outputStream.writeByte ('>');
  11463. escapeIllegalXmlChars (outputStream, child->getText(), false);
  11464. }
  11465. else
  11466. {
  11467. if (indentationLevel >= 0)
  11468. outputStream.write (">\r\n", 3);
  11469. else
  11470. outputStream.writeByte ('>');
  11471. bool lastWasTextNode = false;
  11472. while (child != 0)
  11473. {
  11474. if (child->isTextElement())
  11475. {
  11476. if ((! lastWasTextNode) && (indentationLevel >= 0))
  11477. writeSpaces (outputStream, indentationLevel + 2);
  11478. escapeIllegalXmlChars (outputStream, child->getText(), false);
  11479. lastWasTextNode = true;
  11480. }
  11481. else
  11482. {
  11483. if (indentationLevel >= 0)
  11484. {
  11485. if (lastWasTextNode)
  11486. outputStream.write ("\r\n", 2);
  11487. child->writeElementAsText (outputStream, indentationLevel + 2, lineWrapLength);
  11488. }
  11489. else
  11490. {
  11491. child->writeElementAsText (outputStream, indentationLevel, lineWrapLength);
  11492. }
  11493. lastWasTextNode = false;
  11494. }
  11495. child = child->nextElement;
  11496. }
  11497. if (indentationLevel >= 0)
  11498. {
  11499. if (lastWasTextNode)
  11500. outputStream.write ("\r\n", 2);
  11501. writeSpaces (outputStream, indentationLevel);
  11502. }
  11503. }
  11504. outputStream.write ("</", 2);
  11505. outputStream << tagName;
  11506. if (indentationLevel >= 0)
  11507. outputStream.write (">\r\n", 3);
  11508. else
  11509. outputStream.writeByte ('>');
  11510. }
  11511. else
  11512. {
  11513. if (indentationLevel >= 0)
  11514. outputStream.write ("/>\r\n", 4);
  11515. else
  11516. outputStream.write ("/>", 2);
  11517. }
  11518. }
  11519. else
  11520. {
  11521. if (indentationLevel >= 0)
  11522. writeSpaces (outputStream, indentationLevel + 2);
  11523. escapeIllegalXmlChars (outputStream, getText(), false);
  11524. }
  11525. }
  11526. const String XmlElement::createDocument (const String& dtdToUse,
  11527. const bool allOnOneLine,
  11528. const bool includeXmlHeader,
  11529. const String& encodingType,
  11530. const int lineWrapLength) const
  11531. {
  11532. MemoryOutputStream mem (2048, 4096);
  11533. writeToStream (mem, dtdToUse, allOnOneLine, includeXmlHeader, encodingType, lineWrapLength);
  11534. return mem.toUTF8();
  11535. }
  11536. void XmlElement::writeToStream (OutputStream& output,
  11537. const String& dtdToUse,
  11538. const bool allOnOneLine,
  11539. const bool includeXmlHeader,
  11540. const String& encodingType,
  11541. const int lineWrapLength) const
  11542. {
  11543. if (includeXmlHeader)
  11544. output << "<?xml version=\"1.0\" encoding=\"" << encodingType
  11545. << (allOnOneLine ? "\"?> " : "\"?>\r\n\r\n");
  11546. if (dtdToUse.isNotEmpty())
  11547. output << dtdToUse << (allOnOneLine ? " " : "\r\n");
  11548. writeElementAsText (output, allOnOneLine ? -1 : 0, lineWrapLength);
  11549. }
  11550. bool XmlElement::writeToFile (const File& file,
  11551. const String& dtdToUse,
  11552. const String& encodingType,
  11553. const int lineWrapLength) const
  11554. {
  11555. if (file.hasWriteAccess())
  11556. {
  11557. TemporaryFile tempFile (file);
  11558. ScopedPointer <FileOutputStream> out (tempFile.getFile().createOutputStream());
  11559. if (out != 0)
  11560. {
  11561. writeToStream (*out, dtdToUse, false, true, encodingType, lineWrapLength);
  11562. out = 0;
  11563. return tempFile.overwriteTargetFileWithTemporary();
  11564. }
  11565. }
  11566. return false;
  11567. }
  11568. bool XmlElement::hasTagName (const String& tagNameWanted) const throw()
  11569. {
  11570. #if JUCE_DEBUG
  11571. // if debugging, check that the case is actually the same, because
  11572. // valid xml is case-sensitive, and although this lets it pass, it's
  11573. // better not to..
  11574. if (tagName.equalsIgnoreCase (tagNameWanted))
  11575. {
  11576. jassert (tagName == tagNameWanted);
  11577. return true;
  11578. }
  11579. else
  11580. {
  11581. return false;
  11582. }
  11583. #else
  11584. return tagName.equalsIgnoreCase (tagNameWanted);
  11585. #endif
  11586. }
  11587. XmlElement* XmlElement::getNextElementWithTagName (const String& requiredTagName) const
  11588. {
  11589. XmlElement* e = nextElement;
  11590. while (e != 0 && ! e->hasTagName (requiredTagName))
  11591. e = e->nextElement;
  11592. return e;
  11593. }
  11594. int XmlElement::getNumAttributes() const throw()
  11595. {
  11596. const XmlAttributeNode* att = attributes;
  11597. int count = 0;
  11598. while (att != 0)
  11599. {
  11600. att = att->next;
  11601. ++count;
  11602. }
  11603. return count;
  11604. }
  11605. const String& XmlElement::getAttributeName (const int index) const throw()
  11606. {
  11607. const XmlAttributeNode* att = attributes;
  11608. int count = 0;
  11609. while (att != 0)
  11610. {
  11611. if (count == index)
  11612. return att->name;
  11613. att = att->next;
  11614. ++count;
  11615. }
  11616. return String::empty;
  11617. }
  11618. const String& XmlElement::getAttributeValue (const int index) const throw()
  11619. {
  11620. const XmlAttributeNode* att = attributes;
  11621. int count = 0;
  11622. while (att != 0)
  11623. {
  11624. if (count == index)
  11625. return att->value;
  11626. att = att->next;
  11627. ++count;
  11628. }
  11629. return String::empty;
  11630. }
  11631. bool XmlElement::hasAttribute (const String& attributeName) const throw()
  11632. {
  11633. const XmlAttributeNode* att = attributes;
  11634. while (att != 0)
  11635. {
  11636. if (att->name.equalsIgnoreCase (attributeName))
  11637. return true;
  11638. att = att->next;
  11639. }
  11640. return false;
  11641. }
  11642. const String& XmlElement::getStringAttribute (const String& attributeName) const throw()
  11643. {
  11644. const XmlAttributeNode* att = attributes;
  11645. while (att != 0)
  11646. {
  11647. if (att->name.equalsIgnoreCase (attributeName))
  11648. return att->value;
  11649. att = att->next;
  11650. }
  11651. return String::empty;
  11652. }
  11653. const String XmlElement::getStringAttribute (const String& attributeName, const String& defaultReturnValue) const
  11654. {
  11655. const XmlAttributeNode* att = attributes;
  11656. while (att != 0)
  11657. {
  11658. if (att->name.equalsIgnoreCase (attributeName))
  11659. return att->value;
  11660. att = att->next;
  11661. }
  11662. return defaultReturnValue;
  11663. }
  11664. int XmlElement::getIntAttribute (const String& attributeName, const int defaultReturnValue) const
  11665. {
  11666. const XmlAttributeNode* att = attributes;
  11667. while (att != 0)
  11668. {
  11669. if (att->name.equalsIgnoreCase (attributeName))
  11670. return att->value.getIntValue();
  11671. att = att->next;
  11672. }
  11673. return defaultReturnValue;
  11674. }
  11675. double XmlElement::getDoubleAttribute (const String& attributeName, const double defaultReturnValue) const
  11676. {
  11677. const XmlAttributeNode* att = attributes;
  11678. while (att != 0)
  11679. {
  11680. if (att->name.equalsIgnoreCase (attributeName))
  11681. return att->value.getDoubleValue();
  11682. att = att->next;
  11683. }
  11684. return defaultReturnValue;
  11685. }
  11686. bool XmlElement::getBoolAttribute (const String& attributeName, const bool defaultReturnValue) const
  11687. {
  11688. const XmlAttributeNode* att = attributes;
  11689. while (att != 0)
  11690. {
  11691. if (att->name.equalsIgnoreCase (attributeName))
  11692. {
  11693. juce_wchar firstChar = att->value[0];
  11694. if (CharacterFunctions::isWhitespace (firstChar))
  11695. firstChar = att->value.trimStart() [0];
  11696. return firstChar == '1'
  11697. || firstChar == 't'
  11698. || firstChar == 'y'
  11699. || firstChar == 'T'
  11700. || firstChar == 'Y';
  11701. }
  11702. att = att->next;
  11703. }
  11704. return defaultReturnValue;
  11705. }
  11706. bool XmlElement::compareAttribute (const String& attributeName,
  11707. const String& stringToCompareAgainst,
  11708. const bool ignoreCase) const throw()
  11709. {
  11710. const XmlAttributeNode* att = attributes;
  11711. while (att != 0)
  11712. {
  11713. if (att->name.equalsIgnoreCase (attributeName))
  11714. {
  11715. if (ignoreCase)
  11716. return att->value.equalsIgnoreCase (stringToCompareAgainst);
  11717. else
  11718. return att->value == stringToCompareAgainst;
  11719. }
  11720. att = att->next;
  11721. }
  11722. return false;
  11723. }
  11724. void XmlElement::setAttribute (const String& attributeName, const String& value)
  11725. {
  11726. #if JUCE_DEBUG
  11727. // check the identifier being passed in is legal..
  11728. const juce_wchar* t = attributeName;
  11729. while (*t != 0)
  11730. {
  11731. jassert (CharacterFunctions::isLetterOrDigit (*t)
  11732. || *t == '_'
  11733. || *t == '-'
  11734. || *t == ':');
  11735. ++t;
  11736. }
  11737. #endif
  11738. if (attributes == 0)
  11739. {
  11740. attributes = new XmlAttributeNode (attributeName, value);
  11741. }
  11742. else
  11743. {
  11744. XmlAttributeNode* att = attributes;
  11745. for (;;)
  11746. {
  11747. if (att->name.equalsIgnoreCase (attributeName))
  11748. {
  11749. att->value = value;
  11750. break;
  11751. }
  11752. else if (att->next == 0)
  11753. {
  11754. att->next = new XmlAttributeNode (attributeName, value);
  11755. break;
  11756. }
  11757. att = att->next;
  11758. }
  11759. }
  11760. }
  11761. void XmlElement::setAttribute (const String& attributeName, const int number)
  11762. {
  11763. setAttribute (attributeName, String (number));
  11764. }
  11765. void XmlElement::setAttribute (const String& attributeName, const double number)
  11766. {
  11767. setAttribute (attributeName, String (number));
  11768. }
  11769. void XmlElement::removeAttribute (const String& attributeName) throw()
  11770. {
  11771. XmlAttributeNode* att = attributes;
  11772. XmlAttributeNode* lastAtt = 0;
  11773. while (att != 0)
  11774. {
  11775. if (att->name.equalsIgnoreCase (attributeName))
  11776. {
  11777. if (lastAtt == 0)
  11778. attributes = att->next;
  11779. else
  11780. lastAtt->next = att->next;
  11781. delete att;
  11782. break;
  11783. }
  11784. lastAtt = att;
  11785. att = att->next;
  11786. }
  11787. }
  11788. void XmlElement::removeAllAttributes() throw()
  11789. {
  11790. while (attributes != 0)
  11791. {
  11792. XmlAttributeNode* const nextAtt = attributes->next;
  11793. delete attributes;
  11794. attributes = nextAtt;
  11795. }
  11796. }
  11797. int XmlElement::getNumChildElements() const throw()
  11798. {
  11799. int count = 0;
  11800. const XmlElement* child = firstChildElement;
  11801. while (child != 0)
  11802. {
  11803. ++count;
  11804. child = child->nextElement;
  11805. }
  11806. return count;
  11807. }
  11808. XmlElement* XmlElement::getChildElement (const int index) const throw()
  11809. {
  11810. int count = 0;
  11811. XmlElement* child = firstChildElement;
  11812. while (child != 0 && count < index)
  11813. {
  11814. child = child->nextElement;
  11815. ++count;
  11816. }
  11817. return child;
  11818. }
  11819. XmlElement* XmlElement::getChildByName (const String& childName) const throw()
  11820. {
  11821. XmlElement* child = firstChildElement;
  11822. while (child != 0)
  11823. {
  11824. if (child->hasTagName (childName))
  11825. break;
  11826. child = child->nextElement;
  11827. }
  11828. return child;
  11829. }
  11830. void XmlElement::addChildElement (XmlElement* const newNode) throw()
  11831. {
  11832. if (newNode != 0)
  11833. {
  11834. if (firstChildElement == 0)
  11835. {
  11836. firstChildElement = newNode;
  11837. }
  11838. else
  11839. {
  11840. XmlElement* child = firstChildElement;
  11841. while (child->nextElement != 0)
  11842. child = child->nextElement;
  11843. child->nextElement = newNode;
  11844. // if this is non-zero, then something's probably
  11845. // gone wrong..
  11846. jassert (newNode->nextElement == 0);
  11847. }
  11848. }
  11849. }
  11850. void XmlElement::insertChildElement (XmlElement* const newNode,
  11851. int indexToInsertAt) throw()
  11852. {
  11853. if (newNode != 0)
  11854. {
  11855. removeChildElement (newNode, false);
  11856. if (indexToInsertAt == 0)
  11857. {
  11858. newNode->nextElement = firstChildElement;
  11859. firstChildElement = newNode;
  11860. }
  11861. else
  11862. {
  11863. if (firstChildElement == 0)
  11864. {
  11865. firstChildElement = newNode;
  11866. }
  11867. else
  11868. {
  11869. if (indexToInsertAt < 0)
  11870. indexToInsertAt = std::numeric_limits<int>::max();
  11871. XmlElement* child = firstChildElement;
  11872. while (child->nextElement != 0 && --indexToInsertAt > 0)
  11873. child = child->nextElement;
  11874. newNode->nextElement = child->nextElement;
  11875. child->nextElement = newNode;
  11876. }
  11877. }
  11878. }
  11879. }
  11880. XmlElement* XmlElement::createNewChildElement (const String& childTagName)
  11881. {
  11882. XmlElement* const newElement = new XmlElement (childTagName);
  11883. addChildElement (newElement);
  11884. return newElement;
  11885. }
  11886. bool XmlElement::replaceChildElement (XmlElement* const currentChildElement,
  11887. XmlElement* const newNode) throw()
  11888. {
  11889. if (newNode != 0)
  11890. {
  11891. XmlElement* child = firstChildElement;
  11892. XmlElement* previousNode = 0;
  11893. while (child != 0)
  11894. {
  11895. if (child == currentChildElement)
  11896. {
  11897. if (child != newNode)
  11898. {
  11899. if (previousNode == 0)
  11900. firstChildElement = newNode;
  11901. else
  11902. previousNode->nextElement = newNode;
  11903. newNode->nextElement = child->nextElement;
  11904. delete child;
  11905. }
  11906. return true;
  11907. }
  11908. previousNode = child;
  11909. child = child->nextElement;
  11910. }
  11911. }
  11912. return false;
  11913. }
  11914. void XmlElement::removeChildElement (XmlElement* const childToRemove,
  11915. const bool shouldDeleteTheChild) throw()
  11916. {
  11917. if (childToRemove != 0)
  11918. {
  11919. if (firstChildElement == childToRemove)
  11920. {
  11921. firstChildElement = childToRemove->nextElement;
  11922. childToRemove->nextElement = 0;
  11923. }
  11924. else
  11925. {
  11926. XmlElement* child = firstChildElement;
  11927. XmlElement* last = 0;
  11928. while (child != 0)
  11929. {
  11930. if (child == childToRemove)
  11931. {
  11932. if (last == 0)
  11933. firstChildElement = child->nextElement;
  11934. else
  11935. last->nextElement = child->nextElement;
  11936. childToRemove->nextElement = 0;
  11937. break;
  11938. }
  11939. last = child;
  11940. child = child->nextElement;
  11941. }
  11942. }
  11943. if (shouldDeleteTheChild)
  11944. delete childToRemove;
  11945. }
  11946. }
  11947. bool XmlElement::isEquivalentTo (const XmlElement* const other,
  11948. const bool ignoreOrderOfAttributes) const throw()
  11949. {
  11950. if (this != other)
  11951. {
  11952. if (other == 0 || tagName != other->tagName)
  11953. {
  11954. return false;
  11955. }
  11956. if (ignoreOrderOfAttributes)
  11957. {
  11958. int totalAtts = 0;
  11959. const XmlAttributeNode* att = attributes;
  11960. while (att != 0)
  11961. {
  11962. if (! other->compareAttribute (att->name, att->value))
  11963. return false;
  11964. att = att->next;
  11965. ++totalAtts;
  11966. }
  11967. if (totalAtts != other->getNumAttributes())
  11968. return false;
  11969. }
  11970. else
  11971. {
  11972. const XmlAttributeNode* thisAtt = attributes;
  11973. const XmlAttributeNode* otherAtt = other->attributes;
  11974. for (;;)
  11975. {
  11976. if (thisAtt == 0 || otherAtt == 0)
  11977. {
  11978. if (thisAtt == otherAtt) // both 0, so it's a match
  11979. break;
  11980. return false;
  11981. }
  11982. if (thisAtt->name != otherAtt->name
  11983. || thisAtt->value != otherAtt->value)
  11984. {
  11985. return false;
  11986. }
  11987. thisAtt = thisAtt->next;
  11988. otherAtt = otherAtt->next;
  11989. }
  11990. }
  11991. const XmlElement* thisChild = firstChildElement;
  11992. const XmlElement* otherChild = other->firstChildElement;
  11993. for (;;)
  11994. {
  11995. if (thisChild == 0 || otherChild == 0)
  11996. {
  11997. if (thisChild == otherChild) // both 0, so it's a match
  11998. break;
  11999. return false;
  12000. }
  12001. if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes))
  12002. return false;
  12003. thisChild = thisChild->nextElement;
  12004. otherChild = otherChild->nextElement;
  12005. }
  12006. }
  12007. return true;
  12008. }
  12009. void XmlElement::deleteAllChildElements() throw()
  12010. {
  12011. while (firstChildElement != 0)
  12012. {
  12013. XmlElement* const nextChild = firstChildElement->nextElement;
  12014. delete firstChildElement;
  12015. firstChildElement = nextChild;
  12016. }
  12017. }
  12018. void XmlElement::deleteAllChildElementsWithTagName (const String& name) throw()
  12019. {
  12020. XmlElement* child = firstChildElement;
  12021. while (child != 0)
  12022. {
  12023. if (child->hasTagName (name))
  12024. {
  12025. XmlElement* const nextChild = child->nextElement;
  12026. removeChildElement (child, true);
  12027. child = nextChild;
  12028. }
  12029. else
  12030. {
  12031. child = child->nextElement;
  12032. }
  12033. }
  12034. }
  12035. bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const throw()
  12036. {
  12037. const XmlElement* child = firstChildElement;
  12038. while (child != 0)
  12039. {
  12040. if (child == possibleChild)
  12041. return true;
  12042. child = child->nextElement;
  12043. }
  12044. return false;
  12045. }
  12046. XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) throw()
  12047. {
  12048. if (this == elementToLookFor || elementToLookFor == 0)
  12049. return 0;
  12050. XmlElement* child = firstChildElement;
  12051. while (child != 0)
  12052. {
  12053. if (elementToLookFor == child)
  12054. return this;
  12055. XmlElement* const found = child->findParentElementOf (elementToLookFor);
  12056. if (found != 0)
  12057. return found;
  12058. child = child->nextElement;
  12059. }
  12060. return 0;
  12061. }
  12062. void XmlElement::getChildElementsAsArray (XmlElement** elems) const throw()
  12063. {
  12064. XmlElement* e = firstChildElement;
  12065. while (e != 0)
  12066. {
  12067. *elems++ = e;
  12068. e = e->nextElement;
  12069. }
  12070. }
  12071. void XmlElement::reorderChildElements (XmlElement** const elems, const int num) throw()
  12072. {
  12073. XmlElement* e = firstChildElement = elems[0];
  12074. for (int i = 1; i < num; ++i)
  12075. {
  12076. e->nextElement = elems[i];
  12077. e = e->nextElement;
  12078. }
  12079. e->nextElement = 0;
  12080. }
  12081. bool XmlElement::isTextElement() const throw()
  12082. {
  12083. return tagName.isEmpty();
  12084. }
  12085. static const juce_wchar* const juce_xmltextContentAttributeName = L"text";
  12086. const String& XmlElement::getText() const throw()
  12087. {
  12088. jassert (isTextElement()); // you're trying to get the text from an element that
  12089. // isn't actually a text element.. If this contains text sub-nodes, you
  12090. // probably want to use getAllSubText instead.
  12091. return getStringAttribute (juce_xmltextContentAttributeName);
  12092. }
  12093. void XmlElement::setText (const String& newText)
  12094. {
  12095. if (isTextElement())
  12096. setAttribute (juce_xmltextContentAttributeName, newText);
  12097. else
  12098. jassertfalse; // you can only change the text in a text element, not a normal one.
  12099. }
  12100. const String XmlElement::getAllSubText() const
  12101. {
  12102. String result;
  12103. String::Concatenator concatenator (result);
  12104. const XmlElement* child = firstChildElement;
  12105. while (child != 0)
  12106. {
  12107. if (child->isTextElement())
  12108. concatenator.append (child->getText());
  12109. child = child->nextElement;
  12110. }
  12111. return result;
  12112. }
  12113. const String XmlElement::getChildElementAllSubText (const String& childTagName,
  12114. const String& defaultReturnValue) const
  12115. {
  12116. const XmlElement* const child = getChildByName (childTagName);
  12117. if (child != 0)
  12118. return child->getAllSubText();
  12119. return defaultReturnValue;
  12120. }
  12121. XmlElement* XmlElement::createTextElement (const String& text)
  12122. {
  12123. XmlElement* const e = new XmlElement ((int) 0);
  12124. e->setAttribute (juce_xmltextContentAttributeName, text);
  12125. return e;
  12126. }
  12127. void XmlElement::addTextElement (const String& text)
  12128. {
  12129. addChildElement (createTextElement (text));
  12130. }
  12131. void XmlElement::deleteAllTextElements() throw()
  12132. {
  12133. XmlElement* child = firstChildElement;
  12134. while (child != 0)
  12135. {
  12136. XmlElement* const next = child->nextElement;
  12137. if (child->isTextElement())
  12138. removeChildElement (child, true);
  12139. child = next;
  12140. }
  12141. }
  12142. END_JUCE_NAMESPACE
  12143. /*** End of inlined file: juce_XmlElement.cpp ***/
  12144. /*** Start of inlined file: juce_ReadWriteLock.cpp ***/
  12145. BEGIN_JUCE_NAMESPACE
  12146. ReadWriteLock::ReadWriteLock() throw()
  12147. : numWaitingWriters (0),
  12148. numWriters (0),
  12149. writerThreadId (0)
  12150. {
  12151. }
  12152. ReadWriteLock::~ReadWriteLock() throw()
  12153. {
  12154. jassert (readerThreads.size() == 0);
  12155. jassert (numWriters == 0);
  12156. }
  12157. void ReadWriteLock::enterRead() const throw()
  12158. {
  12159. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12160. const ScopedLock sl (accessLock);
  12161. for (;;)
  12162. {
  12163. jassert (readerThreads.size() % 2 == 0);
  12164. int i;
  12165. for (i = 0; i < readerThreads.size(); i += 2)
  12166. if (readerThreads.getUnchecked(i) == threadId)
  12167. break;
  12168. if (i < readerThreads.size()
  12169. || numWriters + numWaitingWriters == 0
  12170. || (threadId == writerThreadId && numWriters > 0))
  12171. {
  12172. if (i < readerThreads.size())
  12173. {
  12174. readerThreads.set (i + 1, (Thread::ThreadID) (1 + (pointer_sized_int) readerThreads.getUnchecked (i + 1)));
  12175. }
  12176. else
  12177. {
  12178. readerThreads.add (threadId);
  12179. readerThreads.add ((Thread::ThreadID) 1);
  12180. }
  12181. return;
  12182. }
  12183. const ScopedUnlock ul (accessLock);
  12184. waitEvent.wait (100);
  12185. }
  12186. }
  12187. void ReadWriteLock::exitRead() const throw()
  12188. {
  12189. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12190. const ScopedLock sl (accessLock);
  12191. for (int i = 0; i < readerThreads.size(); i += 2)
  12192. {
  12193. if (readerThreads.getUnchecked(i) == threadId)
  12194. {
  12195. const pointer_sized_int newCount = ((pointer_sized_int) readerThreads.getUnchecked (i + 1)) - 1;
  12196. if (newCount == 0)
  12197. {
  12198. readerThreads.removeRange (i, 2);
  12199. waitEvent.signal();
  12200. }
  12201. else
  12202. {
  12203. readerThreads.set (i + 1, (Thread::ThreadID) newCount);
  12204. }
  12205. return;
  12206. }
  12207. }
  12208. jassertfalse; // unlocking a lock that wasn't locked..
  12209. }
  12210. void ReadWriteLock::enterWrite() const throw()
  12211. {
  12212. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12213. const ScopedLock sl (accessLock);
  12214. for (;;)
  12215. {
  12216. if (readerThreads.size() + numWriters == 0
  12217. || threadId == writerThreadId
  12218. || (readerThreads.size() == 2
  12219. && readerThreads.getUnchecked(0) == threadId))
  12220. {
  12221. writerThreadId = threadId;
  12222. ++numWriters;
  12223. break;
  12224. }
  12225. ++numWaitingWriters;
  12226. accessLock.exit();
  12227. waitEvent.wait (100);
  12228. accessLock.enter();
  12229. --numWaitingWriters;
  12230. }
  12231. }
  12232. bool ReadWriteLock::tryEnterWrite() const throw()
  12233. {
  12234. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12235. const ScopedLock sl (accessLock);
  12236. if (readerThreads.size() + numWriters == 0
  12237. || threadId == writerThreadId
  12238. || (readerThreads.size() == 2
  12239. && readerThreads.getUnchecked(0) == threadId))
  12240. {
  12241. writerThreadId = threadId;
  12242. ++numWriters;
  12243. return true;
  12244. }
  12245. return false;
  12246. }
  12247. void ReadWriteLock::exitWrite() const throw()
  12248. {
  12249. const ScopedLock sl (accessLock);
  12250. // check this thread actually had the lock..
  12251. jassert (numWriters > 0 && writerThreadId == Thread::getCurrentThreadId());
  12252. if (--numWriters == 0)
  12253. {
  12254. writerThreadId = 0;
  12255. waitEvent.signal();
  12256. }
  12257. }
  12258. END_JUCE_NAMESPACE
  12259. /*** End of inlined file: juce_ReadWriteLock.cpp ***/
  12260. /*** Start of inlined file: juce_Thread.cpp ***/
  12261. BEGIN_JUCE_NAMESPACE
  12262. // these functions are implemented in the platform-specific code.
  12263. void* juce_createThread (void* userData);
  12264. void juce_killThread (void* handle);
  12265. bool juce_setThreadPriority (void* handle, int priority);
  12266. void juce_setCurrentThreadName (const String& name);
  12267. #if JUCE_WINDOWS
  12268. void juce_CloseThreadHandle (void* handle);
  12269. #endif
  12270. void Thread::threadEntryPoint (Thread* const thread)
  12271. {
  12272. {
  12273. const ScopedLock sl (runningThreadsLock);
  12274. runningThreads.add (thread);
  12275. }
  12276. JUCE_TRY
  12277. {
  12278. thread->threadId_ = Thread::getCurrentThreadId();
  12279. if (thread->threadName_.isNotEmpty())
  12280. juce_setCurrentThreadName (thread->threadName_);
  12281. if (thread->startSuspensionEvent_.wait (10000))
  12282. {
  12283. if (thread->affinityMask_ != 0)
  12284. setCurrentThreadAffinityMask (thread->affinityMask_);
  12285. thread->run();
  12286. }
  12287. }
  12288. JUCE_CATCH_ALL_ASSERT
  12289. {
  12290. const ScopedLock sl (runningThreadsLock);
  12291. jassert (runningThreads.contains (thread));
  12292. runningThreads.removeValue (thread);
  12293. }
  12294. #if JUCE_WINDOWS
  12295. juce_CloseThreadHandle (thread->threadHandle_);
  12296. #endif
  12297. thread->threadHandle_ = 0;
  12298. thread->threadId_ = 0;
  12299. }
  12300. // used to wrap the incoming call from the platform-specific code
  12301. void JUCE_API juce_threadEntryPoint (void* userData)
  12302. {
  12303. Thread::threadEntryPoint (static_cast <Thread*> (userData));
  12304. }
  12305. Thread::Thread (const String& threadName)
  12306. : threadName_ (threadName),
  12307. threadHandle_ (0),
  12308. threadPriority_ (5),
  12309. threadId_ (0),
  12310. affinityMask_ (0),
  12311. threadShouldExit_ (false)
  12312. {
  12313. }
  12314. Thread::~Thread()
  12315. {
  12316. stopThread (100);
  12317. }
  12318. void Thread::startThread()
  12319. {
  12320. const ScopedLock sl (startStopLock);
  12321. threadShouldExit_ = false;
  12322. if (threadHandle_ == 0)
  12323. {
  12324. threadHandle_ = juce_createThread (this);
  12325. juce_setThreadPriority (threadHandle_, threadPriority_);
  12326. startSuspensionEvent_.signal();
  12327. }
  12328. }
  12329. void Thread::startThread (const int priority)
  12330. {
  12331. const ScopedLock sl (startStopLock);
  12332. if (threadHandle_ == 0)
  12333. {
  12334. threadPriority_ = priority;
  12335. startThread();
  12336. }
  12337. else
  12338. {
  12339. setPriority (priority);
  12340. }
  12341. }
  12342. bool Thread::isThreadRunning() const
  12343. {
  12344. return threadHandle_ != 0;
  12345. }
  12346. void Thread::signalThreadShouldExit()
  12347. {
  12348. threadShouldExit_ = true;
  12349. }
  12350. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const
  12351. {
  12352. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  12353. jassert (getThreadId() != getCurrentThreadId());
  12354. const int sleepMsPerIteration = 5;
  12355. int count = timeOutMilliseconds / sleepMsPerIteration;
  12356. while (isThreadRunning())
  12357. {
  12358. if (timeOutMilliseconds > 0 && --count < 0)
  12359. return false;
  12360. sleep (sleepMsPerIteration);
  12361. }
  12362. return true;
  12363. }
  12364. void Thread::stopThread (const int timeOutMilliseconds)
  12365. {
  12366. // agh! You can't stop the thread that's calling this method! How on earth
  12367. // would that work??
  12368. jassert (getCurrentThreadId() != getThreadId());
  12369. const ScopedLock sl (startStopLock);
  12370. if (isThreadRunning())
  12371. {
  12372. signalThreadShouldExit();
  12373. notify();
  12374. if (timeOutMilliseconds != 0)
  12375. waitForThreadToExit (timeOutMilliseconds);
  12376. if (isThreadRunning())
  12377. {
  12378. // very bad karma if this point is reached, as
  12379. // there are bound to be locks and events left in
  12380. // silly states when a thread is killed by force..
  12381. jassertfalse;
  12382. Logger::writeToLog ("!! killing thread by force !!");
  12383. juce_killThread (threadHandle_);
  12384. threadHandle_ = 0;
  12385. threadId_ = 0;
  12386. const ScopedLock sl2 (runningThreadsLock);
  12387. runningThreads.removeValue (this);
  12388. }
  12389. }
  12390. }
  12391. bool Thread::setPriority (const int priority)
  12392. {
  12393. const ScopedLock sl (startStopLock);
  12394. const bool worked = juce_setThreadPriority (threadHandle_, priority);
  12395. if (worked)
  12396. threadPriority_ = priority;
  12397. return worked;
  12398. }
  12399. bool Thread::setCurrentThreadPriority (const int priority)
  12400. {
  12401. return juce_setThreadPriority (0, priority);
  12402. }
  12403. void Thread::setAffinityMask (const uint32 affinityMask)
  12404. {
  12405. affinityMask_ = affinityMask;
  12406. }
  12407. bool Thread::wait (const int timeOutMilliseconds) const
  12408. {
  12409. return defaultEvent_.wait (timeOutMilliseconds);
  12410. }
  12411. void Thread::notify() const
  12412. {
  12413. defaultEvent_.signal();
  12414. }
  12415. int Thread::getNumRunningThreads()
  12416. {
  12417. return runningThreads.size();
  12418. }
  12419. Thread* Thread::getCurrentThread()
  12420. {
  12421. const ThreadID thisId = getCurrentThreadId();
  12422. const ScopedLock sl (runningThreadsLock);
  12423. for (int i = runningThreads.size(); --i >= 0;)
  12424. {
  12425. Thread* const t = runningThreads.getUnchecked(i);
  12426. if (t->threadId_ == thisId)
  12427. return t;
  12428. }
  12429. return 0;
  12430. }
  12431. void Thread::stopAllThreads (const int timeOutMilliseconds)
  12432. {
  12433. {
  12434. const ScopedLock sl (runningThreadsLock);
  12435. for (int i = runningThreads.size(); --i >= 0;)
  12436. runningThreads.getUnchecked(i)->signalThreadShouldExit();
  12437. }
  12438. for (;;)
  12439. {
  12440. Thread* firstThread;
  12441. {
  12442. const ScopedLock sl (runningThreadsLock);
  12443. firstThread = runningThreads.getFirst();
  12444. }
  12445. if (firstThread == 0)
  12446. break;
  12447. firstThread->stopThread (timeOutMilliseconds);
  12448. }
  12449. }
  12450. Array<Thread*> Thread::runningThreads;
  12451. CriticalSection Thread::runningThreadsLock;
  12452. END_JUCE_NAMESPACE
  12453. /*** End of inlined file: juce_Thread.cpp ***/
  12454. /*** Start of inlined file: juce_ThreadPool.cpp ***/
  12455. BEGIN_JUCE_NAMESPACE
  12456. ThreadPoolJob::ThreadPoolJob (const String& name)
  12457. : jobName (name),
  12458. pool (0),
  12459. shouldStop (false),
  12460. isActive (false),
  12461. shouldBeDeleted (false)
  12462. {
  12463. }
  12464. ThreadPoolJob::~ThreadPoolJob()
  12465. {
  12466. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  12467. // to remove it first!
  12468. jassert (pool == 0 || ! pool->contains (this));
  12469. }
  12470. const String ThreadPoolJob::getJobName() const
  12471. {
  12472. return jobName;
  12473. }
  12474. void ThreadPoolJob::setJobName (const String& newName)
  12475. {
  12476. jobName = newName;
  12477. }
  12478. void ThreadPoolJob::signalJobShouldExit()
  12479. {
  12480. shouldStop = true;
  12481. }
  12482. class ThreadPool::ThreadPoolThread : public Thread
  12483. {
  12484. public:
  12485. ThreadPoolThread (ThreadPool& pool_)
  12486. : Thread ("Pool"),
  12487. pool (pool_),
  12488. busy (false)
  12489. {
  12490. }
  12491. ~ThreadPoolThread()
  12492. {
  12493. }
  12494. void run()
  12495. {
  12496. while (! threadShouldExit())
  12497. {
  12498. if (! pool.runNextJob())
  12499. wait (500);
  12500. }
  12501. }
  12502. private:
  12503. ThreadPool& pool;
  12504. bool volatile busy;
  12505. ThreadPoolThread (const ThreadPoolThread&);
  12506. ThreadPoolThread& operator= (const ThreadPoolThread&);
  12507. };
  12508. ThreadPool::ThreadPool (const int numThreads,
  12509. const bool startThreadsOnlyWhenNeeded,
  12510. const int stopThreadsWhenNotUsedTimeoutMs)
  12511. : threadStopTimeout (stopThreadsWhenNotUsedTimeoutMs),
  12512. priority (5)
  12513. {
  12514. jassert (numThreads > 0); // not much point having one of these with no threads in it.
  12515. for (int i = jmax (1, numThreads); --i >= 0;)
  12516. threads.add (new ThreadPoolThread (*this));
  12517. if (! startThreadsOnlyWhenNeeded)
  12518. for (int i = threads.size(); --i >= 0;)
  12519. threads.getUnchecked(i)->startThread (priority);
  12520. }
  12521. ThreadPool::~ThreadPool()
  12522. {
  12523. removeAllJobs (true, 4000);
  12524. int i;
  12525. for (i = threads.size(); --i >= 0;)
  12526. threads.getUnchecked(i)->signalThreadShouldExit();
  12527. for (i = threads.size(); --i >= 0;)
  12528. threads.getUnchecked(i)->stopThread (500);
  12529. }
  12530. void ThreadPool::addJob (ThreadPoolJob* const job)
  12531. {
  12532. jassert (job != 0);
  12533. jassert (job->pool == 0);
  12534. if (job->pool == 0)
  12535. {
  12536. job->pool = this;
  12537. job->shouldStop = false;
  12538. job->isActive = false;
  12539. {
  12540. const ScopedLock sl (lock);
  12541. jobs.add (job);
  12542. int numRunning = 0;
  12543. for (int i = threads.size(); --i >= 0;)
  12544. if (threads.getUnchecked(i)->isThreadRunning() && ! threads.getUnchecked(i)->threadShouldExit())
  12545. ++numRunning;
  12546. if (numRunning < threads.size())
  12547. {
  12548. bool startedOne = false;
  12549. int n = 1000;
  12550. while (--n >= 0 && ! startedOne)
  12551. {
  12552. for (int i = threads.size(); --i >= 0;)
  12553. {
  12554. if (! threads.getUnchecked(i)->isThreadRunning())
  12555. {
  12556. threads.getUnchecked(i)->startThread (priority);
  12557. startedOne = true;
  12558. break;
  12559. }
  12560. }
  12561. if (! startedOne)
  12562. Thread::sleep (2);
  12563. }
  12564. }
  12565. }
  12566. for (int i = threads.size(); --i >= 0;)
  12567. threads.getUnchecked(i)->notify();
  12568. }
  12569. }
  12570. int ThreadPool::getNumJobs() const
  12571. {
  12572. return jobs.size();
  12573. }
  12574. ThreadPoolJob* ThreadPool::getJob (const int index) const
  12575. {
  12576. const ScopedLock sl (lock);
  12577. return jobs [index];
  12578. }
  12579. bool ThreadPool::contains (const ThreadPoolJob* const job) const
  12580. {
  12581. const ScopedLock sl (lock);
  12582. return jobs.contains (const_cast <ThreadPoolJob*> (job));
  12583. }
  12584. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  12585. {
  12586. const ScopedLock sl (lock);
  12587. return jobs.contains (const_cast <ThreadPoolJob*> (job)) && job->isActive;
  12588. }
  12589. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job,
  12590. const int timeOutMs) const
  12591. {
  12592. if (job != 0)
  12593. {
  12594. const uint32 start = Time::getMillisecondCounter();
  12595. while (contains (job))
  12596. {
  12597. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  12598. return false;
  12599. jobFinishedSignal.wait (2);
  12600. }
  12601. }
  12602. return true;
  12603. }
  12604. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  12605. const bool interruptIfRunning,
  12606. const int timeOutMs)
  12607. {
  12608. bool dontWait = true;
  12609. if (job != 0)
  12610. {
  12611. const ScopedLock sl (lock);
  12612. if (jobs.contains (job))
  12613. {
  12614. if (job->isActive)
  12615. {
  12616. if (interruptIfRunning)
  12617. job->signalJobShouldExit();
  12618. dontWait = false;
  12619. }
  12620. else
  12621. {
  12622. jobs.removeValue (job);
  12623. }
  12624. }
  12625. }
  12626. return dontWait || waitForJobToFinish (job, timeOutMs);
  12627. }
  12628. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs,
  12629. const int timeOutMs,
  12630. const bool deleteInactiveJobs,
  12631. ThreadPool::JobSelector* selectedJobsToRemove)
  12632. {
  12633. Array <ThreadPoolJob*> jobsToWaitFor;
  12634. {
  12635. const ScopedLock sl (lock);
  12636. for (int i = jobs.size(); --i >= 0;)
  12637. {
  12638. ThreadPoolJob* const job = jobs.getUnchecked(i);
  12639. if (selectedJobsToRemove == 0 || selectedJobsToRemove->isJobSuitable (job))
  12640. {
  12641. if (job->isActive)
  12642. {
  12643. jobsToWaitFor.add (job);
  12644. if (interruptRunningJobs)
  12645. job->signalJobShouldExit();
  12646. }
  12647. else
  12648. {
  12649. jobs.remove (i);
  12650. if (deleteInactiveJobs)
  12651. delete job;
  12652. }
  12653. }
  12654. }
  12655. }
  12656. const uint32 start = Time::getMillisecondCounter();
  12657. for (;;)
  12658. {
  12659. for (int i = jobsToWaitFor.size(); --i >= 0;)
  12660. if (! isJobRunning (jobsToWaitFor.getUnchecked (i)))
  12661. jobsToWaitFor.remove (i);
  12662. if (jobsToWaitFor.size() == 0)
  12663. break;
  12664. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  12665. return false;
  12666. jobFinishedSignal.wait (20);
  12667. }
  12668. return true;
  12669. }
  12670. const StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  12671. {
  12672. StringArray s;
  12673. const ScopedLock sl (lock);
  12674. for (int i = 0; i < jobs.size(); ++i)
  12675. {
  12676. const ThreadPoolJob* const job = jobs.getUnchecked(i);
  12677. if (job->isActive || ! onlyReturnActiveJobs)
  12678. s.add (job->getJobName());
  12679. }
  12680. return s;
  12681. }
  12682. bool ThreadPool::setThreadPriorities (const int newPriority)
  12683. {
  12684. bool ok = true;
  12685. if (priority != newPriority)
  12686. {
  12687. priority = newPriority;
  12688. for (int i = threads.size(); --i >= 0;)
  12689. if (! threads.getUnchecked(i)->setPriority (newPriority))
  12690. ok = false;
  12691. }
  12692. return ok;
  12693. }
  12694. bool ThreadPool::runNextJob()
  12695. {
  12696. ThreadPoolJob* job = 0;
  12697. {
  12698. const ScopedLock sl (lock);
  12699. for (int i = 0; i < jobs.size(); ++i)
  12700. {
  12701. job = jobs[i];
  12702. if (job != 0 && ! (job->isActive || job->shouldStop))
  12703. break;
  12704. job = 0;
  12705. }
  12706. if (job != 0)
  12707. job->isActive = true;
  12708. }
  12709. if (job != 0)
  12710. {
  12711. JUCE_TRY
  12712. {
  12713. ThreadPoolJob::JobStatus result = job->runJob();
  12714. lastJobEndTime = Time::getApproximateMillisecondCounter();
  12715. const ScopedLock sl (lock);
  12716. if (jobs.contains (job))
  12717. {
  12718. job->isActive = false;
  12719. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  12720. {
  12721. job->pool = 0;
  12722. job->shouldStop = true;
  12723. jobs.removeValue (job);
  12724. if (result == ThreadPoolJob::jobHasFinishedAndShouldBeDeleted)
  12725. delete job;
  12726. jobFinishedSignal.signal();
  12727. }
  12728. else
  12729. {
  12730. // move the job to the end of the queue if it wants another go
  12731. jobs.move (jobs.indexOf (job), -1);
  12732. }
  12733. }
  12734. }
  12735. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  12736. catch (...)
  12737. {
  12738. const ScopedLock sl (lock);
  12739. jobs.removeValue (job);
  12740. }
  12741. #endif
  12742. }
  12743. else
  12744. {
  12745. if (threadStopTimeout > 0
  12746. && Time::getApproximateMillisecondCounter() > lastJobEndTime + threadStopTimeout)
  12747. {
  12748. const ScopedLock sl (lock);
  12749. if (jobs.size() == 0)
  12750. for (int i = threads.size(); --i >= 0;)
  12751. threads.getUnchecked(i)->signalThreadShouldExit();
  12752. }
  12753. else
  12754. {
  12755. return false;
  12756. }
  12757. }
  12758. return true;
  12759. }
  12760. END_JUCE_NAMESPACE
  12761. /*** End of inlined file: juce_ThreadPool.cpp ***/
  12762. /*** Start of inlined file: juce_TimeSliceThread.cpp ***/
  12763. BEGIN_JUCE_NAMESPACE
  12764. TimeSliceThread::TimeSliceThread (const String& threadName)
  12765. : Thread (threadName),
  12766. index (0),
  12767. clientBeingCalled (0),
  12768. clientsChanged (false)
  12769. {
  12770. }
  12771. TimeSliceThread::~TimeSliceThread()
  12772. {
  12773. stopThread (2000);
  12774. }
  12775. void TimeSliceThread::addTimeSliceClient (TimeSliceClient* const client)
  12776. {
  12777. const ScopedLock sl (listLock);
  12778. clients.addIfNotAlreadyThere (client);
  12779. clientsChanged = true;
  12780. notify();
  12781. }
  12782. void TimeSliceThread::removeTimeSliceClient (TimeSliceClient* const client)
  12783. {
  12784. const ScopedLock sl1 (listLock);
  12785. clientsChanged = true;
  12786. // if there's a chance we're in the middle of calling this client, we need to
  12787. // also lock the outer lock..
  12788. if (clientBeingCalled == client)
  12789. {
  12790. const ScopedUnlock ul (listLock); // unlock first to get the order right..
  12791. const ScopedLock sl2 (callbackLock);
  12792. const ScopedLock sl3 (listLock);
  12793. clients.removeValue (client);
  12794. }
  12795. else
  12796. {
  12797. clients.removeValue (client);
  12798. }
  12799. }
  12800. int TimeSliceThread::getNumClients() const
  12801. {
  12802. return clients.size();
  12803. }
  12804. TimeSliceClient* TimeSliceThread::getClient (const int i) const
  12805. {
  12806. const ScopedLock sl (listLock);
  12807. return clients [i];
  12808. }
  12809. void TimeSliceThread::run()
  12810. {
  12811. int numCallsSinceBusy = 0;
  12812. while (! threadShouldExit())
  12813. {
  12814. int timeToWait = 500;
  12815. {
  12816. const ScopedLock sl (callbackLock);
  12817. {
  12818. const ScopedLock sl2 (listLock);
  12819. if (clients.size() > 0)
  12820. {
  12821. index = (index + 1) % clients.size();
  12822. clientBeingCalled = clients [index];
  12823. }
  12824. else
  12825. {
  12826. index = 0;
  12827. clientBeingCalled = 0;
  12828. }
  12829. if (clientsChanged)
  12830. {
  12831. clientsChanged = false;
  12832. numCallsSinceBusy = 0;
  12833. }
  12834. }
  12835. if (clientBeingCalled != 0)
  12836. {
  12837. if (clientBeingCalled->useTimeSlice())
  12838. numCallsSinceBusy = 0;
  12839. else
  12840. ++numCallsSinceBusy;
  12841. if (numCallsSinceBusy >= clients.size())
  12842. timeToWait = 500;
  12843. else if (index == 0)
  12844. timeToWait = 1; // throw in an occasional pause, to stop everything locking up
  12845. else
  12846. timeToWait = 0;
  12847. }
  12848. }
  12849. if (timeToWait > 0)
  12850. wait (timeToWait);
  12851. }
  12852. }
  12853. END_JUCE_NAMESPACE
  12854. /*** End of inlined file: juce_TimeSliceThread.cpp ***/
  12855. /*** Start of inlined file: juce_DeletedAtShutdown.cpp ***/
  12856. BEGIN_JUCE_NAMESPACE
  12857. DeletedAtShutdown::DeletedAtShutdown()
  12858. {
  12859. const ScopedLock sl (getLock());
  12860. getObjects().add (this);
  12861. }
  12862. DeletedAtShutdown::~DeletedAtShutdown()
  12863. {
  12864. const ScopedLock sl (getLock());
  12865. getObjects().removeValue (this);
  12866. }
  12867. void DeletedAtShutdown::deleteAll()
  12868. {
  12869. // make a local copy of the array, so it can't get into a loop if something
  12870. // creates another DeletedAtShutdown object during its destructor.
  12871. Array <DeletedAtShutdown*> localCopy;
  12872. {
  12873. const ScopedLock sl (getLock());
  12874. localCopy = getObjects();
  12875. }
  12876. for (int i = localCopy.size(); --i >= 0;)
  12877. {
  12878. JUCE_TRY
  12879. {
  12880. DeletedAtShutdown* deletee = localCopy.getUnchecked(i);
  12881. // double-check that it's not already been deleted during another object's destructor.
  12882. {
  12883. const ScopedLock sl (getLock());
  12884. if (! getObjects().contains (deletee))
  12885. deletee = 0;
  12886. }
  12887. delete deletee;
  12888. }
  12889. JUCE_CATCH_EXCEPTION
  12890. }
  12891. // if no objects got re-created during shutdown, this should have been emptied by their
  12892. // destructors
  12893. jassert (getObjects().size() == 0);
  12894. getObjects().clear(); // just to make sure the array doesn't have any memory still allocated
  12895. }
  12896. CriticalSection& DeletedAtShutdown::getLock()
  12897. {
  12898. static CriticalSection lock;
  12899. return lock;
  12900. }
  12901. Array <DeletedAtShutdown*>& DeletedAtShutdown::getObjects()
  12902. {
  12903. static Array <DeletedAtShutdown*> objects;
  12904. return objects;
  12905. }
  12906. END_JUCE_NAMESPACE
  12907. /*** End of inlined file: juce_DeletedAtShutdown.cpp ***/
  12908. #endif
  12909. #if JUCE_BUILD_MISC
  12910. /*** Start of inlined file: juce_ValueTree.cpp ***/
  12911. BEGIN_JUCE_NAMESPACE
  12912. class ValueTree::SetPropertyAction : public UndoableAction
  12913. {
  12914. public:
  12915. SetPropertyAction (const SharedObjectPtr& target_, const Identifier& name_,
  12916. const var& newValue_, const var& oldValue_,
  12917. const bool isAddingNewProperty_, const bool isDeletingProperty_)
  12918. : target (target_), name (name_), newValue (newValue_), oldValue (oldValue_),
  12919. isAddingNewProperty (isAddingNewProperty_), isDeletingProperty (isDeletingProperty_)
  12920. {
  12921. }
  12922. ~SetPropertyAction() {}
  12923. bool perform()
  12924. {
  12925. jassert (! (isAddingNewProperty && target->hasProperty (name)));
  12926. if (isDeletingProperty)
  12927. target->removeProperty (name, 0);
  12928. else
  12929. target->setProperty (name, newValue, 0);
  12930. return true;
  12931. }
  12932. bool undo()
  12933. {
  12934. if (isAddingNewProperty)
  12935. target->removeProperty (name, 0);
  12936. else
  12937. target->setProperty (name, oldValue, 0);
  12938. return true;
  12939. }
  12940. int getSizeInUnits()
  12941. {
  12942. return (int) sizeof (*this); //xxx should be more accurate
  12943. }
  12944. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  12945. {
  12946. if (! (isAddingNewProperty || isDeletingProperty))
  12947. {
  12948. SetPropertyAction* next = dynamic_cast <SetPropertyAction*> (nextAction);
  12949. if (next != 0 && next->target == target && next->name == name
  12950. && ! (next->isAddingNewProperty || next->isDeletingProperty))
  12951. {
  12952. return new SetPropertyAction (target, name, next->newValue, oldValue, false, false);
  12953. }
  12954. }
  12955. return 0;
  12956. }
  12957. private:
  12958. const SharedObjectPtr target;
  12959. const Identifier name;
  12960. const var newValue;
  12961. var oldValue;
  12962. const bool isAddingNewProperty : 1, isDeletingProperty : 1;
  12963. SetPropertyAction (const SetPropertyAction&);
  12964. SetPropertyAction& operator= (const SetPropertyAction&);
  12965. };
  12966. class ValueTree::AddOrRemoveChildAction : public UndoableAction
  12967. {
  12968. public:
  12969. AddOrRemoveChildAction (const SharedObjectPtr& target_, const int childIndex_,
  12970. const SharedObjectPtr& newChild_)
  12971. : target (target_),
  12972. child (newChild_ != 0 ? newChild_ : target_->children [childIndex_]),
  12973. childIndex (childIndex_),
  12974. isDeleting (newChild_ == 0)
  12975. {
  12976. jassert (child != 0);
  12977. }
  12978. ~AddOrRemoveChildAction() {}
  12979. bool perform()
  12980. {
  12981. if (isDeleting)
  12982. target->removeChild (childIndex, 0);
  12983. else
  12984. target->addChild (child, childIndex, 0);
  12985. return true;
  12986. }
  12987. bool undo()
  12988. {
  12989. if (isDeleting)
  12990. {
  12991. target->addChild (child, childIndex, 0);
  12992. }
  12993. else
  12994. {
  12995. // If you hit this, it seems that your object's state is getting confused - probably
  12996. // because you've interleaved some undoable and non-undoable operations?
  12997. jassert (childIndex < target->children.size());
  12998. target->removeChild (childIndex, 0);
  12999. }
  13000. return true;
  13001. }
  13002. int getSizeInUnits()
  13003. {
  13004. return (int) sizeof (*this); //xxx should be more accurate
  13005. }
  13006. private:
  13007. const SharedObjectPtr target, child;
  13008. const int childIndex;
  13009. const bool isDeleting;
  13010. AddOrRemoveChildAction (const AddOrRemoveChildAction&);
  13011. AddOrRemoveChildAction& operator= (const AddOrRemoveChildAction&);
  13012. };
  13013. class ValueTree::MoveChildAction : public UndoableAction
  13014. {
  13015. public:
  13016. MoveChildAction (const SharedObjectPtr& parent_,
  13017. const int startIndex_, const int endIndex_)
  13018. : parent (parent_),
  13019. startIndex (startIndex_),
  13020. endIndex (endIndex_)
  13021. {
  13022. }
  13023. ~MoveChildAction() {}
  13024. bool perform()
  13025. {
  13026. parent->moveChild (startIndex, endIndex, 0);
  13027. return true;
  13028. }
  13029. bool undo()
  13030. {
  13031. parent->moveChild (endIndex, startIndex, 0);
  13032. return true;
  13033. }
  13034. int getSizeInUnits()
  13035. {
  13036. return (int) sizeof (*this); //xxx should be more accurate
  13037. }
  13038. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  13039. {
  13040. MoveChildAction* next = dynamic_cast <MoveChildAction*> (nextAction);
  13041. if (next != 0 && next->parent == parent && next->startIndex == endIndex)
  13042. return new MoveChildAction (parent, startIndex, next->endIndex);
  13043. return 0;
  13044. }
  13045. private:
  13046. const SharedObjectPtr parent;
  13047. const int startIndex, endIndex;
  13048. MoveChildAction (const MoveChildAction&);
  13049. MoveChildAction& operator= (const MoveChildAction&);
  13050. };
  13051. ValueTree::SharedObject::SharedObject (const Identifier& type_)
  13052. : type (type_), parent (0)
  13053. {
  13054. }
  13055. ValueTree::SharedObject::SharedObject (const SharedObject& other)
  13056. : type (other.type), properties (other.properties), parent (0)
  13057. {
  13058. for (int i = 0; i < other.children.size(); ++i)
  13059. {
  13060. SharedObject* const child = new SharedObject (*other.children.getUnchecked(i));
  13061. child->parent = this;
  13062. children.add (child);
  13063. }
  13064. }
  13065. ValueTree::SharedObject::~SharedObject()
  13066. {
  13067. jassert (parent == 0); // this should never happen unless something isn't obeying the ref-counting!
  13068. for (int i = children.size(); --i >= 0;)
  13069. {
  13070. const SharedObjectPtr c (children.getUnchecked(i));
  13071. c->parent = 0;
  13072. children.remove (i);
  13073. c->sendParentChangeMessage();
  13074. }
  13075. }
  13076. void ValueTree::SharedObject::sendPropertyChangeMessage (ValueTree& tree, const Identifier& property)
  13077. {
  13078. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  13079. {
  13080. ValueTree* const v = valueTreesWithListeners[i];
  13081. if (v != 0)
  13082. v->listeners.call (&ValueTree::Listener::valueTreePropertyChanged, tree, property);
  13083. }
  13084. }
  13085. void ValueTree::SharedObject::sendPropertyChangeMessage (const Identifier& property)
  13086. {
  13087. ValueTree tree (this);
  13088. ValueTree::SharedObject* t = this;
  13089. while (t != 0)
  13090. {
  13091. t->sendPropertyChangeMessage (tree, property);
  13092. t = t->parent;
  13093. }
  13094. }
  13095. void ValueTree::SharedObject::sendChildChangeMessage (ValueTree& tree)
  13096. {
  13097. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  13098. {
  13099. ValueTree* const v = valueTreesWithListeners[i];
  13100. if (v != 0)
  13101. v->listeners.call (&ValueTree::Listener::valueTreeChildrenChanged, tree);
  13102. }
  13103. }
  13104. void ValueTree::SharedObject::sendChildChangeMessage()
  13105. {
  13106. ValueTree tree (this);
  13107. ValueTree::SharedObject* t = this;
  13108. while (t != 0)
  13109. {
  13110. t->sendChildChangeMessage (tree);
  13111. t = t->parent;
  13112. }
  13113. }
  13114. void ValueTree::SharedObject::sendParentChangeMessage()
  13115. {
  13116. ValueTree tree (this);
  13117. int i;
  13118. for (i = children.size(); --i >= 0;)
  13119. {
  13120. SharedObject* const t = children[i];
  13121. if (t != 0)
  13122. t->sendParentChangeMessage();
  13123. }
  13124. for (i = valueTreesWithListeners.size(); --i >= 0;)
  13125. {
  13126. ValueTree* const v = valueTreesWithListeners[i];
  13127. if (v != 0)
  13128. v->listeners.call (&ValueTree::Listener::valueTreeParentChanged, tree);
  13129. }
  13130. }
  13131. const var& ValueTree::SharedObject::getProperty (const Identifier& name) const
  13132. {
  13133. return properties [name];
  13134. }
  13135. const var ValueTree::SharedObject::getProperty (const Identifier& name, const var& defaultReturnValue) const
  13136. {
  13137. return properties.getWithDefault (name, defaultReturnValue);
  13138. }
  13139. void ValueTree::SharedObject::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  13140. {
  13141. if (undoManager == 0)
  13142. {
  13143. if (properties.set (name, newValue))
  13144. sendPropertyChangeMessage (name);
  13145. }
  13146. else
  13147. {
  13148. var* const existingValue = properties.getItem (name);
  13149. if (existingValue != 0)
  13150. {
  13151. if (*existingValue != newValue)
  13152. undoManager->perform (new SetPropertyAction (this, name, newValue, properties [name], false, false));
  13153. }
  13154. else
  13155. {
  13156. undoManager->perform (new SetPropertyAction (this, name, newValue, var::null, true, false));
  13157. }
  13158. }
  13159. }
  13160. bool ValueTree::SharedObject::hasProperty (const Identifier& name) const
  13161. {
  13162. return properties.contains (name);
  13163. }
  13164. void ValueTree::SharedObject::removeProperty (const Identifier& name, UndoManager* const undoManager)
  13165. {
  13166. if (undoManager == 0)
  13167. {
  13168. if (properties.remove (name))
  13169. sendPropertyChangeMessage (name);
  13170. }
  13171. else
  13172. {
  13173. if (properties.contains (name))
  13174. undoManager->perform (new SetPropertyAction (this, name, var::null, properties [name], false, true));
  13175. }
  13176. }
  13177. void ValueTree::SharedObject::removeAllProperties (UndoManager* const undoManager)
  13178. {
  13179. if (undoManager == 0)
  13180. {
  13181. while (properties.size() > 0)
  13182. {
  13183. const Identifier name (properties.getName (properties.size() - 1));
  13184. properties.remove (name);
  13185. sendPropertyChangeMessage (name);
  13186. }
  13187. }
  13188. else
  13189. {
  13190. for (int i = properties.size(); --i >= 0;)
  13191. undoManager->perform (new SetPropertyAction (this, properties.getName(i), var::null, properties.getValueAt(i), false, true));
  13192. }
  13193. }
  13194. ValueTree ValueTree::SharedObject::getChildWithName (const Identifier& typeToMatch) const
  13195. {
  13196. for (int i = 0; i < children.size(); ++i)
  13197. if (children.getUnchecked(i)->type == typeToMatch)
  13198. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  13199. return ValueTree::invalid;
  13200. }
  13201. ValueTree ValueTree::SharedObject::getOrCreateChildWithName (const Identifier& typeToMatch, UndoManager* undoManager)
  13202. {
  13203. for (int i = 0; i < children.size(); ++i)
  13204. if (children.getUnchecked(i)->type == typeToMatch)
  13205. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  13206. SharedObject* const newObject = new SharedObject (typeToMatch);
  13207. addChild (newObject, -1, undoManager);
  13208. return ValueTree (newObject);
  13209. }
  13210. ValueTree ValueTree::SharedObject::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  13211. {
  13212. for (int i = 0; i < children.size(); ++i)
  13213. if (children.getUnchecked(i)->getProperty (propertyName) == propertyValue)
  13214. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  13215. return ValueTree::invalid;
  13216. }
  13217. bool ValueTree::SharedObject::isAChildOf (const SharedObject* const possibleParent) const
  13218. {
  13219. const SharedObject* p = parent;
  13220. while (p != 0)
  13221. {
  13222. if (p == possibleParent)
  13223. return true;
  13224. p = p->parent;
  13225. }
  13226. return false;
  13227. }
  13228. int ValueTree::SharedObject::indexOf (const ValueTree& child) const
  13229. {
  13230. return children.indexOf (child.object);
  13231. }
  13232. void ValueTree::SharedObject::addChild (SharedObject* child, int index, UndoManager* const undoManager)
  13233. {
  13234. if (child != 0 && child->parent != this)
  13235. {
  13236. if (child != this && ! isAChildOf (child))
  13237. {
  13238. // You should always make sure that a child is removed from its previous parent before
  13239. // adding it somewhere else - otherwise, it's ambiguous as to whether a different
  13240. // undomanager should be used when removing it from its current parent..
  13241. jassert (child->parent == 0);
  13242. if (child->parent != 0)
  13243. {
  13244. jassert (child->parent->children.indexOf (child) >= 0);
  13245. child->parent->removeChild (child->parent->children.indexOf (child), undoManager);
  13246. }
  13247. if (undoManager == 0)
  13248. {
  13249. children.insert (index, child);
  13250. child->parent = this;
  13251. sendChildChangeMessage();
  13252. child->sendParentChangeMessage();
  13253. }
  13254. else
  13255. {
  13256. if (index < 0)
  13257. index = children.size();
  13258. undoManager->perform (new AddOrRemoveChildAction (this, index, child));
  13259. }
  13260. }
  13261. else
  13262. {
  13263. // You're attempting to create a recursive loop! A node
  13264. // can't be a child of one of its own children!
  13265. jassertfalse;
  13266. }
  13267. }
  13268. }
  13269. void ValueTree::SharedObject::removeChild (const int childIndex, UndoManager* const undoManager)
  13270. {
  13271. const SharedObjectPtr child (children [childIndex]);
  13272. if (child != 0)
  13273. {
  13274. if (undoManager == 0)
  13275. {
  13276. children.remove (childIndex);
  13277. child->parent = 0;
  13278. sendChildChangeMessage();
  13279. child->sendParentChangeMessage();
  13280. }
  13281. else
  13282. {
  13283. undoManager->perform (new AddOrRemoveChildAction (this, childIndex, 0));
  13284. }
  13285. }
  13286. }
  13287. void ValueTree::SharedObject::removeAllChildren (UndoManager* const undoManager)
  13288. {
  13289. while (children.size() > 0)
  13290. removeChild (children.size() - 1, undoManager);
  13291. }
  13292. void ValueTree::SharedObject::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  13293. {
  13294. // The source index must be a valid index!
  13295. jassert (((unsigned int) currentIndex) < (unsigned int) children.size());
  13296. if (currentIndex != newIndex
  13297. && ((unsigned int) currentIndex) < (unsigned int) children.size())
  13298. {
  13299. if (undoManager == 0)
  13300. {
  13301. children.move (currentIndex, newIndex);
  13302. sendChildChangeMessage();
  13303. }
  13304. else
  13305. {
  13306. if (((unsigned int) newIndex) >= (unsigned int) children.size())
  13307. newIndex = children.size() - 1;
  13308. undoManager->perform (new MoveChildAction (this, currentIndex, newIndex));
  13309. }
  13310. }
  13311. }
  13312. bool ValueTree::SharedObject::isEquivalentTo (const SharedObject& other) const
  13313. {
  13314. if (type != other.type
  13315. || properties.size() != other.properties.size()
  13316. || children.size() != other.children.size()
  13317. || properties != other.properties)
  13318. return false;
  13319. for (int i = 0; i < children.size(); ++i)
  13320. if (! children.getUnchecked(i)->isEquivalentTo (*other.children.getUnchecked(i)))
  13321. return false;
  13322. return true;
  13323. }
  13324. ValueTree::ValueTree() throw()
  13325. : object (0)
  13326. {
  13327. }
  13328. const ValueTree ValueTree::invalid;
  13329. ValueTree::ValueTree (const Identifier& type_)
  13330. : object (new ValueTree::SharedObject (type_))
  13331. {
  13332. jassert (type_.toString().isNotEmpty()); // All objects should be given a sensible type name!
  13333. }
  13334. ValueTree::ValueTree (SharedObject* const object_)
  13335. : object (object_)
  13336. {
  13337. }
  13338. ValueTree::ValueTree (const ValueTree& other)
  13339. : object (other.object)
  13340. {
  13341. }
  13342. ValueTree& ValueTree::operator= (const ValueTree& other)
  13343. {
  13344. if (listeners.size() > 0)
  13345. {
  13346. if (object != 0)
  13347. object->valueTreesWithListeners.removeValue (this);
  13348. if (other.object != 0)
  13349. other.object->valueTreesWithListeners.add (this);
  13350. }
  13351. object = other.object;
  13352. return *this;
  13353. }
  13354. ValueTree::~ValueTree()
  13355. {
  13356. if (listeners.size() > 0 && object != 0)
  13357. object->valueTreesWithListeners.removeValue (this);
  13358. }
  13359. bool ValueTree::operator== (const ValueTree& other) const throw()
  13360. {
  13361. return object == other.object;
  13362. }
  13363. bool ValueTree::operator!= (const ValueTree& other) const throw()
  13364. {
  13365. return object != other.object;
  13366. }
  13367. bool ValueTree::isEquivalentTo (const ValueTree& other) const
  13368. {
  13369. return object == other.object
  13370. || (object != 0 && other.object != 0 && object->isEquivalentTo (*other.object));
  13371. }
  13372. ValueTree ValueTree::createCopy() const
  13373. {
  13374. return ValueTree (object != 0 ? new SharedObject (*object) : 0);
  13375. }
  13376. bool ValueTree::hasType (const Identifier& typeName) const
  13377. {
  13378. return object != 0 && object->type == typeName;
  13379. }
  13380. const Identifier ValueTree::getType() const
  13381. {
  13382. return object != 0 ? object->type : Identifier();
  13383. }
  13384. ValueTree ValueTree::getParent() const
  13385. {
  13386. return ValueTree (object != 0 ? object->parent : (SharedObject*) 0);
  13387. }
  13388. const var& ValueTree::operator[] (const Identifier& name) const
  13389. {
  13390. return object == 0 ? var::null : object->getProperty (name);
  13391. }
  13392. const var& ValueTree::getProperty (const Identifier& name) const
  13393. {
  13394. return object == 0 ? var::null : object->getProperty (name);
  13395. }
  13396. const var ValueTree::getProperty (const Identifier& name, const var& defaultReturnValue) const
  13397. {
  13398. return object == 0 ? defaultReturnValue : object->getProperty (name, defaultReturnValue);
  13399. }
  13400. void ValueTree::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  13401. {
  13402. jassert (name.toString().isNotEmpty());
  13403. if (object != 0 && name.toString().isNotEmpty())
  13404. object->setProperty (name, newValue, undoManager);
  13405. }
  13406. bool ValueTree::hasProperty (const Identifier& name) const
  13407. {
  13408. return object != 0 && object->hasProperty (name);
  13409. }
  13410. void ValueTree::removeProperty (const Identifier& name, UndoManager* const undoManager)
  13411. {
  13412. if (object != 0)
  13413. object->removeProperty (name, undoManager);
  13414. }
  13415. void ValueTree::removeAllProperties (UndoManager* const undoManager)
  13416. {
  13417. if (object != 0)
  13418. object->removeAllProperties (undoManager);
  13419. }
  13420. int ValueTree::getNumProperties() const
  13421. {
  13422. return object == 0 ? 0 : object->properties.size();
  13423. }
  13424. const Identifier ValueTree::getPropertyName (const int index) const
  13425. {
  13426. return object == 0 ? Identifier()
  13427. : object->properties.getName (index);
  13428. }
  13429. class ValueTreePropertyValueSource : public Value::ValueSource,
  13430. public ValueTree::Listener
  13431. {
  13432. public:
  13433. ValueTreePropertyValueSource (const ValueTree& tree_,
  13434. const Identifier& property_,
  13435. UndoManager* const undoManager_)
  13436. : tree (tree_),
  13437. property (property_),
  13438. undoManager (undoManager_)
  13439. {
  13440. tree.addListener (this);
  13441. }
  13442. ~ValueTreePropertyValueSource()
  13443. {
  13444. tree.removeListener (this);
  13445. }
  13446. const var getValue() const
  13447. {
  13448. return tree [property];
  13449. }
  13450. void setValue (const var& newValue)
  13451. {
  13452. tree.setProperty (property, newValue, undoManager);
  13453. }
  13454. void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged, const Identifier& changedProperty)
  13455. {
  13456. if (tree == treeWhosePropertyHasChanged && property == changedProperty)
  13457. sendChangeMessage (false);
  13458. }
  13459. void valueTreeChildrenChanged (ValueTree&) {}
  13460. void valueTreeParentChanged (ValueTree&) {}
  13461. private:
  13462. ValueTree tree;
  13463. const Identifier property;
  13464. UndoManager* const undoManager;
  13465. ValueTreePropertyValueSource& operator= (const ValueTreePropertyValueSource&);
  13466. };
  13467. Value ValueTree::getPropertyAsValue (const Identifier& name, UndoManager* const undoManager) const
  13468. {
  13469. return Value (new ValueTreePropertyValueSource (*this, name, undoManager));
  13470. }
  13471. int ValueTree::getNumChildren() const
  13472. {
  13473. return object == 0 ? 0 : object->children.size();
  13474. }
  13475. ValueTree ValueTree::getChild (int index) const
  13476. {
  13477. return ValueTree (object != 0 ? (SharedObject*) object->children [index] : (SharedObject*) 0);
  13478. }
  13479. ValueTree ValueTree::getChildWithName (const Identifier& type) const
  13480. {
  13481. return object != 0 ? object->getChildWithName (type) : ValueTree::invalid;
  13482. }
  13483. ValueTree ValueTree::getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager)
  13484. {
  13485. return object != 0 ? object->getOrCreateChildWithName (type, undoManager) : ValueTree::invalid;
  13486. }
  13487. ValueTree ValueTree::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  13488. {
  13489. return object != 0 ? object->getChildWithProperty (propertyName, propertyValue) : ValueTree::invalid;
  13490. }
  13491. bool ValueTree::isAChildOf (const ValueTree& possibleParent) const
  13492. {
  13493. return object != 0 && object->isAChildOf (possibleParent.object);
  13494. }
  13495. int ValueTree::indexOf (const ValueTree& child) const
  13496. {
  13497. return object != 0 ? object->indexOf (child) : -1;
  13498. }
  13499. void ValueTree::addChild (const ValueTree& child, int index, UndoManager* const undoManager)
  13500. {
  13501. if (object != 0)
  13502. object->addChild (child.object, index, undoManager);
  13503. }
  13504. void ValueTree::removeChild (const int childIndex, UndoManager* const undoManager)
  13505. {
  13506. if (object != 0)
  13507. object->removeChild (childIndex, undoManager);
  13508. }
  13509. void ValueTree::removeChild (const ValueTree& child, UndoManager* const undoManager)
  13510. {
  13511. if (object != 0)
  13512. object->removeChild (object->children.indexOf (child.object), undoManager);
  13513. }
  13514. void ValueTree::removeAllChildren (UndoManager* const undoManager)
  13515. {
  13516. if (object != 0)
  13517. object->removeAllChildren (undoManager);
  13518. }
  13519. void ValueTree::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  13520. {
  13521. if (object != 0)
  13522. object->moveChild (currentIndex, newIndex, undoManager);
  13523. }
  13524. void ValueTree::addListener (Listener* listener)
  13525. {
  13526. if (listener != 0)
  13527. {
  13528. if (listeners.size() == 0 && object != 0)
  13529. object->valueTreesWithListeners.add (this);
  13530. listeners.add (listener);
  13531. }
  13532. }
  13533. void ValueTree::removeListener (Listener* listener)
  13534. {
  13535. listeners.remove (listener);
  13536. if (listeners.size() == 0 && object != 0)
  13537. object->valueTreesWithListeners.removeValue (this);
  13538. }
  13539. XmlElement* ValueTree::SharedObject::createXml() const
  13540. {
  13541. XmlElement* xml = new XmlElement (type.toString());
  13542. int i;
  13543. for (i = 0; i < properties.size(); ++i)
  13544. {
  13545. Identifier name (properties.getName(i));
  13546. const var& v = properties [name];
  13547. jassert (! v.isObject()); // DynamicObjects can't be stored as XML!
  13548. xml->setAttribute (name.toString(), v.toString());
  13549. }
  13550. for (i = 0; i < children.size(); ++i)
  13551. xml->addChildElement (children.getUnchecked(i)->createXml());
  13552. return xml;
  13553. }
  13554. XmlElement* ValueTree::createXml() const
  13555. {
  13556. return object != 0 ? object->createXml() : 0;
  13557. }
  13558. ValueTree ValueTree::fromXml (const XmlElement& xml)
  13559. {
  13560. ValueTree v (xml.getTagName());
  13561. const int numAtts = xml.getNumAttributes(); // xxx inefficient - should write an att iterator..
  13562. for (int i = 0; i < numAtts; ++i)
  13563. v.setProperty (xml.getAttributeName (i), var (xml.getAttributeValue (i)), 0);
  13564. forEachXmlChildElement (xml, e)
  13565. {
  13566. v.addChild (fromXml (*e), -1, 0);
  13567. }
  13568. return v;
  13569. }
  13570. void ValueTree::writeToStream (OutputStream& output)
  13571. {
  13572. output.writeString (getType().toString());
  13573. const int numProps = getNumProperties();
  13574. output.writeCompressedInt (numProps);
  13575. int i;
  13576. for (i = 0; i < numProps; ++i)
  13577. {
  13578. const Identifier name (getPropertyName(i));
  13579. output.writeString (name.toString());
  13580. getProperty(name).writeToStream (output);
  13581. }
  13582. const int numChildren = getNumChildren();
  13583. output.writeCompressedInt (numChildren);
  13584. for (i = 0; i < numChildren; ++i)
  13585. getChild (i).writeToStream (output);
  13586. }
  13587. ValueTree ValueTree::readFromStream (InputStream& input)
  13588. {
  13589. const String type (input.readString());
  13590. if (type.isEmpty())
  13591. return ValueTree::invalid;
  13592. ValueTree v (type);
  13593. const int numProps = input.readCompressedInt();
  13594. if (numProps < 0)
  13595. {
  13596. jassertfalse; // trying to read corrupted data!
  13597. return v;
  13598. }
  13599. int i;
  13600. for (i = 0; i < numProps; ++i)
  13601. {
  13602. const String name (input.readString());
  13603. jassert (name.isNotEmpty());
  13604. const var value (var::readFromStream (input));
  13605. v.setProperty (name, value, 0);
  13606. }
  13607. const int numChildren = input.readCompressedInt();
  13608. for (i = 0; i < numChildren; ++i)
  13609. v.addChild (readFromStream (input), -1, 0);
  13610. return v;
  13611. }
  13612. ValueTree ValueTree::readFromData (const void* const data, const size_t numBytes)
  13613. {
  13614. MemoryInputStream in (data, numBytes, false);
  13615. return readFromStream (in);
  13616. }
  13617. END_JUCE_NAMESPACE
  13618. /*** End of inlined file: juce_ValueTree.cpp ***/
  13619. /*** Start of inlined file: juce_Value.cpp ***/
  13620. BEGIN_JUCE_NAMESPACE
  13621. Value::ValueSource::ValueSource()
  13622. {
  13623. }
  13624. Value::ValueSource::~ValueSource()
  13625. {
  13626. }
  13627. void Value::ValueSource::sendChangeMessage (const bool synchronous)
  13628. {
  13629. if (synchronous)
  13630. {
  13631. for (int i = valuesWithListeners.size(); --i >= 0;)
  13632. {
  13633. Value* const v = valuesWithListeners[i];
  13634. if (v != 0)
  13635. v->callListeners();
  13636. }
  13637. }
  13638. else
  13639. {
  13640. triggerAsyncUpdate();
  13641. }
  13642. }
  13643. void Value::ValueSource::handleAsyncUpdate()
  13644. {
  13645. sendChangeMessage (true);
  13646. }
  13647. class SimpleValueSource : public Value::ValueSource
  13648. {
  13649. public:
  13650. SimpleValueSource()
  13651. {
  13652. }
  13653. SimpleValueSource (const var& initialValue)
  13654. : value (initialValue)
  13655. {
  13656. }
  13657. ~SimpleValueSource()
  13658. {
  13659. }
  13660. const var getValue() const
  13661. {
  13662. return value;
  13663. }
  13664. void setValue (const var& newValue)
  13665. {
  13666. if (newValue != value)
  13667. {
  13668. value = newValue;
  13669. sendChangeMessage (false);
  13670. }
  13671. }
  13672. private:
  13673. var value;
  13674. SimpleValueSource (const SimpleValueSource&);
  13675. SimpleValueSource& operator= (const SimpleValueSource&);
  13676. };
  13677. Value::Value()
  13678. : value (new SimpleValueSource())
  13679. {
  13680. }
  13681. Value::Value (ValueSource* const value_)
  13682. : value (value_)
  13683. {
  13684. jassert (value_ != 0);
  13685. }
  13686. Value::Value (const var& initialValue)
  13687. : value (new SimpleValueSource (initialValue))
  13688. {
  13689. }
  13690. Value::Value (const Value& other)
  13691. : value (other.value)
  13692. {
  13693. }
  13694. Value& Value::operator= (const Value& other)
  13695. {
  13696. value = other.value;
  13697. return *this;
  13698. }
  13699. Value::~Value()
  13700. {
  13701. if (listeners.size() > 0)
  13702. value->valuesWithListeners.removeValue (this);
  13703. }
  13704. const var Value::getValue() const
  13705. {
  13706. return value->getValue();
  13707. }
  13708. Value::operator const var() const
  13709. {
  13710. return getValue();
  13711. }
  13712. void Value::setValue (const var& newValue)
  13713. {
  13714. value->setValue (newValue);
  13715. }
  13716. const String Value::toString() const
  13717. {
  13718. return value->getValue().toString();
  13719. }
  13720. Value& Value::operator= (const var& newValue)
  13721. {
  13722. value->setValue (newValue);
  13723. return *this;
  13724. }
  13725. void Value::referTo (const Value& valueToReferTo)
  13726. {
  13727. if (valueToReferTo.value != value)
  13728. {
  13729. if (listeners.size() > 0)
  13730. {
  13731. value->valuesWithListeners.removeValue (this);
  13732. valueToReferTo.value->valuesWithListeners.add (this);
  13733. }
  13734. value = valueToReferTo.value;
  13735. callListeners();
  13736. }
  13737. }
  13738. bool Value::refersToSameSourceAs (const Value& other) const
  13739. {
  13740. return value == other.value;
  13741. }
  13742. bool Value::operator== (const Value& other) const
  13743. {
  13744. return value == other.value || value->getValue() == other.getValue();
  13745. }
  13746. bool Value::operator!= (const Value& other) const
  13747. {
  13748. return value != other.value && value->getValue() != other.getValue();
  13749. }
  13750. void Value::addListener (Listener* const listener)
  13751. {
  13752. if (listener != 0)
  13753. {
  13754. if (listeners.size() == 0)
  13755. value->valuesWithListeners.add (this);
  13756. listeners.add (listener);
  13757. }
  13758. }
  13759. void Value::removeListener (Listener* const listener)
  13760. {
  13761. listeners.remove (listener);
  13762. if (listeners.size() == 0)
  13763. value->valuesWithListeners.removeValue (this);
  13764. }
  13765. void Value::callListeners()
  13766. {
  13767. Value v (*this); // (create a copy in case this gets deleted by a callback)
  13768. listeners.call (&Listener::valueChanged, v);
  13769. }
  13770. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value)
  13771. {
  13772. return stream << value.toString();
  13773. }
  13774. END_JUCE_NAMESPACE
  13775. /*** End of inlined file: juce_Value.cpp ***/
  13776. /*** Start of inlined file: juce_Application.cpp ***/
  13777. #if JUCE_MSVC
  13778. #pragma warning (push)
  13779. #pragma warning (disable: 4245 4514 4100)
  13780. #include <crtdbg.h>
  13781. #pragma warning (pop)
  13782. #endif
  13783. BEGIN_JUCE_NAMESPACE
  13784. void juce_setCurrentThreadName (const String& name);
  13785. static JUCEApplication* appInstance = 0;
  13786. JUCEApplication::JUCEApplication()
  13787. : appReturnValue (0),
  13788. stillInitialising (true)
  13789. {
  13790. }
  13791. JUCEApplication::~JUCEApplication()
  13792. {
  13793. if (appLock != 0)
  13794. {
  13795. appLock->exit();
  13796. appLock = 0;
  13797. }
  13798. }
  13799. JUCEApplication* JUCEApplication::getInstance() throw()
  13800. {
  13801. return appInstance;
  13802. }
  13803. bool JUCEApplication::isInitialising() const throw()
  13804. {
  13805. return stillInitialising;
  13806. }
  13807. const String JUCEApplication::getApplicationVersion()
  13808. {
  13809. return String::empty;
  13810. }
  13811. bool JUCEApplication::moreThanOneInstanceAllowed()
  13812. {
  13813. return true;
  13814. }
  13815. void JUCEApplication::anotherInstanceStarted (const String&)
  13816. {
  13817. }
  13818. void JUCEApplication::systemRequestedQuit()
  13819. {
  13820. quit();
  13821. }
  13822. void JUCEApplication::quit()
  13823. {
  13824. MessageManager::getInstance()->stopDispatchLoop();
  13825. }
  13826. void JUCEApplication::setApplicationReturnValue (const int newReturnValue) throw()
  13827. {
  13828. appReturnValue = newReturnValue;
  13829. }
  13830. void JUCEApplication::unhandledException (const std::exception*,
  13831. const String&,
  13832. const int)
  13833. {
  13834. jassertfalse;
  13835. }
  13836. void JUCEApplication::sendUnhandledException (const std::exception* const e,
  13837. const char* const sourceFile,
  13838. const int lineNumber)
  13839. {
  13840. if (appInstance != 0)
  13841. appInstance->unhandledException (e, sourceFile, lineNumber);
  13842. }
  13843. ApplicationCommandTarget* JUCEApplication::getNextCommandTarget()
  13844. {
  13845. return 0;
  13846. }
  13847. void JUCEApplication::getAllCommands (Array <CommandID>& commands)
  13848. {
  13849. commands.add (StandardApplicationCommandIDs::quit);
  13850. }
  13851. void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  13852. {
  13853. if (commandID == StandardApplicationCommandIDs::quit)
  13854. {
  13855. result.setInfo (TRANS("Quit"),
  13856. TRANS("Quits the application"),
  13857. "Application",
  13858. 0);
  13859. result.defaultKeypresses.add (KeyPress ('q', ModifierKeys::commandModifier, 0));
  13860. }
  13861. }
  13862. bool JUCEApplication::perform (const InvocationInfo& info)
  13863. {
  13864. if (info.commandID == StandardApplicationCommandIDs::quit)
  13865. {
  13866. systemRequestedQuit();
  13867. return true;
  13868. }
  13869. return false;
  13870. }
  13871. int JUCEApplication::main (String& commandLine, JUCEApplication* const app)
  13872. {
  13873. if (! app->initialiseApp (commandLine))
  13874. return 0;
  13875. // now loop until a quit message is received..
  13876. JUCE_TRY
  13877. {
  13878. MessageManager::getInstance()->runDispatchLoop();
  13879. }
  13880. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  13881. catch (const std::exception& e)
  13882. {
  13883. app->unhandledException (&e, __FILE__, __LINE__);
  13884. }
  13885. catch (...)
  13886. {
  13887. app->unhandledException (0, __FILE__, __LINE__);
  13888. }
  13889. #endif
  13890. return shutdownAppAndClearUp();
  13891. }
  13892. bool JUCEApplication::initialiseApp (String& commandLine)
  13893. {
  13894. jassert (appInstance == 0);
  13895. appInstance = this;
  13896. commandLineParameters = commandLine.trim();
  13897. commandLine = String::empty;
  13898. initialiseJuce_GUI();
  13899. #if ! JUCE_IPHONE
  13900. jassert (appLock == 0); // initialiseApp must only be called once!
  13901. if (! moreThanOneInstanceAllowed())
  13902. {
  13903. appLock = new InterProcessLock ("juceAppLock_" + getApplicationName());
  13904. if (! appLock->enter(0))
  13905. {
  13906. MessageManager::broadcastMessage (getApplicationName() + "/" + commandLineParameters);
  13907. delete appInstance;
  13908. appInstance = 0;
  13909. DBG ("Another instance is running - quitting...");
  13910. return false;
  13911. }
  13912. }
  13913. #endif
  13914. // let the app do its setting-up..
  13915. initialise (commandLineParameters);
  13916. // register for broadcast new app messages
  13917. MessageManager::getInstance()->registerBroadcastListener (this);
  13918. stillInitialising = false;
  13919. return true;
  13920. }
  13921. int JUCEApplication::shutdownAppAndClearUp()
  13922. {
  13923. jassert (appInstance != 0);
  13924. ScopedPointer<JUCEApplication> app (appInstance);
  13925. int returnValue = 0;
  13926. MessageManager::getInstance()->deregisterBroadcastListener (static_cast <JUCEApplication*> (app));
  13927. static bool reentrancyCheck = false;
  13928. if (! reentrancyCheck)
  13929. {
  13930. reentrancyCheck = true;
  13931. JUCE_TRY
  13932. {
  13933. // give the app a chance to clean up..
  13934. app->shutdown();
  13935. }
  13936. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  13937. catch (const std::exception& e)
  13938. {
  13939. app->unhandledException (&e, __FILE__, __LINE__);
  13940. }
  13941. catch (...)
  13942. {
  13943. app->unhandledException (0, __FILE__, __LINE__);
  13944. }
  13945. #endif
  13946. JUCE_TRY
  13947. {
  13948. shutdownJuce_GUI();
  13949. returnValue = app->getApplicationReturnValue();
  13950. appInstance = 0;
  13951. app = 0;
  13952. }
  13953. JUCE_CATCH_ALL_ASSERT
  13954. reentrancyCheck = false;
  13955. }
  13956. return returnValue;
  13957. }
  13958. #if JUCE_IPHONE
  13959. extern int juce_IPhoneMain (int argc, const char* argv[], JUCEApplication* app);
  13960. #endif
  13961. #if ! JUCE_WINDOWS
  13962. extern const char* juce_Argv0;
  13963. #endif
  13964. int JUCEApplication::main (int argc, const char* argv[], JUCEApplication* const newApp)
  13965. {
  13966. #if ! JUCE_WINDOWS
  13967. juce_Argv0 = argv[0];
  13968. #endif
  13969. #if JUCE_IPHONE
  13970. const ScopedAutoReleasePool pool;
  13971. return juce_IPhoneMain (argc, argv, newApp);
  13972. #else
  13973. #if JUCE_MAC
  13974. const ScopedAutoReleasePool pool;
  13975. #endif
  13976. String cmd;
  13977. for (int i = 1; i < argc; ++i)
  13978. cmd << argv[i] << ' ';
  13979. return JUCEApplication::main (cmd, newApp);
  13980. #endif
  13981. }
  13982. void JUCEApplication::actionListenerCallback (const String& message)
  13983. {
  13984. if (message.startsWith (getApplicationName() + "/"))
  13985. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  13986. }
  13987. static bool juceInitialisedGUI = false;
  13988. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI()
  13989. {
  13990. if (! juceInitialisedGUI)
  13991. {
  13992. #if JUCE_MAC || JUCE_IPHONE
  13993. const ScopedAutoReleasePool pool;
  13994. #endif
  13995. juceInitialisedGUI = true;
  13996. initialiseJuce_NonGUI();
  13997. MessageManager::getInstance();
  13998. LookAndFeel::setDefaultLookAndFeel (0);
  13999. juce_setCurrentThreadName ("Juce Message Thread");
  14000. #if JUCE_WINDOWS && JUCE_DEBUG
  14001. // This section is just for catching people who mess up their project settings and
  14002. // turn RTTI off..
  14003. try
  14004. {
  14005. TextButton tb (String::empty);
  14006. Component* c = &tb;
  14007. // Got an exception here? Then TURN ON RTTI in your compiler settings!!
  14008. c = dynamic_cast <Button*> (c);
  14009. }
  14010. catch (...)
  14011. {
  14012. // Ended up here? If so, TURN ON RTTI in your compiler settings!! And if you
  14013. // got as far as this catch statement, then why haven't you got exception catching
  14014. // turned on in the debugger???
  14015. jassertfalse;
  14016. }
  14017. #endif
  14018. }
  14019. }
  14020. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI()
  14021. {
  14022. if (juceInitialisedGUI)
  14023. {
  14024. #if JUCE_MAC
  14025. const ScopedAutoReleasePool pool;
  14026. #endif
  14027. {
  14028. DeletedAtShutdown::deleteAll();
  14029. LookAndFeel::clearDefaultLookAndFeel();
  14030. }
  14031. delete MessageManager::getInstance();
  14032. shutdownJuce_NonGUI();
  14033. juceInitialisedGUI = false;
  14034. }
  14035. }
  14036. END_JUCE_NAMESPACE
  14037. /*** End of inlined file: juce_Application.cpp ***/
  14038. /*** Start of inlined file: juce_ApplicationCommandInfo.cpp ***/
  14039. BEGIN_JUCE_NAMESPACE
  14040. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  14041. : commandID (commandID_),
  14042. flags (0)
  14043. {
  14044. }
  14045. void ApplicationCommandInfo::setInfo (const String& shortName_,
  14046. const String& description_,
  14047. const String& categoryName_,
  14048. const int flags_) throw()
  14049. {
  14050. shortName = shortName_;
  14051. description = description_;
  14052. categoryName = categoryName_;
  14053. flags = flags_;
  14054. }
  14055. void ApplicationCommandInfo::setActive (const bool b) throw()
  14056. {
  14057. if (b)
  14058. flags &= ~isDisabled;
  14059. else
  14060. flags |= isDisabled;
  14061. }
  14062. void ApplicationCommandInfo::setTicked (const bool b) throw()
  14063. {
  14064. if (b)
  14065. flags |= isTicked;
  14066. else
  14067. flags &= ~isTicked;
  14068. }
  14069. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  14070. {
  14071. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  14072. }
  14073. END_JUCE_NAMESPACE
  14074. /*** End of inlined file: juce_ApplicationCommandInfo.cpp ***/
  14075. /*** Start of inlined file: juce_ApplicationCommandManager.cpp ***/
  14076. BEGIN_JUCE_NAMESPACE
  14077. ApplicationCommandManager::ApplicationCommandManager()
  14078. : firstTarget (0)
  14079. {
  14080. keyMappings = new KeyPressMappingSet (this);
  14081. Desktop::getInstance().addFocusChangeListener (this);
  14082. }
  14083. ApplicationCommandManager::~ApplicationCommandManager()
  14084. {
  14085. Desktop::getInstance().removeFocusChangeListener (this);
  14086. keyMappings = 0;
  14087. }
  14088. void ApplicationCommandManager::clearCommands()
  14089. {
  14090. commands.clear();
  14091. keyMappings->clearAllKeyPresses();
  14092. triggerAsyncUpdate();
  14093. }
  14094. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  14095. {
  14096. // zero isn't a valid command ID!
  14097. jassert (newCommand.commandID != 0);
  14098. // the name isn't optional!
  14099. jassert (newCommand.shortName.isNotEmpty());
  14100. if (getCommandForID (newCommand.commandID) == 0)
  14101. {
  14102. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  14103. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  14104. commands.add (newInfo);
  14105. keyMappings->resetToDefaultMapping (newCommand.commandID);
  14106. triggerAsyncUpdate();
  14107. }
  14108. else
  14109. {
  14110. // trying to re-register the same command with different parameters?
  14111. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  14112. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  14113. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  14114. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  14115. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  14116. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  14117. }
  14118. }
  14119. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  14120. {
  14121. if (target != 0)
  14122. {
  14123. Array <CommandID> commandIDs;
  14124. target->getAllCommands (commandIDs);
  14125. for (int i = 0; i < commandIDs.size(); ++i)
  14126. {
  14127. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  14128. target->getCommandInfo (info.commandID, info);
  14129. registerCommand (info);
  14130. }
  14131. }
  14132. }
  14133. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  14134. {
  14135. for (int i = commands.size(); --i >= 0;)
  14136. {
  14137. if (commands.getUnchecked (i)->commandID == commandID)
  14138. {
  14139. commands.remove (i);
  14140. triggerAsyncUpdate();
  14141. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  14142. for (int j = keys.size(); --j >= 0;)
  14143. keyMappings->removeKeyPress (keys.getReference (j));
  14144. }
  14145. }
  14146. }
  14147. void ApplicationCommandManager::commandStatusChanged()
  14148. {
  14149. triggerAsyncUpdate();
  14150. }
  14151. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  14152. {
  14153. for (int i = commands.size(); --i >= 0;)
  14154. if (commands.getUnchecked(i)->commandID == commandID)
  14155. return commands.getUnchecked(i);
  14156. return 0;
  14157. }
  14158. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  14159. {
  14160. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  14161. return (ci != 0) ? ci->shortName : String::empty;
  14162. }
  14163. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  14164. {
  14165. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  14166. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  14167. : String::empty;
  14168. }
  14169. const StringArray ApplicationCommandManager::getCommandCategories() const throw()
  14170. {
  14171. StringArray s;
  14172. for (int i = 0; i < commands.size(); ++i)
  14173. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  14174. return s;
  14175. }
  14176. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const throw()
  14177. {
  14178. Array <CommandID> results;
  14179. for (int i = 0; i < commands.size(); ++i)
  14180. if (commands.getUnchecked(i)->categoryName == categoryName)
  14181. results.add (commands.getUnchecked(i)->commandID);
  14182. return results;
  14183. }
  14184. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  14185. {
  14186. ApplicationCommandTarget::InvocationInfo info (commandID);
  14187. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  14188. return invoke (info, asynchronously);
  14189. }
  14190. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  14191. {
  14192. // This call isn't thread-safe for use from a non-UI thread without locking the message
  14193. // manager first..
  14194. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  14195. ApplicationCommandTarget* const target = getFirstCommandTarget (info_.commandID);
  14196. if (target == 0)
  14197. return false;
  14198. ApplicationCommandInfo commandInfo (0);
  14199. target->getCommandInfo (info_.commandID, commandInfo);
  14200. ApplicationCommandTarget::InvocationInfo info (info_);
  14201. info.commandFlags = commandInfo.flags;
  14202. sendListenerInvokeCallback (info);
  14203. const bool ok = target->invoke (info, asynchronously);
  14204. commandStatusChanged();
  14205. return ok;
  14206. }
  14207. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  14208. {
  14209. return firstTarget != 0 ? firstTarget
  14210. : findDefaultComponentTarget();
  14211. }
  14212. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  14213. {
  14214. firstTarget = newTarget;
  14215. }
  14216. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  14217. ApplicationCommandInfo& upToDateInfo)
  14218. {
  14219. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  14220. if (target == 0)
  14221. target = JUCEApplication::getInstance();
  14222. if (target != 0)
  14223. target = target->getTargetForCommand (commandID);
  14224. if (target != 0)
  14225. target->getCommandInfo (commandID, upToDateInfo);
  14226. return target;
  14227. }
  14228. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  14229. {
  14230. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  14231. if (target == 0 && c != 0)
  14232. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  14233. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  14234. return target;
  14235. }
  14236. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  14237. {
  14238. Component* c = Component::getCurrentlyFocusedComponent();
  14239. if (c == 0)
  14240. {
  14241. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  14242. if (activeWindow != 0)
  14243. {
  14244. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  14245. if (c == 0)
  14246. c = activeWindow;
  14247. }
  14248. }
  14249. if (c == 0 && Process::isForegroundProcess())
  14250. {
  14251. // getting a bit desperate now - try all desktop comps..
  14252. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  14253. {
  14254. ApplicationCommandTarget* const target
  14255. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  14256. ->getPeer()->getLastFocusedSubcomponent());
  14257. if (target != 0)
  14258. return target;
  14259. }
  14260. }
  14261. if (c != 0)
  14262. {
  14263. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  14264. // if we're focused on a ResizableWindow, chances are that it's the content
  14265. // component that really should get the event. And if not, the event will
  14266. // still be passed up to the top level window anyway, so let's send it to the
  14267. // content comp.
  14268. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  14269. c = resizableWindow->getContentComponent();
  14270. ApplicationCommandTarget* const target = findTargetForComponent (c);
  14271. if (target != 0)
  14272. return target;
  14273. }
  14274. return JUCEApplication::getInstance();
  14275. }
  14276. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener) throw()
  14277. {
  14278. listeners.add (listener);
  14279. }
  14280. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener) throw()
  14281. {
  14282. listeners.remove (listener);
  14283. }
  14284. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info)
  14285. {
  14286. listeners.call (&ApplicationCommandManagerListener::applicationCommandInvoked, info);
  14287. }
  14288. void ApplicationCommandManager::handleAsyncUpdate()
  14289. {
  14290. listeners.call (&ApplicationCommandManagerListener::applicationCommandListChanged);
  14291. }
  14292. void ApplicationCommandManager::globalFocusChanged (Component*)
  14293. {
  14294. commandStatusChanged();
  14295. }
  14296. END_JUCE_NAMESPACE
  14297. /*** End of inlined file: juce_ApplicationCommandManager.cpp ***/
  14298. /*** Start of inlined file: juce_ApplicationCommandTarget.cpp ***/
  14299. BEGIN_JUCE_NAMESPACE
  14300. ApplicationCommandTarget::ApplicationCommandTarget()
  14301. {
  14302. }
  14303. ApplicationCommandTarget::~ApplicationCommandTarget()
  14304. {
  14305. messageInvoker = 0;
  14306. }
  14307. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  14308. {
  14309. if (isCommandActive (info.commandID))
  14310. {
  14311. if (async)
  14312. {
  14313. if (messageInvoker == 0)
  14314. messageInvoker = new CommandTargetMessageInvoker (this);
  14315. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  14316. return true;
  14317. }
  14318. else
  14319. {
  14320. const bool success = perform (info);
  14321. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  14322. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  14323. // returns the command's info.
  14324. return success;
  14325. }
  14326. }
  14327. return false;
  14328. }
  14329. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  14330. {
  14331. Component* c = dynamic_cast <Component*> (this);
  14332. if (c != 0)
  14333. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  14334. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  14335. return 0;
  14336. }
  14337. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  14338. {
  14339. ApplicationCommandTarget* target = this;
  14340. int depth = 0;
  14341. while (target != 0)
  14342. {
  14343. Array <CommandID> commandIDs;
  14344. target->getAllCommands (commandIDs);
  14345. if (commandIDs.contains (commandID))
  14346. return target;
  14347. target = target->getNextCommandTarget();
  14348. ++depth;
  14349. jassert (depth < 100); // could be a recursive command chain??
  14350. jassert (target != this); // definitely a recursive command chain!
  14351. if (depth > 100 || target == this)
  14352. break;
  14353. }
  14354. if (target == 0)
  14355. {
  14356. target = JUCEApplication::getInstance();
  14357. if (target != 0)
  14358. {
  14359. Array <CommandID> commandIDs;
  14360. target->getAllCommands (commandIDs);
  14361. if (commandIDs.contains (commandID))
  14362. return target;
  14363. }
  14364. }
  14365. return 0;
  14366. }
  14367. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  14368. {
  14369. ApplicationCommandInfo info (commandID);
  14370. info.flags = ApplicationCommandInfo::isDisabled;
  14371. getCommandInfo (commandID, info);
  14372. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  14373. }
  14374. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  14375. {
  14376. ApplicationCommandTarget* target = this;
  14377. int depth = 0;
  14378. while (target != 0)
  14379. {
  14380. if (target->tryToInvoke (info, async))
  14381. return true;
  14382. target = target->getNextCommandTarget();
  14383. ++depth;
  14384. jassert (depth < 100); // could be a recursive command chain??
  14385. jassert (target != this); // definitely a recursive command chain!
  14386. if (depth > 100 || target == this)
  14387. break;
  14388. }
  14389. if (target == 0)
  14390. {
  14391. target = JUCEApplication::getInstance();
  14392. if (target != 0)
  14393. return target->tryToInvoke (info, async);
  14394. }
  14395. return false;
  14396. }
  14397. bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
  14398. {
  14399. ApplicationCommandTarget::InvocationInfo info (commandID);
  14400. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  14401. return invoke (info, asynchronously);
  14402. }
  14403. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_) throw()
  14404. : commandID (commandID_),
  14405. commandFlags (0),
  14406. invocationMethod (direct),
  14407. originatingComponent (0),
  14408. isKeyDown (false),
  14409. millisecsSinceKeyPressed (0)
  14410. {
  14411. }
  14412. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  14413. : owner (owner_)
  14414. {
  14415. }
  14416. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  14417. {
  14418. }
  14419. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  14420. {
  14421. const ScopedPointer <InvocationInfo> info (static_cast <InvocationInfo*> (message.pointerParameter));
  14422. owner->tryToInvoke (*info, false);
  14423. }
  14424. END_JUCE_NAMESPACE
  14425. /*** End of inlined file: juce_ApplicationCommandTarget.cpp ***/
  14426. /*** Start of inlined file: juce_ApplicationProperties.cpp ***/
  14427. BEGIN_JUCE_NAMESPACE
  14428. juce_ImplementSingleton (ApplicationProperties)
  14429. ApplicationProperties::ApplicationProperties() throw()
  14430. : msBeforeSaving (3000),
  14431. options (PropertiesFile::storeAsBinary),
  14432. commonSettingsAreReadOnly (0)
  14433. {
  14434. }
  14435. ApplicationProperties::~ApplicationProperties()
  14436. {
  14437. closeFiles();
  14438. clearSingletonInstance();
  14439. }
  14440. void ApplicationProperties::setStorageParameters (const String& applicationName,
  14441. const String& fileNameSuffix,
  14442. const String& folderName_,
  14443. const int millisecondsBeforeSaving,
  14444. const int propertiesFileOptions) throw()
  14445. {
  14446. appName = applicationName;
  14447. fileSuffix = fileNameSuffix;
  14448. folderName = folderName_;
  14449. msBeforeSaving = millisecondsBeforeSaving;
  14450. options = propertiesFileOptions;
  14451. }
  14452. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  14453. const bool testCommonSettings,
  14454. const bool showWarningDialogOnFailure)
  14455. {
  14456. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  14457. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  14458. if (! (userOk && commonOk))
  14459. {
  14460. if (showWarningDialogOnFailure)
  14461. {
  14462. String filenames;
  14463. if (userProps != 0 && ! userOk)
  14464. filenames << '\n' << userProps->getFile().getFullPathName();
  14465. if (commonProps != 0 && ! commonOk)
  14466. filenames << '\n' << commonProps->getFile().getFullPathName();
  14467. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  14468. appName + TRANS(" - Unable to save settings"),
  14469. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  14470. + appName + TRANS(" needs to be able to write to the following files:\n")
  14471. + filenames
  14472. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  14473. }
  14474. return false;
  14475. }
  14476. return true;
  14477. }
  14478. void ApplicationProperties::openFiles() throw()
  14479. {
  14480. // You need to call setStorageParameters() before trying to get hold of the
  14481. // properties!
  14482. jassert (appName.isNotEmpty());
  14483. if (appName.isNotEmpty())
  14484. {
  14485. if (userProps == 0)
  14486. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  14487. false, msBeforeSaving, options);
  14488. if (commonProps == 0)
  14489. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  14490. true, msBeforeSaving, options);
  14491. userProps->setFallbackPropertySet (commonProps);
  14492. }
  14493. }
  14494. PropertiesFile* ApplicationProperties::getUserSettings() throw()
  14495. {
  14496. if (userProps == 0)
  14497. openFiles();
  14498. return userProps;
  14499. }
  14500. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly) throw()
  14501. {
  14502. if (commonProps == 0)
  14503. openFiles();
  14504. if (returnUserPropsIfReadOnly)
  14505. {
  14506. if (commonSettingsAreReadOnly == 0)
  14507. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  14508. if (commonSettingsAreReadOnly > 0)
  14509. return userProps;
  14510. }
  14511. return commonProps;
  14512. }
  14513. bool ApplicationProperties::saveIfNeeded()
  14514. {
  14515. return (userProps == 0 || userProps->saveIfNeeded())
  14516. && (commonProps == 0 || commonProps->saveIfNeeded());
  14517. }
  14518. void ApplicationProperties::closeFiles()
  14519. {
  14520. userProps = 0;
  14521. commonProps = 0;
  14522. }
  14523. END_JUCE_NAMESPACE
  14524. /*** End of inlined file: juce_ApplicationProperties.cpp ***/
  14525. /*** Start of inlined file: juce_PropertiesFile.cpp ***/
  14526. BEGIN_JUCE_NAMESPACE
  14527. namespace PropertyFileConstants
  14528. {
  14529. static const int magicNumber = (int) ByteOrder::littleEndianInt ("PROP");
  14530. static const int magicNumberCompressed = (int) ByteOrder::littleEndianInt ("CPRP");
  14531. static const char* const fileTag = "PROPERTIES";
  14532. static const char* const valueTag = "VALUE";
  14533. static const char* const nameAttribute = "name";
  14534. static const char* const valueAttribute = "val";
  14535. }
  14536. PropertiesFile::PropertiesFile (const File& f, const int millisecondsBeforeSaving,
  14537. const int options_, InterProcessLock* const processLock_)
  14538. : PropertySet (ignoreCaseOfKeyNames),
  14539. file (f),
  14540. timerInterval (millisecondsBeforeSaving),
  14541. options (options_),
  14542. loadedOk (false),
  14543. needsWriting (false),
  14544. processLock (processLock_)
  14545. {
  14546. // You need to correctly specify just one storage format for the file
  14547. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  14548. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  14549. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  14550. ProcessScopedLock pl (createProcessLock());
  14551. if (pl != 0 && ! pl->isLocked())
  14552. return; // locking failure..
  14553. ScopedPointer<InputStream> fileStream (f.createInputStream());
  14554. if (fileStream != 0)
  14555. {
  14556. int magicNumber = fileStream->readInt();
  14557. if (magicNumber == PropertyFileConstants::magicNumberCompressed)
  14558. {
  14559. fileStream = new GZIPDecompressorInputStream (new SubregionStream (fileStream.release(), 4, -1, true), true);
  14560. magicNumber = PropertyFileConstants::magicNumber;
  14561. }
  14562. if (magicNumber == PropertyFileConstants::magicNumber)
  14563. {
  14564. loadedOk = true;
  14565. BufferedInputStream in (fileStream.release(), 2048, true);
  14566. int numValues = in.readInt();
  14567. while (--numValues >= 0 && ! in.isExhausted())
  14568. {
  14569. const String key (in.readString());
  14570. const String value (in.readString());
  14571. jassert (key.isNotEmpty());
  14572. if (key.isNotEmpty())
  14573. getAllProperties().set (key, value);
  14574. }
  14575. }
  14576. else
  14577. {
  14578. // Not a binary props file - let's see if it's XML..
  14579. fileStream = 0;
  14580. XmlDocument parser (f);
  14581. ScopedPointer<XmlElement> doc (parser.getDocumentElement (true));
  14582. if (doc != 0 && doc->hasTagName (PropertyFileConstants::fileTag))
  14583. {
  14584. doc = parser.getDocumentElement();
  14585. if (doc != 0)
  14586. {
  14587. loadedOk = true;
  14588. forEachXmlChildElementWithTagName (*doc, e, PropertyFileConstants::valueTag)
  14589. {
  14590. const String name (e->getStringAttribute (PropertyFileConstants::nameAttribute));
  14591. if (name.isNotEmpty())
  14592. {
  14593. getAllProperties().set (name,
  14594. e->getFirstChildElement() != 0
  14595. ? e->getFirstChildElement()->createDocument (String::empty, true)
  14596. : e->getStringAttribute (PropertyFileConstants::valueAttribute));
  14597. }
  14598. }
  14599. }
  14600. else
  14601. {
  14602. // must be a pretty broken XML file we're trying to parse here,
  14603. // or a sign that this object needs an InterProcessLock,
  14604. // or just a failure reading the file. This last reason is why
  14605. // we don't jassertfalse here.
  14606. }
  14607. }
  14608. }
  14609. }
  14610. else
  14611. {
  14612. loadedOk = ! f.exists();
  14613. }
  14614. }
  14615. PropertiesFile::~PropertiesFile()
  14616. {
  14617. if (! saveIfNeeded())
  14618. jassertfalse;
  14619. }
  14620. InterProcessLock::ScopedLockType* PropertiesFile::createProcessLock() const
  14621. {
  14622. return processLock != 0 ? new InterProcessLock::ScopedLockType (*processLock) : 0;
  14623. }
  14624. bool PropertiesFile::saveIfNeeded()
  14625. {
  14626. const ScopedLock sl (getLock());
  14627. return (! needsWriting) || save();
  14628. }
  14629. bool PropertiesFile::needsToBeSaved() const
  14630. {
  14631. const ScopedLock sl (getLock());
  14632. return needsWriting;
  14633. }
  14634. void PropertiesFile::setNeedsToBeSaved (const bool needsToBeSaved_)
  14635. {
  14636. const ScopedLock sl (getLock());
  14637. needsWriting = needsToBeSaved_;
  14638. }
  14639. bool PropertiesFile::save()
  14640. {
  14641. const ScopedLock sl (getLock());
  14642. stopTimer();
  14643. if (file == File::nonexistent
  14644. || file.isDirectory()
  14645. || ! file.getParentDirectory().createDirectory())
  14646. return false;
  14647. if ((options & storeAsXML) != 0)
  14648. {
  14649. XmlElement doc (PropertyFileConstants::fileTag);
  14650. for (int i = 0; i < getAllProperties().size(); ++i)
  14651. {
  14652. XmlElement* const e = doc.createNewChildElement (PropertyFileConstants::valueTag);
  14653. e->setAttribute (PropertyFileConstants::nameAttribute, getAllProperties().getAllKeys() [i]);
  14654. // if the value seems to contain xml, store it as such..
  14655. XmlDocument xmlContent (getAllProperties().getAllValues() [i]);
  14656. XmlElement* const childElement = xmlContent.getDocumentElement();
  14657. if (childElement != 0)
  14658. e->addChildElement (childElement);
  14659. else
  14660. e->setAttribute (PropertyFileConstants::valueAttribute,
  14661. getAllProperties().getAllValues() [i]);
  14662. }
  14663. ProcessScopedLock pl (createProcessLock());
  14664. if (pl != 0 && ! pl->isLocked())
  14665. return false; // locking failure..
  14666. if (doc.writeToFile (file, String::empty))
  14667. {
  14668. needsWriting = false;
  14669. return true;
  14670. }
  14671. }
  14672. else
  14673. {
  14674. ProcessScopedLock pl (createProcessLock());
  14675. if (pl != 0 && ! pl->isLocked())
  14676. return false; // locking failure..
  14677. TemporaryFile tempFile (file);
  14678. ScopedPointer <OutputStream> out (tempFile.getFile().createOutputStream());
  14679. if (out != 0)
  14680. {
  14681. if ((options & storeAsCompressedBinary) != 0)
  14682. {
  14683. out->writeInt (PropertyFileConstants::magicNumberCompressed);
  14684. out->flush();
  14685. out = new GZIPCompressorOutputStream (out.release(), 9, true);
  14686. }
  14687. else
  14688. {
  14689. // have you set up the storage option flags correctly?
  14690. jassert ((options & storeAsBinary) != 0);
  14691. out->writeInt (PropertyFileConstants::magicNumber);
  14692. }
  14693. const int numProperties = getAllProperties().size();
  14694. out->writeInt (numProperties);
  14695. for (int i = 0; i < numProperties; ++i)
  14696. {
  14697. out->writeString (getAllProperties().getAllKeys() [i]);
  14698. out->writeString (getAllProperties().getAllValues() [i]);
  14699. }
  14700. out = 0;
  14701. if (tempFile.overwriteTargetFileWithTemporary())
  14702. {
  14703. needsWriting = false;
  14704. return true;
  14705. }
  14706. }
  14707. }
  14708. return false;
  14709. }
  14710. void PropertiesFile::timerCallback()
  14711. {
  14712. saveIfNeeded();
  14713. }
  14714. void PropertiesFile::propertyChanged()
  14715. {
  14716. sendChangeMessage (this);
  14717. needsWriting = true;
  14718. if (timerInterval > 0)
  14719. startTimer (timerInterval);
  14720. else if (timerInterval == 0)
  14721. saveIfNeeded();
  14722. }
  14723. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  14724. const String& fileNameSuffix,
  14725. const String& folderName,
  14726. const bool commonToAllUsers)
  14727. {
  14728. // mustn't have illegal characters in this name..
  14729. jassert (applicationName == File::createLegalFileName (applicationName));
  14730. #if JUCE_MAC || JUCE_IPHONE
  14731. File dir (commonToAllUsers ? "/Library/Preferences"
  14732. : "~/Library/Preferences");
  14733. if (folderName.isNotEmpty())
  14734. dir = dir.getChildFile (folderName);
  14735. #endif
  14736. #ifdef JUCE_LINUX
  14737. const File dir ((commonToAllUsers ? "/var/" : "~/")
  14738. + (folderName.isNotEmpty() ? folderName
  14739. : ("." + applicationName)));
  14740. #endif
  14741. #if JUCE_WINDOWS
  14742. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  14743. : File::userApplicationDataDirectory));
  14744. if (dir == File::nonexistent)
  14745. return File::nonexistent;
  14746. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  14747. : applicationName);
  14748. #endif
  14749. return dir.getChildFile (applicationName)
  14750. .withFileExtension (fileNameSuffix);
  14751. }
  14752. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  14753. const String& fileNameSuffix,
  14754. const String& folderName,
  14755. const bool commonToAllUsers,
  14756. const int millisecondsBeforeSaving,
  14757. const int propertiesFileOptions,
  14758. InterProcessLock* processLock_)
  14759. {
  14760. const File file (getDefaultAppSettingsFile (applicationName,
  14761. fileNameSuffix,
  14762. folderName,
  14763. commonToAllUsers));
  14764. jassert (file != File::nonexistent);
  14765. if (file == File::nonexistent)
  14766. return 0;
  14767. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions,processLock_);
  14768. }
  14769. END_JUCE_NAMESPACE
  14770. /*** End of inlined file: juce_PropertiesFile.cpp ***/
  14771. /*** Start of inlined file: juce_FileBasedDocument.cpp ***/
  14772. BEGIN_JUCE_NAMESPACE
  14773. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  14774. const String& fileWildcard_,
  14775. const String& openFileDialogTitle_,
  14776. const String& saveFileDialogTitle_)
  14777. : changedSinceSave (false),
  14778. fileExtension (fileExtension_),
  14779. fileWildcard (fileWildcard_),
  14780. openFileDialogTitle (openFileDialogTitle_),
  14781. saveFileDialogTitle (saveFileDialogTitle_)
  14782. {
  14783. }
  14784. FileBasedDocument::~FileBasedDocument()
  14785. {
  14786. }
  14787. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  14788. {
  14789. if (changedSinceSave != hasChanged)
  14790. {
  14791. changedSinceSave = hasChanged;
  14792. sendChangeMessage (this);
  14793. }
  14794. }
  14795. void FileBasedDocument::changed()
  14796. {
  14797. changedSinceSave = true;
  14798. sendChangeMessage (this);
  14799. }
  14800. void FileBasedDocument::setFile (const File& newFile)
  14801. {
  14802. if (documentFile != newFile)
  14803. {
  14804. documentFile = newFile;
  14805. changed();
  14806. }
  14807. }
  14808. bool FileBasedDocument::loadFrom (const File& newFile,
  14809. const bool showMessageOnFailure)
  14810. {
  14811. MouseCursor::showWaitCursor();
  14812. const File oldFile (documentFile);
  14813. documentFile = newFile;
  14814. String error;
  14815. if (newFile.existsAsFile())
  14816. {
  14817. error = loadDocument (newFile);
  14818. if (error.isEmpty())
  14819. {
  14820. setChangedFlag (false);
  14821. MouseCursor::hideWaitCursor();
  14822. setLastDocumentOpened (newFile);
  14823. return true;
  14824. }
  14825. }
  14826. else
  14827. {
  14828. error = "The file doesn't exist";
  14829. }
  14830. documentFile = oldFile;
  14831. MouseCursor::hideWaitCursor();
  14832. if (showMessageOnFailure)
  14833. {
  14834. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  14835. TRANS("Failed to open file..."),
  14836. TRANS("There was an error while trying to load the file:\n\n")
  14837. + newFile.getFullPathName()
  14838. + "\n\n"
  14839. + error);
  14840. }
  14841. return false;
  14842. }
  14843. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  14844. {
  14845. FileChooser fc (openFileDialogTitle,
  14846. getLastDocumentOpened(),
  14847. fileWildcard);
  14848. if (fc.browseForFileToOpen())
  14849. return loadFrom (fc.getResult(), showMessageOnFailure);
  14850. return false;
  14851. }
  14852. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  14853. const bool showMessageOnFailure)
  14854. {
  14855. return saveAs (documentFile,
  14856. false,
  14857. askUserForFileIfNotSpecified,
  14858. showMessageOnFailure);
  14859. }
  14860. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  14861. const bool warnAboutOverwritingExistingFiles,
  14862. const bool askUserForFileIfNotSpecified,
  14863. const bool showMessageOnFailure)
  14864. {
  14865. if (newFile == File::nonexistent)
  14866. {
  14867. if (askUserForFileIfNotSpecified)
  14868. {
  14869. return saveAsInteractive (true);
  14870. }
  14871. else
  14872. {
  14873. // can't save to an unspecified file
  14874. jassertfalse;
  14875. return failedToWriteToFile;
  14876. }
  14877. }
  14878. if (warnAboutOverwritingExistingFiles && newFile.exists())
  14879. {
  14880. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  14881. TRANS("File already exists"),
  14882. TRANS("There's already a file called:\n\n")
  14883. + newFile.getFullPathName()
  14884. + TRANS("\n\nAre you sure you want to overwrite it?"),
  14885. TRANS("overwrite"),
  14886. TRANS("cancel")))
  14887. {
  14888. return userCancelledSave;
  14889. }
  14890. }
  14891. MouseCursor::showWaitCursor();
  14892. const File oldFile (documentFile);
  14893. documentFile = newFile;
  14894. String error (saveDocument (newFile));
  14895. if (error.isEmpty())
  14896. {
  14897. setChangedFlag (false);
  14898. MouseCursor::hideWaitCursor();
  14899. return savedOk;
  14900. }
  14901. documentFile = oldFile;
  14902. MouseCursor::hideWaitCursor();
  14903. if (showMessageOnFailure)
  14904. {
  14905. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  14906. TRANS("Error writing to file..."),
  14907. TRANS("An error occurred while trying to save \"")
  14908. + getDocumentTitle()
  14909. + TRANS("\" to the file:\n\n")
  14910. + newFile.getFullPathName()
  14911. + "\n\n"
  14912. + error);
  14913. }
  14914. return failedToWriteToFile;
  14915. }
  14916. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  14917. {
  14918. if (! hasChangedSinceSaved())
  14919. return savedOk;
  14920. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  14921. TRANS("Closing document..."),
  14922. TRANS("Do you want to save the changes to \"")
  14923. + getDocumentTitle() + "\"?",
  14924. TRANS("save"),
  14925. TRANS("discard changes"),
  14926. TRANS("cancel"));
  14927. if (r == 1)
  14928. {
  14929. // save changes
  14930. return save (true, true);
  14931. }
  14932. else if (r == 2)
  14933. {
  14934. // discard changes
  14935. return savedOk;
  14936. }
  14937. return userCancelledSave;
  14938. }
  14939. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  14940. {
  14941. File f;
  14942. if (documentFile.existsAsFile())
  14943. f = documentFile;
  14944. else
  14945. f = getLastDocumentOpened();
  14946. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  14947. if (legalFilename.isEmpty())
  14948. legalFilename = "unnamed";
  14949. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  14950. f = f.getSiblingFile (legalFilename);
  14951. else
  14952. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  14953. f = f.withFileExtension (fileExtension)
  14954. .getNonexistentSibling (true);
  14955. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  14956. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  14957. {
  14958. setLastDocumentOpened (fc.getResult());
  14959. File chosen (fc.getResult());
  14960. if (chosen.getFileExtension().isEmpty())
  14961. {
  14962. chosen = chosen.withFileExtension (fileExtension);
  14963. if (chosen.exists())
  14964. {
  14965. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  14966. TRANS("File already exists"),
  14967. TRANS("There's already a file called:")
  14968. + "\n\n" + chosen.getFullPathName()
  14969. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  14970. TRANS("overwrite"),
  14971. TRANS("cancel")))
  14972. {
  14973. return userCancelledSave;
  14974. }
  14975. }
  14976. }
  14977. return saveAs (chosen, false, false, true);
  14978. }
  14979. return userCancelledSave;
  14980. }
  14981. END_JUCE_NAMESPACE
  14982. /*** End of inlined file: juce_FileBasedDocument.cpp ***/
  14983. /*** Start of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  14984. BEGIN_JUCE_NAMESPACE
  14985. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  14986. : maxNumberOfItems (10)
  14987. {
  14988. }
  14989. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  14990. {
  14991. }
  14992. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  14993. {
  14994. maxNumberOfItems = jmax (1, newMaxNumber);
  14995. while (getNumFiles() > maxNumberOfItems)
  14996. files.remove (getNumFiles() - 1);
  14997. }
  14998. int RecentlyOpenedFilesList::getNumFiles() const
  14999. {
  15000. return files.size();
  15001. }
  15002. const File RecentlyOpenedFilesList::getFile (const int index) const
  15003. {
  15004. return File (files [index]);
  15005. }
  15006. void RecentlyOpenedFilesList::clear()
  15007. {
  15008. files.clear();
  15009. }
  15010. void RecentlyOpenedFilesList::addFile (const File& file)
  15011. {
  15012. const String path (file.getFullPathName());
  15013. files.removeString (path, true);
  15014. files.insert (0, path);
  15015. setMaxNumberOfItems (maxNumberOfItems);
  15016. }
  15017. void RecentlyOpenedFilesList::removeNonExistentFiles()
  15018. {
  15019. for (int i = getNumFiles(); --i >= 0;)
  15020. if (! getFile(i).exists())
  15021. files.remove (i);
  15022. }
  15023. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  15024. const int baseItemId,
  15025. const bool showFullPaths,
  15026. const bool dontAddNonExistentFiles,
  15027. const File** filesToAvoid)
  15028. {
  15029. int num = 0;
  15030. for (int i = 0; i < getNumFiles(); ++i)
  15031. {
  15032. const File f (getFile(i));
  15033. if ((! dontAddNonExistentFiles) || f.exists())
  15034. {
  15035. bool needsAvoiding = false;
  15036. if (filesToAvoid != 0)
  15037. {
  15038. const File** avoid = filesToAvoid;
  15039. while (*avoid != 0)
  15040. {
  15041. if (f == **avoid)
  15042. {
  15043. needsAvoiding = true;
  15044. break;
  15045. }
  15046. ++avoid;
  15047. }
  15048. }
  15049. if (! needsAvoiding)
  15050. {
  15051. menuToAddTo.addItem (baseItemId + i,
  15052. showFullPaths ? f.getFullPathName()
  15053. : f.getFileName());
  15054. ++num;
  15055. }
  15056. }
  15057. }
  15058. return num;
  15059. }
  15060. const String RecentlyOpenedFilesList::toString() const
  15061. {
  15062. return files.joinIntoString ("\n");
  15063. }
  15064. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  15065. {
  15066. clear();
  15067. files.addLines (stringifiedVersion);
  15068. setMaxNumberOfItems (maxNumberOfItems);
  15069. }
  15070. END_JUCE_NAMESPACE
  15071. /*** End of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  15072. /*** Start of inlined file: juce_UndoManager.cpp ***/
  15073. BEGIN_JUCE_NAMESPACE
  15074. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  15075. const int minimumTransactions)
  15076. : totalUnitsStored (0),
  15077. nextIndex (0),
  15078. newTransaction (true),
  15079. reentrancyCheck (false)
  15080. {
  15081. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  15082. minimumTransactions);
  15083. }
  15084. UndoManager::~UndoManager()
  15085. {
  15086. clearUndoHistory();
  15087. }
  15088. void UndoManager::clearUndoHistory()
  15089. {
  15090. transactions.clear();
  15091. transactionNames.clear();
  15092. totalUnitsStored = 0;
  15093. nextIndex = 0;
  15094. sendChangeMessage (this);
  15095. }
  15096. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  15097. {
  15098. return totalUnitsStored;
  15099. }
  15100. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  15101. const int minimumTransactions)
  15102. {
  15103. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  15104. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  15105. }
  15106. bool UndoManager::perform (UndoableAction* const command_, const String& actionName)
  15107. {
  15108. if (command_ != 0)
  15109. {
  15110. ScopedPointer<UndoableAction> command (command_);
  15111. if (actionName.isNotEmpty())
  15112. currentTransactionName = actionName;
  15113. if (reentrancyCheck)
  15114. {
  15115. jassertfalse; // don't call perform() recursively from the UndoableAction::perform() or
  15116. // undo() methods, or else these actions won't actually get done.
  15117. return false;
  15118. }
  15119. else if (command->perform())
  15120. {
  15121. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  15122. if (commandSet != 0 && ! newTransaction)
  15123. {
  15124. UndoableAction* lastAction = commandSet->getLast();
  15125. if (lastAction != 0)
  15126. {
  15127. UndoableAction* coalescedAction = lastAction->createCoalescedAction (command);
  15128. if (coalescedAction != 0)
  15129. {
  15130. command = coalescedAction;
  15131. totalUnitsStored -= lastAction->getSizeInUnits();
  15132. commandSet->removeLast();
  15133. }
  15134. }
  15135. }
  15136. else
  15137. {
  15138. commandSet = new OwnedArray<UndoableAction>();
  15139. transactions.insert (nextIndex, commandSet);
  15140. transactionNames.insert (nextIndex, currentTransactionName);
  15141. ++nextIndex;
  15142. }
  15143. totalUnitsStored += command->getSizeInUnits();
  15144. commandSet->add (command.release());
  15145. newTransaction = false;
  15146. while (nextIndex < transactions.size())
  15147. {
  15148. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  15149. for (int i = lastSet->size(); --i >= 0;)
  15150. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  15151. transactions.removeLast();
  15152. transactionNames.remove (transactionNames.size() - 1);
  15153. }
  15154. while (nextIndex > 0
  15155. && totalUnitsStored > maxNumUnitsToKeep
  15156. && transactions.size() > minimumTransactionsToKeep)
  15157. {
  15158. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  15159. for (int i = firstSet->size(); --i >= 0;)
  15160. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  15161. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  15162. transactions.remove (0);
  15163. transactionNames.remove (0);
  15164. --nextIndex;
  15165. }
  15166. sendChangeMessage (this);
  15167. return true;
  15168. }
  15169. }
  15170. return false;
  15171. }
  15172. void UndoManager::beginNewTransaction (const String& actionName)
  15173. {
  15174. newTransaction = true;
  15175. currentTransactionName = actionName;
  15176. }
  15177. void UndoManager::setCurrentTransactionName (const String& newName)
  15178. {
  15179. currentTransactionName = newName;
  15180. }
  15181. bool UndoManager::canUndo() const
  15182. {
  15183. return nextIndex > 0;
  15184. }
  15185. bool UndoManager::canRedo() const
  15186. {
  15187. return nextIndex < transactions.size();
  15188. }
  15189. const String UndoManager::getUndoDescription() const
  15190. {
  15191. return transactionNames [nextIndex - 1];
  15192. }
  15193. const String UndoManager::getRedoDescription() const
  15194. {
  15195. return transactionNames [nextIndex];
  15196. }
  15197. bool UndoManager::undo()
  15198. {
  15199. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  15200. if (commandSet == 0)
  15201. return false;
  15202. reentrancyCheck = true;
  15203. bool failed = false;
  15204. for (int i = commandSet->size(); --i >= 0;)
  15205. {
  15206. if (! commandSet->getUnchecked(i)->undo())
  15207. {
  15208. jassertfalse;
  15209. failed = true;
  15210. break;
  15211. }
  15212. }
  15213. reentrancyCheck = false;
  15214. if (failed)
  15215. clearUndoHistory();
  15216. else
  15217. --nextIndex;
  15218. beginNewTransaction();
  15219. sendChangeMessage (this);
  15220. return true;
  15221. }
  15222. bool UndoManager::redo()
  15223. {
  15224. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  15225. if (commandSet == 0)
  15226. return false;
  15227. reentrancyCheck = true;
  15228. bool failed = false;
  15229. for (int i = 0; i < commandSet->size(); ++i)
  15230. {
  15231. if (! commandSet->getUnchecked(i)->perform())
  15232. {
  15233. jassertfalse;
  15234. failed = true;
  15235. break;
  15236. }
  15237. }
  15238. reentrancyCheck = false;
  15239. if (failed)
  15240. clearUndoHistory();
  15241. else
  15242. ++nextIndex;
  15243. beginNewTransaction();
  15244. sendChangeMessage (this);
  15245. return true;
  15246. }
  15247. bool UndoManager::undoCurrentTransactionOnly()
  15248. {
  15249. return newTransaction ? false : undo();
  15250. }
  15251. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  15252. {
  15253. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  15254. if (commandSet != 0 && ! newTransaction)
  15255. {
  15256. for (int i = 0; i < commandSet->size(); ++i)
  15257. actionsFound.add (commandSet->getUnchecked(i));
  15258. }
  15259. }
  15260. int UndoManager::getNumActionsInCurrentTransaction() const
  15261. {
  15262. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  15263. if (commandSet != 0 && ! newTransaction)
  15264. return commandSet->size();
  15265. return 0;
  15266. }
  15267. END_JUCE_NAMESPACE
  15268. /*** End of inlined file: juce_UndoManager.cpp ***/
  15269. /*** Start of inlined file: juce_AiffAudioFormat.cpp ***/
  15270. BEGIN_JUCE_NAMESPACE
  15271. static const char* const aiffFormatName = "AIFF file";
  15272. static const char* const aiffExtensions[] = { ".aiff", ".aif", 0 };
  15273. class AiffAudioFormatReader : public AudioFormatReader
  15274. {
  15275. public:
  15276. int bytesPerFrame;
  15277. int64 dataChunkStart;
  15278. bool littleEndian;
  15279. AiffAudioFormatReader (InputStream* in)
  15280. : AudioFormatReader (in, TRANS (aiffFormatName))
  15281. {
  15282. if (input->readInt() == chunkName ("FORM"))
  15283. {
  15284. const int len = input->readIntBigEndian();
  15285. const int64 end = input->getPosition() + len;
  15286. const int nextType = input->readInt();
  15287. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  15288. {
  15289. bool hasGotVer = false;
  15290. bool hasGotData = false;
  15291. bool hasGotType = false;
  15292. while (input->getPosition() < end)
  15293. {
  15294. const int type = input->readInt();
  15295. const uint32 length = (uint32) input->readIntBigEndian();
  15296. const int64 chunkEnd = input->getPosition() + length;
  15297. if (type == chunkName ("FVER"))
  15298. {
  15299. hasGotVer = true;
  15300. const int ver = input->readIntBigEndian();
  15301. if (ver != 0 && ver != (int)0xa2805140)
  15302. break;
  15303. }
  15304. else if (type == chunkName ("COMM"))
  15305. {
  15306. hasGotType = true;
  15307. numChannels = (unsigned int)input->readShortBigEndian();
  15308. lengthInSamples = input->readIntBigEndian();
  15309. bitsPerSample = input->readShortBigEndian();
  15310. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  15311. unsigned char sampleRateBytes[10];
  15312. input->read (sampleRateBytes, 10);
  15313. const int byte0 = sampleRateBytes[0];
  15314. if ((byte0 & 0x80) != 0
  15315. || byte0 <= 0x3F || byte0 > 0x40
  15316. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  15317. break;
  15318. unsigned int sampRate = ByteOrder::bigEndianInt (sampleRateBytes + 2);
  15319. sampRate >>= (16414 - ByteOrder::bigEndianShort (sampleRateBytes));
  15320. sampleRate = (int) sampRate;
  15321. if (length <= 18)
  15322. {
  15323. // some types don't have a chunk large enough to include a compression
  15324. // type, so assume it's just big-endian pcm
  15325. littleEndian = false;
  15326. }
  15327. else
  15328. {
  15329. const int compType = input->readInt();
  15330. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  15331. {
  15332. littleEndian = false;
  15333. }
  15334. else if (compType == chunkName ("sowt"))
  15335. {
  15336. littleEndian = true;
  15337. }
  15338. else
  15339. {
  15340. sampleRate = 0;
  15341. break;
  15342. }
  15343. }
  15344. }
  15345. else if (type == chunkName ("SSND"))
  15346. {
  15347. hasGotData = true;
  15348. const int offset = input->readIntBigEndian();
  15349. dataChunkStart = input->getPosition() + 4 + offset;
  15350. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  15351. }
  15352. else if ((hasGotVer && hasGotData && hasGotType)
  15353. || chunkEnd < input->getPosition()
  15354. || input->isExhausted())
  15355. {
  15356. break;
  15357. }
  15358. input->setPosition (chunkEnd);
  15359. }
  15360. }
  15361. }
  15362. }
  15363. ~AiffAudioFormatReader()
  15364. {
  15365. }
  15366. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  15367. int64 startSampleInFile, int numSamples)
  15368. {
  15369. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  15370. if (samplesAvailable < numSamples)
  15371. {
  15372. for (int i = numDestChannels; --i >= 0;)
  15373. if (destSamples[i] != 0)
  15374. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  15375. numSamples = (int) samplesAvailable;
  15376. }
  15377. if (numSamples <= 0)
  15378. return true;
  15379. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  15380. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  15381. char tempBuffer [tempBufSize];
  15382. while (numSamples > 0)
  15383. {
  15384. int* left = destSamples[0];
  15385. if (left != 0)
  15386. left += startOffsetInDestBuffer;
  15387. int* right = numDestChannels > 1 ? destSamples[1] : 0;
  15388. if (right != 0)
  15389. right += startOffsetInDestBuffer;
  15390. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  15391. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  15392. if (bytesRead < numThisTime * bytesPerFrame)
  15393. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  15394. if (bitsPerSample == 16)
  15395. {
  15396. if (littleEndian)
  15397. {
  15398. const short* src = reinterpret_cast <const short*> (tempBuffer);
  15399. if (numChannels > 1)
  15400. {
  15401. if (left == 0)
  15402. {
  15403. for (int i = numThisTime; --i >= 0;)
  15404. {
  15405. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15406. ++src;
  15407. }
  15408. }
  15409. else if (right == 0)
  15410. {
  15411. for (int i = numThisTime; --i >= 0;)
  15412. {
  15413. ++src;
  15414. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15415. }
  15416. }
  15417. else
  15418. {
  15419. for (int i = numThisTime; --i >= 0;)
  15420. {
  15421. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15422. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15423. }
  15424. }
  15425. }
  15426. else
  15427. {
  15428. for (int i = numThisTime; --i >= 0;)
  15429. {
  15430. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  15431. }
  15432. }
  15433. }
  15434. else
  15435. {
  15436. const char* src = tempBuffer;
  15437. if (numChannels > 1)
  15438. {
  15439. if (left == 0)
  15440. {
  15441. for (int i = numThisTime; --i >= 0;)
  15442. {
  15443. *right++ = ByteOrder::bigEndianShort (src) << 16;
  15444. src += 4;
  15445. }
  15446. }
  15447. else if (right == 0)
  15448. {
  15449. for (int i = numThisTime; --i >= 0;)
  15450. {
  15451. src += 2;
  15452. *left++ = ByteOrder::bigEndianShort (src) << 16;
  15453. src += 2;
  15454. }
  15455. }
  15456. else
  15457. {
  15458. for (int i = numThisTime; --i >= 0;)
  15459. {
  15460. *left++ = ByteOrder::bigEndianShort (src) << 16;
  15461. src += 2;
  15462. *right++ = ByteOrder::bigEndianShort (src) << 16;
  15463. src += 2;
  15464. }
  15465. }
  15466. }
  15467. else
  15468. {
  15469. for (int i = numThisTime; --i >= 0;)
  15470. {
  15471. *left++ = ByteOrder::bigEndianShort (src) << 16;
  15472. src += 2;
  15473. }
  15474. }
  15475. }
  15476. }
  15477. else if (bitsPerSample == 24)
  15478. {
  15479. const char* src = (const char*)tempBuffer;
  15480. if (littleEndian)
  15481. {
  15482. if (numChannels > 1)
  15483. {
  15484. if (left == 0)
  15485. {
  15486. for (int i = numThisTime; --i >= 0;)
  15487. {
  15488. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  15489. src += 6;
  15490. }
  15491. }
  15492. else if (right == 0)
  15493. {
  15494. for (int i = numThisTime; --i >= 0;)
  15495. {
  15496. src += 3;
  15497. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  15498. src += 3;
  15499. }
  15500. }
  15501. else
  15502. {
  15503. for (int i = numThisTime; --i >= 0;)
  15504. {
  15505. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  15506. src += 3;
  15507. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  15508. src += 3;
  15509. }
  15510. }
  15511. }
  15512. else
  15513. {
  15514. for (int i = numThisTime; --i >= 0;)
  15515. {
  15516. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  15517. src += 3;
  15518. }
  15519. }
  15520. }
  15521. else
  15522. {
  15523. if (numChannels > 1)
  15524. {
  15525. if (left == 0)
  15526. {
  15527. for (int i = numThisTime; --i >= 0;)
  15528. {
  15529. *right++ = ByteOrder::bigEndian24Bit (src) << 8;
  15530. src += 6;
  15531. }
  15532. }
  15533. else if (right == 0)
  15534. {
  15535. for (int i = numThisTime; --i >= 0;)
  15536. {
  15537. src += 3;
  15538. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  15539. src += 3;
  15540. }
  15541. }
  15542. else
  15543. {
  15544. for (int i = numThisTime; --i >= 0;)
  15545. {
  15546. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  15547. src += 3;
  15548. *right++ = ByteOrder::bigEndian24Bit (src) << 8;
  15549. src += 3;
  15550. }
  15551. }
  15552. }
  15553. else
  15554. {
  15555. for (int i = numThisTime; --i >= 0;)
  15556. {
  15557. *left++ = ByteOrder::bigEndian24Bit (src) << 8;
  15558. src += 3;
  15559. }
  15560. }
  15561. }
  15562. }
  15563. else if (bitsPerSample == 32)
  15564. {
  15565. const unsigned int* src = reinterpret_cast <const unsigned int*> (tempBuffer);
  15566. unsigned int* l = reinterpret_cast <unsigned int*> (left);
  15567. unsigned int* r = reinterpret_cast <unsigned int*> (right);
  15568. if (littleEndian)
  15569. {
  15570. if (numChannels > 1)
  15571. {
  15572. if (l == 0)
  15573. {
  15574. for (int i = numThisTime; --i >= 0;)
  15575. {
  15576. ++src;
  15577. *r++ = ByteOrder::swapIfBigEndian (*src++);
  15578. }
  15579. }
  15580. else if (r == 0)
  15581. {
  15582. for (int i = numThisTime; --i >= 0;)
  15583. {
  15584. *l++ = ByteOrder::swapIfBigEndian (*src++);
  15585. ++src;
  15586. }
  15587. }
  15588. else
  15589. {
  15590. for (int i = numThisTime; --i >= 0;)
  15591. {
  15592. *l++ = ByteOrder::swapIfBigEndian (*src++);
  15593. *r++ = ByteOrder::swapIfBigEndian (*src++);
  15594. }
  15595. }
  15596. }
  15597. else
  15598. {
  15599. for (int i = numThisTime; --i >= 0;)
  15600. {
  15601. *l++ = ByteOrder::swapIfBigEndian (*src++);
  15602. }
  15603. }
  15604. }
  15605. else
  15606. {
  15607. if (numChannels > 1)
  15608. {
  15609. if (l == 0)
  15610. {
  15611. for (int i = numThisTime; --i >= 0;)
  15612. {
  15613. ++src;
  15614. *r++ = ByteOrder::swapIfLittleEndian (*src++);
  15615. }
  15616. }
  15617. else if (r == 0)
  15618. {
  15619. for (int i = numThisTime; --i >= 0;)
  15620. {
  15621. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  15622. ++src;
  15623. }
  15624. }
  15625. else
  15626. {
  15627. for (int i = numThisTime; --i >= 0;)
  15628. {
  15629. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  15630. *r++ = ByteOrder::swapIfLittleEndian (*src++);
  15631. }
  15632. }
  15633. }
  15634. else
  15635. {
  15636. for (int i = numThisTime; --i >= 0;)
  15637. {
  15638. *l++ = ByteOrder::swapIfLittleEndian (*src++);
  15639. }
  15640. }
  15641. }
  15642. left = reinterpret_cast <int*> (l);
  15643. right = reinterpret_cast <int*> (r);
  15644. }
  15645. else if (bitsPerSample == 8)
  15646. {
  15647. const char* src = tempBuffer;
  15648. if (numChannels > 1)
  15649. {
  15650. if (left == 0)
  15651. {
  15652. for (int i = numThisTime; --i >= 0;)
  15653. {
  15654. *right++ = ((int) *src++) << 24;
  15655. ++src;
  15656. }
  15657. }
  15658. else if (right == 0)
  15659. {
  15660. for (int i = numThisTime; --i >= 0;)
  15661. {
  15662. ++src;
  15663. *left++ = ((int) *src++) << 24;
  15664. }
  15665. }
  15666. else
  15667. {
  15668. for (int i = numThisTime; --i >= 0;)
  15669. {
  15670. *left++ = ((int) *src++) << 24;
  15671. *right++ = ((int) *src++) << 24;
  15672. }
  15673. }
  15674. }
  15675. else
  15676. {
  15677. for (int i = numThisTime; --i >= 0;)
  15678. {
  15679. *left++ = ((int) *src++) << 24;
  15680. }
  15681. }
  15682. }
  15683. startOffsetInDestBuffer += numThisTime;
  15684. numSamples -= numThisTime;
  15685. }
  15686. if (numSamples > 0)
  15687. {
  15688. for (int i = numDestChannels; --i >= 0;)
  15689. if (destSamples[i] != 0)
  15690. zeromem (destSamples[i] + startOffsetInDestBuffer,
  15691. sizeof (int) * numSamples);
  15692. }
  15693. return true;
  15694. }
  15695. juce_UseDebuggingNewOperator
  15696. private:
  15697. AiffAudioFormatReader (const AiffAudioFormatReader&);
  15698. AiffAudioFormatReader& operator= (const AiffAudioFormatReader&);
  15699. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  15700. };
  15701. class AiffAudioFormatWriter : public AudioFormatWriter
  15702. {
  15703. MemoryBlock tempBlock;
  15704. uint32 lengthInSamples, bytesWritten;
  15705. int64 headerPosition;
  15706. bool writeFailed;
  15707. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  15708. AiffAudioFormatWriter (const AiffAudioFormatWriter&);
  15709. AiffAudioFormatWriter& operator= (const AiffAudioFormatWriter&);
  15710. void writeHeader()
  15711. {
  15712. const bool couldSeekOk = output->setPosition (headerPosition);
  15713. (void) couldSeekOk;
  15714. // if this fails, you've given it an output stream that can't seek! It needs
  15715. // to be able to seek back to write the header
  15716. jassert (couldSeekOk);
  15717. const int headerLen = 54;
  15718. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  15719. audioBytes += (audioBytes & 1);
  15720. output->writeInt (chunkName ("FORM"));
  15721. output->writeIntBigEndian (headerLen + audioBytes - 8);
  15722. output->writeInt (chunkName ("AIFF"));
  15723. output->writeInt (chunkName ("COMM"));
  15724. output->writeIntBigEndian (18);
  15725. output->writeShortBigEndian ((short) numChannels);
  15726. output->writeIntBigEndian (lengthInSamples);
  15727. output->writeShortBigEndian ((short) bitsPerSample);
  15728. uint8 sampleRateBytes[10];
  15729. zeromem (sampleRateBytes, 10);
  15730. if (sampleRate <= 1)
  15731. {
  15732. sampleRateBytes[0] = 0x3f;
  15733. sampleRateBytes[1] = 0xff;
  15734. sampleRateBytes[2] = 0x80;
  15735. }
  15736. else
  15737. {
  15738. int mask = 0x40000000;
  15739. sampleRateBytes[0] = 0x40;
  15740. if (sampleRate >= mask)
  15741. {
  15742. jassertfalse;
  15743. sampleRateBytes[1] = 0x1d;
  15744. }
  15745. else
  15746. {
  15747. int n = (int) sampleRate;
  15748. int i;
  15749. for (i = 0; i <= 32 ; ++i)
  15750. {
  15751. if ((n & mask) != 0)
  15752. break;
  15753. mask >>= 1;
  15754. }
  15755. n = n << (i + 1);
  15756. sampleRateBytes[1] = (uint8) (29 - i);
  15757. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  15758. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  15759. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  15760. sampleRateBytes[5] = (uint8) (n & 0xff);
  15761. }
  15762. }
  15763. output->write (sampleRateBytes, 10);
  15764. output->writeInt (chunkName ("SSND"));
  15765. output->writeIntBigEndian (audioBytes + 8);
  15766. output->writeInt (0);
  15767. output->writeInt (0);
  15768. jassert (output->getPosition() == headerLen);
  15769. }
  15770. public:
  15771. AiffAudioFormatWriter (OutputStream* out,
  15772. const double sampleRate_,
  15773. const unsigned int chans,
  15774. const int bits)
  15775. : AudioFormatWriter (out,
  15776. TRANS (aiffFormatName),
  15777. sampleRate_,
  15778. chans,
  15779. bits),
  15780. lengthInSamples (0),
  15781. bytesWritten (0),
  15782. writeFailed (false)
  15783. {
  15784. headerPosition = out->getPosition();
  15785. writeHeader();
  15786. }
  15787. ~AiffAudioFormatWriter()
  15788. {
  15789. if ((bytesWritten & 1) != 0)
  15790. output->writeByte (0);
  15791. writeHeader();
  15792. }
  15793. bool write (const int** data, int numSamples)
  15794. {
  15795. if (writeFailed)
  15796. return false;
  15797. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  15798. tempBlock.ensureSize (bytes, false);
  15799. char* buffer = static_cast <char*> (tempBlock.getData());
  15800. const int* left = data[0];
  15801. const int* right = data[1];
  15802. if (right == 0)
  15803. right = left;
  15804. if (bitsPerSample == 16)
  15805. {
  15806. short* b = reinterpret_cast <short*> (buffer);
  15807. if (numChannels > 1)
  15808. {
  15809. for (int i = numSamples; --i >= 0;)
  15810. {
  15811. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*left++ >> 16));
  15812. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*right++ >> 16));
  15813. }
  15814. }
  15815. else
  15816. {
  15817. for (int i = numSamples; --i >= 0;)
  15818. {
  15819. *b++ = (short) ByteOrder::swapIfLittleEndian ((uint16) (*left++ >> 16));
  15820. }
  15821. }
  15822. }
  15823. else if (bitsPerSample == 24)
  15824. {
  15825. char* b = buffer;
  15826. if (numChannels > 1)
  15827. {
  15828. for (int i = numSamples; --i >= 0;)
  15829. {
  15830. ByteOrder::bigEndian24BitToChars (*left++ >> 8, b);
  15831. b += 3;
  15832. ByteOrder::bigEndian24BitToChars (*right++ >> 8, b);
  15833. b += 3;
  15834. }
  15835. }
  15836. else
  15837. {
  15838. for (int i = numSamples; --i >= 0;)
  15839. {
  15840. ByteOrder::bigEndian24BitToChars (*left++ >> 8, b);
  15841. b += 3;
  15842. }
  15843. }
  15844. }
  15845. else if (bitsPerSample == 32)
  15846. {
  15847. uint32* b = reinterpret_cast <uint32*> (buffer);
  15848. if (numChannels > 1)
  15849. {
  15850. for (int i = numSamples; --i >= 0;)
  15851. {
  15852. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *left++);
  15853. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *right++);
  15854. }
  15855. }
  15856. else
  15857. {
  15858. for (int i = numSamples; --i >= 0;)
  15859. {
  15860. *b++ = ByteOrder::swapIfLittleEndian ((uint32) *left++);
  15861. }
  15862. }
  15863. }
  15864. else if (bitsPerSample == 8)
  15865. {
  15866. char* b = buffer;
  15867. if (numChannels > 1)
  15868. {
  15869. for (int i = numSamples; --i >= 0;)
  15870. {
  15871. *b++ = (char) (*left++ >> 24);
  15872. *b++ = (char) (*right++ >> 24);
  15873. }
  15874. }
  15875. else
  15876. {
  15877. for (int i = numSamples; --i >= 0;)
  15878. {
  15879. *b++ = (char) (*left++ >> 24);
  15880. }
  15881. }
  15882. }
  15883. if (bytesWritten + bytes >= (uint32) 0xfff00000
  15884. || ! output->write (buffer, bytes))
  15885. {
  15886. // failed to write to disk, so let's try writing the header.
  15887. // If it's just run out of disk space, then if it does manage
  15888. // to write the header, we'll still have a useable file..
  15889. writeHeader();
  15890. writeFailed = true;
  15891. return false;
  15892. }
  15893. else
  15894. {
  15895. bytesWritten += bytes;
  15896. lengthInSamples += numSamples;
  15897. return true;
  15898. }
  15899. }
  15900. juce_UseDebuggingNewOperator
  15901. };
  15902. AiffAudioFormat::AiffAudioFormat()
  15903. : AudioFormat (TRANS (aiffFormatName), StringArray (aiffExtensions))
  15904. {
  15905. }
  15906. AiffAudioFormat::~AiffAudioFormat()
  15907. {
  15908. }
  15909. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  15910. {
  15911. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  15912. return Array <int> (rates);
  15913. }
  15914. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  15915. {
  15916. const int depths[] = { 8, 16, 24, 0 };
  15917. return Array <int> (depths);
  15918. }
  15919. bool AiffAudioFormat::canDoStereo()
  15920. {
  15921. return true;
  15922. }
  15923. bool AiffAudioFormat::canDoMono()
  15924. {
  15925. return true;
  15926. }
  15927. #if JUCE_MAC
  15928. bool AiffAudioFormat::canHandleFile (const File& f)
  15929. {
  15930. if (AudioFormat::canHandleFile (f))
  15931. return true;
  15932. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  15933. return type == 'AIFF' || type == 'AIFC'
  15934. || type == 'aiff' || type == 'aifc';
  15935. }
  15936. #endif
  15937. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream,
  15938. const bool deleteStreamIfOpeningFails)
  15939. {
  15940. ScopedPointer <AiffAudioFormatReader> w (new AiffAudioFormatReader (sourceStream));
  15941. if (w->sampleRate != 0)
  15942. return w.release();
  15943. if (! deleteStreamIfOpeningFails)
  15944. w->input = 0;
  15945. return 0;
  15946. }
  15947. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  15948. double sampleRate,
  15949. unsigned int chans,
  15950. int bitsPerSample,
  15951. const StringPairArray& /*metadataValues*/,
  15952. int /*qualityOptionIndex*/)
  15953. {
  15954. if (getPossibleBitDepths().contains (bitsPerSample))
  15955. {
  15956. return new AiffAudioFormatWriter (out,
  15957. sampleRate,
  15958. chans,
  15959. bitsPerSample);
  15960. }
  15961. return 0;
  15962. }
  15963. END_JUCE_NAMESPACE
  15964. /*** End of inlined file: juce_AiffAudioFormat.cpp ***/
  15965. /*** Start of inlined file: juce_AudioFormat.cpp ***/
  15966. BEGIN_JUCE_NAMESPACE
  15967. AudioFormatReader::AudioFormatReader (InputStream* const in,
  15968. const String& formatName_)
  15969. : sampleRate (0),
  15970. bitsPerSample (0),
  15971. lengthInSamples (0),
  15972. numChannels (0),
  15973. usesFloatingPointData (false),
  15974. input (in),
  15975. formatName (formatName_)
  15976. {
  15977. }
  15978. AudioFormatReader::~AudioFormatReader()
  15979. {
  15980. delete input;
  15981. }
  15982. bool AudioFormatReader::read (int** destSamples,
  15983. int numDestChannels,
  15984. int64 startSampleInSource,
  15985. int numSamplesToRead,
  15986. const bool fillLeftoverChannelsWithCopies)
  15987. {
  15988. jassert (numDestChannels > 0); // you have to actually give this some channels to work with!
  15989. int startOffsetInDestBuffer = 0;
  15990. if (startSampleInSource < 0)
  15991. {
  15992. const int silence = (int) jmin (-startSampleInSource, (int64) numSamplesToRead);
  15993. for (int i = numDestChannels; --i >= 0;)
  15994. if (destSamples[i] != 0)
  15995. zeromem (destSamples[i], sizeof (int) * silence);
  15996. startOffsetInDestBuffer += silence;
  15997. numSamplesToRead -= silence;
  15998. startSampleInSource = 0;
  15999. }
  16000. if (numSamplesToRead <= 0)
  16001. return true;
  16002. if (! readSamples (destSamples, jmin ((int) numChannels, numDestChannels), startOffsetInDestBuffer,
  16003. startSampleInSource, numSamplesToRead))
  16004. return false;
  16005. if (numDestChannels > (int) numChannels)
  16006. {
  16007. if (fillLeftoverChannelsWithCopies)
  16008. {
  16009. int* lastFullChannel = destSamples[0];
  16010. for (int i = numDestChannels; --i > 0;)
  16011. {
  16012. if (destSamples[i] != 0)
  16013. {
  16014. lastFullChannel = destSamples[i];
  16015. break;
  16016. }
  16017. }
  16018. if (lastFullChannel != 0)
  16019. for (int i = numChannels; i < numDestChannels; ++i)
  16020. if (destSamples[i] != 0)
  16021. memcpy (destSamples[i], lastFullChannel, sizeof (int) * numSamplesToRead);
  16022. }
  16023. else
  16024. {
  16025. for (int i = numChannels; i < numDestChannels; ++i)
  16026. if (destSamples[i] != 0)
  16027. zeromem (destSamples[i], sizeof (int) * numSamplesToRead);
  16028. }
  16029. }
  16030. return true;
  16031. }
  16032. static void findAudioBufferMaxMin (const float* const buffer, const int num, float& maxVal, float& minVal) throw()
  16033. {
  16034. float mn = buffer[0];
  16035. float mx = mn;
  16036. for (int i = 1; i < num; ++i)
  16037. {
  16038. const float s = buffer[i];
  16039. if (s > mx) mx = s;
  16040. if (s < mn) mn = s;
  16041. }
  16042. maxVal = mx;
  16043. minVal = mn;
  16044. }
  16045. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  16046. int64 numSamples,
  16047. float& lowestLeft, float& highestLeft,
  16048. float& lowestRight, float& highestRight)
  16049. {
  16050. if (numSamples <= 0)
  16051. {
  16052. lowestLeft = 0;
  16053. lowestRight = 0;
  16054. highestLeft = 0;
  16055. highestRight = 0;
  16056. return;
  16057. }
  16058. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  16059. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  16060. int* tempBuffer[3];
  16061. tempBuffer[0] = (int*) tempSpace.getData();
  16062. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  16063. tempBuffer[2] = 0;
  16064. if (usesFloatingPointData)
  16065. {
  16066. float lmin = 1.0e6f;
  16067. float lmax = -lmin;
  16068. float rmin = lmin;
  16069. float rmax = lmax;
  16070. while (numSamples > 0)
  16071. {
  16072. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  16073. read ((int**) tempBuffer, 2, startSampleInFile, numToDo, false);
  16074. numSamples -= numToDo;
  16075. startSampleInFile += numToDo;
  16076. float bufmin, bufmax;
  16077. findAudioBufferMaxMin ((float*) tempBuffer[0], numToDo, bufmax, bufmin);
  16078. lmin = jmin (lmin, bufmin);
  16079. lmax = jmax (lmax, bufmax);
  16080. if (numChannels > 1)
  16081. {
  16082. findAudioBufferMaxMin ((float*) tempBuffer[1], numToDo, bufmax, bufmin);
  16083. rmin = jmin (rmin, bufmin);
  16084. rmax = jmax (rmax, bufmax);
  16085. }
  16086. }
  16087. if (numChannels <= 1)
  16088. {
  16089. rmax = lmax;
  16090. rmin = lmin;
  16091. }
  16092. lowestLeft = lmin;
  16093. highestLeft = lmax;
  16094. lowestRight = rmin;
  16095. highestRight = rmax;
  16096. }
  16097. else
  16098. {
  16099. int lmax = std::numeric_limits<int>::min();
  16100. int lmin = std::numeric_limits<int>::max();
  16101. int rmax = std::numeric_limits<int>::min();
  16102. int rmin = std::numeric_limits<int>::max();
  16103. while (numSamples > 0)
  16104. {
  16105. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  16106. read ((int**) tempBuffer, 2, startSampleInFile, numToDo, false);
  16107. numSamples -= numToDo;
  16108. startSampleInFile += numToDo;
  16109. for (int j = numChannels; --j >= 0;)
  16110. {
  16111. int bufMax = std::numeric_limits<int>::min();
  16112. int bufMin = std::numeric_limits<int>::max();
  16113. const int* const b = tempBuffer[j];
  16114. for (int i = 0; i < numToDo; ++i)
  16115. {
  16116. const int samp = b[i];
  16117. if (samp < bufMin)
  16118. bufMin = samp;
  16119. if (samp > bufMax)
  16120. bufMax = samp;
  16121. }
  16122. if (j == 0)
  16123. {
  16124. lmax = jmax (lmax, bufMax);
  16125. lmin = jmin (lmin, bufMin);
  16126. }
  16127. else
  16128. {
  16129. rmax = jmax (rmax, bufMax);
  16130. rmin = jmin (rmin, bufMin);
  16131. }
  16132. }
  16133. }
  16134. if (numChannels <= 1)
  16135. {
  16136. rmax = lmax;
  16137. rmin = lmin;
  16138. }
  16139. lowestLeft = lmin / (float) std::numeric_limits<int>::max();
  16140. highestLeft = lmax / (float) std::numeric_limits<int>::max();
  16141. lowestRight = rmin / (float) std::numeric_limits<int>::max();
  16142. highestRight = rmax / (float) std::numeric_limits<int>::max();
  16143. }
  16144. }
  16145. int64 AudioFormatReader::searchForLevel (int64 startSample,
  16146. int64 numSamplesToSearch,
  16147. const double magnitudeRangeMinimum,
  16148. const double magnitudeRangeMaximum,
  16149. const int minimumConsecutiveSamples)
  16150. {
  16151. if (numSamplesToSearch == 0)
  16152. return -1;
  16153. const int bufferSize = 4096;
  16154. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  16155. int* tempBuffer[3];
  16156. tempBuffer[0] = (int*) tempSpace.getData();
  16157. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  16158. tempBuffer[2] = 0;
  16159. int consecutive = 0;
  16160. int64 firstMatchPos = -1;
  16161. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  16162. const double doubleMin = jlimit (0.0, (double) std::numeric_limits<int>::max(), magnitudeRangeMinimum * std::numeric_limits<int>::max());
  16163. const double doubleMax = jlimit (doubleMin, (double) std::numeric_limits<int>::max(), magnitudeRangeMaximum * std::numeric_limits<int>::max());
  16164. const int intMagnitudeRangeMinimum = roundToInt (doubleMin);
  16165. const int intMagnitudeRangeMaximum = roundToInt (doubleMax);
  16166. while (numSamplesToSearch != 0)
  16167. {
  16168. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  16169. int64 bufferStart = startSample;
  16170. if (numSamplesToSearch < 0)
  16171. bufferStart -= numThisTime;
  16172. if (bufferStart >= (int) lengthInSamples)
  16173. break;
  16174. read ((int**) tempBuffer, 2, bufferStart, numThisTime, false);
  16175. int num = numThisTime;
  16176. while (--num >= 0)
  16177. {
  16178. if (numSamplesToSearch < 0)
  16179. --startSample;
  16180. bool matches = false;
  16181. const int index = (int) (startSample - bufferStart);
  16182. if (usesFloatingPointData)
  16183. {
  16184. const float sample1 = std::abs (((float*) tempBuffer[0]) [index]);
  16185. if (sample1 >= magnitudeRangeMinimum
  16186. && sample1 <= magnitudeRangeMaximum)
  16187. {
  16188. matches = true;
  16189. }
  16190. else if (numChannels > 1)
  16191. {
  16192. const float sample2 = std::abs (((float*) tempBuffer[1]) [index]);
  16193. matches = (sample2 >= magnitudeRangeMinimum
  16194. && sample2 <= magnitudeRangeMaximum);
  16195. }
  16196. }
  16197. else
  16198. {
  16199. const int sample1 = abs (tempBuffer[0] [index]);
  16200. if (sample1 >= intMagnitudeRangeMinimum
  16201. && sample1 <= intMagnitudeRangeMaximum)
  16202. {
  16203. matches = true;
  16204. }
  16205. else if (numChannels > 1)
  16206. {
  16207. const int sample2 = abs (tempBuffer[1][index]);
  16208. matches = (sample2 >= intMagnitudeRangeMinimum
  16209. && sample2 <= intMagnitudeRangeMaximum);
  16210. }
  16211. }
  16212. if (matches)
  16213. {
  16214. if (firstMatchPos < 0)
  16215. firstMatchPos = startSample;
  16216. if (++consecutive >= minimumConsecutiveSamples)
  16217. {
  16218. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  16219. return -1;
  16220. return firstMatchPos;
  16221. }
  16222. }
  16223. else
  16224. {
  16225. consecutive = 0;
  16226. firstMatchPos = -1;
  16227. }
  16228. if (numSamplesToSearch > 0)
  16229. ++startSample;
  16230. }
  16231. if (numSamplesToSearch > 0)
  16232. numSamplesToSearch -= numThisTime;
  16233. else
  16234. numSamplesToSearch += numThisTime;
  16235. }
  16236. return -1;
  16237. }
  16238. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  16239. const String& formatName_,
  16240. const double rate,
  16241. const unsigned int numChannels_,
  16242. const unsigned int bitsPerSample_)
  16243. : sampleRate (rate),
  16244. numChannels (numChannels_),
  16245. bitsPerSample (bitsPerSample_),
  16246. usesFloatingPointData (false),
  16247. output (out),
  16248. formatName (formatName_)
  16249. {
  16250. }
  16251. AudioFormatWriter::~AudioFormatWriter()
  16252. {
  16253. delete output;
  16254. }
  16255. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  16256. int64 startSample,
  16257. int64 numSamplesToRead)
  16258. {
  16259. const int bufferSize = 16384;
  16260. AudioSampleBuffer tempBuffer (numChannels, bufferSize);
  16261. int* buffers [128];
  16262. zerostruct (buffers);
  16263. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  16264. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  16265. if (numSamplesToRead < 0)
  16266. numSamplesToRead = reader.lengthInSamples;
  16267. while (numSamplesToRead > 0)
  16268. {
  16269. const int numToDo = (int) jmin (numSamplesToRead, (int64) bufferSize);
  16270. if (! reader.read (buffers, numChannels, startSample, numToDo, false))
  16271. return false;
  16272. if (reader.usesFloatingPointData != isFloatingPoint())
  16273. {
  16274. int** bufferChan = buffers;
  16275. while (*bufferChan != 0)
  16276. {
  16277. int* b = *bufferChan++;
  16278. if (isFloatingPoint())
  16279. {
  16280. // int -> float
  16281. const double factor = 1.0 / std::numeric_limits<int>::max();
  16282. for (int i = 0; i < numToDo; ++i)
  16283. ((float*) b)[i] = (float) (factor * b[i]);
  16284. }
  16285. else
  16286. {
  16287. // float -> int
  16288. for (int i = 0; i < numToDo; ++i)
  16289. {
  16290. const double samp = *(const float*) b;
  16291. if (samp <= -1.0)
  16292. *b++ = std::numeric_limits<int>::min();
  16293. else if (samp >= 1.0)
  16294. *b++ = std::numeric_limits<int>::max();
  16295. else
  16296. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  16297. }
  16298. }
  16299. }
  16300. }
  16301. if (! write ((const int**) buffers, numToDo))
  16302. return false;
  16303. numSamplesToRead -= numToDo;
  16304. startSample += numToDo;
  16305. }
  16306. return true;
  16307. }
  16308. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source,
  16309. int numSamplesToRead,
  16310. const int samplesPerBlock)
  16311. {
  16312. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  16313. int* buffers [128];
  16314. zerostruct (buffers);
  16315. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  16316. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  16317. while (numSamplesToRead > 0)
  16318. {
  16319. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  16320. AudioSourceChannelInfo info;
  16321. info.buffer = &tempBuffer;
  16322. info.startSample = 0;
  16323. info.numSamples = numToDo;
  16324. info.clearActiveBufferRegion();
  16325. source.getNextAudioBlock (info);
  16326. if (! isFloatingPoint())
  16327. {
  16328. int** bufferChan = buffers;
  16329. while (*bufferChan != 0)
  16330. {
  16331. int* b = *bufferChan++;
  16332. // float -> int
  16333. for (int j = numToDo; --j >= 0;)
  16334. {
  16335. const double samp = *(const float*) b;
  16336. if (samp <= -1.0)
  16337. *b++ = std::numeric_limits<int>::min();
  16338. else if (samp >= 1.0)
  16339. *b++ = std::numeric_limits<int>::max();
  16340. else
  16341. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  16342. }
  16343. }
  16344. }
  16345. if (! write ((const int**) buffers, numToDo))
  16346. return false;
  16347. numSamplesToRead -= numToDo;
  16348. }
  16349. return true;
  16350. }
  16351. AudioFormat::AudioFormat (const String& name,
  16352. const StringArray& extensions)
  16353. : formatName (name),
  16354. fileExtensions (extensions)
  16355. {
  16356. }
  16357. AudioFormat::~AudioFormat()
  16358. {
  16359. }
  16360. const String& AudioFormat::getFormatName() const
  16361. {
  16362. return formatName;
  16363. }
  16364. const StringArray& AudioFormat::getFileExtensions() const
  16365. {
  16366. return fileExtensions;
  16367. }
  16368. bool AudioFormat::canHandleFile (const File& f)
  16369. {
  16370. for (int i = 0; i < fileExtensions.size(); ++i)
  16371. if (f.hasFileExtension (fileExtensions[i]))
  16372. return true;
  16373. return false;
  16374. }
  16375. bool AudioFormat::isCompressed()
  16376. {
  16377. return false;
  16378. }
  16379. const StringArray AudioFormat::getQualityOptions()
  16380. {
  16381. return StringArray();
  16382. }
  16383. END_JUCE_NAMESPACE
  16384. /*** End of inlined file: juce_AudioFormat.cpp ***/
  16385. /*** Start of inlined file: juce_AudioFormatManager.cpp ***/
  16386. BEGIN_JUCE_NAMESPACE
  16387. AudioFormatManager::AudioFormatManager()
  16388. : defaultFormatIndex (0)
  16389. {
  16390. }
  16391. AudioFormatManager::~AudioFormatManager()
  16392. {
  16393. clearFormats();
  16394. clearSingletonInstance();
  16395. }
  16396. juce_ImplementSingleton (AudioFormatManager);
  16397. void AudioFormatManager::registerFormat (AudioFormat* newFormat,
  16398. const bool makeThisTheDefaultFormat)
  16399. {
  16400. jassert (newFormat != 0);
  16401. if (newFormat != 0)
  16402. {
  16403. #if JUCE_DEBUG
  16404. for (int i = getNumKnownFormats(); --i >= 0;)
  16405. {
  16406. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  16407. {
  16408. jassertfalse; // trying to add the same format twice!
  16409. }
  16410. }
  16411. #endif
  16412. if (makeThisTheDefaultFormat)
  16413. defaultFormatIndex = getNumKnownFormats();
  16414. knownFormats.add (newFormat);
  16415. }
  16416. }
  16417. void AudioFormatManager::registerBasicFormats()
  16418. {
  16419. #if JUCE_MAC
  16420. registerFormat (new AiffAudioFormat(), true);
  16421. registerFormat (new WavAudioFormat(), false);
  16422. #else
  16423. registerFormat (new WavAudioFormat(), true);
  16424. registerFormat (new AiffAudioFormat(), false);
  16425. #endif
  16426. #if JUCE_USE_FLAC
  16427. registerFormat (new FlacAudioFormat(), false);
  16428. #endif
  16429. #if JUCE_USE_OGGVORBIS
  16430. registerFormat (new OggVorbisAudioFormat(), false);
  16431. #endif
  16432. }
  16433. void AudioFormatManager::clearFormats()
  16434. {
  16435. knownFormats.clear();
  16436. defaultFormatIndex = 0;
  16437. }
  16438. int AudioFormatManager::getNumKnownFormats() const
  16439. {
  16440. return knownFormats.size();
  16441. }
  16442. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  16443. {
  16444. return knownFormats [index];
  16445. }
  16446. AudioFormat* AudioFormatManager::getDefaultFormat() const
  16447. {
  16448. return getKnownFormat (defaultFormatIndex);
  16449. }
  16450. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  16451. {
  16452. String e (fileExtension);
  16453. if (! e.startsWithChar ('.'))
  16454. e = "." + e;
  16455. for (int i = 0; i < getNumKnownFormats(); ++i)
  16456. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  16457. return getKnownFormat(i);
  16458. return 0;
  16459. }
  16460. const String AudioFormatManager::getWildcardForAllFormats() const
  16461. {
  16462. StringArray allExtensions;
  16463. int i;
  16464. for (i = 0; i < getNumKnownFormats(); ++i)
  16465. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  16466. allExtensions.trim();
  16467. allExtensions.removeEmptyStrings();
  16468. String s;
  16469. for (i = 0; i < allExtensions.size(); ++i)
  16470. {
  16471. s << '*';
  16472. if (! allExtensions[i].startsWithChar ('.'))
  16473. s << '.';
  16474. s << allExtensions[i];
  16475. if (i < allExtensions.size() - 1)
  16476. s << ';';
  16477. }
  16478. return s;
  16479. }
  16480. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  16481. {
  16482. // you need to actually register some formats before the manager can
  16483. // use them to open a file!
  16484. jassert (getNumKnownFormats() > 0);
  16485. for (int i = 0; i < getNumKnownFormats(); ++i)
  16486. {
  16487. AudioFormat* const af = getKnownFormat(i);
  16488. if (af->canHandleFile (file))
  16489. {
  16490. InputStream* const in = file.createInputStream();
  16491. if (in != 0)
  16492. {
  16493. AudioFormatReader* const r = af->createReaderFor (in, true);
  16494. if (r != 0)
  16495. return r;
  16496. }
  16497. }
  16498. }
  16499. return 0;
  16500. }
  16501. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* audioFileStream)
  16502. {
  16503. // you need to actually register some formats before the manager can
  16504. // use them to open a file!
  16505. jassert (getNumKnownFormats() > 0);
  16506. ScopedPointer <InputStream> in (audioFileStream);
  16507. if (in != 0)
  16508. {
  16509. const int64 originalStreamPos = in->getPosition();
  16510. for (int i = 0; i < getNumKnownFormats(); ++i)
  16511. {
  16512. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  16513. if (r != 0)
  16514. {
  16515. in.release();
  16516. return r;
  16517. }
  16518. in->setPosition (originalStreamPos);
  16519. // the stream that is passed-in must be capable of being repositioned so
  16520. // that all the formats can have a go at opening it.
  16521. jassert (in->getPosition() == originalStreamPos);
  16522. }
  16523. }
  16524. return 0;
  16525. }
  16526. END_JUCE_NAMESPACE
  16527. /*** End of inlined file: juce_AudioFormatManager.cpp ***/
  16528. /*** Start of inlined file: juce_AudioSubsectionReader.cpp ***/
  16529. BEGIN_JUCE_NAMESPACE
  16530. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  16531. const int64 startSample_,
  16532. const int64 length_,
  16533. const bool deleteSourceWhenDeleted_)
  16534. : AudioFormatReader (0, source_->getFormatName()),
  16535. source (source_),
  16536. startSample (startSample_),
  16537. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  16538. {
  16539. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  16540. sampleRate = source->sampleRate;
  16541. bitsPerSample = source->bitsPerSample;
  16542. lengthInSamples = length;
  16543. numChannels = source->numChannels;
  16544. usesFloatingPointData = source->usesFloatingPointData;
  16545. }
  16546. AudioSubsectionReader::~AudioSubsectionReader()
  16547. {
  16548. if (deleteSourceWhenDeleted)
  16549. delete source;
  16550. }
  16551. bool AudioSubsectionReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16552. int64 startSampleInFile, int numSamples)
  16553. {
  16554. if (startSampleInFile + numSamples > length)
  16555. {
  16556. for (int i = numDestChannels; --i >= 0;)
  16557. if (destSamples[i] != 0)
  16558. zeromem (destSamples[i], sizeof (int) * numSamples);
  16559. numSamples = jmin (numSamples, (int) (length - startSampleInFile));
  16560. if (numSamples <= 0)
  16561. return true;
  16562. }
  16563. return source->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer,
  16564. startSampleInFile + startSample, numSamples);
  16565. }
  16566. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  16567. int64 numSamples,
  16568. float& lowestLeft,
  16569. float& highestLeft,
  16570. float& lowestRight,
  16571. float& highestRight)
  16572. {
  16573. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  16574. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  16575. source->readMaxLevels (startSampleInFile + startSample,
  16576. numSamples,
  16577. lowestLeft,
  16578. highestLeft,
  16579. lowestRight,
  16580. highestRight);
  16581. }
  16582. END_JUCE_NAMESPACE
  16583. /*** End of inlined file: juce_AudioSubsectionReader.cpp ***/
  16584. /*** Start of inlined file: juce_AudioThumbnail.cpp ***/
  16585. BEGIN_JUCE_NAMESPACE
  16586. const int timeBeforeDeletingReader = 2000;
  16587. struct AudioThumbnailDataFormat
  16588. {
  16589. char thumbnailMagic[4];
  16590. int samplesPerThumbSample;
  16591. int64 totalSamples; // source samples
  16592. int64 numFinishedSamples; // source samples
  16593. int numThumbnailSamples;
  16594. int numChannels;
  16595. int sampleRate;
  16596. char future[16];
  16597. char data[1];
  16598. void swapEndiannessIfNeeded() throw()
  16599. {
  16600. #if JUCE_BIG_ENDIAN
  16601. flip (samplesPerThumbSample);
  16602. flip (totalSamples);
  16603. flip (numFinishedSamples);
  16604. flip (numThumbnailSamples);
  16605. flip (numChannels);
  16606. flip (sampleRate);
  16607. #endif
  16608. }
  16609. private:
  16610. #if JUCE_BIG_ENDIAN
  16611. static void flip (int& n) { n = (int) ByteOrder::swap ((uint32) n); }
  16612. static void flip (int64& n) { n = (int64) ByteOrder::swap ((uint64) n); }
  16613. #endif
  16614. };
  16615. AudioThumbnail::AudioThumbnail (const int orginalSamplesPerThumbnailSample_,
  16616. AudioFormatManager& formatManagerToUse_,
  16617. AudioThumbnailCache& cacheToUse)
  16618. : formatManagerToUse (formatManagerToUse_),
  16619. cache (cacheToUse),
  16620. orginalSamplesPerThumbnailSample (orginalSamplesPerThumbnailSample_)
  16621. {
  16622. clear();
  16623. }
  16624. AudioThumbnail::~AudioThumbnail()
  16625. {
  16626. cache.removeThumbnail (this);
  16627. const ScopedLock sl (readerLock);
  16628. reader = 0;
  16629. }
  16630. void AudioThumbnail::setSource (InputSource* const newSource)
  16631. {
  16632. cache.removeThumbnail (this);
  16633. timerCallback(); // stops the timer and deletes the reader
  16634. source = newSource;
  16635. clear();
  16636. if (newSource != 0
  16637. && ! (cache.loadThumb (*this, newSource->hashCode())
  16638. && isFullyLoaded()))
  16639. {
  16640. {
  16641. const ScopedLock sl (readerLock);
  16642. reader = createReader();
  16643. }
  16644. if (reader != 0)
  16645. {
  16646. initialiseFromAudioFile (*reader);
  16647. cache.addThumbnail (this);
  16648. }
  16649. }
  16650. sendChangeMessage (this);
  16651. }
  16652. bool AudioThumbnail::useTimeSlice()
  16653. {
  16654. const ScopedLock sl (readerLock);
  16655. if (isFullyLoaded())
  16656. {
  16657. if (reader != 0)
  16658. startTimer (timeBeforeDeletingReader);
  16659. cache.removeThumbnail (this);
  16660. return false;
  16661. }
  16662. if (reader == 0)
  16663. reader = createReader();
  16664. if (reader != 0)
  16665. {
  16666. readNextBlockFromAudioFile (*reader);
  16667. stopTimer();
  16668. sendChangeMessage (this);
  16669. const bool justFinished = isFullyLoaded();
  16670. if (justFinished)
  16671. cache.storeThumb (*this, source->hashCode());
  16672. return ! justFinished;
  16673. }
  16674. return false;
  16675. }
  16676. AudioFormatReader* AudioThumbnail::createReader() const
  16677. {
  16678. if (source != 0)
  16679. {
  16680. InputStream* const audioFileStream = source->createInputStream();
  16681. if (audioFileStream != 0)
  16682. return formatManagerToUse.createReaderFor (audioFileStream);
  16683. }
  16684. return 0;
  16685. }
  16686. void AudioThumbnail::timerCallback()
  16687. {
  16688. stopTimer();
  16689. const ScopedLock sl (readerLock);
  16690. reader = 0;
  16691. }
  16692. void AudioThumbnail::clear()
  16693. {
  16694. data.setSize (sizeof (AudioThumbnailDataFormat) + 3);
  16695. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16696. d->thumbnailMagic[0] = 'j';
  16697. d->thumbnailMagic[1] = 'a';
  16698. d->thumbnailMagic[2] = 't';
  16699. d->thumbnailMagic[3] = 'm';
  16700. d->samplesPerThumbSample = orginalSamplesPerThumbnailSample;
  16701. d->totalSamples = 0;
  16702. d->numFinishedSamples = 0;
  16703. d->numThumbnailSamples = 0;
  16704. d->numChannels = 0;
  16705. d->sampleRate = 0;
  16706. numSamplesCached = 0;
  16707. cacheNeedsRefilling = true;
  16708. }
  16709. void AudioThumbnail::loadFrom (InputStream& input)
  16710. {
  16711. const ScopedLock sl (readerLock);
  16712. data.setSize (0);
  16713. input.readIntoMemoryBlock (data);
  16714. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16715. d->swapEndiannessIfNeeded();
  16716. if (! (d->thumbnailMagic[0] == 'j'
  16717. && d->thumbnailMagic[1] == 'a'
  16718. && d->thumbnailMagic[2] == 't'
  16719. && d->thumbnailMagic[3] == 'm'))
  16720. {
  16721. clear();
  16722. }
  16723. numSamplesCached = 0;
  16724. cacheNeedsRefilling = true;
  16725. }
  16726. void AudioThumbnail::saveTo (OutputStream& output) const
  16727. {
  16728. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16729. d->swapEndiannessIfNeeded();
  16730. output.write (data.getData(), (int) data.getSize());
  16731. d->swapEndiannessIfNeeded();
  16732. }
  16733. bool AudioThumbnail::initialiseFromAudioFile (AudioFormatReader& fileReader)
  16734. {
  16735. AudioThumbnailDataFormat* d = (AudioThumbnailDataFormat*) data.getData();
  16736. d->totalSamples = fileReader.lengthInSamples;
  16737. d->numChannels = jmin ((uint32) 2, fileReader.numChannels);
  16738. d->numFinishedSamples = 0;
  16739. d->sampleRate = roundToInt (fileReader.sampleRate);
  16740. d->numThumbnailSamples = (int) (d->totalSamples / d->samplesPerThumbSample) + 1;
  16741. data.setSize (sizeof (AudioThumbnailDataFormat) + 3 + d->numThumbnailSamples * d->numChannels * 2);
  16742. d = (AudioThumbnailDataFormat*) data.getData();
  16743. zeromem (&(d->data[0]), d->numThumbnailSamples * d->numChannels * 2);
  16744. return d->totalSamples > 0;
  16745. }
  16746. bool AudioThumbnail::readNextBlockFromAudioFile (AudioFormatReader& fileReader)
  16747. {
  16748. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16749. if (d->numFinishedSamples < d->totalSamples)
  16750. {
  16751. const int numToDo = (int) jmin ((int64) 65536, d->totalSamples - d->numFinishedSamples);
  16752. generateSection (fileReader,
  16753. d->numFinishedSamples,
  16754. numToDo);
  16755. d->numFinishedSamples += numToDo;
  16756. }
  16757. cacheNeedsRefilling = true;
  16758. return (d->numFinishedSamples < d->totalSamples);
  16759. }
  16760. int AudioThumbnail::getNumChannels() const throw()
  16761. {
  16762. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16763. jassert (d != 0);
  16764. return d->numChannels;
  16765. }
  16766. double AudioThumbnail::getTotalLength() const throw()
  16767. {
  16768. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16769. jassert (d != 0);
  16770. if (d->sampleRate > 0)
  16771. return d->totalSamples / (double)d->sampleRate;
  16772. else
  16773. return 0.0;
  16774. }
  16775. void AudioThumbnail::generateSection (AudioFormatReader& fileReader,
  16776. int64 startSample,
  16777. int numSamples)
  16778. {
  16779. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16780. jassert (d != 0);
  16781. int firstDataPos = (int) (startSample / d->samplesPerThumbSample);
  16782. int lastDataPos = (int) ((startSample + numSamples) / d->samplesPerThumbSample);
  16783. char* l = getChannelData (0);
  16784. char* r = getChannelData (1);
  16785. for (int i = firstDataPos; i < lastDataPos; ++i)
  16786. {
  16787. const int sourceStart = i * d->samplesPerThumbSample;
  16788. const int sourceEnd = sourceStart + d->samplesPerThumbSample;
  16789. float lowestLeft, highestLeft, lowestRight, highestRight;
  16790. fileReader.readMaxLevels (sourceStart,
  16791. sourceEnd - sourceStart,
  16792. lowestLeft,
  16793. highestLeft,
  16794. lowestRight,
  16795. highestRight);
  16796. int n = i * 2;
  16797. if (r != 0)
  16798. {
  16799. l [n] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  16800. r [n++] = (char) jlimit (-128.0f, 127.0f, lowestRight * 127.0f);
  16801. l [n] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  16802. r [n++] = (char) jlimit (-128.0f, 127.0f, highestRight * 127.0f);
  16803. }
  16804. else
  16805. {
  16806. l [n++] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  16807. l [n++] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  16808. }
  16809. }
  16810. }
  16811. char* AudioThumbnail::getChannelData (int channel) const
  16812. {
  16813. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16814. jassert (d != 0);
  16815. if (channel >= 0 && channel < d->numChannels)
  16816. return d->data + (channel * 2 * d->numThumbnailSamples);
  16817. return 0;
  16818. }
  16819. bool AudioThumbnail::isFullyLoaded() const throw()
  16820. {
  16821. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16822. jassert (d != 0);
  16823. return d->numFinishedSamples >= d->totalSamples;
  16824. }
  16825. void AudioThumbnail::refillCache (const int numSamples,
  16826. double startTime,
  16827. const double timePerPixel)
  16828. {
  16829. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16830. jassert (d != 0);
  16831. if (numSamples <= 0
  16832. || timePerPixel <= 0.0
  16833. || d->sampleRate <= 0)
  16834. {
  16835. numSamplesCached = 0;
  16836. cacheNeedsRefilling = true;
  16837. return;
  16838. }
  16839. if (numSamples == numSamplesCached
  16840. && numChannelsCached == d->numChannels
  16841. && startTime == cachedStart
  16842. && timePerPixel == cachedTimePerPixel
  16843. && ! cacheNeedsRefilling)
  16844. {
  16845. return;
  16846. }
  16847. numSamplesCached = numSamples;
  16848. numChannelsCached = d->numChannels;
  16849. cachedStart = startTime;
  16850. cachedTimePerPixel = timePerPixel;
  16851. cachedLevels.ensureSize (2 * numChannelsCached * numSamples);
  16852. const bool needExtraDetail = (timePerPixel * d->sampleRate <= d->samplesPerThumbSample);
  16853. const ScopedLock sl (readerLock);
  16854. cacheNeedsRefilling = false;
  16855. if (needExtraDetail && reader == 0)
  16856. reader = createReader();
  16857. if (reader != 0 && timePerPixel * d->sampleRate <= d->samplesPerThumbSample)
  16858. {
  16859. startTimer (timeBeforeDeletingReader);
  16860. char* cacheData = static_cast <char*> (cachedLevels.getData());
  16861. int sample = roundToInt (startTime * d->sampleRate);
  16862. for (int i = numSamples; --i >= 0;)
  16863. {
  16864. const int nextSample = roundToInt ((startTime + timePerPixel) * d->sampleRate);
  16865. if (sample >= 0)
  16866. {
  16867. if (sample >= reader->lengthInSamples)
  16868. break;
  16869. float lmin, lmax, rmin, rmax;
  16870. reader->readMaxLevels (sample,
  16871. jmax (1, nextSample - sample),
  16872. lmin, lmax, rmin, rmax);
  16873. cacheData[0] = (char) jlimit (-128, 127, roundFloatToInt (lmin * 127.0f));
  16874. cacheData[1] = (char) jlimit (-128, 127, roundFloatToInt (lmax * 127.0f));
  16875. if (numChannelsCached > 1)
  16876. {
  16877. cacheData[2] = (char) jlimit (-128, 127, roundFloatToInt (rmin * 127.0f));
  16878. cacheData[3] = (char) jlimit (-128, 127, roundFloatToInt (rmax * 127.0f));
  16879. }
  16880. cacheData += 2 * numChannelsCached;
  16881. }
  16882. startTime += timePerPixel;
  16883. sample = nextSample;
  16884. }
  16885. }
  16886. else
  16887. {
  16888. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  16889. {
  16890. char* const channelData = getChannelData (channelNum);
  16891. char* cacheData = static_cast <char*> (cachedLevels.getData()) + channelNum * 2;
  16892. const double timeToThumbSampleFactor = d->sampleRate / (double) d->samplesPerThumbSample;
  16893. startTime = cachedStart;
  16894. int sample = roundToInt (startTime * timeToThumbSampleFactor);
  16895. const int numFinished = (int) (d->numFinishedSamples / d->samplesPerThumbSample);
  16896. for (int i = numSamples; --i >= 0;)
  16897. {
  16898. const int nextSample = roundToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  16899. if (sample >= 0 && channelData != 0)
  16900. {
  16901. char mx = -128;
  16902. char mn = 127;
  16903. while (sample <= nextSample)
  16904. {
  16905. if (sample >= numFinished)
  16906. break;
  16907. const int n = sample << 1;
  16908. const char sampMin = channelData [n];
  16909. const char sampMax = channelData [n + 1];
  16910. if (sampMin < mn)
  16911. mn = sampMin;
  16912. if (sampMax > mx)
  16913. mx = sampMax;
  16914. ++sample;
  16915. }
  16916. if (mn <= mx)
  16917. {
  16918. cacheData[0] = mn;
  16919. cacheData[1] = mx;
  16920. }
  16921. else
  16922. {
  16923. cacheData[0] = 1;
  16924. cacheData[1] = 0;
  16925. }
  16926. }
  16927. else
  16928. {
  16929. cacheData[0] = 1;
  16930. cacheData[1] = 0;
  16931. }
  16932. cacheData += numChannelsCached * 2;
  16933. startTime += timePerPixel;
  16934. sample = nextSample;
  16935. }
  16936. }
  16937. }
  16938. }
  16939. void AudioThumbnail::drawChannel (Graphics& g,
  16940. int x, int y, int w, int h,
  16941. double startTime,
  16942. double endTime,
  16943. int channelNum,
  16944. const float verticalZoomFactor)
  16945. {
  16946. refillCache (w, startTime, (endTime - startTime) / w);
  16947. if (numSamplesCached >= w
  16948. && channelNum >= 0
  16949. && channelNum < numChannelsCached)
  16950. {
  16951. const float topY = (float) y;
  16952. const float bottomY = topY + h;
  16953. const float midY = topY + h * 0.5f;
  16954. const float vscale = verticalZoomFactor * h / 256.0f;
  16955. const Rectangle<int> clip (g.getClipBounds());
  16956. const int skipLeft = jlimit (0, w, clip.getX() - x);
  16957. w -= skipLeft;
  16958. x += skipLeft;
  16959. const char* cacheData = static_cast <const char*> (cachedLevels.getData())
  16960. + (channelNum << 1)
  16961. + skipLeft * (numChannelsCached << 1);
  16962. while (--w >= 0)
  16963. {
  16964. const char mn = cacheData[0];
  16965. const char mx = cacheData[1];
  16966. cacheData += numChannelsCached << 1;
  16967. if (mn <= mx) // if the wrong way round, signifies that the sample's not yet known
  16968. g.drawLine ((float) x, jmax (midY - mx * vscale - 0.3f, topY),
  16969. (float) x, jmin (midY - mn * vscale + 0.3f, bottomY));
  16970. ++x;
  16971. if (x >= clip.getRight())
  16972. break;
  16973. }
  16974. }
  16975. }
  16976. END_JUCE_NAMESPACE
  16977. /*** End of inlined file: juce_AudioThumbnail.cpp ***/
  16978. /*** Start of inlined file: juce_AudioThumbnailCache.cpp ***/
  16979. BEGIN_JUCE_NAMESPACE
  16980. struct ThumbnailCacheEntry
  16981. {
  16982. int64 hash;
  16983. uint32 lastUsed;
  16984. MemoryBlock data;
  16985. juce_UseDebuggingNewOperator
  16986. };
  16987. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  16988. : TimeSliceThread ("thumb cache"),
  16989. maxNumThumbsToStore (maxNumThumbsToStore_)
  16990. {
  16991. startThread (2);
  16992. }
  16993. AudioThumbnailCache::~AudioThumbnailCache()
  16994. {
  16995. }
  16996. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  16997. {
  16998. for (int i = thumbs.size(); --i >= 0;)
  16999. {
  17000. if (thumbs[i]->hash == hashCode)
  17001. {
  17002. MemoryInputStream in (thumbs[i]->data, false);
  17003. thumb.loadFrom (in);
  17004. thumbs[i]->lastUsed = Time::getMillisecondCounter();
  17005. return true;
  17006. }
  17007. }
  17008. return false;
  17009. }
  17010. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  17011. const int64 hashCode)
  17012. {
  17013. MemoryOutputStream out;
  17014. thumb.saveTo (out);
  17015. ThumbnailCacheEntry* te = 0;
  17016. for (int i = thumbs.size(); --i >= 0;)
  17017. {
  17018. if (thumbs[i]->hash == hashCode)
  17019. {
  17020. te = thumbs[i];
  17021. break;
  17022. }
  17023. }
  17024. if (te == 0)
  17025. {
  17026. te = new ThumbnailCacheEntry();
  17027. te->hash = hashCode;
  17028. if (thumbs.size() < maxNumThumbsToStore)
  17029. {
  17030. thumbs.add (te);
  17031. }
  17032. else
  17033. {
  17034. int oldest = 0;
  17035. unsigned int oldestTime = Time::getMillisecondCounter() + 1;
  17036. int i;
  17037. for (i = thumbs.size(); --i >= 0;)
  17038. if (thumbs[i]->lastUsed < oldestTime)
  17039. oldest = i;
  17040. thumbs.set (i, te);
  17041. }
  17042. }
  17043. te->lastUsed = Time::getMillisecondCounter();
  17044. te->data.setSize (0);
  17045. te->data.append (out.getData(), out.getDataSize());
  17046. }
  17047. void AudioThumbnailCache::clear()
  17048. {
  17049. thumbs.clear();
  17050. }
  17051. void AudioThumbnailCache::addThumbnail (AudioThumbnail* const thumb)
  17052. {
  17053. addTimeSliceClient (thumb);
  17054. }
  17055. void AudioThumbnailCache::removeThumbnail (AudioThumbnail* const thumb)
  17056. {
  17057. removeTimeSliceClient (thumb);
  17058. }
  17059. END_JUCE_NAMESPACE
  17060. /*** End of inlined file: juce_AudioThumbnailCache.cpp ***/
  17061. /*** Start of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  17062. #if JUCE_QUICKTIME && ! (JUCE_64BIT || JUCE_IPHONE)
  17063. #if ! JUCE_WINDOWS
  17064. #include <QuickTime/Movies.h>
  17065. #include <QuickTime/QTML.h>
  17066. #include <QuickTime/QuickTimeComponents.h>
  17067. #include <QuickTime/MediaHandlers.h>
  17068. #include <QuickTime/ImageCodec.h>
  17069. #else
  17070. #if JUCE_MSVC
  17071. #pragma warning (push)
  17072. #pragma warning (disable : 4100)
  17073. #endif
  17074. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  17075. add its header directory to your include path.
  17076. Alternatively, if you don't need any QuickTime services, just turn off the JUC_QUICKTIME
  17077. flag in juce_Config.h
  17078. */
  17079. #include <Movies.h>
  17080. #include <QTML.h>
  17081. #include <QuickTimeComponents.h>
  17082. #include <MediaHandlers.h>
  17083. #include <ImageCodec.h>
  17084. #if JUCE_MSVC
  17085. #pragma warning (pop)
  17086. #endif
  17087. #endif
  17088. BEGIN_JUCE_NAMESPACE
  17089. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  17090. static const char* const quickTimeFormatName = "QuickTime file";
  17091. static const char* const quickTimeExtensions[] = { ".mov", ".mp3", ".mp4", 0 };
  17092. class QTAudioReader : public AudioFormatReader
  17093. {
  17094. public:
  17095. QTAudioReader (InputStream* const input_, const int trackNum_)
  17096. : AudioFormatReader (input_, TRANS (quickTimeFormatName)),
  17097. ok (false),
  17098. movie (0),
  17099. trackNum (trackNum_),
  17100. lastSampleRead (0),
  17101. lastThreadId (0),
  17102. extractor (0),
  17103. dataHandle (0)
  17104. {
  17105. bufferList.calloc (256, 1);
  17106. #if JUCE_WINDOWS
  17107. if (InitializeQTML (0) != noErr)
  17108. return;
  17109. #endif
  17110. if (EnterMovies() != noErr)
  17111. return;
  17112. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  17113. if (! opened)
  17114. return;
  17115. {
  17116. const int numTracks = GetMovieTrackCount (movie);
  17117. int trackCount = 0;
  17118. for (int i = 1; i <= numTracks; ++i)
  17119. {
  17120. track = GetMovieIndTrack (movie, i);
  17121. media = GetTrackMedia (track);
  17122. OSType mediaType;
  17123. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  17124. if (mediaType == SoundMediaType
  17125. && trackCount++ == trackNum_)
  17126. {
  17127. ok = true;
  17128. break;
  17129. }
  17130. }
  17131. }
  17132. if (! ok)
  17133. return;
  17134. ok = false;
  17135. lengthInSamples = GetMediaDecodeDuration (media);
  17136. usesFloatingPointData = false;
  17137. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  17138. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  17139. / GetMediaTimeScale (media);
  17140. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  17141. unsigned long output_layout_size;
  17142. err = MovieAudioExtractionGetPropertyInfo (extractor,
  17143. kQTPropertyClass_MovieAudioExtraction_Audio,
  17144. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17145. 0, &output_layout_size, 0);
  17146. if (err != noErr)
  17147. return;
  17148. HeapBlock <AudioChannelLayout> qt_audio_channel_layout;
  17149. qt_audio_channel_layout.calloc (output_layout_size, 1);
  17150. err = MovieAudioExtractionGetProperty (extractor,
  17151. kQTPropertyClass_MovieAudioExtraction_Audio,
  17152. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17153. output_layout_size, qt_audio_channel_layout, 0);
  17154. qt_audio_channel_layout[0].mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  17155. err = MovieAudioExtractionSetProperty (extractor,
  17156. kQTPropertyClass_MovieAudioExtraction_Audio,
  17157. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17158. output_layout_size,
  17159. qt_audio_channel_layout);
  17160. err = MovieAudioExtractionGetProperty (extractor,
  17161. kQTPropertyClass_MovieAudioExtraction_Audio,
  17162. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  17163. sizeof (inputStreamDesc),
  17164. &inputStreamDesc, 0);
  17165. if (err != noErr)
  17166. return;
  17167. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  17168. | kAudioFormatFlagIsPacked
  17169. | kAudioFormatFlagsNativeEndian;
  17170. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  17171. inputStreamDesc.mChannelsPerFrame = jmin ((UInt32) 2, inputStreamDesc.mChannelsPerFrame);
  17172. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  17173. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  17174. err = MovieAudioExtractionSetProperty (extractor,
  17175. kQTPropertyClass_MovieAudioExtraction_Audio,
  17176. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  17177. sizeof (inputStreamDesc),
  17178. &inputStreamDesc);
  17179. if (err != noErr)
  17180. return;
  17181. Boolean allChannelsDiscrete = false;
  17182. err = MovieAudioExtractionSetProperty (extractor,
  17183. kQTPropertyClass_MovieAudioExtraction_Movie,
  17184. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  17185. sizeof (allChannelsDiscrete),
  17186. &allChannelsDiscrete);
  17187. if (err != noErr)
  17188. return;
  17189. bufferList->mNumberBuffers = 1;
  17190. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  17191. bufferList->mBuffers[0].mDataByteSize = (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16;
  17192. dataBuffer.malloc (bufferList->mBuffers[0].mDataByteSize);
  17193. bufferList->mBuffers[0].mData = dataBuffer;
  17194. sampleRate = inputStreamDesc.mSampleRate;
  17195. bitsPerSample = 16;
  17196. numChannels = inputStreamDesc.mChannelsPerFrame;
  17197. detachThread();
  17198. ok = true;
  17199. }
  17200. ~QTAudioReader()
  17201. {
  17202. if (dataHandle != 0)
  17203. DisposeHandle (dataHandle);
  17204. if (extractor != 0)
  17205. {
  17206. MovieAudioExtractionEnd (extractor);
  17207. extractor = 0;
  17208. }
  17209. checkThreadIsAttached();
  17210. DisposeMovie (movie);
  17211. #if JUCE_MAC
  17212. ExitMoviesOnThread ();
  17213. #endif
  17214. }
  17215. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17216. int64 startSampleInFile, int numSamples)
  17217. {
  17218. checkThreadIsAttached();
  17219. while (numSamples > 0)
  17220. {
  17221. if (! loadFrame ((int) startSampleInFile))
  17222. return false;
  17223. const int numToDo = jmin (numSamples, samplesPerFrame);
  17224. for (int j = numDestChannels; --j >= 0;)
  17225. {
  17226. if (destSamples[j] != 0)
  17227. {
  17228. const short* const src = ((const short*) bufferList->mBuffers[0].mData) + j;
  17229. for (int i = 0; i < numToDo; ++i)
  17230. destSamples[j][startOffsetInDestBuffer + i] = src [i << 1] << 16;
  17231. }
  17232. }
  17233. startOffsetInDestBuffer += numToDo;
  17234. startSampleInFile += numToDo;
  17235. numSamples -= numToDo;
  17236. }
  17237. detachThread();
  17238. return true;
  17239. }
  17240. bool loadFrame (const int sampleNum)
  17241. {
  17242. if (lastSampleRead != sampleNum)
  17243. {
  17244. TimeRecord time;
  17245. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  17246. time.base = 0;
  17247. time.value.hi = 0;
  17248. time.value.lo = (UInt32) sampleNum;
  17249. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  17250. kQTPropertyClass_MovieAudioExtraction_Movie,
  17251. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  17252. sizeof (time), &time);
  17253. if (err != noErr)
  17254. return false;
  17255. }
  17256. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * samplesPerFrame;
  17257. UInt32 outFlags = 0;
  17258. UInt32 actualNumSamples = samplesPerFrame;
  17259. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumSamples,
  17260. bufferList, &outFlags);
  17261. lastSampleRead = sampleNum + samplesPerFrame;
  17262. return err == noErr;
  17263. }
  17264. juce_UseDebuggingNewOperator
  17265. bool ok;
  17266. private:
  17267. Movie movie;
  17268. Media media;
  17269. Track track;
  17270. const int trackNum;
  17271. double trackUnitsPerFrame;
  17272. int samplesPerFrame;
  17273. int lastSampleRead;
  17274. Thread::ThreadID lastThreadId;
  17275. MovieAudioExtractionRef extractor;
  17276. AudioStreamBasicDescription inputStreamDesc;
  17277. HeapBlock <AudioBufferList> bufferList;
  17278. HeapBlock <char> dataBuffer;
  17279. Handle dataHandle;
  17280. void checkThreadIsAttached()
  17281. {
  17282. #if JUCE_MAC
  17283. if (Thread::getCurrentThreadId() != lastThreadId)
  17284. EnterMoviesOnThread (0);
  17285. AttachMovieToCurrentThread (movie);
  17286. #endif
  17287. }
  17288. void detachThread()
  17289. {
  17290. #if JUCE_MAC
  17291. DetachMovieFromCurrentThread (movie);
  17292. #endif
  17293. }
  17294. QTAudioReader (const QTAudioReader&);
  17295. QTAudioReader& operator= (const QTAudioReader&);
  17296. };
  17297. QuickTimeAudioFormat::QuickTimeAudioFormat()
  17298. : AudioFormat (TRANS (quickTimeFormatName), StringArray (quickTimeExtensions))
  17299. {
  17300. }
  17301. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  17302. {
  17303. }
  17304. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates()
  17305. {
  17306. return Array<int>();
  17307. }
  17308. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths()
  17309. {
  17310. return Array<int>();
  17311. }
  17312. bool QuickTimeAudioFormat::canDoStereo()
  17313. {
  17314. return true;
  17315. }
  17316. bool QuickTimeAudioFormat::canDoMono()
  17317. {
  17318. return true;
  17319. }
  17320. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  17321. const bool deleteStreamIfOpeningFails)
  17322. {
  17323. ScopedPointer <QTAudioReader> r (new QTAudioReader (sourceStream, 0));
  17324. if (r->ok)
  17325. return r.release();
  17326. if (! deleteStreamIfOpeningFails)
  17327. r->input = 0;
  17328. return 0;
  17329. }
  17330. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  17331. double /*sampleRateToUse*/,
  17332. unsigned int /*numberOfChannels*/,
  17333. int /*bitsPerSample*/,
  17334. const StringPairArray& /*metadataValues*/,
  17335. int /*qualityOptionIndex*/)
  17336. {
  17337. jassertfalse; // not yet implemented!
  17338. return 0;
  17339. }
  17340. END_JUCE_NAMESPACE
  17341. #endif
  17342. /*** End of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  17343. /*** Start of inlined file: juce_WavAudioFormat.cpp ***/
  17344. BEGIN_JUCE_NAMESPACE
  17345. static const char* const wavFormatName = "WAV file";
  17346. static const char* const wavExtensions[] = { ".wav", ".bwf", 0 };
  17347. const char* const WavAudioFormat::bwavDescription = "bwav description";
  17348. const char* const WavAudioFormat::bwavOriginator = "bwav originator";
  17349. const char* const WavAudioFormat::bwavOriginatorRef = "bwav originator ref";
  17350. const char* const WavAudioFormat::bwavOriginationDate = "bwav origination date";
  17351. const char* const WavAudioFormat::bwavOriginationTime = "bwav origination time";
  17352. const char* const WavAudioFormat::bwavTimeReference = "bwav time reference";
  17353. const char* const WavAudioFormat::bwavCodingHistory = "bwav coding history";
  17354. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  17355. const String& originator,
  17356. const String& originatorRef,
  17357. const Time& date,
  17358. const int64 timeReferenceSamples,
  17359. const String& codingHistory)
  17360. {
  17361. StringPairArray m;
  17362. m.set (bwavDescription, description);
  17363. m.set (bwavOriginator, originator);
  17364. m.set (bwavOriginatorRef, originatorRef);
  17365. m.set (bwavOriginationDate, date.formatted ("%Y-%m-%d"));
  17366. m.set (bwavOriginationTime, date.formatted ("%H:%M:%S"));
  17367. m.set (bwavTimeReference, String (timeReferenceSamples));
  17368. m.set (bwavCodingHistory, codingHistory);
  17369. return m;
  17370. }
  17371. #if JUCE_MSVC
  17372. #pragma pack (push, 1)
  17373. #define PACKED
  17374. #elif JUCE_GCC
  17375. #define PACKED __attribute__((packed))
  17376. #else
  17377. #define PACKED
  17378. #endif
  17379. struct BWAVChunk
  17380. {
  17381. char description [256];
  17382. char originator [32];
  17383. char originatorRef [32];
  17384. char originationDate [10];
  17385. char originationTime [8];
  17386. uint32 timeRefLow;
  17387. uint32 timeRefHigh;
  17388. uint16 version;
  17389. uint8 umid[64];
  17390. uint8 reserved[190];
  17391. char codingHistory[1];
  17392. void copyTo (StringPairArray& values) const
  17393. {
  17394. values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, 256));
  17395. values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, 32));
  17396. values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, 32));
  17397. values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, 10));
  17398. values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, 8));
  17399. const uint32 timeLow = ByteOrder::swapIfBigEndian (timeRefLow);
  17400. const uint32 timeHigh = ByteOrder::swapIfBigEndian (timeRefHigh);
  17401. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  17402. values.set (WavAudioFormat::bwavTimeReference, String (time));
  17403. values.set (WavAudioFormat::bwavCodingHistory, String::fromUTF8 (codingHistory));
  17404. }
  17405. static MemoryBlock createFrom (const StringPairArray& values)
  17406. {
  17407. const size_t sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].getNumBytesAsUTF8();
  17408. MemoryBlock data ((sizeNeeded + 3) & ~3);
  17409. data.fillWith (0);
  17410. BWAVChunk* b = (BWAVChunk*) data.getData();
  17411. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  17412. // as they get called in the right order..
  17413. values [WavAudioFormat::bwavDescription].copyToUTF8 (b->description, 257);
  17414. values [WavAudioFormat::bwavOriginator].copyToUTF8 (b->originator, 33);
  17415. values [WavAudioFormat::bwavOriginatorRef].copyToUTF8 (b->originatorRef, 33);
  17416. values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
  17417. values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
  17418. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  17419. b->timeRefLow = ByteOrder::swapIfBigEndian ((uint32) (time & 0xffffffff));
  17420. b->timeRefHigh = ByteOrder::swapIfBigEndian ((uint32) (time >> 32));
  17421. values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory, 0x7fffffff);
  17422. if (b->description[0] != 0
  17423. || b->originator[0] != 0
  17424. || b->originationDate[0] != 0
  17425. || b->originationTime[0] != 0
  17426. || b->codingHistory[0] != 0
  17427. || time != 0)
  17428. {
  17429. return data;
  17430. }
  17431. return MemoryBlock();
  17432. }
  17433. } PACKED;
  17434. struct SMPLChunk
  17435. {
  17436. struct SampleLoop
  17437. {
  17438. uint32 identifier;
  17439. uint32 type;
  17440. uint32 start;
  17441. uint32 end;
  17442. uint32 fraction;
  17443. uint32 playCount;
  17444. } PACKED;
  17445. uint32 manufacturer;
  17446. uint32 product;
  17447. uint32 samplePeriod;
  17448. uint32 midiUnityNote;
  17449. uint32 midiPitchFraction;
  17450. uint32 smpteFormat;
  17451. uint32 smpteOffset;
  17452. uint32 numSampleLoops;
  17453. uint32 samplerData;
  17454. SampleLoop loops[1];
  17455. void copyTo (StringPairArray& values, const int totalSize) const
  17456. {
  17457. values.set ("Manufacturer", String (ByteOrder::swapIfBigEndian (manufacturer)));
  17458. values.set ("Product", String (ByteOrder::swapIfBigEndian (product)));
  17459. values.set ("SamplePeriod", String (ByteOrder::swapIfBigEndian (samplePeriod)));
  17460. values.set ("MidiUnityNote", String (ByteOrder::swapIfBigEndian (midiUnityNote)));
  17461. values.set ("MidiPitchFraction", String (ByteOrder::swapIfBigEndian (midiPitchFraction)));
  17462. values.set ("SmpteFormat", String (ByteOrder::swapIfBigEndian (smpteFormat)));
  17463. values.set ("SmpteOffset", String (ByteOrder::swapIfBigEndian (smpteOffset)));
  17464. values.set ("NumSampleLoops", String (ByteOrder::swapIfBigEndian (numSampleLoops)));
  17465. values.set ("SamplerData", String (ByteOrder::swapIfBigEndian (samplerData)));
  17466. for (uint32 i = 0; i < numSampleLoops; ++i)
  17467. {
  17468. if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
  17469. break;
  17470. const String prefix ("Loop" + String(i));
  17471. values.set (prefix + "Identifier", String (ByteOrder::swapIfBigEndian (loops[i].identifier)));
  17472. values.set (prefix + "Type", String (ByteOrder::swapIfBigEndian (loops[i].type)));
  17473. values.set (prefix + "Start", String (ByteOrder::swapIfBigEndian (loops[i].start)));
  17474. values.set (prefix + "End", String (ByteOrder::swapIfBigEndian (loops[i].end)));
  17475. values.set (prefix + "Fraction", String (ByteOrder::swapIfBigEndian (loops[i].fraction)));
  17476. values.set (prefix + "PlayCount", String (ByteOrder::swapIfBigEndian (loops[i].playCount)));
  17477. }
  17478. }
  17479. static MemoryBlock createFrom (const StringPairArray& values)
  17480. {
  17481. const int numLoops = jmin (64, values.getValue ("NumSampleLoops", "0").getIntValue());
  17482. if (numLoops <= 0)
  17483. return MemoryBlock();
  17484. const size_t sizeNeeded = sizeof (SMPLChunk) + (numLoops - 1) * sizeof (SampleLoop);
  17485. MemoryBlock data ((sizeNeeded + 3) & ~3);
  17486. data.fillWith (0);
  17487. SMPLChunk* s = (SMPLChunk*) data.getData();
  17488. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  17489. // as they get called in the right order..
  17490. s->manufacturer = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Manufacturer", "0").getIntValue());
  17491. s->product = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Product", "0").getIntValue());
  17492. s->samplePeriod = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplePeriod", "0").getIntValue());
  17493. s->midiUnityNote = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiUnityNote", "60").getIntValue());
  17494. s->midiPitchFraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiPitchFraction", "0").getIntValue());
  17495. s->smpteFormat = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteFormat", "0").getIntValue());
  17496. s->smpteOffset = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteOffset", "0").getIntValue());
  17497. s->numSampleLoops = ByteOrder::swapIfBigEndian ((uint32) numLoops);
  17498. s->samplerData = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplerData", "0").getIntValue());
  17499. for (int i = 0; i < numLoops; ++i)
  17500. {
  17501. const String prefix ("Loop" + String(i));
  17502. s->loops[i].identifier = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Identifier", "0").getIntValue());
  17503. s->loops[i].type = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Type", "0").getIntValue());
  17504. s->loops[i].start = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Start", "0").getIntValue());
  17505. s->loops[i].end = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "End", "0").getIntValue());
  17506. s->loops[i].fraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Fraction", "0").getIntValue());
  17507. s->loops[i].playCount = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "PlayCount", "0").getIntValue());
  17508. }
  17509. return data;
  17510. }
  17511. } PACKED;
  17512. struct ExtensibleWavSubFormat
  17513. {
  17514. uint32 data1;
  17515. uint16 data2;
  17516. uint16 data3;
  17517. uint8 data4[8];
  17518. } PACKED;
  17519. #if JUCE_MSVC
  17520. #pragma pack (pop)
  17521. #endif
  17522. #undef PACKED
  17523. class WavAudioFormatReader : public AudioFormatReader
  17524. {
  17525. int bytesPerFrame;
  17526. int64 dataChunkStart, dataLength;
  17527. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  17528. WavAudioFormatReader (const WavAudioFormatReader&);
  17529. WavAudioFormatReader& operator= (const WavAudioFormatReader&);
  17530. public:
  17531. int64 bwavChunkStart, bwavSize;
  17532. WavAudioFormatReader (InputStream* const in)
  17533. : AudioFormatReader (in, TRANS (wavFormatName)),
  17534. dataLength (0),
  17535. bwavChunkStart (0),
  17536. bwavSize (0)
  17537. {
  17538. if (input->readInt() == chunkName ("RIFF"))
  17539. {
  17540. const uint32 len = (uint32) input->readInt();
  17541. const int64 end = input->getPosition() + len;
  17542. bool hasGotType = false;
  17543. bool hasGotData = false;
  17544. if (input->readInt() == chunkName ("WAVE"))
  17545. {
  17546. while (input->getPosition() < end
  17547. && ! input->isExhausted())
  17548. {
  17549. const int chunkType = input->readInt();
  17550. uint32 length = (uint32) input->readInt();
  17551. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  17552. if (chunkType == chunkName ("fmt "))
  17553. {
  17554. // read the format chunk
  17555. const unsigned short format = input->readShort();
  17556. const short numChans = input->readShort();
  17557. sampleRate = input->readInt();
  17558. const int bytesPerSec = input->readInt();
  17559. numChannels = numChans;
  17560. bytesPerFrame = bytesPerSec / (int)sampleRate;
  17561. bitsPerSample = 8 * bytesPerFrame / numChans;
  17562. if (format == 3)
  17563. {
  17564. usesFloatingPointData = true;
  17565. }
  17566. else if (format == 0xfffe /*WAVE_FORMAT_EXTENSIBLE*/)
  17567. {
  17568. if (length < 40) // too short
  17569. {
  17570. bytesPerFrame = 0;
  17571. }
  17572. else
  17573. {
  17574. input->skipNextBytes (12); // skip over blockAlign, bitsPerSample and speakerPosition mask
  17575. ExtensibleWavSubFormat subFormat;
  17576. subFormat.data1 = input->readInt();
  17577. subFormat.data2 = input->readShort();
  17578. subFormat.data3 = input->readShort();
  17579. input->read (subFormat.data4, sizeof (subFormat.data4));
  17580. const ExtensibleWavSubFormat pcmFormat
  17581. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  17582. if (memcmp (&subFormat, &pcmFormat, sizeof (subFormat)) != 0)
  17583. {
  17584. const ExtensibleWavSubFormat ambisonicFormat
  17585. = { 0x00000001, 0x0721, 0x11d3, { 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00 } };
  17586. if (memcmp (&subFormat, &ambisonicFormat, sizeof (subFormat)) != 0)
  17587. bytesPerFrame = 0;
  17588. }
  17589. }
  17590. }
  17591. else if (format != 1)
  17592. {
  17593. bytesPerFrame = 0;
  17594. }
  17595. hasGotType = true;
  17596. }
  17597. else if (chunkType == chunkName ("data"))
  17598. {
  17599. // get the data chunk's position
  17600. dataLength = length;
  17601. dataChunkStart = input->getPosition();
  17602. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  17603. hasGotData = true;
  17604. }
  17605. else if (chunkType == chunkName ("bext"))
  17606. {
  17607. bwavChunkStart = input->getPosition();
  17608. bwavSize = length;
  17609. // Broadcast-wav extension chunk..
  17610. HeapBlock <BWAVChunk> bwav;
  17611. bwav.calloc (jmax ((size_t) length + 1, sizeof (BWAVChunk)), 1);
  17612. input->read (bwav, length);
  17613. bwav->copyTo (metadataValues);
  17614. }
  17615. else if (chunkType == chunkName ("smpl"))
  17616. {
  17617. HeapBlock <SMPLChunk> smpl;
  17618. smpl.calloc (jmax ((size_t) length + 1, sizeof (SMPLChunk)), 1);
  17619. input->read (smpl, length);
  17620. smpl->copyTo (metadataValues, length);
  17621. }
  17622. else if (chunkEnd <= input->getPosition())
  17623. {
  17624. break;
  17625. }
  17626. input->setPosition (chunkEnd);
  17627. }
  17628. }
  17629. }
  17630. }
  17631. ~WavAudioFormatReader()
  17632. {
  17633. }
  17634. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17635. int64 startSampleInFile, int numSamples)
  17636. {
  17637. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  17638. if (samplesAvailable < numSamples)
  17639. {
  17640. for (int i = numDestChannels; --i >= 0;)
  17641. if (destSamples[i] != 0)
  17642. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  17643. numSamples = (int) samplesAvailable;
  17644. }
  17645. if (numSamples <= 0)
  17646. return true;
  17647. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  17648. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  17649. char tempBuffer [tempBufSize];
  17650. while (numSamples > 0)
  17651. {
  17652. int* left = destSamples[0];
  17653. if (left != 0)
  17654. left += startOffsetInDestBuffer;
  17655. int* right = numDestChannels > 1 ? destSamples[1] : 0;
  17656. if (right != 0)
  17657. right += startOffsetInDestBuffer;
  17658. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  17659. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  17660. if (bytesRead < numThisTime * bytesPerFrame)
  17661. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  17662. if (bitsPerSample == 16)
  17663. {
  17664. const short* src = reinterpret_cast <const short*> (tempBuffer);
  17665. if (numChannels > 1)
  17666. {
  17667. if (left == 0)
  17668. {
  17669. for (int i = numThisTime; --i >= 0;)
  17670. {
  17671. ++src;
  17672. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17673. }
  17674. }
  17675. else if (right == 0)
  17676. {
  17677. for (int i = numThisTime; --i >= 0;)
  17678. {
  17679. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17680. ++src;
  17681. }
  17682. }
  17683. else
  17684. {
  17685. for (int i = numThisTime; --i >= 0;)
  17686. {
  17687. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17688. *right++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17689. }
  17690. }
  17691. }
  17692. else
  17693. {
  17694. for (int i = numThisTime; --i >= 0;)
  17695. {
  17696. *left++ = (int) ByteOrder::swapIfBigEndian ((unsigned short) *src++) << 16;
  17697. }
  17698. }
  17699. }
  17700. else if (bitsPerSample == 24)
  17701. {
  17702. const char* src = tempBuffer;
  17703. if (numChannels > 1)
  17704. {
  17705. if (left == 0)
  17706. {
  17707. for (int i = numThisTime; --i >= 0;)
  17708. {
  17709. src += 3;
  17710. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  17711. src += 3;
  17712. }
  17713. }
  17714. else if (right == 0)
  17715. {
  17716. for (int i = numThisTime; --i >= 0;)
  17717. {
  17718. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  17719. src += 6;
  17720. }
  17721. }
  17722. else
  17723. {
  17724. for (int i = 0; i < numThisTime; ++i)
  17725. {
  17726. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  17727. src += 3;
  17728. *right++ = ByteOrder::littleEndian24Bit (src) << 8;
  17729. src += 3;
  17730. }
  17731. }
  17732. }
  17733. else
  17734. {
  17735. for (int i = 0; i < numThisTime; ++i)
  17736. {
  17737. *left++ = ByteOrder::littleEndian24Bit (src) << 8;
  17738. src += 3;
  17739. }
  17740. }
  17741. }
  17742. else if (bitsPerSample == 32)
  17743. {
  17744. const unsigned int* src = (const unsigned int*) tempBuffer;
  17745. unsigned int* l = (unsigned int*) left;
  17746. unsigned int* r = (unsigned int*) right;
  17747. if (numChannels > 1)
  17748. {
  17749. if (l == 0)
  17750. {
  17751. for (int i = numThisTime; --i >= 0;)
  17752. {
  17753. ++src;
  17754. *r++ = ByteOrder::swapIfBigEndian (*src++);
  17755. }
  17756. }
  17757. else if (r == 0)
  17758. {
  17759. for (int i = numThisTime; --i >= 0;)
  17760. {
  17761. *l++ = ByteOrder::swapIfBigEndian (*src++);
  17762. ++src;
  17763. }
  17764. }
  17765. else
  17766. {
  17767. for (int i = numThisTime; --i >= 0;)
  17768. {
  17769. *l++ = ByteOrder::swapIfBigEndian (*src++);
  17770. *r++ = ByteOrder::swapIfBigEndian (*src++);
  17771. }
  17772. }
  17773. }
  17774. else
  17775. {
  17776. for (int i = numThisTime; --i >= 0;)
  17777. {
  17778. *l++ = ByteOrder::swapIfBigEndian (*src++);
  17779. }
  17780. }
  17781. left = (int*)l;
  17782. right = (int*)r;
  17783. }
  17784. else if (bitsPerSample == 8)
  17785. {
  17786. const unsigned char* src = (const unsigned char*) tempBuffer;
  17787. if (numChannels > 1)
  17788. {
  17789. if (left == 0)
  17790. {
  17791. for (int i = numThisTime; --i >= 0;)
  17792. {
  17793. ++src;
  17794. *right++ = ((int) *src++ - 128) << 24;
  17795. }
  17796. }
  17797. else if (right == 0)
  17798. {
  17799. for (int i = numThisTime; --i >= 0;)
  17800. {
  17801. *left++ = ((int) *src++ - 128) << 24;
  17802. ++src;
  17803. }
  17804. }
  17805. else
  17806. {
  17807. for (int i = numThisTime; --i >= 0;)
  17808. {
  17809. *left++ = ((int) *src++ - 128) << 24;
  17810. *right++ = ((int) *src++ - 128) << 24;
  17811. }
  17812. }
  17813. }
  17814. else
  17815. {
  17816. for (int i = numThisTime; --i >= 0;)
  17817. {
  17818. *left++ = ((int)*src++ - 128) << 24;
  17819. }
  17820. }
  17821. }
  17822. startOffsetInDestBuffer += numThisTime;
  17823. numSamples -= numThisTime;
  17824. }
  17825. if (numSamples > 0)
  17826. {
  17827. for (int i = numDestChannels; --i >= 0;)
  17828. if (destSamples[i] != 0)
  17829. zeromem (destSamples[i] + startOffsetInDestBuffer,
  17830. sizeof (int) * numSamples);
  17831. }
  17832. return true;
  17833. }
  17834. juce_UseDebuggingNewOperator
  17835. };
  17836. class WavAudioFormatWriter : public AudioFormatWriter
  17837. {
  17838. MemoryBlock tempBlock, bwavChunk, smplChunk;
  17839. uint32 lengthInSamples, bytesWritten;
  17840. int64 headerPosition;
  17841. bool writeFailed;
  17842. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  17843. WavAudioFormatWriter (const WavAudioFormatWriter&);
  17844. WavAudioFormatWriter& operator= (const WavAudioFormatWriter&);
  17845. void writeHeader()
  17846. {
  17847. const bool seekedOk = output->setPosition (headerPosition);
  17848. (void) seekedOk;
  17849. // if this fails, you've given it an output stream that can't seek! It needs
  17850. // to be able to seek back to write the header
  17851. jassert (seekedOk);
  17852. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  17853. output->writeInt (chunkName ("RIFF"));
  17854. output->writeInt ((int) (lengthInSamples * bytesPerFrame
  17855. + ((bwavChunk.getSize() > 0) ? (44 + bwavChunk.getSize()) : 36)));
  17856. output->writeInt (chunkName ("WAVE"));
  17857. output->writeInt (chunkName ("fmt "));
  17858. output->writeInt (16);
  17859. output->writeShort ((bitsPerSample < 32) ? (short) 1 /*WAVE_FORMAT_PCM*/
  17860. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  17861. output->writeShort ((short) numChannels);
  17862. output->writeInt ((int) sampleRate);
  17863. output->writeInt (bytesPerFrame * (int) sampleRate);
  17864. output->writeShort ((short) bytesPerFrame);
  17865. output->writeShort ((short) bitsPerSample);
  17866. if (bwavChunk.getSize() > 0)
  17867. {
  17868. output->writeInt (chunkName ("bext"));
  17869. output->writeInt ((int) bwavChunk.getSize());
  17870. output->write (bwavChunk.getData(), (int) bwavChunk.getSize());
  17871. }
  17872. if (smplChunk.getSize() > 0)
  17873. {
  17874. output->writeInt (chunkName ("smpl"));
  17875. output->writeInt ((int) smplChunk.getSize());
  17876. output->write (smplChunk.getData(), (int) smplChunk.getSize());
  17877. }
  17878. output->writeInt (chunkName ("data"));
  17879. output->writeInt (lengthInSamples * bytesPerFrame);
  17880. usesFloatingPointData = (bitsPerSample == 32);
  17881. }
  17882. public:
  17883. WavAudioFormatWriter (OutputStream* const out,
  17884. const double sampleRate_,
  17885. const unsigned int numChannels_,
  17886. const int bits,
  17887. const StringPairArray& metadataValues)
  17888. : AudioFormatWriter (out,
  17889. TRANS (wavFormatName),
  17890. sampleRate_,
  17891. numChannels_,
  17892. bits),
  17893. lengthInSamples (0),
  17894. bytesWritten (0),
  17895. writeFailed (false)
  17896. {
  17897. if (metadataValues.size() > 0)
  17898. {
  17899. bwavChunk = BWAVChunk::createFrom (metadataValues);
  17900. smplChunk = SMPLChunk::createFrom (metadataValues);
  17901. }
  17902. headerPosition = out->getPosition();
  17903. writeHeader();
  17904. }
  17905. ~WavAudioFormatWriter()
  17906. {
  17907. writeHeader();
  17908. }
  17909. bool write (const int** data, int numSamples)
  17910. {
  17911. if (writeFailed)
  17912. return false;
  17913. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  17914. tempBlock.ensureSize (bytes, false);
  17915. char* buffer = static_cast <char*> (tempBlock.getData());
  17916. const int* left = data[0];
  17917. const int* right = data[1];
  17918. if (right == 0)
  17919. right = left;
  17920. if (bitsPerSample == 16)
  17921. {
  17922. short* b = (short*) buffer;
  17923. if (numChannels > 1)
  17924. {
  17925. for (int i = numSamples; --i >= 0;)
  17926. {
  17927. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*left++ >> 16));
  17928. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*right++ >> 16));
  17929. }
  17930. }
  17931. else
  17932. {
  17933. for (int i = numSamples; --i >= 0;)
  17934. {
  17935. *b++ = (short) ByteOrder::swapIfBigEndian ((unsigned short) (*left++ >> 16));
  17936. }
  17937. }
  17938. }
  17939. else if (bitsPerSample == 24)
  17940. {
  17941. char* b = buffer;
  17942. if (numChannels > 1)
  17943. {
  17944. for (int i = numSamples; --i >= 0;)
  17945. {
  17946. ByteOrder::littleEndian24BitToChars ((*left++) >> 8, b);
  17947. b += 3;
  17948. ByteOrder::littleEndian24BitToChars ((*right++) >> 8, b);
  17949. b += 3;
  17950. }
  17951. }
  17952. else
  17953. {
  17954. for (int i = numSamples; --i >= 0;)
  17955. {
  17956. ByteOrder::littleEndian24BitToChars ((*left++) >> 8, b);
  17957. b += 3;
  17958. }
  17959. }
  17960. }
  17961. else if (bitsPerSample == 32)
  17962. {
  17963. unsigned int* b = (unsigned int*) buffer;
  17964. if (numChannels > 1)
  17965. {
  17966. for (int i = numSamples; --i >= 0;)
  17967. {
  17968. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *left++);
  17969. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *right++);
  17970. }
  17971. }
  17972. else
  17973. {
  17974. for (int i = numSamples; --i >= 0;)
  17975. {
  17976. *b++ = ByteOrder::swapIfBigEndian ((unsigned int) *left++);
  17977. }
  17978. }
  17979. }
  17980. else if (bitsPerSample == 8)
  17981. {
  17982. unsigned char* b = (unsigned char*) buffer;
  17983. if (numChannels > 1)
  17984. {
  17985. for (int i = numSamples; --i >= 0;)
  17986. {
  17987. *b++ = (unsigned char) (128 + (*left++ >> 24));
  17988. *b++ = (unsigned char) (128 + (*right++ >> 24));
  17989. }
  17990. }
  17991. else
  17992. {
  17993. for (int i = numSamples; --i >= 0;)
  17994. {
  17995. *b++ = (unsigned char) (128 + (*left++ >> 24));
  17996. }
  17997. }
  17998. }
  17999. if (bytesWritten + bytes >= (uint32) 0xfff00000
  18000. || ! output->write (buffer, bytes))
  18001. {
  18002. // failed to write to disk, so let's try writing the header.
  18003. // If it's just run out of disk space, then if it does manage
  18004. // to write the header, we'll still have a useable file..
  18005. writeHeader();
  18006. writeFailed = true;
  18007. return false;
  18008. }
  18009. else
  18010. {
  18011. bytesWritten += bytes;
  18012. lengthInSamples += numSamples;
  18013. return true;
  18014. }
  18015. }
  18016. juce_UseDebuggingNewOperator
  18017. };
  18018. WavAudioFormat::WavAudioFormat()
  18019. : AudioFormat (TRANS (wavFormatName), StringArray (wavExtensions))
  18020. {
  18021. }
  18022. WavAudioFormat::~WavAudioFormat()
  18023. {
  18024. }
  18025. const Array <int> WavAudioFormat::getPossibleSampleRates()
  18026. {
  18027. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  18028. return Array <int> (rates);
  18029. }
  18030. const Array <int> WavAudioFormat::getPossibleBitDepths()
  18031. {
  18032. const int depths[] = { 8, 16, 24, 32, 0 };
  18033. return Array <int> (depths);
  18034. }
  18035. bool WavAudioFormat::canDoStereo()
  18036. {
  18037. return true;
  18038. }
  18039. bool WavAudioFormat::canDoMono()
  18040. {
  18041. return true;
  18042. }
  18043. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  18044. const bool deleteStreamIfOpeningFails)
  18045. {
  18046. ScopedPointer <WavAudioFormatReader> r (new WavAudioFormatReader (sourceStream));
  18047. if (r->sampleRate != 0)
  18048. return r.release();
  18049. if (! deleteStreamIfOpeningFails)
  18050. r->input = 0;
  18051. return 0;
  18052. }
  18053. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out,
  18054. double sampleRate,
  18055. unsigned int numChannels,
  18056. int bitsPerSample,
  18057. const StringPairArray& metadataValues,
  18058. int /*qualityOptionIndex*/)
  18059. {
  18060. if (getPossibleBitDepths().contains (bitsPerSample))
  18061. {
  18062. return new WavAudioFormatWriter (out,
  18063. sampleRate,
  18064. numChannels,
  18065. bitsPerSample,
  18066. metadataValues);
  18067. }
  18068. return 0;
  18069. }
  18070. static bool juce_slowCopyOfWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  18071. {
  18072. TemporaryFile tempFile (file);
  18073. WavAudioFormat wav;
  18074. ScopedPointer <AudioFormatReader> reader (wav.createReaderFor (file.createInputStream(), true));
  18075. if (reader != 0)
  18076. {
  18077. ScopedPointer <OutputStream> outStream (tempFile.getFile().createOutputStream());
  18078. if (outStream != 0)
  18079. {
  18080. ScopedPointer <AudioFormatWriter> writer (wav.createWriterFor (outStream, reader->sampleRate,
  18081. reader->numChannels, reader->bitsPerSample,
  18082. metadata, 0));
  18083. if (writer != 0)
  18084. {
  18085. outStream.release();
  18086. bool ok = writer->writeFromAudioReader (*reader, 0, -1);
  18087. writer = 0;
  18088. reader = 0;
  18089. return ok && tempFile.overwriteTargetFileWithTemporary();
  18090. }
  18091. }
  18092. }
  18093. return false;
  18094. }
  18095. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  18096. {
  18097. ScopedPointer <WavAudioFormatReader> reader ((WavAudioFormatReader*) createReaderFor (wavFile.createInputStream(), true));
  18098. if (reader != 0)
  18099. {
  18100. const int64 bwavPos = reader->bwavChunkStart;
  18101. const int64 bwavSize = reader->bwavSize;
  18102. reader = 0;
  18103. if (bwavSize > 0)
  18104. {
  18105. MemoryBlock chunk = BWAVChunk::createFrom (newMetadata);
  18106. if (chunk.getSize() <= (size_t) bwavSize)
  18107. {
  18108. // the new one will fit in the space available, so write it directly..
  18109. const int64 oldSize = wavFile.getSize();
  18110. {
  18111. ScopedPointer <FileOutputStream> out (wavFile.createOutputStream());
  18112. out->setPosition (bwavPos);
  18113. out->write (chunk.getData(), (int) chunk.getSize());
  18114. out->setPosition (oldSize);
  18115. }
  18116. jassert (wavFile.getSize() == oldSize);
  18117. return true;
  18118. }
  18119. }
  18120. }
  18121. return juce_slowCopyOfWavFileWithNewMetadata (wavFile, newMetadata);
  18122. }
  18123. END_JUCE_NAMESPACE
  18124. /*** End of inlined file: juce_WavAudioFormat.cpp ***/
  18125. /*** Start of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18126. BEGIN_JUCE_NAMESPACE
  18127. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  18128. const bool deleteReaderWhenThisIsDeleted)
  18129. : reader (reader_),
  18130. deleteReader (deleteReaderWhenThisIsDeleted),
  18131. nextPlayPos (0),
  18132. looping (false)
  18133. {
  18134. jassert (reader != 0);
  18135. }
  18136. AudioFormatReaderSource::~AudioFormatReaderSource()
  18137. {
  18138. releaseResources();
  18139. if (deleteReader)
  18140. delete reader;
  18141. }
  18142. void AudioFormatReaderSource::setNextReadPosition (int newPosition)
  18143. {
  18144. nextPlayPos = newPosition;
  18145. }
  18146. void AudioFormatReaderSource::setLooping (const bool shouldLoop) throw()
  18147. {
  18148. looping = shouldLoop;
  18149. }
  18150. int AudioFormatReaderSource::getNextReadPosition() const
  18151. {
  18152. return (looping) ? (nextPlayPos % (int) reader->lengthInSamples)
  18153. : nextPlayPos;
  18154. }
  18155. int AudioFormatReaderSource::getTotalLength() const
  18156. {
  18157. return (int) reader->lengthInSamples;
  18158. }
  18159. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  18160. double /*sampleRate*/)
  18161. {
  18162. }
  18163. void AudioFormatReaderSource::releaseResources()
  18164. {
  18165. }
  18166. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18167. {
  18168. if (info.numSamples > 0)
  18169. {
  18170. const int start = nextPlayPos;
  18171. if (looping)
  18172. {
  18173. const int newStart = start % (int) reader->lengthInSamples;
  18174. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  18175. if (newEnd > newStart)
  18176. {
  18177. info.buffer->readFromAudioReader (reader,
  18178. info.startSample,
  18179. newEnd - newStart,
  18180. newStart,
  18181. true, true);
  18182. }
  18183. else
  18184. {
  18185. const int endSamps = (int) reader->lengthInSamples - newStart;
  18186. info.buffer->readFromAudioReader (reader,
  18187. info.startSample,
  18188. endSamps,
  18189. newStart,
  18190. true, true);
  18191. info.buffer->readFromAudioReader (reader,
  18192. info.startSample + endSamps,
  18193. newEnd,
  18194. 0,
  18195. true, true);
  18196. }
  18197. nextPlayPos = newEnd;
  18198. }
  18199. else
  18200. {
  18201. info.buffer->readFromAudioReader (reader,
  18202. info.startSample,
  18203. info.numSamples,
  18204. start,
  18205. true, true);
  18206. nextPlayPos += info.numSamples;
  18207. }
  18208. }
  18209. }
  18210. END_JUCE_NAMESPACE
  18211. /*** End of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18212. /*** Start of inlined file: juce_AudioSourcePlayer.cpp ***/
  18213. BEGIN_JUCE_NAMESPACE
  18214. AudioSourcePlayer::AudioSourcePlayer()
  18215. : source (0),
  18216. sampleRate (0),
  18217. bufferSize (0),
  18218. tempBuffer (2, 8),
  18219. lastGain (1.0f),
  18220. gain (1.0f)
  18221. {
  18222. }
  18223. AudioSourcePlayer::~AudioSourcePlayer()
  18224. {
  18225. setSource (0);
  18226. }
  18227. void AudioSourcePlayer::setSource (AudioSource* newSource)
  18228. {
  18229. if (source != newSource)
  18230. {
  18231. AudioSource* const oldSource = source;
  18232. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  18233. newSource->prepareToPlay (bufferSize, sampleRate);
  18234. {
  18235. const ScopedLock sl (readLock);
  18236. source = newSource;
  18237. }
  18238. if (oldSource != 0)
  18239. oldSource->releaseResources();
  18240. }
  18241. }
  18242. void AudioSourcePlayer::setGain (const float newGain) throw()
  18243. {
  18244. gain = newGain;
  18245. }
  18246. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  18247. int totalNumInputChannels,
  18248. float** outputChannelData,
  18249. int totalNumOutputChannels,
  18250. int numSamples)
  18251. {
  18252. // these should have been prepared by audioDeviceAboutToStart()...
  18253. jassert (sampleRate > 0 && bufferSize > 0);
  18254. const ScopedLock sl (readLock);
  18255. if (source != 0)
  18256. {
  18257. AudioSourceChannelInfo info;
  18258. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  18259. // messy stuff needed to compact the channels down into an array
  18260. // of non-zero pointers..
  18261. for (i = 0; i < totalNumInputChannels; ++i)
  18262. {
  18263. if (inputChannelData[i] != 0)
  18264. {
  18265. inputChans [numInputs++] = inputChannelData[i];
  18266. if (numInputs >= numElementsInArray (inputChans))
  18267. break;
  18268. }
  18269. }
  18270. for (i = 0; i < totalNumOutputChannels; ++i)
  18271. {
  18272. if (outputChannelData[i] != 0)
  18273. {
  18274. outputChans [numOutputs++] = outputChannelData[i];
  18275. if (numOutputs >= numElementsInArray (outputChans))
  18276. break;
  18277. }
  18278. }
  18279. if (numInputs > numOutputs)
  18280. {
  18281. // if there aren't enough output channels for the number of
  18282. // inputs, we need to create some temporary extra ones (can't
  18283. // use the input data in case it gets written to)
  18284. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  18285. false, false, true);
  18286. for (i = 0; i < numOutputs; ++i)
  18287. {
  18288. channels[numActiveChans] = outputChans[i];
  18289. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18290. ++numActiveChans;
  18291. }
  18292. for (i = numOutputs; i < numInputs; ++i)
  18293. {
  18294. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  18295. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18296. ++numActiveChans;
  18297. }
  18298. }
  18299. else
  18300. {
  18301. for (i = 0; i < numInputs; ++i)
  18302. {
  18303. channels[numActiveChans] = outputChans[i];
  18304. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18305. ++numActiveChans;
  18306. }
  18307. for (i = numInputs; i < numOutputs; ++i)
  18308. {
  18309. channels[numActiveChans] = outputChans[i];
  18310. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  18311. ++numActiveChans;
  18312. }
  18313. }
  18314. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  18315. info.buffer = &buffer;
  18316. info.startSample = 0;
  18317. info.numSamples = numSamples;
  18318. source->getNextAudioBlock (info);
  18319. for (i = info.buffer->getNumChannels(); --i >= 0;)
  18320. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  18321. lastGain = gain;
  18322. }
  18323. else
  18324. {
  18325. for (int i = 0; i < totalNumOutputChannels; ++i)
  18326. if (outputChannelData[i] != 0)
  18327. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  18328. }
  18329. }
  18330. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  18331. {
  18332. sampleRate = device->getCurrentSampleRate();
  18333. bufferSize = device->getCurrentBufferSizeSamples();
  18334. zeromem (channels, sizeof (channels));
  18335. if (source != 0)
  18336. source->prepareToPlay (bufferSize, sampleRate);
  18337. }
  18338. void AudioSourcePlayer::audioDeviceStopped()
  18339. {
  18340. if (source != 0)
  18341. source->releaseResources();
  18342. sampleRate = 0.0;
  18343. bufferSize = 0;
  18344. tempBuffer.setSize (2, 8);
  18345. }
  18346. END_JUCE_NAMESPACE
  18347. /*** End of inlined file: juce_AudioSourcePlayer.cpp ***/
  18348. /*** Start of inlined file: juce_AudioTransportSource.cpp ***/
  18349. BEGIN_JUCE_NAMESPACE
  18350. AudioTransportSource::AudioTransportSource()
  18351. : source (0),
  18352. resamplerSource (0),
  18353. bufferingSource (0),
  18354. positionableSource (0),
  18355. masterSource (0),
  18356. gain (1.0f),
  18357. lastGain (1.0f),
  18358. playing (false),
  18359. stopped (true),
  18360. sampleRate (44100.0),
  18361. sourceSampleRate (0.0),
  18362. blockSize (128),
  18363. readAheadBufferSize (0),
  18364. isPrepared (false),
  18365. inputStreamEOF (false)
  18366. {
  18367. }
  18368. AudioTransportSource::~AudioTransportSource()
  18369. {
  18370. setSource (0);
  18371. releaseResources();
  18372. }
  18373. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  18374. int readAheadBufferSize_,
  18375. double sourceSampleRateToCorrectFor)
  18376. {
  18377. if (source == newSource)
  18378. {
  18379. if (source == 0)
  18380. return;
  18381. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  18382. }
  18383. readAheadBufferSize = readAheadBufferSize_;
  18384. sourceSampleRate = sourceSampleRateToCorrectFor;
  18385. ResamplingAudioSource* newResamplerSource = 0;
  18386. BufferingAudioSource* newBufferingSource = 0;
  18387. PositionableAudioSource* newPositionableSource = 0;
  18388. AudioSource* newMasterSource = 0;
  18389. ScopedPointer <ResamplingAudioSource> oldResamplerSource (resamplerSource);
  18390. ScopedPointer <BufferingAudioSource> oldBufferingSource (bufferingSource);
  18391. AudioSource* oldMasterSource = masterSource;
  18392. if (newSource != 0)
  18393. {
  18394. newPositionableSource = newSource;
  18395. if (readAheadBufferSize_ > 0)
  18396. newPositionableSource = newBufferingSource
  18397. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  18398. newPositionableSource->setNextReadPosition (0);
  18399. if (sourceSampleRateToCorrectFor != 0)
  18400. newMasterSource = newResamplerSource
  18401. = new ResamplingAudioSource (newPositionableSource, false);
  18402. else
  18403. newMasterSource = newPositionableSource;
  18404. if (isPrepared)
  18405. {
  18406. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  18407. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  18408. newMasterSource->prepareToPlay (blockSize, sampleRate);
  18409. }
  18410. }
  18411. {
  18412. const ScopedLock sl (callbackLock);
  18413. source = newSource;
  18414. resamplerSource = newResamplerSource;
  18415. bufferingSource = newBufferingSource;
  18416. masterSource = newMasterSource;
  18417. positionableSource = newPositionableSource;
  18418. playing = false;
  18419. }
  18420. if (oldMasterSource != 0)
  18421. oldMasterSource->releaseResources();
  18422. }
  18423. void AudioTransportSource::start()
  18424. {
  18425. if ((! playing) && masterSource != 0)
  18426. {
  18427. {
  18428. const ScopedLock sl (callbackLock);
  18429. playing = true;
  18430. stopped = false;
  18431. inputStreamEOF = false;
  18432. }
  18433. sendChangeMessage (this);
  18434. }
  18435. }
  18436. void AudioTransportSource::stop()
  18437. {
  18438. if (playing)
  18439. {
  18440. {
  18441. const ScopedLock sl (callbackLock);
  18442. playing = false;
  18443. }
  18444. int n = 500;
  18445. while (--n >= 0 && ! stopped)
  18446. Thread::sleep (2);
  18447. sendChangeMessage (this);
  18448. }
  18449. }
  18450. void AudioTransportSource::setPosition (double newPosition)
  18451. {
  18452. if (sampleRate > 0.0)
  18453. setNextReadPosition (roundToInt (newPosition * sampleRate));
  18454. }
  18455. double AudioTransportSource::getCurrentPosition() const
  18456. {
  18457. if (sampleRate > 0.0)
  18458. return getNextReadPosition() / sampleRate;
  18459. else
  18460. return 0.0;
  18461. }
  18462. void AudioTransportSource::setNextReadPosition (int newPosition)
  18463. {
  18464. if (positionableSource != 0)
  18465. {
  18466. if (sampleRate > 0 && sourceSampleRate > 0)
  18467. newPosition = roundToInt (newPosition * sourceSampleRate / sampleRate);
  18468. positionableSource->setNextReadPosition (newPosition);
  18469. }
  18470. }
  18471. int AudioTransportSource::getNextReadPosition() const
  18472. {
  18473. if (positionableSource != 0)
  18474. {
  18475. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  18476. return roundToInt (positionableSource->getNextReadPosition() * ratio);
  18477. }
  18478. return 0;
  18479. }
  18480. int AudioTransportSource::getTotalLength() const
  18481. {
  18482. const ScopedLock sl (callbackLock);
  18483. if (positionableSource != 0)
  18484. {
  18485. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  18486. return roundToInt (positionableSource->getTotalLength() * ratio);
  18487. }
  18488. return 0;
  18489. }
  18490. bool AudioTransportSource::isLooping() const
  18491. {
  18492. const ScopedLock sl (callbackLock);
  18493. return positionableSource != 0
  18494. && positionableSource->isLooping();
  18495. }
  18496. void AudioTransportSource::setGain (const float newGain) throw()
  18497. {
  18498. gain = newGain;
  18499. }
  18500. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  18501. double sampleRate_)
  18502. {
  18503. const ScopedLock sl (callbackLock);
  18504. sampleRate = sampleRate_;
  18505. blockSize = samplesPerBlockExpected;
  18506. if (masterSource != 0)
  18507. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18508. if (resamplerSource != 0 && sourceSampleRate != 0)
  18509. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  18510. isPrepared = true;
  18511. }
  18512. void AudioTransportSource::releaseResources()
  18513. {
  18514. const ScopedLock sl (callbackLock);
  18515. if (masterSource != 0)
  18516. masterSource->releaseResources();
  18517. isPrepared = false;
  18518. }
  18519. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18520. {
  18521. const ScopedLock sl (callbackLock);
  18522. inputStreamEOF = false;
  18523. if (masterSource != 0 && ! stopped)
  18524. {
  18525. masterSource->getNextAudioBlock (info);
  18526. if (! playing)
  18527. {
  18528. // just stopped playing, so fade out the last block..
  18529. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  18530. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  18531. if (info.numSamples > 256)
  18532. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  18533. }
  18534. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  18535. && ! positionableSource->isLooping())
  18536. {
  18537. playing = false;
  18538. inputStreamEOF = true;
  18539. sendChangeMessage (this);
  18540. }
  18541. stopped = ! playing;
  18542. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  18543. {
  18544. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  18545. lastGain, gain);
  18546. }
  18547. }
  18548. else
  18549. {
  18550. info.clearActiveBufferRegion();
  18551. stopped = true;
  18552. }
  18553. lastGain = gain;
  18554. }
  18555. END_JUCE_NAMESPACE
  18556. /*** End of inlined file: juce_AudioTransportSource.cpp ***/
  18557. /*** Start of inlined file: juce_BufferingAudioSource.cpp ***/
  18558. BEGIN_JUCE_NAMESPACE
  18559. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  18560. public Thread,
  18561. private Timer
  18562. {
  18563. public:
  18564. SharedBufferingAudioSourceThread()
  18565. : Thread ("Audio Buffer")
  18566. {
  18567. }
  18568. ~SharedBufferingAudioSourceThread()
  18569. {
  18570. stopThread (10000);
  18571. clearSingletonInstance();
  18572. }
  18573. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  18574. void addSource (BufferingAudioSource* source)
  18575. {
  18576. const ScopedLock sl (lock);
  18577. if (! sources.contains (source))
  18578. {
  18579. sources.add (source);
  18580. startThread();
  18581. stopTimer();
  18582. }
  18583. notify();
  18584. }
  18585. void removeSource (BufferingAudioSource* source)
  18586. {
  18587. const ScopedLock sl (lock);
  18588. sources.removeValue (source);
  18589. if (sources.size() == 0)
  18590. startTimer (5000);
  18591. }
  18592. private:
  18593. Array <BufferingAudioSource*> sources;
  18594. CriticalSection lock;
  18595. void run()
  18596. {
  18597. while (! threadShouldExit())
  18598. {
  18599. bool busy = false;
  18600. for (int i = sources.size(); --i >= 0;)
  18601. {
  18602. if (threadShouldExit())
  18603. return;
  18604. const ScopedLock sl (lock);
  18605. BufferingAudioSource* const b = sources[i];
  18606. if (b != 0 && b->readNextBufferChunk())
  18607. busy = true;
  18608. }
  18609. if (! busy)
  18610. wait (500);
  18611. }
  18612. }
  18613. void timerCallback()
  18614. {
  18615. stopTimer();
  18616. if (sources.size() == 0)
  18617. deleteInstance();
  18618. }
  18619. SharedBufferingAudioSourceThread (const SharedBufferingAudioSourceThread&);
  18620. SharedBufferingAudioSourceThread& operator= (const SharedBufferingAudioSourceThread&);
  18621. };
  18622. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  18623. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  18624. const bool deleteSourceWhenDeleted_,
  18625. int numberOfSamplesToBuffer_)
  18626. : source (source_),
  18627. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  18628. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  18629. buffer (2, 0),
  18630. bufferValidStart (0),
  18631. bufferValidEnd (0),
  18632. nextPlayPos (0),
  18633. wasSourceLooping (false)
  18634. {
  18635. jassert (source_ != 0);
  18636. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  18637. // not using a larger buffer..
  18638. }
  18639. BufferingAudioSource::~BufferingAudioSource()
  18640. {
  18641. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18642. if (thread != 0)
  18643. thread->removeSource (this);
  18644. if (deleteSourceWhenDeleted)
  18645. delete source;
  18646. }
  18647. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  18648. {
  18649. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  18650. sampleRate = sampleRate_;
  18651. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  18652. buffer.clear();
  18653. bufferValidStart = 0;
  18654. bufferValidEnd = 0;
  18655. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  18656. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  18657. buffer.getNumSamples() / 2))
  18658. {
  18659. SharedBufferingAudioSourceThread::getInstance()->notify();
  18660. Thread::sleep (5);
  18661. }
  18662. }
  18663. void BufferingAudioSource::releaseResources()
  18664. {
  18665. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18666. if (thread != 0)
  18667. thread->removeSource (this);
  18668. buffer.setSize (2, 0);
  18669. source->releaseResources();
  18670. }
  18671. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18672. {
  18673. const ScopedLock sl (bufferStartPosLock);
  18674. const int validStart = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos;
  18675. const int validEnd = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos;
  18676. if (validStart == validEnd)
  18677. {
  18678. // total cache miss
  18679. info.clearActiveBufferRegion();
  18680. }
  18681. else
  18682. {
  18683. if (validStart > 0)
  18684. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  18685. if (validEnd < info.numSamples)
  18686. info.buffer->clear (info.startSample + validEnd,
  18687. info.numSamples - validEnd); // partial cache miss at end
  18688. if (validStart < validEnd)
  18689. {
  18690. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  18691. {
  18692. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  18693. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  18694. if (startBufferIndex < endBufferIndex)
  18695. {
  18696. info.buffer->copyFrom (chan, info.startSample + validStart,
  18697. buffer,
  18698. chan, startBufferIndex,
  18699. validEnd - validStart);
  18700. }
  18701. else
  18702. {
  18703. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  18704. info.buffer->copyFrom (chan, info.startSample + validStart,
  18705. buffer,
  18706. chan, startBufferIndex,
  18707. initialSize);
  18708. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  18709. buffer,
  18710. chan, 0,
  18711. (validEnd - validStart) - initialSize);
  18712. }
  18713. }
  18714. }
  18715. nextPlayPos += info.numSamples;
  18716. if (source->isLooping() && nextPlayPos > 0)
  18717. nextPlayPos %= source->getTotalLength();
  18718. }
  18719. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18720. if (thread != 0)
  18721. thread->notify();
  18722. }
  18723. int BufferingAudioSource::getNextReadPosition() const
  18724. {
  18725. return (source->isLooping() && nextPlayPos > 0)
  18726. ? nextPlayPos % source->getTotalLength()
  18727. : nextPlayPos;
  18728. }
  18729. void BufferingAudioSource::setNextReadPosition (int newPosition)
  18730. {
  18731. const ScopedLock sl (bufferStartPosLock);
  18732. nextPlayPos = newPosition;
  18733. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  18734. if (thread != 0)
  18735. thread->notify();
  18736. }
  18737. bool BufferingAudioSource::readNextBufferChunk()
  18738. {
  18739. int newBVS, newBVE, sectionToReadStart, sectionToReadEnd;
  18740. {
  18741. const ScopedLock sl (bufferStartPosLock);
  18742. if (wasSourceLooping != isLooping())
  18743. {
  18744. wasSourceLooping = isLooping();
  18745. bufferValidStart = 0;
  18746. bufferValidEnd = 0;
  18747. }
  18748. newBVS = jmax (0, nextPlayPos);
  18749. newBVE = newBVS + buffer.getNumSamples() - 4;
  18750. sectionToReadStart = 0;
  18751. sectionToReadEnd = 0;
  18752. const int maxChunkSize = 2048;
  18753. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  18754. {
  18755. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  18756. sectionToReadStart = newBVS;
  18757. sectionToReadEnd = newBVE;
  18758. bufferValidStart = 0;
  18759. bufferValidEnd = 0;
  18760. }
  18761. else if (abs (newBVS - bufferValidStart) > 512
  18762. || abs (newBVE - bufferValidEnd) > 512)
  18763. {
  18764. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  18765. sectionToReadStart = bufferValidEnd;
  18766. sectionToReadEnd = newBVE;
  18767. bufferValidStart = newBVS;
  18768. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  18769. }
  18770. }
  18771. if (sectionToReadStart != sectionToReadEnd)
  18772. {
  18773. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  18774. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  18775. if (bufferIndexStart < bufferIndexEnd)
  18776. {
  18777. readBufferSection (sectionToReadStart,
  18778. sectionToReadEnd - sectionToReadStart,
  18779. bufferIndexStart);
  18780. }
  18781. else
  18782. {
  18783. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  18784. readBufferSection (sectionToReadStart,
  18785. initialSize,
  18786. bufferIndexStart);
  18787. readBufferSection (sectionToReadStart + initialSize,
  18788. (sectionToReadEnd - sectionToReadStart) - initialSize,
  18789. 0);
  18790. }
  18791. const ScopedLock sl2 (bufferStartPosLock);
  18792. bufferValidStart = newBVS;
  18793. bufferValidEnd = newBVE;
  18794. return true;
  18795. }
  18796. else
  18797. {
  18798. return false;
  18799. }
  18800. }
  18801. void BufferingAudioSource::readBufferSection (int start, int length, int bufferOffset)
  18802. {
  18803. if (source->getNextReadPosition() != start)
  18804. source->setNextReadPosition (start);
  18805. AudioSourceChannelInfo info;
  18806. info.buffer = &buffer;
  18807. info.startSample = bufferOffset;
  18808. info.numSamples = length;
  18809. source->getNextAudioBlock (info);
  18810. }
  18811. END_JUCE_NAMESPACE
  18812. /*** End of inlined file: juce_BufferingAudioSource.cpp ***/
  18813. /*** Start of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  18814. BEGIN_JUCE_NAMESPACE
  18815. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  18816. const bool deleteSourceWhenDeleted_)
  18817. : requiredNumberOfChannels (2),
  18818. source (source_),
  18819. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  18820. buffer (2, 16)
  18821. {
  18822. remappedInfo.buffer = &buffer;
  18823. remappedInfo.startSample = 0;
  18824. }
  18825. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  18826. {
  18827. if (deleteSourceWhenDeleted)
  18828. delete source;
  18829. }
  18830. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_) throw()
  18831. {
  18832. const ScopedLock sl (lock);
  18833. requiredNumberOfChannels = requiredNumberOfChannels_;
  18834. }
  18835. void ChannelRemappingAudioSource::clearAllMappings() throw()
  18836. {
  18837. const ScopedLock sl (lock);
  18838. remappedInputs.clear();
  18839. remappedOutputs.clear();
  18840. }
  18841. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex) throw()
  18842. {
  18843. const ScopedLock sl (lock);
  18844. while (remappedInputs.size() < destIndex)
  18845. remappedInputs.add (-1);
  18846. remappedInputs.set (destIndex, sourceIndex);
  18847. }
  18848. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex) throw()
  18849. {
  18850. const ScopedLock sl (lock);
  18851. while (remappedOutputs.size() < sourceIndex)
  18852. remappedOutputs.add (-1);
  18853. remappedOutputs.set (sourceIndex, destIndex);
  18854. }
  18855. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const throw()
  18856. {
  18857. const ScopedLock sl (lock);
  18858. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  18859. return remappedInputs.getUnchecked (inputChannelIndex);
  18860. return -1;
  18861. }
  18862. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const throw()
  18863. {
  18864. const ScopedLock sl (lock);
  18865. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  18866. return remappedOutputs .getUnchecked (outputChannelIndex);
  18867. return -1;
  18868. }
  18869. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  18870. {
  18871. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18872. }
  18873. void ChannelRemappingAudioSource::releaseResources()
  18874. {
  18875. source->releaseResources();
  18876. }
  18877. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  18878. {
  18879. const ScopedLock sl (lock);
  18880. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  18881. const int numChans = bufferToFill.buffer->getNumChannels();
  18882. int i;
  18883. for (i = 0; i < buffer.getNumChannels(); ++i)
  18884. {
  18885. const int remappedChan = getRemappedInputChannel (i);
  18886. if (remappedChan >= 0 && remappedChan < numChans)
  18887. {
  18888. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  18889. remappedChan,
  18890. bufferToFill.startSample,
  18891. bufferToFill.numSamples);
  18892. }
  18893. else
  18894. {
  18895. buffer.clear (i, 0, bufferToFill.numSamples);
  18896. }
  18897. }
  18898. remappedInfo.numSamples = bufferToFill.numSamples;
  18899. source->getNextAudioBlock (remappedInfo);
  18900. bufferToFill.clearActiveBufferRegion();
  18901. for (i = 0; i < requiredNumberOfChannels; ++i)
  18902. {
  18903. const int remappedChan = getRemappedOutputChannel (i);
  18904. if (remappedChan >= 0 && remappedChan < numChans)
  18905. {
  18906. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  18907. buffer, i, 0, bufferToFill.numSamples);
  18908. }
  18909. }
  18910. }
  18911. XmlElement* ChannelRemappingAudioSource::createXml() const throw()
  18912. {
  18913. XmlElement* e = new XmlElement ("MAPPINGS");
  18914. String ins, outs;
  18915. int i;
  18916. const ScopedLock sl (lock);
  18917. for (i = 0; i < remappedInputs.size(); ++i)
  18918. ins << remappedInputs.getUnchecked(i) << ' ';
  18919. for (i = 0; i < remappedOutputs.size(); ++i)
  18920. outs << remappedOutputs.getUnchecked(i) << ' ';
  18921. e->setAttribute ("inputs", ins.trimEnd());
  18922. e->setAttribute ("outputs", outs.trimEnd());
  18923. return e;
  18924. }
  18925. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e) throw()
  18926. {
  18927. if (e.hasTagName ("MAPPINGS"))
  18928. {
  18929. const ScopedLock sl (lock);
  18930. clearAllMappings();
  18931. StringArray ins, outs;
  18932. ins.addTokens (e.getStringAttribute ("inputs"), false);
  18933. outs.addTokens (e.getStringAttribute ("outputs"), false);
  18934. int i;
  18935. for (i = 0; i < ins.size(); ++i)
  18936. remappedInputs.add (ins[i].getIntValue());
  18937. for (i = 0; i < outs.size(); ++i)
  18938. remappedOutputs.add (outs[i].getIntValue());
  18939. }
  18940. }
  18941. END_JUCE_NAMESPACE
  18942. /*** End of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  18943. /*** Start of inlined file: juce_IIRFilterAudioSource.cpp ***/
  18944. BEGIN_JUCE_NAMESPACE
  18945. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  18946. const bool deleteInputWhenDeleted_)
  18947. : input (inputSource),
  18948. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  18949. {
  18950. jassert (inputSource != 0);
  18951. for (int i = 2; --i >= 0;)
  18952. iirFilters.add (new IIRFilter());
  18953. }
  18954. IIRFilterAudioSource::~IIRFilterAudioSource()
  18955. {
  18956. if (deleteInputWhenDeleted)
  18957. delete input;
  18958. }
  18959. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  18960. {
  18961. for (int i = iirFilters.size(); --i >= 0;)
  18962. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  18963. }
  18964. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  18965. {
  18966. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18967. for (int i = iirFilters.size(); --i >= 0;)
  18968. iirFilters.getUnchecked(i)->reset();
  18969. }
  18970. void IIRFilterAudioSource::releaseResources()
  18971. {
  18972. input->releaseResources();
  18973. }
  18974. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  18975. {
  18976. input->getNextAudioBlock (bufferToFill);
  18977. const int numChannels = bufferToFill.buffer->getNumChannels();
  18978. while (numChannels > iirFilters.size())
  18979. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  18980. for (int i = 0; i < numChannels; ++i)
  18981. iirFilters.getUnchecked(i)
  18982. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  18983. bufferToFill.numSamples);
  18984. }
  18985. END_JUCE_NAMESPACE
  18986. /*** End of inlined file: juce_IIRFilterAudioSource.cpp ***/
  18987. /*** Start of inlined file: juce_MixerAudioSource.cpp ***/
  18988. BEGIN_JUCE_NAMESPACE
  18989. MixerAudioSource::MixerAudioSource()
  18990. : tempBuffer (2, 0),
  18991. currentSampleRate (0.0),
  18992. bufferSizeExpected (0)
  18993. {
  18994. }
  18995. MixerAudioSource::~MixerAudioSource()
  18996. {
  18997. removeAllInputs();
  18998. }
  18999. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  19000. {
  19001. if (input != 0 && ! inputs.contains (input))
  19002. {
  19003. double localRate;
  19004. int localBufferSize;
  19005. {
  19006. const ScopedLock sl (lock);
  19007. localRate = currentSampleRate;
  19008. localBufferSize = bufferSizeExpected;
  19009. }
  19010. if (localRate != 0.0)
  19011. input->prepareToPlay (localBufferSize, localRate);
  19012. const ScopedLock sl (lock);
  19013. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  19014. inputs.add (input);
  19015. }
  19016. }
  19017. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  19018. {
  19019. if (input != 0)
  19020. {
  19021. int index;
  19022. {
  19023. const ScopedLock sl (lock);
  19024. index = inputs.indexOf (input);
  19025. if (index >= 0)
  19026. {
  19027. inputsToDelete.shiftBits (index, 1);
  19028. inputs.remove (index);
  19029. }
  19030. }
  19031. if (index >= 0)
  19032. {
  19033. input->releaseResources();
  19034. if (deleteInput)
  19035. delete input;
  19036. }
  19037. }
  19038. }
  19039. void MixerAudioSource::removeAllInputs()
  19040. {
  19041. OwnedArray<AudioSource> toDelete;
  19042. {
  19043. const ScopedLock sl (lock);
  19044. for (int i = inputs.size(); --i >= 0;)
  19045. if (inputsToDelete[i])
  19046. toDelete.add (inputs.getUnchecked(i));
  19047. }
  19048. }
  19049. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19050. {
  19051. tempBuffer.setSize (2, samplesPerBlockExpected);
  19052. const ScopedLock sl (lock);
  19053. currentSampleRate = sampleRate;
  19054. bufferSizeExpected = samplesPerBlockExpected;
  19055. for (int i = inputs.size(); --i >= 0;)
  19056. inputs.getUnchecked(i)->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19057. }
  19058. void MixerAudioSource::releaseResources()
  19059. {
  19060. const ScopedLock sl (lock);
  19061. for (int i = inputs.size(); --i >= 0;)
  19062. inputs.getUnchecked(i)->releaseResources();
  19063. tempBuffer.setSize (2, 0);
  19064. currentSampleRate = 0;
  19065. bufferSizeExpected = 0;
  19066. }
  19067. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19068. {
  19069. const ScopedLock sl (lock);
  19070. if (inputs.size() > 0)
  19071. {
  19072. inputs.getUnchecked(0)->getNextAudioBlock (info);
  19073. if (inputs.size() > 1)
  19074. {
  19075. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  19076. info.buffer->getNumSamples());
  19077. AudioSourceChannelInfo info2;
  19078. info2.buffer = &tempBuffer;
  19079. info2.numSamples = info.numSamples;
  19080. info2.startSample = 0;
  19081. for (int i = 1; i < inputs.size(); ++i)
  19082. {
  19083. inputs.getUnchecked(i)->getNextAudioBlock (info2);
  19084. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  19085. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  19086. }
  19087. }
  19088. }
  19089. else
  19090. {
  19091. info.clearActiveBufferRegion();
  19092. }
  19093. }
  19094. END_JUCE_NAMESPACE
  19095. /*** End of inlined file: juce_MixerAudioSource.cpp ***/
  19096. /*** Start of inlined file: juce_ResamplingAudioSource.cpp ***/
  19097. BEGIN_JUCE_NAMESPACE
  19098. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  19099. const bool deleteInputWhenDeleted_)
  19100. : input (inputSource),
  19101. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  19102. ratio (1.0),
  19103. lastRatio (1.0),
  19104. buffer (2, 0),
  19105. sampsInBuffer (0)
  19106. {
  19107. jassert (input != 0);
  19108. }
  19109. ResamplingAudioSource::~ResamplingAudioSource()
  19110. {
  19111. if (deleteInputWhenDeleted)
  19112. delete input;
  19113. }
  19114. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  19115. {
  19116. jassert (samplesInPerOutputSample > 0);
  19117. const ScopedLock sl (ratioLock);
  19118. ratio = jmax (0.0, samplesInPerOutputSample);
  19119. }
  19120. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  19121. double sampleRate)
  19122. {
  19123. const ScopedLock sl (ratioLock);
  19124. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19125. buffer.setSize (2, roundToInt (samplesPerBlockExpected * ratio) + 32);
  19126. buffer.clear();
  19127. sampsInBuffer = 0;
  19128. bufferPos = 0;
  19129. subSampleOffset = 0.0;
  19130. createLowPass (ratio);
  19131. resetFilters();
  19132. }
  19133. void ResamplingAudioSource::releaseResources()
  19134. {
  19135. input->releaseResources();
  19136. buffer.setSize (2, 0);
  19137. }
  19138. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19139. {
  19140. const ScopedLock sl (ratioLock);
  19141. if (lastRatio != ratio)
  19142. {
  19143. createLowPass (ratio);
  19144. lastRatio = ratio;
  19145. }
  19146. const int sampsNeeded = roundToInt (info.numSamples * ratio) + 2;
  19147. int bufferSize = buffer.getNumSamples();
  19148. if (bufferSize < sampsNeeded + 8)
  19149. {
  19150. bufferPos %= bufferSize;
  19151. bufferSize = sampsNeeded + 32;
  19152. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  19153. }
  19154. bufferPos %= bufferSize;
  19155. int endOfBufferPos = bufferPos + sampsInBuffer;
  19156. while (sampsNeeded > sampsInBuffer)
  19157. {
  19158. endOfBufferPos %= bufferSize;
  19159. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  19160. bufferSize - endOfBufferPos);
  19161. AudioSourceChannelInfo readInfo;
  19162. readInfo.buffer = &buffer;
  19163. readInfo.numSamples = numToDo;
  19164. readInfo.startSample = endOfBufferPos;
  19165. input->getNextAudioBlock (readInfo);
  19166. if (ratio > 1.0001)
  19167. {
  19168. // for down-sampling, pre-apply the filter..
  19169. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  19170. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  19171. }
  19172. sampsInBuffer += numToDo;
  19173. endOfBufferPos += numToDo;
  19174. }
  19175. float* dl = info.buffer->getSampleData (0, info.startSample);
  19176. float* dr = (info.buffer->getNumChannels() > 1) ? info.buffer->getSampleData (1, info.startSample) : 0;
  19177. const float* const bl = buffer.getSampleData (0, 0);
  19178. const float* const br = buffer.getSampleData (1, 0);
  19179. int nextPos = (bufferPos + 1) % bufferSize;
  19180. for (int m = info.numSamples; --m >= 0;)
  19181. {
  19182. const float alpha = (float) subSampleOffset;
  19183. const float invAlpha = 1.0f - alpha;
  19184. *dl++ = bl [bufferPos] * invAlpha + bl [nextPos] * alpha;
  19185. if (dr != 0)
  19186. *dr++ = br [bufferPos] * invAlpha + br [nextPos] * alpha;
  19187. subSampleOffset += ratio;
  19188. jassert (sampsInBuffer > 0);
  19189. while (subSampleOffset >= 1.0)
  19190. {
  19191. if (++bufferPos >= bufferSize)
  19192. bufferPos = 0;
  19193. --sampsInBuffer;
  19194. nextPos = (bufferPos + 1) % bufferSize;
  19195. subSampleOffset -= 1.0;
  19196. }
  19197. }
  19198. if (ratio < 0.9999)
  19199. {
  19200. // for up-sampling, apply the filter after transposing..
  19201. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  19202. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  19203. }
  19204. else if (ratio <= 1.0001)
  19205. {
  19206. // if the filter's not currently being applied, keep it stoked with the last couple of samples to avoid discontinuities
  19207. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  19208. {
  19209. const float* const endOfBuffer = info.buffer->getSampleData (i, info.startSample + info.numSamples - 1);
  19210. FilterState& fs = filterStates[i];
  19211. if (info.numSamples > 1)
  19212. {
  19213. fs.y2 = fs.x2 = *(endOfBuffer - 1);
  19214. }
  19215. else
  19216. {
  19217. fs.y2 = fs.y1;
  19218. fs.x2 = fs.x1;
  19219. }
  19220. fs.y1 = fs.x1 = *endOfBuffer;
  19221. }
  19222. }
  19223. jassert (sampsInBuffer >= 0);
  19224. }
  19225. void ResamplingAudioSource::createLowPass (const double frequencyRatio)
  19226. {
  19227. const double proportionalRate = (frequencyRatio > 1.0) ? 0.5 / frequencyRatio
  19228. : 0.5 * frequencyRatio;
  19229. const double n = 1.0 / tan (double_Pi * jmax (0.001, proportionalRate));
  19230. const double nSquared = n * n;
  19231. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  19232. setFilterCoefficients (c1,
  19233. c1 * 2.0f,
  19234. c1,
  19235. 1.0,
  19236. c1 * 2.0 * (1.0 - nSquared),
  19237. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  19238. }
  19239. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  19240. {
  19241. const double a = 1.0 / c4;
  19242. c1 *= a;
  19243. c2 *= a;
  19244. c3 *= a;
  19245. c5 *= a;
  19246. c6 *= a;
  19247. coefficients[0] = c1;
  19248. coefficients[1] = c2;
  19249. coefficients[2] = c3;
  19250. coefficients[3] = c4;
  19251. coefficients[4] = c5;
  19252. coefficients[5] = c6;
  19253. }
  19254. void ResamplingAudioSource::resetFilters()
  19255. {
  19256. zeromem (filterStates, sizeof (filterStates));
  19257. }
  19258. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  19259. {
  19260. while (--num >= 0)
  19261. {
  19262. const double in = *samples;
  19263. double out = coefficients[0] * in
  19264. + coefficients[1] * fs.x1
  19265. + coefficients[2] * fs.x2
  19266. - coefficients[4] * fs.y1
  19267. - coefficients[5] * fs.y2;
  19268. #if JUCE_INTEL
  19269. if (! (out < -1.0e-8 || out > 1.0e-8))
  19270. out = 0;
  19271. #endif
  19272. fs.x2 = fs.x1;
  19273. fs.x1 = in;
  19274. fs.y2 = fs.y1;
  19275. fs.y1 = out;
  19276. *samples++ = (float) out;
  19277. }
  19278. }
  19279. END_JUCE_NAMESPACE
  19280. /*** End of inlined file: juce_ResamplingAudioSource.cpp ***/
  19281. /*** Start of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  19282. BEGIN_JUCE_NAMESPACE
  19283. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  19284. : frequency (1000.0),
  19285. sampleRate (44100.0),
  19286. currentPhase (0.0),
  19287. phasePerSample (0.0),
  19288. amplitude (0.5f)
  19289. {
  19290. }
  19291. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  19292. {
  19293. }
  19294. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  19295. {
  19296. amplitude = newAmplitude;
  19297. }
  19298. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  19299. {
  19300. frequency = newFrequencyHz;
  19301. phasePerSample = 0.0;
  19302. }
  19303. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  19304. double sampleRate_)
  19305. {
  19306. currentPhase = 0.0;
  19307. phasePerSample = 0.0;
  19308. sampleRate = sampleRate_;
  19309. }
  19310. void ToneGeneratorAudioSource::releaseResources()
  19311. {
  19312. }
  19313. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19314. {
  19315. if (phasePerSample == 0.0)
  19316. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  19317. for (int i = 0; i < info.numSamples; ++i)
  19318. {
  19319. const float sample = amplitude * (float) std::sin (currentPhase);
  19320. currentPhase += phasePerSample;
  19321. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  19322. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  19323. }
  19324. }
  19325. END_JUCE_NAMESPACE
  19326. /*** End of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  19327. /*** Start of inlined file: juce_AudioDeviceManager.cpp ***/
  19328. BEGIN_JUCE_NAMESPACE
  19329. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  19330. : sampleRate (0),
  19331. bufferSize (0),
  19332. useDefaultInputChannels (true),
  19333. useDefaultOutputChannels (true)
  19334. {
  19335. }
  19336. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  19337. {
  19338. return outputDeviceName == other.outputDeviceName
  19339. && inputDeviceName == other.inputDeviceName
  19340. && sampleRate == other.sampleRate
  19341. && bufferSize == other.bufferSize
  19342. && inputChannels == other.inputChannels
  19343. && useDefaultInputChannels == other.useDefaultInputChannels
  19344. && outputChannels == other.outputChannels
  19345. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  19346. }
  19347. AudioDeviceManager::AudioDeviceManager()
  19348. : currentAudioDevice (0),
  19349. numInputChansNeeded (0),
  19350. numOutputChansNeeded (2),
  19351. listNeedsScanning (true),
  19352. useInputNames (false),
  19353. inputLevelMeasurementEnabledCount (0),
  19354. inputLevel (0),
  19355. tempBuffer (2, 2),
  19356. defaultMidiOutput (0),
  19357. cpuUsageMs (0),
  19358. timeToCpuScale (0)
  19359. {
  19360. callbackHandler.owner = this;
  19361. }
  19362. AudioDeviceManager::~AudioDeviceManager()
  19363. {
  19364. currentAudioDevice = 0;
  19365. defaultMidiOutput = 0;
  19366. }
  19367. void AudioDeviceManager::createDeviceTypesIfNeeded()
  19368. {
  19369. if (availableDeviceTypes.size() == 0)
  19370. {
  19371. createAudioDeviceTypes (availableDeviceTypes);
  19372. while (lastDeviceTypeConfigs.size() < availableDeviceTypes.size())
  19373. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  19374. if (availableDeviceTypes.size() > 0)
  19375. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  19376. }
  19377. }
  19378. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  19379. {
  19380. scanDevicesIfNeeded();
  19381. return availableDeviceTypes;
  19382. }
  19383. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio();
  19384. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio();
  19385. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI();
  19386. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound();
  19387. AudioIODeviceType* juce_createAudioIODeviceType_ASIO();
  19388. AudioIODeviceType* juce_createAudioIODeviceType_ALSA();
  19389. AudioIODeviceType* juce_createAudioIODeviceType_JACK();
  19390. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  19391. {
  19392. (void) list; // (to avoid 'unused param' warnings)
  19393. #if JUCE_WINDOWS
  19394. #if JUCE_WASAPI
  19395. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  19396. list.add (juce_createAudioIODeviceType_WASAPI());
  19397. #endif
  19398. #if JUCE_DIRECTSOUND
  19399. list.add (juce_createAudioIODeviceType_DirectSound());
  19400. #endif
  19401. #if JUCE_ASIO
  19402. list.add (juce_createAudioIODeviceType_ASIO());
  19403. #endif
  19404. #endif
  19405. #if JUCE_MAC
  19406. list.add (juce_createAudioIODeviceType_CoreAudio());
  19407. #endif
  19408. #if JUCE_IPHONE
  19409. list.add (juce_createAudioIODeviceType_iPhoneAudio());
  19410. #endif
  19411. #if JUCE_LINUX && JUCE_ALSA
  19412. list.add (juce_createAudioIODeviceType_ALSA());
  19413. #endif
  19414. #if JUCE_LINUX && JUCE_JACK
  19415. list.add (juce_createAudioIODeviceType_JACK());
  19416. #endif
  19417. }
  19418. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  19419. const int numOutputChannelsNeeded,
  19420. const XmlElement* const e,
  19421. const bool selectDefaultDeviceOnFailure,
  19422. const String& preferredDefaultDeviceName,
  19423. const AudioDeviceSetup* preferredSetupOptions)
  19424. {
  19425. scanDevicesIfNeeded();
  19426. numInputChansNeeded = numInputChannelsNeeded;
  19427. numOutputChansNeeded = numOutputChannelsNeeded;
  19428. if (e != 0 && e->hasTagName ("DEVICESETUP"))
  19429. {
  19430. lastExplicitSettings = new XmlElement (*e);
  19431. String error;
  19432. AudioDeviceSetup setup;
  19433. if (preferredSetupOptions != 0)
  19434. setup = *preferredSetupOptions;
  19435. if (e->getStringAttribute ("audioDeviceName").isNotEmpty())
  19436. {
  19437. setup.inputDeviceName = setup.outputDeviceName
  19438. = e->getStringAttribute ("audioDeviceName");
  19439. }
  19440. else
  19441. {
  19442. setup.inputDeviceName = e->getStringAttribute ("audioInputDeviceName");
  19443. setup.outputDeviceName = e->getStringAttribute ("audioOutputDeviceName");
  19444. }
  19445. currentDeviceType = e->getStringAttribute ("deviceType");
  19446. if (currentDeviceType.isEmpty())
  19447. {
  19448. AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName);
  19449. if (type != 0)
  19450. currentDeviceType = type->getTypeName();
  19451. else if (availableDeviceTypes.size() > 0)
  19452. currentDeviceType = availableDeviceTypes[0]->getTypeName();
  19453. }
  19454. setup.bufferSize = e->getIntAttribute ("audioDeviceBufferSize");
  19455. setup.sampleRate = e->getDoubleAttribute ("audioDeviceRate");
  19456. setup.inputChannels.parseString (e->getStringAttribute ("audioDeviceInChans", "11"), 2);
  19457. setup.outputChannels.parseString (e->getStringAttribute ("audioDeviceOutChans", "11"), 2);
  19458. setup.useDefaultInputChannels = ! e->hasAttribute ("audioDeviceInChans");
  19459. setup.useDefaultOutputChannels = ! e->hasAttribute ("audioDeviceOutChans");
  19460. error = setAudioDeviceSetup (setup, true);
  19461. midiInsFromXml.clear();
  19462. forEachXmlChildElementWithTagName (*e, c, "MIDIINPUT")
  19463. midiInsFromXml.add (c->getStringAttribute ("name"));
  19464. const StringArray allMidiIns (MidiInput::getDevices());
  19465. for (int i = allMidiIns.size(); --i >= 0;)
  19466. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  19467. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  19468. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  19469. false, preferredDefaultDeviceName);
  19470. setDefaultMidiOutput (e->getStringAttribute ("defaultMidiOutput"));
  19471. return error;
  19472. }
  19473. else
  19474. {
  19475. AudioDeviceSetup setup;
  19476. if (preferredSetupOptions != 0)
  19477. {
  19478. setup = *preferredSetupOptions;
  19479. }
  19480. else if (preferredDefaultDeviceName.isNotEmpty())
  19481. {
  19482. for (int j = availableDeviceTypes.size(); --j >= 0;)
  19483. {
  19484. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  19485. StringArray outs (type->getDeviceNames (false));
  19486. int i;
  19487. for (i = 0; i < outs.size(); ++i)
  19488. {
  19489. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  19490. {
  19491. setup.outputDeviceName = outs[i];
  19492. break;
  19493. }
  19494. }
  19495. StringArray ins (type->getDeviceNames (true));
  19496. for (i = 0; i < ins.size(); ++i)
  19497. {
  19498. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  19499. {
  19500. setup.inputDeviceName = ins[i];
  19501. break;
  19502. }
  19503. }
  19504. }
  19505. }
  19506. insertDefaultDeviceNames (setup);
  19507. return setAudioDeviceSetup (setup, false);
  19508. }
  19509. }
  19510. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  19511. {
  19512. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  19513. if (type != 0)
  19514. {
  19515. if (setup.outputDeviceName.isEmpty())
  19516. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  19517. if (setup.inputDeviceName.isEmpty())
  19518. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  19519. }
  19520. }
  19521. XmlElement* AudioDeviceManager::createStateXml() const
  19522. {
  19523. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  19524. }
  19525. void AudioDeviceManager::scanDevicesIfNeeded()
  19526. {
  19527. if (listNeedsScanning)
  19528. {
  19529. listNeedsScanning = false;
  19530. createDeviceTypesIfNeeded();
  19531. for (int i = availableDeviceTypes.size(); --i >= 0;)
  19532. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  19533. }
  19534. }
  19535. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  19536. {
  19537. scanDevicesIfNeeded();
  19538. for (int i = availableDeviceTypes.size(); --i >= 0;)
  19539. {
  19540. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  19541. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  19542. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  19543. {
  19544. return type;
  19545. }
  19546. }
  19547. return 0;
  19548. }
  19549. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  19550. {
  19551. setup = currentSetup;
  19552. }
  19553. void AudioDeviceManager::deleteCurrentDevice()
  19554. {
  19555. currentAudioDevice = 0;
  19556. currentSetup.inputDeviceName = String::empty;
  19557. currentSetup.outputDeviceName = String::empty;
  19558. }
  19559. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  19560. const bool treatAsChosenDevice)
  19561. {
  19562. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  19563. {
  19564. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  19565. && currentDeviceType != type)
  19566. {
  19567. currentDeviceType = type;
  19568. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  19569. insertDefaultDeviceNames (s);
  19570. setAudioDeviceSetup (s, treatAsChosenDevice);
  19571. sendChangeMessage (this);
  19572. break;
  19573. }
  19574. }
  19575. }
  19576. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  19577. {
  19578. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  19579. if (availableDeviceTypes[i]->getTypeName() == currentDeviceType)
  19580. return availableDeviceTypes[i];
  19581. return availableDeviceTypes[0];
  19582. }
  19583. const String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  19584. const bool treatAsChosenDevice)
  19585. {
  19586. jassert (&newSetup != &currentSetup); // this will have no effect
  19587. if (newSetup == currentSetup && currentAudioDevice != 0)
  19588. return String::empty;
  19589. if (! (newSetup == currentSetup))
  19590. sendChangeMessage (this);
  19591. stopDevice();
  19592. const String newInputDeviceName (numInputChansNeeded == 0 ? String::empty : newSetup.inputDeviceName);
  19593. const String newOutputDeviceName (numOutputChansNeeded == 0 ? String::empty : newSetup.outputDeviceName);
  19594. String error;
  19595. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  19596. if (type == 0 || (newInputDeviceName.isEmpty() && newOutputDeviceName.isEmpty()))
  19597. {
  19598. deleteCurrentDevice();
  19599. if (treatAsChosenDevice)
  19600. updateXml();
  19601. return String::empty;
  19602. }
  19603. if (currentSetup.inputDeviceName != newInputDeviceName
  19604. || currentSetup.outputDeviceName != newOutputDeviceName
  19605. || currentAudioDevice == 0)
  19606. {
  19607. deleteCurrentDevice();
  19608. scanDevicesIfNeeded();
  19609. if (newOutputDeviceName.isNotEmpty()
  19610. && ! type->getDeviceNames (false).contains (newOutputDeviceName))
  19611. {
  19612. return "No such device: " + newOutputDeviceName;
  19613. }
  19614. if (newInputDeviceName.isNotEmpty()
  19615. && ! type->getDeviceNames (true).contains (newInputDeviceName))
  19616. {
  19617. return "No such device: " + newInputDeviceName;
  19618. }
  19619. currentAudioDevice = type->createDevice (newOutputDeviceName, newInputDeviceName);
  19620. if (currentAudioDevice == 0)
  19621. 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!";
  19622. else
  19623. error = currentAudioDevice->getLastError();
  19624. if (error.isNotEmpty())
  19625. {
  19626. deleteCurrentDevice();
  19627. return error;
  19628. }
  19629. if (newSetup.useDefaultInputChannels)
  19630. {
  19631. inputChannels.clear();
  19632. inputChannels.setRange (0, numInputChansNeeded, true);
  19633. }
  19634. if (newSetup.useDefaultOutputChannels)
  19635. {
  19636. outputChannels.clear();
  19637. outputChannels.setRange (0, numOutputChansNeeded, true);
  19638. }
  19639. if (newInputDeviceName.isEmpty())
  19640. inputChannels.clear();
  19641. if (newOutputDeviceName.isEmpty())
  19642. outputChannels.clear();
  19643. }
  19644. if (! newSetup.useDefaultInputChannels)
  19645. inputChannels = newSetup.inputChannels;
  19646. if (! newSetup.useDefaultOutputChannels)
  19647. outputChannels = newSetup.outputChannels;
  19648. currentSetup = newSetup;
  19649. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  19650. error = currentAudioDevice->open (inputChannels,
  19651. outputChannels,
  19652. currentSetup.sampleRate,
  19653. currentSetup.bufferSize);
  19654. if (error.isEmpty())
  19655. {
  19656. currentDeviceType = currentAudioDevice->getTypeName();
  19657. currentAudioDevice->start (&callbackHandler);
  19658. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  19659. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  19660. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  19661. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  19662. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  19663. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  19664. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  19665. if (treatAsChosenDevice)
  19666. updateXml();
  19667. }
  19668. else
  19669. {
  19670. deleteCurrentDevice();
  19671. }
  19672. return error;
  19673. }
  19674. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  19675. {
  19676. jassert (currentAudioDevice != 0);
  19677. if (rate > 0)
  19678. {
  19679. bool ok = false;
  19680. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  19681. {
  19682. const double sr = currentAudioDevice->getSampleRate (i);
  19683. if (sr == rate)
  19684. ok = true;
  19685. }
  19686. if (! ok)
  19687. rate = 0;
  19688. }
  19689. if (rate == 0)
  19690. {
  19691. double lowestAbove44 = 0.0;
  19692. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  19693. {
  19694. const double sr = currentAudioDevice->getSampleRate (i);
  19695. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  19696. lowestAbove44 = sr;
  19697. }
  19698. if (lowestAbove44 == 0.0)
  19699. rate = currentAudioDevice->getSampleRate (0);
  19700. else
  19701. rate = lowestAbove44;
  19702. }
  19703. return rate;
  19704. }
  19705. void AudioDeviceManager::stopDevice()
  19706. {
  19707. if (currentAudioDevice != 0)
  19708. currentAudioDevice->stop();
  19709. testSound = 0;
  19710. }
  19711. void AudioDeviceManager::closeAudioDevice()
  19712. {
  19713. stopDevice();
  19714. currentAudioDevice = 0;
  19715. }
  19716. void AudioDeviceManager::restartLastAudioDevice()
  19717. {
  19718. if (currentAudioDevice == 0)
  19719. {
  19720. if (currentSetup.inputDeviceName.isEmpty()
  19721. && currentSetup.outputDeviceName.isEmpty())
  19722. {
  19723. // This method will only reload the last device that was running
  19724. // before closeAudioDevice() was called - you need to actually open
  19725. // one first, with setAudioDevice().
  19726. jassertfalse;
  19727. return;
  19728. }
  19729. AudioDeviceSetup s (currentSetup);
  19730. setAudioDeviceSetup (s, false);
  19731. }
  19732. }
  19733. void AudioDeviceManager::updateXml()
  19734. {
  19735. lastExplicitSettings = new XmlElement ("DEVICESETUP");
  19736. lastExplicitSettings->setAttribute ("deviceType", currentDeviceType);
  19737. lastExplicitSettings->setAttribute ("audioOutputDeviceName", currentSetup.outputDeviceName);
  19738. lastExplicitSettings->setAttribute ("audioInputDeviceName", currentSetup.inputDeviceName);
  19739. if (currentAudioDevice != 0)
  19740. {
  19741. lastExplicitSettings->setAttribute ("audioDeviceRate", currentAudioDevice->getCurrentSampleRate());
  19742. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  19743. lastExplicitSettings->setAttribute ("audioDeviceBufferSize", currentAudioDevice->getCurrentBufferSizeSamples());
  19744. if (! currentSetup.useDefaultInputChannels)
  19745. lastExplicitSettings->setAttribute ("audioDeviceInChans", currentSetup.inputChannels.toString (2));
  19746. if (! currentSetup.useDefaultOutputChannels)
  19747. lastExplicitSettings->setAttribute ("audioDeviceOutChans", currentSetup.outputChannels.toString (2));
  19748. }
  19749. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  19750. {
  19751. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  19752. m->setAttribute ("name", enabledMidiInputs[i]->getName());
  19753. }
  19754. if (midiInsFromXml.size() > 0)
  19755. {
  19756. // Add any midi devices that have been enabled before, but which aren't currently
  19757. // open because the device has been disconnected.
  19758. const StringArray availableMidiDevices (MidiInput::getDevices());
  19759. for (int i = 0; i < midiInsFromXml.size(); ++i)
  19760. {
  19761. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  19762. {
  19763. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  19764. m->setAttribute ("name", midiInsFromXml[i]);
  19765. }
  19766. }
  19767. }
  19768. if (defaultMidiOutputName.isNotEmpty())
  19769. lastExplicitSettings->setAttribute ("defaultMidiOutput", defaultMidiOutputName);
  19770. }
  19771. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  19772. {
  19773. {
  19774. const ScopedLock sl (audioCallbackLock);
  19775. if (callbacks.contains (newCallback))
  19776. return;
  19777. }
  19778. if (currentAudioDevice != 0 && newCallback != 0)
  19779. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  19780. const ScopedLock sl (audioCallbackLock);
  19781. callbacks.add (newCallback);
  19782. }
  19783. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callback)
  19784. {
  19785. if (callback != 0)
  19786. {
  19787. bool needsDeinitialising = currentAudioDevice != 0;
  19788. {
  19789. const ScopedLock sl (audioCallbackLock);
  19790. needsDeinitialising = needsDeinitialising && callbacks.contains (callback);
  19791. callbacks.removeValue (callback);
  19792. }
  19793. if (needsDeinitialising)
  19794. callback->audioDeviceStopped();
  19795. }
  19796. }
  19797. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  19798. int numInputChannels,
  19799. float** outputChannelData,
  19800. int numOutputChannels,
  19801. int numSamples)
  19802. {
  19803. const ScopedLock sl (audioCallbackLock);
  19804. if (inputLevelMeasurementEnabledCount > 0)
  19805. {
  19806. for (int j = 0; j < numSamples; ++j)
  19807. {
  19808. float s = 0;
  19809. for (int i = 0; i < numInputChannels; ++i)
  19810. s += std::abs (inputChannelData[i][j]);
  19811. s /= numInputChannels;
  19812. const double decayFactor = 0.99992;
  19813. if (s > inputLevel)
  19814. inputLevel = s;
  19815. else if (inputLevel > 0.001f)
  19816. inputLevel *= decayFactor;
  19817. else
  19818. inputLevel = 0;
  19819. }
  19820. }
  19821. if (callbacks.size() > 0)
  19822. {
  19823. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  19824. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  19825. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  19826. outputChannelData, numOutputChannels, numSamples);
  19827. float** const tempChans = tempBuffer.getArrayOfChannels();
  19828. for (int i = callbacks.size(); --i > 0;)
  19829. {
  19830. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  19831. tempChans, numOutputChannels, numSamples);
  19832. for (int chan = 0; chan < numOutputChannels; ++chan)
  19833. {
  19834. const float* const src = tempChans [chan];
  19835. float* const dst = outputChannelData [chan];
  19836. if (src != 0 && dst != 0)
  19837. for (int j = 0; j < numSamples; ++j)
  19838. dst[j] += src[j];
  19839. }
  19840. }
  19841. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  19842. const double filterAmount = 0.2;
  19843. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  19844. }
  19845. else
  19846. {
  19847. for (int i = 0; i < numOutputChannels; ++i)
  19848. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  19849. }
  19850. if (testSound != 0)
  19851. {
  19852. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  19853. const float* const src = testSound->getSampleData (0, testSoundPosition);
  19854. for (int i = 0; i < numOutputChannels; ++i)
  19855. for (int j = 0; j < numSamps; ++j)
  19856. outputChannelData [i][j] += src[j];
  19857. testSoundPosition += numSamps;
  19858. if (testSoundPosition >= testSound->getNumSamples())
  19859. testSound = 0;
  19860. }
  19861. }
  19862. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  19863. {
  19864. cpuUsageMs = 0;
  19865. const double sampleRate = device->getCurrentSampleRate();
  19866. const int blockSize = device->getCurrentBufferSizeSamples();
  19867. if (sampleRate > 0.0 && blockSize > 0)
  19868. {
  19869. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  19870. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  19871. }
  19872. {
  19873. const ScopedLock sl (audioCallbackLock);
  19874. for (int i = callbacks.size(); --i >= 0;)
  19875. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  19876. }
  19877. sendChangeMessage (this);
  19878. }
  19879. void AudioDeviceManager::audioDeviceStoppedInt()
  19880. {
  19881. cpuUsageMs = 0;
  19882. timeToCpuScale = 0;
  19883. sendChangeMessage (this);
  19884. const ScopedLock sl (audioCallbackLock);
  19885. for (int i = callbacks.size(); --i >= 0;)
  19886. callbacks.getUnchecked(i)->audioDeviceStopped();
  19887. }
  19888. double AudioDeviceManager::getCpuUsage() const
  19889. {
  19890. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  19891. }
  19892. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  19893. const bool enabled)
  19894. {
  19895. if (enabled != isMidiInputEnabled (name))
  19896. {
  19897. if (enabled)
  19898. {
  19899. const int index = MidiInput::getDevices().indexOf (name);
  19900. if (index >= 0)
  19901. {
  19902. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  19903. if (min != 0)
  19904. {
  19905. enabledMidiInputs.add (min);
  19906. min->start();
  19907. }
  19908. }
  19909. }
  19910. else
  19911. {
  19912. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19913. if (enabledMidiInputs[i]->getName() == name)
  19914. enabledMidiInputs.remove (i);
  19915. }
  19916. updateXml();
  19917. sendChangeMessage (this);
  19918. }
  19919. }
  19920. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  19921. {
  19922. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19923. if (enabledMidiInputs[i]->getName() == name)
  19924. return true;
  19925. return false;
  19926. }
  19927. void AudioDeviceManager::addMidiInputCallback (const String& name,
  19928. MidiInputCallback* callback)
  19929. {
  19930. removeMidiInputCallback (name, callback);
  19931. if (name.isEmpty())
  19932. {
  19933. midiCallbacks.add (callback);
  19934. midiCallbackDevices.add (0);
  19935. }
  19936. else
  19937. {
  19938. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19939. {
  19940. if (enabledMidiInputs[i]->getName() == name)
  19941. {
  19942. const ScopedLock sl (midiCallbackLock);
  19943. midiCallbacks.add (callback);
  19944. midiCallbackDevices.add (enabledMidiInputs[i]);
  19945. break;
  19946. }
  19947. }
  19948. }
  19949. }
  19950. void AudioDeviceManager::removeMidiInputCallback (const String& name,
  19951. MidiInputCallback* /*callback*/)
  19952. {
  19953. const ScopedLock sl (midiCallbackLock);
  19954. for (int i = midiCallbacks.size(); --i >= 0;)
  19955. {
  19956. String devName;
  19957. if (midiCallbackDevices.getUnchecked(i) != 0)
  19958. devName = midiCallbackDevices.getUnchecked(i)->getName();
  19959. if (devName == name)
  19960. {
  19961. midiCallbacks.remove (i);
  19962. midiCallbackDevices.remove (i);
  19963. }
  19964. }
  19965. }
  19966. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  19967. const MidiMessage& message)
  19968. {
  19969. if (! message.isActiveSense())
  19970. {
  19971. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  19972. const ScopedLock sl (midiCallbackLock);
  19973. for (int i = midiCallbackDevices.size(); --i >= 0;)
  19974. {
  19975. MidiInput* const md = midiCallbackDevices.getUnchecked(i);
  19976. if (md == source || (md == 0 && isDefaultSource))
  19977. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  19978. }
  19979. }
  19980. }
  19981. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  19982. {
  19983. if (defaultMidiOutputName != deviceName)
  19984. {
  19985. SortedSet <AudioIODeviceCallback*> oldCallbacks;
  19986. {
  19987. const ScopedLock sl (audioCallbackLock);
  19988. oldCallbacks = callbacks;
  19989. callbacks.clear();
  19990. }
  19991. if (currentAudioDevice != 0)
  19992. for (int i = oldCallbacks.size(); --i >= 0;)
  19993. oldCallbacks.getUnchecked(i)->audioDeviceStopped();
  19994. defaultMidiOutput = 0;
  19995. defaultMidiOutputName = deviceName;
  19996. if (deviceName.isNotEmpty())
  19997. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  19998. if (currentAudioDevice != 0)
  19999. for (int i = oldCallbacks.size(); --i >= 0;)
  20000. oldCallbacks.getUnchecked(i)->audioDeviceAboutToStart (currentAudioDevice);
  20001. {
  20002. const ScopedLock sl (audioCallbackLock);
  20003. callbacks = oldCallbacks;
  20004. }
  20005. updateXml();
  20006. sendChangeMessage (this);
  20007. }
  20008. }
  20009. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  20010. int numInputChannels,
  20011. float** outputChannelData,
  20012. int numOutputChannels,
  20013. int numSamples)
  20014. {
  20015. owner->audioDeviceIOCallbackInt (inputChannelData, numInputChannels, outputChannelData, numOutputChannels, numSamples);
  20016. }
  20017. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  20018. {
  20019. owner->audioDeviceAboutToStartInt (device);
  20020. }
  20021. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  20022. {
  20023. owner->audioDeviceStoppedInt();
  20024. }
  20025. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  20026. {
  20027. owner->handleIncomingMidiMessageInt (source, message);
  20028. }
  20029. void AudioDeviceManager::playTestSound()
  20030. {
  20031. { // cunningly nested to swap, unlock and delete in that order.
  20032. ScopedPointer <AudioSampleBuffer> oldSound;
  20033. {
  20034. const ScopedLock sl (audioCallbackLock);
  20035. oldSound = testSound;
  20036. }
  20037. }
  20038. testSoundPosition = 0;
  20039. if (currentAudioDevice != 0)
  20040. {
  20041. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  20042. const int soundLength = (int) sampleRate;
  20043. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  20044. float* samples = newSound->getSampleData (0);
  20045. const double frequency = MidiMessage::getMidiNoteInHertz (80);
  20046. const float amplitude = 0.5f;
  20047. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20048. for (int i = 0; i < soundLength; ++i)
  20049. samples[i] = amplitude * (float) std::sin (i * phasePerSample);
  20050. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  20051. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  20052. const ScopedLock sl (audioCallbackLock);
  20053. testSound = newSound;
  20054. }
  20055. }
  20056. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  20057. {
  20058. const ScopedLock sl (audioCallbackLock);
  20059. if (enableMeasurement)
  20060. ++inputLevelMeasurementEnabledCount;
  20061. else
  20062. --inputLevelMeasurementEnabledCount;
  20063. inputLevel = 0;
  20064. }
  20065. double AudioDeviceManager::getCurrentInputLevel() const
  20066. {
  20067. jassert (inputLevelMeasurementEnabledCount > 0); // you need to call enableInputLevelMeasurement() before using this!
  20068. return inputLevel;
  20069. }
  20070. END_JUCE_NAMESPACE
  20071. /*** End of inlined file: juce_AudioDeviceManager.cpp ***/
  20072. /*** Start of inlined file: juce_AudioIODevice.cpp ***/
  20073. BEGIN_JUCE_NAMESPACE
  20074. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  20075. : name (deviceName),
  20076. typeName (typeName_)
  20077. {
  20078. }
  20079. AudioIODevice::~AudioIODevice()
  20080. {
  20081. }
  20082. bool AudioIODevice::hasControlPanel() const
  20083. {
  20084. return false;
  20085. }
  20086. bool AudioIODevice::showControlPanel()
  20087. {
  20088. jassertfalse; // this should only be called for devices which return true from
  20089. // their hasControlPanel() method.
  20090. return false;
  20091. }
  20092. END_JUCE_NAMESPACE
  20093. /*** End of inlined file: juce_AudioIODevice.cpp ***/
  20094. /*** Start of inlined file: juce_AudioIODeviceType.cpp ***/
  20095. BEGIN_JUCE_NAMESPACE
  20096. AudioIODeviceType::AudioIODeviceType (const String& name)
  20097. : typeName (name)
  20098. {
  20099. }
  20100. AudioIODeviceType::~AudioIODeviceType()
  20101. {
  20102. }
  20103. END_JUCE_NAMESPACE
  20104. /*** End of inlined file: juce_AudioIODeviceType.cpp ***/
  20105. /*** Start of inlined file: juce_MidiOutput.cpp ***/
  20106. BEGIN_JUCE_NAMESPACE
  20107. MidiOutput::MidiOutput()
  20108. : Thread ("midi out"),
  20109. internal (0),
  20110. firstMessage (0)
  20111. {
  20112. }
  20113. MidiOutput::PendingMessage::PendingMessage (const uint8* const data, const int len,
  20114. const double sampleNumber)
  20115. : message (data, len, sampleNumber)
  20116. {
  20117. }
  20118. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  20119. const double millisecondCounterToStartAt,
  20120. double samplesPerSecondForBuffer)
  20121. {
  20122. // You've got to call startBackgroundThread() for this to actually work..
  20123. jassert (isThreadRunning());
  20124. // this needs to be a value in the future - RTFM for this method!
  20125. jassert (millisecondCounterToStartAt > 0);
  20126. const double timeScaleFactor = 1000.0 / samplesPerSecondForBuffer;
  20127. MidiBuffer::Iterator i (buffer);
  20128. const uint8* data;
  20129. int len, time;
  20130. while (i.getNextEvent (data, len, time))
  20131. {
  20132. const double eventTime = millisecondCounterToStartAt + timeScaleFactor * time;
  20133. PendingMessage* const m
  20134. = new PendingMessage (data, len, eventTime);
  20135. const ScopedLock sl (lock);
  20136. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  20137. {
  20138. m->next = firstMessage;
  20139. firstMessage = m;
  20140. }
  20141. else
  20142. {
  20143. PendingMessage* mm = firstMessage;
  20144. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  20145. mm = mm->next;
  20146. m->next = mm->next;
  20147. mm->next = m;
  20148. }
  20149. }
  20150. notify();
  20151. }
  20152. void MidiOutput::clearAllPendingMessages()
  20153. {
  20154. const ScopedLock sl (lock);
  20155. while (firstMessage != 0)
  20156. {
  20157. PendingMessage* const m = firstMessage;
  20158. firstMessage = firstMessage->next;
  20159. delete m;
  20160. }
  20161. }
  20162. void MidiOutput::startBackgroundThread()
  20163. {
  20164. startThread (9);
  20165. }
  20166. void MidiOutput::stopBackgroundThread()
  20167. {
  20168. stopThread (5000);
  20169. }
  20170. void MidiOutput::run()
  20171. {
  20172. while (! threadShouldExit())
  20173. {
  20174. uint32 now = Time::getMillisecondCounter();
  20175. uint32 eventTime = 0;
  20176. uint32 timeToWait = 500;
  20177. PendingMessage* message;
  20178. {
  20179. const ScopedLock sl (lock);
  20180. message = firstMessage;
  20181. if (message != 0)
  20182. {
  20183. eventTime = roundToInt (message->message.getTimeStamp());
  20184. if (eventTime > now + 20)
  20185. {
  20186. timeToWait = eventTime - (now + 20);
  20187. message = 0;
  20188. }
  20189. else
  20190. {
  20191. firstMessage = message->next;
  20192. }
  20193. }
  20194. }
  20195. if (message != 0)
  20196. {
  20197. if (eventTime > now)
  20198. {
  20199. Time::waitForMillisecondCounter (eventTime);
  20200. if (threadShouldExit())
  20201. break;
  20202. }
  20203. if (eventTime > now - 200)
  20204. sendMessageNow (message->message);
  20205. delete message;
  20206. }
  20207. else
  20208. {
  20209. jassert (timeToWait < 1000 * 30);
  20210. wait (timeToWait);
  20211. }
  20212. }
  20213. clearAllPendingMessages();
  20214. }
  20215. END_JUCE_NAMESPACE
  20216. /*** End of inlined file: juce_MidiOutput.cpp ***/
  20217. /*** Start of inlined file: juce_AudioDataConverters.cpp ***/
  20218. BEGIN_JUCE_NAMESPACE
  20219. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20220. {
  20221. const double maxVal = (double) 0x7fff;
  20222. char* intData = static_cast <char*> (dest);
  20223. if (dest != (void*) source || destBytesPerSample <= 4)
  20224. {
  20225. for (int i = 0; i < numSamples; ++i)
  20226. {
  20227. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20228. intData += destBytesPerSample;
  20229. }
  20230. }
  20231. else
  20232. {
  20233. intData += destBytesPerSample * numSamples;
  20234. for (int i = numSamples; --i >= 0;)
  20235. {
  20236. intData -= destBytesPerSample;
  20237. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20238. }
  20239. }
  20240. }
  20241. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20242. {
  20243. const double maxVal = (double) 0x7fff;
  20244. char* intData = static_cast <char*> (dest);
  20245. if (dest != (void*) source || destBytesPerSample <= 4)
  20246. {
  20247. for (int i = 0; i < numSamples; ++i)
  20248. {
  20249. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20250. intData += destBytesPerSample;
  20251. }
  20252. }
  20253. else
  20254. {
  20255. intData += destBytesPerSample * numSamples;
  20256. for (int i = numSamples; --i >= 0;)
  20257. {
  20258. intData -= destBytesPerSample;
  20259. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20260. }
  20261. }
  20262. }
  20263. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20264. {
  20265. const double maxVal = (double) 0x7fffff;
  20266. char* intData = static_cast <char*> (dest);
  20267. if (dest != (void*) source || destBytesPerSample <= 4)
  20268. {
  20269. for (int i = 0; i < numSamples; ++i)
  20270. {
  20271. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20272. intData += destBytesPerSample;
  20273. }
  20274. }
  20275. else
  20276. {
  20277. intData += destBytesPerSample * numSamples;
  20278. for (int i = numSamples; --i >= 0;)
  20279. {
  20280. intData -= destBytesPerSample;
  20281. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20282. }
  20283. }
  20284. }
  20285. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20286. {
  20287. const double maxVal = (double) 0x7fffff;
  20288. char* intData = static_cast <char*> (dest);
  20289. if (dest != (void*) source || destBytesPerSample <= 4)
  20290. {
  20291. for (int i = 0; i < numSamples; ++i)
  20292. {
  20293. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20294. intData += destBytesPerSample;
  20295. }
  20296. }
  20297. else
  20298. {
  20299. intData += destBytesPerSample * numSamples;
  20300. for (int i = numSamples; --i >= 0;)
  20301. {
  20302. intData -= destBytesPerSample;
  20303. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20304. }
  20305. }
  20306. }
  20307. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20308. {
  20309. const double maxVal = (double) 0x7fffffff;
  20310. char* intData = static_cast <char*> (dest);
  20311. if (dest != (void*) source || destBytesPerSample <= 4)
  20312. {
  20313. for (int i = 0; i < numSamples; ++i)
  20314. {
  20315. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20316. intData += destBytesPerSample;
  20317. }
  20318. }
  20319. else
  20320. {
  20321. intData += destBytesPerSample * numSamples;
  20322. for (int i = numSamples; --i >= 0;)
  20323. {
  20324. intData -= destBytesPerSample;
  20325. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20326. }
  20327. }
  20328. }
  20329. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20330. {
  20331. const double maxVal = (double) 0x7fffffff;
  20332. char* intData = static_cast <char*> (dest);
  20333. if (dest != (void*) source || destBytesPerSample <= 4)
  20334. {
  20335. for (int i = 0; i < numSamples; ++i)
  20336. {
  20337. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20338. intData += destBytesPerSample;
  20339. }
  20340. }
  20341. else
  20342. {
  20343. intData += destBytesPerSample * numSamples;
  20344. for (int i = numSamples; --i >= 0;)
  20345. {
  20346. intData -= destBytesPerSample;
  20347. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20348. }
  20349. }
  20350. }
  20351. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20352. {
  20353. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  20354. char* d = static_cast <char*> (dest);
  20355. for (int i = 0; i < numSamples; ++i)
  20356. {
  20357. *(float*) d = source[i];
  20358. #if JUCE_BIG_ENDIAN
  20359. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  20360. #endif
  20361. d += destBytesPerSample;
  20362. }
  20363. }
  20364. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20365. {
  20366. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  20367. char* d = static_cast <char*> (dest);
  20368. for (int i = 0; i < numSamples; ++i)
  20369. {
  20370. *(float*) d = source[i];
  20371. #if JUCE_LITTLE_ENDIAN
  20372. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  20373. #endif
  20374. d += destBytesPerSample;
  20375. }
  20376. }
  20377. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20378. {
  20379. const float scale = 1.0f / 0x7fff;
  20380. const char* intData = static_cast <const char*> (source);
  20381. if (source != (void*) dest || srcBytesPerSample >= 4)
  20382. {
  20383. for (int i = 0; i < numSamples; ++i)
  20384. {
  20385. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  20386. intData += srcBytesPerSample;
  20387. }
  20388. }
  20389. else
  20390. {
  20391. intData += srcBytesPerSample * numSamples;
  20392. for (int i = numSamples; --i >= 0;)
  20393. {
  20394. intData -= srcBytesPerSample;
  20395. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  20396. }
  20397. }
  20398. }
  20399. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20400. {
  20401. const float scale = 1.0f / 0x7fff;
  20402. const char* intData = static_cast <const char*> (source);
  20403. if (source != (void*) dest || srcBytesPerSample >= 4)
  20404. {
  20405. for (int i = 0; i < numSamples; ++i)
  20406. {
  20407. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  20408. intData += srcBytesPerSample;
  20409. }
  20410. }
  20411. else
  20412. {
  20413. intData += srcBytesPerSample * numSamples;
  20414. for (int i = numSamples; --i >= 0;)
  20415. {
  20416. intData -= srcBytesPerSample;
  20417. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  20418. }
  20419. }
  20420. }
  20421. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20422. {
  20423. const float scale = 1.0f / 0x7fffff;
  20424. const char* intData = static_cast <const char*> (source);
  20425. if (source != (void*) dest || srcBytesPerSample >= 4)
  20426. {
  20427. for (int i = 0; i < numSamples; ++i)
  20428. {
  20429. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  20430. intData += srcBytesPerSample;
  20431. }
  20432. }
  20433. else
  20434. {
  20435. intData += srcBytesPerSample * numSamples;
  20436. for (int i = numSamples; --i >= 0;)
  20437. {
  20438. intData -= srcBytesPerSample;
  20439. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  20440. }
  20441. }
  20442. }
  20443. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20444. {
  20445. const float scale = 1.0f / 0x7fffff;
  20446. const char* intData = static_cast <const char*> (source);
  20447. if (source != (void*) dest || srcBytesPerSample >= 4)
  20448. {
  20449. for (int i = 0; i < numSamples; ++i)
  20450. {
  20451. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  20452. intData += srcBytesPerSample;
  20453. }
  20454. }
  20455. else
  20456. {
  20457. intData += srcBytesPerSample * numSamples;
  20458. for (int i = numSamples; --i >= 0;)
  20459. {
  20460. intData -= srcBytesPerSample;
  20461. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  20462. }
  20463. }
  20464. }
  20465. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20466. {
  20467. const float scale = 1.0f / 0x7fffffff;
  20468. const char* intData = static_cast <const char*> (source);
  20469. if (source != (void*) dest || srcBytesPerSample >= 4)
  20470. {
  20471. for (int i = 0; i < numSamples; ++i)
  20472. {
  20473. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  20474. intData += srcBytesPerSample;
  20475. }
  20476. }
  20477. else
  20478. {
  20479. intData += srcBytesPerSample * numSamples;
  20480. for (int i = numSamples; --i >= 0;)
  20481. {
  20482. intData -= srcBytesPerSample;
  20483. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  20484. }
  20485. }
  20486. }
  20487. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20488. {
  20489. const float scale = 1.0f / 0x7fffffff;
  20490. const char* intData = static_cast <const char*> (source);
  20491. if (source != (void*) dest || srcBytesPerSample >= 4)
  20492. {
  20493. for (int i = 0; i < numSamples; ++i)
  20494. {
  20495. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  20496. intData += srcBytesPerSample;
  20497. }
  20498. }
  20499. else
  20500. {
  20501. intData += srcBytesPerSample * numSamples;
  20502. for (int i = numSamples; --i >= 0;)
  20503. {
  20504. intData -= srcBytesPerSample;
  20505. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  20506. }
  20507. }
  20508. }
  20509. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20510. {
  20511. const char* s = static_cast <const char*> (source);
  20512. for (int i = 0; i < numSamples; ++i)
  20513. {
  20514. dest[i] = *(float*)s;
  20515. #if JUCE_BIG_ENDIAN
  20516. uint32* const d = (uint32*) (dest + i);
  20517. *d = ByteOrder::swap (*d);
  20518. #endif
  20519. s += srcBytesPerSample;
  20520. }
  20521. }
  20522. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  20523. {
  20524. const char* s = static_cast <const char*> (source);
  20525. for (int i = 0; i < numSamples; ++i)
  20526. {
  20527. dest[i] = *(float*)s;
  20528. #if JUCE_LITTLE_ENDIAN
  20529. uint32* const d = (uint32*) (dest + i);
  20530. *d = ByteOrder::swap (*d);
  20531. #endif
  20532. s += srcBytesPerSample;
  20533. }
  20534. }
  20535. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  20536. const float* const source,
  20537. void* const dest,
  20538. const int numSamples)
  20539. {
  20540. switch (destFormat)
  20541. {
  20542. case int16LE:
  20543. convertFloatToInt16LE (source, dest, numSamples);
  20544. break;
  20545. case int16BE:
  20546. convertFloatToInt16BE (source, dest, numSamples);
  20547. break;
  20548. case int24LE:
  20549. convertFloatToInt24LE (source, dest, numSamples);
  20550. break;
  20551. case int24BE:
  20552. convertFloatToInt24BE (source, dest, numSamples);
  20553. break;
  20554. case int32LE:
  20555. convertFloatToInt32LE (source, dest, numSamples);
  20556. break;
  20557. case int32BE:
  20558. convertFloatToInt32BE (source, dest, numSamples);
  20559. break;
  20560. case float32LE:
  20561. convertFloatToFloat32LE (source, dest, numSamples);
  20562. break;
  20563. case float32BE:
  20564. convertFloatToFloat32BE (source, dest, numSamples);
  20565. break;
  20566. default:
  20567. jassertfalse;
  20568. break;
  20569. }
  20570. }
  20571. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  20572. const void* const source,
  20573. float* const dest,
  20574. const int numSamples)
  20575. {
  20576. switch (sourceFormat)
  20577. {
  20578. case int16LE:
  20579. convertInt16LEToFloat (source, dest, numSamples);
  20580. break;
  20581. case int16BE:
  20582. convertInt16BEToFloat (source, dest, numSamples);
  20583. break;
  20584. case int24LE:
  20585. convertInt24LEToFloat (source, dest, numSamples);
  20586. break;
  20587. case int24BE:
  20588. convertInt24BEToFloat (source, dest, numSamples);
  20589. break;
  20590. case int32LE:
  20591. convertInt32LEToFloat (source, dest, numSamples);
  20592. break;
  20593. case int32BE:
  20594. convertInt32BEToFloat (source, dest, numSamples);
  20595. break;
  20596. case float32LE:
  20597. convertFloat32LEToFloat (source, dest, numSamples);
  20598. break;
  20599. case float32BE:
  20600. convertFloat32BEToFloat (source, dest, numSamples);
  20601. break;
  20602. default:
  20603. jassertfalse;
  20604. break;
  20605. }
  20606. }
  20607. void AudioDataConverters::interleaveSamples (const float** const source,
  20608. float* const dest,
  20609. const int numSamples,
  20610. const int numChannels)
  20611. {
  20612. for (int chan = 0; chan < numChannels; ++chan)
  20613. {
  20614. int i = chan;
  20615. const float* src = source [chan];
  20616. for (int j = 0; j < numSamples; ++j)
  20617. {
  20618. dest [i] = src [j];
  20619. i += numChannels;
  20620. }
  20621. }
  20622. }
  20623. void AudioDataConverters::deinterleaveSamples (const float* const source,
  20624. float** const dest,
  20625. const int numSamples,
  20626. const int numChannels)
  20627. {
  20628. for (int chan = 0; chan < numChannels; ++chan)
  20629. {
  20630. int i = chan;
  20631. float* dst = dest [chan];
  20632. for (int j = 0; j < numSamples; ++j)
  20633. {
  20634. dst [j] = source [i];
  20635. i += numChannels;
  20636. }
  20637. }
  20638. }
  20639. END_JUCE_NAMESPACE
  20640. /*** End of inlined file: juce_AudioDataConverters.cpp ***/
  20641. /*** Start of inlined file: juce_AudioSampleBuffer.cpp ***/
  20642. BEGIN_JUCE_NAMESPACE
  20643. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  20644. const int numSamples) throw()
  20645. : numChannels (numChannels_),
  20646. size (numSamples)
  20647. {
  20648. jassert (numSamples >= 0);
  20649. jassert (numChannels_ > 0);
  20650. allocateData();
  20651. }
  20652. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  20653. : numChannels (other.numChannels),
  20654. size (other.size)
  20655. {
  20656. allocateData();
  20657. const size_t numBytes = size * sizeof (float);
  20658. for (int i = 0; i < numChannels; ++i)
  20659. memcpy (channels[i], other.channels[i], numBytes);
  20660. }
  20661. void AudioSampleBuffer::allocateData()
  20662. {
  20663. const size_t channelListSize = (numChannels + 1) * sizeof (float*);
  20664. allocatedBytes = (int) (numChannels * size * sizeof (float) + channelListSize + 32);
  20665. allocatedData.malloc (allocatedBytes);
  20666. channels = reinterpret_cast <float**> (allocatedData.getData());
  20667. float* chan = (float*) (allocatedData + channelListSize);
  20668. for (int i = 0; i < numChannels; ++i)
  20669. {
  20670. channels[i] = chan;
  20671. chan += size;
  20672. }
  20673. channels [numChannels] = 0;
  20674. }
  20675. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  20676. const int numChannels_,
  20677. const int numSamples) throw()
  20678. : numChannels (numChannels_),
  20679. size (numSamples),
  20680. allocatedBytes (0)
  20681. {
  20682. jassert (numChannels_ > 0);
  20683. allocateChannels (dataToReferTo);
  20684. }
  20685. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  20686. const int newNumChannels,
  20687. const int newNumSamples) throw()
  20688. {
  20689. jassert (newNumChannels > 0);
  20690. allocatedBytes = 0;
  20691. allocatedData.free();
  20692. numChannels = newNumChannels;
  20693. size = newNumSamples;
  20694. allocateChannels (dataToReferTo);
  20695. }
  20696. void AudioSampleBuffer::allocateChannels (float** const dataToReferTo)
  20697. {
  20698. // (try to avoid doing a malloc here, as that'll blow up things like Pro-Tools)
  20699. if (numChannels < numElementsInArray (preallocatedChannelSpace))
  20700. {
  20701. channels = static_cast <float**> (preallocatedChannelSpace);
  20702. }
  20703. else
  20704. {
  20705. allocatedData.malloc (numChannels + 1, sizeof (float*));
  20706. channels = reinterpret_cast <float**> (allocatedData.getData());
  20707. }
  20708. for (int i = 0; i < numChannels; ++i)
  20709. {
  20710. // you have to pass in the same number of valid pointers as numChannels
  20711. jassert (dataToReferTo[i] != 0);
  20712. channels[i] = dataToReferTo[i];
  20713. }
  20714. channels [numChannels] = 0;
  20715. }
  20716. AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  20717. {
  20718. if (this != &other)
  20719. {
  20720. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  20721. const size_t numBytes = size * sizeof (float);
  20722. for (int i = 0; i < numChannels; ++i)
  20723. memcpy (channels[i], other.channels[i], numBytes);
  20724. }
  20725. return *this;
  20726. }
  20727. AudioSampleBuffer::~AudioSampleBuffer() throw()
  20728. {
  20729. }
  20730. void AudioSampleBuffer::setSize (const int newNumChannels,
  20731. const int newNumSamples,
  20732. const bool keepExistingContent,
  20733. const bool clearExtraSpace,
  20734. const bool avoidReallocating) throw()
  20735. {
  20736. jassert (newNumChannels > 0);
  20737. if (newNumSamples != size || newNumChannels != numChannels)
  20738. {
  20739. const size_t channelListSize = (newNumChannels + 1) * sizeof (float*);
  20740. const size_t newTotalBytes = (newNumChannels * newNumSamples * sizeof (float)) + channelListSize + 32;
  20741. if (keepExistingContent)
  20742. {
  20743. HeapBlock <char> newData;
  20744. newData.allocate (newTotalBytes, clearExtraSpace);
  20745. const int numChansToCopy = jmin (numChannels, newNumChannels);
  20746. const size_t numBytesToCopy = sizeof (float) * jmin (newNumSamples, size);
  20747. float** const newChannels = reinterpret_cast <float**> (newData.getData());
  20748. float* newChan = reinterpret_cast <float*> (newData + channelListSize);
  20749. for (int i = 0; i < numChansToCopy; ++i)
  20750. {
  20751. memcpy (newChan, channels[i], numBytesToCopy);
  20752. newChannels[i] = newChan;
  20753. newChan += newNumSamples;
  20754. }
  20755. allocatedData.swapWith (newData);
  20756. allocatedBytes = (int) newTotalBytes;
  20757. channels = newChannels;
  20758. }
  20759. else
  20760. {
  20761. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  20762. {
  20763. if (clearExtraSpace)
  20764. zeromem (allocatedData, newTotalBytes);
  20765. }
  20766. else
  20767. {
  20768. allocatedBytes = newTotalBytes;
  20769. allocatedData.allocate (newTotalBytes, clearExtraSpace);
  20770. channels = reinterpret_cast <float**> (allocatedData.getData());
  20771. }
  20772. float* chan = reinterpret_cast <float*> (allocatedData + channelListSize);
  20773. for (int i = 0; i < newNumChannels; ++i)
  20774. {
  20775. channels[i] = chan;
  20776. chan += newNumSamples;
  20777. }
  20778. }
  20779. channels [newNumChannels] = 0;
  20780. size = newNumSamples;
  20781. numChannels = newNumChannels;
  20782. }
  20783. }
  20784. void AudioSampleBuffer::clear() throw()
  20785. {
  20786. for (int i = 0; i < numChannels; ++i)
  20787. zeromem (channels[i], size * sizeof (float));
  20788. }
  20789. void AudioSampleBuffer::clear (const int startSample,
  20790. const int numSamples) throw()
  20791. {
  20792. jassert (startSample >= 0 && startSample + numSamples <= size);
  20793. for (int i = 0; i < numChannels; ++i)
  20794. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  20795. }
  20796. void AudioSampleBuffer::clear (const int channel,
  20797. const int startSample,
  20798. const int numSamples) throw()
  20799. {
  20800. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20801. jassert (startSample >= 0 && startSample + numSamples <= size);
  20802. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  20803. }
  20804. void AudioSampleBuffer::applyGain (const int channel,
  20805. const int startSample,
  20806. int numSamples,
  20807. const float gain) throw()
  20808. {
  20809. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20810. jassert (startSample >= 0 && startSample + numSamples <= size);
  20811. if (gain != 1.0f)
  20812. {
  20813. float* d = channels [channel] + startSample;
  20814. if (gain == 0.0f)
  20815. {
  20816. zeromem (d, sizeof (float) * numSamples);
  20817. }
  20818. else
  20819. {
  20820. while (--numSamples >= 0)
  20821. *d++ *= gain;
  20822. }
  20823. }
  20824. }
  20825. void AudioSampleBuffer::applyGainRamp (const int channel,
  20826. const int startSample,
  20827. int numSamples,
  20828. float startGain,
  20829. float endGain) throw()
  20830. {
  20831. if (startGain == endGain)
  20832. {
  20833. applyGain (channel, startSample, numSamples, startGain);
  20834. }
  20835. else
  20836. {
  20837. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20838. jassert (startSample >= 0 && startSample + numSamples <= size);
  20839. const float increment = (endGain - startGain) / numSamples;
  20840. float* d = channels [channel] + startSample;
  20841. while (--numSamples >= 0)
  20842. {
  20843. *d++ *= startGain;
  20844. startGain += increment;
  20845. }
  20846. }
  20847. }
  20848. void AudioSampleBuffer::applyGain (const int startSample,
  20849. const int numSamples,
  20850. const float gain) throw()
  20851. {
  20852. for (int i = 0; i < numChannels; ++i)
  20853. applyGain (i, startSample, numSamples, gain);
  20854. }
  20855. void AudioSampleBuffer::addFrom (const int destChannel,
  20856. const int destStartSample,
  20857. const AudioSampleBuffer& source,
  20858. const int sourceChannel,
  20859. const int sourceStartSample,
  20860. int numSamples,
  20861. const float gain) throw()
  20862. {
  20863. jassert (&source != this || sourceChannel != destChannel);
  20864. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20865. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20866. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  20867. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  20868. if (gain != 0.0f && numSamples > 0)
  20869. {
  20870. float* d = channels [destChannel] + destStartSample;
  20871. const float* s = source.channels [sourceChannel] + sourceStartSample;
  20872. if (gain != 1.0f)
  20873. {
  20874. while (--numSamples >= 0)
  20875. *d++ += gain * *s++;
  20876. }
  20877. else
  20878. {
  20879. while (--numSamples >= 0)
  20880. *d++ += *s++;
  20881. }
  20882. }
  20883. }
  20884. void AudioSampleBuffer::addFrom (const int destChannel,
  20885. const int destStartSample,
  20886. const float* source,
  20887. int numSamples,
  20888. const float gain) throw()
  20889. {
  20890. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20891. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20892. jassert (source != 0);
  20893. if (gain != 0.0f && numSamples > 0)
  20894. {
  20895. float* d = channels [destChannel] + destStartSample;
  20896. if (gain != 1.0f)
  20897. {
  20898. while (--numSamples >= 0)
  20899. *d++ += gain * *source++;
  20900. }
  20901. else
  20902. {
  20903. while (--numSamples >= 0)
  20904. *d++ += *source++;
  20905. }
  20906. }
  20907. }
  20908. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  20909. const int destStartSample,
  20910. const float* source,
  20911. int numSamples,
  20912. float startGain,
  20913. const float endGain) throw()
  20914. {
  20915. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20916. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20917. jassert (source != 0);
  20918. if (startGain == endGain)
  20919. {
  20920. addFrom (destChannel,
  20921. destStartSample,
  20922. source,
  20923. numSamples,
  20924. startGain);
  20925. }
  20926. else
  20927. {
  20928. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  20929. {
  20930. const float increment = (endGain - startGain) / numSamples;
  20931. float* d = channels [destChannel] + destStartSample;
  20932. while (--numSamples >= 0)
  20933. {
  20934. *d++ += startGain * *source++;
  20935. startGain += increment;
  20936. }
  20937. }
  20938. }
  20939. }
  20940. void AudioSampleBuffer::copyFrom (const int destChannel,
  20941. const int destStartSample,
  20942. const AudioSampleBuffer& source,
  20943. const int sourceChannel,
  20944. const int sourceStartSample,
  20945. int numSamples) throw()
  20946. {
  20947. jassert (&source != this || sourceChannel != destChannel);
  20948. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20949. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20950. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  20951. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  20952. if (numSamples > 0)
  20953. {
  20954. memcpy (channels [destChannel] + destStartSample,
  20955. source.channels [sourceChannel] + sourceStartSample,
  20956. sizeof (float) * numSamples);
  20957. }
  20958. }
  20959. void AudioSampleBuffer::copyFrom (const int destChannel,
  20960. const int destStartSample,
  20961. const float* source,
  20962. int numSamples) throw()
  20963. {
  20964. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20965. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20966. jassert (source != 0);
  20967. if (numSamples > 0)
  20968. {
  20969. memcpy (channels [destChannel] + destStartSample,
  20970. source,
  20971. sizeof (float) * numSamples);
  20972. }
  20973. }
  20974. void AudioSampleBuffer::copyFrom (const int destChannel,
  20975. const int destStartSample,
  20976. const float* source,
  20977. int numSamples,
  20978. const float gain) throw()
  20979. {
  20980. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20981. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20982. jassert (source != 0);
  20983. if (numSamples > 0)
  20984. {
  20985. float* d = channels [destChannel] + destStartSample;
  20986. if (gain != 1.0f)
  20987. {
  20988. if (gain == 0)
  20989. {
  20990. zeromem (d, sizeof (float) * numSamples);
  20991. }
  20992. else
  20993. {
  20994. while (--numSamples >= 0)
  20995. *d++ = gain * *source++;
  20996. }
  20997. }
  20998. else
  20999. {
  21000. memcpy (d, source, sizeof (float) * numSamples);
  21001. }
  21002. }
  21003. }
  21004. void AudioSampleBuffer::copyFromWithRamp (const int destChannel,
  21005. const int destStartSample,
  21006. const float* source,
  21007. int numSamples,
  21008. float startGain,
  21009. float endGain) throw()
  21010. {
  21011. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21012. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21013. jassert (source != 0);
  21014. if (startGain == endGain)
  21015. {
  21016. copyFrom (destChannel,
  21017. destStartSample,
  21018. source,
  21019. numSamples,
  21020. startGain);
  21021. }
  21022. else
  21023. {
  21024. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  21025. {
  21026. const float increment = (endGain - startGain) / numSamples;
  21027. float* d = channels [destChannel] + destStartSample;
  21028. while (--numSamples >= 0)
  21029. {
  21030. *d++ = startGain * *source++;
  21031. startGain += increment;
  21032. }
  21033. }
  21034. }
  21035. }
  21036. void AudioSampleBuffer::findMinMax (const int channel,
  21037. const int startSample,
  21038. int numSamples,
  21039. float& minVal,
  21040. float& maxVal) const throw()
  21041. {
  21042. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21043. jassert (startSample >= 0 && startSample + numSamples <= size);
  21044. if (numSamples <= 0)
  21045. {
  21046. minVal = 0.0f;
  21047. maxVal = 0.0f;
  21048. }
  21049. else
  21050. {
  21051. const float* d = channels [channel] + startSample;
  21052. float mn = *d++;
  21053. float mx = mn;
  21054. while (--numSamples > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  21055. {
  21056. const float samp = *d++;
  21057. if (samp > mx)
  21058. mx = samp;
  21059. if (samp < mn)
  21060. mn = samp;
  21061. }
  21062. maxVal = mx;
  21063. minVal = mn;
  21064. }
  21065. }
  21066. float AudioSampleBuffer::getMagnitude (const int channel,
  21067. const int startSample,
  21068. const int numSamples) const throw()
  21069. {
  21070. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21071. jassert (startSample >= 0 && startSample + numSamples <= size);
  21072. float mn, mx;
  21073. findMinMax (channel, startSample, numSamples, mn, mx);
  21074. return jmax (mn, -mn, mx, -mx);
  21075. }
  21076. float AudioSampleBuffer::getMagnitude (const int startSample,
  21077. const int numSamples) const throw()
  21078. {
  21079. float mag = 0.0f;
  21080. for (int i = 0; i < numChannels; ++i)
  21081. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  21082. return mag;
  21083. }
  21084. float AudioSampleBuffer::getRMSLevel (const int channel,
  21085. const int startSample,
  21086. const int numSamples) const throw()
  21087. {
  21088. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21089. jassert (startSample >= 0 && startSample + numSamples <= size);
  21090. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  21091. return 0.0f;
  21092. const float* const data = channels [channel] + startSample;
  21093. double sum = 0.0;
  21094. for (int i = 0; i < numSamples; ++i)
  21095. {
  21096. const float sample = data [i];
  21097. sum += sample * sample;
  21098. }
  21099. return (float) std::sqrt (sum / numSamples);
  21100. }
  21101. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  21102. const int startSample,
  21103. const int numSamples,
  21104. const int readerStartSample,
  21105. const bool useLeftChan,
  21106. const bool useRightChan) throw()
  21107. {
  21108. jassert (reader != 0);
  21109. jassert (startSample >= 0 && startSample + numSamples <= size);
  21110. if (numSamples > 0)
  21111. {
  21112. int* chans[3];
  21113. if (useLeftChan == useRightChan)
  21114. {
  21115. chans[0] = (int*) getSampleData (0, startSample);
  21116. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? (int*) getSampleData (1, startSample) : 0;
  21117. }
  21118. else if (useLeftChan || (reader->numChannels == 1))
  21119. {
  21120. chans[0] = (int*) getSampleData (0, startSample);
  21121. chans[1] = 0;
  21122. }
  21123. else if (useRightChan)
  21124. {
  21125. chans[0] = 0;
  21126. chans[1] = (int*) getSampleData (0, startSample);
  21127. }
  21128. chans[2] = 0;
  21129. reader->read (chans, 2, readerStartSample, numSamples, true);
  21130. if (! reader->usesFloatingPointData)
  21131. {
  21132. for (int j = 0; j < 2; ++j)
  21133. {
  21134. float* const d = reinterpret_cast <float*> (chans[j]);
  21135. if (d != 0)
  21136. {
  21137. const float multiplier = 1.0f / 0x7fffffff;
  21138. for (int i = 0; i < numSamples; ++i)
  21139. d[i] = *(int*)(d + i) * multiplier;
  21140. }
  21141. }
  21142. }
  21143. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  21144. {
  21145. // if this is a stereo buffer and the source was mono, dupe the first channel..
  21146. memcpy (getSampleData (1, startSample),
  21147. getSampleData (0, startSample),
  21148. sizeof (float) * numSamples);
  21149. }
  21150. }
  21151. }
  21152. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  21153. const int startSample,
  21154. const int numSamples) const throw()
  21155. {
  21156. jassert (startSample >= 0 && startSample + numSamples <= size);
  21157. if (numSamples > 0)
  21158. {
  21159. int* chans [3];
  21160. if (writer->isFloatingPoint())
  21161. {
  21162. chans[0] = (int*) getSampleData (0, startSample);
  21163. if (numChannels > 1)
  21164. chans[1] = (int*) getSampleData (1, startSample);
  21165. else
  21166. chans[1] = 0;
  21167. chans[2] = 0;
  21168. writer->write ((const int**) chans, numSamples);
  21169. }
  21170. else
  21171. {
  21172. HeapBlock <int> tempBuffer (numSamples * 2);
  21173. chans[0] = tempBuffer;
  21174. if (numChannels > 1)
  21175. chans[1] = chans[0] + numSamples;
  21176. else
  21177. chans[1] = 0;
  21178. chans[2] = 0;
  21179. for (int j = 0; j < 2; ++j)
  21180. {
  21181. int* const dest = chans[j];
  21182. if (dest != 0)
  21183. {
  21184. const float* const src = channels [j] + startSample;
  21185. for (int i = 0; i < numSamples; ++i)
  21186. {
  21187. const double samp = src[i];
  21188. if (samp <= -1.0)
  21189. dest[i] = std::numeric_limits<int>::min();
  21190. else if (samp >= 1.0)
  21191. dest[i] = std::numeric_limits<int>::max();
  21192. else
  21193. dest[i] = roundToInt (std::numeric_limits<int>::max() * samp);
  21194. }
  21195. }
  21196. }
  21197. writer->write ((const int**) chans, numSamples);
  21198. }
  21199. }
  21200. }
  21201. END_JUCE_NAMESPACE
  21202. /*** End of inlined file: juce_AudioSampleBuffer.cpp ***/
  21203. /*** Start of inlined file: juce_IIRFilter.cpp ***/
  21204. BEGIN_JUCE_NAMESPACE
  21205. IIRFilter::IIRFilter()
  21206. : active (false)
  21207. {
  21208. reset();
  21209. }
  21210. IIRFilter::IIRFilter (const IIRFilter& other)
  21211. : active (other.active)
  21212. {
  21213. const ScopedLock sl (other.processLock);
  21214. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  21215. reset();
  21216. }
  21217. IIRFilter::~IIRFilter()
  21218. {
  21219. }
  21220. void IIRFilter::reset() throw()
  21221. {
  21222. const ScopedLock sl (processLock);
  21223. x1 = 0;
  21224. x2 = 0;
  21225. y1 = 0;
  21226. y2 = 0;
  21227. }
  21228. float IIRFilter::processSingleSampleRaw (const float in) throw()
  21229. {
  21230. float out = coefficients[0] * in
  21231. + coefficients[1] * x1
  21232. + coefficients[2] * x2
  21233. - coefficients[4] * y1
  21234. - coefficients[5] * y2;
  21235. #if JUCE_INTEL
  21236. if (! (out < -1.0e-8 || out > 1.0e-8))
  21237. out = 0;
  21238. #endif
  21239. x2 = x1;
  21240. x1 = in;
  21241. y2 = y1;
  21242. y1 = out;
  21243. return out;
  21244. }
  21245. void IIRFilter::processSamples (float* const samples,
  21246. const int numSamples) throw()
  21247. {
  21248. const ScopedLock sl (processLock);
  21249. if (active)
  21250. {
  21251. for (int i = 0; i < numSamples; ++i)
  21252. {
  21253. const float in = samples[i];
  21254. float out = coefficients[0] * in
  21255. + coefficients[1] * x1
  21256. + coefficients[2] * x2
  21257. - coefficients[4] * y1
  21258. - coefficients[5] * y2;
  21259. #if JUCE_INTEL
  21260. if (! (out < -1.0e-8 || out > 1.0e-8))
  21261. out = 0;
  21262. #endif
  21263. x2 = x1;
  21264. x1 = in;
  21265. y2 = y1;
  21266. y1 = out;
  21267. samples[i] = out;
  21268. }
  21269. }
  21270. }
  21271. void IIRFilter::makeLowPass (const double sampleRate,
  21272. const double frequency) throw()
  21273. {
  21274. jassert (sampleRate > 0);
  21275. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  21276. const double nSquared = n * n;
  21277. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  21278. setCoefficients (c1,
  21279. c1 * 2.0f,
  21280. c1,
  21281. 1.0,
  21282. c1 * 2.0 * (1.0 - nSquared),
  21283. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  21284. }
  21285. void IIRFilter::makeHighPass (const double sampleRate,
  21286. const double frequency) throw()
  21287. {
  21288. const double n = tan (double_Pi * frequency / sampleRate);
  21289. const double nSquared = n * n;
  21290. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  21291. setCoefficients (c1,
  21292. c1 * -2.0f,
  21293. c1,
  21294. 1.0,
  21295. c1 * 2.0 * (nSquared - 1.0),
  21296. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  21297. }
  21298. void IIRFilter::makeLowShelf (const double sampleRate,
  21299. const double cutOffFrequency,
  21300. const double Q,
  21301. const float gainFactor) throw()
  21302. {
  21303. jassert (sampleRate > 0);
  21304. jassert (Q > 0);
  21305. const double A = jmax (0.0f, gainFactor);
  21306. const double aminus1 = A - 1.0;
  21307. const double aplus1 = A + 1.0;
  21308. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  21309. const double coso = std::cos (omega);
  21310. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  21311. const double aminus1TimesCoso = aminus1 * coso;
  21312. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  21313. A * 2.0 * (aminus1 - aplus1 * coso),
  21314. A * (aplus1 - aminus1TimesCoso - beta),
  21315. aplus1 + aminus1TimesCoso + beta,
  21316. -2.0 * (aminus1 + aplus1 * coso),
  21317. aplus1 + aminus1TimesCoso - beta);
  21318. }
  21319. void IIRFilter::makeHighShelf (const double sampleRate,
  21320. const double cutOffFrequency,
  21321. const double Q,
  21322. const float gainFactor) throw()
  21323. {
  21324. jassert (sampleRate > 0);
  21325. jassert (Q > 0);
  21326. const double A = jmax (0.0f, gainFactor);
  21327. const double aminus1 = A - 1.0;
  21328. const double aplus1 = A + 1.0;
  21329. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  21330. const double coso = std::cos (omega);
  21331. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  21332. const double aminus1TimesCoso = aminus1 * coso;
  21333. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  21334. A * -2.0 * (aminus1 + aplus1 * coso),
  21335. A * (aplus1 + aminus1TimesCoso - beta),
  21336. aplus1 - aminus1TimesCoso + beta,
  21337. 2.0 * (aminus1 - aplus1 * coso),
  21338. aplus1 - aminus1TimesCoso - beta);
  21339. }
  21340. void IIRFilter::makeBandPass (const double sampleRate,
  21341. const double centreFrequency,
  21342. const double Q,
  21343. const float gainFactor) throw()
  21344. {
  21345. jassert (sampleRate > 0);
  21346. jassert (Q > 0);
  21347. const double A = jmax (0.0f, gainFactor);
  21348. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  21349. const double alpha = 0.5 * std::sin (omega) / Q;
  21350. const double c2 = -2.0 * std::cos (omega);
  21351. const double alphaTimesA = alpha * A;
  21352. const double alphaOverA = alpha / A;
  21353. setCoefficients (1.0 + alphaTimesA,
  21354. c2,
  21355. 1.0 - alphaTimesA,
  21356. 1.0 + alphaOverA,
  21357. c2,
  21358. 1.0 - alphaOverA);
  21359. }
  21360. void IIRFilter::makeInactive() throw()
  21361. {
  21362. const ScopedLock sl (processLock);
  21363. active = false;
  21364. }
  21365. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  21366. {
  21367. const ScopedLock sl (processLock);
  21368. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  21369. active = other.active;
  21370. }
  21371. void IIRFilter::setCoefficients (double c1,
  21372. double c2,
  21373. double c3,
  21374. double c4,
  21375. double c5,
  21376. double c6) throw()
  21377. {
  21378. const double a = 1.0 / c4;
  21379. c1 *= a;
  21380. c2 *= a;
  21381. c3 *= a;
  21382. c5 *= a;
  21383. c6 *= a;
  21384. const ScopedLock sl (processLock);
  21385. coefficients[0] = (float) c1;
  21386. coefficients[1] = (float) c2;
  21387. coefficients[2] = (float) c3;
  21388. coefficients[3] = (float) c4;
  21389. coefficients[4] = (float) c5;
  21390. coefficients[5] = (float) c6;
  21391. active = true;
  21392. }
  21393. END_JUCE_NAMESPACE
  21394. /*** End of inlined file: juce_IIRFilter.cpp ***/
  21395. /*** Start of inlined file: juce_MidiBuffer.cpp ***/
  21396. BEGIN_JUCE_NAMESPACE
  21397. MidiBuffer::MidiBuffer() throw()
  21398. : bytesUsed (0)
  21399. {
  21400. }
  21401. MidiBuffer::MidiBuffer (const MidiMessage& message) throw()
  21402. : bytesUsed (0)
  21403. {
  21404. addEvent (message, 0);
  21405. }
  21406. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  21407. : data (other.data),
  21408. bytesUsed (other.bytesUsed)
  21409. {
  21410. }
  21411. MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  21412. {
  21413. bytesUsed = other.bytesUsed;
  21414. data = other.data;
  21415. return *this;
  21416. }
  21417. void MidiBuffer::swapWith (MidiBuffer& other)
  21418. {
  21419. data.swapWith (other.data);
  21420. swapVariables <int> (bytesUsed, other.bytesUsed);
  21421. }
  21422. MidiBuffer::~MidiBuffer() throw()
  21423. {
  21424. }
  21425. inline uint8* MidiBuffer::getData() const throw()
  21426. {
  21427. return static_cast <uint8*> (data.getData());
  21428. }
  21429. inline int MidiBuffer::getEventTime (const void* const d) throw()
  21430. {
  21431. return *static_cast <const int*> (d);
  21432. }
  21433. inline uint16 MidiBuffer::getEventDataSize (const void* const d) throw()
  21434. {
  21435. return *reinterpret_cast <const uint16*> (static_cast <const char*> (d) + sizeof (int));
  21436. }
  21437. inline uint16 MidiBuffer::getEventTotalSize (const void* const d) throw()
  21438. {
  21439. return getEventDataSize (d) + sizeof (int) + sizeof (uint16);
  21440. }
  21441. void MidiBuffer::clear() throw()
  21442. {
  21443. bytesUsed = 0;
  21444. }
  21445. void MidiBuffer::clear (const int startSample,
  21446. const int numSamples) throw()
  21447. {
  21448. uint8* const start = findEventAfter (getData(), startSample - 1);
  21449. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  21450. if (end > start)
  21451. {
  21452. const int bytesToMove = bytesUsed - (int) (end - getData());
  21453. if (bytesToMove > 0)
  21454. memmove (start, end, bytesToMove);
  21455. bytesUsed -= (int) (end - start);
  21456. }
  21457. }
  21458. void MidiBuffer::addEvent (const MidiMessage& m,
  21459. const int sampleNumber) throw()
  21460. {
  21461. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  21462. }
  21463. static int findActualEventLength (const uint8* const data,
  21464. const int maxBytes) throw()
  21465. {
  21466. unsigned int byte = (unsigned int) *data;
  21467. int size = 0;
  21468. if (byte == 0xf0 || byte == 0xf7)
  21469. {
  21470. const uint8* d = data + 1;
  21471. while (d < data + maxBytes)
  21472. if (*d++ == 0xf7)
  21473. break;
  21474. size = (int) (d - data);
  21475. }
  21476. else if (byte == 0xff)
  21477. {
  21478. int n;
  21479. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  21480. size = jmin (maxBytes, n + 2 + bytesLeft);
  21481. }
  21482. else if (byte >= 0x80)
  21483. {
  21484. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  21485. }
  21486. return size;
  21487. }
  21488. void MidiBuffer::addEvent (const uint8* const newData,
  21489. const int maxBytes,
  21490. const int sampleNumber) throw()
  21491. {
  21492. const int numBytes = findActualEventLength (newData, maxBytes);
  21493. if (numBytes > 0)
  21494. {
  21495. int spaceNeeded = bytesUsed + numBytes + sizeof (int) + sizeof (uint16);
  21496. data.ensureSize ((spaceNeeded + spaceNeeded / 2 + 8) & ~7);
  21497. uint8* d = findEventAfter (getData(), sampleNumber);
  21498. const int bytesToMove = bytesUsed - (int) (d - getData());
  21499. if (bytesToMove > 0)
  21500. memmove (d + numBytes + sizeof (int) + sizeof (uint16), d, bytesToMove);
  21501. *reinterpret_cast <int*> (d) = sampleNumber;
  21502. d += sizeof (int);
  21503. *reinterpret_cast <uint16*> (d) = (uint16) numBytes;
  21504. d += sizeof (uint16);
  21505. memcpy (d, newData, numBytes);
  21506. bytesUsed += numBytes + sizeof (int) + sizeof (uint16);
  21507. }
  21508. }
  21509. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  21510. const int startSample,
  21511. const int numSamples,
  21512. const int sampleDeltaToAdd) throw()
  21513. {
  21514. Iterator i (otherBuffer);
  21515. i.setNextSamplePosition (startSample);
  21516. const uint8* eventData;
  21517. int eventSize, position;
  21518. while (i.getNextEvent (eventData, eventSize, position)
  21519. && (position < startSample + numSamples || numSamples < 0))
  21520. {
  21521. addEvent (eventData, eventSize, position + sampleDeltaToAdd);
  21522. }
  21523. }
  21524. void MidiBuffer::ensureSize (size_t minimumNumBytes)
  21525. {
  21526. data.ensureSize (minimumNumBytes);
  21527. }
  21528. bool MidiBuffer::isEmpty() const throw()
  21529. {
  21530. return bytesUsed == 0;
  21531. }
  21532. int MidiBuffer::getNumEvents() const throw()
  21533. {
  21534. int n = 0;
  21535. const uint8* d = getData();
  21536. const uint8* const end = d + bytesUsed;
  21537. while (d < end)
  21538. {
  21539. d += getEventTotalSize (d);
  21540. ++n;
  21541. }
  21542. return n;
  21543. }
  21544. int MidiBuffer::getFirstEventTime() const throw()
  21545. {
  21546. return bytesUsed > 0 ? getEventTime (data.getData()) : 0;
  21547. }
  21548. int MidiBuffer::getLastEventTime() const throw()
  21549. {
  21550. if (bytesUsed == 0)
  21551. return 0;
  21552. const uint8* d = getData();
  21553. const uint8* const endData = d + bytesUsed;
  21554. for (;;)
  21555. {
  21556. const uint8* const nextOne = d + getEventTotalSize (d);
  21557. if (nextOne >= endData)
  21558. return getEventTime (d);
  21559. d = nextOne;
  21560. }
  21561. }
  21562. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  21563. {
  21564. const uint8* const endData = getData() + bytesUsed;
  21565. while (d < endData && getEventTime (d) <= samplePosition)
  21566. d += getEventTotalSize (d);
  21567. return d;
  21568. }
  21569. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer_) throw()
  21570. : buffer (buffer_),
  21571. data (buffer_.getData())
  21572. {
  21573. }
  21574. MidiBuffer::Iterator::~Iterator() throw()
  21575. {
  21576. }
  21577. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  21578. {
  21579. data = buffer.getData();
  21580. const uint8* dataEnd = data + buffer.bytesUsed;
  21581. while (data < dataEnd && getEventTime (data) < samplePosition)
  21582. data += getEventTotalSize (data);
  21583. }
  21584. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData, int& numBytes, int& samplePosition) throw()
  21585. {
  21586. if (data >= buffer.getData() + buffer.bytesUsed)
  21587. return false;
  21588. samplePosition = getEventTime (data);
  21589. numBytes = getEventDataSize (data);
  21590. data += sizeof (int) + sizeof (uint16);
  21591. midiData = data;
  21592. data += numBytes;
  21593. return true;
  21594. }
  21595. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result, int& samplePosition) throw()
  21596. {
  21597. if (data >= buffer.getData() + buffer.bytesUsed)
  21598. return false;
  21599. samplePosition = getEventTime (data);
  21600. const int numBytes = getEventDataSize (data);
  21601. data += sizeof (int) + sizeof (uint16);
  21602. result = MidiMessage (data, numBytes, samplePosition);
  21603. data += numBytes;
  21604. return true;
  21605. }
  21606. END_JUCE_NAMESPACE
  21607. /*** End of inlined file: juce_MidiBuffer.cpp ***/
  21608. /*** Start of inlined file: juce_MidiFile.cpp ***/
  21609. BEGIN_JUCE_NAMESPACE
  21610. namespace MidiFileHelpers
  21611. {
  21612. static void writeVariableLengthInt (OutputStream& out, unsigned int v)
  21613. {
  21614. unsigned int buffer = v & 0x7F;
  21615. while ((v >>= 7) != 0)
  21616. {
  21617. buffer <<= 8;
  21618. buffer |= ((v & 0x7F) | 0x80);
  21619. }
  21620. for (;;)
  21621. {
  21622. out.writeByte ((char) buffer);
  21623. if (buffer & 0x80)
  21624. buffer >>= 8;
  21625. else
  21626. break;
  21627. }
  21628. }
  21629. static bool parseMidiHeader (const uint8* &data, short& timeFormat, short& fileType, short& numberOfTracks) throw()
  21630. {
  21631. unsigned int ch = (int) ByteOrder::bigEndianInt (data);
  21632. data += 4;
  21633. if (ch != ByteOrder::bigEndianInt ("MThd"))
  21634. {
  21635. bool ok = false;
  21636. if (ch == ByteOrder::bigEndianInt ("RIFF"))
  21637. {
  21638. for (int i = 0; i < 8; ++i)
  21639. {
  21640. ch = ByteOrder::bigEndianInt (data);
  21641. data += 4;
  21642. if (ch == ByteOrder::bigEndianInt ("MThd"))
  21643. {
  21644. ok = true;
  21645. break;
  21646. }
  21647. }
  21648. }
  21649. if (! ok)
  21650. return false;
  21651. }
  21652. unsigned int bytesRemaining = ByteOrder::bigEndianInt (data);
  21653. data += 4;
  21654. fileType = (short) ByteOrder::bigEndianShort (data);
  21655. data += 2;
  21656. numberOfTracks = (short) ByteOrder::bigEndianShort (data);
  21657. data += 2;
  21658. timeFormat = (short) ByteOrder::bigEndianShort (data);
  21659. data += 2;
  21660. bytesRemaining -= 6;
  21661. data += bytesRemaining;
  21662. return true;
  21663. }
  21664. static double convertTicksToSeconds (const double time,
  21665. const MidiMessageSequence& tempoEvents,
  21666. const int timeFormat)
  21667. {
  21668. if (timeFormat > 0)
  21669. {
  21670. int numer = 4, denom = 4;
  21671. double tempoTime = 0.0, correctedTempoTime = 0.0;
  21672. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  21673. double secsPerTick = 0.5 * tickLen;
  21674. const int numEvents = tempoEvents.getNumEvents();
  21675. for (int i = 0; i < numEvents; ++i)
  21676. {
  21677. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  21678. if (time <= m.getTimeStamp())
  21679. break;
  21680. if (timeFormat > 0)
  21681. {
  21682. correctedTempoTime = correctedTempoTime
  21683. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  21684. }
  21685. else
  21686. {
  21687. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  21688. }
  21689. tempoTime = m.getTimeStamp();
  21690. if (m.isTempoMetaEvent())
  21691. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  21692. else if (m.isTimeSignatureMetaEvent())
  21693. m.getTimeSignatureInfo (numer, denom);
  21694. while (i + 1 < numEvents)
  21695. {
  21696. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  21697. if (m2.getTimeStamp() == tempoTime)
  21698. {
  21699. ++i;
  21700. if (m2.isTempoMetaEvent())
  21701. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  21702. else if (m2.isTimeSignatureMetaEvent())
  21703. m2.getTimeSignatureInfo (numer, denom);
  21704. }
  21705. else
  21706. {
  21707. break;
  21708. }
  21709. }
  21710. }
  21711. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  21712. }
  21713. else
  21714. {
  21715. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  21716. }
  21717. }
  21718. }
  21719. MidiFile::MidiFile()
  21720. : timeFormat ((short) (unsigned short) 0xe728)
  21721. {
  21722. }
  21723. MidiFile::~MidiFile()
  21724. {
  21725. clear();
  21726. }
  21727. void MidiFile::clear()
  21728. {
  21729. tracks.clear();
  21730. }
  21731. int MidiFile::getNumTracks() const throw()
  21732. {
  21733. return tracks.size();
  21734. }
  21735. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  21736. {
  21737. return tracks [index];
  21738. }
  21739. void MidiFile::addTrack (const MidiMessageSequence& trackSequence)
  21740. {
  21741. tracks.add (new MidiMessageSequence (trackSequence));
  21742. }
  21743. short MidiFile::getTimeFormat() const throw()
  21744. {
  21745. return timeFormat;
  21746. }
  21747. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  21748. {
  21749. timeFormat = (short) ticks;
  21750. }
  21751. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  21752. const int subframeResolution) throw()
  21753. {
  21754. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  21755. }
  21756. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  21757. {
  21758. for (int i = tracks.size(); --i >= 0;)
  21759. {
  21760. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  21761. for (int j = 0; j < numEvents; ++j)
  21762. {
  21763. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  21764. if (m.isTempoMetaEvent())
  21765. tempoChangeEvents.addEvent (m);
  21766. }
  21767. }
  21768. }
  21769. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  21770. {
  21771. for (int i = tracks.size(); --i >= 0;)
  21772. {
  21773. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  21774. for (int j = 0; j < numEvents; ++j)
  21775. {
  21776. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  21777. if (m.isTimeSignatureMetaEvent())
  21778. timeSigEvents.addEvent (m);
  21779. }
  21780. }
  21781. }
  21782. double MidiFile::getLastTimestamp() const
  21783. {
  21784. double t = 0.0;
  21785. for (int i = tracks.size(); --i >= 0;)
  21786. t = jmax (t, tracks.getUnchecked(i)->getEndTime());
  21787. return t;
  21788. }
  21789. bool MidiFile::readFrom (InputStream& sourceStream)
  21790. {
  21791. clear();
  21792. MemoryBlock data;
  21793. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  21794. // (put a sanity-check on the file size, as midi files are generally small)
  21795. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  21796. {
  21797. size_t size = data.getSize();
  21798. const uint8* d = static_cast <const uint8*> (data.getData());
  21799. short fileType, expectedTracks;
  21800. if (size > 16 && MidiFileHelpers::parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  21801. {
  21802. size -= (int) (d - static_cast <const uint8*> (data.getData()));
  21803. int track = 0;
  21804. while (size > 0 && track < expectedTracks)
  21805. {
  21806. const int chunkType = (int) ByteOrder::bigEndianInt (d);
  21807. d += 4;
  21808. const int chunkSize = (int) ByteOrder::bigEndianInt (d);
  21809. d += 4;
  21810. if (chunkSize <= 0)
  21811. break;
  21812. if (size < 0)
  21813. return false;
  21814. if (chunkType == (int) ByteOrder::bigEndianInt ("MTrk"))
  21815. {
  21816. readNextTrack (d, chunkSize);
  21817. }
  21818. size -= chunkSize + 8;
  21819. d += chunkSize;
  21820. ++track;
  21821. }
  21822. return true;
  21823. }
  21824. }
  21825. return false;
  21826. }
  21827. // a comparator that puts all the note-offs before note-ons that have the same time
  21828. int MidiFile::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  21829. const MidiMessageSequence::MidiEventHolder* const second)
  21830. {
  21831. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  21832. if (diff == 0)
  21833. {
  21834. if (first->message.isNoteOff() && second->message.isNoteOn())
  21835. return -1;
  21836. else if (first->message.isNoteOn() && second->message.isNoteOff())
  21837. return 1;
  21838. else
  21839. return 0;
  21840. }
  21841. else
  21842. {
  21843. return (diff > 0) ? 1 : -1;
  21844. }
  21845. }
  21846. void MidiFile::readNextTrack (const uint8* data, int size)
  21847. {
  21848. double time = 0;
  21849. char lastStatusByte = 0;
  21850. MidiMessageSequence result;
  21851. while (size > 0)
  21852. {
  21853. int bytesUsed;
  21854. const int delay = MidiMessage::readVariableLengthVal (data, bytesUsed);
  21855. data += bytesUsed;
  21856. size -= bytesUsed;
  21857. time += delay;
  21858. int messSize = 0;
  21859. const MidiMessage mm (data, size, messSize, lastStatusByte, time);
  21860. if (messSize <= 0)
  21861. break;
  21862. size -= messSize;
  21863. data += messSize;
  21864. result.addEvent (mm);
  21865. const char firstByte = *(mm.getRawData());
  21866. if ((firstByte & 0xf0) != 0xf0)
  21867. lastStatusByte = firstByte;
  21868. }
  21869. // use a sort that puts all the note-offs before note-ons that have the same time
  21870. result.list.sort (*this, true);
  21871. result.updateMatchedPairs();
  21872. addTrack (result);
  21873. }
  21874. void MidiFile::convertTimestampTicksToSeconds()
  21875. {
  21876. MidiMessageSequence tempoEvents;
  21877. findAllTempoEvents (tempoEvents);
  21878. findAllTimeSigEvents (tempoEvents);
  21879. for (int i = 0; i < tracks.size(); ++i)
  21880. {
  21881. MidiMessageSequence& ms = *tracks.getUnchecked(i);
  21882. for (int j = ms.getNumEvents(); --j >= 0;)
  21883. {
  21884. MidiMessage& m = ms.getEventPointer(j)->message;
  21885. m.setTimeStamp (MidiFileHelpers::convertTicksToSeconds (m.getTimeStamp(),
  21886. tempoEvents,
  21887. timeFormat));
  21888. }
  21889. }
  21890. }
  21891. bool MidiFile::writeTo (OutputStream& out)
  21892. {
  21893. out.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MThd"));
  21894. out.writeIntBigEndian (6);
  21895. out.writeShortBigEndian (1); // type
  21896. out.writeShortBigEndian ((short) tracks.size());
  21897. out.writeShortBigEndian (timeFormat);
  21898. for (int i = 0; i < tracks.size(); ++i)
  21899. writeTrack (out, i);
  21900. out.flush();
  21901. return true;
  21902. }
  21903. void MidiFile::writeTrack (OutputStream& mainOut,
  21904. const int trackNum)
  21905. {
  21906. MemoryOutputStream out;
  21907. const MidiMessageSequence& ms = *tracks[trackNum];
  21908. int lastTick = 0;
  21909. char lastStatusByte = 0;
  21910. for (int i = 0; i < ms.getNumEvents(); ++i)
  21911. {
  21912. const MidiMessage& mm = ms.getEventPointer(i)->message;
  21913. const int tick = roundToInt (mm.getTimeStamp());
  21914. const int delta = jmax (0, tick - lastTick);
  21915. MidiFileHelpers::writeVariableLengthInt (out, delta);
  21916. lastTick = tick;
  21917. const char statusByte = *(mm.getRawData());
  21918. if ((statusByte == lastStatusByte)
  21919. && ((statusByte & 0xf0) != 0xf0)
  21920. && i > 0
  21921. && mm.getRawDataSize() > 1)
  21922. {
  21923. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  21924. }
  21925. else
  21926. {
  21927. out.write (mm.getRawData(), mm.getRawDataSize());
  21928. }
  21929. lastStatusByte = statusByte;
  21930. }
  21931. out.writeByte (0);
  21932. const MidiMessage m (MidiMessage::endOfTrack());
  21933. out.write (m.getRawData(),
  21934. m.getRawDataSize());
  21935. mainOut.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MTrk"));
  21936. mainOut.writeIntBigEndian ((int) out.getDataSize());
  21937. mainOut.write (out.getData(), (int) out.getDataSize());
  21938. }
  21939. END_JUCE_NAMESPACE
  21940. /*** End of inlined file: juce_MidiFile.cpp ***/
  21941. /*** Start of inlined file: juce_MidiKeyboardState.cpp ***/
  21942. BEGIN_JUCE_NAMESPACE
  21943. MidiKeyboardState::MidiKeyboardState()
  21944. {
  21945. zerostruct (noteStates);
  21946. }
  21947. MidiKeyboardState::~MidiKeyboardState()
  21948. {
  21949. }
  21950. void MidiKeyboardState::reset()
  21951. {
  21952. const ScopedLock sl (lock);
  21953. zerostruct (noteStates);
  21954. eventsToAdd.clear();
  21955. }
  21956. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  21957. {
  21958. jassert (midiChannel >= 0 && midiChannel <= 16);
  21959. return ((unsigned int) n) < 128
  21960. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  21961. }
  21962. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  21963. {
  21964. return ((unsigned int) n) < 128
  21965. && (noteStates[n] & midiChannelMask) != 0;
  21966. }
  21967. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  21968. {
  21969. jassert (midiChannel >= 0 && midiChannel <= 16);
  21970. jassert (((unsigned int) midiNoteNumber) < 128);
  21971. const ScopedLock sl (lock);
  21972. if (((unsigned int) midiNoteNumber) < 128)
  21973. {
  21974. const int timeNow = (int) Time::getMillisecondCounter();
  21975. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  21976. eventsToAdd.clear (0, timeNow - 500);
  21977. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  21978. }
  21979. }
  21980. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  21981. {
  21982. if (((unsigned int) midiNoteNumber) < 128)
  21983. {
  21984. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  21985. for (int i = listeners.size(); --i >= 0;)
  21986. listeners.getUnchecked(i)->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  21987. }
  21988. }
  21989. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  21990. {
  21991. const ScopedLock sl (lock);
  21992. if (isNoteOn (midiChannel, midiNoteNumber))
  21993. {
  21994. const int timeNow = (int) Time::getMillisecondCounter();
  21995. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  21996. eventsToAdd.clear (0, timeNow - 500);
  21997. noteOffInternal (midiChannel, midiNoteNumber);
  21998. }
  21999. }
  22000. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  22001. {
  22002. if (isNoteOn (midiChannel, midiNoteNumber))
  22003. {
  22004. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  22005. for (int i = listeners.size(); --i >= 0;)
  22006. listeners.getUnchecked(i)->handleNoteOff (this, midiChannel, midiNoteNumber);
  22007. }
  22008. }
  22009. void MidiKeyboardState::allNotesOff (const int midiChannel)
  22010. {
  22011. const ScopedLock sl (lock);
  22012. if (midiChannel <= 0)
  22013. {
  22014. for (int i = 1; i <= 16; ++i)
  22015. allNotesOff (i);
  22016. }
  22017. else
  22018. {
  22019. for (int i = 0; i < 128; ++i)
  22020. noteOff (midiChannel, i);
  22021. }
  22022. }
  22023. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  22024. {
  22025. if (message.isNoteOn())
  22026. {
  22027. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  22028. }
  22029. else if (message.isNoteOff())
  22030. {
  22031. noteOffInternal (message.getChannel(), message.getNoteNumber());
  22032. }
  22033. else if (message.isAllNotesOff())
  22034. {
  22035. for (int i = 0; i < 128; ++i)
  22036. noteOffInternal (message.getChannel(), i);
  22037. }
  22038. }
  22039. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  22040. const int startSample,
  22041. const int numSamples,
  22042. const bool injectIndirectEvents)
  22043. {
  22044. MidiBuffer::Iterator i (buffer);
  22045. MidiMessage message (0xf4, 0.0);
  22046. int time;
  22047. const ScopedLock sl (lock);
  22048. while (i.getNextEvent (message, time))
  22049. processNextMidiEvent (message);
  22050. if (injectIndirectEvents)
  22051. {
  22052. MidiBuffer::Iterator i2 (eventsToAdd);
  22053. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  22054. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  22055. while (i2.getNextEvent (message, time))
  22056. {
  22057. const int pos = jlimit (0, numSamples - 1, roundToInt ((time - firstEventToAdd) * scaleFactor));
  22058. buffer.addEvent (message, startSample + pos);
  22059. }
  22060. }
  22061. eventsToAdd.clear();
  22062. }
  22063. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener) throw()
  22064. {
  22065. const ScopedLock sl (lock);
  22066. listeners.addIfNotAlreadyThere (listener);
  22067. }
  22068. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener) throw()
  22069. {
  22070. const ScopedLock sl (lock);
  22071. listeners.removeValue (listener);
  22072. }
  22073. END_JUCE_NAMESPACE
  22074. /*** End of inlined file: juce_MidiKeyboardState.cpp ***/
  22075. /*** Start of inlined file: juce_MidiMessage.cpp ***/
  22076. BEGIN_JUCE_NAMESPACE
  22077. int MidiMessage::readVariableLengthVal (const uint8* data,
  22078. int& numBytesUsed) throw()
  22079. {
  22080. numBytesUsed = 0;
  22081. int v = 0;
  22082. int i;
  22083. do
  22084. {
  22085. i = (int) *data++;
  22086. if (++numBytesUsed > 6)
  22087. break;
  22088. v = (v << 7) + (i & 0x7f);
  22089. } while (i & 0x80);
  22090. return v;
  22091. }
  22092. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  22093. {
  22094. // this method only works for valid starting bytes of a short midi message
  22095. jassert (firstByte >= 0x80
  22096. && firstByte != 0xf0
  22097. && firstByte != 0xf7);
  22098. static const char messageLengths[] =
  22099. {
  22100. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22101. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22102. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22103. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22104. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22105. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22106. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22107. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  22108. };
  22109. return messageLengths [firstByte & 0x7f];
  22110. }
  22111. MidiMessage::MidiMessage (const void* const d, const int dataSize, const double t)
  22112. : timeStamp (t),
  22113. size (dataSize)
  22114. {
  22115. jassert (dataSize > 0);
  22116. if (dataSize <= 4)
  22117. data = static_cast<uint8*> (preallocatedData.asBytes);
  22118. else
  22119. data = new uint8 [dataSize];
  22120. memcpy (data, d, dataSize);
  22121. // check that the length matches the data..
  22122. jassert (size > 3 || data[0] >= 0xf0 || getMessageLengthFromFirstByte (data[0]) == size);
  22123. }
  22124. MidiMessage::MidiMessage (const int byte1, const double t) throw()
  22125. : timeStamp (t),
  22126. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22127. size (1)
  22128. {
  22129. data[0] = (uint8) byte1;
  22130. // check that the length matches the data..
  22131. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  22132. }
  22133. MidiMessage::MidiMessage (const int byte1, const int byte2, const double t) throw()
  22134. : timeStamp (t),
  22135. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22136. size (2)
  22137. {
  22138. data[0] = (uint8) byte1;
  22139. data[1] = (uint8) byte2;
  22140. // check that the length matches the data..
  22141. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  22142. }
  22143. MidiMessage::MidiMessage (const int byte1, const int byte2, const int byte3, const double t) throw()
  22144. : timeStamp (t),
  22145. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22146. size (3)
  22147. {
  22148. data[0] = (uint8) byte1;
  22149. data[1] = (uint8) byte2;
  22150. data[2] = (uint8) byte3;
  22151. // check that the length matches the data..
  22152. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  22153. }
  22154. MidiMessage::MidiMessage (const MidiMessage& other)
  22155. : timeStamp (other.timeStamp),
  22156. size (other.size)
  22157. {
  22158. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22159. {
  22160. data = new uint8 [size];
  22161. memcpy (data, other.data, size);
  22162. }
  22163. else
  22164. {
  22165. data = static_cast<uint8*> (preallocatedData.asBytes);
  22166. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22167. }
  22168. }
  22169. MidiMessage::MidiMessage (const MidiMessage& other, const double newTimeStamp)
  22170. : timeStamp (newTimeStamp),
  22171. size (other.size)
  22172. {
  22173. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22174. {
  22175. data = new uint8 [size];
  22176. memcpy (data, other.data, size);
  22177. }
  22178. else
  22179. {
  22180. data = static_cast<uint8*> (preallocatedData.asBytes);
  22181. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22182. }
  22183. }
  22184. MidiMessage::MidiMessage (const void* src_, int sz, int& numBytesUsed, const uint8 lastStatusByte, double t)
  22185. : timeStamp (t),
  22186. data (static_cast<uint8*> (preallocatedData.asBytes))
  22187. {
  22188. const uint8* src = static_cast <const uint8*> (src_);
  22189. unsigned int byte = (unsigned int) *src;
  22190. if (byte < 0x80)
  22191. {
  22192. byte = (unsigned int) (uint8) lastStatusByte;
  22193. numBytesUsed = -1;
  22194. }
  22195. else
  22196. {
  22197. numBytesUsed = 0;
  22198. --sz;
  22199. ++src;
  22200. }
  22201. if (byte >= 0x80)
  22202. {
  22203. if (byte == 0xf0)
  22204. {
  22205. const uint8* d = src;
  22206. while (d < src + sz)
  22207. {
  22208. if (*d >= 0x80) // stop if we hit a status byte, and don't include it in this message
  22209. {
  22210. if (*d == 0xf7) // include an 0xf7 if we hit one
  22211. ++d;
  22212. break;
  22213. }
  22214. ++d;
  22215. }
  22216. size = 1 + (int) (d - src);
  22217. data = new uint8 [size];
  22218. *data = (uint8) byte;
  22219. memcpy (data + 1, src, size - 1);
  22220. }
  22221. else if (byte == 0xff)
  22222. {
  22223. int n;
  22224. const int bytesLeft = readVariableLengthVal (src + 1, n);
  22225. size = jmin (sz + 1, n + 2 + bytesLeft);
  22226. data = new uint8 [size];
  22227. *data = (uint8) byte;
  22228. memcpy (data + 1, src, size - 1);
  22229. }
  22230. else
  22231. {
  22232. preallocatedData.asInt32 = 0;
  22233. size = getMessageLengthFromFirstByte ((uint8) byte);
  22234. data[0] = (uint8) byte;
  22235. if (size > 1)
  22236. {
  22237. data[1] = src[0];
  22238. if (size > 2)
  22239. data[2] = src[1];
  22240. }
  22241. }
  22242. numBytesUsed += size;
  22243. }
  22244. else
  22245. {
  22246. preallocatedData.asInt32 = 0;
  22247. size = 0;
  22248. }
  22249. }
  22250. MidiMessage& MidiMessage::operator= (const MidiMessage& other)
  22251. {
  22252. if (this != &other)
  22253. {
  22254. timeStamp = other.timeStamp;
  22255. size = other.size;
  22256. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  22257. delete[] data;
  22258. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22259. {
  22260. data = new uint8 [size];
  22261. memcpy (data, other.data, size);
  22262. }
  22263. else
  22264. {
  22265. data = static_cast<uint8*> (preallocatedData.asBytes);
  22266. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22267. }
  22268. }
  22269. return *this;
  22270. }
  22271. MidiMessage::~MidiMessage()
  22272. {
  22273. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  22274. delete[] data;
  22275. }
  22276. int MidiMessage::getChannel() const throw()
  22277. {
  22278. if ((data[0] & 0xf0) != 0xf0)
  22279. return (data[0] & 0xf) + 1;
  22280. else
  22281. return 0;
  22282. }
  22283. bool MidiMessage::isForChannel (const int channel) const throw()
  22284. {
  22285. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22286. return ((data[0] & 0xf) == channel - 1)
  22287. && ((data[0] & 0xf0) != 0xf0);
  22288. }
  22289. void MidiMessage::setChannel (const int channel) throw()
  22290. {
  22291. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22292. if ((data[0] & 0xf0) != (uint8) 0xf0)
  22293. data[0] = (uint8) ((data[0] & (uint8)0xf0)
  22294. | (uint8)(channel - 1));
  22295. }
  22296. bool MidiMessage::isNoteOn (const bool returnTrueForVelocity0) const throw()
  22297. {
  22298. return ((data[0] & 0xf0) == 0x90)
  22299. && (returnTrueForVelocity0 || data[2] != 0);
  22300. }
  22301. bool MidiMessage::isNoteOff (const bool returnTrueForNoteOnVelocity0) const throw()
  22302. {
  22303. return ((data[0] & 0xf0) == 0x80)
  22304. || (returnTrueForNoteOnVelocity0 && (data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  22305. }
  22306. bool MidiMessage::isNoteOnOrOff() const throw()
  22307. {
  22308. const int d = data[0] & 0xf0;
  22309. return (d == 0x90) || (d == 0x80);
  22310. }
  22311. int MidiMessage::getNoteNumber() const throw()
  22312. {
  22313. return data[1];
  22314. }
  22315. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  22316. {
  22317. if (isNoteOnOrOff())
  22318. data[1] = (uint8) jlimit (0, 127, newNoteNumber);
  22319. }
  22320. uint8 MidiMessage::getVelocity() const throw()
  22321. {
  22322. if (isNoteOnOrOff())
  22323. return data[2];
  22324. else
  22325. return 0;
  22326. }
  22327. float MidiMessage::getFloatVelocity() const throw()
  22328. {
  22329. return getVelocity() * (1.0f / 127.0f);
  22330. }
  22331. void MidiMessage::setVelocity (const float newVelocity) throw()
  22332. {
  22333. if (isNoteOnOrOff())
  22334. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (newVelocity * 127.0f));
  22335. }
  22336. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  22337. {
  22338. if (isNoteOnOrOff())
  22339. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (scaleFactor * data[2]));
  22340. }
  22341. bool MidiMessage::isAftertouch() const throw()
  22342. {
  22343. return (data[0] & 0xf0) == 0xa0;
  22344. }
  22345. int MidiMessage::getAfterTouchValue() const throw()
  22346. {
  22347. return data[2];
  22348. }
  22349. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  22350. const int noteNum,
  22351. const int aftertouchValue) throw()
  22352. {
  22353. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22354. jassert (((unsigned int) noteNum) <= 127);
  22355. jassert (((unsigned int) aftertouchValue) <= 127);
  22356. return MidiMessage (0xa0 | jlimit (0, 15, channel - 1),
  22357. noteNum & 0x7f,
  22358. aftertouchValue & 0x7f);
  22359. }
  22360. bool MidiMessage::isChannelPressure() const throw()
  22361. {
  22362. return (data[0] & 0xf0) == 0xd0;
  22363. }
  22364. int MidiMessage::getChannelPressureValue() const throw()
  22365. {
  22366. jassert (isChannelPressure());
  22367. return data[1];
  22368. }
  22369. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  22370. const int pressure) throw()
  22371. {
  22372. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22373. jassert (((unsigned int) pressure) <= 127);
  22374. return MidiMessage (0xd0 | jlimit (0, 15, channel - 1),
  22375. pressure & 0x7f);
  22376. }
  22377. bool MidiMessage::isProgramChange() const throw()
  22378. {
  22379. return (data[0] & 0xf0) == 0xc0;
  22380. }
  22381. int MidiMessage::getProgramChangeNumber() const throw()
  22382. {
  22383. return data[1];
  22384. }
  22385. const MidiMessage MidiMessage::programChange (const int channel,
  22386. const int programNumber) throw()
  22387. {
  22388. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22389. return MidiMessage (0xc0 | jlimit (0, 15, channel - 1),
  22390. programNumber & 0x7f);
  22391. }
  22392. bool MidiMessage::isPitchWheel() const throw()
  22393. {
  22394. return (data[0] & 0xf0) == 0xe0;
  22395. }
  22396. int MidiMessage::getPitchWheelValue() const throw()
  22397. {
  22398. return data[1] | (data[2] << 7);
  22399. }
  22400. const MidiMessage MidiMessage::pitchWheel (const int channel,
  22401. const int position) throw()
  22402. {
  22403. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  22404. jassert (((unsigned int) position) <= 0x3fff);
  22405. return MidiMessage (0xe0 | jlimit (0, 15, channel - 1),
  22406. position & 127,
  22407. (position >> 7) & 127);
  22408. }
  22409. bool MidiMessage::isController() const throw()
  22410. {
  22411. return (data[0] & 0xf0) == 0xb0;
  22412. }
  22413. int MidiMessage::getControllerNumber() const throw()
  22414. {
  22415. jassert (isController());
  22416. return data[1];
  22417. }
  22418. int MidiMessage::getControllerValue() const throw()
  22419. {
  22420. jassert (isController());
  22421. return data[2];
  22422. }
  22423. const MidiMessage MidiMessage::controllerEvent (const int channel,
  22424. const int controllerType,
  22425. const int value) throw()
  22426. {
  22427. // the channel must be between 1 and 16 inclusive
  22428. jassert (channel > 0 && channel <= 16);
  22429. return MidiMessage (0xb0 | jlimit (0, 15, channel - 1),
  22430. controllerType & 127,
  22431. value & 127);
  22432. }
  22433. const MidiMessage MidiMessage::noteOn (const int channel,
  22434. const int noteNumber,
  22435. const float velocity) throw()
  22436. {
  22437. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  22438. }
  22439. const MidiMessage MidiMessage::noteOn (const int channel,
  22440. const int noteNumber,
  22441. const uint8 velocity) throw()
  22442. {
  22443. jassert (channel > 0 && channel <= 16);
  22444. jassert (((unsigned int) noteNumber) <= 127);
  22445. return MidiMessage (0x90 | jlimit (0, 15, channel - 1),
  22446. noteNumber & 127,
  22447. jlimit (0, 127, roundToInt (velocity)));
  22448. }
  22449. const MidiMessage MidiMessage::noteOff (const int channel,
  22450. const int noteNumber) throw()
  22451. {
  22452. jassert (channel > 0 && channel <= 16);
  22453. jassert (((unsigned int) noteNumber) <= 127);
  22454. return MidiMessage (0x80 | jlimit (0, 15, channel - 1), noteNumber & 127, 0);
  22455. }
  22456. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  22457. {
  22458. jassert (channel > 0 && channel <= 16);
  22459. return controllerEvent (channel, 123, 0);
  22460. }
  22461. bool MidiMessage::isAllNotesOff() const throw()
  22462. {
  22463. return (data[0] & 0xf0) == 0xb0
  22464. && data[1] == 123;
  22465. }
  22466. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  22467. {
  22468. return controllerEvent (channel, 120, 0);
  22469. }
  22470. bool MidiMessage::isAllSoundOff() const throw()
  22471. {
  22472. return (data[0] & 0xf0) == 0xb0
  22473. && data[1] == 120;
  22474. }
  22475. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  22476. {
  22477. return controllerEvent (channel, 121, 0);
  22478. }
  22479. const MidiMessage MidiMessage::masterVolume (const float volume)
  22480. {
  22481. const int vol = jlimit (0, 0x3fff, roundToInt (volume * 0x4000));
  22482. uint8 buf[8];
  22483. buf[0] = 0xf0;
  22484. buf[1] = 0x7f;
  22485. buf[2] = 0x7f;
  22486. buf[3] = 0x04;
  22487. buf[4] = 0x01;
  22488. buf[5] = (uint8) (vol & 0x7f);
  22489. buf[6] = (uint8) (vol >> 7);
  22490. buf[7] = 0xf7;
  22491. return MidiMessage (buf, 8);
  22492. }
  22493. bool MidiMessage::isSysEx() const throw()
  22494. {
  22495. return *data == 0xf0;
  22496. }
  22497. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData, const int dataSize)
  22498. {
  22499. MemoryBlock mm (dataSize + 2);
  22500. uint8* const m = static_cast <uint8*> (mm.getData());
  22501. m[0] = 0xf0;
  22502. memcpy (m + 1, sysexData, dataSize);
  22503. m[dataSize + 1] = 0xf7;
  22504. return MidiMessage (m, dataSize + 2);
  22505. }
  22506. const uint8* MidiMessage::getSysExData() const throw()
  22507. {
  22508. return (isSysEx()) ? getRawData() + 1 : 0;
  22509. }
  22510. int MidiMessage::getSysExDataSize() const throw()
  22511. {
  22512. return (isSysEx()) ? size - 2 : 0;
  22513. }
  22514. bool MidiMessage::isMetaEvent() const throw()
  22515. {
  22516. return *data == 0xff;
  22517. }
  22518. bool MidiMessage::isActiveSense() const throw()
  22519. {
  22520. return *data == 0xfe;
  22521. }
  22522. int MidiMessage::getMetaEventType() const throw()
  22523. {
  22524. if (*data != 0xff)
  22525. return -1;
  22526. else
  22527. return data[1];
  22528. }
  22529. int MidiMessage::getMetaEventLength() const throw()
  22530. {
  22531. if (*data == 0xff)
  22532. {
  22533. int n;
  22534. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  22535. }
  22536. return 0;
  22537. }
  22538. const uint8* MidiMessage::getMetaEventData() const throw()
  22539. {
  22540. int n;
  22541. const uint8* d = data + 2;
  22542. readVariableLengthVal (d, n);
  22543. return d + n;
  22544. }
  22545. bool MidiMessage::isTrackMetaEvent() const throw()
  22546. {
  22547. return getMetaEventType() == 0;
  22548. }
  22549. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  22550. {
  22551. return getMetaEventType() == 47;
  22552. }
  22553. bool MidiMessage::isTextMetaEvent() const throw()
  22554. {
  22555. const int t = getMetaEventType();
  22556. return t > 0 && t < 16;
  22557. }
  22558. const String MidiMessage::getTextFromTextMetaEvent() const
  22559. {
  22560. return String (reinterpret_cast <const char*> (getMetaEventData()), getMetaEventLength());
  22561. }
  22562. bool MidiMessage::isTrackNameEvent() const throw()
  22563. {
  22564. return (data[1] == 3)
  22565. && (*data == 0xff);
  22566. }
  22567. bool MidiMessage::isTempoMetaEvent() const throw()
  22568. {
  22569. return (data[1] == 81)
  22570. && (*data == 0xff);
  22571. }
  22572. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  22573. {
  22574. return (data[1] == 0x20)
  22575. && (*data == 0xff)
  22576. && (data[2] == 1);
  22577. }
  22578. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  22579. {
  22580. return data[3] + 1;
  22581. }
  22582. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  22583. {
  22584. if (! isTempoMetaEvent())
  22585. return 0.0;
  22586. const uint8* const d = getMetaEventData();
  22587. return (((unsigned int) d[0] << 16)
  22588. | ((unsigned int) d[1] << 8)
  22589. | d[2])
  22590. / 1000000.0;
  22591. }
  22592. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  22593. {
  22594. if (timeFormat > 0)
  22595. {
  22596. if (! isTempoMetaEvent())
  22597. return 0.5 / timeFormat;
  22598. return getTempoSecondsPerQuarterNote() / timeFormat;
  22599. }
  22600. else
  22601. {
  22602. const int frameCode = (-timeFormat) >> 8;
  22603. double framesPerSecond;
  22604. switch (frameCode)
  22605. {
  22606. case 24: framesPerSecond = 24.0; break;
  22607. case 25: framesPerSecond = 25.0; break;
  22608. case 29: framesPerSecond = 29.97; break;
  22609. case 30: framesPerSecond = 30.0; break;
  22610. default: framesPerSecond = 30.0; break;
  22611. }
  22612. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  22613. }
  22614. }
  22615. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  22616. {
  22617. uint8 d[8];
  22618. d[0] = 0xff;
  22619. d[1] = 81;
  22620. d[2] = 3;
  22621. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  22622. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  22623. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  22624. return MidiMessage (d, 6, 0.0);
  22625. }
  22626. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  22627. {
  22628. return (data[1] == 0x58)
  22629. && (*data == (uint8) 0xff);
  22630. }
  22631. void MidiMessage::getTimeSignatureInfo (int& numerator, int& denominator) const throw()
  22632. {
  22633. if (isTimeSignatureMetaEvent())
  22634. {
  22635. const uint8* const d = getMetaEventData();
  22636. numerator = d[0];
  22637. denominator = 1 << d[1];
  22638. }
  22639. else
  22640. {
  22641. numerator = 4;
  22642. denominator = 4;
  22643. }
  22644. }
  22645. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator, const int denominator)
  22646. {
  22647. uint8 d[8];
  22648. d[0] = 0xff;
  22649. d[1] = 0x58;
  22650. d[2] = 0x04;
  22651. d[3] = (uint8) numerator;
  22652. int n = 1;
  22653. int powerOfTwo = 0;
  22654. while (n < denominator)
  22655. {
  22656. n <<= 1;
  22657. ++powerOfTwo;
  22658. }
  22659. d[4] = (uint8) powerOfTwo;
  22660. d[5] = 0x01;
  22661. d[6] = 96;
  22662. return MidiMessage (d, 7, 0.0);
  22663. }
  22664. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  22665. {
  22666. uint8 d[8];
  22667. d[0] = 0xff;
  22668. d[1] = 0x20;
  22669. d[2] = 0x01;
  22670. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  22671. return MidiMessage (d, 4, 0.0);
  22672. }
  22673. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  22674. {
  22675. return getMetaEventType() == 89;
  22676. }
  22677. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  22678. {
  22679. return (int) *getMetaEventData();
  22680. }
  22681. const MidiMessage MidiMessage::endOfTrack() throw()
  22682. {
  22683. return MidiMessage (0xff, 0x2f, 0, 0.0);
  22684. }
  22685. bool MidiMessage::isSongPositionPointer() const throw()
  22686. {
  22687. return *data == 0xf2;
  22688. }
  22689. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  22690. {
  22691. return data[1] | (data[2] << 7);
  22692. }
  22693. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  22694. {
  22695. return MidiMessage (0xf2,
  22696. positionInMidiBeats & 127,
  22697. (positionInMidiBeats >> 7) & 127);
  22698. }
  22699. bool MidiMessage::isMidiStart() const throw()
  22700. {
  22701. return *data == 0xfa;
  22702. }
  22703. const MidiMessage MidiMessage::midiStart() throw()
  22704. {
  22705. return MidiMessage (0xfa);
  22706. }
  22707. bool MidiMessage::isMidiContinue() const throw()
  22708. {
  22709. return *data == 0xfb;
  22710. }
  22711. const MidiMessage MidiMessage::midiContinue() throw()
  22712. {
  22713. return MidiMessage (0xfb);
  22714. }
  22715. bool MidiMessage::isMidiStop() const throw()
  22716. {
  22717. return *data == 0xfc;
  22718. }
  22719. const MidiMessage MidiMessage::midiStop() throw()
  22720. {
  22721. return MidiMessage (0xfc);
  22722. }
  22723. bool MidiMessage::isMidiClock() const throw()
  22724. {
  22725. return *data == 0xf8;
  22726. }
  22727. const MidiMessage MidiMessage::midiClock() throw()
  22728. {
  22729. return MidiMessage (0xf8);
  22730. }
  22731. bool MidiMessage::isQuarterFrame() const throw()
  22732. {
  22733. return *data == 0xf1;
  22734. }
  22735. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  22736. {
  22737. return ((int) data[1]) >> 4;
  22738. }
  22739. int MidiMessage::getQuarterFrameValue() const throw()
  22740. {
  22741. return ((int) data[1]) & 0x0f;
  22742. }
  22743. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  22744. const int value) throw()
  22745. {
  22746. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  22747. }
  22748. bool MidiMessage::isFullFrame() const throw()
  22749. {
  22750. return data[0] == 0xf0
  22751. && data[1] == 0x7f
  22752. && size >= 10
  22753. && data[3] == 0x01
  22754. && data[4] == 0x01;
  22755. }
  22756. void MidiMessage::getFullFrameParameters (int& hours,
  22757. int& minutes,
  22758. int& seconds,
  22759. int& frames,
  22760. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  22761. {
  22762. jassert (isFullFrame());
  22763. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  22764. hours = data[5] & 0x1f;
  22765. minutes = data[6];
  22766. seconds = data[7];
  22767. frames = data[8];
  22768. }
  22769. const MidiMessage MidiMessage::fullFrame (const int hours,
  22770. const int minutes,
  22771. const int seconds,
  22772. const int frames,
  22773. MidiMessage::SmpteTimecodeType timecodeType)
  22774. {
  22775. uint8 d[10];
  22776. d[0] = 0xf0;
  22777. d[1] = 0x7f;
  22778. d[2] = 0x7f;
  22779. d[3] = 0x01;
  22780. d[4] = 0x01;
  22781. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  22782. d[6] = (uint8) minutes;
  22783. d[7] = (uint8) seconds;
  22784. d[8] = (uint8) frames;
  22785. d[9] = 0xf7;
  22786. return MidiMessage (d, 10, 0.0);
  22787. }
  22788. bool MidiMessage::isMidiMachineControlMessage() const throw()
  22789. {
  22790. return data[0] == 0xf0
  22791. && data[1] == 0x7f
  22792. && data[3] == 0x06
  22793. && size > 5;
  22794. }
  22795. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  22796. {
  22797. jassert (isMidiMachineControlMessage());
  22798. return (MidiMachineControlCommand) data[4];
  22799. }
  22800. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  22801. {
  22802. uint8 d[6];
  22803. d[0] = 0xf0;
  22804. d[1] = 0x7f;
  22805. d[2] = 0x00;
  22806. d[3] = 0x06;
  22807. d[4] = (uint8) command;
  22808. d[5] = 0xf7;
  22809. return MidiMessage (d, 6, 0.0);
  22810. }
  22811. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  22812. int& minutes,
  22813. int& seconds,
  22814. int& frames) const throw()
  22815. {
  22816. if (size >= 12
  22817. && data[0] == 0xf0
  22818. && data[1] == 0x7f
  22819. && data[3] == 0x06
  22820. && data[4] == 0x44
  22821. && data[5] == 0x06
  22822. && data[6] == 0x01)
  22823. {
  22824. hours = data[7] % 24; // (that some machines send out hours > 24)
  22825. minutes = data[8];
  22826. seconds = data[9];
  22827. frames = data[10];
  22828. return true;
  22829. }
  22830. return false;
  22831. }
  22832. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  22833. int minutes,
  22834. int seconds,
  22835. int frames)
  22836. {
  22837. uint8 d[12];
  22838. d[0] = 0xf0;
  22839. d[1] = 0x7f;
  22840. d[2] = 0x00;
  22841. d[3] = 0x06;
  22842. d[4] = 0x44;
  22843. d[5] = 0x06;
  22844. d[6] = 0x01;
  22845. d[7] = (uint8) hours;
  22846. d[8] = (uint8) minutes;
  22847. d[9] = (uint8) seconds;
  22848. d[10] = (uint8) frames;
  22849. d[11] = 0xf7;
  22850. return MidiMessage (d, 12, 0.0);
  22851. }
  22852. const String MidiMessage::getMidiNoteName (int note,
  22853. bool useSharps,
  22854. bool includeOctaveNumber,
  22855. int octaveNumForMiddleC) throw()
  22856. {
  22857. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E",
  22858. "F", "F#", "G", "G#", "A",
  22859. "A#", "B" };
  22860. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E",
  22861. "F", "Gb", "G", "Ab", "A",
  22862. "Bb", "B" };
  22863. if (((unsigned int) note) < 128)
  22864. {
  22865. const String s ((useSharps) ? sharpNoteNames [note % 12]
  22866. : flatNoteNames [note % 12]);
  22867. if (includeOctaveNumber)
  22868. return s + String (note / 12 + (octaveNumForMiddleC - 5));
  22869. else
  22870. return s;
  22871. }
  22872. return String::empty;
  22873. }
  22874. const double MidiMessage::getMidiNoteInHertz (int noteNumber) throw()
  22875. {
  22876. noteNumber -= 12 * 6 + 9; // now 0 = A440
  22877. return 440.0 * pow (2.0, noteNumber / 12.0);
  22878. }
  22879. const String MidiMessage::getGMInstrumentName (int n) throw()
  22880. {
  22881. const char *names[] =
  22882. {
  22883. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  22884. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  22885. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  22886. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  22887. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  22888. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  22889. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  22890. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  22891. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  22892. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  22893. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  22894. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  22895. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  22896. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  22897. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  22898. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  22899. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  22900. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  22901. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  22902. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  22903. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  22904. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  22905. "Applause", "Gunshot"
  22906. };
  22907. return (((unsigned int) n) < 128) ? names[n]
  22908. : (const char*)0;
  22909. }
  22910. const String MidiMessage::getGMInstrumentBankName (int n) throw()
  22911. {
  22912. const char* names[] =
  22913. {
  22914. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  22915. "Bass", "Strings", "Ensemble", "Brass",
  22916. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  22917. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  22918. };
  22919. return (((unsigned int) n) <= 15) ? names[n]
  22920. : (const char*)0;
  22921. }
  22922. const String MidiMessage::getRhythmInstrumentName (int n) throw()
  22923. {
  22924. const char* names[] =
  22925. {
  22926. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  22927. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  22928. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  22929. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  22930. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  22931. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  22932. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  22933. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  22934. "Mute Triangle", "Open Triangle"
  22935. };
  22936. return (n >= 35 && n <= 81) ? names [n - 35]
  22937. : (const char*)0;
  22938. }
  22939. const String MidiMessage::getControllerName (int n) throw()
  22940. {
  22941. const char* names[] =
  22942. {
  22943. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  22944. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  22945. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  22946. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  22947. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  22948. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  22949. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  22950. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  22951. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  22952. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  22953. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  22954. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  22955. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  22956. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  22957. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  22958. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  22959. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  22960. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  22961. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  22962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  22963. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  22964. "Poly Operation"
  22965. };
  22966. return (((unsigned int) n) < 128) ? names[n]
  22967. : (const char*)0;
  22968. }
  22969. END_JUCE_NAMESPACE
  22970. /*** End of inlined file: juce_MidiMessage.cpp ***/
  22971. /*** Start of inlined file: juce_MidiMessageCollector.cpp ***/
  22972. BEGIN_JUCE_NAMESPACE
  22973. MidiMessageCollector::MidiMessageCollector()
  22974. : lastCallbackTime (0),
  22975. sampleRate (44100.0001)
  22976. {
  22977. }
  22978. MidiMessageCollector::~MidiMessageCollector()
  22979. {
  22980. }
  22981. void MidiMessageCollector::reset (const double sampleRate_)
  22982. {
  22983. jassert (sampleRate_ > 0);
  22984. const ScopedLock sl (midiCallbackLock);
  22985. sampleRate = sampleRate_;
  22986. incomingMessages.clear();
  22987. lastCallbackTime = Time::getMillisecondCounterHiRes();
  22988. }
  22989. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  22990. {
  22991. // you need to call reset() to set the correct sample rate before using this object
  22992. jassert (sampleRate != 44100.0001);
  22993. // the messages that come in here need to be time-stamped correctly - see MidiInput
  22994. // for details of what the number should be.
  22995. jassert (message.getTimeStamp() != 0);
  22996. const ScopedLock sl (midiCallbackLock);
  22997. const int sampleNumber
  22998. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  22999. incomingMessages.addEvent (message, sampleNumber);
  23000. // if the messages don't get used for over a second, we'd better
  23001. // get rid of any old ones to avoid the queue getting too big
  23002. if (sampleNumber > sampleRate)
  23003. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  23004. }
  23005. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  23006. const int numSamples)
  23007. {
  23008. // you need to call reset() to set the correct sample rate before using this object
  23009. jassert (sampleRate != 44100.0001);
  23010. const double timeNow = Time::getMillisecondCounterHiRes();
  23011. const double msElapsed = timeNow - lastCallbackTime;
  23012. const ScopedLock sl (midiCallbackLock);
  23013. lastCallbackTime = timeNow;
  23014. if (! incomingMessages.isEmpty())
  23015. {
  23016. int numSourceSamples = jmax (1, roundToInt (msElapsed * 0.001 * sampleRate));
  23017. int startSample = 0;
  23018. int scale = 1 << 16;
  23019. const uint8* midiData;
  23020. int numBytes, samplePosition;
  23021. MidiBuffer::Iterator iter (incomingMessages);
  23022. if (numSourceSamples > numSamples)
  23023. {
  23024. // if our list of events is longer than the buffer we're being
  23025. // asked for, scale them down to squeeze them all in..
  23026. const int maxBlockLengthToUse = numSamples << 5;
  23027. if (numSourceSamples > maxBlockLengthToUse)
  23028. {
  23029. startSample = numSourceSamples - maxBlockLengthToUse;
  23030. numSourceSamples = maxBlockLengthToUse;
  23031. iter.setNextSamplePosition (startSample);
  23032. }
  23033. scale = (numSamples << 10) / numSourceSamples;
  23034. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23035. {
  23036. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  23037. destBuffer.addEvent (midiData, numBytes,
  23038. jlimit (0, numSamples - 1, samplePosition));
  23039. }
  23040. }
  23041. else
  23042. {
  23043. // if our event list is shorter than the number we need, put them
  23044. // towards the end of the buffer
  23045. startSample = numSamples - numSourceSamples;
  23046. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23047. {
  23048. destBuffer.addEvent (midiData, numBytes,
  23049. jlimit (0, numSamples - 1, samplePosition + startSample));
  23050. }
  23051. }
  23052. incomingMessages.clear();
  23053. }
  23054. }
  23055. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  23056. {
  23057. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  23058. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23059. addMessageToQueue (m);
  23060. }
  23061. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  23062. {
  23063. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  23064. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23065. addMessageToQueue (m);
  23066. }
  23067. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  23068. {
  23069. addMessageToQueue (message);
  23070. }
  23071. END_JUCE_NAMESPACE
  23072. /*** End of inlined file: juce_MidiMessageCollector.cpp ***/
  23073. /*** Start of inlined file: juce_MidiMessageSequence.cpp ***/
  23074. BEGIN_JUCE_NAMESPACE
  23075. MidiMessageSequence::MidiMessageSequence()
  23076. {
  23077. }
  23078. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  23079. {
  23080. list.ensureStorageAllocated (other.list.size());
  23081. for (int i = 0; i < other.list.size(); ++i)
  23082. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  23083. }
  23084. MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  23085. {
  23086. MidiMessageSequence otherCopy (other);
  23087. swapWith (otherCopy);
  23088. return *this;
  23089. }
  23090. void MidiMessageSequence::swapWith (MidiMessageSequence& other) throw()
  23091. {
  23092. list.swapWithArray (other.list);
  23093. }
  23094. MidiMessageSequence::~MidiMessageSequence()
  23095. {
  23096. }
  23097. void MidiMessageSequence::clear()
  23098. {
  23099. list.clear();
  23100. }
  23101. int MidiMessageSequence::getNumEvents() const
  23102. {
  23103. return list.size();
  23104. }
  23105. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  23106. {
  23107. return list [index];
  23108. }
  23109. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  23110. {
  23111. const MidiEventHolder* const meh = list [index];
  23112. if (meh != 0 && meh->noteOffObject != 0)
  23113. return meh->noteOffObject->message.getTimeStamp();
  23114. else
  23115. return 0.0;
  23116. }
  23117. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  23118. {
  23119. const MidiEventHolder* const meh = list [index];
  23120. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  23121. }
  23122. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  23123. {
  23124. return list.indexOf (event);
  23125. }
  23126. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  23127. {
  23128. const int numEvents = list.size();
  23129. int i;
  23130. for (i = 0; i < numEvents; ++i)
  23131. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  23132. break;
  23133. return i;
  23134. }
  23135. double MidiMessageSequence::getStartTime() const
  23136. {
  23137. if (list.size() > 0)
  23138. return list.getUnchecked(0)->message.getTimeStamp();
  23139. else
  23140. return 0;
  23141. }
  23142. double MidiMessageSequence::getEndTime() const
  23143. {
  23144. if (list.size() > 0)
  23145. return list.getLast()->message.getTimeStamp();
  23146. else
  23147. return 0;
  23148. }
  23149. double MidiMessageSequence::getEventTime (const int index) const
  23150. {
  23151. if (((unsigned int) index) < (unsigned int) list.size())
  23152. return list.getUnchecked (index)->message.getTimeStamp();
  23153. return 0.0;
  23154. }
  23155. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  23156. double timeAdjustment)
  23157. {
  23158. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  23159. timeAdjustment += newMessage.getTimeStamp();
  23160. newOne->message.setTimeStamp (timeAdjustment);
  23161. int i;
  23162. for (i = list.size(); --i >= 0;)
  23163. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  23164. break;
  23165. list.insert (i + 1, newOne);
  23166. }
  23167. void MidiMessageSequence::deleteEvent (const int index,
  23168. const bool deleteMatchingNoteUp)
  23169. {
  23170. if (((unsigned int) index) < (unsigned int) list.size())
  23171. {
  23172. if (deleteMatchingNoteUp)
  23173. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  23174. list.remove (index);
  23175. }
  23176. }
  23177. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  23178. double timeAdjustment,
  23179. double firstAllowableTime,
  23180. double endOfAllowableDestTimes)
  23181. {
  23182. firstAllowableTime -= timeAdjustment;
  23183. endOfAllowableDestTimes -= timeAdjustment;
  23184. for (int i = 0; i < other.list.size(); ++i)
  23185. {
  23186. const MidiMessage& m = other.list.getUnchecked(i)->message;
  23187. const double t = m.getTimeStamp();
  23188. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  23189. {
  23190. MidiEventHolder* const newOne = new MidiEventHolder (m);
  23191. newOne->message.setTimeStamp (timeAdjustment + t);
  23192. list.add (newOne);
  23193. }
  23194. }
  23195. sort();
  23196. }
  23197. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  23198. const MidiMessageSequence::MidiEventHolder* const second) throw()
  23199. {
  23200. const double diff = first->message.getTimeStamp()
  23201. - second->message.getTimeStamp();
  23202. return (diff > 0) - (diff < 0);
  23203. }
  23204. void MidiMessageSequence::sort()
  23205. {
  23206. list.sort (*this, true);
  23207. }
  23208. void MidiMessageSequence::updateMatchedPairs()
  23209. {
  23210. for (int i = 0; i < list.size(); ++i)
  23211. {
  23212. const MidiMessage& m1 = list.getUnchecked(i)->message;
  23213. if (m1.isNoteOn())
  23214. {
  23215. list.getUnchecked(i)->noteOffObject = 0;
  23216. const int note = m1.getNoteNumber();
  23217. const int chan = m1.getChannel();
  23218. const int len = list.size();
  23219. for (int j = i + 1; j < len; ++j)
  23220. {
  23221. const MidiMessage& m = list.getUnchecked(j)->message;
  23222. if (m.getNoteNumber() == note && m.getChannel() == chan)
  23223. {
  23224. if (m.isNoteOff())
  23225. {
  23226. list.getUnchecked(i)->noteOffObject = list[j];
  23227. break;
  23228. }
  23229. else if (m.isNoteOn())
  23230. {
  23231. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  23232. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  23233. list.getUnchecked(i)->noteOffObject = list[j];
  23234. break;
  23235. }
  23236. }
  23237. }
  23238. }
  23239. }
  23240. }
  23241. void MidiMessageSequence::addTimeToMessages (const double delta)
  23242. {
  23243. for (int i = list.size(); --i >= 0;)
  23244. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  23245. + delta);
  23246. }
  23247. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  23248. MidiMessageSequence& destSequence,
  23249. const bool alsoIncludeMetaEvents) const
  23250. {
  23251. for (int i = 0; i < list.size(); ++i)
  23252. {
  23253. const MidiMessage& mm = list.getUnchecked(i)->message;
  23254. if (mm.isForChannel (channelNumberToExtract)
  23255. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  23256. {
  23257. destSequence.addEvent (mm);
  23258. }
  23259. }
  23260. }
  23261. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  23262. {
  23263. for (int i = 0; i < list.size(); ++i)
  23264. {
  23265. const MidiMessage& mm = list.getUnchecked(i)->message;
  23266. if (mm.isSysEx())
  23267. destSequence.addEvent (mm);
  23268. }
  23269. }
  23270. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  23271. {
  23272. for (int i = list.size(); --i >= 0;)
  23273. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  23274. list.remove(i);
  23275. }
  23276. void MidiMessageSequence::deleteSysExMessages()
  23277. {
  23278. for (int i = list.size(); --i >= 0;)
  23279. if (list.getUnchecked(i)->message.isSysEx())
  23280. list.remove(i);
  23281. }
  23282. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  23283. const double time,
  23284. OwnedArray<MidiMessage>& dest)
  23285. {
  23286. bool doneProg = false;
  23287. bool donePitchWheel = false;
  23288. Array <int> doneControllers;
  23289. doneControllers.ensureStorageAllocated (32);
  23290. for (int i = list.size(); --i >= 0;)
  23291. {
  23292. const MidiMessage& mm = list.getUnchecked(i)->message;
  23293. if (mm.isForChannel (channelNumber)
  23294. && mm.getTimeStamp() <= time)
  23295. {
  23296. if (mm.isProgramChange())
  23297. {
  23298. if (! doneProg)
  23299. {
  23300. dest.add (new MidiMessage (mm, 0.0));
  23301. doneProg = true;
  23302. }
  23303. }
  23304. else if (mm.isController())
  23305. {
  23306. if (! doneControllers.contains (mm.getControllerNumber()))
  23307. {
  23308. dest.add (new MidiMessage (mm, 0.0));
  23309. doneControllers.add (mm.getControllerNumber());
  23310. }
  23311. }
  23312. else if (mm.isPitchWheel())
  23313. {
  23314. if (! donePitchWheel)
  23315. {
  23316. dest.add (new MidiMessage (mm, 0.0));
  23317. donePitchWheel = true;
  23318. }
  23319. }
  23320. }
  23321. }
  23322. }
  23323. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  23324. : message (message_),
  23325. noteOffObject (0)
  23326. {
  23327. }
  23328. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  23329. {
  23330. }
  23331. END_JUCE_NAMESPACE
  23332. /*** End of inlined file: juce_MidiMessageSequence.cpp ***/
  23333. /*** Start of inlined file: juce_AudioPluginFormat.cpp ***/
  23334. BEGIN_JUCE_NAMESPACE
  23335. AudioPluginFormat::AudioPluginFormat() throw()
  23336. {
  23337. }
  23338. AudioPluginFormat::~AudioPluginFormat()
  23339. {
  23340. }
  23341. END_JUCE_NAMESPACE
  23342. /*** End of inlined file: juce_AudioPluginFormat.cpp ***/
  23343. /*** Start of inlined file: juce_AudioPluginFormatManager.cpp ***/
  23344. BEGIN_JUCE_NAMESPACE
  23345. AudioPluginFormatManager::AudioPluginFormatManager() throw()
  23346. {
  23347. }
  23348. AudioPluginFormatManager::~AudioPluginFormatManager() throw()
  23349. {
  23350. clearSingletonInstance();
  23351. }
  23352. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  23353. void AudioPluginFormatManager::addDefaultFormats()
  23354. {
  23355. #if JUCE_DEBUG
  23356. // you should only call this method once!
  23357. for (int i = formats.size(); --i >= 0;)
  23358. {
  23359. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  23360. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  23361. #endif
  23362. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  23363. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  23364. #endif
  23365. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  23366. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  23367. #endif
  23368. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  23369. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  23370. #endif
  23371. }
  23372. #endif
  23373. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  23374. formats.add (new AudioUnitPluginFormat());
  23375. #endif
  23376. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  23377. formats.add (new VSTPluginFormat());
  23378. #endif
  23379. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  23380. formats.add (new DirectXPluginFormat());
  23381. #endif
  23382. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  23383. formats.add (new LADSPAPluginFormat());
  23384. #endif
  23385. }
  23386. int AudioPluginFormatManager::getNumFormats() throw()
  23387. {
  23388. return formats.size();
  23389. }
  23390. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index) throw()
  23391. {
  23392. return formats [index];
  23393. }
  23394. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format) throw()
  23395. {
  23396. formats.add (format);
  23397. }
  23398. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  23399. String& errorMessage) const
  23400. {
  23401. AudioPluginInstance* result = 0;
  23402. for (int i = 0; i < formats.size(); ++i)
  23403. {
  23404. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  23405. if (result != 0)
  23406. break;
  23407. }
  23408. if (result == 0)
  23409. {
  23410. if (! doesPluginStillExist (description))
  23411. errorMessage = TRANS ("This plug-in file no longer exists");
  23412. else
  23413. errorMessage = TRANS ("This plug-in failed to load correctly");
  23414. }
  23415. return result;
  23416. }
  23417. bool AudioPluginFormatManager::doesPluginStillExist (const PluginDescription& description) const
  23418. {
  23419. for (int i = 0; i < formats.size(); ++i)
  23420. if (formats.getUnchecked(i)->getName() == description.pluginFormatName)
  23421. return formats.getUnchecked(i)->doesPluginStillExist (description);
  23422. return false;
  23423. }
  23424. END_JUCE_NAMESPACE
  23425. /*** End of inlined file: juce_AudioPluginFormatManager.cpp ***/
  23426. /*** Start of inlined file: juce_AudioPluginInstance.cpp ***/
  23427. #define JUCE_PLUGIN_HOST 1
  23428. BEGIN_JUCE_NAMESPACE
  23429. AudioPluginInstance::AudioPluginInstance()
  23430. {
  23431. }
  23432. AudioPluginInstance::~AudioPluginInstance()
  23433. {
  23434. }
  23435. END_JUCE_NAMESPACE
  23436. /*** End of inlined file: juce_AudioPluginInstance.cpp ***/
  23437. /*** Start of inlined file: juce_KnownPluginList.cpp ***/
  23438. BEGIN_JUCE_NAMESPACE
  23439. KnownPluginList::KnownPluginList()
  23440. {
  23441. }
  23442. KnownPluginList::~KnownPluginList()
  23443. {
  23444. }
  23445. void KnownPluginList::clear()
  23446. {
  23447. if (types.size() > 0)
  23448. {
  23449. types.clear();
  23450. sendChangeMessage (this);
  23451. }
  23452. }
  23453. PluginDescription* KnownPluginList::getTypeForFile (const String& fileOrIdentifier) const throw()
  23454. {
  23455. for (int i = 0; i < types.size(); ++i)
  23456. if (types.getUnchecked(i)->fileOrIdentifier == fileOrIdentifier)
  23457. return types.getUnchecked(i);
  23458. return 0;
  23459. }
  23460. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const throw()
  23461. {
  23462. for (int i = 0; i < types.size(); ++i)
  23463. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  23464. return types.getUnchecked(i);
  23465. return 0;
  23466. }
  23467. bool KnownPluginList::addType (const PluginDescription& type)
  23468. {
  23469. for (int i = types.size(); --i >= 0;)
  23470. {
  23471. if (types.getUnchecked(i)->isDuplicateOf (type))
  23472. {
  23473. // strange - found a duplicate plugin with different info..
  23474. jassert (types.getUnchecked(i)->name == type.name);
  23475. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  23476. *types.getUnchecked(i) = type;
  23477. return false;
  23478. }
  23479. }
  23480. types.add (new PluginDescription (type));
  23481. sendChangeMessage (this);
  23482. return true;
  23483. }
  23484. void KnownPluginList::removeType (const int index) throw()
  23485. {
  23486. types.remove (index);
  23487. sendChangeMessage (this);
  23488. }
  23489. static Time getFileModTime (const String& fileOrIdentifier) throw()
  23490. {
  23491. if (fileOrIdentifier.startsWithChar ('/')
  23492. || fileOrIdentifier[1] == ':')
  23493. {
  23494. return File (fileOrIdentifier).getLastModificationTime();
  23495. }
  23496. return Time (0);
  23497. }
  23498. static bool timesAreDifferent (const Time& t1, const Time& t2) throw()
  23499. {
  23500. return t1 != t2 || t1 == Time (0);
  23501. }
  23502. bool KnownPluginList::isListingUpToDate (const String& fileOrIdentifier) const throw()
  23503. {
  23504. if (getTypeForFile (fileOrIdentifier) == 0)
  23505. return false;
  23506. for (int i = types.size(); --i >= 0;)
  23507. {
  23508. const PluginDescription* const d = types.getUnchecked(i);
  23509. if (d->fileOrIdentifier == fileOrIdentifier
  23510. && timesAreDifferent (d->lastFileModTime, getFileModTime (fileOrIdentifier)))
  23511. {
  23512. return false;
  23513. }
  23514. }
  23515. return true;
  23516. }
  23517. bool KnownPluginList::scanAndAddFile (const String& fileOrIdentifier,
  23518. const bool dontRescanIfAlreadyInList,
  23519. OwnedArray <PluginDescription>& typesFound,
  23520. AudioPluginFormat& format)
  23521. {
  23522. bool addedOne = false;
  23523. if (dontRescanIfAlreadyInList
  23524. && getTypeForFile (fileOrIdentifier) != 0)
  23525. {
  23526. bool needsRescanning = false;
  23527. for (int i = types.size(); --i >= 0;)
  23528. {
  23529. const PluginDescription* const d = types.getUnchecked(i);
  23530. if (d->fileOrIdentifier == fileOrIdentifier)
  23531. {
  23532. if (timesAreDifferent (d->lastFileModTime, getFileModTime (fileOrIdentifier)))
  23533. needsRescanning = true;
  23534. else
  23535. typesFound.add (new PluginDescription (*d));
  23536. }
  23537. }
  23538. if (! needsRescanning)
  23539. return false;
  23540. }
  23541. OwnedArray <PluginDescription> found;
  23542. format.findAllTypesForFile (found, fileOrIdentifier);
  23543. for (int i = 0; i < found.size(); ++i)
  23544. {
  23545. PluginDescription* const desc = found.getUnchecked(i);
  23546. jassert (desc != 0);
  23547. if (addType (*desc))
  23548. addedOne = true;
  23549. typesFound.add (new PluginDescription (*desc));
  23550. }
  23551. return addedOne;
  23552. }
  23553. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  23554. OwnedArray <PluginDescription>& typesFound)
  23555. {
  23556. for (int i = 0; i < files.size(); ++i)
  23557. {
  23558. bool loaded = false;
  23559. for (int j = 0; j < AudioPluginFormatManager::getInstance()->getNumFormats(); ++j)
  23560. {
  23561. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (j);
  23562. if (scanAndAddFile (files[i], true, typesFound, *format))
  23563. loaded = true;
  23564. }
  23565. if (! loaded)
  23566. {
  23567. const File f (files[i]);
  23568. if (f.isDirectory())
  23569. {
  23570. StringArray s;
  23571. {
  23572. Array<File> subFiles;
  23573. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  23574. for (int j = 0; j < subFiles.size(); ++j)
  23575. s.add (subFiles.getReference(j).getFullPathName());
  23576. }
  23577. scanAndAddDragAndDroppedFiles (s, typesFound);
  23578. }
  23579. }
  23580. }
  23581. }
  23582. class PluginSorter
  23583. {
  23584. public:
  23585. KnownPluginList::SortMethod method;
  23586. PluginSorter() throw() {}
  23587. int compareElements (const PluginDescription* const first,
  23588. const PluginDescription* const second) const throw()
  23589. {
  23590. int diff = 0;
  23591. if (method == KnownPluginList::sortByCategory)
  23592. diff = first->category.compareLexicographically (second->category);
  23593. else if (method == KnownPluginList::sortByManufacturer)
  23594. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  23595. else if (method == KnownPluginList::sortByFileSystemLocation)
  23596. diff = first->fileOrIdentifier.replaceCharacter ('\\', '/')
  23597. .upToLastOccurrenceOf ("/", false, false)
  23598. .compare (second->fileOrIdentifier.replaceCharacter ('\\', '/')
  23599. .upToLastOccurrenceOf ("/", false, false));
  23600. if (diff == 0)
  23601. diff = first->name.compareLexicographically (second->name);
  23602. return diff;
  23603. }
  23604. };
  23605. void KnownPluginList::sort (const SortMethod method)
  23606. {
  23607. if (method != defaultOrder)
  23608. {
  23609. PluginSorter sorter;
  23610. sorter.method = method;
  23611. types.sort (sorter, true);
  23612. sendChangeMessage (this);
  23613. }
  23614. }
  23615. XmlElement* KnownPluginList::createXml() const
  23616. {
  23617. XmlElement* const e = new XmlElement ("KNOWNPLUGINS");
  23618. for (int i = 0; i < types.size(); ++i)
  23619. e->addChildElement (types.getUnchecked(i)->createXml());
  23620. return e;
  23621. }
  23622. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  23623. {
  23624. clear();
  23625. if (xml.hasTagName ("KNOWNPLUGINS"))
  23626. {
  23627. forEachXmlChildElement (xml, e)
  23628. {
  23629. PluginDescription info;
  23630. if (info.loadFromXml (*e))
  23631. addType (info);
  23632. }
  23633. }
  23634. }
  23635. const int menuIdBase = 0x324503f4;
  23636. // This is used to turn a bunch of paths into a nested menu structure.
  23637. struct PluginFilesystemTree
  23638. {
  23639. private:
  23640. String folder;
  23641. OwnedArray <PluginFilesystemTree> subFolders;
  23642. Array <PluginDescription*> plugins;
  23643. void addPlugin (PluginDescription* const pd, const String& path)
  23644. {
  23645. if (path.isEmpty())
  23646. {
  23647. plugins.add (pd);
  23648. }
  23649. else
  23650. {
  23651. const String firstSubFolder (path.upToFirstOccurrenceOf ("/", false, false));
  23652. const String remainingPath (path.fromFirstOccurrenceOf ("/", false, false));
  23653. for (int i = subFolders.size(); --i >= 0;)
  23654. {
  23655. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  23656. {
  23657. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  23658. return;
  23659. }
  23660. }
  23661. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  23662. newFolder->folder = firstSubFolder;
  23663. subFolders.add (newFolder);
  23664. newFolder->addPlugin (pd, remainingPath);
  23665. }
  23666. }
  23667. // removes any deeply nested folders that don't contain any actual plugins
  23668. void optimise()
  23669. {
  23670. for (int i = subFolders.size(); --i >= 0;)
  23671. {
  23672. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  23673. sub->optimise();
  23674. if (sub->plugins.size() == 0)
  23675. {
  23676. for (int j = 0; j < sub->subFolders.size(); ++j)
  23677. subFolders.add (sub->subFolders.getUnchecked(j));
  23678. sub->subFolders.clear (false);
  23679. subFolders.remove (i);
  23680. }
  23681. }
  23682. }
  23683. public:
  23684. void buildTree (const Array <PluginDescription*>& allPlugins)
  23685. {
  23686. for (int i = 0; i < allPlugins.size(); ++i)
  23687. {
  23688. String path (allPlugins.getUnchecked(i)
  23689. ->fileOrIdentifier.replaceCharacter ('\\', '/')
  23690. .upToLastOccurrenceOf ("/", false, false));
  23691. if (path.substring (1, 2) == ":")
  23692. path = path.substring (2);
  23693. addPlugin (allPlugins.getUnchecked(i), path);
  23694. }
  23695. optimise();
  23696. }
  23697. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  23698. {
  23699. int i;
  23700. for (i = 0; i < subFolders.size(); ++i)
  23701. {
  23702. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  23703. PopupMenu subMenu;
  23704. sub->addToMenu (subMenu, allPlugins);
  23705. #if JUCE_MAC
  23706. // avoid the special AU formatting nonsense on Mac..
  23707. m.addSubMenu (sub->folder.fromFirstOccurrenceOf (":", false, false), subMenu);
  23708. #else
  23709. m.addSubMenu (sub->folder, subMenu);
  23710. #endif
  23711. }
  23712. for (i = 0; i < plugins.size(); ++i)
  23713. {
  23714. PluginDescription* const plugin = plugins.getUnchecked(i);
  23715. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  23716. plugin->name, true, false);
  23717. }
  23718. }
  23719. };
  23720. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  23721. {
  23722. Array <PluginDescription*> sorted;
  23723. {
  23724. PluginSorter sorter;
  23725. sorter.method = sortMethod;
  23726. for (int i = 0; i < types.size(); ++i)
  23727. sorted.addSorted (sorter, types.getUnchecked(i));
  23728. }
  23729. if (sortMethod == sortByCategory
  23730. || sortMethod == sortByManufacturer)
  23731. {
  23732. String lastSubMenuName;
  23733. PopupMenu sub;
  23734. for (int i = 0; i < sorted.size(); ++i)
  23735. {
  23736. const PluginDescription* const pd = sorted.getUnchecked(i);
  23737. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  23738. : pd->manufacturerName);
  23739. if (! thisSubMenuName.containsNonWhitespaceChars())
  23740. thisSubMenuName = "Other";
  23741. if (thisSubMenuName != lastSubMenuName)
  23742. {
  23743. if (sub.getNumItems() > 0)
  23744. {
  23745. menu.addSubMenu (lastSubMenuName, sub);
  23746. sub.clear();
  23747. }
  23748. lastSubMenuName = thisSubMenuName;
  23749. }
  23750. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  23751. }
  23752. if (sub.getNumItems() > 0)
  23753. menu.addSubMenu (lastSubMenuName, sub);
  23754. }
  23755. else if (sortMethod == sortByFileSystemLocation)
  23756. {
  23757. PluginFilesystemTree root;
  23758. root.buildTree (sorted);
  23759. root.addToMenu (menu, types);
  23760. }
  23761. else
  23762. {
  23763. for (int i = 0; i < sorted.size(); ++i)
  23764. {
  23765. const PluginDescription* const pd = sorted.getUnchecked(i);
  23766. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  23767. }
  23768. }
  23769. }
  23770. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  23771. {
  23772. const int i = menuResultCode - menuIdBase;
  23773. return (((unsigned int) i) < (unsigned int) types.size()) ? i : -1;
  23774. }
  23775. END_JUCE_NAMESPACE
  23776. /*** End of inlined file: juce_KnownPluginList.cpp ***/
  23777. /*** Start of inlined file: juce_PluginDescription.cpp ***/
  23778. BEGIN_JUCE_NAMESPACE
  23779. PluginDescription::PluginDescription() throw()
  23780. : uid (0),
  23781. isInstrument (false),
  23782. numInputChannels (0),
  23783. numOutputChannels (0)
  23784. {
  23785. }
  23786. PluginDescription::~PluginDescription() throw()
  23787. {
  23788. }
  23789. PluginDescription::PluginDescription (const PluginDescription& other) throw()
  23790. : name (other.name),
  23791. pluginFormatName (other.pluginFormatName),
  23792. category (other.category),
  23793. manufacturerName (other.manufacturerName),
  23794. version (other.version),
  23795. fileOrIdentifier (other.fileOrIdentifier),
  23796. lastFileModTime (other.lastFileModTime),
  23797. uid (other.uid),
  23798. isInstrument (other.isInstrument),
  23799. numInputChannels (other.numInputChannels),
  23800. numOutputChannels (other.numOutputChannels)
  23801. {
  23802. }
  23803. PluginDescription& PluginDescription::operator= (const PluginDescription& other) throw()
  23804. {
  23805. name = other.name;
  23806. pluginFormatName = other.pluginFormatName;
  23807. category = other.category;
  23808. manufacturerName = other.manufacturerName;
  23809. version = other.version;
  23810. fileOrIdentifier = other.fileOrIdentifier;
  23811. uid = other.uid;
  23812. isInstrument = other.isInstrument;
  23813. lastFileModTime = other.lastFileModTime;
  23814. numInputChannels = other.numInputChannels;
  23815. numOutputChannels = other.numOutputChannels;
  23816. return *this;
  23817. }
  23818. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  23819. {
  23820. return fileOrIdentifier == other.fileOrIdentifier
  23821. && uid == other.uid;
  23822. }
  23823. const String PluginDescription::createIdentifierString() const throw()
  23824. {
  23825. return pluginFormatName
  23826. + "-" + name
  23827. + "-" + String::toHexString (fileOrIdentifier.hashCode())
  23828. + "-" + String::toHexString (uid);
  23829. }
  23830. XmlElement* PluginDescription::createXml() const
  23831. {
  23832. XmlElement* const e = new XmlElement ("PLUGIN");
  23833. e->setAttribute ("name", name);
  23834. e->setAttribute ("format", pluginFormatName);
  23835. e->setAttribute ("category", category);
  23836. e->setAttribute ("manufacturer", manufacturerName);
  23837. e->setAttribute ("version", version);
  23838. e->setAttribute ("file", fileOrIdentifier);
  23839. e->setAttribute ("uid", String::toHexString (uid));
  23840. e->setAttribute ("isInstrument", isInstrument);
  23841. e->setAttribute ("fileTime", String::toHexString (lastFileModTime.toMilliseconds()));
  23842. e->setAttribute ("numInputs", numInputChannels);
  23843. e->setAttribute ("numOutputs", numOutputChannels);
  23844. return e;
  23845. }
  23846. bool PluginDescription::loadFromXml (const XmlElement& xml)
  23847. {
  23848. if (xml.hasTagName ("PLUGIN"))
  23849. {
  23850. name = xml.getStringAttribute ("name");
  23851. pluginFormatName = xml.getStringAttribute ("format");
  23852. category = xml.getStringAttribute ("category");
  23853. manufacturerName = xml.getStringAttribute ("manufacturer");
  23854. version = xml.getStringAttribute ("version");
  23855. fileOrIdentifier = xml.getStringAttribute ("file");
  23856. uid = xml.getStringAttribute ("uid").getHexValue32();
  23857. isInstrument = xml.getBoolAttribute ("isInstrument", false);
  23858. lastFileModTime = Time (xml.getStringAttribute ("fileTime").getHexValue64());
  23859. numInputChannels = xml.getIntAttribute ("numInputs");
  23860. numOutputChannels = xml.getIntAttribute ("numOutputs");
  23861. return true;
  23862. }
  23863. return false;
  23864. }
  23865. END_JUCE_NAMESPACE
  23866. /*** End of inlined file: juce_PluginDescription.cpp ***/
  23867. /*** Start of inlined file: juce_PluginDirectoryScanner.cpp ***/
  23868. BEGIN_JUCE_NAMESPACE
  23869. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  23870. AudioPluginFormat& formatToLookFor,
  23871. FileSearchPath directoriesToSearch,
  23872. const bool recursive,
  23873. const File& deadMansPedalFile_)
  23874. : list (listToAddTo),
  23875. format (formatToLookFor),
  23876. deadMansPedalFile (deadMansPedalFile_),
  23877. nextIndex (0),
  23878. progress (0)
  23879. {
  23880. directoriesToSearch.removeRedundantPaths();
  23881. filesOrIdentifiersToScan = format.searchPathsForPlugins (directoriesToSearch, recursive);
  23882. // If any plugins have crashed recently when being loaded, move them to the
  23883. // end of the list to give the others a chance to load correctly..
  23884. const StringArray crashedPlugins (getDeadMansPedalFile());
  23885. for (int i = 0; i < crashedPlugins.size(); ++i)
  23886. {
  23887. const String f = crashedPlugins[i];
  23888. for (int j = filesOrIdentifiersToScan.size(); --j >= 0;)
  23889. if (f == filesOrIdentifiersToScan[j])
  23890. filesOrIdentifiersToScan.move (j, -1);
  23891. }
  23892. }
  23893. PluginDirectoryScanner::~PluginDirectoryScanner()
  23894. {
  23895. }
  23896. const String PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const throw()
  23897. {
  23898. return format.getNameOfPluginFromIdentifier (filesOrIdentifiersToScan [nextIndex]);
  23899. }
  23900. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  23901. {
  23902. String file (filesOrIdentifiersToScan [nextIndex]);
  23903. if (file.isNotEmpty())
  23904. {
  23905. if (! list.isListingUpToDate (file))
  23906. {
  23907. OwnedArray <PluginDescription> typesFound;
  23908. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  23909. StringArray crashedPlugins (getDeadMansPedalFile());
  23910. crashedPlugins.removeString (file);
  23911. crashedPlugins.add (file);
  23912. setDeadMansPedalFile (crashedPlugins);
  23913. list.scanAndAddFile (file,
  23914. dontRescanIfAlreadyInList,
  23915. typesFound,
  23916. format);
  23917. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  23918. crashedPlugins.removeString (file);
  23919. setDeadMansPedalFile (crashedPlugins);
  23920. if (typesFound.size() == 0)
  23921. failedFiles.add (file);
  23922. }
  23923. ++nextIndex;
  23924. progress = nextIndex / (float) filesOrIdentifiersToScan.size();
  23925. }
  23926. return nextIndex < filesOrIdentifiersToScan.size();
  23927. }
  23928. const StringArray PluginDirectoryScanner::getDeadMansPedalFile() throw()
  23929. {
  23930. StringArray lines;
  23931. if (deadMansPedalFile != File::nonexistent)
  23932. {
  23933. lines.addLines (deadMansPedalFile.loadFileAsString());
  23934. lines.removeEmptyStrings();
  23935. }
  23936. return lines;
  23937. }
  23938. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents) throw()
  23939. {
  23940. if (deadMansPedalFile != File::nonexistent)
  23941. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  23942. }
  23943. END_JUCE_NAMESPACE
  23944. /*** End of inlined file: juce_PluginDirectoryScanner.cpp ***/
  23945. /*** Start of inlined file: juce_PluginListComponent.cpp ***/
  23946. BEGIN_JUCE_NAMESPACE
  23947. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  23948. const File& deadMansPedalFile_,
  23949. PropertiesFile* const propertiesToUse_)
  23950. : list (listToEdit),
  23951. deadMansPedalFile (deadMansPedalFile_),
  23952. propertiesToUse (propertiesToUse_)
  23953. {
  23954. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  23955. addAndMakeVisible (optionsButton = new TextButton ("Options..."));
  23956. optionsButton->addButtonListener (this);
  23957. optionsButton->setTriggeredOnMouseDown (true);
  23958. setSize (400, 600);
  23959. list.addChangeListener (this);
  23960. }
  23961. PluginListComponent::~PluginListComponent()
  23962. {
  23963. list.removeChangeListener (this);
  23964. deleteAllChildren();
  23965. }
  23966. void PluginListComponent::resized()
  23967. {
  23968. listBox->setBounds (0, 0, getWidth(), getHeight() - 30);
  23969. optionsButton->changeWidthToFitText (24);
  23970. optionsButton->setTopLeftPosition (8, getHeight() - 28);
  23971. }
  23972. void PluginListComponent::changeListenerCallback (void*)
  23973. {
  23974. listBox->updateContent();
  23975. listBox->repaint();
  23976. }
  23977. int PluginListComponent::getNumRows()
  23978. {
  23979. return list.getNumTypes();
  23980. }
  23981. void PluginListComponent::paintListBoxItem (int row,
  23982. Graphics& g,
  23983. int width, int height,
  23984. bool rowIsSelected)
  23985. {
  23986. if (rowIsSelected)
  23987. g.fillAll (findColour (TextEditor::highlightColourId));
  23988. const PluginDescription* const pd = list.getType (row);
  23989. if (pd != 0)
  23990. {
  23991. GlyphArrangement ga;
  23992. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  23993. g.setColour (Colours::black);
  23994. ga.draw (g);
  23995. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  23996. String desc;
  23997. desc << pd->pluginFormatName
  23998. << (pd->isInstrument ? " instrument" : " effect")
  23999. << " - "
  24000. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  24001. << " / "
  24002. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  24003. if (pd->manufacturerName.isNotEmpty())
  24004. desc << " - " << pd->manufacturerName;
  24005. if (pd->version.isNotEmpty())
  24006. desc << " - " << pd->version;
  24007. if (pd->category.isNotEmpty())
  24008. desc << " - category: '" << pd->category << '\'';
  24009. g.setColour (Colours::grey);
  24010. ga.clear();
  24011. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, bb.getRight() + 10.0f, height * 0.8f, width - bb.getRight() - 12.0f, true);
  24012. ga.draw (g);
  24013. }
  24014. }
  24015. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  24016. {
  24017. list.removeType (lastRowSelected);
  24018. }
  24019. void PluginListComponent::buttonClicked (Button* b)
  24020. {
  24021. if (optionsButton == b)
  24022. {
  24023. PopupMenu menu;
  24024. menu.addItem (1, TRANS("Clear list"));
  24025. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox->getNumSelectedRows() > 0);
  24026. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox->getNumSelectedRows() > 0);
  24027. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  24028. menu.addSeparator();
  24029. menu.addItem (2, TRANS("Sort alphabetically"));
  24030. menu.addItem (3, TRANS("Sort by category"));
  24031. menu.addItem (4, TRANS("Sort by manufacturer"));
  24032. menu.addSeparator();
  24033. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  24034. {
  24035. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  24036. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  24037. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  24038. }
  24039. const int r = menu.showAt (optionsButton);
  24040. if (r == 1)
  24041. {
  24042. list.clear();
  24043. }
  24044. else if (r == 2)
  24045. {
  24046. list.sort (KnownPluginList::sortAlphabetically);
  24047. }
  24048. else if (r == 3)
  24049. {
  24050. list.sort (KnownPluginList::sortByCategory);
  24051. }
  24052. else if (r == 4)
  24053. {
  24054. list.sort (KnownPluginList::sortByManufacturer);
  24055. }
  24056. else if (r == 5)
  24057. {
  24058. const SparseSet <int> selected (listBox->getSelectedRows());
  24059. for (int i = list.getNumTypes(); --i >= 0;)
  24060. if (selected.contains (i))
  24061. list.removeType (i);
  24062. }
  24063. else if (r == 6)
  24064. {
  24065. const PluginDescription* const desc = list.getType (listBox->getSelectedRow());
  24066. if (desc != 0)
  24067. {
  24068. if (File (desc->fileOrIdentifier).existsAsFile())
  24069. File (desc->fileOrIdentifier).getParentDirectory().startAsProcess();
  24070. }
  24071. }
  24072. else if (r == 7)
  24073. {
  24074. for (int i = list.getNumTypes(); --i >= 0;)
  24075. {
  24076. if (! AudioPluginFormatManager::getInstance()->doesPluginStillExist (*list.getType (i)))
  24077. {
  24078. list.removeType (i);
  24079. }
  24080. }
  24081. }
  24082. else if (r != 0)
  24083. {
  24084. typeToScan = r - 10;
  24085. startTimer (1);
  24086. }
  24087. }
  24088. }
  24089. void PluginListComponent::timerCallback()
  24090. {
  24091. stopTimer();
  24092. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  24093. }
  24094. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  24095. {
  24096. return true;
  24097. }
  24098. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  24099. {
  24100. OwnedArray <PluginDescription> typesFound;
  24101. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  24102. }
  24103. void PluginListComponent::scanFor (AudioPluginFormat* format)
  24104. {
  24105. if (format == 0)
  24106. return;
  24107. FileSearchPath path (format->getDefaultLocationsToSearch());
  24108. if (propertiesToUse != 0)
  24109. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24110. {
  24111. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  24112. FileSearchPathListComponent pathList;
  24113. pathList.setSize (500, 300);
  24114. pathList.setPath (path);
  24115. aw.addCustomComponent (&pathList);
  24116. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  24117. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  24118. if (aw.runModalLoop() == 0)
  24119. return;
  24120. path = pathList.getPath();
  24121. }
  24122. if (propertiesToUse != 0)
  24123. {
  24124. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24125. propertiesToUse->saveIfNeeded();
  24126. }
  24127. double progress = 0.0;
  24128. AlertWindow aw (TRANS("Scanning for plugins..."),
  24129. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  24130. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  24131. aw.addProgressBarComponent (progress);
  24132. aw.enterModalState();
  24133. MessageManager::getInstance()->runDispatchLoopUntil (300);
  24134. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  24135. for (;;)
  24136. {
  24137. aw.setMessage (TRANS("Testing:\n\n")
  24138. + scanner.getNextPluginFileThatWillBeScanned());
  24139. MessageManager::getInstance()->runDispatchLoopUntil (20);
  24140. if (! scanner.scanNextFile (true))
  24141. break;
  24142. if (! aw.isCurrentlyModal())
  24143. break;
  24144. progress = scanner.getProgress();
  24145. }
  24146. if (scanner.getFailedFiles().size() > 0)
  24147. {
  24148. StringArray shortNames;
  24149. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  24150. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  24151. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  24152. TRANS("Scan complete"),
  24153. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  24154. + shortNames.joinIntoString (", "));
  24155. }
  24156. }
  24157. END_JUCE_NAMESPACE
  24158. /*** End of inlined file: juce_PluginListComponent.cpp ***/
  24159. /*** Start of inlined file: juce_AudioUnitPluginFormat.mm ***/
  24160. #if JUCE_PLUGINHOST_AU && ! (JUCE_LINUX || JUCE_WINDOWS)
  24161. #include <AudioUnit/AudioUnit.h>
  24162. #include <AudioUnit/AUCocoaUIView.h>
  24163. #include <CoreAudioKit/AUGenericView.h>
  24164. #if JUCE_SUPPORT_CARBON
  24165. #include <AudioToolbox/AudioUnitUtilities.h>
  24166. #include <AudioUnit/AudioUnitCarbonView.h>
  24167. #endif
  24168. BEGIN_JUCE_NAMESPACE
  24169. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  24170. #endif
  24171. #if JUCE_MAC
  24172. // Change this to disable logging of various activities
  24173. #ifndef AU_LOGGING
  24174. #define AU_LOGGING 1
  24175. #endif
  24176. #if AU_LOGGING
  24177. #define log(a) Logger::writeToLog(a);
  24178. #else
  24179. #define log(a)
  24180. #endif
  24181. namespace AudioUnitFormatHelpers
  24182. {
  24183. static int insideCallback = 0;
  24184. static const String osTypeToString (OSType type)
  24185. {
  24186. char s[4];
  24187. s[0] = (char) (((uint32) type) >> 24);
  24188. s[1] = (char) (((uint32) type) >> 16);
  24189. s[2] = (char) (((uint32) type) >> 8);
  24190. s[3] = (char) ((uint32) type);
  24191. return String (s, 4);
  24192. }
  24193. static OSType stringToOSType (const String& s1)
  24194. {
  24195. const String s (s1 + " ");
  24196. return (((OSType) (unsigned char) s[0]) << 24)
  24197. | (((OSType) (unsigned char) s[1]) << 16)
  24198. | (((OSType) (unsigned char) s[2]) << 8)
  24199. | ((OSType) (unsigned char) s[3]);
  24200. }
  24201. static const char* auIdentifierPrefix = "AudioUnit:";
  24202. static const String createAUPluginIdentifier (const ComponentDescription& desc)
  24203. {
  24204. jassert (osTypeToString ('abcd') == "abcd"); // agh, must have got the endianness wrong..
  24205. jassert (stringToOSType ("abcd") == (OSType) 'abcd'); // ditto
  24206. String s (auIdentifierPrefix);
  24207. if (desc.componentType == kAudioUnitType_MusicDevice)
  24208. s << "Synths/";
  24209. else if (desc.componentType == kAudioUnitType_MusicEffect
  24210. || desc.componentType == kAudioUnitType_Effect)
  24211. s << "Effects/";
  24212. else if (desc.componentType == kAudioUnitType_Generator)
  24213. s << "Generators/";
  24214. else if (desc.componentType == kAudioUnitType_Panner)
  24215. s << "Panners/";
  24216. s << osTypeToString (desc.componentType) << ","
  24217. << osTypeToString (desc.componentSubType) << ","
  24218. << osTypeToString (desc.componentManufacturer);
  24219. return s;
  24220. }
  24221. static void getAUDetails (ComponentRecord* comp, String& name, String& manufacturer)
  24222. {
  24223. Handle componentNameHandle = NewHandle (sizeof (void*));
  24224. Handle componentInfoHandle = NewHandle (sizeof (void*));
  24225. if (componentNameHandle != 0 && componentInfoHandle != 0)
  24226. {
  24227. ComponentDescription desc;
  24228. if (GetComponentInfo (comp, &desc, componentNameHandle, componentInfoHandle, 0) == noErr)
  24229. {
  24230. ConstStr255Param nameString = (ConstStr255Param) (*componentNameHandle);
  24231. ConstStr255Param infoString = (ConstStr255Param) (*componentInfoHandle);
  24232. if (nameString != 0 && nameString[0] != 0)
  24233. {
  24234. const String all ((const char*) nameString + 1, nameString[0]);
  24235. DBG ("name: "+ all);
  24236. manufacturer = all.upToFirstOccurrenceOf (":", false, false).trim();
  24237. name = all.fromFirstOccurrenceOf (":", false, false).trim();
  24238. }
  24239. if (infoString != 0 && infoString[0] != 0)
  24240. {
  24241. DBG ("info: " + String ((const char*) infoString + 1, infoString[0]));
  24242. }
  24243. if (name.isEmpty())
  24244. name = "<Unknown>";
  24245. }
  24246. DisposeHandle (componentNameHandle);
  24247. DisposeHandle (componentInfoHandle);
  24248. }
  24249. }
  24250. static bool getComponentDescFromIdentifier (const String& fileOrIdentifier, ComponentDescription& desc,
  24251. String& name, String& version, String& manufacturer)
  24252. {
  24253. zerostruct (desc);
  24254. if (fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  24255. {
  24256. String s (fileOrIdentifier.substring (jmax (fileOrIdentifier.lastIndexOfChar (':'),
  24257. fileOrIdentifier.lastIndexOfChar ('/')) + 1));
  24258. StringArray tokens;
  24259. tokens.addTokens (s, ",", String::empty);
  24260. tokens.trim();
  24261. tokens.removeEmptyStrings();
  24262. if (tokens.size() == 3)
  24263. {
  24264. desc.componentType = stringToOSType (tokens[0]);
  24265. desc.componentSubType = stringToOSType (tokens[1]);
  24266. desc.componentManufacturer = stringToOSType (tokens[2]);
  24267. ComponentRecord* comp = FindNextComponent (0, &desc);
  24268. if (comp != 0)
  24269. {
  24270. getAUDetails (comp, name, manufacturer);
  24271. return true;
  24272. }
  24273. }
  24274. }
  24275. return false;
  24276. }
  24277. }
  24278. class AudioUnitPluginWindowCarbon;
  24279. class AudioUnitPluginWindowCocoa;
  24280. class AudioUnitPluginInstance : public AudioPluginInstance
  24281. {
  24282. public:
  24283. ~AudioUnitPluginInstance();
  24284. // AudioPluginInstance methods:
  24285. void fillInPluginDescription (PluginDescription& desc) const
  24286. {
  24287. desc.name = pluginName;
  24288. desc.fileOrIdentifier = AudioUnitFormatHelpers::createAUPluginIdentifier (componentDesc);
  24289. desc.uid = ((int) componentDesc.componentType)
  24290. ^ ((int) componentDesc.componentSubType)
  24291. ^ ((int) componentDesc.componentManufacturer);
  24292. desc.lastFileModTime = 0;
  24293. desc.pluginFormatName = "AudioUnit";
  24294. desc.category = getCategory();
  24295. desc.manufacturerName = manufacturer;
  24296. desc.version = version;
  24297. desc.numInputChannels = getNumInputChannels();
  24298. desc.numOutputChannels = getNumOutputChannels();
  24299. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  24300. }
  24301. const String getName() const { return pluginName; }
  24302. bool acceptsMidi() const { return wantsMidiMessages; }
  24303. bool producesMidi() const { return false; }
  24304. // AudioProcessor methods:
  24305. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  24306. void releaseResources();
  24307. void processBlock (AudioSampleBuffer& buffer,
  24308. MidiBuffer& midiMessages);
  24309. AudioProcessorEditor* createEditor();
  24310. const String getInputChannelName (const int index) const;
  24311. bool isInputChannelStereoPair (int index) const;
  24312. const String getOutputChannelName (const int index) const;
  24313. bool isOutputChannelStereoPair (int index) const;
  24314. int getNumParameters();
  24315. float getParameter (int index);
  24316. void setParameter (int index, float newValue);
  24317. const String getParameterName (int index);
  24318. const String getParameterText (int index);
  24319. bool isParameterAutomatable (int index) const;
  24320. int getNumPrograms();
  24321. int getCurrentProgram();
  24322. void setCurrentProgram (int index);
  24323. const String getProgramName (int index);
  24324. void changeProgramName (int index, const String& newName);
  24325. void getStateInformation (MemoryBlock& destData);
  24326. void getCurrentProgramStateInformation (MemoryBlock& destData);
  24327. void setStateInformation (const void* data, int sizeInBytes);
  24328. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  24329. juce_UseDebuggingNewOperator
  24330. private:
  24331. friend class AudioUnitPluginWindowCarbon;
  24332. friend class AudioUnitPluginWindowCocoa;
  24333. friend class AudioUnitPluginFormat;
  24334. ComponentDescription componentDesc;
  24335. String pluginName, manufacturer, version;
  24336. String fileOrIdentifier;
  24337. CriticalSection lock;
  24338. bool initialised, wantsMidiMessages, wasPlaying;
  24339. HeapBlock <AudioBufferList> outputBufferList;
  24340. AudioTimeStamp timeStamp;
  24341. AudioSampleBuffer* currentBuffer;
  24342. AudioUnit audioUnit;
  24343. Array <int> parameterIds;
  24344. bool getComponentDescFromFile (const String& fileOrIdentifier);
  24345. void initialise();
  24346. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  24347. const AudioTimeStamp* inTimeStamp,
  24348. UInt32 inBusNumber,
  24349. UInt32 inNumberFrames,
  24350. AudioBufferList* ioData) const;
  24351. static OSStatus renderGetInputCallback (void* inRefCon,
  24352. AudioUnitRenderActionFlags* ioActionFlags,
  24353. const AudioTimeStamp* inTimeStamp,
  24354. UInt32 inBusNumber,
  24355. UInt32 inNumberFrames,
  24356. AudioBufferList* ioData)
  24357. {
  24358. return ((AudioUnitPluginInstance*) inRefCon)
  24359. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  24360. }
  24361. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  24362. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  24363. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  24364. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  24365. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  24366. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  24367. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  24368. {
  24369. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  24370. }
  24371. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  24372. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  24373. Float64* outCurrentMeasureDownBeat)
  24374. {
  24375. return ((AudioUnitPluginInstance*) inHostUserData)
  24376. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  24377. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  24378. }
  24379. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  24380. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  24381. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  24382. {
  24383. return ((AudioUnitPluginInstance*) inHostUserData)
  24384. ->getTransportState (outIsPlaying, outTransportStateChanged,
  24385. outCurrentSampleInTimeLine, outIsCycling,
  24386. outCycleStartBeat, outCycleEndBeat);
  24387. }
  24388. void getNumChannels (int& numIns, int& numOuts)
  24389. {
  24390. numIns = 0;
  24391. numOuts = 0;
  24392. AUChannelInfo supportedChannels [128];
  24393. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  24394. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  24395. 0, supportedChannels, &supportedChannelsSize) == noErr
  24396. && supportedChannelsSize > 0)
  24397. {
  24398. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  24399. {
  24400. numIns = jmax (numIns, (int) supportedChannels[i].inChannels);
  24401. numOuts = jmax (numOuts, (int) supportedChannels[i].outChannels);
  24402. }
  24403. }
  24404. else
  24405. {
  24406. // (this really means the plugin will take any number of ins/outs as long
  24407. // as they are the same)
  24408. numIns = numOuts = 2;
  24409. }
  24410. }
  24411. const String getCategory() const;
  24412. AudioUnitPluginInstance (const String& fileOrIdentifier);
  24413. };
  24414. AudioUnitPluginInstance::AudioUnitPluginInstance (const String& fileOrIdentifier)
  24415. : fileOrIdentifier (fileOrIdentifier),
  24416. initialised (false),
  24417. wantsMidiMessages (false),
  24418. audioUnit (0),
  24419. currentBuffer (0)
  24420. {
  24421. using namespace AudioUnitFormatHelpers;
  24422. try
  24423. {
  24424. ++insideCallback;
  24425. log ("Opening AU: " + fileOrIdentifier);
  24426. if (getComponentDescFromFile (fileOrIdentifier))
  24427. {
  24428. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  24429. if (comp != 0)
  24430. {
  24431. audioUnit = (AudioUnit) OpenComponent (comp);
  24432. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  24433. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  24434. }
  24435. }
  24436. --insideCallback;
  24437. }
  24438. catch (...)
  24439. {
  24440. --insideCallback;
  24441. }
  24442. }
  24443. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  24444. {
  24445. const ScopedLock sl (lock);
  24446. jassert (AudioUnitFormatHelpers::insideCallback == 0);
  24447. if (audioUnit != 0)
  24448. {
  24449. AudioUnitUninitialize (audioUnit);
  24450. CloseComponent (audioUnit);
  24451. audioUnit = 0;
  24452. }
  24453. }
  24454. bool AudioUnitPluginInstance::getComponentDescFromFile (const String& fileOrIdentifier)
  24455. {
  24456. zerostruct (componentDesc);
  24457. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, componentDesc, pluginName, version, manufacturer))
  24458. return true;
  24459. const File file (fileOrIdentifier);
  24460. if (! file.hasFileExtension (".component"))
  24461. return false;
  24462. const char* const utf8 = fileOrIdentifier.toUTF8();
  24463. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  24464. strlen (utf8), file.isDirectory());
  24465. if (url != 0)
  24466. {
  24467. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  24468. CFRelease (url);
  24469. if (bundleRef != 0)
  24470. {
  24471. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  24472. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  24473. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  24474. if (pluginName.isEmpty())
  24475. pluginName = file.getFileNameWithoutExtension();
  24476. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  24477. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  24478. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  24479. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  24480. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  24481. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  24482. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  24483. UseResFile (resFileId);
  24484. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  24485. {
  24486. Handle h = Get1IndResource ('thng', i);
  24487. if (h != 0)
  24488. {
  24489. HLock (h);
  24490. const uint32* const types = (const uint32*) *h;
  24491. if (types[0] == kAudioUnitType_MusicDevice
  24492. || types[0] == kAudioUnitType_MusicEffect
  24493. || types[0] == kAudioUnitType_Effect
  24494. || types[0] == kAudioUnitType_Generator
  24495. || types[0] == kAudioUnitType_Panner)
  24496. {
  24497. componentDesc.componentType = types[0];
  24498. componentDesc.componentSubType = types[1];
  24499. componentDesc.componentManufacturer = types[2];
  24500. break;
  24501. }
  24502. HUnlock (h);
  24503. ReleaseResource (h);
  24504. }
  24505. }
  24506. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  24507. CFRelease (bundleRef);
  24508. }
  24509. }
  24510. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  24511. }
  24512. void AudioUnitPluginInstance::initialise()
  24513. {
  24514. if (initialised || audioUnit == 0)
  24515. return;
  24516. log ("Initialising AU: " + pluginName);
  24517. parameterIds.clear();
  24518. {
  24519. UInt32 paramListSize = 0;
  24520. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  24521. 0, 0, &paramListSize);
  24522. if (paramListSize > 0)
  24523. {
  24524. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  24525. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  24526. 0, &parameterIds.getReference(0), &paramListSize);
  24527. }
  24528. }
  24529. {
  24530. AURenderCallbackStruct info;
  24531. zerostruct (info);
  24532. info.inputProcRefCon = this;
  24533. info.inputProc = renderGetInputCallback;
  24534. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  24535. 0, &info, sizeof (info));
  24536. }
  24537. {
  24538. HostCallbackInfo info;
  24539. zerostruct (info);
  24540. info.hostUserData = this;
  24541. info.beatAndTempoProc = getBeatAndTempoCallback;
  24542. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  24543. info.transportStateProc = getTransportStateCallback;
  24544. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  24545. 0, &info, sizeof (info));
  24546. }
  24547. int numIns, numOuts;
  24548. getNumChannels (numIns, numOuts);
  24549. setPlayConfigDetails (numIns, numOuts, 0, 0);
  24550. initialised = AudioUnitInitialize (audioUnit) == noErr;
  24551. setLatencySamples (0);
  24552. }
  24553. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  24554. int samplesPerBlockExpected)
  24555. {
  24556. if (audioUnit != 0)
  24557. {
  24558. Float64 sampleRateIn = 0, sampleRateOut = 0;
  24559. UInt32 sampleRateSize = sizeof (sampleRateIn);
  24560. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sampleRateIn, &sampleRateSize);
  24561. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sampleRateOut, &sampleRateSize);
  24562. if (sampleRateIn != sampleRate_ || sampleRateOut != sampleRate_)
  24563. {
  24564. if (initialised)
  24565. {
  24566. AudioUnitUninitialize (audioUnit);
  24567. initialised = false;
  24568. }
  24569. Float64 sr = sampleRate_;
  24570. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sr, sizeof (Float64));
  24571. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sr, sizeof (Float64));
  24572. }
  24573. }
  24574. initialise();
  24575. if (initialised)
  24576. {
  24577. int numIns, numOuts;
  24578. getNumChannels (numIns, numOuts);
  24579. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  24580. Float64 latencySecs = 0.0;
  24581. UInt32 latencySize = sizeof (latencySecs);
  24582. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  24583. 0, &latencySecs, &latencySize);
  24584. setLatencySamples (roundToInt (latencySecs * sampleRate_));
  24585. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  24586. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  24587. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  24588. AudioStreamBasicDescription stream;
  24589. zerostruct (stream);
  24590. stream.mSampleRate = sampleRate_;
  24591. stream.mFormatID = kAudioFormatLinearPCM;
  24592. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  24593. stream.mFramesPerPacket = 1;
  24594. stream.mBytesPerPacket = 4;
  24595. stream.mBytesPerFrame = 4;
  24596. stream.mBitsPerChannel = 32;
  24597. stream.mChannelsPerFrame = numIns;
  24598. OSStatus err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input,
  24599. 0, &stream, sizeof (stream));
  24600. stream.mChannelsPerFrame = numOuts;
  24601. err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output,
  24602. 0, &stream, sizeof (stream));
  24603. outputBufferList.calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1), 1);
  24604. outputBufferList->mNumberBuffers = numOuts;
  24605. for (int i = numOuts; --i >= 0;)
  24606. outputBufferList->mBuffers[i].mNumberChannels = 1;
  24607. zerostruct (timeStamp);
  24608. timeStamp.mSampleTime = 0;
  24609. timeStamp.mHostTime = AudioGetCurrentHostTime();
  24610. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  24611. currentBuffer = 0;
  24612. wasPlaying = false;
  24613. }
  24614. }
  24615. void AudioUnitPluginInstance::releaseResources()
  24616. {
  24617. if (initialised)
  24618. {
  24619. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  24620. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  24621. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  24622. outputBufferList.free();
  24623. currentBuffer = 0;
  24624. }
  24625. }
  24626. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  24627. const AudioTimeStamp* inTimeStamp,
  24628. UInt32 inBusNumber,
  24629. UInt32 inNumberFrames,
  24630. AudioBufferList* ioData) const
  24631. {
  24632. if (inBusNumber == 0
  24633. && currentBuffer != 0)
  24634. {
  24635. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  24636. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  24637. {
  24638. if (i < currentBuffer->getNumChannels())
  24639. {
  24640. memcpy (ioData->mBuffers[i].mData,
  24641. currentBuffer->getSampleData (i, 0),
  24642. sizeof (float) * inNumberFrames);
  24643. }
  24644. else
  24645. {
  24646. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  24647. }
  24648. }
  24649. }
  24650. return noErr;
  24651. }
  24652. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  24653. MidiBuffer& midiMessages)
  24654. {
  24655. const int numSamples = buffer.getNumSamples();
  24656. if (initialised)
  24657. {
  24658. AudioUnitRenderActionFlags flags = 0;
  24659. timeStamp.mHostTime = AudioGetCurrentHostTime();
  24660. for (int i = getNumOutputChannels(); --i >= 0;)
  24661. {
  24662. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  24663. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  24664. }
  24665. currentBuffer = &buffer;
  24666. if (wantsMidiMessages)
  24667. {
  24668. const uint8* midiEventData;
  24669. int midiEventSize, midiEventPosition;
  24670. MidiBuffer::Iterator i (midiMessages);
  24671. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  24672. {
  24673. if (midiEventSize <= 3)
  24674. MusicDeviceMIDIEvent (audioUnit,
  24675. midiEventData[0], midiEventData[1], midiEventData[2],
  24676. midiEventPosition);
  24677. else
  24678. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  24679. }
  24680. midiMessages.clear();
  24681. }
  24682. AudioUnitRender (audioUnit, &flags, &timeStamp,
  24683. 0, numSamples, outputBufferList);
  24684. timeStamp.mSampleTime += numSamples;
  24685. }
  24686. else
  24687. {
  24688. // Not initialised, so just bypass..
  24689. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  24690. buffer.clear (i, 0, buffer.getNumSamples());
  24691. }
  24692. }
  24693. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  24694. {
  24695. AudioPlayHead* const ph = getPlayHead();
  24696. AudioPlayHead::CurrentPositionInfo result;
  24697. if (ph != 0 && ph->getCurrentPosition (result))
  24698. {
  24699. if (outCurrentBeat != 0)
  24700. *outCurrentBeat = result.ppqPosition;
  24701. if (outCurrentTempo != 0)
  24702. *outCurrentTempo = result.bpm;
  24703. }
  24704. else
  24705. {
  24706. if (outCurrentBeat != 0)
  24707. *outCurrentBeat = 0;
  24708. if (outCurrentTempo != 0)
  24709. *outCurrentTempo = 120.0;
  24710. }
  24711. return noErr;
  24712. }
  24713. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  24714. Float32* outTimeSig_Numerator,
  24715. UInt32* outTimeSig_Denominator,
  24716. Float64* outCurrentMeasureDownBeat) const
  24717. {
  24718. AudioPlayHead* const ph = getPlayHead();
  24719. AudioPlayHead::CurrentPositionInfo result;
  24720. if (ph != 0 && ph->getCurrentPosition (result))
  24721. {
  24722. if (outTimeSig_Numerator != 0)
  24723. *outTimeSig_Numerator = result.timeSigNumerator;
  24724. if (outTimeSig_Denominator != 0)
  24725. *outTimeSig_Denominator = result.timeSigDenominator;
  24726. if (outDeltaSampleOffsetToNextBeat != 0)
  24727. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  24728. if (outCurrentMeasureDownBeat != 0)
  24729. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  24730. }
  24731. else
  24732. {
  24733. if (outDeltaSampleOffsetToNextBeat != 0)
  24734. *outDeltaSampleOffsetToNextBeat = 0;
  24735. if (outTimeSig_Numerator != 0)
  24736. *outTimeSig_Numerator = 4;
  24737. if (outTimeSig_Denominator != 0)
  24738. *outTimeSig_Denominator = 4;
  24739. if (outCurrentMeasureDownBeat != 0)
  24740. *outCurrentMeasureDownBeat = 0;
  24741. }
  24742. return noErr;
  24743. }
  24744. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  24745. Boolean* outTransportStateChanged,
  24746. Float64* outCurrentSampleInTimeLine,
  24747. Boolean* outIsCycling,
  24748. Float64* outCycleStartBeat,
  24749. Float64* outCycleEndBeat)
  24750. {
  24751. AudioPlayHead* const ph = getPlayHead();
  24752. AudioPlayHead::CurrentPositionInfo result;
  24753. if (ph != 0 && ph->getCurrentPosition (result))
  24754. {
  24755. if (outIsPlaying != 0)
  24756. *outIsPlaying = result.isPlaying;
  24757. if (outTransportStateChanged != 0)
  24758. {
  24759. *outTransportStateChanged = result.isPlaying != wasPlaying;
  24760. wasPlaying = result.isPlaying;
  24761. }
  24762. if (outCurrentSampleInTimeLine != 0)
  24763. *outCurrentSampleInTimeLine = roundToInt (result.timeInSeconds * getSampleRate());
  24764. if (outIsCycling != 0)
  24765. *outIsCycling = false;
  24766. if (outCycleStartBeat != 0)
  24767. *outCycleStartBeat = 0;
  24768. if (outCycleEndBeat != 0)
  24769. *outCycleEndBeat = 0;
  24770. }
  24771. else
  24772. {
  24773. if (outIsPlaying != 0)
  24774. *outIsPlaying = false;
  24775. if (outTransportStateChanged != 0)
  24776. *outTransportStateChanged = false;
  24777. if (outCurrentSampleInTimeLine != 0)
  24778. *outCurrentSampleInTimeLine = 0;
  24779. if (outIsCycling != 0)
  24780. *outIsCycling = false;
  24781. if (outCycleStartBeat != 0)
  24782. *outCycleStartBeat = 0;
  24783. if (outCycleEndBeat != 0)
  24784. *outCycleEndBeat = 0;
  24785. }
  24786. return noErr;
  24787. }
  24788. class AudioUnitPluginWindowCocoa : public AudioProcessorEditor
  24789. {
  24790. public:
  24791. AudioUnitPluginWindowCocoa (AudioUnitPluginInstance& plugin_, const bool createGenericViewIfNeeded)
  24792. : AudioProcessorEditor (&plugin_),
  24793. plugin (plugin_),
  24794. wrapper (0)
  24795. {
  24796. addAndMakeVisible (wrapper = new NSViewComponent());
  24797. setOpaque (true);
  24798. setVisible (true);
  24799. setSize (100, 100);
  24800. createView (createGenericViewIfNeeded);
  24801. }
  24802. ~AudioUnitPluginWindowCocoa()
  24803. {
  24804. const bool wasValid = isValid();
  24805. wrapper->setView (0);
  24806. if (wasValid)
  24807. plugin.editorBeingDeleted (this);
  24808. delete wrapper;
  24809. }
  24810. bool isValid() const { return wrapper->getView() != 0; }
  24811. void paint (Graphics& g)
  24812. {
  24813. g.fillAll (Colours::white);
  24814. }
  24815. void resized()
  24816. {
  24817. wrapper->setSize (getWidth(), getHeight());
  24818. }
  24819. private:
  24820. AudioUnitPluginInstance& plugin;
  24821. NSViewComponent* wrapper;
  24822. bool createView (const bool createGenericViewIfNeeded)
  24823. {
  24824. NSView* pluginView = 0;
  24825. UInt32 dataSize = 0;
  24826. Boolean isWritable = false;
  24827. if (AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24828. 0, &dataSize, &isWritable) == noErr
  24829. && dataSize != 0
  24830. && AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24831. 0, &dataSize, &isWritable) == noErr)
  24832. {
  24833. HeapBlock <AudioUnitCocoaViewInfo> info;
  24834. info.calloc (dataSize, 1);
  24835. if (AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24836. 0, info, &dataSize) == noErr)
  24837. {
  24838. NSString* viewClassName = (NSString*) (info->mCocoaAUViewClass[0]);
  24839. NSString* path = (NSString*) CFURLCopyPath (info->mCocoaAUViewBundleLocation);
  24840. NSBundle* viewBundle = [NSBundle bundleWithPath: [path autorelease]];
  24841. Class viewClass = [viewBundle classNamed: viewClassName];
  24842. if ([viewClass conformsToProtocol: @protocol (AUCocoaUIBase)]
  24843. && [viewClass instancesRespondToSelector: @selector (interfaceVersion)]
  24844. && [viewClass instancesRespondToSelector: @selector (uiViewForAudioUnit: withSize:)])
  24845. {
  24846. id factory = [[[viewClass alloc] init] autorelease];
  24847. pluginView = [factory uiViewForAudioUnit: plugin.audioUnit
  24848. withSize: NSMakeSize (getWidth(), getHeight())];
  24849. }
  24850. for (int i = (dataSize - sizeof (CFURLRef)) / sizeof (CFStringRef); --i >= 0;)
  24851. {
  24852. CFRelease (info->mCocoaAUViewClass[i]);
  24853. CFRelease (info->mCocoaAUViewBundleLocation);
  24854. }
  24855. }
  24856. }
  24857. if (createGenericViewIfNeeded && (pluginView == 0))
  24858. pluginView = [[AUGenericView alloc] initWithAudioUnit: plugin.audioUnit];
  24859. wrapper->setView (pluginView);
  24860. if (pluginView != 0)
  24861. setSize ([pluginView frame].size.width,
  24862. [pluginView frame].size.height);
  24863. return pluginView != 0;
  24864. }
  24865. };
  24866. #if JUCE_SUPPORT_CARBON
  24867. class AudioUnitPluginWindowCarbon : public AudioProcessorEditor
  24868. {
  24869. public:
  24870. AudioUnitPluginWindowCarbon (AudioUnitPluginInstance& plugin_)
  24871. : AudioProcessorEditor (&plugin_),
  24872. plugin (plugin_),
  24873. viewComponent (0)
  24874. {
  24875. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  24876. setOpaque (true);
  24877. setVisible (true);
  24878. setSize (400, 300);
  24879. ComponentDescription viewList [16];
  24880. UInt32 viewListSize = sizeof (viewList);
  24881. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  24882. 0, &viewList, &viewListSize);
  24883. componentRecord = FindNextComponent (0, &viewList[0]);
  24884. }
  24885. ~AudioUnitPluginWindowCarbon()
  24886. {
  24887. innerWrapper = 0;
  24888. if (isValid())
  24889. plugin.editorBeingDeleted (this);
  24890. }
  24891. bool isValid() const throw() { return componentRecord != 0; }
  24892. void paint (Graphics& g)
  24893. {
  24894. g.fillAll (Colours::black);
  24895. }
  24896. void resized()
  24897. {
  24898. innerWrapper->setSize (getWidth(), getHeight());
  24899. }
  24900. bool keyStateChanged (bool)
  24901. {
  24902. return false;
  24903. }
  24904. bool keyPressed (const KeyPress&)
  24905. {
  24906. return false;
  24907. }
  24908. AudioUnit getAudioUnit() const { return plugin.audioUnit; }
  24909. AudioUnitCarbonView getViewComponent()
  24910. {
  24911. if (viewComponent == 0 && componentRecord != 0)
  24912. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  24913. return viewComponent;
  24914. }
  24915. void closeViewComponent()
  24916. {
  24917. if (viewComponent != 0)
  24918. {
  24919. CloseComponent (viewComponent);
  24920. viewComponent = 0;
  24921. }
  24922. }
  24923. juce_UseDebuggingNewOperator
  24924. private:
  24925. AudioUnitPluginInstance& plugin;
  24926. ComponentRecord* componentRecord;
  24927. AudioUnitCarbonView viewComponent;
  24928. class InnerWrapperComponent : public CarbonViewWrapperComponent
  24929. {
  24930. public:
  24931. InnerWrapperComponent (AudioUnitPluginWindowCarbon* const owner_)
  24932. : owner (owner_)
  24933. {
  24934. }
  24935. ~InnerWrapperComponent()
  24936. {
  24937. deleteWindow();
  24938. }
  24939. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  24940. {
  24941. log ("Opening AU GUI: " + owner->plugin.getName());
  24942. AudioUnitCarbonView viewComponent = owner->getViewComponent();
  24943. if (viewComponent == 0)
  24944. return 0;
  24945. Float32Point pos = { 0, 0 };
  24946. Float32Point size = { 250, 200 };
  24947. HIViewRef pluginView = 0;
  24948. AudioUnitCarbonViewCreate (viewComponent,
  24949. owner->getAudioUnit(),
  24950. windowRef,
  24951. rootView,
  24952. &pos,
  24953. &size,
  24954. (ControlRef*) &pluginView);
  24955. return pluginView;
  24956. }
  24957. void removeView (HIViewRef)
  24958. {
  24959. log ("Closing AU GUI: " + owner->plugin.getName());
  24960. owner->closeViewComponent();
  24961. }
  24962. private:
  24963. AudioUnitPluginWindowCarbon* const owner;
  24964. };
  24965. friend class InnerWrapperComponent;
  24966. ScopedPointer<InnerWrapperComponent> innerWrapper;
  24967. };
  24968. #endif
  24969. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  24970. {
  24971. ScopedPointer<AudioProcessorEditor> w (new AudioUnitPluginWindowCocoa (*this, false));
  24972. if (! static_cast <AudioUnitPluginWindowCocoa*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  24973. w = 0;
  24974. #if JUCE_SUPPORT_CARBON
  24975. if (w == 0)
  24976. {
  24977. w = new AudioUnitPluginWindowCarbon (*this);
  24978. if (! static_cast <AudioUnitPluginWindowCarbon*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  24979. w = 0;
  24980. }
  24981. #endif
  24982. if (w == 0)
  24983. w = new AudioUnitPluginWindowCocoa (*this, true); // use AUGenericView as a fallback
  24984. return w.release();
  24985. }
  24986. const String AudioUnitPluginInstance::getCategory() const
  24987. {
  24988. const char* result = 0;
  24989. switch (componentDesc.componentType)
  24990. {
  24991. case kAudioUnitType_Effect:
  24992. case kAudioUnitType_MusicEffect:
  24993. result = "Effect";
  24994. break;
  24995. case kAudioUnitType_MusicDevice:
  24996. result = "Synth";
  24997. break;
  24998. case kAudioUnitType_Generator:
  24999. result = "Generator";
  25000. break;
  25001. case kAudioUnitType_Panner:
  25002. result = "Panner";
  25003. break;
  25004. default:
  25005. break;
  25006. }
  25007. return result;
  25008. }
  25009. int AudioUnitPluginInstance::getNumParameters()
  25010. {
  25011. return parameterIds.size();
  25012. }
  25013. float AudioUnitPluginInstance::getParameter (int index)
  25014. {
  25015. const ScopedLock sl (lock);
  25016. Float32 value = 0.0f;
  25017. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  25018. {
  25019. AudioUnitGetParameter (audioUnit,
  25020. (UInt32) parameterIds.getUnchecked (index),
  25021. kAudioUnitScope_Global, 0,
  25022. &value);
  25023. }
  25024. return value;
  25025. }
  25026. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  25027. {
  25028. const ScopedLock sl (lock);
  25029. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  25030. {
  25031. AudioUnitSetParameter (audioUnit,
  25032. (UInt32) parameterIds.getUnchecked (index),
  25033. kAudioUnitScope_Global, 0,
  25034. newValue, 0);
  25035. }
  25036. }
  25037. const String AudioUnitPluginInstance::getParameterName (int index)
  25038. {
  25039. AudioUnitParameterInfo info;
  25040. zerostruct (info);
  25041. UInt32 sz = sizeof (info);
  25042. String name;
  25043. if (AudioUnitGetProperty (audioUnit,
  25044. kAudioUnitProperty_ParameterInfo,
  25045. kAudioUnitScope_Global,
  25046. parameterIds [index], &info, &sz) == noErr)
  25047. {
  25048. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  25049. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  25050. else
  25051. name = String (info.name, sizeof (info.name));
  25052. }
  25053. return name;
  25054. }
  25055. const String AudioUnitPluginInstance::getParameterText (int index)
  25056. {
  25057. return String (getParameter (index));
  25058. }
  25059. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  25060. {
  25061. AudioUnitParameterInfo info;
  25062. UInt32 sz = sizeof (info);
  25063. if (AudioUnitGetProperty (audioUnit,
  25064. kAudioUnitProperty_ParameterInfo,
  25065. kAudioUnitScope_Global,
  25066. parameterIds [index], &info, &sz) == noErr)
  25067. {
  25068. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  25069. }
  25070. return true;
  25071. }
  25072. int AudioUnitPluginInstance::getNumPrograms()
  25073. {
  25074. CFArrayRef presets;
  25075. UInt32 sz = sizeof (CFArrayRef);
  25076. int num = 0;
  25077. if (AudioUnitGetProperty (audioUnit,
  25078. kAudioUnitProperty_FactoryPresets,
  25079. kAudioUnitScope_Global,
  25080. 0, &presets, &sz) == noErr)
  25081. {
  25082. num = (int) CFArrayGetCount (presets);
  25083. CFRelease (presets);
  25084. }
  25085. return num;
  25086. }
  25087. int AudioUnitPluginInstance::getCurrentProgram()
  25088. {
  25089. AUPreset current;
  25090. current.presetNumber = 0;
  25091. UInt32 sz = sizeof (AUPreset);
  25092. AudioUnitGetProperty (audioUnit,
  25093. kAudioUnitProperty_FactoryPresets,
  25094. kAudioUnitScope_Global,
  25095. 0, &current, &sz);
  25096. return current.presetNumber;
  25097. }
  25098. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  25099. {
  25100. AUPreset current;
  25101. current.presetNumber = newIndex;
  25102. current.presetName = 0;
  25103. AudioUnitSetProperty (audioUnit,
  25104. kAudioUnitProperty_FactoryPresets,
  25105. kAudioUnitScope_Global,
  25106. 0, &current, sizeof (AUPreset));
  25107. }
  25108. const String AudioUnitPluginInstance::getProgramName (int index)
  25109. {
  25110. String s;
  25111. CFArrayRef presets;
  25112. UInt32 sz = sizeof (CFArrayRef);
  25113. if (AudioUnitGetProperty (audioUnit,
  25114. kAudioUnitProperty_FactoryPresets,
  25115. kAudioUnitScope_Global,
  25116. 0, &presets, &sz) == noErr)
  25117. {
  25118. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  25119. {
  25120. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  25121. if (p != 0 && p->presetNumber == index)
  25122. {
  25123. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  25124. break;
  25125. }
  25126. }
  25127. CFRelease (presets);
  25128. }
  25129. return s;
  25130. }
  25131. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  25132. {
  25133. jassertfalse; // xxx not implemented!
  25134. }
  25135. const String AudioUnitPluginInstance::getInputChannelName (const int index) const
  25136. {
  25137. if (((unsigned int) index) < (unsigned int) getNumInputChannels())
  25138. return "Input " + String (index + 1);
  25139. return String::empty;
  25140. }
  25141. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  25142. {
  25143. if (((unsigned int) index) >= (unsigned int) getNumInputChannels())
  25144. return false;
  25145. return true;
  25146. }
  25147. const String AudioUnitPluginInstance::getOutputChannelName (const int index) const
  25148. {
  25149. if (((unsigned int) index) < (unsigned int) getNumOutputChannels())
  25150. return "Output " + String (index + 1);
  25151. return String::empty;
  25152. }
  25153. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  25154. {
  25155. if (((unsigned int) index) >= (unsigned int) getNumOutputChannels())
  25156. return false;
  25157. return true;
  25158. }
  25159. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  25160. {
  25161. getCurrentProgramStateInformation (destData);
  25162. }
  25163. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  25164. {
  25165. CFPropertyListRef propertyList = 0;
  25166. UInt32 sz = sizeof (CFPropertyListRef);
  25167. if (AudioUnitGetProperty (audioUnit,
  25168. kAudioUnitProperty_ClassInfo,
  25169. kAudioUnitScope_Global,
  25170. 0, &propertyList, &sz) == noErr)
  25171. {
  25172. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  25173. CFWriteStreamOpen (stream);
  25174. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  25175. CFWriteStreamClose (stream);
  25176. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  25177. destData.setSize (bytesWritten);
  25178. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  25179. CFRelease (data);
  25180. CFRelease (stream);
  25181. CFRelease (propertyList);
  25182. }
  25183. }
  25184. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  25185. {
  25186. setCurrentProgramStateInformation (data, sizeInBytes);
  25187. }
  25188. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  25189. {
  25190. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  25191. (const UInt8*) data,
  25192. sizeInBytes,
  25193. kCFAllocatorNull);
  25194. CFReadStreamOpen (stream);
  25195. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  25196. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  25197. stream,
  25198. 0,
  25199. kCFPropertyListImmutable,
  25200. &format,
  25201. 0);
  25202. CFRelease (stream);
  25203. if (propertyList != 0)
  25204. AudioUnitSetProperty (audioUnit,
  25205. kAudioUnitProperty_ClassInfo,
  25206. kAudioUnitScope_Global,
  25207. 0, &propertyList, sizeof (propertyList));
  25208. }
  25209. AudioUnitPluginFormat::AudioUnitPluginFormat()
  25210. {
  25211. }
  25212. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  25213. {
  25214. }
  25215. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  25216. const String& fileOrIdentifier)
  25217. {
  25218. if (! fileMightContainThisPluginType (fileOrIdentifier))
  25219. return;
  25220. PluginDescription desc;
  25221. desc.fileOrIdentifier = fileOrIdentifier;
  25222. desc.uid = 0;
  25223. try
  25224. {
  25225. ScopedPointer <AudioPluginInstance> createdInstance (createInstanceFromDescription (desc));
  25226. AudioUnitPluginInstance* const auInstance = dynamic_cast <AudioUnitPluginInstance*> ((AudioPluginInstance*) createdInstance);
  25227. if (auInstance != 0)
  25228. {
  25229. auInstance->fillInPluginDescription (desc);
  25230. results.add (new PluginDescription (desc));
  25231. }
  25232. }
  25233. catch (...)
  25234. {
  25235. // crashed while loading...
  25236. }
  25237. }
  25238. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  25239. {
  25240. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  25241. {
  25242. ScopedPointer <AudioUnitPluginInstance> result (new AudioUnitPluginInstance (desc.fileOrIdentifier));
  25243. if (result->audioUnit != 0)
  25244. {
  25245. result->initialise();
  25246. return result.release();
  25247. }
  25248. }
  25249. return 0;
  25250. }
  25251. const StringArray AudioUnitPluginFormat::searchPathsForPlugins (const FileSearchPath& /*directoriesToSearch*/,
  25252. const bool /*recursive*/)
  25253. {
  25254. StringArray result;
  25255. ComponentRecord* comp = 0;
  25256. ComponentDescription desc;
  25257. zerostruct (desc);
  25258. for (;;)
  25259. {
  25260. zerostruct (desc);
  25261. comp = FindNextComponent (comp, &desc);
  25262. if (comp == 0)
  25263. break;
  25264. GetComponentInfo (comp, &desc, 0, 0, 0);
  25265. if (desc.componentType == kAudioUnitType_MusicDevice
  25266. || desc.componentType == kAudioUnitType_MusicEffect
  25267. || desc.componentType == kAudioUnitType_Effect
  25268. || desc.componentType == kAudioUnitType_Generator
  25269. || desc.componentType == kAudioUnitType_Panner)
  25270. {
  25271. const String s (AudioUnitFormatHelpers::createAUPluginIdentifier (desc));
  25272. DBG (s);
  25273. result.add (s);
  25274. }
  25275. }
  25276. return result;
  25277. }
  25278. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  25279. {
  25280. ComponentDescription desc;
  25281. String name, version, manufacturer;
  25282. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer))
  25283. return FindNextComponent (0, &desc) != 0;
  25284. const File f (fileOrIdentifier);
  25285. return f.hasFileExtension (".component")
  25286. && f.isDirectory();
  25287. }
  25288. const String AudioUnitPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  25289. {
  25290. ComponentDescription desc;
  25291. String name, version, manufacturer;
  25292. AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer);
  25293. if (name.isEmpty())
  25294. name = fileOrIdentifier;
  25295. return name;
  25296. }
  25297. bool AudioUnitPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  25298. {
  25299. if (desc.fileOrIdentifier.startsWithIgnoreCase (AudioUnitFormatHelpers::auIdentifierPrefix))
  25300. return fileMightContainThisPluginType (desc.fileOrIdentifier);
  25301. else
  25302. return File (desc.fileOrIdentifier).exists();
  25303. }
  25304. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  25305. {
  25306. return FileSearchPath ("/(Default AudioUnit locations)");
  25307. }
  25308. #endif
  25309. END_JUCE_NAMESPACE
  25310. #undef log
  25311. #endif
  25312. /*** End of inlined file: juce_AudioUnitPluginFormat.mm ***/
  25313. /*** Start of inlined file: juce_VSTPluginFormat.mm ***/
  25314. // This file just wraps juce_VSTPluginFormat.cpp in an objective-C wrapper
  25315. #define JUCE_MAC_VST_INCLUDED 1
  25316. /*** Start of inlined file: juce_VSTPluginFormat.cpp ***/
  25317. #if JUCE_PLUGINHOST_VST && (JUCE_MAC_VST_INCLUDED || ! JUCE_MAC)
  25318. #if JUCE_WINDOWS
  25319. #undef _WIN32_WINNT
  25320. #define _WIN32_WINNT 0x500
  25321. #undef STRICT
  25322. #define STRICT
  25323. #include <windows.h>
  25324. #include <float.h>
  25325. #pragma warning (disable : 4312 4355)
  25326. #elif JUCE_LINUX
  25327. #include <float.h>
  25328. #include <sys/time.h>
  25329. #include <X11/Xlib.h>
  25330. #include <X11/Xutil.h>
  25331. #include <X11/Xatom.h>
  25332. #undef Font
  25333. #undef KeyPress
  25334. #undef Drawable
  25335. #undef Time
  25336. #else
  25337. #include <Cocoa/Cocoa.h>
  25338. #include <Carbon/Carbon.h>
  25339. #endif
  25340. #if ! (JUCE_MAC && JUCE_64BIT)
  25341. BEGIN_JUCE_NAMESPACE
  25342. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  25343. #endif
  25344. #undef PRAGMA_ALIGN_SUPPORTED
  25345. #define VST_FORCE_DEPRECATED 0
  25346. #if JUCE_MSVC
  25347. #pragma warning (push)
  25348. #pragma warning (disable: 4996)
  25349. #endif
  25350. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  25351. your include path if you want to add VST support.
  25352. If you're not interested in VSTs, you can disable them by changing the
  25353. JUCE_PLUGINHOST_VST flag in juce_Config.h
  25354. */
  25355. #include "pluginterfaces/vst2.x/aeffectx.h"
  25356. #if JUCE_MSVC
  25357. #pragma warning (pop)
  25358. #endif
  25359. #if JUCE_LINUX
  25360. #define Font JUCE_NAMESPACE::Font
  25361. #define KeyPress JUCE_NAMESPACE::KeyPress
  25362. #define Drawable JUCE_NAMESPACE::Drawable
  25363. #define Time JUCE_NAMESPACE::Time
  25364. #endif
  25365. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  25366. #ifdef __aeffect__
  25367. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25368. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25369. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  25370. events to the list.
  25371. This is used by both the VST hosting code and the plugin wrapper.
  25372. */
  25373. class VSTMidiEventList
  25374. {
  25375. public:
  25376. VSTMidiEventList()
  25377. : numEventsUsed (0), numEventsAllocated (0)
  25378. {
  25379. }
  25380. ~VSTMidiEventList()
  25381. {
  25382. freeEvents();
  25383. }
  25384. void clear()
  25385. {
  25386. numEventsUsed = 0;
  25387. if (events != 0)
  25388. events->numEvents = 0;
  25389. }
  25390. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  25391. {
  25392. ensureSize (numEventsUsed + 1);
  25393. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  25394. events->numEvents = ++numEventsUsed;
  25395. if (numBytes <= 4)
  25396. {
  25397. if (e->type == kVstSysExType)
  25398. {
  25399. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  25400. e->type = kVstMidiType;
  25401. e->byteSize = sizeof (VstMidiEvent);
  25402. e->noteLength = 0;
  25403. e->noteOffset = 0;
  25404. e->detune = 0;
  25405. e->noteOffVelocity = 0;
  25406. }
  25407. e->deltaFrames = frameOffset;
  25408. memcpy (e->midiData, midiData, numBytes);
  25409. }
  25410. else
  25411. {
  25412. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  25413. if (se->type == kVstSysExType)
  25414. se->sysexDump = (char*) juce_realloc (se->sysexDump, numBytes);
  25415. else
  25416. se->sysexDump = (char*) juce_malloc (numBytes);
  25417. memcpy (se->sysexDump, midiData, numBytes);
  25418. se->type = kVstSysExType;
  25419. se->byteSize = sizeof (VstMidiSysexEvent);
  25420. se->deltaFrames = frameOffset;
  25421. se->flags = 0;
  25422. se->dumpBytes = numBytes;
  25423. se->resvd1 = 0;
  25424. se->resvd2 = 0;
  25425. }
  25426. }
  25427. // Handy method to pull the events out of an event buffer supplied by the host
  25428. // or plugin.
  25429. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  25430. {
  25431. for (int i = 0; i < events->numEvents; ++i)
  25432. {
  25433. const VstEvent* const e = events->events[i];
  25434. if (e != 0)
  25435. {
  25436. if (e->type == kVstMidiType)
  25437. {
  25438. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  25439. 4, e->deltaFrames);
  25440. }
  25441. else if (e->type == kVstSysExType)
  25442. {
  25443. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  25444. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  25445. e->deltaFrames);
  25446. }
  25447. }
  25448. }
  25449. }
  25450. void ensureSize (int numEventsNeeded)
  25451. {
  25452. if (numEventsNeeded > numEventsAllocated)
  25453. {
  25454. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  25455. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  25456. if (events == 0)
  25457. events.calloc (size, 1);
  25458. else
  25459. events.realloc (size, 1);
  25460. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  25461. {
  25462. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  25463. (int) sizeof (VstMidiSysexEvent)));
  25464. e->type = kVstMidiType;
  25465. e->byteSize = sizeof (VstMidiEvent);
  25466. events->events[i] = (VstEvent*) e;
  25467. }
  25468. numEventsAllocated = numEventsNeeded;
  25469. }
  25470. }
  25471. void freeEvents()
  25472. {
  25473. if (events != 0)
  25474. {
  25475. for (int i = numEventsAllocated; --i >= 0;)
  25476. {
  25477. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  25478. if (e->type == kVstSysExType)
  25479. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  25480. juce_free (e);
  25481. }
  25482. events.free();
  25483. numEventsUsed = 0;
  25484. numEventsAllocated = 0;
  25485. }
  25486. }
  25487. HeapBlock <VstEvents> events;
  25488. private:
  25489. int numEventsUsed, numEventsAllocated;
  25490. };
  25491. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25492. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  25493. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  25494. #if ! JUCE_WINDOWS
  25495. static void _fpreset() {}
  25496. static void _clearfp() {}
  25497. #endif
  25498. extern void juce_callAnyTimersSynchronously();
  25499. const int fxbVersionNum = 1;
  25500. struct fxProgram
  25501. {
  25502. long chunkMagic; // 'CcnK'
  25503. long byteSize; // of this chunk, excl. magic + byteSize
  25504. long fxMagic; // 'FxCk'
  25505. long version;
  25506. long fxID; // fx unique id
  25507. long fxVersion;
  25508. long numParams;
  25509. char prgName[28];
  25510. float params[1]; // variable no. of parameters
  25511. };
  25512. struct fxSet
  25513. {
  25514. long chunkMagic; // 'CcnK'
  25515. long byteSize; // of this chunk, excl. magic + byteSize
  25516. long fxMagic; // 'FxBk'
  25517. long version;
  25518. long fxID; // fx unique id
  25519. long fxVersion;
  25520. long numPrograms;
  25521. char future[128];
  25522. fxProgram programs[1]; // variable no. of programs
  25523. };
  25524. struct fxChunkSet
  25525. {
  25526. long chunkMagic; // 'CcnK'
  25527. long byteSize; // of this chunk, excl. magic + byteSize
  25528. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  25529. long version;
  25530. long fxID; // fx unique id
  25531. long fxVersion;
  25532. long numPrograms;
  25533. char future[128];
  25534. long chunkSize;
  25535. char chunk[8]; // variable
  25536. };
  25537. struct fxProgramSet
  25538. {
  25539. long chunkMagic; // 'CcnK'
  25540. long byteSize; // of this chunk, excl. magic + byteSize
  25541. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  25542. long version;
  25543. long fxID; // fx unique id
  25544. long fxVersion;
  25545. long numPrograms;
  25546. char name[28];
  25547. long chunkSize;
  25548. char chunk[8]; // variable
  25549. };
  25550. static long vst_swap (const long x) throw()
  25551. {
  25552. #ifdef JUCE_LITTLE_ENDIAN
  25553. return (long) ByteOrder::swap ((uint32) x);
  25554. #else
  25555. return x;
  25556. #endif
  25557. }
  25558. static float vst_swapFloat (const float x) throw()
  25559. {
  25560. #ifdef JUCE_LITTLE_ENDIAN
  25561. union { uint32 asInt; float asFloat; } n;
  25562. n.asFloat = x;
  25563. n.asInt = ByteOrder::swap (n.asInt);
  25564. return n.asFloat;
  25565. #else
  25566. return x;
  25567. #endif
  25568. }
  25569. typedef AEffect* (*MainCall) (audioMasterCallback);
  25570. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  25571. static int shellUIDToCreate = 0;
  25572. static int insideVSTCallback = 0;
  25573. class VSTPluginWindow;
  25574. // Change this to disable logging of various VST activities
  25575. #ifndef VST_LOGGING
  25576. #define VST_LOGGING 1
  25577. #endif
  25578. #if VST_LOGGING
  25579. #define log(a) Logger::writeToLog(a);
  25580. #else
  25581. #define log(a)
  25582. #endif
  25583. #if JUCE_MAC && JUCE_PPC
  25584. static void* NewCFMFromMachO (void* const machofp) throw()
  25585. {
  25586. void* result = juce_malloc (8);
  25587. ((void**) result)[0] = machofp;
  25588. ((void**) result)[1] = result;
  25589. return result;
  25590. }
  25591. #endif
  25592. #if JUCE_LINUX
  25593. extern Display* display;
  25594. extern XContext windowHandleXContext;
  25595. typedef void (*EventProcPtr) (XEvent* ev);
  25596. static bool xErrorTriggered;
  25597. static int temporaryErrorHandler (Display*, XErrorEvent*)
  25598. {
  25599. xErrorTriggered = true;
  25600. return 0;
  25601. }
  25602. static int getPropertyFromXWindow (Window handle, Atom atom)
  25603. {
  25604. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  25605. xErrorTriggered = false;
  25606. int userSize;
  25607. unsigned long bytes, userCount;
  25608. unsigned char* data;
  25609. Atom userType;
  25610. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  25611. &userType, &userSize, &userCount, &bytes, &data);
  25612. XSetErrorHandler (oldErrorHandler);
  25613. return (userCount == 1 && ! xErrorTriggered) ? *(int*) data
  25614. : 0;
  25615. }
  25616. static Window getChildWindow (Window windowToCheck)
  25617. {
  25618. Window rootWindow, parentWindow;
  25619. Window* childWindows;
  25620. unsigned int numChildren;
  25621. XQueryTree (display,
  25622. windowToCheck,
  25623. &rootWindow,
  25624. &parentWindow,
  25625. &childWindows,
  25626. &numChildren);
  25627. if (numChildren > 0)
  25628. return childWindows [0];
  25629. return 0;
  25630. }
  25631. static void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  25632. {
  25633. if (e.mods.isLeftButtonDown())
  25634. {
  25635. ev.xbutton.button = Button1;
  25636. ev.xbutton.state |= Button1Mask;
  25637. }
  25638. else if (e.mods.isRightButtonDown())
  25639. {
  25640. ev.xbutton.button = Button3;
  25641. ev.xbutton.state |= Button3Mask;
  25642. }
  25643. else if (e.mods.isMiddleButtonDown())
  25644. {
  25645. ev.xbutton.button = Button2;
  25646. ev.xbutton.state |= Button2Mask;
  25647. }
  25648. }
  25649. static void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  25650. {
  25651. if (e.mods.isLeftButtonDown())
  25652. ev.xmotion.state |= Button1Mask;
  25653. else if (e.mods.isRightButtonDown())
  25654. ev.xmotion.state |= Button3Mask;
  25655. else if (e.mods.isMiddleButtonDown())
  25656. ev.xmotion.state |= Button2Mask;
  25657. }
  25658. static void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  25659. {
  25660. if (e.mods.isLeftButtonDown())
  25661. ev.xcrossing.state |= Button1Mask;
  25662. else if (e.mods.isRightButtonDown())
  25663. ev.xcrossing.state |= Button3Mask;
  25664. else if (e.mods.isMiddleButtonDown())
  25665. ev.xcrossing.state |= Button2Mask;
  25666. }
  25667. static void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  25668. {
  25669. if (increment < 0)
  25670. {
  25671. ev.xbutton.button = Button5;
  25672. ev.xbutton.state |= Button5Mask;
  25673. }
  25674. else if (increment > 0)
  25675. {
  25676. ev.xbutton.button = Button4;
  25677. ev.xbutton.state |= Button4Mask;
  25678. }
  25679. }
  25680. #endif
  25681. class ModuleHandle : public ReferenceCountedObject
  25682. {
  25683. public:
  25684. File file;
  25685. MainCall moduleMain;
  25686. String pluginName;
  25687. static Array <ModuleHandle*>& getActiveModules()
  25688. {
  25689. static Array <ModuleHandle*> activeModules;
  25690. return activeModules;
  25691. }
  25692. static ModuleHandle* findOrCreateModule (const File& file)
  25693. {
  25694. for (int i = getActiveModules().size(); --i >= 0;)
  25695. {
  25696. ModuleHandle* const module = getActiveModules().getUnchecked(i);
  25697. if (module->file == file)
  25698. return module;
  25699. }
  25700. _fpreset(); // (doesn't do any harm)
  25701. ++insideVSTCallback;
  25702. shellUIDToCreate = 0;
  25703. log ("Attempting to load VST: " + file.getFullPathName());
  25704. ScopedPointer <ModuleHandle> m (new ModuleHandle (file));
  25705. if (! m->open())
  25706. m = 0;
  25707. --insideVSTCallback;
  25708. _fpreset(); // (doesn't do any harm)
  25709. return m.release();
  25710. }
  25711. ModuleHandle (const File& file_)
  25712. : file (file_),
  25713. moduleMain (0),
  25714. #if JUCE_WINDOWS || JUCE_LINUX
  25715. hModule (0)
  25716. #elif JUCE_MAC
  25717. fragId (0),
  25718. resHandle (0),
  25719. bundleRef (0),
  25720. resFileId (0)
  25721. #endif
  25722. {
  25723. getActiveModules().add (this);
  25724. #if JUCE_WINDOWS || JUCE_LINUX
  25725. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  25726. #elif JUCE_MAC
  25727. FSRef ref;
  25728. PlatformUtilities::makeFSRefFromPath (&ref, file_.getParentDirectory().getFullPathName());
  25729. FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, &parentDirFSSpec, 0);
  25730. #endif
  25731. }
  25732. ~ModuleHandle()
  25733. {
  25734. getActiveModules().removeValue (this);
  25735. close();
  25736. }
  25737. juce_UseDebuggingNewOperator
  25738. #if JUCE_WINDOWS || JUCE_LINUX
  25739. void* hModule;
  25740. String fullParentDirectoryPathName;
  25741. bool open()
  25742. {
  25743. #if JUCE_WINDOWS
  25744. static bool timePeriodSet = false;
  25745. if (! timePeriodSet)
  25746. {
  25747. timePeriodSet = true;
  25748. timeBeginPeriod (2);
  25749. }
  25750. #endif
  25751. pluginName = file.getFileNameWithoutExtension();
  25752. hModule = PlatformUtilities::loadDynamicLibrary (file.getFullPathName());
  25753. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "VSTPluginMain");
  25754. if (moduleMain == 0)
  25755. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "main");
  25756. return moduleMain != 0;
  25757. }
  25758. void close()
  25759. {
  25760. _fpreset(); // (doesn't do any harm)
  25761. PlatformUtilities::freeDynamicLibrary (hModule);
  25762. }
  25763. void closeEffect (AEffect* eff)
  25764. {
  25765. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25766. }
  25767. #else
  25768. CFragConnectionID fragId;
  25769. Handle resHandle;
  25770. CFBundleRef bundleRef;
  25771. FSSpec parentDirFSSpec;
  25772. short resFileId;
  25773. bool open()
  25774. {
  25775. bool ok = false;
  25776. const String filename (file.getFullPathName());
  25777. if (file.hasFileExtension (".vst"))
  25778. {
  25779. const char* const utf8 = filename.toUTF8();
  25780. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  25781. strlen (utf8), file.isDirectory());
  25782. if (url != 0)
  25783. {
  25784. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  25785. CFRelease (url);
  25786. if (bundleRef != 0)
  25787. {
  25788. if (CFBundleLoadExecutable (bundleRef))
  25789. {
  25790. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  25791. if (moduleMain == 0)
  25792. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  25793. if (moduleMain != 0)
  25794. {
  25795. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  25796. if (name != 0)
  25797. {
  25798. if (CFGetTypeID (name) == CFStringGetTypeID())
  25799. {
  25800. char buffer[1024];
  25801. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  25802. pluginName = buffer;
  25803. }
  25804. }
  25805. if (pluginName.isEmpty())
  25806. pluginName = file.getFileNameWithoutExtension();
  25807. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  25808. ok = true;
  25809. }
  25810. }
  25811. if (! ok)
  25812. {
  25813. CFBundleUnloadExecutable (bundleRef);
  25814. CFRelease (bundleRef);
  25815. bundleRef = 0;
  25816. }
  25817. }
  25818. }
  25819. }
  25820. #if JUCE_PPC
  25821. else
  25822. {
  25823. FSRef fn;
  25824. if (FSPathMakeRef ((UInt8*) filename.toUTF8(), &fn, 0) == noErr)
  25825. {
  25826. resFileId = FSOpenResFile (&fn, fsRdPerm);
  25827. if (resFileId != -1)
  25828. {
  25829. const int numEffs = Count1Resources ('aEff');
  25830. for (int i = 0; i < numEffs; ++i)
  25831. {
  25832. resHandle = Get1IndResource ('aEff', i + 1);
  25833. if (resHandle != 0)
  25834. {
  25835. OSType type;
  25836. Str255 name;
  25837. SInt16 id;
  25838. GetResInfo (resHandle, &id, &type, name);
  25839. pluginName = String ((const char*) name + 1, name[0]);
  25840. DetachResource (resHandle);
  25841. HLock (resHandle);
  25842. Ptr ptr;
  25843. Str255 errorText;
  25844. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  25845. name, kPrivateCFragCopy,
  25846. &fragId, &ptr, errorText);
  25847. if (err == noErr)
  25848. {
  25849. moduleMain = (MainCall) newMachOFromCFM (ptr);
  25850. ok = true;
  25851. }
  25852. else
  25853. {
  25854. HUnlock (resHandle);
  25855. }
  25856. break;
  25857. }
  25858. }
  25859. if (! ok)
  25860. CloseResFile (resFileId);
  25861. }
  25862. }
  25863. }
  25864. #endif
  25865. return ok;
  25866. }
  25867. void close()
  25868. {
  25869. #if JUCE_PPC
  25870. if (fragId != 0)
  25871. {
  25872. if (moduleMain != 0)
  25873. disposeMachOFromCFM ((void*) moduleMain);
  25874. CloseConnection (&fragId);
  25875. HUnlock (resHandle);
  25876. if (resFileId != 0)
  25877. CloseResFile (resFileId);
  25878. }
  25879. else
  25880. #endif
  25881. if (bundleRef != 0)
  25882. {
  25883. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  25884. if (CFGetRetainCount (bundleRef) == 1)
  25885. CFBundleUnloadExecutable (bundleRef);
  25886. if (CFGetRetainCount (bundleRef) > 0)
  25887. CFRelease (bundleRef);
  25888. }
  25889. }
  25890. void closeEffect (AEffect* eff)
  25891. {
  25892. #if JUCE_PPC
  25893. if (fragId != 0)
  25894. {
  25895. Array<void*> thingsToDelete;
  25896. thingsToDelete.add ((void*) eff->dispatcher);
  25897. thingsToDelete.add ((void*) eff->process);
  25898. thingsToDelete.add ((void*) eff->setParameter);
  25899. thingsToDelete.add ((void*) eff->getParameter);
  25900. thingsToDelete.add ((void*) eff->processReplacing);
  25901. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25902. for (int i = thingsToDelete.size(); --i >= 0;)
  25903. disposeMachOFromCFM (thingsToDelete[i]);
  25904. }
  25905. else
  25906. #endif
  25907. {
  25908. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25909. }
  25910. }
  25911. #if JUCE_PPC
  25912. static void* newMachOFromCFM (void* cfmfp)
  25913. {
  25914. if (cfmfp == 0)
  25915. return 0;
  25916. UInt32* const mfp = new UInt32[6];
  25917. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  25918. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  25919. mfp[2] = 0x800c0000;
  25920. mfp[3] = 0x804c0004;
  25921. mfp[4] = 0x7c0903a6;
  25922. mfp[5] = 0x4e800420;
  25923. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  25924. return mfp;
  25925. }
  25926. static void disposeMachOFromCFM (void* ptr)
  25927. {
  25928. delete[] static_cast <UInt32*> (ptr);
  25929. }
  25930. void coerceAEffectFunctionCalls (AEffect* eff)
  25931. {
  25932. if (fragId != 0)
  25933. {
  25934. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  25935. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  25936. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  25937. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  25938. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  25939. }
  25940. }
  25941. #endif
  25942. #endif
  25943. };
  25944. /**
  25945. An instance of a plugin, created by a VSTPluginFormat.
  25946. */
  25947. class VSTPluginInstance : public AudioPluginInstance,
  25948. private Timer,
  25949. private AsyncUpdater
  25950. {
  25951. public:
  25952. ~VSTPluginInstance();
  25953. // AudioPluginInstance methods:
  25954. void fillInPluginDescription (PluginDescription& desc) const
  25955. {
  25956. desc.name = name;
  25957. desc.fileOrIdentifier = module->file.getFullPathName();
  25958. desc.uid = getUID();
  25959. desc.lastFileModTime = module->file.getLastModificationTime();
  25960. desc.pluginFormatName = "VST";
  25961. desc.category = getCategory();
  25962. {
  25963. char buffer [kVstMaxVendorStrLen + 8];
  25964. zerostruct (buffer);
  25965. dispatch (effGetVendorString, 0, 0, buffer, 0);
  25966. desc.manufacturerName = buffer;
  25967. }
  25968. desc.version = getVersion();
  25969. desc.numInputChannels = getNumInputChannels();
  25970. desc.numOutputChannels = getNumOutputChannels();
  25971. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  25972. }
  25973. const String getName() const { return name; }
  25974. int getUID() const throw();
  25975. bool acceptsMidi() const { return wantsMidiMessages; }
  25976. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  25977. // AudioProcessor methods:
  25978. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  25979. void releaseResources();
  25980. void processBlock (AudioSampleBuffer& buffer,
  25981. MidiBuffer& midiMessages);
  25982. AudioProcessorEditor* createEditor();
  25983. const String getInputChannelName (const int index) const;
  25984. bool isInputChannelStereoPair (int index) const;
  25985. const String getOutputChannelName (const int index) const;
  25986. bool isOutputChannelStereoPair (int index) const;
  25987. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  25988. float getParameter (int index);
  25989. void setParameter (int index, float newValue);
  25990. const String getParameterName (int index);
  25991. const String getParameterText (int index);
  25992. bool isParameterAutomatable (int index) const;
  25993. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  25994. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  25995. void setCurrentProgram (int index);
  25996. const String getProgramName (int index);
  25997. void changeProgramName (int index, const String& newName);
  25998. void getStateInformation (MemoryBlock& destData);
  25999. void getCurrentProgramStateInformation (MemoryBlock& destData);
  26000. void setStateInformation (const void* data, int sizeInBytes);
  26001. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  26002. void timerCallback();
  26003. void handleAsyncUpdate();
  26004. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  26005. juce_UseDebuggingNewOperator
  26006. private:
  26007. friend class VSTPluginWindow;
  26008. friend class VSTPluginFormat;
  26009. AEffect* effect;
  26010. String name;
  26011. CriticalSection lock;
  26012. bool wantsMidiMessages, initialised, isPowerOn;
  26013. mutable StringArray programNames;
  26014. AudioSampleBuffer tempBuffer;
  26015. CriticalSection midiInLock;
  26016. MidiBuffer incomingMidi;
  26017. VSTMidiEventList midiEventsToSend;
  26018. VstTimeInfo vstHostTime;
  26019. HeapBlock <float*> channels;
  26020. ReferenceCountedObjectPtr <ModuleHandle> module;
  26021. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  26022. bool restoreProgramSettings (const fxProgram* const prog);
  26023. const String getCurrentProgramName();
  26024. void setParamsInProgramBlock (fxProgram* const prog) throw();
  26025. void updateStoredProgramNames();
  26026. void initialise();
  26027. void handleMidiFromPlugin (const VstEvents* const events);
  26028. void createTempParameterStore (MemoryBlock& dest);
  26029. void restoreFromTempParameterStore (const MemoryBlock& mb);
  26030. const String getParameterLabel (int index) const;
  26031. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  26032. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  26033. void setChunkData (const char* data, int size, bool isPreset);
  26034. bool loadFromFXBFile (const void* data, int numBytes);
  26035. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  26036. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  26037. const String getVersion() const throw();
  26038. const String getCategory() const throw();
  26039. bool hasEditor() const throw() { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  26040. void setPower (const bool on);
  26041. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  26042. };
  26043. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  26044. : effect (0),
  26045. wantsMidiMessages (false),
  26046. initialised (false),
  26047. isPowerOn (false),
  26048. tempBuffer (1, 1),
  26049. module (module_)
  26050. {
  26051. try
  26052. {
  26053. _fpreset();
  26054. ++insideVSTCallback;
  26055. name = module->pluginName;
  26056. log ("Creating VST instance: " + name);
  26057. #if JUCE_MAC
  26058. if (module->resFileId != 0)
  26059. UseResFile (module->resFileId);
  26060. #if JUCE_PPC
  26061. if (module->fragId != 0)
  26062. {
  26063. static void* audioMasterCoerced = 0;
  26064. if (audioMasterCoerced == 0)
  26065. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  26066. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  26067. }
  26068. else
  26069. #endif
  26070. #endif
  26071. {
  26072. effect = module->moduleMain (&audioMaster);
  26073. }
  26074. --insideVSTCallback;
  26075. if (effect != 0 && effect->magic == kEffectMagic)
  26076. {
  26077. #if JUCE_PPC
  26078. module->coerceAEffectFunctionCalls (effect);
  26079. #endif
  26080. jassert (effect->resvd2 == 0);
  26081. jassert (effect->object != 0);
  26082. _fpreset(); // some dodgy plugs fuck around with this
  26083. }
  26084. else
  26085. {
  26086. effect = 0;
  26087. }
  26088. }
  26089. catch (...)
  26090. {
  26091. --insideVSTCallback;
  26092. }
  26093. }
  26094. VSTPluginInstance::~VSTPluginInstance()
  26095. {
  26096. {
  26097. const ScopedLock sl (lock);
  26098. jassert (insideVSTCallback == 0);
  26099. if (effect != 0 && effect->magic == kEffectMagic)
  26100. {
  26101. try
  26102. {
  26103. #if JUCE_MAC
  26104. if (module->resFileId != 0)
  26105. UseResFile (module->resFileId);
  26106. #endif
  26107. // Must delete any editors before deleting the plugin instance!
  26108. jassert (getActiveEditor() == 0);
  26109. _fpreset(); // some dodgy plugs fuck around with this
  26110. module->closeEffect (effect);
  26111. }
  26112. catch (...)
  26113. {}
  26114. }
  26115. module = 0;
  26116. effect = 0;
  26117. }
  26118. }
  26119. void VSTPluginInstance::initialise()
  26120. {
  26121. if (initialised || effect == 0)
  26122. return;
  26123. log ("Initialising VST: " + module->pluginName);
  26124. initialised = true;
  26125. dispatch (effIdentify, 0, 0, 0, 0);
  26126. // this code would ask the plugin for its name, but so few plugins
  26127. // actually bother implementing this correctly, that it's better to
  26128. // just ignore it and use the file name instead.
  26129. /* {
  26130. char buffer [256];
  26131. zerostruct (buffer);
  26132. dispatch (effGetEffectName, 0, 0, buffer, 0);
  26133. name = String (buffer).trim();
  26134. if (name.isEmpty())
  26135. name = module->pluginName;
  26136. }
  26137. */
  26138. if (getSampleRate() > 0)
  26139. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  26140. if (getBlockSize() > 0)
  26141. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  26142. dispatch (effOpen, 0, 0, 0, 0);
  26143. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  26144. getSampleRate(), getBlockSize());
  26145. if (getNumPrograms() > 1)
  26146. setCurrentProgram (0);
  26147. else
  26148. dispatch (effSetProgram, 0, 0, 0, 0);
  26149. int i;
  26150. for (i = effect->numInputs; --i >= 0;)
  26151. dispatch (effConnectInput, i, 1, 0, 0);
  26152. for (i = effect->numOutputs; --i >= 0;)
  26153. dispatch (effConnectOutput, i, 1, 0, 0);
  26154. updateStoredProgramNames();
  26155. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  26156. setLatencySamples (effect->initialDelay);
  26157. }
  26158. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  26159. int samplesPerBlockExpected)
  26160. {
  26161. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  26162. sampleRate_, samplesPerBlockExpected);
  26163. setLatencySamples (effect->initialDelay);
  26164. channels.calloc (jmax (16, getNumOutputChannels(), getNumInputChannels()) + 2);
  26165. vstHostTime.tempo = 120.0;
  26166. vstHostTime.timeSigNumerator = 4;
  26167. vstHostTime.timeSigDenominator = 4;
  26168. vstHostTime.sampleRate = sampleRate_;
  26169. vstHostTime.samplePos = 0;
  26170. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  26171. initialise();
  26172. if (initialised)
  26173. {
  26174. wantsMidiMessages = wantsMidiMessages
  26175. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  26176. if (wantsMidiMessages)
  26177. midiEventsToSend.ensureSize (256);
  26178. else
  26179. midiEventsToSend.freeEvents();
  26180. incomingMidi.clear();
  26181. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  26182. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  26183. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  26184. if (! isPowerOn)
  26185. setPower (true);
  26186. // dodgy hack to force some plugins to initialise the sample rate..
  26187. if ((! hasEditor()) && getNumParameters() > 0)
  26188. {
  26189. const float old = getParameter (0);
  26190. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  26191. setParameter (0, old);
  26192. }
  26193. dispatch (effStartProcess, 0, 0, 0, 0);
  26194. }
  26195. }
  26196. void VSTPluginInstance::releaseResources()
  26197. {
  26198. if (initialised)
  26199. {
  26200. dispatch (effStopProcess, 0, 0, 0, 0);
  26201. setPower (false);
  26202. }
  26203. tempBuffer.setSize (1, 1);
  26204. incomingMidi.clear();
  26205. midiEventsToSend.freeEvents();
  26206. channels.free();
  26207. }
  26208. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  26209. MidiBuffer& midiMessages)
  26210. {
  26211. const int numSamples = buffer.getNumSamples();
  26212. if (initialised)
  26213. {
  26214. AudioPlayHead* playHead = getPlayHead();
  26215. if (playHead != 0)
  26216. {
  26217. AudioPlayHead::CurrentPositionInfo position;
  26218. playHead->getCurrentPosition (position);
  26219. vstHostTime.tempo = position.bpm;
  26220. vstHostTime.timeSigNumerator = position.timeSigNumerator;
  26221. vstHostTime.timeSigDenominator = position.timeSigDenominator;
  26222. vstHostTime.ppqPos = position.ppqPosition;
  26223. vstHostTime.barStartPos = position.ppqPositionOfLastBarStart;
  26224. vstHostTime.flags |= kVstTempoValid | kVstTimeSigValid | kVstPpqPosValid | kVstBarsValid;
  26225. if (position.isPlaying)
  26226. vstHostTime.flags |= kVstTransportPlaying;
  26227. else
  26228. vstHostTime.flags &= ~kVstTransportPlaying;
  26229. }
  26230. #if JUCE_WINDOWS
  26231. vstHostTime.nanoSeconds = timeGetTime() * 1000000.0;
  26232. #elif JUCE_LINUX
  26233. timeval micro;
  26234. gettimeofday (&micro, 0);
  26235. vstHostTime.nanoSeconds = micro.tv_usec * 1000.0;
  26236. #elif JUCE_MAC
  26237. UnsignedWide micro;
  26238. Microseconds (&micro);
  26239. vstHostTime.nanoSeconds = micro.lo * 1000.0;
  26240. #endif
  26241. if (wantsMidiMessages)
  26242. {
  26243. midiEventsToSend.clear();
  26244. midiEventsToSend.ensureSize (1);
  26245. MidiBuffer::Iterator iter (midiMessages);
  26246. const uint8* midiData;
  26247. int numBytesOfMidiData, samplePosition;
  26248. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  26249. {
  26250. midiEventsToSend.addEvent (midiData, numBytesOfMidiData,
  26251. jlimit (0, numSamples - 1, samplePosition));
  26252. }
  26253. try
  26254. {
  26255. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend.events, 0);
  26256. }
  26257. catch (...)
  26258. {}
  26259. }
  26260. int i;
  26261. const int maxChans = jmax (effect->numInputs, effect->numOutputs);
  26262. for (i = 0; i < maxChans; ++i)
  26263. channels[i] = buffer.getSampleData (i);
  26264. channels [maxChans] = 0;
  26265. _clearfp();
  26266. if ((effect->flags & effFlagsCanReplacing) != 0)
  26267. {
  26268. try
  26269. {
  26270. effect->processReplacing (effect, channels, channels, numSamples);
  26271. }
  26272. catch (...)
  26273. {}
  26274. }
  26275. else
  26276. {
  26277. tempBuffer.setSize (effect->numOutputs, numSamples);
  26278. tempBuffer.clear();
  26279. float* outs [64];
  26280. for (i = effect->numOutputs; --i >= 0;)
  26281. outs[i] = tempBuffer.getSampleData (i);
  26282. outs [effect->numOutputs] = 0;
  26283. try
  26284. {
  26285. effect->process (effect, channels, outs, numSamples);
  26286. }
  26287. catch (...)
  26288. {}
  26289. for (i = effect->numOutputs; --i >= 0;)
  26290. buffer.copyFrom (i, 0, outs[i], numSamples);
  26291. }
  26292. }
  26293. else
  26294. {
  26295. // Not initialised, so just bypass..
  26296. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  26297. buffer.clear (i, 0, buffer.getNumSamples());
  26298. }
  26299. {
  26300. // copy any incoming midi..
  26301. const ScopedLock sl (midiInLock);
  26302. midiMessages.swapWith (incomingMidi);
  26303. incomingMidi.clear();
  26304. }
  26305. }
  26306. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  26307. {
  26308. if (events != 0)
  26309. {
  26310. const ScopedLock sl (midiInLock);
  26311. VSTMidiEventList::addEventsToMidiBuffer (events, incomingMidi);
  26312. }
  26313. }
  26314. static Array <VSTPluginWindow*> activeVSTWindows;
  26315. class VSTPluginWindow : public AudioProcessorEditor,
  26316. #if ! JUCE_MAC
  26317. public ComponentMovementWatcher,
  26318. #endif
  26319. public Timer
  26320. {
  26321. public:
  26322. VSTPluginWindow (VSTPluginInstance& plugin_)
  26323. : AudioProcessorEditor (&plugin_),
  26324. #if ! JUCE_MAC
  26325. ComponentMovementWatcher (this),
  26326. #endif
  26327. plugin (plugin_),
  26328. isOpen (false),
  26329. wasShowing (false),
  26330. pluginRefusesToResize (false),
  26331. pluginWantsKeys (false),
  26332. alreadyInside (false),
  26333. recursiveResize (false)
  26334. {
  26335. #if JUCE_WINDOWS
  26336. sizeCheckCount = 0;
  26337. pluginHWND = 0;
  26338. #elif JUCE_LINUX
  26339. pluginWindow = None;
  26340. pluginProc = None;
  26341. #else
  26342. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  26343. #endif
  26344. activeVSTWindows.add (this);
  26345. setSize (1, 1);
  26346. setOpaque (true);
  26347. setVisible (true);
  26348. }
  26349. ~VSTPluginWindow()
  26350. {
  26351. #if JUCE_MAC
  26352. innerWrapper = 0;
  26353. #else
  26354. closePluginWindow();
  26355. #endif
  26356. activeVSTWindows.removeValue (this);
  26357. plugin.editorBeingDeleted (this);
  26358. }
  26359. #if ! JUCE_MAC
  26360. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  26361. {
  26362. if (recursiveResize)
  26363. return;
  26364. Component* const topComp = getTopLevelComponent();
  26365. if (topComp->getPeer() != 0)
  26366. {
  26367. const Point<int> pos (relativePositionToOtherComponent (topComp, Point<int>()));
  26368. recursiveResize = true;
  26369. #if JUCE_WINDOWS
  26370. if (pluginHWND != 0)
  26371. MoveWindow (pluginHWND, pos.getX(), pos.getY(), getWidth(), getHeight(), TRUE);
  26372. #elif JUCE_LINUX
  26373. if (pluginWindow != 0)
  26374. {
  26375. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  26376. XMoveWindow (display, pluginWindow, pos.getX(), pos.getY());
  26377. XMapRaised (display, pluginWindow);
  26378. }
  26379. #endif
  26380. recursiveResize = false;
  26381. }
  26382. }
  26383. void componentVisibilityChanged (Component&)
  26384. {
  26385. const bool isShowingNow = isShowing();
  26386. if (wasShowing != isShowingNow)
  26387. {
  26388. wasShowing = isShowingNow;
  26389. if (isShowingNow)
  26390. openPluginWindow();
  26391. else
  26392. closePluginWindow();
  26393. }
  26394. componentMovedOrResized (true, true);
  26395. }
  26396. void componentPeerChanged()
  26397. {
  26398. closePluginWindow();
  26399. openPluginWindow();
  26400. }
  26401. #endif
  26402. bool keyStateChanged (bool)
  26403. {
  26404. return pluginWantsKeys;
  26405. }
  26406. bool keyPressed (const KeyPress&)
  26407. {
  26408. return pluginWantsKeys;
  26409. }
  26410. #if JUCE_MAC
  26411. void paint (Graphics& g)
  26412. {
  26413. g.fillAll (Colours::black);
  26414. }
  26415. #else
  26416. void paint (Graphics& g)
  26417. {
  26418. if (isOpen)
  26419. {
  26420. ComponentPeer* const peer = getPeer();
  26421. if (peer != 0)
  26422. {
  26423. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  26424. peer->addMaskedRegion (pos.getX(), pos.getY(), getWidth(), getHeight());
  26425. #if JUCE_LINUX
  26426. if (pluginWindow != 0)
  26427. {
  26428. const Rectangle<int> clip (g.getClipBounds());
  26429. XEvent ev;
  26430. zerostruct (ev);
  26431. ev.xexpose.type = Expose;
  26432. ev.xexpose.display = display;
  26433. ev.xexpose.window = pluginWindow;
  26434. ev.xexpose.x = clip.getX();
  26435. ev.xexpose.y = clip.getY();
  26436. ev.xexpose.width = clip.getWidth();
  26437. ev.xexpose.height = clip.getHeight();
  26438. sendEventToChild (&ev);
  26439. }
  26440. #endif
  26441. }
  26442. }
  26443. else
  26444. {
  26445. g.fillAll (Colours::black);
  26446. }
  26447. }
  26448. #endif
  26449. void timerCallback()
  26450. {
  26451. #if JUCE_WINDOWS
  26452. if (--sizeCheckCount <= 0)
  26453. {
  26454. sizeCheckCount = 10;
  26455. checkPluginWindowSize();
  26456. }
  26457. #endif
  26458. try
  26459. {
  26460. static bool reentrant = false;
  26461. if (! reentrant)
  26462. {
  26463. reentrant = true;
  26464. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  26465. reentrant = false;
  26466. }
  26467. }
  26468. catch (...)
  26469. {}
  26470. }
  26471. void mouseDown (const MouseEvent& e)
  26472. {
  26473. #if JUCE_LINUX
  26474. if (pluginWindow == 0)
  26475. return;
  26476. toFront (true);
  26477. XEvent ev;
  26478. zerostruct (ev);
  26479. ev.xbutton.display = display;
  26480. ev.xbutton.type = ButtonPress;
  26481. ev.xbutton.window = pluginWindow;
  26482. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  26483. ev.xbutton.time = CurrentTime;
  26484. ev.xbutton.x = e.x;
  26485. ev.xbutton.y = e.y;
  26486. ev.xbutton.x_root = e.getScreenX();
  26487. ev.xbutton.y_root = e.getScreenY();
  26488. translateJuceToXButtonModifiers (e, ev);
  26489. sendEventToChild (&ev);
  26490. #elif JUCE_WINDOWS
  26491. (void) e;
  26492. toFront (true);
  26493. #endif
  26494. }
  26495. void broughtToFront()
  26496. {
  26497. activeVSTWindows.removeValue (this);
  26498. activeVSTWindows.add (this);
  26499. #if JUCE_MAC
  26500. dispatch (effEditTop, 0, 0, 0, 0);
  26501. #endif
  26502. }
  26503. juce_UseDebuggingNewOperator
  26504. private:
  26505. VSTPluginInstance& plugin;
  26506. bool isOpen, wasShowing, recursiveResize;
  26507. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  26508. #if JUCE_WINDOWS
  26509. HWND pluginHWND;
  26510. void* originalWndProc;
  26511. int sizeCheckCount;
  26512. #elif JUCE_LINUX
  26513. Window pluginWindow;
  26514. EventProcPtr pluginProc;
  26515. #endif
  26516. #if JUCE_MAC
  26517. void openPluginWindow (WindowRef parentWindow)
  26518. {
  26519. if (isOpen || parentWindow == 0)
  26520. return;
  26521. isOpen = true;
  26522. ERect* rect = 0;
  26523. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26524. dispatch (effEditOpen, 0, 0, parentWindow, 0);
  26525. // do this before and after like in the steinberg example
  26526. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26527. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  26528. // Install keyboard hooks
  26529. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  26530. // double-check it's not too tiny
  26531. int w = 250, h = 150;
  26532. if (rect != 0)
  26533. {
  26534. w = rect->right - rect->left;
  26535. h = rect->bottom - rect->top;
  26536. if (w == 0 || h == 0)
  26537. {
  26538. w = 250;
  26539. h = 150;
  26540. }
  26541. }
  26542. w = jmax (w, 32);
  26543. h = jmax (h, 32);
  26544. setSize (w, h);
  26545. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  26546. repaint();
  26547. }
  26548. #else
  26549. void openPluginWindow()
  26550. {
  26551. if (isOpen || getWindowHandle() == 0)
  26552. return;
  26553. log ("Opening VST UI: " + plugin.name);
  26554. isOpen = true;
  26555. ERect* rect = 0;
  26556. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26557. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  26558. // do this before and after like in the steinberg example
  26559. dispatch (effEditGetRect, 0, 0, &rect, 0);
  26560. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  26561. // Install keyboard hooks
  26562. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  26563. #if JUCE_WINDOWS
  26564. originalWndProc = 0;
  26565. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  26566. if (pluginHWND == 0)
  26567. {
  26568. isOpen = false;
  26569. setSize (300, 150);
  26570. return;
  26571. }
  26572. #pragma warning (push)
  26573. #pragma warning (disable: 4244)
  26574. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWL_WNDPROC);
  26575. if (! pluginWantsKeys)
  26576. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) vstHookWndProc);
  26577. #pragma warning (pop)
  26578. int w, h;
  26579. RECT r;
  26580. GetWindowRect (pluginHWND, &r);
  26581. w = r.right - r.left;
  26582. h = r.bottom - r.top;
  26583. if (rect != 0)
  26584. {
  26585. const int rw = rect->right - rect->left;
  26586. const int rh = rect->bottom - rect->top;
  26587. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  26588. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  26589. {
  26590. // very dodgy logic to decide which size is right.
  26591. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  26592. {
  26593. SetWindowPos (pluginHWND, 0,
  26594. 0, 0, rw, rh,
  26595. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  26596. GetWindowRect (pluginHWND, &r);
  26597. w = r.right - r.left;
  26598. h = r.bottom - r.top;
  26599. pluginRefusesToResize = (w != rw) || (h != rh);
  26600. w = rw;
  26601. h = rh;
  26602. }
  26603. }
  26604. }
  26605. #elif JUCE_LINUX
  26606. pluginWindow = getChildWindow ((Window) getWindowHandle());
  26607. if (pluginWindow != 0)
  26608. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  26609. XInternAtom (display, "_XEventProc", False));
  26610. int w = 250, h = 150;
  26611. if (rect != 0)
  26612. {
  26613. w = rect->right - rect->left;
  26614. h = rect->bottom - rect->top;
  26615. if (w == 0 || h == 0)
  26616. {
  26617. w = 250;
  26618. h = 150;
  26619. }
  26620. }
  26621. if (pluginWindow != 0)
  26622. XMapRaised (display, pluginWindow);
  26623. #endif
  26624. // double-check it's not too tiny
  26625. w = jmax (w, 32);
  26626. h = jmax (h, 32);
  26627. setSize (w, h);
  26628. #if JUCE_WINDOWS
  26629. checkPluginWindowSize();
  26630. #endif
  26631. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  26632. repaint();
  26633. }
  26634. #endif
  26635. #if ! JUCE_MAC
  26636. void closePluginWindow()
  26637. {
  26638. if (isOpen)
  26639. {
  26640. log ("Closing VST UI: " + plugin.getName());
  26641. isOpen = false;
  26642. dispatch (effEditClose, 0, 0, 0, 0);
  26643. #if JUCE_WINDOWS
  26644. #pragma warning (push)
  26645. #pragma warning (disable: 4244)
  26646. if (pluginHWND != 0 && IsWindow (pluginHWND))
  26647. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) originalWndProc);
  26648. #pragma warning (pop)
  26649. stopTimer();
  26650. if (pluginHWND != 0 && IsWindow (pluginHWND))
  26651. DestroyWindow (pluginHWND);
  26652. pluginHWND = 0;
  26653. #elif JUCE_LINUX
  26654. stopTimer();
  26655. pluginWindow = 0;
  26656. pluginProc = 0;
  26657. #endif
  26658. }
  26659. }
  26660. #endif
  26661. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  26662. {
  26663. return plugin.dispatch (opcode, index, value, ptr, opt);
  26664. }
  26665. #if JUCE_WINDOWS
  26666. void checkPluginWindowSize() throw()
  26667. {
  26668. RECT r;
  26669. GetWindowRect (pluginHWND, &r);
  26670. const int w = r.right - r.left;
  26671. const int h = r.bottom - r.top;
  26672. if (isShowing() && w > 0 && h > 0
  26673. && (w != getWidth() || h != getHeight())
  26674. && ! pluginRefusesToResize)
  26675. {
  26676. setSize (w, h);
  26677. sizeCheckCount = 0;
  26678. }
  26679. }
  26680. // hooks to get keyboard events from VST windows..
  26681. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  26682. {
  26683. for (int i = activeVSTWindows.size(); --i >= 0;)
  26684. {
  26685. const VSTPluginWindow* const w = (const VSTPluginWindow*) activeVSTWindows.getUnchecked (i);
  26686. if (w->pluginHWND == hW)
  26687. {
  26688. if (message == WM_CHAR
  26689. || message == WM_KEYDOWN
  26690. || message == WM_SYSKEYDOWN
  26691. || message == WM_KEYUP
  26692. || message == WM_SYSKEYUP
  26693. || message == WM_APPCOMMAND)
  26694. {
  26695. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  26696. message, wParam, lParam);
  26697. }
  26698. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  26699. (HWND) w->pluginHWND,
  26700. message,
  26701. wParam,
  26702. lParam);
  26703. }
  26704. }
  26705. return DefWindowProc (hW, message, wParam, lParam);
  26706. }
  26707. #endif
  26708. #if JUCE_LINUX
  26709. // overload mouse/keyboard events to forward them to the plugin's inner window..
  26710. void sendEventToChild (XEvent* event)
  26711. {
  26712. if (pluginProc != 0)
  26713. {
  26714. // if the plugin publishes an event procedure, pass the event directly..
  26715. pluginProc (event);
  26716. }
  26717. else if (pluginWindow != 0)
  26718. {
  26719. // if the plugin has a window, then send the event to the window so that
  26720. // its message thread will pick it up..
  26721. XSendEvent (display, pluginWindow, False, 0L, event);
  26722. XFlush (display);
  26723. }
  26724. }
  26725. void mouseEnter (const MouseEvent& e)
  26726. {
  26727. if (pluginWindow != 0)
  26728. {
  26729. XEvent ev;
  26730. zerostruct (ev);
  26731. ev.xcrossing.display = display;
  26732. ev.xcrossing.type = EnterNotify;
  26733. ev.xcrossing.window = pluginWindow;
  26734. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  26735. ev.xcrossing.time = CurrentTime;
  26736. ev.xcrossing.x = e.x;
  26737. ev.xcrossing.y = e.y;
  26738. ev.xcrossing.x_root = e.getScreenX();
  26739. ev.xcrossing.y_root = e.getScreenY();
  26740. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  26741. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  26742. translateJuceToXCrossingModifiers (e, ev);
  26743. sendEventToChild (&ev);
  26744. }
  26745. }
  26746. void mouseExit (const MouseEvent& e)
  26747. {
  26748. if (pluginWindow != 0)
  26749. {
  26750. XEvent ev;
  26751. zerostruct (ev);
  26752. ev.xcrossing.display = display;
  26753. ev.xcrossing.type = LeaveNotify;
  26754. ev.xcrossing.window = pluginWindow;
  26755. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  26756. ev.xcrossing.time = CurrentTime;
  26757. ev.xcrossing.x = e.x;
  26758. ev.xcrossing.y = e.y;
  26759. ev.xcrossing.x_root = e.getScreenX();
  26760. ev.xcrossing.y_root = e.getScreenY();
  26761. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  26762. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  26763. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  26764. translateJuceToXCrossingModifiers (e, ev);
  26765. sendEventToChild (&ev);
  26766. }
  26767. }
  26768. void mouseMove (const MouseEvent& e)
  26769. {
  26770. if (pluginWindow != 0)
  26771. {
  26772. XEvent ev;
  26773. zerostruct (ev);
  26774. ev.xmotion.display = display;
  26775. ev.xmotion.type = MotionNotify;
  26776. ev.xmotion.window = pluginWindow;
  26777. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  26778. ev.xmotion.time = CurrentTime;
  26779. ev.xmotion.is_hint = NotifyNormal;
  26780. ev.xmotion.x = e.x;
  26781. ev.xmotion.y = e.y;
  26782. ev.xmotion.x_root = e.getScreenX();
  26783. ev.xmotion.y_root = e.getScreenY();
  26784. sendEventToChild (&ev);
  26785. }
  26786. }
  26787. void mouseDrag (const MouseEvent& e)
  26788. {
  26789. if (pluginWindow != 0)
  26790. {
  26791. XEvent ev;
  26792. zerostruct (ev);
  26793. ev.xmotion.display = display;
  26794. ev.xmotion.type = MotionNotify;
  26795. ev.xmotion.window = pluginWindow;
  26796. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  26797. ev.xmotion.time = CurrentTime;
  26798. ev.xmotion.x = e.x ;
  26799. ev.xmotion.y = e.y;
  26800. ev.xmotion.x_root = e.getScreenX();
  26801. ev.xmotion.y_root = e.getScreenY();
  26802. ev.xmotion.is_hint = NotifyNormal;
  26803. translateJuceToXMotionModifiers (e, ev);
  26804. sendEventToChild (&ev);
  26805. }
  26806. }
  26807. void mouseUp (const MouseEvent& e)
  26808. {
  26809. if (pluginWindow != 0)
  26810. {
  26811. XEvent ev;
  26812. zerostruct (ev);
  26813. ev.xbutton.display = display;
  26814. ev.xbutton.type = ButtonRelease;
  26815. ev.xbutton.window = pluginWindow;
  26816. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  26817. ev.xbutton.time = CurrentTime;
  26818. ev.xbutton.x = e.x;
  26819. ev.xbutton.y = e.y;
  26820. ev.xbutton.x_root = e.getScreenX();
  26821. ev.xbutton.y_root = e.getScreenY();
  26822. translateJuceToXButtonModifiers (e, ev);
  26823. sendEventToChild (&ev);
  26824. }
  26825. }
  26826. void mouseWheelMove (const MouseEvent& e,
  26827. float incrementX,
  26828. float incrementY)
  26829. {
  26830. if (pluginWindow != 0)
  26831. {
  26832. XEvent ev;
  26833. zerostruct (ev);
  26834. ev.xbutton.display = display;
  26835. ev.xbutton.type = ButtonPress;
  26836. ev.xbutton.window = pluginWindow;
  26837. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  26838. ev.xbutton.time = CurrentTime;
  26839. ev.xbutton.x = e.x;
  26840. ev.xbutton.y = e.y;
  26841. ev.xbutton.x_root = e.getScreenX();
  26842. ev.xbutton.y_root = e.getScreenY();
  26843. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  26844. sendEventToChild (&ev);
  26845. // TODO - put a usleep here ?
  26846. ev.xbutton.type = ButtonRelease;
  26847. sendEventToChild (&ev);
  26848. }
  26849. }
  26850. #endif
  26851. #if JUCE_MAC
  26852. #if ! JUCE_SUPPORT_CARBON
  26853. #error "To build VSTs, you need to enable the JUCE_SUPPORT_CARBON flag in your config!"
  26854. #endif
  26855. class InnerWrapperComponent : public CarbonViewWrapperComponent
  26856. {
  26857. public:
  26858. InnerWrapperComponent (VSTPluginWindow* const owner_)
  26859. : owner (owner_),
  26860. alreadyInside (false)
  26861. {
  26862. }
  26863. ~InnerWrapperComponent()
  26864. {
  26865. deleteWindow();
  26866. }
  26867. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  26868. {
  26869. owner->openPluginWindow (windowRef);
  26870. return 0;
  26871. }
  26872. void removeView (HIViewRef)
  26873. {
  26874. owner->dispatch (effEditClose, 0, 0, 0, 0);
  26875. owner->dispatch (effEditSleep, 0, 0, 0, 0);
  26876. }
  26877. bool getEmbeddedViewSize (int& w, int& h)
  26878. {
  26879. ERect* rect = 0;
  26880. owner->dispatch (effEditGetRect, 0, 0, &rect, 0);
  26881. w = rect->right - rect->left;
  26882. h = rect->bottom - rect->top;
  26883. return true;
  26884. }
  26885. void mouseDown (int x, int y)
  26886. {
  26887. if (! alreadyInside)
  26888. {
  26889. alreadyInside = true;
  26890. getTopLevelComponent()->toFront (true);
  26891. owner->dispatch (effEditMouse, x, y, 0, 0);
  26892. alreadyInside = false;
  26893. }
  26894. else
  26895. {
  26896. PostEvent (::mouseDown, 0);
  26897. }
  26898. }
  26899. void paint()
  26900. {
  26901. ComponentPeer* const peer = getPeer();
  26902. if (peer != 0)
  26903. {
  26904. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  26905. ERect r;
  26906. r.left = pos.getX();
  26907. r.right = r.left + getWidth();
  26908. r.top = pos.getY();
  26909. r.bottom = r.top + getHeight();
  26910. owner->dispatch (effEditDraw, 0, 0, &r, 0);
  26911. }
  26912. }
  26913. private:
  26914. VSTPluginWindow* const owner;
  26915. bool alreadyInside;
  26916. };
  26917. friend class InnerWrapperComponent;
  26918. ScopedPointer <InnerWrapperComponent> innerWrapper;
  26919. void resized()
  26920. {
  26921. innerWrapper->setSize (getWidth(), getHeight());
  26922. }
  26923. #endif
  26924. };
  26925. AudioProcessorEditor* VSTPluginInstance::createEditor()
  26926. {
  26927. if (hasEditor())
  26928. return new VSTPluginWindow (*this);
  26929. return 0;
  26930. }
  26931. void VSTPluginInstance::handleAsyncUpdate()
  26932. {
  26933. // indicates that something about the plugin has changed..
  26934. updateHostDisplay();
  26935. }
  26936. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  26937. {
  26938. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  26939. {
  26940. changeProgramName (getCurrentProgram(), prog->prgName);
  26941. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  26942. setParameter (i, vst_swapFloat (prog->params[i]));
  26943. return true;
  26944. }
  26945. return false;
  26946. }
  26947. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  26948. const int dataSize)
  26949. {
  26950. if (dataSize < 28)
  26951. return false;
  26952. const fxSet* const set = (const fxSet*) data;
  26953. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  26954. || vst_swap (set->version) > fxbVersionNum)
  26955. return false;
  26956. if (vst_swap (set->fxMagic) == 'FxBk')
  26957. {
  26958. // bank of programs
  26959. if (vst_swap (set->numPrograms) >= 0)
  26960. {
  26961. const int oldProg = getCurrentProgram();
  26962. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  26963. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  26964. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  26965. {
  26966. if (i != oldProg)
  26967. {
  26968. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  26969. if (((const char*) prog) - ((const char*) set) >= dataSize)
  26970. return false;
  26971. if (vst_swap (set->numPrograms) > 0)
  26972. setCurrentProgram (i);
  26973. if (! restoreProgramSettings (prog))
  26974. return false;
  26975. }
  26976. }
  26977. if (vst_swap (set->numPrograms) > 0)
  26978. setCurrentProgram (oldProg);
  26979. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  26980. if (((const char*) prog) - ((const char*) set) >= dataSize)
  26981. return false;
  26982. if (! restoreProgramSettings (prog))
  26983. return false;
  26984. }
  26985. }
  26986. else if (vst_swap (set->fxMagic) == 'FxCk')
  26987. {
  26988. // single program
  26989. const fxProgram* const prog = (const fxProgram*) data;
  26990. if (vst_swap (prog->chunkMagic) != 'CcnK')
  26991. return false;
  26992. changeProgramName (getCurrentProgram(), prog->prgName);
  26993. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  26994. setParameter (i, vst_swapFloat (prog->params[i]));
  26995. }
  26996. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  26997. {
  26998. // non-preset chunk
  26999. const fxChunkSet* const cset = (const fxChunkSet*) data;
  27000. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  27001. return false;
  27002. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  27003. }
  27004. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  27005. {
  27006. // preset chunk
  27007. const fxProgramSet* const cset = (const fxProgramSet*) data;
  27008. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  27009. return false;
  27010. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  27011. changeProgramName (getCurrentProgram(), cset->name);
  27012. }
  27013. else
  27014. {
  27015. return false;
  27016. }
  27017. return true;
  27018. }
  27019. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog) throw()
  27020. {
  27021. const int numParams = getNumParameters();
  27022. prog->chunkMagic = vst_swap ('CcnK');
  27023. prog->byteSize = 0;
  27024. prog->fxMagic = vst_swap ('FxCk');
  27025. prog->version = vst_swap (fxbVersionNum);
  27026. prog->fxID = vst_swap (getUID());
  27027. prog->fxVersion = vst_swap (getVersionNumber());
  27028. prog->numParams = vst_swap (numParams);
  27029. getCurrentProgramName().copyToCString (prog->prgName, sizeof (prog->prgName) - 1);
  27030. for (int i = 0; i < numParams; ++i)
  27031. prog->params[i] = vst_swapFloat (getParameter (i));
  27032. }
  27033. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  27034. {
  27035. const int numPrograms = getNumPrograms();
  27036. const int numParams = getNumParameters();
  27037. if (usesChunks())
  27038. {
  27039. if (isFXB)
  27040. {
  27041. MemoryBlock chunk;
  27042. getChunkData (chunk, false, maxSizeMB);
  27043. const size_t totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  27044. dest.setSize (totalLen, true);
  27045. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  27046. set->chunkMagic = vst_swap ('CcnK');
  27047. set->byteSize = 0;
  27048. set->fxMagic = vst_swap ('FBCh');
  27049. set->version = vst_swap (fxbVersionNum);
  27050. set->fxID = vst_swap (getUID());
  27051. set->fxVersion = vst_swap (getVersionNumber());
  27052. set->numPrograms = vst_swap (numPrograms);
  27053. set->chunkSize = vst_swap ((long) chunk.getSize());
  27054. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27055. }
  27056. else
  27057. {
  27058. MemoryBlock chunk;
  27059. getChunkData (chunk, true, maxSizeMB);
  27060. const size_t totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  27061. dest.setSize (totalLen, true);
  27062. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  27063. set->chunkMagic = vst_swap ('CcnK');
  27064. set->byteSize = 0;
  27065. set->fxMagic = vst_swap ('FPCh');
  27066. set->version = vst_swap (fxbVersionNum);
  27067. set->fxID = vst_swap (getUID());
  27068. set->fxVersion = vst_swap (getVersionNumber());
  27069. set->numPrograms = vst_swap (numPrograms);
  27070. set->chunkSize = vst_swap ((long) chunk.getSize());
  27071. getCurrentProgramName().copyToCString (set->name, sizeof (set->name) - 1);
  27072. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27073. }
  27074. }
  27075. else
  27076. {
  27077. if (isFXB)
  27078. {
  27079. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27080. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  27081. dest.setSize (len, true);
  27082. fxSet* const set = (fxSet*) dest.getData();
  27083. set->chunkMagic = vst_swap ('CcnK');
  27084. set->byteSize = 0;
  27085. set->fxMagic = vst_swap ('FxBk');
  27086. set->version = vst_swap (fxbVersionNum);
  27087. set->fxID = vst_swap (getUID());
  27088. set->fxVersion = vst_swap (getVersionNumber());
  27089. set->numPrograms = vst_swap (numPrograms);
  27090. const int oldProgram = getCurrentProgram();
  27091. MemoryBlock oldSettings;
  27092. createTempParameterStore (oldSettings);
  27093. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  27094. for (int i = 0; i < numPrograms; ++i)
  27095. {
  27096. if (i != oldProgram)
  27097. {
  27098. setCurrentProgram (i);
  27099. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  27100. }
  27101. }
  27102. setCurrentProgram (oldProgram);
  27103. restoreFromTempParameterStore (oldSettings);
  27104. }
  27105. else
  27106. {
  27107. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27108. dest.setSize (totalLen, true);
  27109. setParamsInProgramBlock ((fxProgram*) dest.getData());
  27110. }
  27111. }
  27112. return true;
  27113. }
  27114. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  27115. {
  27116. if (usesChunks())
  27117. {
  27118. void* data = 0;
  27119. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  27120. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  27121. {
  27122. mb.setSize (bytes);
  27123. mb.copyFrom (data, 0, bytes);
  27124. }
  27125. }
  27126. }
  27127. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  27128. {
  27129. if (size > 0 && usesChunks())
  27130. {
  27131. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  27132. if (! isPreset)
  27133. updateStoredProgramNames();
  27134. }
  27135. }
  27136. void VSTPluginInstance::timerCallback()
  27137. {
  27138. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  27139. stopTimer();
  27140. }
  27141. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  27142. {
  27143. const ScopedLock sl (lock);
  27144. ++insideVSTCallback;
  27145. int result = 0;
  27146. try
  27147. {
  27148. if (effect != 0)
  27149. {
  27150. #if JUCE_MAC
  27151. if (module->resFileId != 0)
  27152. UseResFile (module->resFileId);
  27153. CGrafPtr oldPort;
  27154. if (getActiveEditor() != 0)
  27155. {
  27156. const Point<int> pos (getActiveEditor()->relativePositionToOtherComponent (getActiveEditor()->getTopLevelComponent(), Point<int>()));
  27157. GetPort (&oldPort);
  27158. SetPortWindowPort ((WindowRef) getActiveEditor()->getWindowHandle());
  27159. SetOrigin (-pos.getX(), -pos.getY());
  27160. }
  27161. #endif
  27162. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  27163. #if JUCE_MAC
  27164. if (getActiveEditor() != 0)
  27165. SetPort (oldPort);
  27166. module->resFileId = CurResFile();
  27167. #endif
  27168. --insideVSTCallback;
  27169. return result;
  27170. }
  27171. }
  27172. catch (...)
  27173. {
  27174. }
  27175. --insideVSTCallback;
  27176. return result;
  27177. }
  27178. // handles non plugin-specific callbacks..
  27179. static const int defaultVSTSampleRateValue = 16384;
  27180. static const int defaultVSTBlockSizeValue = 512;
  27181. static VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  27182. {
  27183. (void) index;
  27184. (void) value;
  27185. (void) opt;
  27186. switch (opcode)
  27187. {
  27188. case audioMasterCanDo:
  27189. {
  27190. static const char* canDos[] = { "supplyIdle",
  27191. "sendVstEvents",
  27192. "sendVstMidiEvent",
  27193. "sendVstTimeInfo",
  27194. "receiveVstEvents",
  27195. "receiveVstMidiEvent",
  27196. "supportShell",
  27197. "shellCategory" };
  27198. for (int i = 0; i < numElementsInArray (canDos); ++i)
  27199. if (strcmp (canDos[i], (const char*) ptr) == 0)
  27200. return 1;
  27201. return 0;
  27202. }
  27203. case audioMasterVersion:
  27204. return 0x2400;
  27205. case audioMasterCurrentId:
  27206. return shellUIDToCreate;
  27207. case audioMasterGetNumAutomatableParameters:
  27208. return 0;
  27209. case audioMasterGetAutomationState:
  27210. return 1;
  27211. case audioMasterGetVendorVersion:
  27212. return 0x0101;
  27213. case audioMasterGetVendorString:
  27214. case audioMasterGetProductString:
  27215. {
  27216. String hostName ("Juce VST Host");
  27217. if (JUCEApplication::getInstance() != 0)
  27218. hostName = JUCEApplication::getInstance()->getApplicationName();
  27219. hostName.copyToCString ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  27220. }
  27221. break;
  27222. case audioMasterGetSampleRate:
  27223. return (VstIntPtr) defaultVSTSampleRateValue;
  27224. case audioMasterGetBlockSize:
  27225. return (VstIntPtr) defaultVSTBlockSizeValue;
  27226. case audioMasterSetOutputSampleRate:
  27227. return 0;
  27228. default:
  27229. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  27230. break;
  27231. }
  27232. return 0;
  27233. }
  27234. // handles callbacks for a specific plugin
  27235. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  27236. {
  27237. switch (opcode)
  27238. {
  27239. case audioMasterAutomate:
  27240. sendParamChangeMessageToListeners (index, opt);
  27241. break;
  27242. case audioMasterProcessEvents:
  27243. handleMidiFromPlugin ((const VstEvents*) ptr);
  27244. break;
  27245. case audioMasterGetTime:
  27246. #if JUCE_MSVC
  27247. #pragma warning (push)
  27248. #pragma warning (disable: 4311)
  27249. #endif
  27250. return (VstIntPtr) &vstHostTime;
  27251. #if JUCE_MSVC
  27252. #pragma warning (pop)
  27253. #endif
  27254. break;
  27255. case audioMasterIdle:
  27256. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  27257. {
  27258. ++insideVSTCallback;
  27259. #if JUCE_MAC
  27260. if (getActiveEditor() != 0)
  27261. dispatch (effEditIdle, 0, 0, 0, 0);
  27262. #endif
  27263. juce_callAnyTimersSynchronously();
  27264. handleUpdateNowIfNeeded();
  27265. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  27266. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  27267. --insideVSTCallback;
  27268. }
  27269. break;
  27270. case audioMasterUpdateDisplay:
  27271. triggerAsyncUpdate();
  27272. break;
  27273. case audioMasterTempoAt:
  27274. // returns (10000 * bpm)
  27275. break;
  27276. case audioMasterNeedIdle:
  27277. startTimer (50);
  27278. break;
  27279. case audioMasterSizeWindow:
  27280. if (getActiveEditor() != 0)
  27281. getActiveEditor()->setSize (index, value);
  27282. return 1;
  27283. case audioMasterGetSampleRate:
  27284. return (VstIntPtr) (getSampleRate() > 0 ? getSampleRate() : defaultVSTSampleRateValue);
  27285. case audioMasterGetBlockSize:
  27286. return (VstIntPtr) (getBlockSize() > 0 ? getBlockSize() : defaultVSTBlockSizeValue);
  27287. case audioMasterWantMidi:
  27288. wantsMidiMessages = true;
  27289. break;
  27290. case audioMasterGetDirectory:
  27291. #if JUCE_MAC
  27292. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  27293. #else
  27294. return (VstIntPtr) (pointer_sized_uint) module->fullParentDirectoryPathName.toUTF8();
  27295. #endif
  27296. case audioMasterGetAutomationState:
  27297. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  27298. break;
  27299. // none of these are handled (yet)..
  27300. case audioMasterBeginEdit:
  27301. case audioMasterEndEdit:
  27302. case audioMasterSetTime:
  27303. case audioMasterPinConnected:
  27304. case audioMasterGetParameterQuantization:
  27305. case audioMasterIOChanged:
  27306. case audioMasterGetInputLatency:
  27307. case audioMasterGetOutputLatency:
  27308. case audioMasterGetPreviousPlug:
  27309. case audioMasterGetNextPlug:
  27310. case audioMasterWillReplaceOrAccumulate:
  27311. case audioMasterGetCurrentProcessLevel:
  27312. case audioMasterOfflineStart:
  27313. case audioMasterOfflineRead:
  27314. case audioMasterOfflineWrite:
  27315. case audioMasterOfflineGetCurrentPass:
  27316. case audioMasterOfflineGetCurrentMetaPass:
  27317. case audioMasterVendorSpecific:
  27318. case audioMasterSetIcon:
  27319. case audioMasterGetLanguage:
  27320. case audioMasterOpenWindow:
  27321. case audioMasterCloseWindow:
  27322. break;
  27323. default:
  27324. return handleGeneralCallback (opcode, index, value, ptr, opt);
  27325. }
  27326. return 0;
  27327. }
  27328. // entry point for all callbacks from the plugin
  27329. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  27330. {
  27331. try
  27332. {
  27333. if (effect != 0 && effect->resvd2 != 0)
  27334. {
  27335. return ((VSTPluginInstance*)(effect->resvd2))
  27336. ->handleCallback (opcode, index, value, ptr, opt);
  27337. }
  27338. return handleGeneralCallback (opcode, index, value, ptr, opt);
  27339. }
  27340. catch (...)
  27341. {
  27342. return 0;
  27343. }
  27344. }
  27345. const String VSTPluginInstance::getVersion() const throw()
  27346. {
  27347. unsigned int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  27348. String s;
  27349. if (v == 0 || v == -1)
  27350. v = getVersionNumber();
  27351. if (v != 0)
  27352. {
  27353. int versionBits[4];
  27354. int n = 0;
  27355. while (v != 0)
  27356. {
  27357. versionBits [n++] = (v & 0xff);
  27358. v >>= 8;
  27359. }
  27360. s << 'V';
  27361. while (n > 0)
  27362. {
  27363. s << versionBits [--n];
  27364. if (n > 0)
  27365. s << '.';
  27366. }
  27367. }
  27368. return s;
  27369. }
  27370. int VSTPluginInstance::getUID() const throw()
  27371. {
  27372. int uid = effect != 0 ? effect->uniqueID : 0;
  27373. if (uid == 0)
  27374. uid = module->file.hashCode();
  27375. return uid;
  27376. }
  27377. const String VSTPluginInstance::getCategory() const throw()
  27378. {
  27379. const char* result = 0;
  27380. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  27381. {
  27382. case kPlugCategEffect:
  27383. result = "Effect";
  27384. break;
  27385. case kPlugCategSynth:
  27386. result = "Synth";
  27387. break;
  27388. case kPlugCategAnalysis:
  27389. result = "Anaylsis";
  27390. break;
  27391. case kPlugCategMastering:
  27392. result = "Mastering";
  27393. break;
  27394. case kPlugCategSpacializer:
  27395. result = "Spacial";
  27396. break;
  27397. case kPlugCategRoomFx:
  27398. result = "Reverb";
  27399. break;
  27400. case kPlugSurroundFx:
  27401. result = "Surround";
  27402. break;
  27403. case kPlugCategRestoration:
  27404. result = "Restoration";
  27405. break;
  27406. case kPlugCategGenerator:
  27407. result = "Tone generation";
  27408. break;
  27409. default:
  27410. break;
  27411. }
  27412. return result;
  27413. }
  27414. float VSTPluginInstance::getParameter (int index)
  27415. {
  27416. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  27417. {
  27418. try
  27419. {
  27420. const ScopedLock sl (lock);
  27421. return effect->getParameter (effect, index);
  27422. }
  27423. catch (...)
  27424. {
  27425. }
  27426. }
  27427. return 0.0f;
  27428. }
  27429. void VSTPluginInstance::setParameter (int index, float newValue)
  27430. {
  27431. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  27432. {
  27433. try
  27434. {
  27435. const ScopedLock sl (lock);
  27436. if (effect->getParameter (effect, index) != newValue)
  27437. effect->setParameter (effect, index, newValue);
  27438. }
  27439. catch (...)
  27440. {
  27441. }
  27442. }
  27443. }
  27444. const String VSTPluginInstance::getParameterName (int index)
  27445. {
  27446. if (effect != 0)
  27447. {
  27448. jassert (index >= 0 && index < effect->numParams);
  27449. char nm [256];
  27450. zerostruct (nm);
  27451. dispatch (effGetParamName, index, 0, nm, 0);
  27452. return String (nm).trim();
  27453. }
  27454. return String::empty;
  27455. }
  27456. const String VSTPluginInstance::getParameterLabel (int index) const
  27457. {
  27458. if (effect != 0)
  27459. {
  27460. jassert (index >= 0 && index < effect->numParams);
  27461. char nm [256];
  27462. zerostruct (nm);
  27463. dispatch (effGetParamLabel, index, 0, nm, 0);
  27464. return String (nm).trim();
  27465. }
  27466. return String::empty;
  27467. }
  27468. const String VSTPluginInstance::getParameterText (int index)
  27469. {
  27470. if (effect != 0)
  27471. {
  27472. jassert (index >= 0 && index < effect->numParams);
  27473. char nm [256];
  27474. zerostruct (nm);
  27475. dispatch (effGetParamDisplay, index, 0, nm, 0);
  27476. return String (nm).trim();
  27477. }
  27478. return String::empty;
  27479. }
  27480. bool VSTPluginInstance::isParameterAutomatable (int index) const
  27481. {
  27482. if (effect != 0)
  27483. {
  27484. jassert (index >= 0 && index < effect->numParams);
  27485. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  27486. }
  27487. return false;
  27488. }
  27489. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  27490. {
  27491. dest.setSize (64 + 4 * getNumParameters());
  27492. dest.fillWith (0);
  27493. getCurrentProgramName().copyToCString ((char*) dest.getData(), 63);
  27494. float* const p = (float*) (((char*) dest.getData()) + 64);
  27495. for (int i = 0; i < getNumParameters(); ++i)
  27496. p[i] = getParameter(i);
  27497. }
  27498. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  27499. {
  27500. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  27501. float* p = (float*) (((char*) m.getData()) + 64);
  27502. for (int i = 0; i < getNumParameters(); ++i)
  27503. setParameter (i, p[i]);
  27504. }
  27505. void VSTPluginInstance::setCurrentProgram (int newIndex)
  27506. {
  27507. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  27508. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  27509. }
  27510. const String VSTPluginInstance::getProgramName (int index)
  27511. {
  27512. if (index == getCurrentProgram())
  27513. {
  27514. return getCurrentProgramName();
  27515. }
  27516. else if (effect != 0)
  27517. {
  27518. char nm [256];
  27519. zerostruct (nm);
  27520. if (dispatch (effGetProgramNameIndexed,
  27521. jlimit (0, getNumPrograms(), index),
  27522. -1, nm, 0) != 0)
  27523. {
  27524. return String (nm).trim();
  27525. }
  27526. }
  27527. return programNames [index];
  27528. }
  27529. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  27530. {
  27531. if (index == getCurrentProgram())
  27532. {
  27533. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  27534. dispatch (effSetProgramName, 0, 0, (void*) newName.substring (0, 24).toCString(), 0.0f);
  27535. }
  27536. else
  27537. {
  27538. jassertfalse; // xxx not implemented!
  27539. }
  27540. }
  27541. void VSTPluginInstance::updateStoredProgramNames()
  27542. {
  27543. if (effect != 0 && getNumPrograms() > 0)
  27544. {
  27545. char nm [256];
  27546. zerostruct (nm);
  27547. // only do this if the plugin can't use indexed names..
  27548. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  27549. {
  27550. const int oldProgram = getCurrentProgram();
  27551. MemoryBlock oldSettings;
  27552. createTempParameterStore (oldSettings);
  27553. for (int i = 0; i < getNumPrograms(); ++i)
  27554. {
  27555. setCurrentProgram (i);
  27556. getCurrentProgramName(); // (this updates the list)
  27557. }
  27558. setCurrentProgram (oldProgram);
  27559. restoreFromTempParameterStore (oldSettings);
  27560. }
  27561. }
  27562. }
  27563. const String VSTPluginInstance::getCurrentProgramName()
  27564. {
  27565. if (effect != 0)
  27566. {
  27567. char nm [256];
  27568. zerostruct (nm);
  27569. dispatch (effGetProgramName, 0, 0, nm, 0);
  27570. const int index = getCurrentProgram();
  27571. if (programNames[index].isEmpty())
  27572. {
  27573. while (programNames.size() < index)
  27574. programNames.add (String::empty);
  27575. programNames.set (index, String (nm).trim());
  27576. }
  27577. return String (nm).trim();
  27578. }
  27579. return String::empty;
  27580. }
  27581. const String VSTPluginInstance::getInputChannelName (const int index) const
  27582. {
  27583. if (index >= 0 && index < getNumInputChannels())
  27584. {
  27585. VstPinProperties pinProps;
  27586. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  27587. return String (pinProps.label, sizeof (pinProps.label));
  27588. }
  27589. return String::empty;
  27590. }
  27591. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  27592. {
  27593. if (index < 0 || index >= getNumInputChannels())
  27594. return false;
  27595. VstPinProperties pinProps;
  27596. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  27597. return (pinProps.flags & kVstPinIsStereo) != 0;
  27598. return true;
  27599. }
  27600. const String VSTPluginInstance::getOutputChannelName (const int index) const
  27601. {
  27602. if (index >= 0 && index < getNumOutputChannels())
  27603. {
  27604. VstPinProperties pinProps;
  27605. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  27606. return String (pinProps.label, sizeof (pinProps.label));
  27607. }
  27608. return String::empty;
  27609. }
  27610. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  27611. {
  27612. if (index < 0 || index >= getNumOutputChannels())
  27613. return false;
  27614. VstPinProperties pinProps;
  27615. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  27616. return (pinProps.flags & kVstPinIsStereo) != 0;
  27617. return true;
  27618. }
  27619. void VSTPluginInstance::setPower (const bool on)
  27620. {
  27621. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  27622. isPowerOn = on;
  27623. }
  27624. const int defaultMaxSizeMB = 64;
  27625. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  27626. {
  27627. saveToFXBFile (destData, true, defaultMaxSizeMB);
  27628. }
  27629. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  27630. {
  27631. saveToFXBFile (destData, false, defaultMaxSizeMB);
  27632. }
  27633. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  27634. {
  27635. loadFromFXBFile (data, sizeInBytes);
  27636. }
  27637. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  27638. {
  27639. loadFromFXBFile (data, sizeInBytes);
  27640. }
  27641. VSTPluginFormat::VSTPluginFormat()
  27642. {
  27643. }
  27644. VSTPluginFormat::~VSTPluginFormat()
  27645. {
  27646. }
  27647. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  27648. const String& fileOrIdentifier)
  27649. {
  27650. if (! fileMightContainThisPluginType (fileOrIdentifier))
  27651. return;
  27652. PluginDescription desc;
  27653. desc.fileOrIdentifier = fileOrIdentifier;
  27654. desc.uid = 0;
  27655. ScopedPointer <VSTPluginInstance> instance (dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc)));
  27656. if (instance == 0)
  27657. return;
  27658. try
  27659. {
  27660. #if JUCE_MAC
  27661. if (instance->module->resFileId != 0)
  27662. UseResFile (instance->module->resFileId);
  27663. #endif
  27664. instance->fillInPluginDescription (desc);
  27665. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  27666. if (category != kPlugCategShell)
  27667. {
  27668. // Normal plugin...
  27669. results.add (new PluginDescription (desc));
  27670. ++insideVSTCallback;
  27671. instance->dispatch (effOpen, 0, 0, 0, 0);
  27672. --insideVSTCallback;
  27673. }
  27674. else
  27675. {
  27676. // It's a shell plugin, so iterate all the subtypes...
  27677. char shellEffectName [64];
  27678. for (;;)
  27679. {
  27680. zerostruct (shellEffectName);
  27681. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  27682. if (uid == 0)
  27683. {
  27684. break;
  27685. }
  27686. else
  27687. {
  27688. desc.uid = uid;
  27689. desc.name = shellEffectName;
  27690. bool alreadyThere = false;
  27691. for (int i = results.size(); --i >= 0;)
  27692. {
  27693. PluginDescription* const d = results.getUnchecked(i);
  27694. if (d->isDuplicateOf (desc))
  27695. {
  27696. alreadyThere = true;
  27697. break;
  27698. }
  27699. }
  27700. if (! alreadyThere)
  27701. results.add (new PluginDescription (desc));
  27702. }
  27703. }
  27704. }
  27705. }
  27706. catch (...)
  27707. {
  27708. // crashed while loading...
  27709. }
  27710. }
  27711. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  27712. {
  27713. ScopedPointer <VSTPluginInstance> result;
  27714. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  27715. {
  27716. File file (desc.fileOrIdentifier);
  27717. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  27718. file.getParentDirectory().setAsCurrentWorkingDirectory();
  27719. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (file));
  27720. if (module != 0)
  27721. {
  27722. shellUIDToCreate = desc.uid;
  27723. result = new VSTPluginInstance (module);
  27724. if (result->effect != 0)
  27725. {
  27726. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) (VSTPluginInstance*) result;
  27727. result->initialise();
  27728. }
  27729. else
  27730. {
  27731. result = 0;
  27732. }
  27733. }
  27734. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  27735. }
  27736. return result.release();
  27737. }
  27738. bool VSTPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  27739. {
  27740. const File f (fileOrIdentifier);
  27741. #if JUCE_MAC
  27742. if (f.isDirectory() && f.hasFileExtension (".vst"))
  27743. return true;
  27744. #if JUCE_PPC
  27745. FSRef fileRef;
  27746. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  27747. {
  27748. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  27749. if (resFileId != -1)
  27750. {
  27751. const int numEffects = Count1Resources ('aEff');
  27752. CloseResFile (resFileId);
  27753. if (numEffects > 0)
  27754. return true;
  27755. }
  27756. }
  27757. #endif
  27758. return false;
  27759. #elif JUCE_WINDOWS
  27760. return f.existsAsFile()
  27761. && f.hasFileExtension (".dll");
  27762. #elif JUCE_LINUX
  27763. return f.existsAsFile()
  27764. && f.hasFileExtension (".so");
  27765. #endif
  27766. }
  27767. const String VSTPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  27768. {
  27769. return fileOrIdentifier;
  27770. }
  27771. bool VSTPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  27772. {
  27773. return File (desc.fileOrIdentifier).exists();
  27774. }
  27775. const StringArray VSTPluginFormat::searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive)
  27776. {
  27777. StringArray results;
  27778. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  27779. recursiveFileSearch (results, directoriesToSearch [j], recursive);
  27780. return results;
  27781. }
  27782. void VSTPluginFormat::recursiveFileSearch (StringArray& results, const File& dir, const bool recursive)
  27783. {
  27784. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  27785. // .component or .vst directories.
  27786. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  27787. while (iter.next())
  27788. {
  27789. const File f (iter.getFile());
  27790. bool isPlugin = false;
  27791. if (fileMightContainThisPluginType (f.getFullPathName()))
  27792. {
  27793. isPlugin = true;
  27794. results.add (f.getFullPathName());
  27795. }
  27796. if (recursive && (! isPlugin) && f.isDirectory())
  27797. recursiveFileSearch (results, f, true);
  27798. }
  27799. }
  27800. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  27801. {
  27802. #if JUCE_MAC
  27803. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  27804. #elif JUCE_WINDOWS
  27805. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  27806. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  27807. #elif JUCE_LINUX
  27808. return FileSearchPath ("/usr/lib/vst");
  27809. #endif
  27810. }
  27811. END_JUCE_NAMESPACE
  27812. #endif
  27813. #undef log
  27814. #endif
  27815. /*** End of inlined file: juce_VSTPluginFormat.cpp ***/
  27816. /*** End of inlined file: juce_VSTPluginFormat.mm ***/
  27817. /*** Start of inlined file: juce_AudioProcessor.cpp ***/
  27818. BEGIN_JUCE_NAMESPACE
  27819. AudioProcessor::AudioProcessor()
  27820. : playHead (0),
  27821. activeEditor (0),
  27822. sampleRate (0),
  27823. blockSize (0),
  27824. numInputChannels (0),
  27825. numOutputChannels (0),
  27826. latencySamples (0),
  27827. suspended (false),
  27828. nonRealtime (false)
  27829. {
  27830. }
  27831. AudioProcessor::~AudioProcessor()
  27832. {
  27833. // ooh, nasty - the editor should have been deleted before the filter
  27834. // that it refers to is deleted..
  27835. jassert (activeEditor == 0);
  27836. #if JUCE_DEBUG
  27837. // This will fail if you've called beginParameterChangeGesture() for one
  27838. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  27839. jassert (changingParams.countNumberOfSetBits() == 0);
  27840. #endif
  27841. }
  27842. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  27843. {
  27844. playHead = newPlayHead;
  27845. }
  27846. void AudioProcessor::addListener (AudioProcessorListener* const newListener) throw()
  27847. {
  27848. const ScopedLock sl (listenerLock);
  27849. listeners.addIfNotAlreadyThere (newListener);
  27850. }
  27851. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove) throw()
  27852. {
  27853. const ScopedLock sl (listenerLock);
  27854. listeners.removeValue (listenerToRemove);
  27855. }
  27856. void AudioProcessor::setPlayConfigDetails (const int numIns,
  27857. const int numOuts,
  27858. const double sampleRate_,
  27859. const int blockSize_) throw()
  27860. {
  27861. numInputChannels = numIns;
  27862. numOutputChannels = numOuts;
  27863. sampleRate = sampleRate_;
  27864. blockSize = blockSize_;
  27865. }
  27866. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  27867. {
  27868. nonRealtime = nonRealtime_;
  27869. }
  27870. void AudioProcessor::setLatencySamples (const int newLatency)
  27871. {
  27872. if (latencySamples != newLatency)
  27873. {
  27874. latencySamples = newLatency;
  27875. updateHostDisplay();
  27876. }
  27877. }
  27878. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  27879. const float newValue)
  27880. {
  27881. setParameter (parameterIndex, newValue);
  27882. sendParamChangeMessageToListeners (parameterIndex, newValue);
  27883. }
  27884. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  27885. {
  27886. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27887. for (int i = listeners.size(); --i >= 0;)
  27888. {
  27889. AudioProcessorListener* l;
  27890. {
  27891. const ScopedLock sl (listenerLock);
  27892. l = listeners [i];
  27893. }
  27894. if (l != 0)
  27895. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  27896. }
  27897. }
  27898. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  27899. {
  27900. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27901. #if JUCE_DEBUG
  27902. // This means you've called beginParameterChangeGesture twice in succession without a matching
  27903. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  27904. jassert (! changingParams [parameterIndex]);
  27905. changingParams.setBit (parameterIndex);
  27906. #endif
  27907. for (int i = listeners.size(); --i >= 0;)
  27908. {
  27909. AudioProcessorListener* l;
  27910. {
  27911. const ScopedLock sl (listenerLock);
  27912. l = listeners [i];
  27913. }
  27914. if (l != 0)
  27915. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  27916. }
  27917. }
  27918. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  27919. {
  27920. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27921. #if JUCE_DEBUG
  27922. // This means you've called endParameterChangeGesture without having previously called
  27923. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  27924. // calls matched correctly.
  27925. jassert (changingParams [parameterIndex]);
  27926. changingParams.clearBit (parameterIndex);
  27927. #endif
  27928. for (int i = listeners.size(); --i >= 0;)
  27929. {
  27930. AudioProcessorListener* l;
  27931. {
  27932. const ScopedLock sl (listenerLock);
  27933. l = listeners [i];
  27934. }
  27935. if (l != 0)
  27936. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  27937. }
  27938. }
  27939. void AudioProcessor::updateHostDisplay()
  27940. {
  27941. for (int i = listeners.size(); --i >= 0;)
  27942. {
  27943. AudioProcessorListener* l;
  27944. {
  27945. const ScopedLock sl (listenerLock);
  27946. l = listeners [i];
  27947. }
  27948. if (l != 0)
  27949. l->audioProcessorChanged (this);
  27950. }
  27951. }
  27952. bool AudioProcessor::isParameterAutomatable (int /*parameterIndex*/) const
  27953. {
  27954. return true;
  27955. }
  27956. bool AudioProcessor::isMetaParameter (int /*parameterIndex*/) const
  27957. {
  27958. return false;
  27959. }
  27960. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  27961. {
  27962. const ScopedLock sl (callbackLock);
  27963. suspended = shouldBeSuspended;
  27964. }
  27965. void AudioProcessor::reset()
  27966. {
  27967. }
  27968. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  27969. {
  27970. const ScopedLock sl (callbackLock);
  27971. jassert (activeEditor == editor);
  27972. if (activeEditor == editor)
  27973. activeEditor = 0;
  27974. }
  27975. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  27976. {
  27977. if (activeEditor != 0)
  27978. return activeEditor;
  27979. AudioProcessorEditor* const ed = createEditor();
  27980. if (ed != 0)
  27981. {
  27982. // you must give your editor comp a size before returning it..
  27983. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  27984. const ScopedLock sl (callbackLock);
  27985. activeEditor = ed;
  27986. }
  27987. return ed;
  27988. }
  27989. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  27990. {
  27991. getStateInformation (destData);
  27992. }
  27993. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  27994. {
  27995. setStateInformation (data, sizeInBytes);
  27996. }
  27997. // magic number to identify memory blocks that we've stored as XML
  27998. const uint32 magicXmlNumber = 0x21324356;
  27999. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  28000. JUCE_NAMESPACE::MemoryBlock& destData)
  28001. {
  28002. const String xmlString (xml.createDocument (String::empty, true, false));
  28003. const int stringLength = xmlString.getNumBytesAsUTF8();
  28004. destData.setSize (stringLength + 10);
  28005. char* const d = (char*) destData.getData();
  28006. *(uint32*) d = ByteOrder::swapIfBigEndian ((const uint32) magicXmlNumber);
  28007. *(uint32*) (d + 4) = ByteOrder::swapIfBigEndian ((const uint32) stringLength);
  28008. xmlString.copyToUTF8 (d + 8, stringLength + 1);
  28009. }
  28010. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  28011. const int sizeInBytes)
  28012. {
  28013. if (sizeInBytes > 8
  28014. && ByteOrder::littleEndianInt (data) == magicXmlNumber)
  28015. {
  28016. const int stringLength = (int) ByteOrder::littleEndianInt (((const char*) data) + 4);
  28017. if (stringLength > 0)
  28018. {
  28019. XmlDocument doc (String::fromUTF8 (((const char*) data) + 8,
  28020. jmin ((sizeInBytes - 8), stringLength)));
  28021. return doc.getDocumentElement();
  28022. }
  28023. }
  28024. return 0;
  28025. }
  28026. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int)
  28027. {
  28028. }
  28029. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int)
  28030. {
  28031. }
  28032. bool AudioPlayHead::CurrentPositionInfo::operator== (const CurrentPositionInfo& other) const throw()
  28033. {
  28034. return timeInSeconds == other.timeInSeconds
  28035. && ppqPosition == other.ppqPosition
  28036. && editOriginTime == other.editOriginTime
  28037. && ppqPositionOfLastBarStart == other.ppqPositionOfLastBarStart
  28038. && frameRate == other.frameRate
  28039. && isPlaying == other.isPlaying
  28040. && isRecording == other.isRecording
  28041. && bpm == other.bpm
  28042. && timeSigNumerator == other.timeSigNumerator
  28043. && timeSigDenominator == other.timeSigDenominator;
  28044. }
  28045. bool AudioPlayHead::CurrentPositionInfo::operator!= (const CurrentPositionInfo& other) const throw()
  28046. {
  28047. return ! operator== (other);
  28048. }
  28049. void AudioPlayHead::CurrentPositionInfo::resetToDefault()
  28050. {
  28051. zerostruct (*this);
  28052. timeSigNumerator = 4;
  28053. timeSigDenominator = 4;
  28054. bpm = 120;
  28055. }
  28056. END_JUCE_NAMESPACE
  28057. /*** End of inlined file: juce_AudioProcessor.cpp ***/
  28058. /*** Start of inlined file: juce_AudioProcessorEditor.cpp ***/
  28059. BEGIN_JUCE_NAMESPACE
  28060. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  28061. : owner (owner_)
  28062. {
  28063. // the filter must be valid..
  28064. jassert (owner != 0);
  28065. }
  28066. AudioProcessorEditor::~AudioProcessorEditor()
  28067. {
  28068. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  28069. // filter for some reason..
  28070. jassert (owner->getActiveEditor() != this);
  28071. }
  28072. END_JUCE_NAMESPACE
  28073. /*** End of inlined file: juce_AudioProcessorEditor.cpp ***/
  28074. /*** Start of inlined file: juce_AudioProcessorGraph.cpp ***/
  28075. BEGIN_JUCE_NAMESPACE
  28076. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  28077. AudioProcessorGraph::Node::Node (const uint32 id_, AudioProcessor* const processor_)
  28078. : id (id_),
  28079. processor (processor_),
  28080. isPrepared (false)
  28081. {
  28082. jassert (processor_ != 0);
  28083. }
  28084. AudioProcessorGraph::Node::~Node()
  28085. {
  28086. delete processor;
  28087. }
  28088. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  28089. AudioProcessorGraph* const graph)
  28090. {
  28091. if (! isPrepared)
  28092. {
  28093. isPrepared = true;
  28094. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28095. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (processor);
  28096. if (ioProc != 0)
  28097. ioProc->setParentGraph (graph);
  28098. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  28099. processor->getNumOutputChannels(),
  28100. sampleRate, blockSize);
  28101. processor->prepareToPlay (sampleRate, blockSize);
  28102. }
  28103. }
  28104. void AudioProcessorGraph::Node::unprepare()
  28105. {
  28106. if (isPrepared)
  28107. {
  28108. isPrepared = false;
  28109. processor->releaseResources();
  28110. }
  28111. }
  28112. AudioProcessorGraph::AudioProcessorGraph()
  28113. : lastNodeId (0),
  28114. renderingBuffers (1, 1),
  28115. currentAudioOutputBuffer (1, 1)
  28116. {
  28117. }
  28118. AudioProcessorGraph::~AudioProcessorGraph()
  28119. {
  28120. clearRenderingSequence();
  28121. clear();
  28122. }
  28123. const String AudioProcessorGraph::getName() const
  28124. {
  28125. return "Audio Graph";
  28126. }
  28127. void AudioProcessorGraph::clear()
  28128. {
  28129. nodes.clear();
  28130. connections.clear();
  28131. triggerAsyncUpdate();
  28132. }
  28133. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const
  28134. {
  28135. for (int i = nodes.size(); --i >= 0;)
  28136. if (nodes.getUnchecked(i)->id == nodeId)
  28137. return nodes.getUnchecked(i);
  28138. return 0;
  28139. }
  28140. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  28141. uint32 nodeId)
  28142. {
  28143. if (newProcessor == 0)
  28144. {
  28145. jassertfalse;
  28146. return 0;
  28147. }
  28148. if (nodeId == 0)
  28149. {
  28150. nodeId = ++lastNodeId;
  28151. }
  28152. else
  28153. {
  28154. // you can't add a node with an id that already exists in the graph..
  28155. jassert (getNodeForId (nodeId) == 0);
  28156. removeNode (nodeId);
  28157. }
  28158. lastNodeId = nodeId;
  28159. Node* const n = new Node (nodeId, newProcessor);
  28160. nodes.add (n);
  28161. triggerAsyncUpdate();
  28162. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28163. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (n->processor);
  28164. if (ioProc != 0)
  28165. ioProc->setParentGraph (this);
  28166. return n;
  28167. }
  28168. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  28169. {
  28170. disconnectNode (nodeId);
  28171. for (int i = nodes.size(); --i >= 0;)
  28172. {
  28173. if (nodes.getUnchecked(i)->id == nodeId)
  28174. {
  28175. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28176. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (nodes.getUnchecked(i)->processor);
  28177. if (ioProc != 0)
  28178. ioProc->setParentGraph (0);
  28179. nodes.remove (i);
  28180. triggerAsyncUpdate();
  28181. return true;
  28182. }
  28183. }
  28184. return false;
  28185. }
  28186. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  28187. const int sourceChannelIndex,
  28188. const uint32 destNodeId,
  28189. const int destChannelIndex) const
  28190. {
  28191. for (int i = connections.size(); --i >= 0;)
  28192. {
  28193. const Connection* const c = connections.getUnchecked(i);
  28194. if (c->sourceNodeId == sourceNodeId
  28195. && c->destNodeId == destNodeId
  28196. && c->sourceChannelIndex == sourceChannelIndex
  28197. && c->destChannelIndex == destChannelIndex)
  28198. {
  28199. return c;
  28200. }
  28201. }
  28202. return 0;
  28203. }
  28204. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  28205. const uint32 possibleDestNodeId) const
  28206. {
  28207. for (int i = connections.size(); --i >= 0;)
  28208. {
  28209. const Connection* const c = connections.getUnchecked(i);
  28210. if (c->sourceNodeId == possibleSourceNodeId
  28211. && c->destNodeId == possibleDestNodeId)
  28212. {
  28213. return true;
  28214. }
  28215. }
  28216. return false;
  28217. }
  28218. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  28219. const int sourceChannelIndex,
  28220. const uint32 destNodeId,
  28221. const int destChannelIndex) const
  28222. {
  28223. if (sourceChannelIndex < 0
  28224. || destChannelIndex < 0
  28225. || sourceNodeId == destNodeId
  28226. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  28227. return false;
  28228. const Node* const source = getNodeForId (sourceNodeId);
  28229. if (source == 0
  28230. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  28231. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  28232. return false;
  28233. const Node* const dest = getNodeForId (destNodeId);
  28234. if (dest == 0
  28235. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  28236. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  28237. return false;
  28238. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  28239. destNodeId, destChannelIndex) == 0;
  28240. }
  28241. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  28242. const int sourceChannelIndex,
  28243. const uint32 destNodeId,
  28244. const int destChannelIndex)
  28245. {
  28246. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  28247. return false;
  28248. Connection* const c = new Connection();
  28249. c->sourceNodeId = sourceNodeId;
  28250. c->sourceChannelIndex = sourceChannelIndex;
  28251. c->destNodeId = destNodeId;
  28252. c->destChannelIndex = destChannelIndex;
  28253. connections.add (c);
  28254. triggerAsyncUpdate();
  28255. return true;
  28256. }
  28257. void AudioProcessorGraph::removeConnection (const int index)
  28258. {
  28259. connections.remove (index);
  28260. triggerAsyncUpdate();
  28261. }
  28262. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  28263. const uint32 destNodeId, const int destChannelIndex)
  28264. {
  28265. bool doneAnything = false;
  28266. for (int i = connections.size(); --i >= 0;)
  28267. {
  28268. const Connection* const c = connections.getUnchecked(i);
  28269. if (c->sourceNodeId == sourceNodeId
  28270. && c->destNodeId == destNodeId
  28271. && c->sourceChannelIndex == sourceChannelIndex
  28272. && c->destChannelIndex == destChannelIndex)
  28273. {
  28274. removeConnection (i);
  28275. doneAnything = true;
  28276. triggerAsyncUpdate();
  28277. }
  28278. }
  28279. return doneAnything;
  28280. }
  28281. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  28282. {
  28283. bool doneAnything = false;
  28284. for (int i = connections.size(); --i >= 0;)
  28285. {
  28286. const Connection* const c = connections.getUnchecked(i);
  28287. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  28288. {
  28289. removeConnection (i);
  28290. doneAnything = true;
  28291. triggerAsyncUpdate();
  28292. }
  28293. }
  28294. return doneAnything;
  28295. }
  28296. bool AudioProcessorGraph::removeIllegalConnections()
  28297. {
  28298. bool doneAnything = false;
  28299. for (int i = connections.size(); --i >= 0;)
  28300. {
  28301. const Connection* const c = connections.getUnchecked(i);
  28302. const Node* const source = getNodeForId (c->sourceNodeId);
  28303. const Node* const dest = getNodeForId (c->destNodeId);
  28304. if (source == 0 || dest == 0
  28305. || (c->sourceChannelIndex != midiChannelIndex
  28306. && (((unsigned int) c->sourceChannelIndex) >= (unsigned int) source->processor->getNumOutputChannels()))
  28307. || (c->sourceChannelIndex == midiChannelIndex
  28308. && ! source->processor->producesMidi())
  28309. || (c->destChannelIndex != midiChannelIndex
  28310. && (((unsigned int) c->destChannelIndex) >= (unsigned int) dest->processor->getNumInputChannels()))
  28311. || (c->destChannelIndex == midiChannelIndex
  28312. && ! dest->processor->acceptsMidi()))
  28313. {
  28314. removeConnection (i);
  28315. doneAnything = true;
  28316. triggerAsyncUpdate();
  28317. }
  28318. }
  28319. return doneAnything;
  28320. }
  28321. namespace GraphRenderingOps
  28322. {
  28323. class AudioGraphRenderingOp
  28324. {
  28325. public:
  28326. AudioGraphRenderingOp() {}
  28327. virtual ~AudioGraphRenderingOp() {}
  28328. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  28329. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  28330. const int numSamples) = 0;
  28331. juce_UseDebuggingNewOperator
  28332. };
  28333. class ClearChannelOp : public AudioGraphRenderingOp
  28334. {
  28335. public:
  28336. ClearChannelOp (const int channelNum_)
  28337. : channelNum (channelNum_)
  28338. {}
  28339. ~ClearChannelOp() {}
  28340. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  28341. {
  28342. sharedBufferChans.clear (channelNum, 0, numSamples);
  28343. }
  28344. private:
  28345. const int channelNum;
  28346. ClearChannelOp (const ClearChannelOp&);
  28347. ClearChannelOp& operator= (const ClearChannelOp&);
  28348. };
  28349. class CopyChannelOp : public AudioGraphRenderingOp
  28350. {
  28351. public:
  28352. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  28353. : srcChannelNum (srcChannelNum_),
  28354. dstChannelNum (dstChannelNum_)
  28355. {}
  28356. ~CopyChannelOp() {}
  28357. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  28358. {
  28359. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  28360. }
  28361. private:
  28362. const int srcChannelNum, dstChannelNum;
  28363. CopyChannelOp (const CopyChannelOp&);
  28364. CopyChannelOp& operator= (const CopyChannelOp&);
  28365. };
  28366. class AddChannelOp : public AudioGraphRenderingOp
  28367. {
  28368. public:
  28369. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  28370. : srcChannelNum (srcChannelNum_),
  28371. dstChannelNum (dstChannelNum_)
  28372. {}
  28373. ~AddChannelOp() {}
  28374. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  28375. {
  28376. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  28377. }
  28378. private:
  28379. const int srcChannelNum, dstChannelNum;
  28380. AddChannelOp (const AddChannelOp&);
  28381. AddChannelOp& operator= (const AddChannelOp&);
  28382. };
  28383. class ClearMidiBufferOp : public AudioGraphRenderingOp
  28384. {
  28385. public:
  28386. ClearMidiBufferOp (const int bufferNum_)
  28387. : bufferNum (bufferNum_)
  28388. {}
  28389. ~ClearMidiBufferOp() {}
  28390. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  28391. {
  28392. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  28393. }
  28394. private:
  28395. const int bufferNum;
  28396. ClearMidiBufferOp (const ClearMidiBufferOp&);
  28397. ClearMidiBufferOp& operator= (const ClearMidiBufferOp&);
  28398. };
  28399. class CopyMidiBufferOp : public AudioGraphRenderingOp
  28400. {
  28401. public:
  28402. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  28403. : srcBufferNum (srcBufferNum_),
  28404. dstBufferNum (dstBufferNum_)
  28405. {}
  28406. ~CopyMidiBufferOp() {}
  28407. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  28408. {
  28409. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  28410. }
  28411. private:
  28412. const int srcBufferNum, dstBufferNum;
  28413. CopyMidiBufferOp (const CopyMidiBufferOp&);
  28414. CopyMidiBufferOp& operator= (const CopyMidiBufferOp&);
  28415. };
  28416. class AddMidiBufferOp : public AudioGraphRenderingOp
  28417. {
  28418. public:
  28419. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  28420. : srcBufferNum (srcBufferNum_),
  28421. dstBufferNum (dstBufferNum_)
  28422. {}
  28423. ~AddMidiBufferOp() {}
  28424. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  28425. {
  28426. sharedMidiBuffers.getUnchecked (dstBufferNum)
  28427. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  28428. }
  28429. private:
  28430. const int srcBufferNum, dstBufferNum;
  28431. AddMidiBufferOp (const AddMidiBufferOp&);
  28432. AddMidiBufferOp& operator= (const AddMidiBufferOp&);
  28433. };
  28434. class ProcessBufferOp : public AudioGraphRenderingOp
  28435. {
  28436. public:
  28437. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  28438. const Array <int>& audioChannelsToUse_,
  28439. const int totalChans_,
  28440. const int midiBufferToUse_)
  28441. : node (node_),
  28442. processor (node_->processor),
  28443. audioChannelsToUse (audioChannelsToUse_),
  28444. totalChans (jmax (1, totalChans_)),
  28445. midiBufferToUse (midiBufferToUse_)
  28446. {
  28447. channels.calloc (totalChans);
  28448. while (audioChannelsToUse.size() < totalChans)
  28449. audioChannelsToUse.add (0);
  28450. }
  28451. ~ProcessBufferOp()
  28452. {
  28453. }
  28454. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  28455. {
  28456. for (int i = totalChans; --i >= 0;)
  28457. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  28458. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  28459. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  28460. }
  28461. const AudioProcessorGraph::Node::Ptr node;
  28462. AudioProcessor* const processor;
  28463. private:
  28464. Array <int> audioChannelsToUse;
  28465. HeapBlock <float*> channels;
  28466. int totalChans;
  28467. int midiBufferToUse;
  28468. ProcessBufferOp (const ProcessBufferOp&);
  28469. ProcessBufferOp& operator= (const ProcessBufferOp&);
  28470. };
  28471. /** Used to calculate the correct sequence of rendering ops needed, based on
  28472. the best re-use of shared buffers at each stage.
  28473. */
  28474. class RenderingOpSequenceCalculator
  28475. {
  28476. public:
  28477. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  28478. const Array<void*>& orderedNodes_,
  28479. Array<void*>& renderingOps)
  28480. : graph (graph_),
  28481. orderedNodes (orderedNodes_)
  28482. {
  28483. nodeIds.add (-2); // first buffer is read-only zeros
  28484. channels.add (0);
  28485. midiNodeIds.add (-2);
  28486. for (int i = 0; i < orderedNodes.size(); ++i)
  28487. {
  28488. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  28489. renderingOps, i);
  28490. markAnyUnusedBuffersAsFree (i);
  28491. }
  28492. }
  28493. int getNumBuffersNeeded() const { return nodeIds.size(); }
  28494. int getNumMidiBuffersNeeded() const { return midiNodeIds.size(); }
  28495. juce_UseDebuggingNewOperator
  28496. private:
  28497. AudioProcessorGraph& graph;
  28498. const Array<void*>& orderedNodes;
  28499. Array <int> nodeIds, channels, midiNodeIds;
  28500. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  28501. Array<void*>& renderingOps,
  28502. const int ourRenderingIndex)
  28503. {
  28504. const int numIns = node->processor->getNumInputChannels();
  28505. const int numOuts = node->processor->getNumOutputChannels();
  28506. const int totalChans = jmax (numIns, numOuts);
  28507. Array <int> audioChannelsToUse;
  28508. int midiBufferToUse = -1;
  28509. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  28510. {
  28511. // get a list of all the inputs to this node
  28512. Array <int> sourceNodes, sourceOutputChans;
  28513. for (int i = graph.getNumConnections(); --i >= 0;)
  28514. {
  28515. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  28516. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  28517. {
  28518. sourceNodes.add (c->sourceNodeId);
  28519. sourceOutputChans.add (c->sourceChannelIndex);
  28520. }
  28521. }
  28522. int bufIndex = -1;
  28523. if (sourceNodes.size() == 0)
  28524. {
  28525. // unconnected input channel
  28526. if (inputChan >= numOuts)
  28527. {
  28528. bufIndex = getReadOnlyEmptyBuffer();
  28529. jassert (bufIndex >= 0);
  28530. }
  28531. else
  28532. {
  28533. bufIndex = getFreeBuffer (false);
  28534. renderingOps.add (new ClearChannelOp (bufIndex));
  28535. }
  28536. }
  28537. else if (sourceNodes.size() == 1)
  28538. {
  28539. // channel with a straightforward single input..
  28540. const int srcNode = sourceNodes.getUnchecked(0);
  28541. const int srcChan = sourceOutputChans.getUnchecked(0);
  28542. bufIndex = getBufferContaining (srcNode, srcChan);
  28543. if (bufIndex < 0)
  28544. {
  28545. // if not found, this is probably a feedback loop
  28546. bufIndex = getReadOnlyEmptyBuffer();
  28547. jassert (bufIndex >= 0);
  28548. }
  28549. if (inputChan < numOuts
  28550. && isBufferNeededLater (ourRenderingIndex,
  28551. inputChan,
  28552. srcNode, srcChan))
  28553. {
  28554. // can't mess up this channel because it's needed later by another node, so we
  28555. // need to use a copy of it..
  28556. const int newFreeBuffer = getFreeBuffer (false);
  28557. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  28558. bufIndex = newFreeBuffer;
  28559. }
  28560. }
  28561. else
  28562. {
  28563. // channel with a mix of several inputs..
  28564. // try to find a re-usable channel from our inputs..
  28565. int reusableInputIndex = -1;
  28566. for (int i = 0; i < sourceNodes.size(); ++i)
  28567. {
  28568. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  28569. sourceOutputChans.getUnchecked(i));
  28570. if (sourceBufIndex >= 0
  28571. && ! isBufferNeededLater (ourRenderingIndex,
  28572. inputChan,
  28573. sourceNodes.getUnchecked(i),
  28574. sourceOutputChans.getUnchecked(i)))
  28575. {
  28576. // we've found one of our input chans that can be re-used..
  28577. reusableInputIndex = i;
  28578. bufIndex = sourceBufIndex;
  28579. break;
  28580. }
  28581. }
  28582. if (reusableInputIndex < 0)
  28583. {
  28584. // can't re-use any of our input chans, so get a new one and copy everything into it..
  28585. bufIndex = getFreeBuffer (false);
  28586. jassert (bufIndex != 0);
  28587. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  28588. sourceOutputChans.getUnchecked (0));
  28589. if (srcIndex < 0)
  28590. {
  28591. // if not found, this is probably a feedback loop
  28592. renderingOps.add (new ClearChannelOp (bufIndex));
  28593. }
  28594. else
  28595. {
  28596. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  28597. }
  28598. reusableInputIndex = 0;
  28599. }
  28600. for (int j = 0; j < sourceNodes.size(); ++j)
  28601. {
  28602. if (j != reusableInputIndex)
  28603. {
  28604. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  28605. sourceOutputChans.getUnchecked(j));
  28606. if (srcIndex >= 0)
  28607. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  28608. }
  28609. }
  28610. }
  28611. jassert (bufIndex >= 0);
  28612. audioChannelsToUse.add (bufIndex);
  28613. if (inputChan < numOuts)
  28614. markBufferAsContaining (bufIndex, node->id, inputChan);
  28615. }
  28616. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  28617. {
  28618. const int bufIndex = getFreeBuffer (false);
  28619. jassert (bufIndex != 0);
  28620. audioChannelsToUse.add (bufIndex);
  28621. markBufferAsContaining (bufIndex, node->id, outputChan);
  28622. }
  28623. // Now the same thing for midi..
  28624. Array <int> midiSourceNodes;
  28625. for (int i = graph.getNumConnections(); --i >= 0;)
  28626. {
  28627. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  28628. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  28629. midiSourceNodes.add (c->sourceNodeId);
  28630. }
  28631. if (midiSourceNodes.size() == 0)
  28632. {
  28633. // No midi inputs..
  28634. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  28635. if (node->processor->acceptsMidi() || node->processor->producesMidi())
  28636. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  28637. }
  28638. else if (midiSourceNodes.size() == 1)
  28639. {
  28640. // One midi input..
  28641. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  28642. AudioProcessorGraph::midiChannelIndex);
  28643. if (midiBufferToUse >= 0)
  28644. {
  28645. if (isBufferNeededLater (ourRenderingIndex,
  28646. AudioProcessorGraph::midiChannelIndex,
  28647. midiSourceNodes.getUnchecked(0),
  28648. AudioProcessorGraph::midiChannelIndex))
  28649. {
  28650. // can't mess up this channel because it's needed later by another node, so we
  28651. // need to use a copy of it..
  28652. const int newFreeBuffer = getFreeBuffer (true);
  28653. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  28654. midiBufferToUse = newFreeBuffer;
  28655. }
  28656. }
  28657. else
  28658. {
  28659. // probably a feedback loop, so just use an empty one..
  28660. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  28661. }
  28662. }
  28663. else
  28664. {
  28665. // More than one midi input being mixed..
  28666. int reusableInputIndex = -1;
  28667. for (int i = 0; i < midiSourceNodes.size(); ++i)
  28668. {
  28669. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  28670. AudioProcessorGraph::midiChannelIndex);
  28671. if (sourceBufIndex >= 0
  28672. && ! isBufferNeededLater (ourRenderingIndex,
  28673. AudioProcessorGraph::midiChannelIndex,
  28674. midiSourceNodes.getUnchecked(i),
  28675. AudioProcessorGraph::midiChannelIndex))
  28676. {
  28677. // we've found one of our input buffers that can be re-used..
  28678. reusableInputIndex = i;
  28679. midiBufferToUse = sourceBufIndex;
  28680. break;
  28681. }
  28682. }
  28683. if (reusableInputIndex < 0)
  28684. {
  28685. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  28686. midiBufferToUse = getFreeBuffer (true);
  28687. jassert (midiBufferToUse >= 0);
  28688. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  28689. AudioProcessorGraph::midiChannelIndex);
  28690. if (srcIndex >= 0)
  28691. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  28692. else
  28693. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  28694. reusableInputIndex = 0;
  28695. }
  28696. for (int j = 0; j < midiSourceNodes.size(); ++j)
  28697. {
  28698. if (j != reusableInputIndex)
  28699. {
  28700. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  28701. AudioProcessorGraph::midiChannelIndex);
  28702. if (srcIndex >= 0)
  28703. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  28704. }
  28705. }
  28706. }
  28707. if (node->processor->producesMidi())
  28708. markBufferAsContaining (midiBufferToUse, node->id,
  28709. AudioProcessorGraph::midiChannelIndex);
  28710. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  28711. totalChans, midiBufferToUse));
  28712. }
  28713. int getFreeBuffer (const bool forMidi)
  28714. {
  28715. if (forMidi)
  28716. {
  28717. for (int i = 1; i < midiNodeIds.size(); ++i)
  28718. if (midiNodeIds.getUnchecked(i) < 0)
  28719. return i;
  28720. midiNodeIds.add (-1);
  28721. return midiNodeIds.size() - 1;
  28722. }
  28723. else
  28724. {
  28725. for (int i = 1; i < nodeIds.size(); ++i)
  28726. if (nodeIds.getUnchecked(i) < 0)
  28727. return i;
  28728. nodeIds.add (-1);
  28729. channels.add (0);
  28730. return nodeIds.size() - 1;
  28731. }
  28732. }
  28733. int getReadOnlyEmptyBuffer() const
  28734. {
  28735. return 0;
  28736. }
  28737. int getBufferContaining (const int nodeId, const int outputChannel) const
  28738. {
  28739. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  28740. {
  28741. for (int i = midiNodeIds.size(); --i >= 0;)
  28742. if (midiNodeIds.getUnchecked(i) == nodeId)
  28743. return i;
  28744. }
  28745. else
  28746. {
  28747. for (int i = nodeIds.size(); --i >= 0;)
  28748. if (nodeIds.getUnchecked(i) == nodeId
  28749. && channels.getUnchecked(i) == outputChannel)
  28750. return i;
  28751. }
  28752. return -1;
  28753. }
  28754. void markAnyUnusedBuffersAsFree (const int stepIndex)
  28755. {
  28756. int i;
  28757. for (i = 0; i < nodeIds.size(); ++i)
  28758. {
  28759. if (nodeIds.getUnchecked(i) >= 0
  28760. && ! isBufferNeededLater (stepIndex, -1,
  28761. nodeIds.getUnchecked(i),
  28762. channels.getUnchecked(i)))
  28763. {
  28764. nodeIds.set (i, -1);
  28765. }
  28766. }
  28767. for (i = 0; i < midiNodeIds.size(); ++i)
  28768. {
  28769. if (midiNodeIds.getUnchecked(i) >= 0
  28770. && ! isBufferNeededLater (stepIndex, -1,
  28771. midiNodeIds.getUnchecked(i),
  28772. AudioProcessorGraph::midiChannelIndex))
  28773. {
  28774. midiNodeIds.set (i, -1);
  28775. }
  28776. }
  28777. }
  28778. bool isBufferNeededLater (int stepIndexToSearchFrom,
  28779. int inputChannelOfIndexToIgnore,
  28780. const int nodeId,
  28781. const int outputChanIndex) const
  28782. {
  28783. while (stepIndexToSearchFrom < orderedNodes.size())
  28784. {
  28785. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  28786. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  28787. {
  28788. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  28789. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  28790. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  28791. return true;
  28792. }
  28793. else
  28794. {
  28795. for (int i = 0; i < node->processor->getNumInputChannels(); ++i)
  28796. if (i != inputChannelOfIndexToIgnore
  28797. && graph.getConnectionBetween (nodeId, outputChanIndex,
  28798. node->id, i) != 0)
  28799. return true;
  28800. }
  28801. inputChannelOfIndexToIgnore = -1;
  28802. ++stepIndexToSearchFrom;
  28803. }
  28804. return false;
  28805. }
  28806. void markBufferAsContaining (int bufferNum, int nodeId, int outputIndex)
  28807. {
  28808. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  28809. {
  28810. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  28811. midiNodeIds.set (bufferNum, nodeId);
  28812. }
  28813. else
  28814. {
  28815. jassert (bufferNum >= 0 && bufferNum < nodeIds.size());
  28816. nodeIds.set (bufferNum, nodeId);
  28817. channels.set (bufferNum, outputIndex);
  28818. }
  28819. }
  28820. RenderingOpSequenceCalculator (const RenderingOpSequenceCalculator&);
  28821. RenderingOpSequenceCalculator& operator= (const RenderingOpSequenceCalculator&);
  28822. };
  28823. }
  28824. void AudioProcessorGraph::clearRenderingSequence()
  28825. {
  28826. const ScopedLock sl (renderLock);
  28827. for (int i = renderingOps.size(); --i >= 0;)
  28828. {
  28829. GraphRenderingOps::AudioGraphRenderingOp* const r
  28830. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  28831. renderingOps.remove (i);
  28832. delete r;
  28833. }
  28834. }
  28835. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  28836. const uint32 possibleDestinationId,
  28837. const int recursionCheck) const
  28838. {
  28839. if (recursionCheck > 0)
  28840. {
  28841. for (int i = connections.size(); --i >= 0;)
  28842. {
  28843. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  28844. if (c->destNodeId == possibleDestinationId
  28845. && (c->sourceNodeId == possibleInputId
  28846. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  28847. return true;
  28848. }
  28849. }
  28850. return false;
  28851. }
  28852. void AudioProcessorGraph::buildRenderingSequence()
  28853. {
  28854. Array<void*> newRenderingOps;
  28855. int numRenderingBuffersNeeded = 2;
  28856. int numMidiBuffersNeeded = 1;
  28857. {
  28858. MessageManagerLock mml;
  28859. Array<void*> orderedNodes;
  28860. int i;
  28861. for (i = 0; i < nodes.size(); ++i)
  28862. {
  28863. Node* const node = nodes.getUnchecked(i);
  28864. node->prepare (getSampleRate(), getBlockSize(), this);
  28865. int j = 0;
  28866. for (; j < orderedNodes.size(); ++j)
  28867. if (isAnInputTo (node->id,
  28868. ((Node*) orderedNodes.getUnchecked (j))->id,
  28869. nodes.size() + 1))
  28870. break;
  28871. orderedNodes.insert (j, node);
  28872. }
  28873. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  28874. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  28875. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  28876. }
  28877. Array<void*> oldRenderingOps (renderingOps);
  28878. {
  28879. // swap over to the new rendering sequence..
  28880. const ScopedLock sl (renderLock);
  28881. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  28882. renderingBuffers.clear();
  28883. for (int i = midiBuffers.size(); --i >= 0;)
  28884. midiBuffers.getUnchecked(i)->clear();
  28885. while (midiBuffers.size() < numMidiBuffersNeeded)
  28886. midiBuffers.add (new MidiBuffer());
  28887. renderingOps = newRenderingOps;
  28888. }
  28889. for (int i = oldRenderingOps.size(); --i >= 0;)
  28890. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  28891. }
  28892. void AudioProcessorGraph::handleAsyncUpdate()
  28893. {
  28894. buildRenderingSequence();
  28895. }
  28896. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  28897. {
  28898. currentAudioInputBuffer = 0;
  28899. currentAudioOutputBuffer.setSize (jmax (1, getNumOutputChannels()), estimatedSamplesPerBlock);
  28900. currentMidiInputBuffer = 0;
  28901. currentMidiOutputBuffer.clear();
  28902. clearRenderingSequence();
  28903. buildRenderingSequence();
  28904. }
  28905. void AudioProcessorGraph::releaseResources()
  28906. {
  28907. for (int i = 0; i < nodes.size(); ++i)
  28908. nodes.getUnchecked(i)->unprepare();
  28909. renderingBuffers.setSize (1, 1);
  28910. midiBuffers.clear();
  28911. currentAudioInputBuffer = 0;
  28912. currentAudioOutputBuffer.setSize (1, 1);
  28913. currentMidiInputBuffer = 0;
  28914. currentMidiOutputBuffer.clear();
  28915. }
  28916. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  28917. {
  28918. const int numSamples = buffer.getNumSamples();
  28919. const ScopedLock sl (renderLock);
  28920. currentAudioInputBuffer = &buffer;
  28921. currentAudioOutputBuffer.setSize (jmax (1, buffer.getNumChannels()), numSamples);
  28922. currentAudioOutputBuffer.clear();
  28923. currentMidiInputBuffer = &midiMessages;
  28924. currentMidiOutputBuffer.clear();
  28925. int i;
  28926. for (i = 0; i < renderingOps.size(); ++i)
  28927. {
  28928. GraphRenderingOps::AudioGraphRenderingOp* const op
  28929. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  28930. op->perform (renderingBuffers, midiBuffers, numSamples);
  28931. }
  28932. for (i = 0; i < buffer.getNumChannels(); ++i)
  28933. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  28934. midiMessages.clear();
  28935. midiMessages.addEvents (currentMidiOutputBuffer, 0, buffer.getNumSamples(), 0);
  28936. }
  28937. const String AudioProcessorGraph::getInputChannelName (const int channelIndex) const
  28938. {
  28939. return "Input " + String (channelIndex + 1);
  28940. }
  28941. const String AudioProcessorGraph::getOutputChannelName (const int channelIndex) const
  28942. {
  28943. return "Output " + String (channelIndex + 1);
  28944. }
  28945. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const
  28946. {
  28947. return true;
  28948. }
  28949. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const
  28950. {
  28951. return true;
  28952. }
  28953. bool AudioProcessorGraph::acceptsMidi() const
  28954. {
  28955. return true;
  28956. }
  28957. bool AudioProcessorGraph::producesMidi() const
  28958. {
  28959. return true;
  28960. }
  28961. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/)
  28962. {
  28963. }
  28964. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/)
  28965. {
  28966. }
  28967. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  28968. : type (type_),
  28969. graph (0)
  28970. {
  28971. }
  28972. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  28973. {
  28974. }
  28975. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  28976. {
  28977. switch (type)
  28978. {
  28979. case audioOutputNode:
  28980. return "Audio Output";
  28981. case audioInputNode:
  28982. return "Audio Input";
  28983. case midiOutputNode:
  28984. return "Midi Output";
  28985. case midiInputNode:
  28986. return "Midi Input";
  28987. default:
  28988. break;
  28989. }
  28990. return String::empty;
  28991. }
  28992. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  28993. {
  28994. d.name = getName();
  28995. d.uid = d.name.hashCode();
  28996. d.category = "I/O devices";
  28997. d.pluginFormatName = "Internal";
  28998. d.manufacturerName = "Raw Material Software";
  28999. d.version = "1.0";
  29000. d.isInstrument = false;
  29001. d.numInputChannels = getNumInputChannels();
  29002. if (type == audioOutputNode && graph != 0)
  29003. d.numInputChannels = graph->getNumInputChannels();
  29004. d.numOutputChannels = getNumOutputChannels();
  29005. if (type == audioInputNode && graph != 0)
  29006. d.numOutputChannels = graph->getNumOutputChannels();
  29007. }
  29008. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  29009. {
  29010. jassert (graph != 0);
  29011. }
  29012. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  29013. {
  29014. }
  29015. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  29016. MidiBuffer& midiMessages)
  29017. {
  29018. jassert (graph != 0);
  29019. switch (type)
  29020. {
  29021. case audioOutputNode:
  29022. {
  29023. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  29024. buffer.getNumChannels()); --i >= 0;)
  29025. {
  29026. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  29027. }
  29028. break;
  29029. }
  29030. case audioInputNode:
  29031. {
  29032. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  29033. buffer.getNumChannels()); --i >= 0;)
  29034. {
  29035. buffer.copyFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  29036. }
  29037. break;
  29038. }
  29039. case midiOutputNode:
  29040. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  29041. break;
  29042. case midiInputNode:
  29043. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  29044. break;
  29045. default:
  29046. break;
  29047. }
  29048. }
  29049. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  29050. {
  29051. return type == midiOutputNode;
  29052. }
  29053. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  29054. {
  29055. return type == midiInputNode;
  29056. }
  29057. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (const int channelIndex) const
  29058. {
  29059. switch (type)
  29060. {
  29061. case audioOutputNode:
  29062. return "Output " + String (channelIndex + 1);
  29063. case midiOutputNode:
  29064. return "Midi Output";
  29065. default:
  29066. break;
  29067. }
  29068. return String::empty;
  29069. }
  29070. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (const int channelIndex) const
  29071. {
  29072. switch (type)
  29073. {
  29074. case audioInputNode:
  29075. return "Input " + String (channelIndex + 1);
  29076. case midiInputNode:
  29077. return "Midi Input";
  29078. default:
  29079. break;
  29080. }
  29081. return String::empty;
  29082. }
  29083. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  29084. {
  29085. return type == audioInputNode || type == audioOutputNode;
  29086. }
  29087. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  29088. {
  29089. return isInputChannelStereoPair (index);
  29090. }
  29091. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const
  29092. {
  29093. return type == audioInputNode || type == midiInputNode;
  29094. }
  29095. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const
  29096. {
  29097. return type == audioOutputNode || type == midiOutputNode;
  29098. }
  29099. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor()
  29100. {
  29101. return 0;
  29102. }
  29103. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  29104. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  29105. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  29106. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  29107. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  29108. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  29109. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  29110. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  29111. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  29112. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  29113. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  29114. {
  29115. }
  29116. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  29117. {
  29118. }
  29119. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph)
  29120. {
  29121. graph = newGraph;
  29122. if (graph != 0)
  29123. {
  29124. setPlayConfigDetails (type == audioOutputNode ? graph->getNumOutputChannels() : 0,
  29125. type == audioInputNode ? graph->getNumInputChannels() : 0,
  29126. getSampleRate(),
  29127. getBlockSize());
  29128. updateHostDisplay();
  29129. }
  29130. }
  29131. END_JUCE_NAMESPACE
  29132. /*** End of inlined file: juce_AudioProcessorGraph.cpp ***/
  29133. /*** Start of inlined file: juce_AudioProcessorPlayer.cpp ***/
  29134. BEGIN_JUCE_NAMESPACE
  29135. AudioProcessorPlayer::AudioProcessorPlayer()
  29136. : processor (0),
  29137. sampleRate (0),
  29138. blockSize (0),
  29139. isPrepared (false),
  29140. numInputChans (0),
  29141. numOutputChans (0),
  29142. tempBuffer (1, 1)
  29143. {
  29144. }
  29145. AudioProcessorPlayer::~AudioProcessorPlayer()
  29146. {
  29147. setProcessor (0);
  29148. }
  29149. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  29150. {
  29151. if (processor != processorToPlay)
  29152. {
  29153. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  29154. {
  29155. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  29156. sampleRate, blockSize);
  29157. processorToPlay->prepareToPlay (sampleRate, blockSize);
  29158. }
  29159. AudioProcessor* oldOne;
  29160. {
  29161. const ScopedLock sl (lock);
  29162. oldOne = isPrepared ? processor : 0;
  29163. processor = processorToPlay;
  29164. isPrepared = true;
  29165. }
  29166. if (oldOne != 0)
  29167. oldOne->releaseResources();
  29168. }
  29169. }
  29170. void AudioProcessorPlayer::audioDeviceIOCallback (const float** const inputChannelData,
  29171. const int numInputChannels,
  29172. float** const outputChannelData,
  29173. const int numOutputChannels,
  29174. const int numSamples)
  29175. {
  29176. // these should have been prepared by audioDeviceAboutToStart()...
  29177. jassert (sampleRate > 0 && blockSize > 0);
  29178. incomingMidi.clear();
  29179. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  29180. int i, totalNumChans = 0;
  29181. if (numInputChannels > numOutputChannels)
  29182. {
  29183. // if there aren't enough output channels for the number of
  29184. // inputs, we need to create some temporary extra ones (can't
  29185. // use the input data in case it gets written to)
  29186. tempBuffer.setSize (numInputChannels - numOutputChannels, numSamples,
  29187. false, false, true);
  29188. for (i = 0; i < numOutputChannels; ++i)
  29189. {
  29190. channels[totalNumChans] = outputChannelData[i];
  29191. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29192. ++totalNumChans;
  29193. }
  29194. for (i = numOutputChannels; i < numInputChannels; ++i)
  29195. {
  29196. channels[totalNumChans] = tempBuffer.getSampleData (i - numOutputChannels, 0);
  29197. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29198. ++totalNumChans;
  29199. }
  29200. }
  29201. else
  29202. {
  29203. for (i = 0; i < numInputChannels; ++i)
  29204. {
  29205. channels[totalNumChans] = outputChannelData[i];
  29206. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29207. ++totalNumChans;
  29208. }
  29209. for (i = numInputChannels; i < numOutputChannels; ++i)
  29210. {
  29211. channels[totalNumChans] = outputChannelData[i];
  29212. zeromem (channels[totalNumChans], sizeof (float) * numSamples);
  29213. ++totalNumChans;
  29214. }
  29215. }
  29216. AudioSampleBuffer buffer (channels, totalNumChans, numSamples);
  29217. const ScopedLock sl (lock);
  29218. if (processor != 0)
  29219. {
  29220. const ScopedLock sl (processor->getCallbackLock());
  29221. if (processor->isSuspended())
  29222. {
  29223. for (i = 0; i < numOutputChannels; ++i)
  29224. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  29225. }
  29226. else
  29227. {
  29228. processor->processBlock (buffer, incomingMidi);
  29229. }
  29230. }
  29231. }
  29232. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  29233. {
  29234. const ScopedLock sl (lock);
  29235. sampleRate = device->getCurrentSampleRate();
  29236. blockSize = device->getCurrentBufferSizeSamples();
  29237. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  29238. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  29239. messageCollector.reset (sampleRate);
  29240. zeromem (channels, sizeof (channels));
  29241. if (processor != 0)
  29242. {
  29243. if (isPrepared)
  29244. processor->releaseResources();
  29245. AudioProcessor* const oldProcessor = processor;
  29246. setProcessor (0);
  29247. setProcessor (oldProcessor);
  29248. }
  29249. }
  29250. void AudioProcessorPlayer::audioDeviceStopped()
  29251. {
  29252. const ScopedLock sl (lock);
  29253. if (processor != 0 && isPrepared)
  29254. processor->releaseResources();
  29255. sampleRate = 0.0;
  29256. blockSize = 0;
  29257. isPrepared = false;
  29258. tempBuffer.setSize (1, 1);
  29259. }
  29260. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  29261. {
  29262. messageCollector.addMessageToQueue (message);
  29263. }
  29264. END_JUCE_NAMESPACE
  29265. /*** End of inlined file: juce_AudioProcessorPlayer.cpp ***/
  29266. /*** Start of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  29267. BEGIN_JUCE_NAMESPACE
  29268. class ProcessorParameterPropertyComp : public PropertyComponent,
  29269. public AudioProcessorListener,
  29270. public AsyncUpdater
  29271. {
  29272. public:
  29273. ProcessorParameterPropertyComp (const String& name,
  29274. AudioProcessor* const owner_,
  29275. const int index_)
  29276. : PropertyComponent (name),
  29277. owner (owner_),
  29278. index (index_)
  29279. {
  29280. addAndMakeVisible (slider = new ParamSlider (owner_, index_));
  29281. owner_->addListener (this);
  29282. }
  29283. ~ProcessorParameterPropertyComp()
  29284. {
  29285. owner->removeListener (this);
  29286. deleteAllChildren();
  29287. }
  29288. void refresh()
  29289. {
  29290. slider->setValue (owner->getParameter (index), false);
  29291. }
  29292. void audioProcessorChanged (AudioProcessor*) {}
  29293. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  29294. {
  29295. if (parameterIndex == index)
  29296. triggerAsyncUpdate();
  29297. }
  29298. void handleAsyncUpdate()
  29299. {
  29300. refresh();
  29301. }
  29302. juce_UseDebuggingNewOperator
  29303. private:
  29304. AudioProcessor* const owner;
  29305. const int index;
  29306. Slider* slider;
  29307. class ParamSlider : public Slider
  29308. {
  29309. public:
  29310. ParamSlider (AudioProcessor* const owner_, const int index_)
  29311. : Slider (String::empty),
  29312. owner (owner_),
  29313. index (index_)
  29314. {
  29315. setRange (0.0, 1.0, 0.0);
  29316. setSliderStyle (Slider::LinearBar);
  29317. setTextBoxIsEditable (false);
  29318. setScrollWheelEnabled (false);
  29319. }
  29320. ~ParamSlider()
  29321. {
  29322. }
  29323. void valueChanged()
  29324. {
  29325. const float newVal = (float) getValue();
  29326. if (owner->getParameter (index) != newVal)
  29327. owner->setParameter (index, newVal);
  29328. }
  29329. const String getTextFromValue (double /*value*/)
  29330. {
  29331. return owner->getParameterText (index);
  29332. }
  29333. juce_UseDebuggingNewOperator
  29334. private:
  29335. AudioProcessor* const owner;
  29336. const int index;
  29337. ParamSlider (const ParamSlider&);
  29338. ParamSlider& operator= (const ParamSlider&);
  29339. };
  29340. ProcessorParameterPropertyComp (const ProcessorParameterPropertyComp&);
  29341. ProcessorParameterPropertyComp& operator= (const ProcessorParameterPropertyComp&);
  29342. };
  29343. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner_)
  29344. : AudioProcessorEditor (owner_)
  29345. {
  29346. setOpaque (true);
  29347. addAndMakeVisible (panel = new PropertyPanel());
  29348. Array <PropertyComponent*> params;
  29349. const int numParams = owner_->getNumParameters();
  29350. int totalHeight = 0;
  29351. for (int i = 0; i < numParams; ++i)
  29352. {
  29353. String name (owner_->getParameterName (i));
  29354. if (name.trim().isEmpty())
  29355. name = "Unnamed";
  29356. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, owner_, i);
  29357. params.add (pc);
  29358. totalHeight += pc->getPreferredHeight();
  29359. }
  29360. panel->addProperties (params);
  29361. setSize (400, jlimit (25, 400, totalHeight));
  29362. }
  29363. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  29364. {
  29365. deleteAllChildren();
  29366. }
  29367. void GenericAudioProcessorEditor::paint (Graphics& g)
  29368. {
  29369. g.fillAll (Colours::white);
  29370. }
  29371. void GenericAudioProcessorEditor::resized()
  29372. {
  29373. panel->setSize (getWidth(), getHeight());
  29374. }
  29375. END_JUCE_NAMESPACE
  29376. /*** End of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  29377. /*** Start of inlined file: juce_Sampler.cpp ***/
  29378. BEGIN_JUCE_NAMESPACE
  29379. SamplerSound::SamplerSound (const String& name_,
  29380. AudioFormatReader& source,
  29381. const BigInteger& midiNotes_,
  29382. const int midiNoteForNormalPitch,
  29383. const double attackTimeSecs,
  29384. const double releaseTimeSecs,
  29385. const double maxSampleLengthSeconds)
  29386. : name (name_),
  29387. midiNotes (midiNotes_),
  29388. midiRootNote (midiNoteForNormalPitch)
  29389. {
  29390. sourceSampleRate = source.sampleRate;
  29391. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  29392. {
  29393. length = 0;
  29394. attackSamples = 0;
  29395. releaseSamples = 0;
  29396. }
  29397. else
  29398. {
  29399. length = jmin ((int) source.lengthInSamples,
  29400. (int) (maxSampleLengthSeconds * sourceSampleRate));
  29401. data = new AudioSampleBuffer (jmin (2, (int) source.numChannels), length + 4);
  29402. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  29403. attackSamples = roundToInt (attackTimeSecs * sourceSampleRate);
  29404. releaseSamples = roundToInt (releaseTimeSecs * sourceSampleRate);
  29405. }
  29406. }
  29407. SamplerSound::~SamplerSound()
  29408. {
  29409. }
  29410. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  29411. {
  29412. return midiNotes [midiNoteNumber];
  29413. }
  29414. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  29415. {
  29416. return true;
  29417. }
  29418. SamplerVoice::SamplerVoice()
  29419. : pitchRatio (0.0),
  29420. sourceSamplePosition (0.0),
  29421. lgain (0.0f),
  29422. rgain (0.0f),
  29423. isInAttack (false),
  29424. isInRelease (false)
  29425. {
  29426. }
  29427. SamplerVoice::~SamplerVoice()
  29428. {
  29429. }
  29430. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  29431. {
  29432. return dynamic_cast <const SamplerSound*> (sound) != 0;
  29433. }
  29434. void SamplerVoice::startNote (const int midiNoteNumber,
  29435. const float velocity,
  29436. SynthesiserSound* s,
  29437. const int /*currentPitchWheelPosition*/)
  29438. {
  29439. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  29440. jassert (sound != 0); // this object can only play SamplerSounds!
  29441. if (sound != 0)
  29442. {
  29443. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  29444. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  29445. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  29446. sourceSamplePosition = 0.0;
  29447. lgain = velocity;
  29448. rgain = velocity;
  29449. isInAttack = (sound->attackSamples > 0);
  29450. isInRelease = false;
  29451. if (isInAttack)
  29452. {
  29453. attackReleaseLevel = 0.0f;
  29454. attackDelta = (float) (pitchRatio / sound->attackSamples);
  29455. }
  29456. else
  29457. {
  29458. attackReleaseLevel = 1.0f;
  29459. attackDelta = 0.0f;
  29460. }
  29461. if (sound->releaseSamples > 0)
  29462. {
  29463. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  29464. }
  29465. else
  29466. {
  29467. releaseDelta = 0.0f;
  29468. }
  29469. }
  29470. }
  29471. void SamplerVoice::stopNote (const bool allowTailOff)
  29472. {
  29473. if (allowTailOff)
  29474. {
  29475. isInAttack = false;
  29476. isInRelease = true;
  29477. }
  29478. else
  29479. {
  29480. clearCurrentNote();
  29481. }
  29482. }
  29483. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  29484. {
  29485. }
  29486. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  29487. const int /*newValue*/)
  29488. {
  29489. }
  29490. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  29491. {
  29492. const SamplerSound* const playingSound = static_cast <SamplerSound*> (getCurrentlyPlayingSound().getObject());
  29493. if (playingSound != 0)
  29494. {
  29495. const float* const inL = playingSound->data->getSampleData (0, 0);
  29496. const float* const inR = playingSound->data->getNumChannels() > 1
  29497. ? playingSound->data->getSampleData (1, 0) : 0;
  29498. float* outL = outputBuffer.getSampleData (0, startSample);
  29499. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  29500. while (--numSamples >= 0)
  29501. {
  29502. const int pos = (int) sourceSamplePosition;
  29503. const float alpha = (float) (sourceSamplePosition - pos);
  29504. const float invAlpha = 1.0f - alpha;
  29505. // just using a very simple linear interpolation here..
  29506. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  29507. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  29508. : l;
  29509. l *= lgain;
  29510. r *= rgain;
  29511. if (isInAttack)
  29512. {
  29513. l *= attackReleaseLevel;
  29514. r *= attackReleaseLevel;
  29515. attackReleaseLevel += attackDelta;
  29516. if (attackReleaseLevel >= 1.0f)
  29517. {
  29518. attackReleaseLevel = 1.0f;
  29519. isInAttack = false;
  29520. }
  29521. }
  29522. else if (isInRelease)
  29523. {
  29524. l *= attackReleaseLevel;
  29525. r *= attackReleaseLevel;
  29526. attackReleaseLevel += releaseDelta;
  29527. if (attackReleaseLevel <= 0.0f)
  29528. {
  29529. stopNote (false);
  29530. break;
  29531. }
  29532. }
  29533. if (outR != 0)
  29534. {
  29535. *outL++ += l;
  29536. *outR++ += r;
  29537. }
  29538. else
  29539. {
  29540. *outL++ += (l + r) * 0.5f;
  29541. }
  29542. sourceSamplePosition += pitchRatio;
  29543. if (sourceSamplePosition > playingSound->length)
  29544. {
  29545. stopNote (false);
  29546. break;
  29547. }
  29548. }
  29549. }
  29550. }
  29551. END_JUCE_NAMESPACE
  29552. /*** End of inlined file: juce_Sampler.cpp ***/
  29553. /*** Start of inlined file: juce_Synthesiser.cpp ***/
  29554. BEGIN_JUCE_NAMESPACE
  29555. SynthesiserSound::SynthesiserSound()
  29556. {
  29557. }
  29558. SynthesiserSound::~SynthesiserSound()
  29559. {
  29560. }
  29561. SynthesiserVoice::SynthesiserVoice()
  29562. : currentSampleRate (44100.0),
  29563. currentlyPlayingNote (-1),
  29564. noteOnTime (0),
  29565. currentlyPlayingSound (0)
  29566. {
  29567. }
  29568. SynthesiserVoice::~SynthesiserVoice()
  29569. {
  29570. }
  29571. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  29572. {
  29573. return currentlyPlayingSound != 0
  29574. && currentlyPlayingSound->appliesToChannel (midiChannel);
  29575. }
  29576. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  29577. {
  29578. currentSampleRate = newRate;
  29579. }
  29580. void SynthesiserVoice::clearCurrentNote()
  29581. {
  29582. currentlyPlayingNote = -1;
  29583. currentlyPlayingSound = 0;
  29584. }
  29585. Synthesiser::Synthesiser()
  29586. : sampleRate (0),
  29587. lastNoteOnCounter (0),
  29588. shouldStealNotes (true)
  29589. {
  29590. for (int i = 0; i < numElementsInArray (lastPitchWheelValues); ++i)
  29591. lastPitchWheelValues[i] = 0x2000;
  29592. }
  29593. Synthesiser::~Synthesiser()
  29594. {
  29595. }
  29596. SynthesiserVoice* Synthesiser::getVoice (const int index) const
  29597. {
  29598. const ScopedLock sl (lock);
  29599. return voices [index];
  29600. }
  29601. void Synthesiser::clearVoices()
  29602. {
  29603. const ScopedLock sl (lock);
  29604. voices.clear();
  29605. }
  29606. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  29607. {
  29608. const ScopedLock sl (lock);
  29609. voices.add (newVoice);
  29610. }
  29611. void Synthesiser::removeVoice (const int index)
  29612. {
  29613. const ScopedLock sl (lock);
  29614. voices.remove (index);
  29615. }
  29616. void Synthesiser::clearSounds()
  29617. {
  29618. const ScopedLock sl (lock);
  29619. sounds.clear();
  29620. }
  29621. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  29622. {
  29623. const ScopedLock sl (lock);
  29624. sounds.add (newSound);
  29625. }
  29626. void Synthesiser::removeSound (const int index)
  29627. {
  29628. const ScopedLock sl (lock);
  29629. sounds.remove (index);
  29630. }
  29631. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  29632. {
  29633. shouldStealNotes = shouldStealNotes_;
  29634. }
  29635. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  29636. {
  29637. if (sampleRate != newRate)
  29638. {
  29639. const ScopedLock sl (lock);
  29640. allNotesOff (0, false);
  29641. sampleRate = newRate;
  29642. for (int i = voices.size(); --i >= 0;)
  29643. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  29644. }
  29645. }
  29646. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  29647. const MidiBuffer& midiData,
  29648. int startSample,
  29649. int numSamples)
  29650. {
  29651. // must set the sample rate before using this!
  29652. jassert (sampleRate != 0);
  29653. const ScopedLock sl (lock);
  29654. MidiBuffer::Iterator midiIterator (midiData);
  29655. midiIterator.setNextSamplePosition (startSample);
  29656. MidiMessage m (0xf4, 0.0);
  29657. while (numSamples > 0)
  29658. {
  29659. int midiEventPos;
  29660. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  29661. && midiEventPos < startSample + numSamples;
  29662. const int numThisTime = useEvent ? midiEventPos - startSample
  29663. : numSamples;
  29664. if (numThisTime > 0)
  29665. {
  29666. for (int i = voices.size(); --i >= 0;)
  29667. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  29668. }
  29669. if (useEvent)
  29670. {
  29671. if (m.isNoteOn())
  29672. {
  29673. const int channel = m.getChannel();
  29674. noteOn (channel,
  29675. m.getNoteNumber(),
  29676. m.getFloatVelocity());
  29677. }
  29678. else if (m.isNoteOff())
  29679. {
  29680. noteOff (m.getChannel(),
  29681. m.getNoteNumber(),
  29682. true);
  29683. }
  29684. else if (m.isAllNotesOff() || m.isAllSoundOff())
  29685. {
  29686. allNotesOff (m.getChannel(), true);
  29687. }
  29688. else if (m.isPitchWheel())
  29689. {
  29690. const int channel = m.getChannel();
  29691. const int wheelPos = m.getPitchWheelValue();
  29692. lastPitchWheelValues [channel - 1] = wheelPos;
  29693. handlePitchWheel (channel, wheelPos);
  29694. }
  29695. else if (m.isController())
  29696. {
  29697. handleController (m.getChannel(),
  29698. m.getControllerNumber(),
  29699. m.getControllerValue());
  29700. }
  29701. }
  29702. startSample += numThisTime;
  29703. numSamples -= numThisTime;
  29704. }
  29705. }
  29706. void Synthesiser::noteOn (const int midiChannel,
  29707. const int midiNoteNumber,
  29708. const float velocity)
  29709. {
  29710. const ScopedLock sl (lock);
  29711. for (int i = sounds.size(); --i >= 0;)
  29712. {
  29713. SynthesiserSound* const sound = sounds.getUnchecked(i);
  29714. if (sound->appliesToNote (midiNoteNumber)
  29715. && sound->appliesToChannel (midiChannel))
  29716. {
  29717. startVoice (findFreeVoice (sound, shouldStealNotes),
  29718. sound, midiChannel, midiNoteNumber, velocity);
  29719. }
  29720. }
  29721. }
  29722. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  29723. SynthesiserSound* const sound,
  29724. const int midiChannel,
  29725. const int midiNoteNumber,
  29726. const float velocity)
  29727. {
  29728. if (voice != 0 && sound != 0)
  29729. {
  29730. if (voice->currentlyPlayingSound != 0)
  29731. voice->stopNote (false);
  29732. voice->startNote (midiNoteNumber,
  29733. velocity,
  29734. sound,
  29735. lastPitchWheelValues [midiChannel - 1]);
  29736. voice->currentlyPlayingNote = midiNoteNumber;
  29737. voice->noteOnTime = ++lastNoteOnCounter;
  29738. voice->currentlyPlayingSound = sound;
  29739. }
  29740. }
  29741. void Synthesiser::noteOff (const int midiChannel,
  29742. const int midiNoteNumber,
  29743. const bool allowTailOff)
  29744. {
  29745. const ScopedLock sl (lock);
  29746. for (int i = voices.size(); --i >= 0;)
  29747. {
  29748. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29749. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  29750. {
  29751. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  29752. if (sound != 0
  29753. && sound->appliesToNote (midiNoteNumber)
  29754. && sound->appliesToChannel (midiChannel))
  29755. {
  29756. voice->stopNote (allowTailOff);
  29757. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  29758. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  29759. }
  29760. }
  29761. }
  29762. }
  29763. void Synthesiser::allNotesOff (const int midiChannel,
  29764. const bool allowTailOff)
  29765. {
  29766. const ScopedLock sl (lock);
  29767. for (int i = voices.size(); --i >= 0;)
  29768. {
  29769. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29770. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29771. voice->stopNote (allowTailOff);
  29772. }
  29773. }
  29774. void Synthesiser::handlePitchWheel (const int midiChannel,
  29775. const int wheelValue)
  29776. {
  29777. const ScopedLock sl (lock);
  29778. for (int i = voices.size(); --i >= 0;)
  29779. {
  29780. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29781. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29782. {
  29783. voice->pitchWheelMoved (wheelValue);
  29784. }
  29785. }
  29786. }
  29787. void Synthesiser::handleController (const int midiChannel,
  29788. const int controllerNumber,
  29789. const int controllerValue)
  29790. {
  29791. const ScopedLock sl (lock);
  29792. for (int i = voices.size(); --i >= 0;)
  29793. {
  29794. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29795. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29796. voice->controllerMoved (controllerNumber, controllerValue);
  29797. }
  29798. }
  29799. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  29800. const bool stealIfNoneAvailable) const
  29801. {
  29802. const ScopedLock sl (lock);
  29803. for (int i = voices.size(); --i >= 0;)
  29804. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  29805. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  29806. return voices.getUnchecked (i);
  29807. if (stealIfNoneAvailable)
  29808. {
  29809. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  29810. SynthesiserVoice* oldest = 0;
  29811. for (int i = voices.size(); --i >= 0;)
  29812. {
  29813. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29814. if (voice->canPlaySound (soundToPlay)
  29815. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  29816. oldest = voice;
  29817. }
  29818. jassert (oldest != 0);
  29819. return oldest;
  29820. }
  29821. return 0;
  29822. }
  29823. END_JUCE_NAMESPACE
  29824. /*** End of inlined file: juce_Synthesiser.cpp ***/
  29825. /*** Start of inlined file: juce_ActionBroadcaster.cpp ***/
  29826. BEGIN_JUCE_NAMESPACE
  29827. ActionBroadcaster::ActionBroadcaster() throw()
  29828. {
  29829. // are you trying to create this object before or after juce has been intialised??
  29830. jassert (MessageManager::instance != 0);
  29831. }
  29832. ActionBroadcaster::~ActionBroadcaster()
  29833. {
  29834. // all event-based objects must be deleted BEFORE juce is shut down!
  29835. jassert (MessageManager::instance != 0);
  29836. }
  29837. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  29838. {
  29839. actionListenerList.addActionListener (listener);
  29840. }
  29841. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  29842. {
  29843. jassert (actionListenerList.isValidMessageListener());
  29844. if (actionListenerList.isValidMessageListener())
  29845. actionListenerList.removeActionListener (listener);
  29846. }
  29847. void ActionBroadcaster::removeAllActionListeners()
  29848. {
  29849. actionListenerList.removeAllActionListeners();
  29850. }
  29851. void ActionBroadcaster::sendActionMessage (const String& message) const
  29852. {
  29853. actionListenerList.sendActionMessage (message);
  29854. }
  29855. END_JUCE_NAMESPACE
  29856. /*** End of inlined file: juce_ActionBroadcaster.cpp ***/
  29857. /*** Start of inlined file: juce_ActionListenerList.cpp ***/
  29858. BEGIN_JUCE_NAMESPACE
  29859. // special message of our own with a string in it
  29860. class ActionMessage : public Message
  29861. {
  29862. public:
  29863. const String message;
  29864. ActionMessage (const String& messageText,
  29865. void* const listener_) throw()
  29866. : message (messageText)
  29867. {
  29868. pointerParameter = listener_;
  29869. }
  29870. ~ActionMessage() throw()
  29871. {
  29872. }
  29873. private:
  29874. ActionMessage (const ActionMessage&);
  29875. ActionMessage& operator= (const ActionMessage&);
  29876. };
  29877. ActionListenerList::ActionListenerList() throw()
  29878. {
  29879. }
  29880. ActionListenerList::~ActionListenerList() throw()
  29881. {
  29882. }
  29883. void ActionListenerList::addActionListener (ActionListener* const listener) throw()
  29884. {
  29885. const ScopedLock sl (actionListenerLock_);
  29886. jassert (listener != 0);
  29887. jassert (! actionListeners_.contains (listener)); // trying to add a listener to the list twice!
  29888. if (listener != 0)
  29889. actionListeners_.add (listener);
  29890. }
  29891. void ActionListenerList::removeActionListener (ActionListener* const listener) throw()
  29892. {
  29893. const ScopedLock sl (actionListenerLock_);
  29894. jassert (actionListeners_.contains (listener)); // trying to remove a listener that isn't on the list!
  29895. actionListeners_.removeValue (listener);
  29896. }
  29897. void ActionListenerList::removeAllActionListeners() throw()
  29898. {
  29899. const ScopedLock sl (actionListenerLock_);
  29900. actionListeners_.clear();
  29901. }
  29902. void ActionListenerList::sendActionMessage (const String& message) const
  29903. {
  29904. const ScopedLock sl (actionListenerLock_);
  29905. for (int i = actionListeners_.size(); --i >= 0;)
  29906. postMessage (new ActionMessage (message, static_cast <ActionListener*> (actionListeners_.getUnchecked(i))));
  29907. }
  29908. void ActionListenerList::handleMessage (const Message& message)
  29909. {
  29910. const ActionMessage& am = (const ActionMessage&) message;
  29911. if (actionListeners_.contains (am.pointerParameter))
  29912. static_cast <ActionListener*> (am.pointerParameter)->actionListenerCallback (am.message);
  29913. }
  29914. END_JUCE_NAMESPACE
  29915. /*** End of inlined file: juce_ActionListenerList.cpp ***/
  29916. /*** Start of inlined file: juce_AsyncUpdater.cpp ***/
  29917. BEGIN_JUCE_NAMESPACE
  29918. AsyncUpdater::AsyncUpdater() throw()
  29919. : asyncMessagePending (false)
  29920. {
  29921. internalAsyncHandler.owner = this;
  29922. }
  29923. AsyncUpdater::~AsyncUpdater()
  29924. {
  29925. }
  29926. void AsyncUpdater::triggerAsyncUpdate() throw()
  29927. {
  29928. if (! asyncMessagePending)
  29929. {
  29930. asyncMessagePending = true;
  29931. internalAsyncHandler.postMessage (new Message());
  29932. }
  29933. }
  29934. void AsyncUpdater::cancelPendingUpdate() throw()
  29935. {
  29936. asyncMessagePending = false;
  29937. }
  29938. void AsyncUpdater::handleUpdateNowIfNeeded()
  29939. {
  29940. if (asyncMessagePending)
  29941. {
  29942. asyncMessagePending = false;
  29943. handleAsyncUpdate();
  29944. }
  29945. }
  29946. void AsyncUpdater::AsyncUpdaterInternal::handleMessage (const Message&)
  29947. {
  29948. owner->handleUpdateNowIfNeeded();
  29949. }
  29950. END_JUCE_NAMESPACE
  29951. /*** End of inlined file: juce_AsyncUpdater.cpp ***/
  29952. /*** Start of inlined file: juce_ChangeBroadcaster.cpp ***/
  29953. BEGIN_JUCE_NAMESPACE
  29954. ChangeBroadcaster::ChangeBroadcaster() throw()
  29955. {
  29956. // are you trying to create this object before or after juce has been intialised??
  29957. jassert (MessageManager::instance != 0);
  29958. }
  29959. ChangeBroadcaster::~ChangeBroadcaster()
  29960. {
  29961. // all event-based objects must be deleted BEFORE juce is shut down!
  29962. jassert (MessageManager::instance != 0);
  29963. }
  29964. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener) throw()
  29965. {
  29966. changeListenerList.addChangeListener (listener);
  29967. }
  29968. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener) throw()
  29969. {
  29970. jassert (changeListenerList.isValidMessageListener());
  29971. if (changeListenerList.isValidMessageListener())
  29972. changeListenerList.removeChangeListener (listener);
  29973. }
  29974. void ChangeBroadcaster::removeAllChangeListeners() throw()
  29975. {
  29976. changeListenerList.removeAllChangeListeners();
  29977. }
  29978. void ChangeBroadcaster::sendChangeMessage (void* objectThatHasChanged) throw()
  29979. {
  29980. changeListenerList.sendChangeMessage (objectThatHasChanged);
  29981. }
  29982. void ChangeBroadcaster::sendSynchronousChangeMessage (void* objectThatHasChanged)
  29983. {
  29984. changeListenerList.sendSynchronousChangeMessage (objectThatHasChanged);
  29985. }
  29986. void ChangeBroadcaster::dispatchPendingMessages()
  29987. {
  29988. changeListenerList.dispatchPendingMessages();
  29989. }
  29990. END_JUCE_NAMESPACE
  29991. /*** End of inlined file: juce_ChangeBroadcaster.cpp ***/
  29992. /*** Start of inlined file: juce_ChangeListenerList.cpp ***/
  29993. BEGIN_JUCE_NAMESPACE
  29994. ChangeListenerList::ChangeListenerList() throw()
  29995. : lastChangedObject (0),
  29996. messagePending (false)
  29997. {
  29998. }
  29999. ChangeListenerList::~ChangeListenerList() throw()
  30000. {
  30001. }
  30002. void ChangeListenerList::addChangeListener (ChangeListener* const listener) throw()
  30003. {
  30004. const ScopedLock sl (lock);
  30005. jassert (listener != 0);
  30006. if (listener != 0)
  30007. listeners.add (listener);
  30008. }
  30009. void ChangeListenerList::removeChangeListener (ChangeListener* const listener) throw()
  30010. {
  30011. const ScopedLock sl (lock);
  30012. listeners.removeValue (listener);
  30013. }
  30014. void ChangeListenerList::removeAllChangeListeners() throw()
  30015. {
  30016. const ScopedLock sl (lock);
  30017. listeners.clear();
  30018. }
  30019. void ChangeListenerList::sendChangeMessage (void* const objectThatHasChanged) throw()
  30020. {
  30021. const ScopedLock sl (lock);
  30022. if ((! messagePending) && (listeners.size() > 0))
  30023. {
  30024. lastChangedObject = objectThatHasChanged;
  30025. postMessage (new Message (0, 0, 0, objectThatHasChanged));
  30026. messagePending = true;
  30027. }
  30028. }
  30029. void ChangeListenerList::handleMessage (const Message& message)
  30030. {
  30031. sendSynchronousChangeMessage (message.pointerParameter);
  30032. }
  30033. void ChangeListenerList::sendSynchronousChangeMessage (void* const objectThatHasChanged)
  30034. {
  30035. const ScopedLock sl (lock);
  30036. messagePending = false;
  30037. for (int i = listeners.size(); --i >= 0;)
  30038. {
  30039. ChangeListener* const l = static_cast <ChangeListener*> (listeners.getUnchecked (i));
  30040. {
  30041. const ScopedUnlock tempUnlocker (lock);
  30042. l->changeListenerCallback (objectThatHasChanged);
  30043. }
  30044. i = jmin (i, listeners.size());
  30045. }
  30046. }
  30047. void ChangeListenerList::dispatchPendingMessages()
  30048. {
  30049. if (messagePending)
  30050. sendSynchronousChangeMessage (lastChangedObject);
  30051. }
  30052. END_JUCE_NAMESPACE
  30053. /*** End of inlined file: juce_ChangeListenerList.cpp ***/
  30054. /*** Start of inlined file: juce_InterprocessConnection.cpp ***/
  30055. BEGIN_JUCE_NAMESPACE
  30056. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  30057. const uint32 magicMessageHeaderNumber)
  30058. : Thread ("Juce IPC connection"),
  30059. callbackConnectionState (false),
  30060. useMessageThread (callbacksOnMessageThread),
  30061. magicMessageHeader (magicMessageHeaderNumber),
  30062. pipeReceiveMessageTimeout (-1)
  30063. {
  30064. }
  30065. InterprocessConnection::~InterprocessConnection()
  30066. {
  30067. callbackConnectionState = false;
  30068. disconnect();
  30069. }
  30070. bool InterprocessConnection::connectToSocket (const String& hostName,
  30071. const int portNumber,
  30072. const int timeOutMillisecs)
  30073. {
  30074. disconnect();
  30075. const ScopedLock sl (pipeAndSocketLock);
  30076. socket = new StreamingSocket();
  30077. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  30078. {
  30079. connectionMadeInt();
  30080. startThread();
  30081. return true;
  30082. }
  30083. else
  30084. {
  30085. socket = 0;
  30086. return false;
  30087. }
  30088. }
  30089. bool InterprocessConnection::connectToPipe (const String& pipeName,
  30090. const int pipeReceiveMessageTimeoutMs)
  30091. {
  30092. disconnect();
  30093. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30094. if (newPipe->openExisting (pipeName))
  30095. {
  30096. const ScopedLock sl (pipeAndSocketLock);
  30097. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30098. initialiseWithPipe (newPipe.release());
  30099. return true;
  30100. }
  30101. return false;
  30102. }
  30103. bool InterprocessConnection::createPipe (const String& pipeName,
  30104. const int pipeReceiveMessageTimeoutMs)
  30105. {
  30106. disconnect();
  30107. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30108. if (newPipe->createNewPipe (pipeName))
  30109. {
  30110. const ScopedLock sl (pipeAndSocketLock);
  30111. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30112. initialiseWithPipe (newPipe.release());
  30113. return true;
  30114. }
  30115. return false;
  30116. }
  30117. void InterprocessConnection::disconnect()
  30118. {
  30119. if (socket != 0)
  30120. socket->close();
  30121. if (pipe != 0)
  30122. {
  30123. pipe->cancelPendingReads();
  30124. pipe->close();
  30125. }
  30126. stopThread (4000);
  30127. {
  30128. const ScopedLock sl (pipeAndSocketLock);
  30129. socket = 0;
  30130. pipe = 0;
  30131. }
  30132. connectionLostInt();
  30133. }
  30134. bool InterprocessConnection::isConnected() const
  30135. {
  30136. const ScopedLock sl (pipeAndSocketLock);
  30137. return ((socket != 0 && socket->isConnected())
  30138. || (pipe != 0 && pipe->isOpen()))
  30139. && isThreadRunning();
  30140. }
  30141. const String InterprocessConnection::getConnectedHostName() const
  30142. {
  30143. if (pipe != 0)
  30144. {
  30145. return "localhost";
  30146. }
  30147. else if (socket != 0)
  30148. {
  30149. if (! socket->isLocal())
  30150. return socket->getHostName();
  30151. return "localhost";
  30152. }
  30153. return String::empty;
  30154. }
  30155. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  30156. {
  30157. uint32 messageHeader[2];
  30158. messageHeader [0] = ByteOrder::swapIfBigEndian (magicMessageHeader);
  30159. messageHeader [1] = ByteOrder::swapIfBigEndian ((uint32) message.getSize());
  30160. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  30161. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  30162. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  30163. size_t bytesWritten = 0;
  30164. const ScopedLock sl (pipeAndSocketLock);
  30165. if (socket != 0)
  30166. {
  30167. bytesWritten = socket->write (messageData.getData(), (int) messageData.getSize());
  30168. }
  30169. else if (pipe != 0)
  30170. {
  30171. bytesWritten = pipe->write (messageData.getData(), (int) messageData.getSize());
  30172. }
  30173. if (bytesWritten < 0)
  30174. {
  30175. // error..
  30176. return false;
  30177. }
  30178. return (bytesWritten == messageData.getSize());
  30179. }
  30180. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  30181. {
  30182. jassert (socket == 0);
  30183. socket = socket_;
  30184. connectionMadeInt();
  30185. startThread();
  30186. }
  30187. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  30188. {
  30189. jassert (pipe == 0);
  30190. pipe = pipe_;
  30191. connectionMadeInt();
  30192. startThread();
  30193. }
  30194. const int messageMagicNumber = 0xb734128b;
  30195. void InterprocessConnection::handleMessage (const Message& message)
  30196. {
  30197. if (message.intParameter1 == messageMagicNumber)
  30198. {
  30199. switch (message.intParameter2)
  30200. {
  30201. case 0:
  30202. {
  30203. ScopedPointer <MemoryBlock> data (static_cast <MemoryBlock*> (message.pointerParameter));
  30204. messageReceived (*data);
  30205. break;
  30206. }
  30207. case 1:
  30208. connectionMade();
  30209. break;
  30210. case 2:
  30211. connectionLost();
  30212. break;
  30213. }
  30214. }
  30215. }
  30216. void InterprocessConnection::connectionMadeInt()
  30217. {
  30218. if (! callbackConnectionState)
  30219. {
  30220. callbackConnectionState = true;
  30221. if (useMessageThread)
  30222. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  30223. else
  30224. connectionMade();
  30225. }
  30226. }
  30227. void InterprocessConnection::connectionLostInt()
  30228. {
  30229. if (callbackConnectionState)
  30230. {
  30231. callbackConnectionState = false;
  30232. if (useMessageThread)
  30233. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  30234. else
  30235. connectionLost();
  30236. }
  30237. }
  30238. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  30239. {
  30240. jassert (callbackConnectionState);
  30241. if (useMessageThread)
  30242. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  30243. else
  30244. messageReceived (data);
  30245. }
  30246. bool InterprocessConnection::readNextMessageInt()
  30247. {
  30248. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  30249. uint32 messageHeader[2];
  30250. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader), true)
  30251. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  30252. if (bytes == sizeof (messageHeader)
  30253. && ByteOrder::swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  30254. {
  30255. int bytesInMessage = (int) ByteOrder::swapIfBigEndian (messageHeader[1]);
  30256. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  30257. {
  30258. MemoryBlock messageData (bytesInMessage, true);
  30259. int bytesRead = 0;
  30260. while (bytesInMessage > 0)
  30261. {
  30262. if (threadShouldExit())
  30263. return false;
  30264. const int numThisTime = jmin (bytesInMessage, 65536);
  30265. const int bytesIn = (socket != 0) ? socket->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, true)
  30266. : pipe->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, pipeReceiveMessageTimeout);
  30267. if (bytesIn <= 0)
  30268. break;
  30269. bytesRead += bytesIn;
  30270. bytesInMessage -= bytesIn;
  30271. }
  30272. if (bytesRead >= 0)
  30273. deliverDataInt (messageData);
  30274. }
  30275. }
  30276. else if (bytes < 0)
  30277. {
  30278. {
  30279. const ScopedLock sl (pipeAndSocketLock);
  30280. socket = 0;
  30281. }
  30282. connectionLostInt();
  30283. return false;
  30284. }
  30285. return true;
  30286. }
  30287. void InterprocessConnection::run()
  30288. {
  30289. while (! threadShouldExit())
  30290. {
  30291. if (socket != 0)
  30292. {
  30293. const int ready = socket->waitUntilReady (true, 0);
  30294. if (ready < 0)
  30295. {
  30296. {
  30297. const ScopedLock sl (pipeAndSocketLock);
  30298. socket = 0;
  30299. }
  30300. connectionLostInt();
  30301. break;
  30302. }
  30303. else if (ready > 0)
  30304. {
  30305. if (! readNextMessageInt())
  30306. break;
  30307. }
  30308. else
  30309. {
  30310. Thread::sleep (2);
  30311. }
  30312. }
  30313. else if (pipe != 0)
  30314. {
  30315. if (! pipe->isOpen())
  30316. {
  30317. {
  30318. const ScopedLock sl (pipeAndSocketLock);
  30319. pipe = 0;
  30320. }
  30321. connectionLostInt();
  30322. break;
  30323. }
  30324. else
  30325. {
  30326. if (! readNextMessageInt())
  30327. break;
  30328. }
  30329. }
  30330. else
  30331. {
  30332. break;
  30333. }
  30334. }
  30335. }
  30336. END_JUCE_NAMESPACE
  30337. /*** End of inlined file: juce_InterprocessConnection.cpp ***/
  30338. /*** Start of inlined file: juce_InterprocessConnectionServer.cpp ***/
  30339. BEGIN_JUCE_NAMESPACE
  30340. InterprocessConnectionServer::InterprocessConnectionServer()
  30341. : Thread ("Juce IPC server")
  30342. {
  30343. }
  30344. InterprocessConnectionServer::~InterprocessConnectionServer()
  30345. {
  30346. stop();
  30347. }
  30348. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  30349. {
  30350. stop();
  30351. socket = new StreamingSocket();
  30352. if (socket->createListener (portNumber))
  30353. {
  30354. startThread();
  30355. return true;
  30356. }
  30357. socket = 0;
  30358. return false;
  30359. }
  30360. void InterprocessConnectionServer::stop()
  30361. {
  30362. signalThreadShouldExit();
  30363. if (socket != 0)
  30364. socket->close();
  30365. stopThread (4000);
  30366. socket = 0;
  30367. }
  30368. void InterprocessConnectionServer::run()
  30369. {
  30370. while ((! threadShouldExit()) && socket != 0)
  30371. {
  30372. ScopedPointer <StreamingSocket> clientSocket (socket->waitForNextConnection());
  30373. if (clientSocket != 0)
  30374. {
  30375. InterprocessConnection* newConnection = createConnectionObject();
  30376. if (newConnection != 0)
  30377. newConnection->initialiseWithSocket (clientSocket.release());
  30378. }
  30379. }
  30380. }
  30381. END_JUCE_NAMESPACE
  30382. /*** End of inlined file: juce_InterprocessConnectionServer.cpp ***/
  30383. /*** Start of inlined file: juce_Message.cpp ***/
  30384. BEGIN_JUCE_NAMESPACE
  30385. Message::Message() throw()
  30386. : intParameter1 (0),
  30387. intParameter2 (0),
  30388. intParameter3 (0),
  30389. pointerParameter (0)
  30390. {
  30391. }
  30392. Message::Message (const int intParameter1_,
  30393. const int intParameter2_,
  30394. const int intParameter3_,
  30395. void* const pointerParameter_) throw()
  30396. : intParameter1 (intParameter1_),
  30397. intParameter2 (intParameter2_),
  30398. intParameter3 (intParameter3_),
  30399. pointerParameter (pointerParameter_)
  30400. {
  30401. }
  30402. Message::~Message() throw()
  30403. {
  30404. }
  30405. END_JUCE_NAMESPACE
  30406. /*** End of inlined file: juce_Message.cpp ***/
  30407. /*** Start of inlined file: juce_MessageListener.cpp ***/
  30408. BEGIN_JUCE_NAMESPACE
  30409. MessageListener::MessageListener() throw()
  30410. {
  30411. // are you trying to create a messagelistener before or after juce has been intialised??
  30412. jassert (MessageManager::instance != 0);
  30413. if (MessageManager::instance != 0)
  30414. MessageManager::instance->messageListeners.add (this);
  30415. }
  30416. MessageListener::~MessageListener()
  30417. {
  30418. if (MessageManager::instance != 0)
  30419. MessageManager::instance->messageListeners.removeValue (this);
  30420. }
  30421. void MessageListener::postMessage (Message* const message) const throw()
  30422. {
  30423. message->messageRecipient = const_cast <MessageListener*> (this);
  30424. if (MessageManager::instance == 0)
  30425. MessageManager::getInstance();
  30426. MessageManager::instance->postMessageToQueue (message);
  30427. }
  30428. bool MessageListener::isValidMessageListener() const throw()
  30429. {
  30430. return (MessageManager::instance != 0)
  30431. && MessageManager::instance->messageListeners.contains (this);
  30432. }
  30433. END_JUCE_NAMESPACE
  30434. /*** End of inlined file: juce_MessageListener.cpp ***/
  30435. /*** Start of inlined file: juce_MessageManager.cpp ***/
  30436. BEGIN_JUCE_NAMESPACE
  30437. // platform-specific functions..
  30438. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  30439. bool juce_postMessageToSystemQueue (void* message);
  30440. MessageManager* MessageManager::instance = 0;
  30441. static const int quitMessageId = 0xfffff321;
  30442. MessageManager::MessageManager() throw()
  30443. : quitMessagePosted (false),
  30444. quitMessageReceived (false),
  30445. threadWithLock (0)
  30446. {
  30447. messageThreadId = Thread::getCurrentThreadId();
  30448. }
  30449. MessageManager::~MessageManager() throw()
  30450. {
  30451. broadcastListeners = 0;
  30452. doPlatformSpecificShutdown();
  30453. jassert (instance == this);
  30454. instance = 0; // do this last in case this instance is still needed by doPlatformSpecificShutdown()
  30455. }
  30456. MessageManager* MessageManager::getInstance() throw()
  30457. {
  30458. if (instance == 0)
  30459. {
  30460. instance = new MessageManager();
  30461. doPlatformSpecificInitialisation();
  30462. }
  30463. return instance;
  30464. }
  30465. void MessageManager::postMessageToQueue (Message* const message)
  30466. {
  30467. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  30468. delete message;
  30469. }
  30470. CallbackMessage::CallbackMessage() throw() {}
  30471. CallbackMessage::~CallbackMessage() throw() {}
  30472. void CallbackMessage::post()
  30473. {
  30474. if (MessageManager::instance != 0)
  30475. MessageManager::instance->postCallbackMessage (this);
  30476. }
  30477. void MessageManager::postCallbackMessage (Message* const message)
  30478. {
  30479. message->messageRecipient = 0;
  30480. postMessageToQueue (message);
  30481. }
  30482. // not for public use..
  30483. void MessageManager::deliverMessage (void* const message)
  30484. {
  30485. const ScopedPointer <Message> m (static_cast <Message*> (message));
  30486. MessageListener* const recipient = m->messageRecipient;
  30487. JUCE_TRY
  30488. {
  30489. if (messageListeners.contains (recipient))
  30490. {
  30491. recipient->handleMessage (*m);
  30492. }
  30493. else if (recipient == 0)
  30494. {
  30495. if (m->intParameter1 == quitMessageId)
  30496. {
  30497. quitMessageReceived = true;
  30498. }
  30499. else
  30500. {
  30501. CallbackMessage* const cm = dynamic_cast <CallbackMessage*> (static_cast <Message*> (m));
  30502. if (cm != 0)
  30503. cm->messageCallback();
  30504. }
  30505. }
  30506. }
  30507. JUCE_CATCH_EXCEPTION
  30508. }
  30509. #if ! (JUCE_MAC || JUCE_IPHONE)
  30510. void MessageManager::runDispatchLoop()
  30511. {
  30512. jassert (isThisTheMessageThread()); // must only be called by the message thread
  30513. runDispatchLoopUntil (-1);
  30514. }
  30515. void MessageManager::stopDispatchLoop()
  30516. {
  30517. Message* const m = new Message (quitMessageId, 0, 0, 0);
  30518. m->messageRecipient = 0;
  30519. postMessageToQueue (m);
  30520. quitMessagePosted = true;
  30521. }
  30522. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  30523. {
  30524. jassert (isThisTheMessageThread()); // must only be called by the message thread
  30525. const int64 endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  30526. while ((millisecondsToRunFor < 0 || endTime > Time::currentTimeMillis())
  30527. && ! quitMessageReceived)
  30528. {
  30529. JUCE_TRY
  30530. {
  30531. if (! juce_dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0))
  30532. {
  30533. const int msToWait = (int) (endTime - Time::currentTimeMillis());
  30534. if (msToWait > 0)
  30535. Thread::sleep (jmin (5, msToWait));
  30536. }
  30537. }
  30538. JUCE_CATCH_EXCEPTION
  30539. }
  30540. return ! quitMessageReceived;
  30541. }
  30542. #endif
  30543. void MessageManager::deliverBroadcastMessage (const String& value)
  30544. {
  30545. if (broadcastListeners != 0)
  30546. broadcastListeners->sendActionMessage (value);
  30547. }
  30548. void MessageManager::registerBroadcastListener (ActionListener* const listener) throw()
  30549. {
  30550. if (broadcastListeners == 0)
  30551. broadcastListeners = new ActionListenerList();
  30552. broadcastListeners->addActionListener (listener);
  30553. }
  30554. void MessageManager::deregisterBroadcastListener (ActionListener* const listener) throw()
  30555. {
  30556. if (broadcastListeners != 0)
  30557. broadcastListeners->removeActionListener (listener);
  30558. }
  30559. bool MessageManager::isThisTheMessageThread() const throw()
  30560. {
  30561. return Thread::getCurrentThreadId() == messageThreadId;
  30562. }
  30563. void MessageManager::setCurrentThreadAsMessageThread()
  30564. {
  30565. if (messageThreadId != Thread::getCurrentThreadId())
  30566. {
  30567. messageThreadId = Thread::getCurrentThreadId();
  30568. // This is needed on windows to make sure the message window is created by this thread
  30569. doPlatformSpecificShutdown();
  30570. doPlatformSpecificInitialisation();
  30571. }
  30572. }
  30573. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  30574. {
  30575. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  30576. return thisThread == messageThreadId || thisThread == threadWithLock;
  30577. }
  30578. /* The only safe way to lock the message thread while another thread does
  30579. some work is by posting a special message, whose purpose is to tie up the event
  30580. loop until the other thread has finished its business.
  30581. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  30582. get locked before making an event callback, because if the same OS lock gets indirectly
  30583. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  30584. in Cocoa).
  30585. */
  30586. class MessageManagerLock::SharedEvents : public ReferenceCountedObject
  30587. {
  30588. public:
  30589. SharedEvents() {}
  30590. ~SharedEvents() {}
  30591. /* This class just holds a couple of events to communicate between the BlockingMessage
  30592. and the MessageManagerLock. Because both of these objects may be deleted at any time,
  30593. this shared data must be kept in a separate, ref-counted container. */
  30594. WaitableEvent lockedEvent, releaseEvent;
  30595. private:
  30596. SharedEvents (const SharedEvents&);
  30597. SharedEvents& operator= (const SharedEvents&);
  30598. };
  30599. class MessageManagerLock::BlockingMessage : public CallbackMessage
  30600. {
  30601. public:
  30602. BlockingMessage (MessageManagerLock::SharedEvents* const events_) : events (events_) {}
  30603. ~BlockingMessage() throw() {}
  30604. void messageCallback()
  30605. {
  30606. events->lockedEvent.signal();
  30607. events->releaseEvent.wait();
  30608. }
  30609. juce_UseDebuggingNewOperator
  30610. private:
  30611. ReferenceCountedObjectPtr <MessageManagerLock::SharedEvents> events;
  30612. BlockingMessage (const BlockingMessage&);
  30613. BlockingMessage& operator= (const BlockingMessage&);
  30614. };
  30615. MessageManagerLock::MessageManagerLock (Thread* const threadToCheck) throw()
  30616. : sharedEvents (0),
  30617. locked (false)
  30618. {
  30619. init (threadToCheck, 0);
  30620. }
  30621. MessageManagerLock::MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal) throw()
  30622. : sharedEvents (0),
  30623. locked (false)
  30624. {
  30625. init (0, jobToCheckForExitSignal);
  30626. }
  30627. void MessageManagerLock::init (Thread* const threadToCheck, ThreadPoolJob* const job) throw()
  30628. {
  30629. if (MessageManager::instance != 0)
  30630. {
  30631. if (MessageManager::instance->currentThreadHasLockedMessageManager())
  30632. {
  30633. locked = true; // either we're on the message thread, or this is a re-entrant call.
  30634. }
  30635. else
  30636. {
  30637. if (threadToCheck == 0 && job == 0)
  30638. {
  30639. MessageManager::instance->lockingLock.enter();
  30640. }
  30641. else
  30642. {
  30643. while (! MessageManager::instance->lockingLock.tryEnter())
  30644. {
  30645. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  30646. || (job != 0 && job->shouldExit()))
  30647. return;
  30648. Thread::sleep (1);
  30649. }
  30650. }
  30651. sharedEvents = new SharedEvents();
  30652. sharedEvents->incReferenceCount();
  30653. (new BlockingMessage (sharedEvents))->post();
  30654. while (! sharedEvents->lockedEvent.wait (50))
  30655. {
  30656. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  30657. || (job != 0 && job->shouldExit()))
  30658. {
  30659. sharedEvents->releaseEvent.signal();
  30660. sharedEvents->decReferenceCount();
  30661. sharedEvents = 0;
  30662. MessageManager::instance->lockingLock.exit();
  30663. return;
  30664. }
  30665. }
  30666. jassert (MessageManager::instance->threadWithLock == 0);
  30667. MessageManager::instance->threadWithLock = Thread::getCurrentThreadId();
  30668. locked = true;
  30669. }
  30670. }
  30671. }
  30672. MessageManagerLock::~MessageManagerLock() throw()
  30673. {
  30674. if (sharedEvents != 0)
  30675. {
  30676. jassert (MessageManager::instance == 0 || MessageManager::instance->currentThreadHasLockedMessageManager());
  30677. sharedEvents->releaseEvent.signal();
  30678. sharedEvents->decReferenceCount();
  30679. if (MessageManager::instance != 0)
  30680. {
  30681. MessageManager::instance->threadWithLock = 0;
  30682. MessageManager::instance->lockingLock.exit();
  30683. }
  30684. }
  30685. }
  30686. END_JUCE_NAMESPACE
  30687. /*** End of inlined file: juce_MessageManager.cpp ***/
  30688. /*** Start of inlined file: juce_MultiTimer.cpp ***/
  30689. BEGIN_JUCE_NAMESPACE
  30690. class MultiTimer::MultiTimerCallback : public Timer
  30691. {
  30692. public:
  30693. MultiTimerCallback (const int timerId_, MultiTimer& owner_)
  30694. : timerId (timerId_),
  30695. owner (owner_)
  30696. {
  30697. }
  30698. ~MultiTimerCallback()
  30699. {
  30700. }
  30701. void timerCallback()
  30702. {
  30703. owner.timerCallback (timerId);
  30704. }
  30705. const int timerId;
  30706. private:
  30707. MultiTimer& owner;
  30708. };
  30709. MultiTimer::MultiTimer() throw()
  30710. {
  30711. }
  30712. MultiTimer::MultiTimer (const MultiTimer&) throw()
  30713. {
  30714. }
  30715. MultiTimer::~MultiTimer()
  30716. {
  30717. const ScopedLock sl (timerListLock);
  30718. timers.clear();
  30719. }
  30720. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  30721. {
  30722. const ScopedLock sl (timerListLock);
  30723. for (int i = timers.size(); --i >= 0;)
  30724. {
  30725. MultiTimerCallback* const t = timers.getUnchecked(i);
  30726. if (t->timerId == timerId)
  30727. {
  30728. t->startTimer (intervalInMilliseconds);
  30729. return;
  30730. }
  30731. }
  30732. MultiTimerCallback* const newTimer = new MultiTimerCallback (timerId, *this);
  30733. timers.add (newTimer);
  30734. newTimer->startTimer (intervalInMilliseconds);
  30735. }
  30736. void MultiTimer::stopTimer (const int timerId) throw()
  30737. {
  30738. const ScopedLock sl (timerListLock);
  30739. for (int i = timers.size(); --i >= 0;)
  30740. {
  30741. MultiTimerCallback* const t = timers.getUnchecked(i);
  30742. if (t->timerId == timerId)
  30743. t->stopTimer();
  30744. }
  30745. }
  30746. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  30747. {
  30748. const ScopedLock sl (timerListLock);
  30749. for (int i = timers.size(); --i >= 0;)
  30750. {
  30751. const MultiTimerCallback* const t = timers.getUnchecked(i);
  30752. if (t->timerId == timerId)
  30753. return t->isTimerRunning();
  30754. }
  30755. return false;
  30756. }
  30757. int MultiTimer::getTimerInterval (const int timerId) const throw()
  30758. {
  30759. const ScopedLock sl (timerListLock);
  30760. for (int i = timers.size(); --i >= 0;)
  30761. {
  30762. const MultiTimerCallback* const t = timers.getUnchecked(i);
  30763. if (t->timerId == timerId)
  30764. return t->getTimerInterval();
  30765. }
  30766. return 0;
  30767. }
  30768. END_JUCE_NAMESPACE
  30769. /*** End of inlined file: juce_MultiTimer.cpp ***/
  30770. /*** Start of inlined file: juce_Timer.cpp ***/
  30771. BEGIN_JUCE_NAMESPACE
  30772. class InternalTimerThread : private Thread,
  30773. private MessageListener,
  30774. private DeletedAtShutdown,
  30775. private AsyncUpdater
  30776. {
  30777. public:
  30778. InternalTimerThread()
  30779. : Thread ("Juce Timer"),
  30780. firstTimer (0),
  30781. callbackNeeded (0)
  30782. {
  30783. triggerAsyncUpdate();
  30784. }
  30785. ~InternalTimerThread() throw()
  30786. {
  30787. stopThread (4000);
  30788. jassert (instance == this || instance == 0);
  30789. if (instance == this)
  30790. instance = 0;
  30791. }
  30792. void run()
  30793. {
  30794. uint32 lastTime = Time::getMillisecondCounter();
  30795. while (! threadShouldExit())
  30796. {
  30797. const uint32 now = Time::getMillisecondCounter();
  30798. if (now <= lastTime)
  30799. {
  30800. wait (2);
  30801. continue;
  30802. }
  30803. const int elapsed = now - lastTime;
  30804. lastTime = now;
  30805. int timeUntilFirstTimer = 1000;
  30806. {
  30807. const ScopedLock sl (lock);
  30808. decrementAllCounters (elapsed);
  30809. if (firstTimer != 0)
  30810. timeUntilFirstTimer = firstTimer->countdownMs;
  30811. }
  30812. if (timeUntilFirstTimer <= 0)
  30813. {
  30814. /* If we managed to set the atomic boolean to true then send a message, this is needed
  30815. as a memory barrier so the message won't be sent before callbackNeeded is set to true,
  30816. but if it fails it means the message-thread changed the value from under us so at least
  30817. some processing is happenening and we can just loop around and try again
  30818. */
  30819. if (callbackNeeded.compareAndSetBool (1, 0))
  30820. {
  30821. postMessage (new Message());
  30822. /* Sometimes our message can get discarded by the OS (e.g. when running as an RTAS
  30823. when the app has a modal loop), so this is how long to wait before assuming the
  30824. message has been lost and trying again.
  30825. */
  30826. const uint32 messageDeliveryTimeout = now + 2000;
  30827. while (callbackNeeded.get() != 0)
  30828. {
  30829. wait (4);
  30830. if (threadShouldExit())
  30831. return;
  30832. if (Time::getMillisecondCounter() > messageDeliveryTimeout)
  30833. break;
  30834. }
  30835. }
  30836. }
  30837. else
  30838. {
  30839. // don't wait for too long because running this loop also helps keep the
  30840. // Time::getApproximateMillisecondTimer value stay up-to-date
  30841. wait (jlimit (1, 50, timeUntilFirstTimer));
  30842. }
  30843. }
  30844. }
  30845. void callTimers()
  30846. {
  30847. const ScopedLock sl (lock);
  30848. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  30849. {
  30850. Timer* const t = firstTimer;
  30851. t->countdownMs = t->periodMs;
  30852. removeTimer (t);
  30853. addTimer (t);
  30854. const ScopedUnlock ul (lock);
  30855. JUCE_TRY
  30856. {
  30857. t->timerCallback();
  30858. }
  30859. JUCE_CATCH_EXCEPTION
  30860. }
  30861. /* This is needed as a memory barrier to make sure all processing of current timers is done
  30862. before the boolean is set. This set should never fail since if it was false in the first place,
  30863. we wouldn't get a message (so it can't be changed from false to true from under us), and if we
  30864. get a message then the value is true and the other thread can only set it to true again and
  30865. we will get another callback to set it to false.
  30866. */
  30867. callbackNeeded.set (0);
  30868. }
  30869. void handleMessage (const Message&)
  30870. {
  30871. callTimers();
  30872. }
  30873. void callTimersSynchronously()
  30874. {
  30875. if (! isThreadRunning())
  30876. {
  30877. // (This is relied on by some plugins in cases where the MM has
  30878. // had to restart and the async callback never started)
  30879. cancelPendingUpdate();
  30880. triggerAsyncUpdate();
  30881. }
  30882. callTimers();
  30883. }
  30884. static void callAnyTimersSynchronously()
  30885. {
  30886. if (InternalTimerThread::instance != 0)
  30887. InternalTimerThread::instance->callTimersSynchronously();
  30888. }
  30889. static inline void add (Timer* const tim) throw()
  30890. {
  30891. if (instance == 0)
  30892. instance = new InternalTimerThread();
  30893. const ScopedLock sl (instance->lock);
  30894. instance->addTimer (tim);
  30895. }
  30896. static inline void remove (Timer* const tim) throw()
  30897. {
  30898. if (instance != 0)
  30899. {
  30900. const ScopedLock sl (instance->lock);
  30901. instance->removeTimer (tim);
  30902. }
  30903. }
  30904. static inline void resetCounter (Timer* const tim,
  30905. const int newCounter) throw()
  30906. {
  30907. if (instance != 0)
  30908. {
  30909. tim->countdownMs = newCounter;
  30910. tim->periodMs = newCounter;
  30911. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  30912. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  30913. {
  30914. const ScopedLock sl (instance->lock);
  30915. instance->removeTimer (tim);
  30916. instance->addTimer (tim);
  30917. }
  30918. }
  30919. }
  30920. private:
  30921. friend class Timer;
  30922. static InternalTimerThread* instance;
  30923. static CriticalSection lock;
  30924. Timer* volatile firstTimer;
  30925. Atomic <int> callbackNeeded;
  30926. void addTimer (Timer* const t) throw()
  30927. {
  30928. #if JUCE_DEBUG
  30929. Timer* tt = firstTimer;
  30930. while (tt != 0)
  30931. {
  30932. // trying to add a timer that's already here - shouldn't get to this point,
  30933. // so if you get this assertion, let me know!
  30934. jassert (tt != t);
  30935. tt = tt->next;
  30936. }
  30937. jassert (t->previous == 0 && t->next == 0);
  30938. #endif
  30939. Timer* i = firstTimer;
  30940. if (i == 0 || i->countdownMs > t->countdownMs)
  30941. {
  30942. t->next = firstTimer;
  30943. firstTimer = t;
  30944. }
  30945. else
  30946. {
  30947. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  30948. i = i->next;
  30949. jassert (i != 0);
  30950. t->next = i->next;
  30951. t->previous = i;
  30952. i->next = t;
  30953. }
  30954. if (t->next != 0)
  30955. t->next->previous = t;
  30956. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  30957. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  30958. notify();
  30959. }
  30960. void removeTimer (Timer* const t) throw()
  30961. {
  30962. #if JUCE_DEBUG
  30963. Timer* tt = firstTimer;
  30964. bool found = false;
  30965. while (tt != 0)
  30966. {
  30967. if (tt == t)
  30968. {
  30969. found = true;
  30970. break;
  30971. }
  30972. tt = tt->next;
  30973. }
  30974. // trying to remove a timer that's not here - shouldn't get to this point,
  30975. // so if you get this assertion, let me know!
  30976. jassert (found);
  30977. #endif
  30978. if (t->previous != 0)
  30979. {
  30980. jassert (firstTimer != t);
  30981. t->previous->next = t->next;
  30982. }
  30983. else
  30984. {
  30985. jassert (firstTimer == t);
  30986. firstTimer = t->next;
  30987. }
  30988. if (t->next != 0)
  30989. t->next->previous = t->previous;
  30990. t->next = 0;
  30991. t->previous = 0;
  30992. }
  30993. void decrementAllCounters (const int numMillisecs) const
  30994. {
  30995. Timer* t = firstTimer;
  30996. while (t != 0)
  30997. {
  30998. t->countdownMs -= numMillisecs;
  30999. t = t->next;
  31000. }
  31001. }
  31002. void handleAsyncUpdate()
  31003. {
  31004. startThread (7);
  31005. }
  31006. InternalTimerThread (const InternalTimerThread&);
  31007. InternalTimerThread& operator= (const InternalTimerThread&);
  31008. };
  31009. InternalTimerThread* InternalTimerThread::instance = 0;
  31010. CriticalSection InternalTimerThread::lock;
  31011. void juce_callAnyTimersSynchronously()
  31012. {
  31013. InternalTimerThread::callAnyTimersSynchronously();
  31014. }
  31015. #if JUCE_DEBUG
  31016. static SortedSet <Timer*> activeTimers;
  31017. #endif
  31018. Timer::Timer() throw()
  31019. : countdownMs (0),
  31020. periodMs (0),
  31021. previous (0),
  31022. next (0)
  31023. {
  31024. #if JUCE_DEBUG
  31025. activeTimers.add (this);
  31026. #endif
  31027. }
  31028. Timer::Timer (const Timer&) throw()
  31029. : countdownMs (0),
  31030. periodMs (0),
  31031. previous (0),
  31032. next (0)
  31033. {
  31034. #if JUCE_DEBUG
  31035. activeTimers.add (this);
  31036. #endif
  31037. }
  31038. Timer::~Timer()
  31039. {
  31040. stopTimer();
  31041. #if JUCE_DEBUG
  31042. activeTimers.removeValue (this);
  31043. #endif
  31044. }
  31045. void Timer::startTimer (const int interval) throw()
  31046. {
  31047. const ScopedLock sl (InternalTimerThread::lock);
  31048. #if JUCE_DEBUG
  31049. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31050. jassert (activeTimers.contains (this));
  31051. #endif
  31052. if (periodMs == 0)
  31053. {
  31054. countdownMs = interval;
  31055. periodMs = jmax (1, interval);
  31056. InternalTimerThread::add (this);
  31057. }
  31058. else
  31059. {
  31060. InternalTimerThread::resetCounter (this, interval);
  31061. }
  31062. }
  31063. void Timer::stopTimer() throw()
  31064. {
  31065. const ScopedLock sl (InternalTimerThread::lock);
  31066. #if JUCE_DEBUG
  31067. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31068. jassert (activeTimers.contains (this));
  31069. #endif
  31070. if (periodMs > 0)
  31071. {
  31072. InternalTimerThread::remove (this);
  31073. periodMs = 0;
  31074. }
  31075. }
  31076. END_JUCE_NAMESPACE
  31077. /*** End of inlined file: juce_Timer.cpp ***/
  31078. #endif
  31079. #if JUCE_BUILD_GUI
  31080. /*** Start of inlined file: juce_Component.cpp ***/
  31081. BEGIN_JUCE_NAMESPACE
  31082. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  31083. enum ComponentMessageNumbers
  31084. {
  31085. customCommandMessage = 0x7fff0001,
  31086. exitModalStateMessage = 0x7fff0002
  31087. };
  31088. static uint32 nextComponentUID = 0;
  31089. Component* Component::currentlyFocusedComponent = 0;
  31090. Component::Component()
  31091. : parentComponent_ (0),
  31092. componentUID (++nextComponentUID),
  31093. numDeepMouseListeners (0),
  31094. lookAndFeel_ (0),
  31095. effect_ (0),
  31096. bufferedImage_ (0),
  31097. mouseListeners_ (0),
  31098. keyListeners_ (0),
  31099. componentFlags_ (0)
  31100. {
  31101. }
  31102. Component::Component (const String& name)
  31103. : componentName_ (name),
  31104. parentComponent_ (0),
  31105. componentUID (++nextComponentUID),
  31106. numDeepMouseListeners (0),
  31107. lookAndFeel_ (0),
  31108. effect_ (0),
  31109. bufferedImage_ (0),
  31110. mouseListeners_ (0),
  31111. keyListeners_ (0),
  31112. componentFlags_ (0)
  31113. {
  31114. }
  31115. Component::~Component()
  31116. {
  31117. componentListeners.call (&ComponentListener::componentBeingDeleted, *this);
  31118. if (parentComponent_ != 0)
  31119. {
  31120. parentComponent_->removeChildComponent (this);
  31121. }
  31122. else if ((currentlyFocusedComponent == this)
  31123. || isParentOf (currentlyFocusedComponent))
  31124. {
  31125. giveAwayFocus();
  31126. }
  31127. if (flags.hasHeavyweightPeerFlag)
  31128. removeFromDesktop();
  31129. for (int i = childComponentList_.size(); --i >= 0;)
  31130. childComponentList_.getUnchecked(i)->parentComponent_ = 0;
  31131. delete mouseListeners_;
  31132. delete keyListeners_;
  31133. }
  31134. void Component::setName (const String& name)
  31135. {
  31136. // if component methods are being called from threads other than the message
  31137. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31138. checkMessageManagerIsLocked
  31139. if (componentName_ != name)
  31140. {
  31141. componentName_ = name;
  31142. if (flags.hasHeavyweightPeerFlag)
  31143. {
  31144. ComponentPeer* const peer = getPeer();
  31145. jassert (peer != 0);
  31146. if (peer != 0)
  31147. peer->setTitle (name);
  31148. }
  31149. BailOutChecker checker (this);
  31150. componentListeners.callChecked (checker, &ComponentListener::componentNameChanged, *this);
  31151. }
  31152. }
  31153. void Component::setVisible (bool shouldBeVisible)
  31154. {
  31155. if (flags.visibleFlag != shouldBeVisible)
  31156. {
  31157. // if component methods are being called from threads other than the message
  31158. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31159. checkMessageManagerIsLocked
  31160. SafePointer<Component> safePointer (this);
  31161. flags.visibleFlag = shouldBeVisible;
  31162. internalRepaint (0, 0, getWidth(), getHeight());
  31163. sendFakeMouseMove();
  31164. if (! shouldBeVisible)
  31165. {
  31166. if (currentlyFocusedComponent == this
  31167. || isParentOf (currentlyFocusedComponent))
  31168. {
  31169. if (parentComponent_ != 0)
  31170. parentComponent_->grabKeyboardFocus();
  31171. else
  31172. giveAwayFocus();
  31173. }
  31174. }
  31175. if (safePointer != 0)
  31176. {
  31177. sendVisibilityChangeMessage();
  31178. if (safePointer != 0 && flags.hasHeavyweightPeerFlag)
  31179. {
  31180. ComponentPeer* const peer = getPeer();
  31181. jassert (peer != 0);
  31182. if (peer != 0)
  31183. {
  31184. peer->setVisible (shouldBeVisible);
  31185. internalHierarchyChanged();
  31186. }
  31187. }
  31188. }
  31189. }
  31190. }
  31191. void Component::visibilityChanged()
  31192. {
  31193. }
  31194. void Component::sendVisibilityChangeMessage()
  31195. {
  31196. BailOutChecker checker (this);
  31197. visibilityChanged();
  31198. if (! checker.shouldBailOut())
  31199. componentListeners.callChecked (checker, &ComponentListener::componentVisibilityChanged, *this);
  31200. }
  31201. bool Component::isShowing() const
  31202. {
  31203. if (flags.visibleFlag)
  31204. {
  31205. if (parentComponent_ != 0)
  31206. {
  31207. return parentComponent_->isShowing();
  31208. }
  31209. else
  31210. {
  31211. const ComponentPeer* const peer = getPeer();
  31212. return peer != 0 && ! peer->isMinimised();
  31213. }
  31214. }
  31215. return false;
  31216. }
  31217. class FadeOutProxyComponent : public Component,
  31218. public Timer
  31219. {
  31220. public:
  31221. FadeOutProxyComponent (Component* comp,
  31222. const int fadeLengthMs,
  31223. const int deltaXToMove,
  31224. const int deltaYToMove,
  31225. const float scaleFactorAtEnd)
  31226. : lastTime (0),
  31227. alpha (1.0f),
  31228. scale (1.0f)
  31229. {
  31230. image = comp->createComponentSnapshot (comp->getLocalBounds());
  31231. setBounds (comp->getBounds());
  31232. comp->getParentComponent()->addAndMakeVisible (this);
  31233. toBehind (comp);
  31234. alphaChangePerMs = -1.0f / (float)fadeLengthMs;
  31235. centreX = comp->getX() + comp->getWidth() * 0.5f;
  31236. xChangePerMs = deltaXToMove / (float)fadeLengthMs;
  31237. centreY = comp->getY() + comp->getHeight() * 0.5f;
  31238. yChangePerMs = deltaYToMove / (float)fadeLengthMs;
  31239. scaleChangePerMs = (scaleFactorAtEnd - 1.0f) / (float)fadeLengthMs;
  31240. setInterceptsMouseClicks (false, false);
  31241. // 30 fps is enough for a fade, but we need a higher rate if it's moving as well..
  31242. startTimer (1000 / ((deltaXToMove == 0 && deltaYToMove == 0) ? 30 : 50));
  31243. }
  31244. ~FadeOutProxyComponent()
  31245. {
  31246. }
  31247. void paint (Graphics& g)
  31248. {
  31249. g.setOpacity (alpha);
  31250. g.drawImage (image,
  31251. 0, 0, getWidth(), getHeight(),
  31252. 0, 0, image.getWidth(), image.getHeight());
  31253. }
  31254. void timerCallback()
  31255. {
  31256. const uint32 now = Time::getMillisecondCounter();
  31257. if (lastTime == 0)
  31258. lastTime = now;
  31259. const int msPassed = (now > lastTime) ? now - lastTime : 0;
  31260. lastTime = now;
  31261. alpha += alphaChangePerMs * msPassed;
  31262. if (alpha > 0)
  31263. {
  31264. if (xChangePerMs != 0.0f || yChangePerMs != 0.0f || scaleChangePerMs != 0.0f)
  31265. {
  31266. centreX += xChangePerMs * msPassed;
  31267. centreY += yChangePerMs * msPassed;
  31268. scale += scaleChangePerMs * msPassed;
  31269. const int w = roundToInt (image.getWidth() * scale);
  31270. const int h = roundToInt (image.getHeight() * scale);
  31271. setBounds (roundToInt (centreX) - w / 2,
  31272. roundToInt (centreY) - h / 2,
  31273. w, h);
  31274. }
  31275. repaint();
  31276. }
  31277. else
  31278. {
  31279. delete this;
  31280. }
  31281. }
  31282. juce_UseDebuggingNewOperator
  31283. private:
  31284. Image image;
  31285. uint32 lastTime;
  31286. float alpha, alphaChangePerMs;
  31287. float centreX, xChangePerMs;
  31288. float centreY, yChangePerMs;
  31289. float scale, scaleChangePerMs;
  31290. FadeOutProxyComponent (const FadeOutProxyComponent&);
  31291. FadeOutProxyComponent& operator= (const FadeOutProxyComponent&);
  31292. };
  31293. void Component::fadeOutComponent (const int millisecondsToFade,
  31294. const int deltaXToMove,
  31295. const int deltaYToMove,
  31296. const float scaleFactorAtEnd)
  31297. {
  31298. //xxx won't work for comps without parents
  31299. if (isShowing() && millisecondsToFade > 0)
  31300. new FadeOutProxyComponent (this, millisecondsToFade,
  31301. deltaXToMove, deltaYToMove, scaleFactorAtEnd);
  31302. setVisible (false);
  31303. }
  31304. bool Component::isValidComponent() const
  31305. {
  31306. return (this != 0) && isValidMessageListener();
  31307. }
  31308. void* Component::getWindowHandle() const
  31309. {
  31310. const ComponentPeer* const peer = getPeer();
  31311. if (peer != 0)
  31312. return peer->getNativeHandle();
  31313. return 0;
  31314. }
  31315. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  31316. {
  31317. // if component methods are being called from threads other than the message
  31318. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31319. checkMessageManagerIsLocked
  31320. if (isOpaque())
  31321. styleWanted &= ~ComponentPeer::windowIsSemiTransparent;
  31322. else
  31323. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  31324. int currentStyleFlags = 0;
  31325. // don't use getPeer(), so that we only get the peer that's specifically
  31326. // for this comp, and not for one of its parents.
  31327. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  31328. if (peer != 0)
  31329. currentStyleFlags = peer->getStyleFlags();
  31330. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  31331. {
  31332. SafePointer<Component> safePointer (this);
  31333. #if JUCE_LINUX
  31334. // it's wise to give the component a non-zero size before
  31335. // putting it on the desktop, as X windows get confused by this, and
  31336. // a (1, 1) minimum size is enforced here.
  31337. setSize (jmax (1, getWidth()),
  31338. jmax (1, getHeight()));
  31339. #endif
  31340. const Point<int> topLeft (relativePositionToGlobal (Point<int> (0, 0)));
  31341. bool wasFullscreen = false;
  31342. bool wasMinimised = false;
  31343. ComponentBoundsConstrainer* currentConstainer = 0;
  31344. Rectangle<int> oldNonFullScreenBounds;
  31345. if (peer != 0)
  31346. {
  31347. wasFullscreen = peer->isFullScreen();
  31348. wasMinimised = peer->isMinimised();
  31349. currentConstainer = peer->getConstrainer();
  31350. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  31351. removeFromDesktop();
  31352. setTopLeftPosition (topLeft.getX(), topLeft.getY());
  31353. }
  31354. if (parentComponent_ != 0)
  31355. parentComponent_->removeChildComponent (this);
  31356. if (safePointer != 0)
  31357. {
  31358. flags.hasHeavyweightPeerFlag = true;
  31359. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  31360. Desktop::getInstance().addDesktopComponent (this);
  31361. bounds_.setPosition (topLeft);
  31362. peer->setBounds (topLeft.getX(), topLeft.getY(), getWidth(), getHeight(), false);
  31363. peer->setVisible (isVisible());
  31364. if (wasFullscreen)
  31365. {
  31366. peer->setFullScreen (true);
  31367. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  31368. }
  31369. if (wasMinimised)
  31370. peer->setMinimised (true);
  31371. if (isAlwaysOnTop())
  31372. peer->setAlwaysOnTop (true);
  31373. peer->setConstrainer (currentConstainer);
  31374. repaint();
  31375. }
  31376. internalHierarchyChanged();
  31377. }
  31378. }
  31379. void Component::removeFromDesktop()
  31380. {
  31381. // if component methods are being called from threads other than the message
  31382. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31383. checkMessageManagerIsLocked
  31384. if (flags.hasHeavyweightPeerFlag)
  31385. {
  31386. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  31387. flags.hasHeavyweightPeerFlag = false;
  31388. jassert (peer != 0);
  31389. delete peer;
  31390. Desktop::getInstance().removeDesktopComponent (this);
  31391. }
  31392. }
  31393. bool Component::isOnDesktop() const throw()
  31394. {
  31395. return flags.hasHeavyweightPeerFlag;
  31396. }
  31397. void Component::userTriedToCloseWindow()
  31398. {
  31399. /* This means that the user's trying to get rid of your window with the 'close window' system
  31400. menu option (on windows) or possibly the task manager - you should really handle this
  31401. and delete or hide your component in an appropriate way.
  31402. If you want to ignore the event and don't want to trigger this assertion, just override
  31403. this method and do nothing.
  31404. */
  31405. jassertfalse;
  31406. }
  31407. void Component::minimisationStateChanged (bool)
  31408. {
  31409. }
  31410. void Component::setOpaque (const bool shouldBeOpaque)
  31411. {
  31412. if (shouldBeOpaque != flags.opaqueFlag)
  31413. {
  31414. flags.opaqueFlag = shouldBeOpaque;
  31415. if (flags.hasHeavyweightPeerFlag)
  31416. {
  31417. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  31418. if (peer != 0)
  31419. {
  31420. // to make it recreate the heavyweight window
  31421. addToDesktop (peer->getStyleFlags());
  31422. }
  31423. }
  31424. repaint();
  31425. }
  31426. }
  31427. bool Component::isOpaque() const throw()
  31428. {
  31429. return flags.opaqueFlag;
  31430. }
  31431. void Component::setBufferedToImage (const bool shouldBeBuffered)
  31432. {
  31433. if (shouldBeBuffered != flags.bufferToImageFlag)
  31434. {
  31435. bufferedImage_ = Image();
  31436. flags.bufferToImageFlag = shouldBeBuffered;
  31437. }
  31438. }
  31439. void Component::toFront (const bool setAsForeground)
  31440. {
  31441. // if component methods are being called from threads other than the message
  31442. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31443. checkMessageManagerIsLocked
  31444. if (flags.hasHeavyweightPeerFlag)
  31445. {
  31446. ComponentPeer* const peer = getPeer();
  31447. if (peer != 0)
  31448. {
  31449. peer->toFront (setAsForeground);
  31450. if (setAsForeground && ! hasKeyboardFocus (true))
  31451. grabKeyboardFocus();
  31452. }
  31453. }
  31454. else if (parentComponent_ != 0)
  31455. {
  31456. Array<Component*>& childList = parentComponent_->childComponentList_;
  31457. if (childList.getLast() != this)
  31458. {
  31459. const int index = childList.indexOf (this);
  31460. if (index >= 0)
  31461. {
  31462. int insertIndex = -1;
  31463. if (! flags.alwaysOnTopFlag)
  31464. {
  31465. insertIndex = childList.size() - 1;
  31466. while (insertIndex > 0 && childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  31467. --insertIndex;
  31468. }
  31469. if (index != insertIndex)
  31470. {
  31471. childList.move (index, insertIndex);
  31472. sendFakeMouseMove();
  31473. repaintParent();
  31474. }
  31475. }
  31476. }
  31477. if (setAsForeground)
  31478. {
  31479. internalBroughtToFront();
  31480. grabKeyboardFocus();
  31481. }
  31482. }
  31483. }
  31484. void Component::toBehind (Component* const other)
  31485. {
  31486. if (other != 0 && other != this)
  31487. {
  31488. // the two components must belong to the same parent..
  31489. jassert (parentComponent_ == other->parentComponent_);
  31490. if (parentComponent_ != 0)
  31491. {
  31492. Array<Component*>& childList = parentComponent_->childComponentList_;
  31493. const int index = childList.indexOf (this);
  31494. if (index >= 0 && childList [index + 1] != other)
  31495. {
  31496. int otherIndex = childList.indexOf (other);
  31497. if (otherIndex >= 0)
  31498. {
  31499. if (index < otherIndex)
  31500. --otherIndex;
  31501. childList.move (index, otherIndex);
  31502. sendFakeMouseMove();
  31503. repaintParent();
  31504. }
  31505. }
  31506. }
  31507. else if (isOnDesktop())
  31508. {
  31509. jassert (other->isOnDesktop());
  31510. if (other->isOnDesktop())
  31511. {
  31512. ComponentPeer* const us = getPeer();
  31513. ComponentPeer* const them = other->getPeer();
  31514. jassert (us != 0 && them != 0);
  31515. if (us != 0 && them != 0)
  31516. us->toBehind (them);
  31517. }
  31518. }
  31519. }
  31520. }
  31521. void Component::toBack()
  31522. {
  31523. Array<Component*>& childList = parentComponent_->childComponentList_;
  31524. if (isOnDesktop())
  31525. {
  31526. jassertfalse; //xxx need to add this to native window
  31527. }
  31528. else if (parentComponent_ != 0 && childList.getFirst() != this)
  31529. {
  31530. const int index = childList.indexOf (this);
  31531. if (index > 0)
  31532. {
  31533. int insertIndex = 0;
  31534. if (flags.alwaysOnTopFlag)
  31535. {
  31536. while (insertIndex < childList.size()
  31537. && ! childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  31538. {
  31539. ++insertIndex;
  31540. }
  31541. }
  31542. if (index != insertIndex)
  31543. {
  31544. childList.move (index, insertIndex);
  31545. sendFakeMouseMove();
  31546. repaintParent();
  31547. }
  31548. }
  31549. }
  31550. }
  31551. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  31552. {
  31553. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  31554. {
  31555. flags.alwaysOnTopFlag = shouldStayOnTop;
  31556. if (isOnDesktop())
  31557. {
  31558. ComponentPeer* const peer = getPeer();
  31559. jassert (peer != 0);
  31560. if (peer != 0)
  31561. {
  31562. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  31563. {
  31564. // some kinds of peer can't change their always-on-top status, so
  31565. // for these, we'll need to create a new window
  31566. const int oldFlags = peer->getStyleFlags();
  31567. removeFromDesktop();
  31568. addToDesktop (oldFlags);
  31569. }
  31570. }
  31571. }
  31572. if (shouldStayOnTop)
  31573. toFront (false);
  31574. internalHierarchyChanged();
  31575. }
  31576. }
  31577. bool Component::isAlwaysOnTop() const throw()
  31578. {
  31579. return flags.alwaysOnTopFlag;
  31580. }
  31581. int Component::proportionOfWidth (const float proportion) const throw()
  31582. {
  31583. return roundToInt (proportion * bounds_.getWidth());
  31584. }
  31585. int Component::proportionOfHeight (const float proportion) const throw()
  31586. {
  31587. return roundToInt (proportion * bounds_.getHeight());
  31588. }
  31589. int Component::getParentWidth() const throw()
  31590. {
  31591. return (parentComponent_ != 0) ? parentComponent_->getWidth()
  31592. : getParentMonitorArea().getWidth();
  31593. }
  31594. int Component::getParentHeight() const throw()
  31595. {
  31596. return (parentComponent_ != 0) ? parentComponent_->getHeight()
  31597. : getParentMonitorArea().getHeight();
  31598. }
  31599. int Component::getScreenX() const
  31600. {
  31601. return getScreenPosition().getX();
  31602. }
  31603. int Component::getScreenY() const
  31604. {
  31605. return getScreenPosition().getY();
  31606. }
  31607. const Point<int> Component::getScreenPosition() const
  31608. {
  31609. return (parentComponent_ != 0) ? parentComponent_->getScreenPosition() + getPosition()
  31610. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenPosition()
  31611. : getPosition());
  31612. }
  31613. const Rectangle<int> Component::getScreenBounds() const
  31614. {
  31615. return bounds_.withPosition (getScreenPosition());
  31616. }
  31617. const Point<int> Component::relativePositionToGlobal (const Point<int>& relativePosition) const
  31618. {
  31619. const Component* c = this;
  31620. Point<int> p (relativePosition);
  31621. do
  31622. {
  31623. if (c->flags.hasHeavyweightPeerFlag)
  31624. return c->getPeer()->relativePositionToGlobal (p);
  31625. p += c->getPosition();
  31626. c = c->parentComponent_;
  31627. }
  31628. while (c != 0);
  31629. return p;
  31630. }
  31631. const Point<int> Component::globalPositionToRelative (const Point<int>& screenPosition) const
  31632. {
  31633. if (flags.hasHeavyweightPeerFlag)
  31634. {
  31635. return getPeer()->globalPositionToRelative (screenPosition);
  31636. }
  31637. else
  31638. {
  31639. if (parentComponent_ != 0)
  31640. return parentComponent_->globalPositionToRelative (screenPosition) - getPosition();
  31641. return screenPosition - getPosition();
  31642. }
  31643. }
  31644. const Point<int> Component::relativePositionToOtherComponent (const Component* const targetComponent, const Point<int>& positionRelativeToThis) const
  31645. {
  31646. Point<int> p (positionRelativeToThis);
  31647. if (targetComponent != 0)
  31648. {
  31649. const Component* c = this;
  31650. do
  31651. {
  31652. if (c == targetComponent)
  31653. return p;
  31654. if (c->flags.hasHeavyweightPeerFlag)
  31655. {
  31656. p = c->getPeer()->relativePositionToGlobal (p);
  31657. break;
  31658. }
  31659. p += c->getPosition();
  31660. c = c->parentComponent_;
  31661. }
  31662. while (c != 0);
  31663. p = targetComponent->globalPositionToRelative (p);
  31664. }
  31665. return p;
  31666. }
  31667. void Component::setBounds (int x, int y, int w, int h)
  31668. {
  31669. // if component methods are being called from threads other than the message
  31670. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31671. checkMessageManagerIsLocked
  31672. if (w < 0) w = 0;
  31673. if (h < 0) h = 0;
  31674. const bool wasResized = (getWidth() != w || getHeight() != h);
  31675. const bool wasMoved = (getX() != x || getY() != y);
  31676. #if JUCE_DEBUG
  31677. // It's a very bad idea to try to resize a window during its paint() method!
  31678. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  31679. #endif
  31680. if (wasMoved || wasResized)
  31681. {
  31682. if (flags.visibleFlag)
  31683. {
  31684. // send a fake mouse move to trigger enter/exit messages if needed..
  31685. sendFakeMouseMove();
  31686. if (! flags.hasHeavyweightPeerFlag)
  31687. repaintParent();
  31688. }
  31689. bounds_.setBounds (x, y, w, h);
  31690. if (wasResized)
  31691. repaint();
  31692. else if (! flags.hasHeavyweightPeerFlag)
  31693. repaintParent();
  31694. if (flags.hasHeavyweightPeerFlag)
  31695. {
  31696. ComponentPeer* const peer = getPeer();
  31697. if (peer != 0)
  31698. {
  31699. if (wasMoved && wasResized)
  31700. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  31701. else if (wasMoved)
  31702. peer->setPosition (getX(), getY());
  31703. else if (wasResized)
  31704. peer->setSize (getWidth(), getHeight());
  31705. }
  31706. }
  31707. sendMovedResizedMessages (wasMoved, wasResized);
  31708. }
  31709. }
  31710. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  31711. {
  31712. JUCE_TRY
  31713. {
  31714. if (wasMoved)
  31715. moved();
  31716. if (wasResized)
  31717. {
  31718. resized();
  31719. for (int i = childComponentList_.size(); --i >= 0;)
  31720. {
  31721. childComponentList_.getUnchecked(i)->parentSizeChanged();
  31722. i = jmin (i, childComponentList_.size());
  31723. }
  31724. }
  31725. BailOutChecker checker (this);
  31726. if (parentComponent_ != 0)
  31727. parentComponent_->childBoundsChanged (this);
  31728. if (! checker.shouldBailOut())
  31729. componentListeners.callChecked (checker, &ComponentListener::componentMovedOrResized,
  31730. *this, wasMoved, wasResized);
  31731. }
  31732. JUCE_CATCH_EXCEPTION
  31733. }
  31734. void Component::setSize (const int w, const int h)
  31735. {
  31736. setBounds (getX(), getY(), w, h);
  31737. }
  31738. void Component::setTopLeftPosition (const int x, const int y)
  31739. {
  31740. setBounds (x, y, getWidth(), getHeight());
  31741. }
  31742. void Component::setTopRightPosition (const int x, const int y)
  31743. {
  31744. setTopLeftPosition (x - getWidth(), y);
  31745. }
  31746. void Component::setBounds (const Rectangle<int>& r)
  31747. {
  31748. setBounds (r.getX(),
  31749. r.getY(),
  31750. r.getWidth(),
  31751. r.getHeight());
  31752. }
  31753. void Component::setBoundsRelative (const float x, const float y,
  31754. const float w, const float h)
  31755. {
  31756. const int pw = getParentWidth();
  31757. const int ph = getParentHeight();
  31758. setBounds (roundToInt (x * pw),
  31759. roundToInt (y * ph),
  31760. roundToInt (w * pw),
  31761. roundToInt (h * ph));
  31762. }
  31763. void Component::setCentrePosition (const int x, const int y)
  31764. {
  31765. setTopLeftPosition (x - getWidth() / 2,
  31766. y - getHeight() / 2);
  31767. }
  31768. void Component::setCentreRelative (const float x, const float y)
  31769. {
  31770. setCentrePosition (roundToInt (getParentWidth() * x),
  31771. roundToInt (getParentHeight() * y));
  31772. }
  31773. void Component::centreWithSize (const int width, const int height)
  31774. {
  31775. setBounds ((getParentWidth() - width) / 2,
  31776. (getParentHeight() - height) / 2,
  31777. width,
  31778. height);
  31779. }
  31780. void Component::setBoundsInset (const BorderSize& borders)
  31781. {
  31782. setBounds (borders.getLeft(),
  31783. borders.getTop(),
  31784. getParentWidth() - (borders.getLeftAndRight()),
  31785. getParentHeight() - (borders.getTopAndBottom()));
  31786. }
  31787. void Component::setBoundsToFit (int x, int y, int width, int height,
  31788. const Justification& justification,
  31789. const bool onlyReduceInSize)
  31790. {
  31791. // it's no good calling this method unless both the component and
  31792. // target rectangle have a finite size.
  31793. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  31794. if (getWidth() > 0 && getHeight() > 0
  31795. && width > 0 && height > 0)
  31796. {
  31797. int newW, newH;
  31798. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  31799. {
  31800. newW = getWidth();
  31801. newH = getHeight();
  31802. }
  31803. else
  31804. {
  31805. const double imageRatio = getHeight() / (double) getWidth();
  31806. const double targetRatio = height / (double) width;
  31807. if (imageRatio <= targetRatio)
  31808. {
  31809. newW = width;
  31810. newH = jmin (height, roundToInt (newW * imageRatio));
  31811. }
  31812. else
  31813. {
  31814. newH = height;
  31815. newW = jmin (width, roundToInt (newH / imageRatio));
  31816. }
  31817. }
  31818. if (newW > 0 && newH > 0)
  31819. {
  31820. int newX, newY;
  31821. justification.applyToRectangle (newX, newY, newW, newH,
  31822. x, y, width, height);
  31823. setBounds (newX, newY, newW, newH);
  31824. }
  31825. }
  31826. }
  31827. bool Component::hitTest (int x, int y)
  31828. {
  31829. if (! flags.ignoresMouseClicksFlag)
  31830. return true;
  31831. if (flags.allowChildMouseClicksFlag)
  31832. {
  31833. for (int i = getNumChildComponents(); --i >= 0;)
  31834. {
  31835. Component* const c = getChildComponent (i);
  31836. if (c->isVisible()
  31837. && c->bounds_.contains (x, y)
  31838. && c->hitTest (x - c->getX(),
  31839. y - c->getY()))
  31840. {
  31841. return true;
  31842. }
  31843. }
  31844. }
  31845. return false;
  31846. }
  31847. void Component::setInterceptsMouseClicks (const bool allowClicks,
  31848. const bool allowClicksOnChildComponents) throw()
  31849. {
  31850. flags.ignoresMouseClicksFlag = ! allowClicks;
  31851. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  31852. }
  31853. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  31854. bool& allowsClicksOnChildComponents) const throw()
  31855. {
  31856. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  31857. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  31858. }
  31859. bool Component::contains (const int x, const int y)
  31860. {
  31861. if (((unsigned int) x) < (unsigned int) getWidth()
  31862. && ((unsigned int) y) < (unsigned int) getHeight()
  31863. && hitTest (x, y))
  31864. {
  31865. if (parentComponent_ != 0)
  31866. {
  31867. return parentComponent_->contains (x + getX(),
  31868. y + getY());
  31869. }
  31870. else if (flags.hasHeavyweightPeerFlag)
  31871. {
  31872. const ComponentPeer* const peer = getPeer();
  31873. if (peer != 0)
  31874. return peer->contains (Point<int> (x, y), true);
  31875. }
  31876. }
  31877. return false;
  31878. }
  31879. bool Component::reallyContains (int x, int y, const bool returnTrueIfWithinAChild)
  31880. {
  31881. if (! contains (x, y))
  31882. return false;
  31883. Component* p = this;
  31884. while (p->parentComponent_ != 0)
  31885. {
  31886. x += p->getX();
  31887. y += p->getY();
  31888. p = p->parentComponent_;
  31889. }
  31890. const Component* const c = p->getComponentAt (x, y);
  31891. return (c == this) || (returnTrueIfWithinAChild && isParentOf (c));
  31892. }
  31893. Component* Component::getComponentAt (const Point<int>& position)
  31894. {
  31895. return getComponentAt (position.getX(), position.getY());
  31896. }
  31897. Component* Component::getComponentAt (const int x, const int y)
  31898. {
  31899. if (flags.visibleFlag
  31900. && ((unsigned int) x) < (unsigned int) getWidth()
  31901. && ((unsigned int) y) < (unsigned int) getHeight()
  31902. && hitTest (x, y))
  31903. {
  31904. for (int i = childComponentList_.size(); --i >= 0;)
  31905. {
  31906. Component* const child = childComponentList_.getUnchecked(i);
  31907. Component* const c = child->getComponentAt (x - child->getX(),
  31908. y - child->getY());
  31909. if (c != 0)
  31910. return c;
  31911. }
  31912. return this;
  31913. }
  31914. return 0;
  31915. }
  31916. void Component::addChildComponent (Component* const child, int zOrder)
  31917. {
  31918. // if component methods are being called from threads other than the message
  31919. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31920. checkMessageManagerIsLocked
  31921. if (child != 0 && child->parentComponent_ != this)
  31922. {
  31923. if (child->parentComponent_ != 0)
  31924. child->parentComponent_->removeChildComponent (child);
  31925. else
  31926. child->removeFromDesktop();
  31927. child->parentComponent_ = this;
  31928. if (child->isVisible())
  31929. child->repaintParent();
  31930. if (! child->isAlwaysOnTop())
  31931. {
  31932. if (zOrder < 0 || zOrder > childComponentList_.size())
  31933. zOrder = childComponentList_.size();
  31934. while (zOrder > 0)
  31935. {
  31936. if (! childComponentList_.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  31937. break;
  31938. --zOrder;
  31939. }
  31940. }
  31941. childComponentList_.insert (zOrder, child);
  31942. child->internalHierarchyChanged();
  31943. internalChildrenChanged();
  31944. }
  31945. }
  31946. void Component::addAndMakeVisible (Component* const child, int zOrder)
  31947. {
  31948. if (child != 0)
  31949. {
  31950. child->setVisible (true);
  31951. addChildComponent (child, zOrder);
  31952. }
  31953. }
  31954. void Component::removeChildComponent (Component* const child)
  31955. {
  31956. removeChildComponent (childComponentList_.indexOf (child));
  31957. }
  31958. Component* Component::removeChildComponent (const int index)
  31959. {
  31960. // if component methods are being called from threads other than the message
  31961. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31962. checkMessageManagerIsLocked
  31963. Component* const child = childComponentList_ [index];
  31964. if (child != 0)
  31965. {
  31966. sendFakeMouseMove();
  31967. child->repaintParent();
  31968. childComponentList_.remove (index);
  31969. child->parentComponent_ = 0;
  31970. JUCE_TRY
  31971. {
  31972. if ((currentlyFocusedComponent == child)
  31973. || child->isParentOf (currentlyFocusedComponent))
  31974. {
  31975. // get rid first to force the grabKeyboardFocus to change to us.
  31976. giveAwayFocus();
  31977. grabKeyboardFocus();
  31978. }
  31979. }
  31980. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  31981. catch (const std::exception& e)
  31982. {
  31983. currentlyFocusedComponent = 0;
  31984. Desktop::getInstance().triggerFocusCallback();
  31985. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  31986. }
  31987. catch (...)
  31988. {
  31989. currentlyFocusedComponent = 0;
  31990. Desktop::getInstance().triggerFocusCallback();
  31991. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  31992. }
  31993. #endif
  31994. child->internalHierarchyChanged();
  31995. internalChildrenChanged();
  31996. }
  31997. return child;
  31998. }
  31999. void Component::removeAllChildren()
  32000. {
  32001. while (childComponentList_.size() > 0)
  32002. removeChildComponent (childComponentList_.size() - 1);
  32003. }
  32004. void Component::deleteAllChildren()
  32005. {
  32006. while (childComponentList_.size() > 0)
  32007. delete (removeChildComponent (childComponentList_.size() - 1));
  32008. }
  32009. int Component::getNumChildComponents() const throw()
  32010. {
  32011. return childComponentList_.size();
  32012. }
  32013. Component* Component::getChildComponent (const int index) const throw()
  32014. {
  32015. return childComponentList_ [index];
  32016. }
  32017. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  32018. {
  32019. return childComponentList_.indexOf (const_cast <Component*> (child));
  32020. }
  32021. Component* Component::getTopLevelComponent() const throw()
  32022. {
  32023. const Component* comp = this;
  32024. while (comp->parentComponent_ != 0)
  32025. comp = comp->parentComponent_;
  32026. return const_cast <Component*> (comp);
  32027. }
  32028. bool Component::isParentOf (const Component* possibleChild) const throw()
  32029. {
  32030. if (! possibleChild->isValidComponent())
  32031. {
  32032. jassert (possibleChild == 0);
  32033. return false;
  32034. }
  32035. while (possibleChild != 0)
  32036. {
  32037. possibleChild = possibleChild->parentComponent_;
  32038. if (possibleChild == this)
  32039. return true;
  32040. }
  32041. return false;
  32042. }
  32043. void Component::parentHierarchyChanged()
  32044. {
  32045. }
  32046. void Component::childrenChanged()
  32047. {
  32048. }
  32049. void Component::internalChildrenChanged()
  32050. {
  32051. if (componentListeners.isEmpty())
  32052. {
  32053. childrenChanged();
  32054. }
  32055. else
  32056. {
  32057. BailOutChecker checker (this);
  32058. childrenChanged();
  32059. if (! checker.shouldBailOut())
  32060. componentListeners.callChecked (checker, &ComponentListener::componentChildrenChanged, *this);
  32061. }
  32062. }
  32063. void Component::internalHierarchyChanged()
  32064. {
  32065. BailOutChecker checker (this);
  32066. parentHierarchyChanged();
  32067. if (checker.shouldBailOut())
  32068. return;
  32069. componentListeners.callChecked (checker, &ComponentListener::componentParentHierarchyChanged, *this);
  32070. if (checker.shouldBailOut())
  32071. return;
  32072. for (int i = childComponentList_.size(); --i >= 0;)
  32073. {
  32074. childComponentList_.getUnchecked (i)->internalHierarchyChanged();
  32075. if (checker.shouldBailOut())
  32076. {
  32077. // you really shouldn't delete the parent component during a callback telling you
  32078. // that it's changed..
  32079. jassertfalse;
  32080. return;
  32081. }
  32082. i = jmin (i, childComponentList_.size());
  32083. }
  32084. }
  32085. void* Component::runModalLoopCallback (void* userData)
  32086. {
  32087. return (void*) (pointer_sized_int) static_cast <Component*> (userData)->runModalLoop();
  32088. }
  32089. int Component::runModalLoop()
  32090. {
  32091. if (! MessageManager::getInstance()->isThisTheMessageThread())
  32092. {
  32093. // use a callback so this can be called from non-gui threads
  32094. return (int) (pointer_sized_int) MessageManager::getInstance()
  32095. ->callFunctionOnMessageThread (&runModalLoopCallback, this);
  32096. }
  32097. if (! isCurrentlyModal())
  32098. enterModalState (true);
  32099. return ModalComponentManager::getInstance()->runEventLoopForCurrentComponent();
  32100. }
  32101. void Component::enterModalState (const bool takeKeyboardFocus_, ModalComponentManager::Callback* const callback)
  32102. {
  32103. // if component methods are being called from threads other than the message
  32104. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32105. checkMessageManagerIsLocked
  32106. // Check for an attempt to make a component modal when it already is!
  32107. // This can cause nasty problems..
  32108. jassert (! flags.currentlyModalFlag);
  32109. if (! isCurrentlyModal())
  32110. {
  32111. ModalComponentManager::getInstance()->startModal (this, callback);
  32112. flags.currentlyModalFlag = true;
  32113. setVisible (true);
  32114. if (takeKeyboardFocus_)
  32115. grabKeyboardFocus();
  32116. }
  32117. }
  32118. void Component::exitModalState (const int returnValue)
  32119. {
  32120. if (isCurrentlyModal())
  32121. {
  32122. if (MessageManager::getInstance()->isThisTheMessageThread())
  32123. {
  32124. ModalComponentManager::getInstance()->endModal (this, returnValue);
  32125. flags.currentlyModalFlag = false;
  32126. bringModalComponentToFront();
  32127. }
  32128. else
  32129. {
  32130. postMessage (new Message (exitModalStateMessage, returnValue, 0, 0));
  32131. }
  32132. }
  32133. }
  32134. bool Component::isCurrentlyModal() const throw()
  32135. {
  32136. return flags.currentlyModalFlag
  32137. && getCurrentlyModalComponent() == this;
  32138. }
  32139. bool Component::isCurrentlyBlockedByAnotherModalComponent() const
  32140. {
  32141. Component* const mc = getCurrentlyModalComponent();
  32142. return mc != 0
  32143. && mc != this
  32144. && (! mc->isParentOf (this))
  32145. && ! mc->canModalEventBeSentToComponent (this);
  32146. }
  32147. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() throw()
  32148. {
  32149. return ModalComponentManager::getInstance()->getNumModalComponents();
  32150. }
  32151. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) throw()
  32152. {
  32153. return ModalComponentManager::getInstance()->getModalComponent (index);
  32154. }
  32155. void Component::bringModalComponentToFront()
  32156. {
  32157. ComponentPeer* lastOne = 0;
  32158. for (int i = 0; i < getNumCurrentlyModalComponents(); ++i)
  32159. {
  32160. Component* const c = getCurrentlyModalComponent (i);
  32161. if (c == 0)
  32162. break;
  32163. ComponentPeer* peer = c->getPeer();
  32164. if (peer != 0 && peer != lastOne)
  32165. {
  32166. if (lastOne == 0)
  32167. {
  32168. peer->toFront (true);
  32169. peer->grabFocus();
  32170. }
  32171. else
  32172. peer->toBehind (lastOne);
  32173. lastOne = peer;
  32174. }
  32175. }
  32176. }
  32177. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  32178. {
  32179. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  32180. }
  32181. bool Component::isBroughtToFrontOnMouseClick() const throw()
  32182. {
  32183. return flags.bringToFrontOnClickFlag;
  32184. }
  32185. void Component::setMouseCursor (const MouseCursor& cursor)
  32186. {
  32187. if (cursor_ != cursor)
  32188. {
  32189. cursor_ = cursor;
  32190. if (flags.visibleFlag)
  32191. updateMouseCursor();
  32192. }
  32193. }
  32194. const MouseCursor Component::getMouseCursor()
  32195. {
  32196. return cursor_;
  32197. }
  32198. void Component::updateMouseCursor() const
  32199. {
  32200. sendFakeMouseMove();
  32201. }
  32202. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  32203. {
  32204. flags.repaintOnMouseActivityFlag = shouldRepaint;
  32205. }
  32206. void Component::repaintParent()
  32207. {
  32208. if (flags.visibleFlag)
  32209. internalRepaint (0, 0, getWidth(), getHeight());
  32210. }
  32211. void Component::repaint()
  32212. {
  32213. repaint (0, 0, getWidth(), getHeight());
  32214. }
  32215. void Component::repaint (const int x, const int y,
  32216. const int w, const int h)
  32217. {
  32218. bufferedImage_ = Image();
  32219. if (flags.visibleFlag)
  32220. internalRepaint (x, y, w, h);
  32221. }
  32222. void Component::repaint (const Rectangle<int>& area)
  32223. {
  32224. repaint (area.getX(), area.getY(), area.getWidth(), area.getHeight());
  32225. }
  32226. void Component::internalRepaint (int x, int y, int w, int h)
  32227. {
  32228. // if component methods are being called from threads other than the message
  32229. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32230. checkMessageManagerIsLocked
  32231. if (x < 0)
  32232. {
  32233. w += x;
  32234. x = 0;
  32235. }
  32236. if (x + w > getWidth())
  32237. w = getWidth() - x;
  32238. if (w > 0)
  32239. {
  32240. if (y < 0)
  32241. {
  32242. h += y;
  32243. y = 0;
  32244. }
  32245. if (y + h > getHeight())
  32246. h = getHeight() - y;
  32247. if (h > 0)
  32248. {
  32249. if (parentComponent_ != 0)
  32250. {
  32251. x += getX();
  32252. y += getY();
  32253. if (parentComponent_->flags.visibleFlag)
  32254. parentComponent_->internalRepaint (x, y, w, h);
  32255. }
  32256. else if (flags.hasHeavyweightPeerFlag)
  32257. {
  32258. ComponentPeer* const peer = getPeer();
  32259. if (peer != 0)
  32260. peer->repaint (Rectangle<int> (x, y, w, h));
  32261. }
  32262. }
  32263. }
  32264. }
  32265. void Component::renderComponent (Graphics& g)
  32266. {
  32267. const Rectangle<int> clipBounds (g.getClipBounds());
  32268. g.saveState();
  32269. clipObscuredRegions (g, clipBounds, 0, 0);
  32270. if (! g.isClipEmpty())
  32271. {
  32272. if (flags.bufferToImageFlag)
  32273. {
  32274. if (bufferedImage_.isNull())
  32275. {
  32276. bufferedImage_ = Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  32277. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  32278. Graphics imG (bufferedImage_);
  32279. paint (imG);
  32280. }
  32281. g.setColour (Colours::black);
  32282. g.drawImageAt (bufferedImage_, 0, 0);
  32283. }
  32284. else
  32285. {
  32286. paint (g);
  32287. }
  32288. }
  32289. g.restoreState();
  32290. for (int i = 0; i < childComponentList_.size(); ++i)
  32291. {
  32292. Component* const child = childComponentList_.getUnchecked (i);
  32293. if (child->isVisible() && clipBounds.intersects (child->getBounds()))
  32294. {
  32295. g.saveState();
  32296. if (g.reduceClipRegion (child->getX(), child->getY(),
  32297. child->getWidth(), child->getHeight()))
  32298. {
  32299. for (int j = i + 1; j < childComponentList_.size(); ++j)
  32300. {
  32301. const Component* const sibling = childComponentList_.getUnchecked (j);
  32302. if (sibling->flags.opaqueFlag && sibling->isVisible())
  32303. g.excludeClipRegion (sibling->getBounds());
  32304. }
  32305. if (! g.isClipEmpty())
  32306. {
  32307. g.setOrigin (child->getX(), child->getY());
  32308. child->paintEntireComponent (g);
  32309. }
  32310. }
  32311. g.restoreState();
  32312. }
  32313. }
  32314. g.saveState();
  32315. paintOverChildren (g);
  32316. g.restoreState();
  32317. }
  32318. void Component::paintEntireComponent (Graphics& g)
  32319. {
  32320. jassert (! g.isClipEmpty());
  32321. #if JUCE_DEBUG
  32322. flags.isInsidePaintCall = true;
  32323. #endif
  32324. if (effect_ != 0)
  32325. {
  32326. Image effectImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  32327. getWidth(), getHeight(),
  32328. ! flags.opaqueFlag, Image::NativeImage);
  32329. {
  32330. Graphics g2 (effectImage);
  32331. renderComponent (g2);
  32332. }
  32333. effect_->applyEffect (effectImage, g);
  32334. }
  32335. else
  32336. {
  32337. renderComponent (g);
  32338. }
  32339. #if JUCE_DEBUG
  32340. flags.isInsidePaintCall = false;
  32341. #endif
  32342. }
  32343. const Image Component::createComponentSnapshot (const Rectangle<int>& areaToGrab,
  32344. const bool clipImageToComponentBounds)
  32345. {
  32346. Rectangle<int> r (areaToGrab);
  32347. if (clipImageToComponentBounds)
  32348. r = r.getIntersection (getLocalBounds());
  32349. Image componentImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  32350. jmax (1, r.getWidth()),
  32351. jmax (1, r.getHeight()),
  32352. true);
  32353. Graphics imageContext (componentImage);
  32354. imageContext.setOrigin (-r.getX(), -r.getY());
  32355. paintEntireComponent (imageContext);
  32356. return componentImage;
  32357. }
  32358. void Component::setComponentEffect (ImageEffectFilter* const effect)
  32359. {
  32360. if (effect_ != effect)
  32361. {
  32362. effect_ = effect;
  32363. repaint();
  32364. }
  32365. }
  32366. LookAndFeel& Component::getLookAndFeel() const throw()
  32367. {
  32368. const Component* c = this;
  32369. do
  32370. {
  32371. if (c->lookAndFeel_ != 0)
  32372. return *(c->lookAndFeel_);
  32373. c = c->parentComponent_;
  32374. }
  32375. while (c != 0);
  32376. return LookAndFeel::getDefaultLookAndFeel();
  32377. }
  32378. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  32379. {
  32380. if (lookAndFeel_ != newLookAndFeel)
  32381. {
  32382. lookAndFeel_ = newLookAndFeel;
  32383. sendLookAndFeelChange();
  32384. }
  32385. }
  32386. void Component::lookAndFeelChanged()
  32387. {
  32388. }
  32389. void Component::sendLookAndFeelChange()
  32390. {
  32391. repaint();
  32392. lookAndFeelChanged();
  32393. // (it's not a great idea to do anything that would delete this component
  32394. // during the lookAndFeelChanged() callback)
  32395. jassert (isValidComponent());
  32396. SafePointer<Component> safePointer (this);
  32397. for (int i = childComponentList_.size(); --i >= 0;)
  32398. {
  32399. childComponentList_.getUnchecked (i)->sendLookAndFeelChange();
  32400. if (safePointer == 0)
  32401. return;
  32402. i = jmin (i, childComponentList_.size());
  32403. }
  32404. }
  32405. static const Identifier getColourPropertyId (const int colourId)
  32406. {
  32407. String s;
  32408. s.preallocateStorage (18);
  32409. s << "jcclr_" << String::toHexString (colourId);
  32410. return s;
  32411. }
  32412. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const
  32413. {
  32414. var* v = properties.getItem (getColourPropertyId (colourId));
  32415. if (v != 0)
  32416. return Colour ((int) *v);
  32417. if (inheritFromParent && parentComponent_ != 0)
  32418. return parentComponent_->findColour (colourId, true);
  32419. return getLookAndFeel().findColour (colourId);
  32420. }
  32421. bool Component::isColourSpecified (const int colourId) const
  32422. {
  32423. return properties.contains (getColourPropertyId (colourId));
  32424. }
  32425. void Component::removeColour (const int colourId)
  32426. {
  32427. if (properties.remove (getColourPropertyId (colourId)))
  32428. colourChanged();
  32429. }
  32430. void Component::setColour (const int colourId, const Colour& colour)
  32431. {
  32432. if (properties.set (getColourPropertyId (colourId), (int) colour.getARGB()))
  32433. colourChanged();
  32434. }
  32435. void Component::copyAllExplicitColoursTo (Component& target) const
  32436. {
  32437. bool changed = false;
  32438. for (int i = properties.size(); --i >= 0;)
  32439. {
  32440. const Identifier name (properties.getName(i));
  32441. if (name.toString().startsWith ("jcclr_"))
  32442. if (target.properties.set (name, properties [name]))
  32443. changed = true;
  32444. }
  32445. if (changed)
  32446. target.colourChanged();
  32447. }
  32448. void Component::colourChanged()
  32449. {
  32450. }
  32451. const Rectangle<int> Component::getLocalBounds() const throw()
  32452. {
  32453. return Rectangle<int> (0, 0, getWidth(), getHeight());
  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 * (1.0f / 256.0f);
  33107. const float wheelIncrementY = amountY * (1.0f / 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. Component* const 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->isValidComponent())
  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. Component* const componentLosingFocus = currentlyFocusedComponent;
  33427. currentlyFocusedComponent = 0;
  33428. Desktop::getInstance().triggerFocusCallback();
  33429. if (componentLosingFocus->isValidComponent())
  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 (Point<int> (getWidth() / 2,
  33456. getHeight() / 2)));
  33457. }
  33458. void Component::addKeyListener (KeyListener* const newListener)
  33459. {
  33460. if (keyListeners_ == 0)
  33461. keyListeners_ = new Array <KeyListener*>();
  33462. keyListeners_->addIfNotAlreadyThere (newListener);
  33463. }
  33464. void Component::removeKeyListener (KeyListener* const listenerToRemove)
  33465. {
  33466. if (keyListeners_ != 0)
  33467. keyListeners_->removeValue (listenerToRemove);
  33468. }
  33469. bool Component::keyPressed (const KeyPress&)
  33470. {
  33471. return false;
  33472. }
  33473. bool Component::keyStateChanged (const bool /*isKeyDown*/)
  33474. {
  33475. return false;
  33476. }
  33477. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  33478. {
  33479. if (parentComponent_ != 0)
  33480. parentComponent_->modifierKeysChanged (modifiers);
  33481. }
  33482. void Component::internalModifierKeysChanged()
  33483. {
  33484. sendFakeMouseMove();
  33485. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  33486. }
  33487. ComponentPeer* Component::getPeer() const
  33488. {
  33489. if (flags.hasHeavyweightPeerFlag)
  33490. return ComponentPeer::getPeerFor (this);
  33491. else if (parentComponent_ != 0)
  33492. return parentComponent_->getPeer();
  33493. else
  33494. return 0;
  33495. }
  33496. Component::BailOutChecker::BailOutChecker (Component* const component1, Component* const component2_)
  33497. : safePointer1 (component1), safePointer2 (component2_), component2 (component2_)
  33498. {
  33499. jassert (component1 != 0);
  33500. }
  33501. bool Component::BailOutChecker::shouldBailOut() const throw()
  33502. {
  33503. return safePointer1 == 0 || safePointer2.getComponent() != component2;
  33504. }
  33505. END_JUCE_NAMESPACE
  33506. /*** End of inlined file: juce_Component.cpp ***/
  33507. /*** Start of inlined file: juce_ComponentListener.cpp ***/
  33508. BEGIN_JUCE_NAMESPACE
  33509. void ComponentListener::componentMovedOrResized (Component&, bool, bool) {}
  33510. void ComponentListener::componentBroughtToFront (Component&) {}
  33511. void ComponentListener::componentVisibilityChanged (Component&) {}
  33512. void ComponentListener::componentChildrenChanged (Component&) {}
  33513. void ComponentListener::componentParentHierarchyChanged (Component&) {}
  33514. void ComponentListener::componentNameChanged (Component&) {}
  33515. void ComponentListener::componentBeingDeleted (Component&) {}
  33516. END_JUCE_NAMESPACE
  33517. /*** End of inlined file: juce_ComponentListener.cpp ***/
  33518. /*** Start of inlined file: juce_Desktop.cpp ***/
  33519. BEGIN_JUCE_NAMESPACE
  33520. Desktop::Desktop()
  33521. : mouseClickCounter (0),
  33522. kioskModeComponent (0)
  33523. {
  33524. createMouseInputSources();
  33525. refreshMonitorSizes();
  33526. }
  33527. Desktop::~Desktop()
  33528. {
  33529. jassert (instance == this);
  33530. instance = 0;
  33531. // doh! If you don't delete all your windows before exiting, you're going to
  33532. // be leaking memory!
  33533. jassert (desktopComponents.size() == 0);
  33534. }
  33535. Desktop& JUCE_CALLTYPE Desktop::getInstance()
  33536. {
  33537. if (instance == 0)
  33538. instance = new Desktop();
  33539. return *instance;
  33540. }
  33541. Desktop* Desktop::instance = 0;
  33542. extern void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords,
  33543. const bool clipToWorkArea);
  33544. void Desktop::refreshMonitorSizes()
  33545. {
  33546. const Array <Rectangle<int> > oldClipped (monitorCoordsClipped);
  33547. const Array <Rectangle<int> > oldUnclipped (monitorCoordsUnclipped);
  33548. monitorCoordsClipped.clear();
  33549. monitorCoordsUnclipped.clear();
  33550. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  33551. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  33552. jassert (monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  33553. if (oldClipped != monitorCoordsClipped
  33554. || oldUnclipped != monitorCoordsUnclipped)
  33555. {
  33556. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  33557. {
  33558. ComponentPeer* const p = ComponentPeer::getPeer (i);
  33559. if (p != 0)
  33560. p->handleScreenSizeChange();
  33561. }
  33562. }
  33563. }
  33564. int Desktop::getNumDisplayMonitors() const throw()
  33565. {
  33566. return monitorCoordsClipped.size();
  33567. }
  33568. const Rectangle<int> Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  33569. {
  33570. return clippedToWorkArea ? monitorCoordsClipped [index]
  33571. : monitorCoordsUnclipped [index];
  33572. }
  33573. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  33574. {
  33575. RectangleList rl;
  33576. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  33577. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  33578. return rl;
  33579. }
  33580. const Rectangle<int> Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  33581. {
  33582. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  33583. }
  33584. const Rectangle<int> Desktop::getMonitorAreaContaining (const Point<int>& position, const bool clippedToWorkArea) const
  33585. {
  33586. Rectangle<int> best (getMainMonitorArea (clippedToWorkArea));
  33587. double bestDistance = 1.0e10;
  33588. for (int i = getNumDisplayMonitors(); --i >= 0;)
  33589. {
  33590. const Rectangle<int> rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  33591. if (rect.contains (position))
  33592. return rect;
  33593. const double distance = rect.getCentre().getDistanceFrom (position);
  33594. if (distance < bestDistance)
  33595. {
  33596. bestDistance = distance;
  33597. best = rect;
  33598. }
  33599. }
  33600. return best;
  33601. }
  33602. int Desktop::getNumComponents() const throw()
  33603. {
  33604. return desktopComponents.size();
  33605. }
  33606. Component* Desktop::getComponent (const int index) const throw()
  33607. {
  33608. return desktopComponents [index];
  33609. }
  33610. Component* Desktop::findComponentAt (const Point<int>& screenPosition) const
  33611. {
  33612. for (int i = desktopComponents.size(); --i >= 0;)
  33613. {
  33614. Component* const c = desktopComponents.getUnchecked(i);
  33615. const Point<int> relative (c->globalPositionToRelative (screenPosition));
  33616. if (c->contains (relative.getX(), relative.getY()))
  33617. return c->getComponentAt (relative.getX(), relative.getY());
  33618. }
  33619. return 0;
  33620. }
  33621. void Desktop::addDesktopComponent (Component* const c)
  33622. {
  33623. jassert (c != 0);
  33624. jassert (! desktopComponents.contains (c));
  33625. desktopComponents.addIfNotAlreadyThere (c);
  33626. }
  33627. void Desktop::removeDesktopComponent (Component* const c)
  33628. {
  33629. desktopComponents.removeValue (c);
  33630. }
  33631. void Desktop::componentBroughtToFront (Component* const c)
  33632. {
  33633. const int index = desktopComponents.indexOf (c);
  33634. jassert (index >= 0);
  33635. if (index >= 0)
  33636. {
  33637. int newIndex = -1;
  33638. if (! c->isAlwaysOnTop())
  33639. {
  33640. newIndex = desktopComponents.size();
  33641. while (newIndex > 0 && desktopComponents.getUnchecked (newIndex - 1)->isAlwaysOnTop())
  33642. --newIndex;
  33643. --newIndex;
  33644. }
  33645. desktopComponents.move (index, newIndex);
  33646. }
  33647. }
  33648. const Point<int> Desktop::getLastMouseDownPosition() throw()
  33649. {
  33650. return getInstance().getMainMouseSource().getLastMouseDownPosition();
  33651. }
  33652. int Desktop::getMouseButtonClickCounter() throw()
  33653. {
  33654. return getInstance().mouseClickCounter;
  33655. }
  33656. void Desktop::incrementMouseClickCounter() throw()
  33657. {
  33658. ++mouseClickCounter;
  33659. }
  33660. int Desktop::getNumDraggingMouseSources() const throw()
  33661. {
  33662. int num = 0;
  33663. for (int i = mouseSources.size(); --i >= 0;)
  33664. if (mouseSources.getUnchecked(i)->isDragging())
  33665. ++num;
  33666. return num;
  33667. }
  33668. MouseInputSource* Desktop::getDraggingMouseSource (int index) const throw()
  33669. {
  33670. int num = 0;
  33671. for (int i = mouseSources.size(); --i >= 0;)
  33672. {
  33673. MouseInputSource* const mi = mouseSources.getUnchecked(i);
  33674. if (mi->isDragging())
  33675. {
  33676. if (index == num)
  33677. return mi;
  33678. ++num;
  33679. }
  33680. }
  33681. return 0;
  33682. }
  33683. void Desktop::addFocusChangeListener (FocusChangeListener* const listener)
  33684. {
  33685. focusListeners.add (listener);
  33686. }
  33687. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener)
  33688. {
  33689. focusListeners.remove (listener);
  33690. }
  33691. void Desktop::triggerFocusCallback()
  33692. {
  33693. triggerAsyncUpdate();
  33694. }
  33695. void Desktop::handleAsyncUpdate()
  33696. {
  33697. Component* currentFocus = Component::getCurrentlyFocusedComponent();
  33698. focusListeners.call (&FocusChangeListener::globalFocusChanged, currentFocus);
  33699. }
  33700. void Desktop::addGlobalMouseListener (MouseListener* const listener)
  33701. {
  33702. mouseListeners.add (listener);
  33703. resetTimer();
  33704. }
  33705. void Desktop::removeGlobalMouseListener (MouseListener* const listener)
  33706. {
  33707. mouseListeners.remove (listener);
  33708. resetTimer();
  33709. }
  33710. void Desktop::timerCallback()
  33711. {
  33712. if (lastFakeMouseMove != getMousePosition())
  33713. sendMouseMove();
  33714. }
  33715. void Desktop::sendMouseMove()
  33716. {
  33717. if (! mouseListeners.isEmpty())
  33718. {
  33719. startTimer (20);
  33720. lastFakeMouseMove = getMousePosition();
  33721. Component* const target = findComponentAt (lastFakeMouseMove);
  33722. if (target != 0)
  33723. {
  33724. Component::BailOutChecker checker (target);
  33725. const Point<int> pos (target->globalPositionToRelative (lastFakeMouseMove));
  33726. const Time now (Time::getCurrentTime());
  33727. const MouseEvent me (getMainMouseSource(), pos, ModifierKeys::getCurrentModifiers(),
  33728. target, target, now, pos, now, 0, false);
  33729. if (me.mods.isAnyMouseButtonDown())
  33730. mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  33731. else
  33732. mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  33733. }
  33734. }
  33735. }
  33736. void Desktop::resetTimer()
  33737. {
  33738. if (mouseListeners.size() == 0)
  33739. stopTimer();
  33740. else
  33741. startTimer (100);
  33742. lastFakeMouseMove = getMousePosition();
  33743. }
  33744. extern void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  33745. void Desktop::setKioskModeComponent (Component* componentToUse, const bool allowMenusAndBars)
  33746. {
  33747. if (kioskModeComponent != componentToUse)
  33748. {
  33749. // agh! Don't delete a component without first stopping it being the kiosk comp
  33750. jassert (kioskModeComponent == 0 || kioskModeComponent->isValidComponent());
  33751. // agh! Don't remove a component from the desktop if it's the kiosk comp!
  33752. jassert (kioskModeComponent == 0 || kioskModeComponent->isOnDesktop());
  33753. if (kioskModeComponent->isValidComponent())
  33754. {
  33755. juce_setKioskComponent (kioskModeComponent, false, allowMenusAndBars);
  33756. kioskModeComponent->setBounds (kioskComponentOriginalBounds);
  33757. }
  33758. kioskModeComponent = componentToUse;
  33759. if (kioskModeComponent != 0)
  33760. {
  33761. jassert (kioskModeComponent->isValidComponent());
  33762. // Only components that are already on the desktop can be put into kiosk mode!
  33763. jassert (kioskModeComponent->isOnDesktop());
  33764. kioskComponentOriginalBounds = kioskModeComponent->getBounds();
  33765. juce_setKioskComponent (kioskModeComponent, true, allowMenusAndBars);
  33766. }
  33767. }
  33768. }
  33769. END_JUCE_NAMESPACE
  33770. /*** End of inlined file: juce_Desktop.cpp ***/
  33771. /*** Start of inlined file: juce_ModalComponentManager.cpp ***/
  33772. BEGIN_JUCE_NAMESPACE
  33773. class ModalComponentManager::ModalItem : public ComponentListener
  33774. {
  33775. public:
  33776. ModalItem (Component* const comp, Callback* const callback)
  33777. : component (comp), returnValue (0), isActive (true), isDeleted (false)
  33778. {
  33779. if (callback != 0)
  33780. callbacks.add (callback);
  33781. jassert (comp != 0);
  33782. component->addComponentListener (this);
  33783. }
  33784. ~ModalItem()
  33785. {
  33786. if (! isDeleted)
  33787. component->removeComponentListener (this);
  33788. }
  33789. void componentBeingDeleted (Component&)
  33790. {
  33791. isDeleted = true;
  33792. cancel();
  33793. }
  33794. void componentVisibilityChanged (Component&)
  33795. {
  33796. if (! component->isShowing())
  33797. cancel();
  33798. }
  33799. void componentParentHierarchyChanged (Component&)
  33800. {
  33801. if (! component->isShowing())
  33802. cancel();
  33803. }
  33804. void cancel()
  33805. {
  33806. if (isActive)
  33807. {
  33808. isActive = false;
  33809. ModalComponentManager::getInstance()->triggerAsyncUpdate();
  33810. }
  33811. }
  33812. Component* component;
  33813. OwnedArray<Callback> callbacks;
  33814. int returnValue;
  33815. bool isActive, isDeleted;
  33816. private:
  33817. ModalItem (const ModalItem&);
  33818. ModalItem& operator= (const ModalItem&);
  33819. };
  33820. ModalComponentManager::ModalComponentManager()
  33821. {
  33822. }
  33823. ModalComponentManager::~ModalComponentManager()
  33824. {
  33825. clearSingletonInstance();
  33826. }
  33827. juce_ImplementSingleton_SingleThreaded (ModalComponentManager);
  33828. void ModalComponentManager::startModal (Component* component, Callback* callback)
  33829. {
  33830. if (component != 0)
  33831. stack.add (new ModalItem (component, callback));
  33832. }
  33833. void ModalComponentManager::attachCallback (Component* component, Callback* callback)
  33834. {
  33835. if (callback != 0)
  33836. {
  33837. ScopedPointer<Callback> callbackDeleter (callback);
  33838. for (int i = stack.size(); --i >= 0;)
  33839. {
  33840. ModalItem* const item = stack.getUnchecked(i);
  33841. if (item->component == component)
  33842. {
  33843. item->callbacks.add (callback);
  33844. callbackDeleter.release();
  33845. break;
  33846. }
  33847. }
  33848. }
  33849. }
  33850. void ModalComponentManager::endModal (Component* component)
  33851. {
  33852. for (int i = stack.size(); --i >= 0;)
  33853. {
  33854. ModalItem* const item = stack.getUnchecked(i);
  33855. if (item->component == component)
  33856. item->cancel();
  33857. }
  33858. }
  33859. void ModalComponentManager::endModal (Component* component, int returnValue)
  33860. {
  33861. for (int i = stack.size(); --i >= 0;)
  33862. {
  33863. ModalItem* const item = stack.getUnchecked(i);
  33864. if (item->component == component)
  33865. {
  33866. item->returnValue = returnValue;
  33867. item->cancel();
  33868. }
  33869. }
  33870. }
  33871. int ModalComponentManager::getNumModalComponents() const
  33872. {
  33873. int n = 0;
  33874. for (int i = 0; i < stack.size(); ++i)
  33875. if (stack.getUnchecked(i)->isActive)
  33876. ++n;
  33877. return n;
  33878. }
  33879. Component* ModalComponentManager::getModalComponent (const int index) const
  33880. {
  33881. int n = 0;
  33882. for (int i = stack.size(); --i >= 0;)
  33883. {
  33884. const ModalItem* const item = stack.getUnchecked(i);
  33885. if (item->isActive)
  33886. if (n++ == index)
  33887. return item->component;
  33888. }
  33889. return 0;
  33890. }
  33891. bool ModalComponentManager::isModal (Component* const comp) const
  33892. {
  33893. for (int i = stack.size(); --i >= 0;)
  33894. {
  33895. const ModalItem* const item = stack.getUnchecked(i);
  33896. if (item->isActive && item->component == comp)
  33897. return true;
  33898. }
  33899. return false;
  33900. }
  33901. bool ModalComponentManager::isFrontModalComponent (Component* const comp) const
  33902. {
  33903. return comp == getModalComponent (0);
  33904. }
  33905. void ModalComponentManager::handleAsyncUpdate()
  33906. {
  33907. for (int i = stack.size(); --i >= 0;)
  33908. {
  33909. const ModalItem* const item = stack.getUnchecked(i);
  33910. if (! item->isActive)
  33911. {
  33912. for (int j = item->callbacks.size(); --j >= 0;)
  33913. item->callbacks.getUnchecked(j)->modalStateFinished (item->returnValue);
  33914. stack.remove (i);
  33915. }
  33916. }
  33917. }
  33918. class ModalComponentManager::ReturnValueRetriever : public ModalComponentManager::Callback
  33919. {
  33920. public:
  33921. ReturnValueRetriever (int& value_, bool& finished_) : value (value_), finished (finished_) {}
  33922. ~ReturnValueRetriever() {}
  33923. void modalStateFinished (int returnValue)
  33924. {
  33925. finished = true;
  33926. value = returnValue;
  33927. }
  33928. private:
  33929. int& value;
  33930. bool& finished;
  33931. ReturnValueRetriever (const ReturnValueRetriever&);
  33932. ReturnValueRetriever& operator= (const ReturnValueRetriever&);
  33933. };
  33934. int ModalComponentManager::runEventLoopForCurrentComponent()
  33935. {
  33936. // This can only be run from the message thread!
  33937. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  33938. Component* currentlyModal = getModalComponent (0);
  33939. if (currentlyModal == 0)
  33940. return 0;
  33941. Component::SafePointer<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  33942. int returnValue = 0;
  33943. bool finished = false;
  33944. attachCallback (currentlyModal, new ReturnValueRetriever (returnValue, finished));
  33945. JUCE_TRY
  33946. {
  33947. while (! finished)
  33948. {
  33949. if (! MessageManager::getInstance()->runDispatchLoopUntil (20))
  33950. break;
  33951. }
  33952. }
  33953. JUCE_CATCH_EXCEPTION
  33954. if (prevFocused != 0)
  33955. prevFocused->grabKeyboardFocus();
  33956. return returnValue;
  33957. }
  33958. END_JUCE_NAMESPACE
  33959. /*** End of inlined file: juce_ModalComponentManager.cpp ***/
  33960. /*** Start of inlined file: juce_ArrowButton.cpp ***/
  33961. BEGIN_JUCE_NAMESPACE
  33962. ArrowButton::ArrowButton (const String& name,
  33963. float arrowDirectionInRadians,
  33964. const Colour& arrowColour)
  33965. : Button (name),
  33966. colour (arrowColour)
  33967. {
  33968. path.lineTo (0.0f, 1.0f);
  33969. path.lineTo (1.0f, 0.5f);
  33970. path.closeSubPath();
  33971. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  33972. 0.5f, 0.5f));
  33973. setComponentEffect (&shadow);
  33974. buttonStateChanged();
  33975. }
  33976. ArrowButton::~ArrowButton()
  33977. {
  33978. }
  33979. void ArrowButton::paintButton (Graphics& g,
  33980. bool /*isMouseOverButton*/,
  33981. bool /*isButtonDown*/)
  33982. {
  33983. g.setColour (colour);
  33984. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  33985. (float) offset,
  33986. (float) (getWidth() - 3),
  33987. (float) (getHeight() - 3),
  33988. false));
  33989. }
  33990. void ArrowButton::buttonStateChanged()
  33991. {
  33992. offset = (isDown()) ? 1 : 0;
  33993. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  33994. 0.3f, -1, 0);
  33995. }
  33996. END_JUCE_NAMESPACE
  33997. /*** End of inlined file: juce_ArrowButton.cpp ***/
  33998. /*** Start of inlined file: juce_Button.cpp ***/
  33999. BEGIN_JUCE_NAMESPACE
  34000. class Button::RepeatTimer : public Timer
  34001. {
  34002. public:
  34003. RepeatTimer (Button& owner_) : owner (owner_) {}
  34004. void timerCallback() { owner.repeatTimerCallback(); }
  34005. juce_UseDebuggingNewOperator
  34006. private:
  34007. Button& owner;
  34008. RepeatTimer (const RepeatTimer&);
  34009. RepeatTimer& operator= (const RepeatTimer&);
  34010. };
  34011. Button::Button (const String& name)
  34012. : Component (name),
  34013. text (name),
  34014. buttonPressTime (0),
  34015. lastTimeCallbackTime (0),
  34016. commandManagerToUse (0),
  34017. autoRepeatDelay (-1),
  34018. autoRepeatSpeed (0),
  34019. autoRepeatMinimumDelay (-1),
  34020. radioGroupId (0),
  34021. commandID (0),
  34022. connectedEdgeFlags (0),
  34023. buttonState (buttonNormal),
  34024. lastToggleState (false),
  34025. clickTogglesState (false),
  34026. needsToRelease (false),
  34027. needsRepainting (false),
  34028. isKeyDown (false),
  34029. triggerOnMouseDown (false),
  34030. generateTooltip (false)
  34031. {
  34032. setWantsKeyboardFocus (true);
  34033. isOn.addListener (this);
  34034. }
  34035. Button::~Button()
  34036. {
  34037. isOn.removeListener (this);
  34038. if (commandManagerToUse != 0)
  34039. commandManagerToUse->removeListener (this);
  34040. repeatTimer = 0;
  34041. clearShortcuts();
  34042. }
  34043. void Button::setButtonText (const String& newText)
  34044. {
  34045. if (text != newText)
  34046. {
  34047. text = newText;
  34048. repaint();
  34049. }
  34050. }
  34051. void Button::setTooltip (const String& newTooltip)
  34052. {
  34053. SettableTooltipClient::setTooltip (newTooltip);
  34054. generateTooltip = false;
  34055. }
  34056. const String Button::getTooltip()
  34057. {
  34058. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  34059. {
  34060. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  34061. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  34062. for (int i = 0; i < keyPresses.size(); ++i)
  34063. {
  34064. const String key (keyPresses.getReference(i).getTextDescription());
  34065. tt << " [";
  34066. if (key.length() == 1)
  34067. tt << TRANS("shortcut") << ": '" << key << "']";
  34068. else
  34069. tt << key << ']';
  34070. }
  34071. return tt;
  34072. }
  34073. return SettableTooltipClient::getTooltip();
  34074. }
  34075. void Button::setConnectedEdges (const int connectedEdgeFlags_)
  34076. {
  34077. if (connectedEdgeFlags != connectedEdgeFlags_)
  34078. {
  34079. connectedEdgeFlags = connectedEdgeFlags_;
  34080. repaint();
  34081. }
  34082. }
  34083. void Button::setToggleState (const bool shouldBeOn,
  34084. const bool sendChangeNotification)
  34085. {
  34086. if (shouldBeOn != lastToggleState)
  34087. {
  34088. if (isOn != shouldBeOn) // this test means that if the value is void rather than explicitly set to
  34089. isOn = shouldBeOn; // false, it won't be changed unless the required value is true.
  34090. lastToggleState = shouldBeOn;
  34091. repaint();
  34092. if (sendChangeNotification)
  34093. {
  34094. Component::SafePointer<Component> deletionWatcher (this);
  34095. sendClickMessage (ModifierKeys());
  34096. if (deletionWatcher == 0)
  34097. return;
  34098. }
  34099. if (lastToggleState)
  34100. turnOffOtherButtonsInGroup (sendChangeNotification);
  34101. }
  34102. }
  34103. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  34104. {
  34105. clickTogglesState = shouldToggle;
  34106. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  34107. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  34108. // it is that this button represents, and the button will update its state to reflect this
  34109. // in the applicationCommandListChanged() method.
  34110. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  34111. }
  34112. bool Button::getClickingTogglesState() const throw()
  34113. {
  34114. return clickTogglesState;
  34115. }
  34116. void Button::valueChanged (Value& value)
  34117. {
  34118. if (value.refersToSameSourceAs (isOn))
  34119. setToggleState (isOn.getValue(), true);
  34120. }
  34121. void Button::setRadioGroupId (const int newGroupId)
  34122. {
  34123. if (radioGroupId != newGroupId)
  34124. {
  34125. radioGroupId = newGroupId;
  34126. if (lastToggleState)
  34127. turnOffOtherButtonsInGroup (true);
  34128. }
  34129. }
  34130. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  34131. {
  34132. Component* const p = getParentComponent();
  34133. if (p != 0 && radioGroupId != 0)
  34134. {
  34135. Component::SafePointer<Component> deletionWatcher (this);
  34136. for (int i = p->getNumChildComponents(); --i >= 0;)
  34137. {
  34138. Component* const c = p->getChildComponent (i);
  34139. if (c != this)
  34140. {
  34141. Button* const b = dynamic_cast <Button*> (c);
  34142. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  34143. {
  34144. b->setToggleState (false, sendChangeNotification);
  34145. if (deletionWatcher == 0)
  34146. return;
  34147. }
  34148. }
  34149. }
  34150. }
  34151. }
  34152. void Button::enablementChanged()
  34153. {
  34154. updateState (0);
  34155. repaint();
  34156. }
  34157. Button::ButtonState Button::updateState (const MouseEvent* const e)
  34158. {
  34159. ButtonState state = buttonNormal;
  34160. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  34161. {
  34162. Point<int> mousePos;
  34163. if (e == 0)
  34164. mousePos = getMouseXYRelative();
  34165. else
  34166. mousePos = e->getEventRelativeTo (this).getPosition();
  34167. const bool over = reallyContains (mousePos.getX(), mousePos.getY(), true);
  34168. const bool down = isMouseButtonDown();
  34169. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  34170. state = buttonDown;
  34171. else if (over)
  34172. state = buttonOver;
  34173. }
  34174. setState (state);
  34175. return state;
  34176. }
  34177. void Button::setState (const ButtonState newState)
  34178. {
  34179. if (buttonState != newState)
  34180. {
  34181. buttonState = newState;
  34182. repaint();
  34183. if (buttonState == buttonDown)
  34184. {
  34185. buttonPressTime = Time::getApproximateMillisecondCounter();
  34186. lastTimeCallbackTime = buttonPressTime;
  34187. }
  34188. sendStateMessage();
  34189. }
  34190. }
  34191. bool Button::isDown() const throw()
  34192. {
  34193. return buttonState == buttonDown;
  34194. }
  34195. bool Button::isOver() const throw()
  34196. {
  34197. return buttonState != buttonNormal;
  34198. }
  34199. void Button::buttonStateChanged()
  34200. {
  34201. }
  34202. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  34203. {
  34204. const uint32 now = Time::getApproximateMillisecondCounter();
  34205. return now > buttonPressTime ? now - buttonPressTime : 0;
  34206. }
  34207. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  34208. {
  34209. triggerOnMouseDown = isTriggeredOnMouseDown;
  34210. }
  34211. void Button::clicked()
  34212. {
  34213. }
  34214. void Button::clicked (const ModifierKeys& /*modifiers*/)
  34215. {
  34216. clicked();
  34217. }
  34218. static const int clickMessageId = 0x2f3f4f99;
  34219. void Button::triggerClick()
  34220. {
  34221. postCommandMessage (clickMessageId);
  34222. }
  34223. void Button::internalClickCallback (const ModifierKeys& modifiers)
  34224. {
  34225. if (clickTogglesState)
  34226. setToggleState ((radioGroupId != 0) || ! lastToggleState, false);
  34227. sendClickMessage (modifiers);
  34228. }
  34229. void Button::flashButtonState()
  34230. {
  34231. if (isEnabled())
  34232. {
  34233. needsToRelease = true;
  34234. setState (buttonDown);
  34235. getRepeatTimer().startTimer (100);
  34236. }
  34237. }
  34238. void Button::handleCommandMessage (int commandId)
  34239. {
  34240. if (commandId == clickMessageId)
  34241. {
  34242. if (isEnabled())
  34243. {
  34244. flashButtonState();
  34245. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34246. }
  34247. }
  34248. else
  34249. {
  34250. Component::handleCommandMessage (commandId);
  34251. }
  34252. }
  34253. void Button::addButtonListener (ButtonListener* const newListener)
  34254. {
  34255. buttonListeners.add (newListener);
  34256. }
  34257. void Button::removeButtonListener (ButtonListener* const listener)
  34258. {
  34259. buttonListeners.remove (listener);
  34260. }
  34261. void Button::sendClickMessage (const ModifierKeys& modifiers)
  34262. {
  34263. Component::BailOutChecker checker (this);
  34264. if (commandManagerToUse != 0 && commandID != 0)
  34265. {
  34266. ApplicationCommandTarget::InvocationInfo info (commandID);
  34267. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  34268. info.originatingComponent = this;
  34269. commandManagerToUse->invoke (info, true);
  34270. }
  34271. clicked (modifiers);
  34272. if (! checker.shouldBailOut())
  34273. buttonListeners.callChecked (checker, &ButtonListener::buttonClicked, this);
  34274. }
  34275. void Button::sendStateMessage()
  34276. {
  34277. Component::BailOutChecker checker (this);
  34278. buttonStateChanged();
  34279. if (! checker.shouldBailOut())
  34280. buttonListeners.callChecked (checker, &ButtonListener::buttonStateChanged, this);
  34281. }
  34282. void Button::paint (Graphics& g)
  34283. {
  34284. if (needsToRelease && isEnabled())
  34285. {
  34286. needsToRelease = false;
  34287. needsRepainting = true;
  34288. }
  34289. paintButton (g, isOver(), isDown());
  34290. }
  34291. void Button::mouseEnter (const MouseEvent& e)
  34292. {
  34293. updateState (&e);
  34294. }
  34295. void Button::mouseExit (const MouseEvent& e)
  34296. {
  34297. updateState (&e);
  34298. }
  34299. void Button::mouseDown (const MouseEvent& e)
  34300. {
  34301. updateState (&e);
  34302. if (isDown())
  34303. {
  34304. if (autoRepeatDelay >= 0)
  34305. getRepeatTimer().startTimer (autoRepeatDelay);
  34306. if (triggerOnMouseDown)
  34307. internalClickCallback (e.mods);
  34308. }
  34309. }
  34310. void Button::mouseUp (const MouseEvent& e)
  34311. {
  34312. const bool wasDown = isDown();
  34313. updateState (&e);
  34314. if (wasDown && isOver() && ! triggerOnMouseDown)
  34315. internalClickCallback (e.mods);
  34316. }
  34317. void Button::mouseDrag (const MouseEvent& e)
  34318. {
  34319. const ButtonState oldState = buttonState;
  34320. updateState (&e);
  34321. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  34322. getRepeatTimer().startTimer (autoRepeatSpeed);
  34323. }
  34324. void Button::focusGained (FocusChangeType)
  34325. {
  34326. updateState (0);
  34327. repaint();
  34328. }
  34329. void Button::focusLost (FocusChangeType)
  34330. {
  34331. updateState (0);
  34332. repaint();
  34333. }
  34334. void Button::setVisible (bool shouldBeVisible)
  34335. {
  34336. if (shouldBeVisible != isVisible())
  34337. {
  34338. Component::setVisible (shouldBeVisible);
  34339. if (! shouldBeVisible)
  34340. needsToRelease = false;
  34341. updateState (0);
  34342. }
  34343. else
  34344. {
  34345. Component::setVisible (shouldBeVisible);
  34346. }
  34347. }
  34348. void Button::parentHierarchyChanged()
  34349. {
  34350. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  34351. if (newKeySource != keySource.getComponent())
  34352. {
  34353. if (keySource != 0)
  34354. keySource->removeKeyListener (this);
  34355. keySource = newKeySource;
  34356. if (keySource != 0)
  34357. keySource->addKeyListener (this);
  34358. }
  34359. }
  34360. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  34361. const int commandID_,
  34362. const bool generateTooltip_)
  34363. {
  34364. commandID = commandID_;
  34365. generateTooltip = generateTooltip_;
  34366. if (commandManagerToUse != commandManagerToUse_)
  34367. {
  34368. if (commandManagerToUse != 0)
  34369. commandManagerToUse->removeListener (this);
  34370. commandManagerToUse = commandManagerToUse_;
  34371. if (commandManagerToUse != 0)
  34372. commandManagerToUse->addListener (this);
  34373. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  34374. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  34375. // it is that this button represents, and the button will update its state to reflect this
  34376. // in the applicationCommandListChanged() method.
  34377. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  34378. }
  34379. if (commandManagerToUse != 0)
  34380. applicationCommandListChanged();
  34381. else
  34382. setEnabled (true);
  34383. }
  34384. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  34385. {
  34386. if (info.commandID == commandID
  34387. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  34388. {
  34389. flashButtonState();
  34390. }
  34391. }
  34392. void Button::applicationCommandListChanged()
  34393. {
  34394. if (commandManagerToUse != 0)
  34395. {
  34396. ApplicationCommandInfo info (0);
  34397. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  34398. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  34399. if (target != 0)
  34400. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  34401. }
  34402. }
  34403. void Button::addShortcut (const KeyPress& key)
  34404. {
  34405. if (key.isValid())
  34406. {
  34407. jassert (! isRegisteredForShortcut (key)); // already registered!
  34408. shortcuts.add (key);
  34409. parentHierarchyChanged();
  34410. }
  34411. }
  34412. void Button::clearShortcuts()
  34413. {
  34414. shortcuts.clear();
  34415. parentHierarchyChanged();
  34416. }
  34417. bool Button::isShortcutPressed() const
  34418. {
  34419. if (! isCurrentlyBlockedByAnotherModalComponent())
  34420. {
  34421. for (int i = shortcuts.size(); --i >= 0;)
  34422. if (shortcuts.getReference(i).isCurrentlyDown())
  34423. return true;
  34424. }
  34425. return false;
  34426. }
  34427. bool Button::isRegisteredForShortcut (const KeyPress& key) const
  34428. {
  34429. for (int i = shortcuts.size(); --i >= 0;)
  34430. if (key == shortcuts.getReference(i))
  34431. return true;
  34432. return false;
  34433. }
  34434. bool Button::keyStateChanged (const bool, Component*)
  34435. {
  34436. if (! isEnabled())
  34437. return false;
  34438. const bool wasDown = isKeyDown;
  34439. isKeyDown = isShortcutPressed();
  34440. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  34441. getRepeatTimer().startTimer (autoRepeatDelay);
  34442. updateState (0);
  34443. if (isEnabled() && wasDown && ! isKeyDown)
  34444. {
  34445. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34446. // (return immediately - this button may now have been deleted)
  34447. return true;
  34448. }
  34449. return wasDown || isKeyDown;
  34450. }
  34451. bool Button::keyPressed (const KeyPress&, Component*)
  34452. {
  34453. // returning true will avoid forwarding events for keys that we're using as shortcuts
  34454. return isShortcutPressed();
  34455. }
  34456. bool Button::keyPressed (const KeyPress& key)
  34457. {
  34458. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  34459. {
  34460. triggerClick();
  34461. return true;
  34462. }
  34463. return false;
  34464. }
  34465. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  34466. const int repeatMillisecs,
  34467. const int minimumDelayInMillisecs) throw()
  34468. {
  34469. autoRepeatDelay = initialDelayMillisecs;
  34470. autoRepeatSpeed = repeatMillisecs;
  34471. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  34472. }
  34473. void Button::repeatTimerCallback()
  34474. {
  34475. if (needsRepainting)
  34476. {
  34477. getRepeatTimer().stopTimer();
  34478. updateState (0);
  34479. needsRepainting = false;
  34480. }
  34481. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState (0) == buttonDown)))
  34482. {
  34483. int repeatSpeed = autoRepeatSpeed;
  34484. if (autoRepeatMinimumDelay >= 0)
  34485. {
  34486. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  34487. timeHeldDown *= timeHeldDown;
  34488. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  34489. }
  34490. repeatSpeed = jmax (1, repeatSpeed);
  34491. getRepeatTimer().startTimer (repeatSpeed);
  34492. const uint32 now = Time::getApproximateMillisecondCounter();
  34493. const int numTimesToCallback = (now > lastTimeCallbackTime) ? jmax (1, (int) (now - lastTimeCallbackTime) / repeatSpeed) : 1;
  34494. lastTimeCallbackTime = now;
  34495. Component::SafePointer<Component> deletionWatcher (this);
  34496. for (int i = numTimesToCallback; --i >= 0;)
  34497. {
  34498. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34499. if (deletionWatcher == 0 || ! isDown())
  34500. return;
  34501. }
  34502. }
  34503. else if (! needsToRelease)
  34504. {
  34505. getRepeatTimer().stopTimer();
  34506. }
  34507. }
  34508. Button::RepeatTimer& Button::getRepeatTimer()
  34509. {
  34510. if (repeatTimer == 0)
  34511. repeatTimer = new RepeatTimer (*this);
  34512. return *repeatTimer;
  34513. }
  34514. END_JUCE_NAMESPACE
  34515. /*** End of inlined file: juce_Button.cpp ***/
  34516. /*** Start of inlined file: juce_DrawableButton.cpp ***/
  34517. BEGIN_JUCE_NAMESPACE
  34518. DrawableButton::DrawableButton (const String& name,
  34519. const DrawableButton::ButtonStyle buttonStyle)
  34520. : Button (name),
  34521. style (buttonStyle),
  34522. edgeIndent (3)
  34523. {
  34524. if (buttonStyle == ImageOnButtonBackground)
  34525. {
  34526. backgroundOff = Colour (0xffbbbbff);
  34527. backgroundOn = Colour (0xff3333ff);
  34528. }
  34529. else
  34530. {
  34531. backgroundOff = Colours::transparentBlack;
  34532. backgroundOn = Colour (0xaabbbbff);
  34533. }
  34534. }
  34535. DrawableButton::~DrawableButton()
  34536. {
  34537. deleteImages();
  34538. }
  34539. void DrawableButton::deleteImages()
  34540. {
  34541. }
  34542. void DrawableButton::setImages (const Drawable* normal,
  34543. const Drawable* over,
  34544. const Drawable* down,
  34545. const Drawable* disabled,
  34546. const Drawable* normalOn,
  34547. const Drawable* overOn,
  34548. const Drawable* downOn,
  34549. const Drawable* disabledOn)
  34550. {
  34551. deleteImages();
  34552. jassert (normal != 0); // you really need to give it at least a normal image..
  34553. if (normal != 0)
  34554. normalImage = normal->createCopy();
  34555. if (over != 0)
  34556. overImage = over->createCopy();
  34557. if (down != 0)
  34558. downImage = down->createCopy();
  34559. if (disabled != 0)
  34560. disabledImage = disabled->createCopy();
  34561. if (normalOn != 0)
  34562. normalImageOn = normalOn->createCopy();
  34563. if (overOn != 0)
  34564. overImageOn = overOn->createCopy();
  34565. if (downOn != 0)
  34566. downImageOn = downOn->createCopy();
  34567. if (disabledOn != 0)
  34568. disabledImageOn = disabledOn->createCopy();
  34569. repaint();
  34570. }
  34571. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  34572. {
  34573. if (style != newStyle)
  34574. {
  34575. style = newStyle;
  34576. repaint();
  34577. }
  34578. }
  34579. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  34580. const Colour& toggledOnColour)
  34581. {
  34582. if (backgroundOff != toggledOffColour
  34583. || backgroundOn != toggledOnColour)
  34584. {
  34585. backgroundOff = toggledOffColour;
  34586. backgroundOn = toggledOnColour;
  34587. repaint();
  34588. }
  34589. }
  34590. const Colour& DrawableButton::getBackgroundColour() const throw()
  34591. {
  34592. return getToggleState() ? backgroundOn
  34593. : backgroundOff;
  34594. }
  34595. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  34596. {
  34597. edgeIndent = numPixelsIndent;
  34598. repaint();
  34599. }
  34600. void DrawableButton::paintButton (Graphics& g,
  34601. bool isMouseOverButton,
  34602. bool isButtonDown)
  34603. {
  34604. Rectangle<int> imageSpace;
  34605. if (style == ImageOnButtonBackground)
  34606. {
  34607. const int insetX = getWidth() / 4;
  34608. const int insetY = getHeight() / 4;
  34609. imageSpace.setBounds (insetX, insetY, getWidth() - insetX * 2, getHeight() - insetY * 2);
  34610. getLookAndFeel().drawButtonBackground (g, *this,
  34611. getBackgroundColour(),
  34612. isMouseOverButton,
  34613. isButtonDown);
  34614. }
  34615. else
  34616. {
  34617. g.fillAll (getBackgroundColour());
  34618. const int textH = (style == ImageAboveTextLabel)
  34619. ? jmin (16, proportionOfHeight (0.25f))
  34620. : 0;
  34621. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  34622. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  34623. imageSpace.setBounds (indentX, indentY,
  34624. getWidth() - indentX * 2,
  34625. getHeight() - indentY * 2 - textH);
  34626. if (textH > 0)
  34627. {
  34628. g.setFont ((float) textH);
  34629. g.setColour (Colours::black.withAlpha (isEnabled() ? 1.0f : 0.4f));
  34630. g.drawFittedText (getButtonText(),
  34631. 2, getHeight() - textH - 1,
  34632. getWidth() - 4, textH,
  34633. Justification::centred, 1);
  34634. }
  34635. }
  34636. g.setImageResamplingQuality (Graphics::mediumResamplingQuality);
  34637. g.setOpacity (1.0f);
  34638. const Drawable* imageToDraw = 0;
  34639. if (isEnabled())
  34640. {
  34641. imageToDraw = getCurrentImage();
  34642. }
  34643. else
  34644. {
  34645. imageToDraw = getToggleState() ? disabledImageOn
  34646. : disabledImage;
  34647. if (imageToDraw == 0)
  34648. {
  34649. g.setOpacity (0.4f);
  34650. imageToDraw = getNormalImage();
  34651. }
  34652. }
  34653. if (imageToDraw != 0)
  34654. {
  34655. if (style == ImageRaw)
  34656. {
  34657. imageToDraw->draw (g, 1.0f);
  34658. }
  34659. else
  34660. {
  34661. imageToDraw->drawWithin (g,
  34662. imageSpace.getX(),
  34663. imageSpace.getY(),
  34664. imageSpace.getWidth(),
  34665. imageSpace.getHeight(),
  34666. RectanglePlacement::centred,
  34667. 1.0f);
  34668. }
  34669. }
  34670. }
  34671. const Drawable* DrawableButton::getCurrentImage() const throw()
  34672. {
  34673. if (isDown())
  34674. return getDownImage();
  34675. if (isOver())
  34676. return getOverImage();
  34677. return getNormalImage();
  34678. }
  34679. const Drawable* DrawableButton::getNormalImage() const throw()
  34680. {
  34681. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  34682. : normalImage;
  34683. }
  34684. const Drawable* DrawableButton::getOverImage() const throw()
  34685. {
  34686. const Drawable* d = normalImage;
  34687. if (getToggleState())
  34688. {
  34689. if (overImageOn != 0)
  34690. d = overImageOn;
  34691. else if (normalImageOn != 0)
  34692. d = normalImageOn;
  34693. else if (overImage != 0)
  34694. d = overImage;
  34695. }
  34696. else
  34697. {
  34698. if (overImage != 0)
  34699. d = overImage;
  34700. }
  34701. return d;
  34702. }
  34703. const Drawable* DrawableButton::getDownImage() const throw()
  34704. {
  34705. const Drawable* d = normalImage;
  34706. if (getToggleState())
  34707. {
  34708. if (downImageOn != 0)
  34709. d = downImageOn;
  34710. else if (overImageOn != 0)
  34711. d = overImageOn;
  34712. else if (normalImageOn != 0)
  34713. d = normalImageOn;
  34714. else if (downImage != 0)
  34715. d = downImage;
  34716. else
  34717. d = getOverImage();
  34718. }
  34719. else
  34720. {
  34721. if (downImage != 0)
  34722. d = downImage;
  34723. else
  34724. d = getOverImage();
  34725. }
  34726. return d;
  34727. }
  34728. END_JUCE_NAMESPACE
  34729. /*** End of inlined file: juce_DrawableButton.cpp ***/
  34730. /*** Start of inlined file: juce_HyperlinkButton.cpp ***/
  34731. BEGIN_JUCE_NAMESPACE
  34732. HyperlinkButton::HyperlinkButton (const String& linkText,
  34733. const URL& linkURL)
  34734. : Button (linkText),
  34735. url (linkURL),
  34736. font (14.0f, Font::underlined),
  34737. resizeFont (true),
  34738. justification (Justification::centred)
  34739. {
  34740. setMouseCursor (MouseCursor::PointingHandCursor);
  34741. setTooltip (linkURL.toString (false));
  34742. }
  34743. HyperlinkButton::~HyperlinkButton()
  34744. {
  34745. }
  34746. void HyperlinkButton::setFont (const Font& newFont,
  34747. const bool resizeToMatchComponentHeight,
  34748. const Justification& justificationType)
  34749. {
  34750. font = newFont;
  34751. resizeFont = resizeToMatchComponentHeight;
  34752. justification = justificationType;
  34753. repaint();
  34754. }
  34755. void HyperlinkButton::setURL (const URL& newURL) throw()
  34756. {
  34757. url = newURL;
  34758. setTooltip (newURL.toString (false));
  34759. }
  34760. const Font HyperlinkButton::getFontToUse() const
  34761. {
  34762. Font f (font);
  34763. if (resizeFont)
  34764. f.setHeight (getHeight() * 0.7f);
  34765. return f;
  34766. }
  34767. void HyperlinkButton::changeWidthToFitText()
  34768. {
  34769. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  34770. }
  34771. void HyperlinkButton::colourChanged()
  34772. {
  34773. repaint();
  34774. }
  34775. void HyperlinkButton::clicked()
  34776. {
  34777. if (url.isWellFormed())
  34778. url.launchInDefaultBrowser();
  34779. }
  34780. void HyperlinkButton::paintButton (Graphics& g,
  34781. bool isMouseOverButton,
  34782. bool isButtonDown)
  34783. {
  34784. const Colour textColour (findColour (textColourId));
  34785. if (isEnabled())
  34786. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  34787. : textColour);
  34788. else
  34789. g.setColour (textColour.withMultipliedAlpha (0.4f));
  34790. g.setFont (getFontToUse());
  34791. g.drawText (getButtonText(),
  34792. 2, 0, getWidth() - 2, getHeight(),
  34793. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  34794. true);
  34795. }
  34796. END_JUCE_NAMESPACE
  34797. /*** End of inlined file: juce_HyperlinkButton.cpp ***/
  34798. /*** Start of inlined file: juce_ImageButton.cpp ***/
  34799. BEGIN_JUCE_NAMESPACE
  34800. ImageButton::ImageButton (const String& text_)
  34801. : Button (text_),
  34802. scaleImageToFit (true),
  34803. preserveProportions (true),
  34804. alphaThreshold (0),
  34805. imageX (0),
  34806. imageY (0),
  34807. imageW (0),
  34808. imageH (0),
  34809. normalImage (0),
  34810. overImage (0),
  34811. downImage (0)
  34812. {
  34813. }
  34814. ImageButton::~ImageButton()
  34815. {
  34816. }
  34817. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  34818. const bool rescaleImagesWhenButtonSizeChanges,
  34819. const bool preserveImageProportions,
  34820. const Image& normalImage_,
  34821. const float imageOpacityWhenNormal,
  34822. const Colour& overlayColourWhenNormal,
  34823. const Image& overImage_,
  34824. const float imageOpacityWhenOver,
  34825. const Colour& overlayColourWhenOver,
  34826. const Image& downImage_,
  34827. const float imageOpacityWhenDown,
  34828. const Colour& overlayColourWhenDown,
  34829. const float hitTestAlphaThreshold)
  34830. {
  34831. normalImage = normalImage_;
  34832. overImage = overImage_;
  34833. downImage = downImage_;
  34834. if (resizeButtonNowToFitThisImage && normalImage.isValid())
  34835. {
  34836. imageW = normalImage.getWidth();
  34837. imageH = normalImage.getHeight();
  34838. setSize (imageW, imageH);
  34839. }
  34840. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  34841. preserveProportions = preserveImageProportions;
  34842. normalOpacity = imageOpacityWhenNormal;
  34843. normalOverlay = overlayColourWhenNormal;
  34844. overOpacity = imageOpacityWhenOver;
  34845. overOverlay = overlayColourWhenOver;
  34846. downOpacity = imageOpacityWhenDown;
  34847. downOverlay = overlayColourWhenDown;
  34848. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundToInt (255.0f * hitTestAlphaThreshold));
  34849. repaint();
  34850. }
  34851. const Image ImageButton::getCurrentImage() const
  34852. {
  34853. if (isDown() || getToggleState())
  34854. return getDownImage();
  34855. if (isOver())
  34856. return getOverImage();
  34857. return getNormalImage();
  34858. }
  34859. const Image ImageButton::getNormalImage() const
  34860. {
  34861. return normalImage;
  34862. }
  34863. const Image ImageButton::getOverImage() const
  34864. {
  34865. return overImage.isValid() ? overImage
  34866. : normalImage;
  34867. }
  34868. const Image ImageButton::getDownImage() const
  34869. {
  34870. return downImage.isValid() ? downImage
  34871. : getOverImage();
  34872. }
  34873. void ImageButton::paintButton (Graphics& g,
  34874. bool isMouseOverButton,
  34875. bool isButtonDown)
  34876. {
  34877. if (! isEnabled())
  34878. {
  34879. isMouseOverButton = false;
  34880. isButtonDown = false;
  34881. }
  34882. Image im (getCurrentImage());
  34883. if (im.isValid())
  34884. {
  34885. const int iw = im.getWidth();
  34886. const int ih = im.getHeight();
  34887. imageW = getWidth();
  34888. imageH = getHeight();
  34889. imageX = (imageW - iw) >> 1;
  34890. imageY = (imageH - ih) >> 1;
  34891. if (scaleImageToFit)
  34892. {
  34893. if (preserveProportions)
  34894. {
  34895. int newW, newH;
  34896. const float imRatio = ih / (float)iw;
  34897. const float destRatio = imageH / (float)imageW;
  34898. if (imRatio > destRatio)
  34899. {
  34900. newW = roundToInt (imageH / imRatio);
  34901. newH = imageH;
  34902. }
  34903. else
  34904. {
  34905. newW = imageW;
  34906. newH = roundToInt (imageW * imRatio);
  34907. }
  34908. imageX = (imageW - newW) / 2;
  34909. imageY = (imageH - newH) / 2;
  34910. imageW = newW;
  34911. imageH = newH;
  34912. }
  34913. else
  34914. {
  34915. imageX = 0;
  34916. imageY = 0;
  34917. }
  34918. }
  34919. if (! scaleImageToFit)
  34920. {
  34921. imageW = iw;
  34922. imageH = ih;
  34923. }
  34924. getLookAndFeel().drawImageButton (g, &im, imageX, imageY, imageW, imageH,
  34925. isButtonDown ? downOverlay
  34926. : (isMouseOverButton ? overOverlay
  34927. : normalOverlay),
  34928. isButtonDown ? downOpacity
  34929. : (isMouseOverButton ? overOpacity
  34930. : normalOpacity),
  34931. *this);
  34932. }
  34933. }
  34934. bool ImageButton::hitTest (int x, int y)
  34935. {
  34936. if (alphaThreshold == 0)
  34937. return true;
  34938. Image im (getCurrentImage());
  34939. return im.isNull() || (imageW > 0 && imageH > 0
  34940. && alphaThreshold < im.getPixelAt (((x - imageX) * im.getWidth()) / imageW,
  34941. ((y - imageY) * im.getHeight()) / imageH).getAlpha());
  34942. }
  34943. END_JUCE_NAMESPACE
  34944. /*** End of inlined file: juce_ImageButton.cpp ***/
  34945. /*** Start of inlined file: juce_ShapeButton.cpp ***/
  34946. BEGIN_JUCE_NAMESPACE
  34947. ShapeButton::ShapeButton (const String& text_,
  34948. const Colour& normalColour_,
  34949. const Colour& overColour_,
  34950. const Colour& downColour_)
  34951. : Button (text_),
  34952. normalColour (normalColour_),
  34953. overColour (overColour_),
  34954. downColour (downColour_),
  34955. maintainShapeProportions (false),
  34956. outlineWidth (0.0f)
  34957. {
  34958. }
  34959. ShapeButton::~ShapeButton()
  34960. {
  34961. }
  34962. void ShapeButton::setColours (const Colour& newNormalColour,
  34963. const Colour& newOverColour,
  34964. const Colour& newDownColour)
  34965. {
  34966. normalColour = newNormalColour;
  34967. overColour = newOverColour;
  34968. downColour = newDownColour;
  34969. }
  34970. void ShapeButton::setOutline (const Colour& newOutlineColour,
  34971. const float newOutlineWidth)
  34972. {
  34973. outlineColour = newOutlineColour;
  34974. outlineWidth = newOutlineWidth;
  34975. }
  34976. void ShapeButton::setShape (const Path& newShape,
  34977. const bool resizeNowToFitThisShape,
  34978. const bool maintainShapeProportions_,
  34979. const bool hasShadow)
  34980. {
  34981. shape = newShape;
  34982. maintainShapeProportions = maintainShapeProportions_;
  34983. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  34984. setComponentEffect ((hasShadow) ? &shadow : 0);
  34985. if (resizeNowToFitThisShape)
  34986. {
  34987. Rectangle<float> bounds (shape.getBounds());
  34988. if (hasShadow)
  34989. bounds.expand (4.0f, 4.0f);
  34990. shape.applyTransform (AffineTransform::translation (-bounds.getX(), -bounds.getY()));
  34991. setSize (1 + (int) (bounds.getWidth() + outlineWidth),
  34992. 1 + (int) (bounds.getHeight() + outlineWidth));
  34993. }
  34994. }
  34995. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  34996. {
  34997. if (! isEnabled())
  34998. {
  34999. isMouseOverButton = false;
  35000. isButtonDown = false;
  35001. }
  35002. g.setColour ((isButtonDown) ? downColour
  35003. : (isMouseOverButton) ? overColour
  35004. : normalColour);
  35005. int w = getWidth();
  35006. int h = getHeight();
  35007. if (getComponentEffect() != 0)
  35008. {
  35009. w -= 4;
  35010. h -= 4;
  35011. }
  35012. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  35013. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  35014. w - offset - outlineWidth,
  35015. h - offset - outlineWidth,
  35016. maintainShapeProportions));
  35017. g.fillPath (shape, trans);
  35018. if (outlineWidth > 0.0f)
  35019. {
  35020. g.setColour (outlineColour);
  35021. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  35022. }
  35023. }
  35024. END_JUCE_NAMESPACE
  35025. /*** End of inlined file: juce_ShapeButton.cpp ***/
  35026. /*** Start of inlined file: juce_TextButton.cpp ***/
  35027. BEGIN_JUCE_NAMESPACE
  35028. TextButton::TextButton (const String& name,
  35029. const String& toolTip)
  35030. : Button (name)
  35031. {
  35032. setTooltip (toolTip);
  35033. }
  35034. TextButton::~TextButton()
  35035. {
  35036. }
  35037. void TextButton::paintButton (Graphics& g,
  35038. bool isMouseOverButton,
  35039. bool isButtonDown)
  35040. {
  35041. getLookAndFeel().drawButtonBackground (g, *this,
  35042. findColour (getToggleState() ? buttonOnColourId
  35043. : buttonColourId),
  35044. isMouseOverButton,
  35045. isButtonDown);
  35046. getLookAndFeel().drawButtonText (g, *this,
  35047. isMouseOverButton,
  35048. isButtonDown);
  35049. }
  35050. void TextButton::colourChanged()
  35051. {
  35052. repaint();
  35053. }
  35054. const Font TextButton::getFont()
  35055. {
  35056. return Font (jmin (15.0f, getHeight() * 0.6f));
  35057. }
  35058. void TextButton::changeWidthToFitText (const int newHeight)
  35059. {
  35060. if (newHeight >= 0)
  35061. setSize (jmax (1, getWidth()), newHeight);
  35062. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  35063. getHeight());
  35064. }
  35065. END_JUCE_NAMESPACE
  35066. /*** End of inlined file: juce_TextButton.cpp ***/
  35067. /*** Start of inlined file: juce_ToggleButton.cpp ***/
  35068. BEGIN_JUCE_NAMESPACE
  35069. ToggleButton::ToggleButton (const String& buttonText)
  35070. : Button (buttonText)
  35071. {
  35072. setClickingTogglesState (true);
  35073. }
  35074. ToggleButton::~ToggleButton()
  35075. {
  35076. }
  35077. void ToggleButton::paintButton (Graphics& g,
  35078. bool isMouseOverButton,
  35079. bool isButtonDown)
  35080. {
  35081. getLookAndFeel().drawToggleButton (g, *this,
  35082. isMouseOverButton,
  35083. isButtonDown);
  35084. }
  35085. void ToggleButton::changeWidthToFitText()
  35086. {
  35087. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  35088. }
  35089. void ToggleButton::colourChanged()
  35090. {
  35091. repaint();
  35092. }
  35093. END_JUCE_NAMESPACE
  35094. /*** End of inlined file: juce_ToggleButton.cpp ***/
  35095. /*** Start of inlined file: juce_ToolbarButton.cpp ***/
  35096. BEGIN_JUCE_NAMESPACE
  35097. ToolbarButton::ToolbarButton (const int itemId_,
  35098. const String& buttonText,
  35099. Drawable* const normalImage_,
  35100. Drawable* const toggledOnImage_)
  35101. : ToolbarItemComponent (itemId_, buttonText, true),
  35102. normalImage (normalImage_),
  35103. toggledOnImage (toggledOnImage_)
  35104. {
  35105. jassert (normalImage_ != 0);
  35106. }
  35107. ToolbarButton::~ToolbarButton()
  35108. {
  35109. }
  35110. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth,
  35111. bool /*isToolbarVertical*/,
  35112. int& preferredSize,
  35113. int& minSize, int& maxSize)
  35114. {
  35115. preferredSize = minSize = maxSize = toolbarDepth;
  35116. return true;
  35117. }
  35118. void ToolbarButton::paintButtonArea (Graphics& g,
  35119. int width, int height,
  35120. bool /*isMouseOver*/,
  35121. bool /*isMouseDown*/)
  35122. {
  35123. Drawable* d = normalImage;
  35124. if (getToggleState() && toggledOnImage != 0)
  35125. d = toggledOnImage;
  35126. if (! isEnabled())
  35127. {
  35128. Image im (Image::ARGB, width, height, true);
  35129. {
  35130. Graphics g2 (im);
  35131. d->drawWithin (g2, 0, 0, width, height, RectanglePlacement::centred, 1.0f);
  35132. }
  35133. im.desaturate();
  35134. g.drawImageAt (im, 0, 0);
  35135. }
  35136. else
  35137. {
  35138. d->drawWithin (g, 0, 0, width, height, RectanglePlacement::centred, 1.0f);
  35139. }
  35140. }
  35141. void ToolbarButton::contentAreaChanged (const Rectangle<int>&)
  35142. {
  35143. }
  35144. END_JUCE_NAMESPACE
  35145. /*** End of inlined file: juce_ToolbarButton.cpp ***/
  35146. /*** Start of inlined file: juce_CodeDocument.cpp ***/
  35147. BEGIN_JUCE_NAMESPACE
  35148. class CodeDocumentLine
  35149. {
  35150. public:
  35151. CodeDocumentLine (const juce_wchar* const line_,
  35152. const int lineLength_,
  35153. const int numNewLineChars,
  35154. const int lineStartInFile_)
  35155. : line (line_, lineLength_),
  35156. lineStartInFile (lineStartInFile_),
  35157. lineLength (lineLength_),
  35158. lineLengthWithoutNewLines (lineLength_ - numNewLineChars)
  35159. {
  35160. }
  35161. ~CodeDocumentLine()
  35162. {
  35163. }
  35164. static void createLines (Array <CodeDocumentLine*>& newLines, const String& text)
  35165. {
  35166. const juce_wchar* const t = text;
  35167. int pos = 0;
  35168. while (t [pos] != 0)
  35169. {
  35170. const int startOfLine = pos;
  35171. int numNewLineChars = 0;
  35172. while (t[pos] != 0)
  35173. {
  35174. if (t[pos] == '\r')
  35175. {
  35176. ++numNewLineChars;
  35177. ++pos;
  35178. if (t[pos] == '\n')
  35179. {
  35180. ++numNewLineChars;
  35181. ++pos;
  35182. }
  35183. break;
  35184. }
  35185. if (t[pos] == '\n')
  35186. {
  35187. ++numNewLineChars;
  35188. ++pos;
  35189. break;
  35190. }
  35191. ++pos;
  35192. }
  35193. newLines.add (new CodeDocumentLine (t + startOfLine, pos - startOfLine,
  35194. numNewLineChars, startOfLine));
  35195. }
  35196. jassert (pos == text.length());
  35197. }
  35198. bool endsWithLineBreak() const throw()
  35199. {
  35200. return lineLengthWithoutNewLines != lineLength;
  35201. }
  35202. void updateLength() throw()
  35203. {
  35204. lineLengthWithoutNewLines = lineLength = line.length();
  35205. while (lineLengthWithoutNewLines > 0
  35206. && (line [lineLengthWithoutNewLines - 1] == '\n'
  35207. || line [lineLengthWithoutNewLines - 1] == '\r'))
  35208. {
  35209. --lineLengthWithoutNewLines;
  35210. }
  35211. }
  35212. String line;
  35213. int lineStartInFile, lineLength, lineLengthWithoutNewLines;
  35214. };
  35215. CodeDocument::Iterator::Iterator (CodeDocument* const document_)
  35216. : document (document_),
  35217. currentLine (document_->lines[0]),
  35218. line (0),
  35219. position (0)
  35220. {
  35221. }
  35222. CodeDocument::Iterator::Iterator (const CodeDocument::Iterator& other)
  35223. : document (other.document),
  35224. currentLine (other.currentLine),
  35225. line (other.line),
  35226. position (other.position)
  35227. {
  35228. }
  35229. CodeDocument::Iterator& CodeDocument::Iterator::operator= (const CodeDocument::Iterator& other) throw()
  35230. {
  35231. document = other.document;
  35232. currentLine = other.currentLine;
  35233. line = other.line;
  35234. position = other.position;
  35235. return *this;
  35236. }
  35237. CodeDocument::Iterator::~Iterator() throw()
  35238. {
  35239. }
  35240. juce_wchar CodeDocument::Iterator::nextChar()
  35241. {
  35242. if (currentLine == 0)
  35243. return 0;
  35244. jassert (currentLine == document->lines.getUnchecked (line));
  35245. const juce_wchar result = currentLine->line [position - currentLine->lineStartInFile];
  35246. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  35247. {
  35248. ++line;
  35249. currentLine = document->lines [line];
  35250. }
  35251. return result;
  35252. }
  35253. void CodeDocument::Iterator::skip()
  35254. {
  35255. if (currentLine != 0)
  35256. {
  35257. jassert (currentLine == document->lines.getUnchecked (line));
  35258. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  35259. {
  35260. ++line;
  35261. currentLine = document->lines [line];
  35262. }
  35263. }
  35264. }
  35265. void CodeDocument::Iterator::skipToEndOfLine()
  35266. {
  35267. if (currentLine != 0)
  35268. {
  35269. jassert (currentLine == document->lines.getUnchecked (line));
  35270. ++line;
  35271. currentLine = document->lines [line];
  35272. if (currentLine != 0)
  35273. position = currentLine->lineStartInFile;
  35274. else
  35275. position = document->getNumCharacters();
  35276. }
  35277. }
  35278. juce_wchar CodeDocument::Iterator::peekNextChar() const
  35279. {
  35280. if (currentLine == 0)
  35281. return 0;
  35282. jassert (currentLine == document->lines.getUnchecked (line));
  35283. return const_cast <const String&> (currentLine->line) [position - currentLine->lineStartInFile];
  35284. }
  35285. void CodeDocument::Iterator::skipWhitespace()
  35286. {
  35287. while (CharacterFunctions::isWhitespace (peekNextChar()))
  35288. skip();
  35289. }
  35290. bool CodeDocument::Iterator::isEOF() const throw()
  35291. {
  35292. return currentLine == 0;
  35293. }
  35294. CodeDocument::Position::Position() throw()
  35295. : owner (0), characterPos (0), line (0),
  35296. indexInLine (0), positionMaintained (false)
  35297. {
  35298. }
  35299. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  35300. const int line_, const int indexInLine_) throw()
  35301. : owner (const_cast <CodeDocument*> (ownerDocument)),
  35302. characterPos (0), line (line_),
  35303. indexInLine (indexInLine_), positionMaintained (false)
  35304. {
  35305. setLineAndIndex (line_, indexInLine_);
  35306. }
  35307. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  35308. const int characterPos_) throw()
  35309. : owner (const_cast <CodeDocument*> (ownerDocument)),
  35310. positionMaintained (false)
  35311. {
  35312. setPosition (characterPos_);
  35313. }
  35314. CodeDocument::Position::Position (const Position& other) throw()
  35315. : owner (other.owner), characterPos (other.characterPos), line (other.line),
  35316. indexInLine (other.indexInLine), positionMaintained (false)
  35317. {
  35318. jassert (*this == other);
  35319. }
  35320. CodeDocument::Position::~Position() throw()
  35321. {
  35322. setPositionMaintained (false);
  35323. }
  35324. CodeDocument::Position& CodeDocument::Position::operator= (const Position& other) throw()
  35325. {
  35326. if (this != &other)
  35327. {
  35328. const bool wasPositionMaintained = positionMaintained;
  35329. if (owner != other.owner)
  35330. setPositionMaintained (false);
  35331. owner = other.owner;
  35332. line = other.line;
  35333. indexInLine = other.indexInLine;
  35334. characterPos = other.characterPos;
  35335. setPositionMaintained (wasPositionMaintained);
  35336. jassert (*this == other);
  35337. }
  35338. return *this;
  35339. }
  35340. bool CodeDocument::Position::operator== (const Position& other) const throw()
  35341. {
  35342. jassert ((characterPos == other.characterPos)
  35343. == (line == other.line && indexInLine == other.indexInLine));
  35344. return characterPos == other.characterPos
  35345. && line == other.line
  35346. && indexInLine == other.indexInLine
  35347. && owner == other.owner;
  35348. }
  35349. bool CodeDocument::Position::operator!= (const Position& other) const throw()
  35350. {
  35351. return ! operator== (other);
  35352. }
  35353. void CodeDocument::Position::setLineAndIndex (const int newLine, const int newIndexInLine) throw()
  35354. {
  35355. jassert (owner != 0);
  35356. if (owner->lines.size() == 0)
  35357. {
  35358. line = 0;
  35359. indexInLine = 0;
  35360. characterPos = 0;
  35361. }
  35362. else
  35363. {
  35364. if (newLine >= owner->lines.size())
  35365. {
  35366. line = owner->lines.size() - 1;
  35367. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35368. jassert (l != 0);
  35369. indexInLine = l->lineLengthWithoutNewLines;
  35370. characterPos = l->lineStartInFile + indexInLine;
  35371. }
  35372. else
  35373. {
  35374. line = jmax (0, newLine);
  35375. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35376. jassert (l != 0);
  35377. if (l->lineLengthWithoutNewLines > 0)
  35378. indexInLine = jlimit (0, l->lineLengthWithoutNewLines, newIndexInLine);
  35379. else
  35380. indexInLine = 0;
  35381. characterPos = l->lineStartInFile + indexInLine;
  35382. }
  35383. }
  35384. }
  35385. void CodeDocument::Position::setPosition (const int newPosition) throw()
  35386. {
  35387. jassert (owner != 0);
  35388. line = 0;
  35389. indexInLine = 0;
  35390. characterPos = 0;
  35391. if (newPosition > 0)
  35392. {
  35393. int lineStart = 0;
  35394. int lineEnd = owner->lines.size();
  35395. for (;;)
  35396. {
  35397. if (lineEnd - lineStart < 4)
  35398. {
  35399. for (int i = lineStart; i < lineEnd; ++i)
  35400. {
  35401. CodeDocumentLine* const l = owner->lines.getUnchecked (i);
  35402. int index = newPosition - l->lineStartInFile;
  35403. if (index >= 0 && (index < l->lineLength || i == lineEnd - 1))
  35404. {
  35405. line = i;
  35406. indexInLine = jmin (l->lineLengthWithoutNewLines, index);
  35407. characterPos = l->lineStartInFile + indexInLine;
  35408. }
  35409. }
  35410. break;
  35411. }
  35412. else
  35413. {
  35414. const int midIndex = (lineStart + lineEnd + 1) / 2;
  35415. CodeDocumentLine* const mid = owner->lines.getUnchecked (midIndex);
  35416. if (newPosition >= mid->lineStartInFile)
  35417. lineStart = midIndex;
  35418. else
  35419. lineEnd = midIndex;
  35420. }
  35421. }
  35422. }
  35423. }
  35424. void CodeDocument::Position::moveBy (int characterDelta) throw()
  35425. {
  35426. jassert (owner != 0);
  35427. if (characterDelta == 1)
  35428. {
  35429. setPosition (getPosition());
  35430. // If moving right, make sure we don't get stuck between the \r and \n characters..
  35431. if (line < owner->lines.size())
  35432. {
  35433. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35434. if (indexInLine + characterDelta < l->lineLength
  35435. && indexInLine + characterDelta >= l->lineLengthWithoutNewLines + 1)
  35436. ++characterDelta;
  35437. }
  35438. }
  35439. setPosition (characterPos + characterDelta);
  35440. }
  35441. const CodeDocument::Position CodeDocument::Position::movedBy (const int characterDelta) const throw()
  35442. {
  35443. CodeDocument::Position p (*this);
  35444. p.moveBy (characterDelta);
  35445. return p;
  35446. }
  35447. const CodeDocument::Position CodeDocument::Position::movedByLines (const int deltaLines) const throw()
  35448. {
  35449. CodeDocument::Position p (*this);
  35450. p.setLineAndIndex (getLineNumber() + deltaLines, getIndexInLine());
  35451. return p;
  35452. }
  35453. const juce_wchar CodeDocument::Position::getCharacter() const throw()
  35454. {
  35455. const CodeDocumentLine* const l = owner->lines [line];
  35456. return l == 0 ? 0 : l->line [getIndexInLine()];
  35457. }
  35458. const String CodeDocument::Position::getLineText() const throw()
  35459. {
  35460. const CodeDocumentLine* const l = owner->lines [line];
  35461. return l == 0 ? String::empty : l->line;
  35462. }
  35463. void CodeDocument::Position::setPositionMaintained (const bool isMaintained) throw()
  35464. {
  35465. if (isMaintained != positionMaintained)
  35466. {
  35467. positionMaintained = isMaintained;
  35468. if (owner != 0)
  35469. {
  35470. if (isMaintained)
  35471. {
  35472. jassert (! owner->positionsToMaintain.contains (this));
  35473. owner->positionsToMaintain.add (this);
  35474. }
  35475. else
  35476. {
  35477. // If this happens, you may have deleted the document while there are Position objects that are still using it...
  35478. jassert (owner->positionsToMaintain.contains (this));
  35479. owner->positionsToMaintain.removeValue (this);
  35480. }
  35481. }
  35482. }
  35483. }
  35484. CodeDocument::CodeDocument()
  35485. : undoManager (std::numeric_limits<int>::max(), 10000),
  35486. currentActionIndex (0),
  35487. indexOfSavedState (-1),
  35488. maximumLineLength (-1),
  35489. newLineChars ("\r\n")
  35490. {
  35491. }
  35492. CodeDocument::~CodeDocument()
  35493. {
  35494. }
  35495. const String CodeDocument::getAllContent() const throw()
  35496. {
  35497. return getTextBetween (Position (this, 0),
  35498. Position (this, lines.size(), 0));
  35499. }
  35500. const String CodeDocument::getTextBetween (const Position& start, const Position& end) const throw()
  35501. {
  35502. if (end.getPosition() <= start.getPosition())
  35503. return String::empty;
  35504. const int startLine = start.getLineNumber();
  35505. const int endLine = end.getLineNumber();
  35506. if (startLine == endLine)
  35507. {
  35508. CodeDocumentLine* const line = lines [startLine];
  35509. return (line == 0) ? String::empty : line->line.substring (start.getIndexInLine(), end.getIndexInLine());
  35510. }
  35511. String result;
  35512. result.preallocateStorage (end.getPosition() - start.getPosition() + 4);
  35513. String::Concatenator concatenator (result);
  35514. const int maxLine = jmin (lines.size() - 1, endLine);
  35515. for (int i = jmax (0, startLine); i <= maxLine; ++i)
  35516. {
  35517. const CodeDocumentLine* line = lines.getUnchecked(i);
  35518. int len = line->lineLength;
  35519. if (i == startLine)
  35520. {
  35521. const int index = start.getIndexInLine();
  35522. concatenator.append (line->line.substring (index, len));
  35523. }
  35524. else if (i == endLine)
  35525. {
  35526. len = end.getIndexInLine();
  35527. concatenator.append (line->line.substring (0, len));
  35528. }
  35529. else
  35530. {
  35531. concatenator.append (line->line);
  35532. }
  35533. }
  35534. return result;
  35535. }
  35536. int CodeDocument::getNumCharacters() const throw()
  35537. {
  35538. const CodeDocumentLine* const lastLine = lines.getLast();
  35539. return (lastLine == 0) ? 0 : lastLine->lineStartInFile + lastLine->lineLength;
  35540. }
  35541. const String CodeDocument::getLine (const int lineIndex) const throw()
  35542. {
  35543. const CodeDocumentLine* const line = lines [lineIndex];
  35544. return (line == 0) ? String::empty : line->line;
  35545. }
  35546. int CodeDocument::getMaximumLineLength() throw()
  35547. {
  35548. if (maximumLineLength < 0)
  35549. {
  35550. maximumLineLength = 0;
  35551. for (int i = lines.size(); --i >= 0;)
  35552. maximumLineLength = jmax (maximumLineLength, lines.getUnchecked(i)->lineLength);
  35553. }
  35554. return maximumLineLength;
  35555. }
  35556. void CodeDocument::deleteSection (const Position& startPosition, const Position& endPosition)
  35557. {
  35558. remove (startPosition.getPosition(), endPosition.getPosition(), true);
  35559. }
  35560. void CodeDocument::insertText (const Position& position, const String& text)
  35561. {
  35562. insert (text, position.getPosition(), true);
  35563. }
  35564. void CodeDocument::replaceAllContent (const String& newContent)
  35565. {
  35566. remove (0, getNumCharacters(), true);
  35567. insert (newContent, 0, true);
  35568. }
  35569. bool CodeDocument::loadFromStream (InputStream& stream)
  35570. {
  35571. replaceAllContent (stream.readEntireStreamAsString());
  35572. setSavePoint();
  35573. clearUndoHistory();
  35574. return true;
  35575. }
  35576. bool CodeDocument::writeToStream (OutputStream& stream)
  35577. {
  35578. for (int i = 0; i < lines.size(); ++i)
  35579. {
  35580. String temp (lines.getUnchecked(i)->line); // use a copy to avoid bloating the memory footprint of the stored string.
  35581. const char* utf8 = temp.toUTF8();
  35582. if (! stream.write (utf8, (int) strlen (utf8)))
  35583. return false;
  35584. }
  35585. return true;
  35586. }
  35587. void CodeDocument::setNewLineCharacters (const String& newLine) throw()
  35588. {
  35589. jassert (newLine == "\r\n" || newLine == "\n" || newLine == "\r");
  35590. newLineChars = newLine;
  35591. }
  35592. void CodeDocument::newTransaction()
  35593. {
  35594. undoManager.beginNewTransaction (String::empty);
  35595. }
  35596. void CodeDocument::undo()
  35597. {
  35598. newTransaction();
  35599. undoManager.undo();
  35600. }
  35601. void CodeDocument::redo()
  35602. {
  35603. undoManager.redo();
  35604. }
  35605. void CodeDocument::clearUndoHistory()
  35606. {
  35607. undoManager.clearUndoHistory();
  35608. }
  35609. void CodeDocument::setSavePoint() throw()
  35610. {
  35611. indexOfSavedState = currentActionIndex;
  35612. }
  35613. bool CodeDocument::hasChangedSinceSavePoint() const throw()
  35614. {
  35615. return currentActionIndex != indexOfSavedState;
  35616. }
  35617. static int getCodeCharacterCategory (const juce_wchar character) throw()
  35618. {
  35619. return (CharacterFunctions::isLetterOrDigit (character) || character == '_')
  35620. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  35621. }
  35622. const CodeDocument::Position CodeDocument::findWordBreakAfter (const Position& position) const throw()
  35623. {
  35624. Position p (position);
  35625. const int maxDistance = 256;
  35626. int i = 0;
  35627. while (i < maxDistance
  35628. && CharacterFunctions::isWhitespace (p.getCharacter())
  35629. && (i == 0 || (p.getCharacter() != '\n'
  35630. && p.getCharacter() != '\r')))
  35631. {
  35632. ++i;
  35633. p.moveBy (1);
  35634. }
  35635. if (i == 0)
  35636. {
  35637. const int type = getCodeCharacterCategory (p.getCharacter());
  35638. while (i < maxDistance && type == getCodeCharacterCategory (p.getCharacter()))
  35639. {
  35640. ++i;
  35641. p.moveBy (1);
  35642. }
  35643. while (i < maxDistance
  35644. && CharacterFunctions::isWhitespace (p.getCharacter())
  35645. && (i == 0 || (p.getCharacter() != '\n'
  35646. && p.getCharacter() != '\r')))
  35647. {
  35648. ++i;
  35649. p.moveBy (1);
  35650. }
  35651. }
  35652. return p;
  35653. }
  35654. const CodeDocument::Position CodeDocument::findWordBreakBefore (const Position& position) const throw()
  35655. {
  35656. Position p (position);
  35657. const int maxDistance = 256;
  35658. int i = 0;
  35659. bool stoppedAtLineStart = false;
  35660. while (i < maxDistance)
  35661. {
  35662. const juce_wchar c = p.movedBy (-1).getCharacter();
  35663. if (c == '\r' || c == '\n')
  35664. {
  35665. stoppedAtLineStart = true;
  35666. if (i > 0)
  35667. break;
  35668. }
  35669. if (! CharacterFunctions::isWhitespace (c))
  35670. break;
  35671. p.moveBy (-1);
  35672. ++i;
  35673. }
  35674. if (i < maxDistance && ! stoppedAtLineStart)
  35675. {
  35676. const int type = getCodeCharacterCategory (p.movedBy (-1).getCharacter());
  35677. while (i < maxDistance && type == getCodeCharacterCategory (p.movedBy (-1).getCharacter()))
  35678. {
  35679. p.moveBy (-1);
  35680. ++i;
  35681. }
  35682. }
  35683. return p;
  35684. }
  35685. void CodeDocument::checkLastLineStatus()
  35686. {
  35687. while (lines.size() > 0
  35688. && lines.getLast()->lineLength == 0
  35689. && (lines.size() == 1 || ! lines.getUnchecked (lines.size() - 2)->endsWithLineBreak()))
  35690. {
  35691. // remove any empty lines at the end if the preceding line doesn't end in a newline.
  35692. lines.removeLast();
  35693. }
  35694. const CodeDocumentLine* const lastLine = lines.getLast();
  35695. if (lastLine != 0 && lastLine->endsWithLineBreak())
  35696. {
  35697. // check that there's an empty line at the end if the preceding one ends in a newline..
  35698. lines.add (new CodeDocumentLine (String::empty, 0, 0, lastLine->lineStartInFile + lastLine->lineLength));
  35699. }
  35700. }
  35701. void CodeDocument::addListener (CodeDocument::Listener* const listener) throw()
  35702. {
  35703. listeners.add (listener);
  35704. }
  35705. void CodeDocument::removeListener (CodeDocument::Listener* const listener) throw()
  35706. {
  35707. listeners.remove (listener);
  35708. }
  35709. void CodeDocument::sendListenerChangeMessage (const int startLine, const int endLine)
  35710. {
  35711. Position startPos (this, startLine, 0);
  35712. Position endPos (this, endLine, 0);
  35713. listeners.call (&Listener::codeDocumentChanged, startPos, endPos);
  35714. }
  35715. class CodeDocumentInsertAction : public UndoableAction
  35716. {
  35717. CodeDocument& owner;
  35718. const String text;
  35719. int insertPos;
  35720. CodeDocumentInsertAction (const CodeDocumentInsertAction&);
  35721. CodeDocumentInsertAction& operator= (const CodeDocumentInsertAction&);
  35722. public:
  35723. CodeDocumentInsertAction (CodeDocument& owner_, const String& text_, const int insertPos_) throw()
  35724. : owner (owner_),
  35725. text (text_),
  35726. insertPos (insertPos_)
  35727. {
  35728. }
  35729. ~CodeDocumentInsertAction() {}
  35730. bool perform()
  35731. {
  35732. owner.currentActionIndex++;
  35733. owner.insert (text, insertPos, false);
  35734. return true;
  35735. }
  35736. bool undo()
  35737. {
  35738. owner.currentActionIndex--;
  35739. owner.remove (insertPos, insertPos + text.length(), false);
  35740. return true;
  35741. }
  35742. int getSizeInUnits() { return text.length() + 32; }
  35743. };
  35744. void CodeDocument::insert (const String& text, const int insertPos, const bool undoable)
  35745. {
  35746. if (text.isEmpty())
  35747. return;
  35748. if (undoable)
  35749. {
  35750. undoManager.perform (new CodeDocumentInsertAction (*this, text, insertPos));
  35751. }
  35752. else
  35753. {
  35754. Position pos (this, insertPos);
  35755. const int firstAffectedLine = pos.getLineNumber();
  35756. int lastAffectedLine = firstAffectedLine + 1;
  35757. CodeDocumentLine* const firstLine = lines [firstAffectedLine];
  35758. String textInsideOriginalLine (text);
  35759. if (firstLine != 0)
  35760. {
  35761. const int index = pos.getIndexInLine();
  35762. textInsideOriginalLine = firstLine->line.substring (0, index)
  35763. + textInsideOriginalLine
  35764. + firstLine->line.substring (index);
  35765. }
  35766. maximumLineLength = -1;
  35767. Array <CodeDocumentLine*> newLines;
  35768. CodeDocumentLine::createLines (newLines, textInsideOriginalLine);
  35769. jassert (newLines.size() > 0);
  35770. CodeDocumentLine* const newFirstLine = newLines.getUnchecked (0);
  35771. newFirstLine->lineStartInFile = firstLine != 0 ? firstLine->lineStartInFile : 0;
  35772. lines.set (firstAffectedLine, newFirstLine);
  35773. if (newLines.size() > 1)
  35774. {
  35775. for (int i = 1; i < newLines.size(); ++i)
  35776. {
  35777. CodeDocumentLine* const l = newLines.getUnchecked (i);
  35778. lines.insert (firstAffectedLine + i, l);
  35779. }
  35780. lastAffectedLine = lines.size();
  35781. }
  35782. int i, lineStart = newFirstLine->lineStartInFile;
  35783. for (i = firstAffectedLine; i < lines.size(); ++i)
  35784. {
  35785. CodeDocumentLine* const l = lines.getUnchecked (i);
  35786. l->lineStartInFile = lineStart;
  35787. lineStart += l->lineLength;
  35788. }
  35789. checkLastLineStatus();
  35790. const int newTextLength = text.length();
  35791. for (i = 0; i < positionsToMaintain.size(); ++i)
  35792. {
  35793. CodeDocument::Position* const p = positionsToMaintain.getUnchecked(i);
  35794. if (p->getPosition() >= insertPos)
  35795. p->setPosition (p->getPosition() + newTextLength);
  35796. }
  35797. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  35798. }
  35799. }
  35800. class CodeDocumentDeleteAction : public UndoableAction
  35801. {
  35802. CodeDocument& owner;
  35803. int startPos, endPos;
  35804. String removedText;
  35805. CodeDocumentDeleteAction (const CodeDocumentDeleteAction&);
  35806. CodeDocumentDeleteAction& operator= (const CodeDocumentDeleteAction&);
  35807. public:
  35808. CodeDocumentDeleteAction (CodeDocument& owner_, const int startPos_, const int endPos_) throw()
  35809. : owner (owner_),
  35810. startPos (startPos_),
  35811. endPos (endPos_)
  35812. {
  35813. removedText = owner.getTextBetween (CodeDocument::Position (&owner, startPos),
  35814. CodeDocument::Position (&owner, endPos));
  35815. }
  35816. ~CodeDocumentDeleteAction() {}
  35817. bool perform()
  35818. {
  35819. owner.currentActionIndex++;
  35820. owner.remove (startPos, endPos, false);
  35821. return true;
  35822. }
  35823. bool undo()
  35824. {
  35825. owner.currentActionIndex--;
  35826. owner.insert (removedText, startPos, false);
  35827. return true;
  35828. }
  35829. int getSizeInUnits() { return removedText.length() + 32; }
  35830. };
  35831. void CodeDocument::remove (const int startPos, const int endPos, const bool undoable)
  35832. {
  35833. if (endPos <= startPos)
  35834. return;
  35835. if (undoable)
  35836. {
  35837. undoManager.perform (new CodeDocumentDeleteAction (*this, startPos, endPos));
  35838. }
  35839. else
  35840. {
  35841. Position startPosition (this, startPos);
  35842. Position endPosition (this, endPos);
  35843. maximumLineLength = -1;
  35844. const int firstAffectedLine = startPosition.getLineNumber();
  35845. const int endLine = endPosition.getLineNumber();
  35846. int lastAffectedLine = firstAffectedLine + 1;
  35847. CodeDocumentLine* const firstLine = lines.getUnchecked (firstAffectedLine);
  35848. if (firstAffectedLine == endLine)
  35849. {
  35850. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  35851. + firstLine->line.substring (endPosition.getIndexInLine());
  35852. firstLine->updateLength();
  35853. }
  35854. else
  35855. {
  35856. lastAffectedLine = lines.size();
  35857. CodeDocumentLine* const lastLine = lines.getUnchecked (endLine);
  35858. jassert (lastLine != 0);
  35859. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  35860. + lastLine->line.substring (endPosition.getIndexInLine());
  35861. firstLine->updateLength();
  35862. int numLinesToRemove = endLine - firstAffectedLine;
  35863. lines.removeRange (firstAffectedLine + 1, numLinesToRemove);
  35864. }
  35865. int i;
  35866. for (i = firstAffectedLine + 1; i < lines.size(); ++i)
  35867. {
  35868. CodeDocumentLine* const l = lines.getUnchecked (i);
  35869. const CodeDocumentLine* const previousLine = lines.getUnchecked (i - 1);
  35870. l->lineStartInFile = previousLine->lineStartInFile + previousLine->lineLength;
  35871. }
  35872. checkLastLineStatus();
  35873. const int totalChars = getNumCharacters();
  35874. for (i = 0; i < positionsToMaintain.size(); ++i)
  35875. {
  35876. CodeDocument::Position* p = positionsToMaintain.getUnchecked(i);
  35877. if (p->getPosition() > startPosition.getPosition())
  35878. p->setPosition (jmax (startPos, p->getPosition() + startPos - endPos));
  35879. if (p->getPosition() > totalChars)
  35880. p->setPosition (totalChars);
  35881. }
  35882. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  35883. }
  35884. }
  35885. END_JUCE_NAMESPACE
  35886. /*** End of inlined file: juce_CodeDocument.cpp ***/
  35887. /*** Start of inlined file: juce_CodeEditorComponent.cpp ***/
  35888. BEGIN_JUCE_NAMESPACE
  35889. class CodeEditorComponent::CaretComponent : public Component,
  35890. public Timer
  35891. {
  35892. public:
  35893. CaretComponent (CodeEditorComponent& owner_)
  35894. : owner (owner_)
  35895. {
  35896. setAlwaysOnTop (true);
  35897. setInterceptsMouseClicks (false, false);
  35898. }
  35899. ~CaretComponent()
  35900. {
  35901. }
  35902. void paint (Graphics& g)
  35903. {
  35904. g.fillAll (findColour (CodeEditorComponent::caretColourId));
  35905. }
  35906. void timerCallback()
  35907. {
  35908. setVisible (shouldBeShown() && ! isVisible());
  35909. }
  35910. void updatePosition()
  35911. {
  35912. startTimer (400);
  35913. setVisible (shouldBeShown());
  35914. setBounds (owner.getCharacterBounds (owner.getCaretPos()).withWidth (2));
  35915. }
  35916. private:
  35917. CodeEditorComponent& owner;
  35918. CaretComponent (const CaretComponent&);
  35919. CaretComponent& operator= (const CaretComponent&);
  35920. bool shouldBeShown() const { return owner.hasKeyboardFocus (true); }
  35921. };
  35922. class CodeEditorComponent::CodeEditorLine
  35923. {
  35924. public:
  35925. CodeEditorLine() throw()
  35926. : highlightColumnStart (0), highlightColumnEnd (0)
  35927. {
  35928. }
  35929. ~CodeEditorLine() throw()
  35930. {
  35931. }
  35932. bool update (CodeDocument& document, int lineNum,
  35933. CodeDocument::Iterator& source,
  35934. CodeTokeniser* analyser, const int spacesPerTab,
  35935. const CodeDocument::Position& selectionStart,
  35936. const CodeDocument::Position& selectionEnd)
  35937. {
  35938. Array <SyntaxToken> newTokens;
  35939. newTokens.ensureStorageAllocated (8);
  35940. if (analyser == 0)
  35941. {
  35942. newTokens.add (SyntaxToken (document.getLine (lineNum), -1));
  35943. }
  35944. else if (lineNum < document.getNumLines())
  35945. {
  35946. const CodeDocument::Position pos (&document, lineNum, 0);
  35947. createTokens (pos.getPosition(), pos.getLineText(),
  35948. source, analyser, newTokens);
  35949. }
  35950. replaceTabsWithSpaces (newTokens, spacesPerTab);
  35951. int newHighlightStart = 0;
  35952. int newHighlightEnd = 0;
  35953. if (selectionStart.getLineNumber() <= lineNum && selectionEnd.getLineNumber() >= lineNum)
  35954. {
  35955. const String line (document.getLine (lineNum));
  35956. CodeDocument::Position lineStart (&document, lineNum, 0), lineEnd (&document, lineNum + 1, 0);
  35957. newHighlightStart = indexToColumn (jmax (0, selectionStart.getPosition() - lineStart.getPosition()),
  35958. line, spacesPerTab);
  35959. newHighlightEnd = indexToColumn (jmin (lineEnd.getPosition() - lineStart.getPosition(), selectionEnd.getPosition() - lineStart.getPosition()),
  35960. line, spacesPerTab);
  35961. }
  35962. if (newHighlightStart != highlightColumnStart || newHighlightEnd != highlightColumnEnd)
  35963. {
  35964. highlightColumnStart = newHighlightStart;
  35965. highlightColumnEnd = newHighlightEnd;
  35966. }
  35967. else
  35968. {
  35969. if (tokens.size() == newTokens.size())
  35970. {
  35971. bool allTheSame = true;
  35972. for (int i = newTokens.size(); --i >= 0;)
  35973. {
  35974. if (tokens.getReference(i) != newTokens.getReference(i))
  35975. {
  35976. allTheSame = false;
  35977. break;
  35978. }
  35979. }
  35980. if (allTheSame)
  35981. return false;
  35982. }
  35983. }
  35984. tokens.swapWithArray (newTokens);
  35985. return true;
  35986. }
  35987. void draw (CodeEditorComponent& owner, Graphics& g, const Font& font,
  35988. float x, const int y, const int baselineOffset, const int lineHeight,
  35989. const Colour& highlightColour) const throw()
  35990. {
  35991. if (highlightColumnStart < highlightColumnEnd)
  35992. {
  35993. g.setColour (highlightColour);
  35994. g.fillRect (roundToInt (x + highlightColumnStart * owner.getCharWidth()), y,
  35995. roundToInt ((highlightColumnEnd - highlightColumnStart) * owner.getCharWidth()), lineHeight);
  35996. }
  35997. int lastType = std::numeric_limits<int>::min();
  35998. for (int i = 0; i < tokens.size(); ++i)
  35999. {
  36000. SyntaxToken& token = tokens.getReference(i);
  36001. if (lastType != token.tokenType)
  36002. {
  36003. lastType = token.tokenType;
  36004. g.setColour (owner.getColourForTokenType (lastType));
  36005. }
  36006. g.drawSingleLineText (token.text, roundToInt (x), y + baselineOffset);
  36007. if (i < tokens.size() - 1)
  36008. {
  36009. if (token.width < 0)
  36010. token.width = font.getStringWidthFloat (token.text);
  36011. x += token.width;
  36012. }
  36013. }
  36014. }
  36015. private:
  36016. struct SyntaxToken
  36017. {
  36018. String text;
  36019. int tokenType;
  36020. float width;
  36021. SyntaxToken (const String& text_, const int type) throw()
  36022. : text (text_), tokenType (type), width (-1.0f)
  36023. {
  36024. }
  36025. bool operator!= (const SyntaxToken& other) const throw()
  36026. {
  36027. return text != other.text || tokenType != other.tokenType;
  36028. }
  36029. };
  36030. Array <SyntaxToken> tokens;
  36031. int highlightColumnStart, highlightColumnEnd;
  36032. static void createTokens (int startPosition, const String& lineText,
  36033. CodeDocument::Iterator& source,
  36034. CodeTokeniser* analyser,
  36035. Array <SyntaxToken>& newTokens)
  36036. {
  36037. CodeDocument::Iterator lastIterator (source);
  36038. const int lineLength = lineText.length();
  36039. for (;;)
  36040. {
  36041. int tokenType = analyser->readNextToken (source);
  36042. int tokenStart = lastIterator.getPosition();
  36043. int tokenEnd = source.getPosition();
  36044. if (tokenEnd <= tokenStart)
  36045. break;
  36046. tokenEnd -= startPosition;
  36047. if (tokenEnd > 0)
  36048. {
  36049. tokenStart -= startPosition;
  36050. newTokens.add (SyntaxToken (lineText.substring (jmax (0, tokenStart), tokenEnd),
  36051. tokenType));
  36052. if (tokenEnd >= lineLength)
  36053. break;
  36054. }
  36055. lastIterator = source;
  36056. }
  36057. source = lastIterator;
  36058. }
  36059. static void replaceTabsWithSpaces (Array <SyntaxToken>& tokens, const int spacesPerTab) throw()
  36060. {
  36061. int x = 0;
  36062. for (int i = 0; i < tokens.size(); ++i)
  36063. {
  36064. SyntaxToken& t = tokens.getReference(i);
  36065. for (;;)
  36066. {
  36067. int tabPos = t.text.indexOfChar ('\t');
  36068. if (tabPos < 0)
  36069. break;
  36070. const int spacesNeeded = spacesPerTab - ((tabPos + x) % spacesPerTab);
  36071. t.text = t.text.replaceSection (tabPos, 1, String::repeatedString (" ", spacesNeeded));
  36072. }
  36073. x += t.text.length();
  36074. }
  36075. }
  36076. int indexToColumn (int index, const String& line, int spacesPerTab) const throw()
  36077. {
  36078. jassert (index <= line.length());
  36079. int col = 0;
  36080. for (int i = 0; i < index; ++i)
  36081. {
  36082. if (line[i] != '\t')
  36083. ++col;
  36084. else
  36085. col += spacesPerTab - (col % spacesPerTab);
  36086. }
  36087. return col;
  36088. }
  36089. };
  36090. CodeEditorComponent::CodeEditorComponent (CodeDocument& document_,
  36091. CodeTokeniser* const codeTokeniser_)
  36092. : document (document_),
  36093. firstLineOnScreen (0),
  36094. gutter (5),
  36095. spacesPerTab (4),
  36096. lineHeight (0),
  36097. linesOnScreen (0),
  36098. columnsOnScreen (0),
  36099. scrollbarThickness (16),
  36100. columnToTryToMaintain (-1),
  36101. useSpacesForTabs (false),
  36102. xOffset (0),
  36103. codeTokeniser (codeTokeniser_)
  36104. {
  36105. caretPos = CodeDocument::Position (&document_, 0, 0);
  36106. caretPos.setPositionMaintained (true);
  36107. selectionStart = CodeDocument::Position (&document_, 0, 0);
  36108. selectionStart.setPositionMaintained (true);
  36109. selectionEnd = CodeDocument::Position (&document_, 0, 0);
  36110. selectionEnd.setPositionMaintained (true);
  36111. setOpaque (true);
  36112. setMouseCursor (MouseCursor (MouseCursor::IBeamCursor));
  36113. setWantsKeyboardFocus (true);
  36114. addAndMakeVisible (verticalScrollBar = new ScrollBar (true));
  36115. verticalScrollBar->setSingleStepSize (1.0);
  36116. addAndMakeVisible (horizontalScrollBar = new ScrollBar (false));
  36117. horizontalScrollBar->setSingleStepSize (1.0);
  36118. addAndMakeVisible (caret = new CaretComponent (*this));
  36119. Font f (12.0f);
  36120. f.setTypefaceName (Font::getDefaultMonospacedFontName());
  36121. setFont (f);
  36122. resetToDefaultColours();
  36123. verticalScrollBar->addListener (this);
  36124. horizontalScrollBar->addListener (this);
  36125. document.addListener (this);
  36126. }
  36127. CodeEditorComponent::~CodeEditorComponent()
  36128. {
  36129. document.removeListener (this);
  36130. deleteAllChildren();
  36131. }
  36132. void CodeEditorComponent::loadContent (const String& newContent)
  36133. {
  36134. clearCachedIterators (0);
  36135. document.replaceAllContent (newContent);
  36136. document.clearUndoHistory();
  36137. document.setSavePoint();
  36138. caretPos.setPosition (0);
  36139. selectionStart.setPosition (0);
  36140. selectionEnd.setPosition (0);
  36141. scrollToLine (0);
  36142. }
  36143. bool CodeEditorComponent::isTextInputActive() const
  36144. {
  36145. return true;
  36146. }
  36147. void CodeEditorComponent::codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  36148. const CodeDocument::Position& affectedTextEnd)
  36149. {
  36150. clearCachedIterators (affectedTextStart.getLineNumber());
  36151. triggerAsyncUpdate();
  36152. caret->updatePosition();
  36153. columnToTryToMaintain = -1;
  36154. if (affectedTextEnd.getPosition() >= selectionStart.getPosition()
  36155. && affectedTextStart.getPosition() <= selectionEnd.getPosition())
  36156. deselectAll();
  36157. if (caretPos.getPosition() > affectedTextEnd.getPosition()
  36158. || caretPos.getPosition() < affectedTextStart.getPosition())
  36159. moveCaretTo (affectedTextStart, false);
  36160. updateScrollBars();
  36161. }
  36162. void CodeEditorComponent::resized()
  36163. {
  36164. linesOnScreen = (getHeight() - scrollbarThickness) / lineHeight;
  36165. columnsOnScreen = (int) ((getWidth() - scrollbarThickness) / charWidth);
  36166. lines.clear();
  36167. rebuildLineTokens();
  36168. caret->updatePosition();
  36169. verticalScrollBar->setBounds (getWidth() - scrollbarThickness, 0, scrollbarThickness, getHeight() - scrollbarThickness);
  36170. horizontalScrollBar->setBounds (gutter, getHeight() - scrollbarThickness, getWidth() - scrollbarThickness - gutter, scrollbarThickness);
  36171. updateScrollBars();
  36172. }
  36173. void CodeEditorComponent::paint (Graphics& g)
  36174. {
  36175. handleUpdateNowIfNeeded();
  36176. g.fillAll (findColour (CodeEditorComponent::backgroundColourId));
  36177. g.reduceClipRegion (gutter, 0, verticalScrollBar->getX() - gutter, horizontalScrollBar->getY());
  36178. g.setFont (font);
  36179. const int baselineOffset = (int) font.getAscent();
  36180. const Colour defaultColour (findColour (CodeEditorComponent::defaultTextColourId));
  36181. const Colour highlightColour (findColour (CodeEditorComponent::highlightColourId));
  36182. const Rectangle<int> clip (g.getClipBounds());
  36183. const int firstLineToDraw = jmax (0, clip.getY() / lineHeight);
  36184. const int lastLineToDraw = jmin (lines.size(), clip.getBottom() / lineHeight + 1);
  36185. for (int j = firstLineToDraw; j < lastLineToDraw; ++j)
  36186. {
  36187. lines.getUnchecked(j)->draw (*this, g, font,
  36188. (float) (gutter - xOffset * charWidth),
  36189. lineHeight * j, baselineOffset, lineHeight,
  36190. highlightColour);
  36191. }
  36192. }
  36193. void CodeEditorComponent::setScrollbarThickness (const int thickness) throw()
  36194. {
  36195. if (scrollbarThickness != thickness)
  36196. {
  36197. scrollbarThickness = thickness;
  36198. resized();
  36199. }
  36200. }
  36201. void CodeEditorComponent::handleAsyncUpdate()
  36202. {
  36203. rebuildLineTokens();
  36204. }
  36205. void CodeEditorComponent::rebuildLineTokens()
  36206. {
  36207. cancelPendingUpdate();
  36208. const int numNeeded = linesOnScreen + 1;
  36209. int minLineToRepaint = numNeeded;
  36210. int maxLineToRepaint = 0;
  36211. if (numNeeded != lines.size())
  36212. {
  36213. lines.clear();
  36214. for (int i = numNeeded; --i >= 0;)
  36215. lines.add (new CodeEditorLine());
  36216. minLineToRepaint = 0;
  36217. maxLineToRepaint = numNeeded;
  36218. }
  36219. jassert (numNeeded == lines.size());
  36220. CodeDocument::Iterator source (&document);
  36221. getIteratorForPosition (CodeDocument::Position (&document, firstLineOnScreen, 0).getPosition(), source);
  36222. for (int i = 0; i < numNeeded; ++i)
  36223. {
  36224. CodeEditorLine* const line = lines.getUnchecked(i);
  36225. if (line->update (document, firstLineOnScreen + i, source, codeTokeniser, spacesPerTab,
  36226. selectionStart, selectionEnd))
  36227. {
  36228. minLineToRepaint = jmin (minLineToRepaint, i);
  36229. maxLineToRepaint = jmax (maxLineToRepaint, i);
  36230. }
  36231. }
  36232. if (minLineToRepaint <= maxLineToRepaint)
  36233. {
  36234. repaint (gutter, lineHeight * minLineToRepaint - 1,
  36235. verticalScrollBar->getX() - gutter,
  36236. lineHeight * (1 + maxLineToRepaint - minLineToRepaint) + 2);
  36237. }
  36238. }
  36239. void CodeEditorComponent::moveCaretTo (const CodeDocument::Position& newPos, const bool highlighting)
  36240. {
  36241. caretPos = newPos;
  36242. columnToTryToMaintain = -1;
  36243. if (highlighting)
  36244. {
  36245. if (dragType == notDragging)
  36246. {
  36247. if (abs (caretPos.getPosition() - selectionStart.getPosition())
  36248. < abs (caretPos.getPosition() - selectionEnd.getPosition()))
  36249. dragType = draggingSelectionStart;
  36250. else
  36251. dragType = draggingSelectionEnd;
  36252. }
  36253. if (dragType == draggingSelectionStart)
  36254. {
  36255. selectionStart = caretPos;
  36256. if (selectionEnd.getPosition() < selectionStart.getPosition())
  36257. {
  36258. const CodeDocument::Position temp (selectionStart);
  36259. selectionStart = selectionEnd;
  36260. selectionEnd = temp;
  36261. dragType = draggingSelectionEnd;
  36262. }
  36263. }
  36264. else
  36265. {
  36266. selectionEnd = caretPos;
  36267. if (selectionEnd.getPosition() < selectionStart.getPosition())
  36268. {
  36269. const CodeDocument::Position temp (selectionStart);
  36270. selectionStart = selectionEnd;
  36271. selectionEnd = temp;
  36272. dragType = draggingSelectionStart;
  36273. }
  36274. }
  36275. triggerAsyncUpdate();
  36276. }
  36277. else
  36278. {
  36279. deselectAll();
  36280. }
  36281. caret->updatePosition();
  36282. scrollToKeepCaretOnScreen();
  36283. updateScrollBars();
  36284. }
  36285. void CodeEditorComponent::deselectAll()
  36286. {
  36287. if (selectionStart != selectionEnd)
  36288. triggerAsyncUpdate();
  36289. selectionStart = caretPos;
  36290. selectionEnd = caretPos;
  36291. }
  36292. void CodeEditorComponent::updateScrollBars()
  36293. {
  36294. verticalScrollBar->setRangeLimits (0, jmax (document.getNumLines(), firstLineOnScreen + linesOnScreen));
  36295. verticalScrollBar->setCurrentRange (firstLineOnScreen, linesOnScreen);
  36296. horizontalScrollBar->setRangeLimits (0, jmax ((double) document.getMaximumLineLength(), xOffset + columnsOnScreen));
  36297. horizontalScrollBar->setCurrentRange (xOffset, columnsOnScreen);
  36298. }
  36299. void CodeEditorComponent::scrollToLineInternal (int newFirstLineOnScreen)
  36300. {
  36301. newFirstLineOnScreen = jlimit (0, jmax (0, document.getNumLines() - 1),
  36302. newFirstLineOnScreen);
  36303. if (newFirstLineOnScreen != firstLineOnScreen)
  36304. {
  36305. firstLineOnScreen = newFirstLineOnScreen;
  36306. caret->updatePosition();
  36307. updateCachedIterators (firstLineOnScreen);
  36308. triggerAsyncUpdate();
  36309. }
  36310. }
  36311. void CodeEditorComponent::scrollToColumnInternal (double column)
  36312. {
  36313. const double newOffset = jlimit (0.0, document.getMaximumLineLength() + 3.0, column);
  36314. if (xOffset != newOffset)
  36315. {
  36316. xOffset = newOffset;
  36317. caret->updatePosition();
  36318. repaint();
  36319. }
  36320. }
  36321. void CodeEditorComponent::scrollToLine (int newFirstLineOnScreen)
  36322. {
  36323. scrollToLineInternal (newFirstLineOnScreen);
  36324. updateScrollBars();
  36325. }
  36326. void CodeEditorComponent::scrollToColumn (int newFirstColumnOnScreen)
  36327. {
  36328. scrollToColumnInternal (newFirstColumnOnScreen);
  36329. updateScrollBars();
  36330. }
  36331. void CodeEditorComponent::scrollBy (int deltaLines)
  36332. {
  36333. scrollToLine (firstLineOnScreen + deltaLines);
  36334. }
  36335. void CodeEditorComponent::scrollToKeepCaretOnScreen()
  36336. {
  36337. if (caretPos.getLineNumber() < firstLineOnScreen)
  36338. scrollBy (caretPos.getLineNumber() - firstLineOnScreen);
  36339. else if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  36340. scrollBy (caretPos.getLineNumber() - (firstLineOnScreen + linesOnScreen - 1));
  36341. const int column = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  36342. if (column >= xOffset + columnsOnScreen - 1)
  36343. scrollToColumn (column + 1 - columnsOnScreen);
  36344. else if (column < xOffset)
  36345. scrollToColumn (column);
  36346. }
  36347. const Rectangle<int> CodeEditorComponent::getCharacterBounds (const CodeDocument::Position& pos) const throw()
  36348. {
  36349. return Rectangle<int> (roundToInt ((gutter - xOffset * charWidth) + indexToColumn (pos.getLineNumber(), pos.getIndexInLine()) * charWidth),
  36350. (pos.getLineNumber() - firstLineOnScreen) * lineHeight,
  36351. roundToInt (charWidth),
  36352. lineHeight);
  36353. }
  36354. const CodeDocument::Position CodeEditorComponent::getPositionAt (int x, int y)
  36355. {
  36356. const int line = y / lineHeight + firstLineOnScreen;
  36357. const int column = roundToInt ((x - (gutter - xOffset * charWidth)) / charWidth);
  36358. const int index = columnToIndex (line, column);
  36359. return CodeDocument::Position (&document, line, index);
  36360. }
  36361. void CodeEditorComponent::insertTextAtCaret (const String& newText)
  36362. {
  36363. document.deleteSection (selectionStart, selectionEnd);
  36364. if (newText.isNotEmpty())
  36365. document.insertText (caretPos, newText);
  36366. scrollToKeepCaretOnScreen();
  36367. }
  36368. void CodeEditorComponent::insertTabAtCaret()
  36369. {
  36370. if (CharacterFunctions::isWhitespace (caretPos.getCharacter())
  36371. && caretPos.getLineNumber() == caretPos.movedBy (1).getLineNumber())
  36372. {
  36373. moveCaretTo (document.findWordBreakAfter (caretPos), false);
  36374. }
  36375. if (useSpacesForTabs)
  36376. {
  36377. const int caretCol = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  36378. const int spacesNeeded = spacesPerTab - (caretCol % spacesPerTab);
  36379. insertTextAtCaret (String::repeatedString (" ", spacesNeeded));
  36380. }
  36381. else
  36382. {
  36383. insertTextAtCaret ("\t");
  36384. }
  36385. }
  36386. void CodeEditorComponent::cut()
  36387. {
  36388. insertTextAtCaret (String::empty);
  36389. }
  36390. void CodeEditorComponent::copy()
  36391. {
  36392. newTransaction();
  36393. const String selection (document.getTextBetween (selectionStart, selectionEnd));
  36394. if (selection.isNotEmpty())
  36395. SystemClipboard::copyTextToClipboard (selection);
  36396. }
  36397. void CodeEditorComponent::copyThenCut()
  36398. {
  36399. copy();
  36400. cut();
  36401. newTransaction();
  36402. }
  36403. void CodeEditorComponent::paste()
  36404. {
  36405. newTransaction();
  36406. const String clip (SystemClipboard::getTextFromClipboard());
  36407. if (clip.isNotEmpty())
  36408. insertTextAtCaret (clip);
  36409. newTransaction();
  36410. }
  36411. void CodeEditorComponent::cursorLeft (const bool moveInWholeWordSteps, const bool selecting)
  36412. {
  36413. newTransaction();
  36414. if (moveInWholeWordSteps)
  36415. moveCaretTo (document.findWordBreakBefore (caretPos), selecting);
  36416. else
  36417. moveCaretTo (caretPos.movedBy (-1), selecting);
  36418. }
  36419. void CodeEditorComponent::cursorRight (const bool moveInWholeWordSteps, const bool selecting)
  36420. {
  36421. newTransaction();
  36422. if (moveInWholeWordSteps)
  36423. moveCaretTo (document.findWordBreakAfter (caretPos), selecting);
  36424. else
  36425. moveCaretTo (caretPos.movedBy (1), selecting);
  36426. }
  36427. void CodeEditorComponent::moveLineDelta (const int delta, const bool selecting)
  36428. {
  36429. CodeDocument::Position pos (caretPos);
  36430. const int newLineNum = pos.getLineNumber() + delta;
  36431. if (columnToTryToMaintain < 0)
  36432. columnToTryToMaintain = indexToColumn (pos.getLineNumber(), pos.getIndexInLine());
  36433. pos.setLineAndIndex (newLineNum, columnToIndex (newLineNum, columnToTryToMaintain));
  36434. const int colToMaintain = columnToTryToMaintain;
  36435. moveCaretTo (pos, selecting);
  36436. columnToTryToMaintain = colToMaintain;
  36437. }
  36438. void CodeEditorComponent::cursorDown (const bool selecting)
  36439. {
  36440. newTransaction();
  36441. if (caretPos.getLineNumber() == document.getNumLines() - 1)
  36442. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  36443. else
  36444. moveLineDelta (1, selecting);
  36445. }
  36446. void CodeEditorComponent::cursorUp (const bool selecting)
  36447. {
  36448. newTransaction();
  36449. if (caretPos.getLineNumber() == 0)
  36450. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  36451. else
  36452. moveLineDelta (-1, selecting);
  36453. }
  36454. void CodeEditorComponent::pageDown (const bool selecting)
  36455. {
  36456. newTransaction();
  36457. scrollBy (jlimit (0, linesOnScreen, 1 + document.getNumLines() - firstLineOnScreen - linesOnScreen));
  36458. moveLineDelta (linesOnScreen, selecting);
  36459. }
  36460. void CodeEditorComponent::pageUp (const bool selecting)
  36461. {
  36462. newTransaction();
  36463. scrollBy (-linesOnScreen);
  36464. moveLineDelta (-linesOnScreen, selecting);
  36465. }
  36466. void CodeEditorComponent::scrollUp()
  36467. {
  36468. newTransaction();
  36469. scrollBy (1);
  36470. if (caretPos.getLineNumber() < firstLineOnScreen)
  36471. moveLineDelta (1, false);
  36472. }
  36473. void CodeEditorComponent::scrollDown()
  36474. {
  36475. newTransaction();
  36476. scrollBy (-1);
  36477. if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  36478. moveLineDelta (-1, false);
  36479. }
  36480. void CodeEditorComponent::goToStartOfDocument (const bool selecting)
  36481. {
  36482. newTransaction();
  36483. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  36484. }
  36485. static int findFirstNonWhitespaceChar (const String& line) throw()
  36486. {
  36487. const int len = line.length();
  36488. for (int i = 0; i < len; ++i)
  36489. if (! CharacterFunctions::isWhitespace (line [i]))
  36490. return i;
  36491. return 0;
  36492. }
  36493. void CodeEditorComponent::goToStartOfLine (const bool selecting)
  36494. {
  36495. newTransaction();
  36496. int index = findFirstNonWhitespaceChar (caretPos.getLineText());
  36497. if (index >= caretPos.getIndexInLine() && caretPos.getIndexInLine() > 0)
  36498. index = 0;
  36499. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), index), selecting);
  36500. }
  36501. void CodeEditorComponent::goToEndOfDocument (const bool selecting)
  36502. {
  36503. newTransaction();
  36504. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  36505. }
  36506. void CodeEditorComponent::goToEndOfLine (const bool selecting)
  36507. {
  36508. newTransaction();
  36509. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), std::numeric_limits<int>::max()), selecting);
  36510. }
  36511. void CodeEditorComponent::backspace (const bool moveInWholeWordSteps)
  36512. {
  36513. if (moveInWholeWordSteps)
  36514. {
  36515. cut(); // in case something is already highlighted
  36516. moveCaretTo (document.findWordBreakBefore (caretPos), true);
  36517. }
  36518. else
  36519. {
  36520. if (selectionStart == selectionEnd)
  36521. selectionStart.moveBy (-1);
  36522. }
  36523. cut();
  36524. }
  36525. void CodeEditorComponent::deleteForward (const bool moveInWholeWordSteps)
  36526. {
  36527. if (moveInWholeWordSteps)
  36528. {
  36529. cut(); // in case something is already highlighted
  36530. moveCaretTo (document.findWordBreakAfter (caretPos), true);
  36531. }
  36532. else
  36533. {
  36534. if (selectionStart == selectionEnd)
  36535. selectionEnd.moveBy (1);
  36536. else
  36537. newTransaction();
  36538. }
  36539. cut();
  36540. }
  36541. void CodeEditorComponent::selectAll()
  36542. {
  36543. newTransaction();
  36544. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), false);
  36545. moveCaretTo (CodeDocument::Position (&document, 0, 0), true);
  36546. }
  36547. void CodeEditorComponent::undo()
  36548. {
  36549. document.undo();
  36550. scrollToKeepCaretOnScreen();
  36551. }
  36552. void CodeEditorComponent::redo()
  36553. {
  36554. document.redo();
  36555. scrollToKeepCaretOnScreen();
  36556. }
  36557. void CodeEditorComponent::newTransaction()
  36558. {
  36559. document.newTransaction();
  36560. startTimer (600);
  36561. }
  36562. void CodeEditorComponent::timerCallback()
  36563. {
  36564. newTransaction();
  36565. }
  36566. const Range<int> CodeEditorComponent::getHighlightedRegion() const
  36567. {
  36568. return Range<int> (selectionStart.getPosition(), selectionEnd.getPosition());
  36569. }
  36570. void CodeEditorComponent::setHighlightedRegion (const Range<int>& newRange)
  36571. {
  36572. moveCaretTo (CodeDocument::Position (&document, newRange.getStart()), false);
  36573. moveCaretTo (CodeDocument::Position (&document, newRange.getEnd()), true);
  36574. }
  36575. const String CodeEditorComponent::getTextInRange (const Range<int>& range) const
  36576. {
  36577. return document.getTextBetween (CodeDocument::Position (&document, range.getStart()),
  36578. CodeDocument::Position (&document, range.getEnd()));
  36579. }
  36580. bool CodeEditorComponent::keyPressed (const KeyPress& key)
  36581. {
  36582. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  36583. const bool shiftDown = key.getModifiers().isShiftDown();
  36584. if (key.isKeyCode (KeyPress::leftKey))
  36585. {
  36586. cursorLeft (moveInWholeWordSteps, shiftDown);
  36587. }
  36588. else if (key.isKeyCode (KeyPress::rightKey))
  36589. {
  36590. cursorRight (moveInWholeWordSteps, shiftDown);
  36591. }
  36592. else if (key.isKeyCode (KeyPress::upKey))
  36593. {
  36594. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  36595. scrollDown();
  36596. #if JUCE_MAC
  36597. else if (key.getModifiers().isCommandDown())
  36598. goToStartOfDocument (shiftDown);
  36599. #endif
  36600. else
  36601. cursorUp (shiftDown);
  36602. }
  36603. else if (key.isKeyCode (KeyPress::downKey))
  36604. {
  36605. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  36606. scrollUp();
  36607. #if JUCE_MAC
  36608. else if (key.getModifiers().isCommandDown())
  36609. goToEndOfDocument (shiftDown);
  36610. #endif
  36611. else
  36612. cursorDown (shiftDown);
  36613. }
  36614. else if (key.isKeyCode (KeyPress::pageDownKey))
  36615. {
  36616. pageDown (shiftDown);
  36617. }
  36618. else if (key.isKeyCode (KeyPress::pageUpKey))
  36619. {
  36620. pageUp (shiftDown);
  36621. }
  36622. else if (key.isKeyCode (KeyPress::homeKey))
  36623. {
  36624. if (moveInWholeWordSteps)
  36625. goToStartOfDocument (shiftDown);
  36626. else
  36627. goToStartOfLine (shiftDown);
  36628. }
  36629. else if (key.isKeyCode (KeyPress::endKey))
  36630. {
  36631. if (moveInWholeWordSteps)
  36632. goToEndOfDocument (shiftDown);
  36633. else
  36634. goToEndOfLine (shiftDown);
  36635. }
  36636. else if (key.isKeyCode (KeyPress::backspaceKey))
  36637. {
  36638. backspace (moveInWholeWordSteps);
  36639. }
  36640. else if (key.isKeyCode (KeyPress::deleteKey))
  36641. {
  36642. deleteForward (moveInWholeWordSteps);
  36643. }
  36644. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0))
  36645. {
  36646. copy();
  36647. }
  36648. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  36649. {
  36650. copyThenCut();
  36651. }
  36652. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0))
  36653. {
  36654. paste();
  36655. }
  36656. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  36657. {
  36658. undo();
  36659. }
  36660. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0)
  36661. || key == KeyPress ('z', ModifierKeys::commandModifier | ModifierKeys::shiftModifier, 0))
  36662. {
  36663. redo();
  36664. }
  36665. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  36666. {
  36667. selectAll();
  36668. }
  36669. else if (key == KeyPress::tabKey || key.getTextCharacter() == '\t')
  36670. {
  36671. insertTabAtCaret();
  36672. }
  36673. else if (key == KeyPress::returnKey)
  36674. {
  36675. newTransaction();
  36676. insertTextAtCaret (document.getNewLineCharacters());
  36677. }
  36678. else if (key.isKeyCode (KeyPress::escapeKey))
  36679. {
  36680. newTransaction();
  36681. }
  36682. else if (key.getTextCharacter() >= ' ')
  36683. {
  36684. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  36685. }
  36686. else
  36687. {
  36688. return false;
  36689. }
  36690. return true;
  36691. }
  36692. void CodeEditorComponent::mouseDown (const MouseEvent& e)
  36693. {
  36694. newTransaction();
  36695. dragType = notDragging;
  36696. if (! e.mods.isPopupMenu())
  36697. {
  36698. beginDragAutoRepeat (100);
  36699. moveCaretTo (getPositionAt (e.x, e.y), e.mods.isShiftDown());
  36700. }
  36701. else
  36702. {
  36703. /*PopupMenu m;
  36704. addPopupMenuItems (m, &e);
  36705. const int result = m.show();
  36706. if (result != 0)
  36707. performPopupMenuAction (result);
  36708. */
  36709. }
  36710. }
  36711. void CodeEditorComponent::mouseDrag (const MouseEvent& e)
  36712. {
  36713. if (! e.mods.isPopupMenu())
  36714. moveCaretTo (getPositionAt (e.x, e.y), true);
  36715. }
  36716. void CodeEditorComponent::mouseUp (const MouseEvent&)
  36717. {
  36718. newTransaction();
  36719. beginDragAutoRepeat (0);
  36720. dragType = notDragging;
  36721. }
  36722. void CodeEditorComponent::mouseDoubleClick (const MouseEvent& e)
  36723. {
  36724. CodeDocument::Position tokenStart (getPositionAt (e.x, e.y));
  36725. CodeDocument::Position tokenEnd (tokenStart);
  36726. if (e.getNumberOfClicks() > 2)
  36727. {
  36728. tokenStart.setLineAndIndex (tokenStart.getLineNumber(), 0);
  36729. tokenEnd.setLineAndIndex (tokenStart.getLineNumber() + 1, 0);
  36730. }
  36731. else
  36732. {
  36733. while (CharacterFunctions::isLetterOrDigit (tokenEnd.getCharacter()))
  36734. tokenEnd.moveBy (1);
  36735. tokenStart = tokenEnd;
  36736. while (tokenStart.getIndexInLine() > 0
  36737. && CharacterFunctions::isLetterOrDigit (tokenStart.movedBy (-1).getCharacter()))
  36738. tokenStart.moveBy (-1);
  36739. }
  36740. moveCaretTo (tokenEnd, false);
  36741. moveCaretTo (tokenStart, true);
  36742. }
  36743. void CodeEditorComponent::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  36744. {
  36745. if ((verticalScrollBar->isVisible() && wheelIncrementY != 0)
  36746. || (horizontalScrollBar->isVisible() && wheelIncrementX != 0))
  36747. {
  36748. verticalScrollBar->mouseWheelMove (e, 0, wheelIncrementY);
  36749. horizontalScrollBar->mouseWheelMove (e, wheelIncrementX, 0);
  36750. }
  36751. else
  36752. {
  36753. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  36754. }
  36755. }
  36756. void CodeEditorComponent::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  36757. {
  36758. if (scrollBarThatHasMoved == verticalScrollBar)
  36759. scrollToLineInternal ((int) newRangeStart);
  36760. else
  36761. scrollToColumnInternal (newRangeStart);
  36762. }
  36763. void CodeEditorComponent::focusGained (FocusChangeType)
  36764. {
  36765. caret->updatePosition();
  36766. }
  36767. void CodeEditorComponent::focusLost (FocusChangeType)
  36768. {
  36769. caret->updatePosition();
  36770. }
  36771. void CodeEditorComponent::setTabSize (const int numSpaces, const bool insertSpaces) throw()
  36772. {
  36773. useSpacesForTabs = insertSpaces;
  36774. if (spacesPerTab != numSpaces)
  36775. {
  36776. spacesPerTab = numSpaces;
  36777. triggerAsyncUpdate();
  36778. }
  36779. }
  36780. int CodeEditorComponent::indexToColumn (int lineNum, int index) const throw()
  36781. {
  36782. const String line (document.getLine (lineNum));
  36783. jassert (index <= line.length());
  36784. int col = 0;
  36785. for (int i = 0; i < index; ++i)
  36786. {
  36787. if (line[i] != '\t')
  36788. ++col;
  36789. else
  36790. col += getTabSize() - (col % getTabSize());
  36791. }
  36792. return col;
  36793. }
  36794. int CodeEditorComponent::columnToIndex (int lineNum, int column) const throw()
  36795. {
  36796. const String line (document.getLine (lineNum));
  36797. const int lineLength = line.length();
  36798. int i, col = 0;
  36799. for (i = 0; i < lineLength; ++i)
  36800. {
  36801. if (line[i] != '\t')
  36802. ++col;
  36803. else
  36804. col += getTabSize() - (col % getTabSize());
  36805. if (col > column)
  36806. break;
  36807. }
  36808. return i;
  36809. }
  36810. void CodeEditorComponent::setFont (const Font& newFont)
  36811. {
  36812. font = newFont;
  36813. charWidth = font.getStringWidthFloat ("0");
  36814. lineHeight = roundToInt (font.getHeight());
  36815. resized();
  36816. }
  36817. void CodeEditorComponent::resetToDefaultColours()
  36818. {
  36819. coloursForTokenCategories.clear();
  36820. if (codeTokeniser != 0)
  36821. {
  36822. for (int i = codeTokeniser->getTokenTypes().size(); --i >= 0;)
  36823. setColourForTokenType (i, codeTokeniser->getDefaultColour (i));
  36824. }
  36825. }
  36826. void CodeEditorComponent::setColourForTokenType (const int tokenType, const Colour& colour)
  36827. {
  36828. jassert (tokenType < 256);
  36829. while (coloursForTokenCategories.size() < tokenType)
  36830. coloursForTokenCategories.add (Colours::black);
  36831. coloursForTokenCategories.set (tokenType, colour);
  36832. repaint();
  36833. }
  36834. const Colour CodeEditorComponent::getColourForTokenType (const int tokenType) const throw()
  36835. {
  36836. if (((unsigned int) tokenType) >= (unsigned int) coloursForTokenCategories.size())
  36837. return findColour (CodeEditorComponent::defaultTextColourId);
  36838. return coloursForTokenCategories.getReference (tokenType);
  36839. }
  36840. void CodeEditorComponent::clearCachedIterators (const int firstLineToBeInvalid) throw()
  36841. {
  36842. int i;
  36843. for (i = cachedIterators.size(); --i >= 0;)
  36844. if (cachedIterators.getUnchecked (i)->getLine() < firstLineToBeInvalid)
  36845. break;
  36846. cachedIterators.removeRange (jmax (0, i - 1), cachedIterators.size());
  36847. }
  36848. void CodeEditorComponent::updateCachedIterators (int maxLineNum)
  36849. {
  36850. const int maxNumCachedPositions = 5000;
  36851. const int linesBetweenCachedSources = jmax (10, document.getNumLines() / maxNumCachedPositions);
  36852. if (cachedIterators.size() == 0)
  36853. cachedIterators.add (new CodeDocument::Iterator (&document));
  36854. if (codeTokeniser == 0)
  36855. return;
  36856. for (;;)
  36857. {
  36858. CodeDocument::Iterator* last = cachedIterators.getLast();
  36859. if (last->getLine() >= maxLineNum)
  36860. break;
  36861. CodeDocument::Iterator* t = new CodeDocument::Iterator (*last);
  36862. cachedIterators.add (t);
  36863. const int targetLine = last->getLine() + linesBetweenCachedSources;
  36864. for (;;)
  36865. {
  36866. codeTokeniser->readNextToken (*t);
  36867. if (t->getLine() >= targetLine)
  36868. break;
  36869. if (t->isEOF())
  36870. return;
  36871. }
  36872. }
  36873. }
  36874. void CodeEditorComponent::getIteratorForPosition (int position, CodeDocument::Iterator& source)
  36875. {
  36876. if (codeTokeniser == 0)
  36877. return;
  36878. for (int i = cachedIterators.size(); --i >= 0;)
  36879. {
  36880. CodeDocument::Iterator* t = cachedIterators.getUnchecked (i);
  36881. if (t->getPosition() <= position)
  36882. {
  36883. source = *t;
  36884. break;
  36885. }
  36886. }
  36887. while (source.getPosition() < position)
  36888. {
  36889. const CodeDocument::Iterator original (source);
  36890. codeTokeniser->readNextToken (source);
  36891. if (source.getPosition() > position || source.isEOF())
  36892. {
  36893. source = original;
  36894. break;
  36895. }
  36896. }
  36897. }
  36898. END_JUCE_NAMESPACE
  36899. /*** End of inlined file: juce_CodeEditorComponent.cpp ***/
  36900. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  36901. BEGIN_JUCE_NAMESPACE
  36902. CPlusPlusCodeTokeniser::CPlusPlusCodeTokeniser()
  36903. {
  36904. }
  36905. CPlusPlusCodeTokeniser::~CPlusPlusCodeTokeniser()
  36906. {
  36907. }
  36908. namespace CppTokeniser
  36909. {
  36910. static bool isIdentifierStart (const juce_wchar c) throw()
  36911. {
  36912. return CharacterFunctions::isLetter (c)
  36913. || c == '_' || c == '@';
  36914. }
  36915. static bool isIdentifierBody (const juce_wchar c) throw()
  36916. {
  36917. return CharacterFunctions::isLetterOrDigit (c)
  36918. || c == '_' || c == '@';
  36919. }
  36920. static bool isReservedKeyword (const juce_wchar* const token, const int tokenLength) throw()
  36921. {
  36922. static const juce_wchar* const keywords2Char[] =
  36923. { JUCE_T("if"), JUCE_T("do"), JUCE_T("or"), JUCE_T("id"), 0 };
  36924. static const juce_wchar* const keywords3Char[] =
  36925. { 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 };
  36926. static const juce_wchar* const keywords4Char[] =
  36927. { JUCE_T("bool"), JUCE_T("void"), JUCE_T("this"), JUCE_T("true"), JUCE_T("long"), JUCE_T("else"), JUCE_T("char"),
  36928. JUCE_T("enum"), JUCE_T("case"), JUCE_T("goto"), JUCE_T("auto"), 0 };
  36929. static const juce_wchar* const keywords5Char[] =
  36930. { JUCE_T("while"), JUCE_T("bitor"), JUCE_T("break"), JUCE_T("catch"), JUCE_T("class"), JUCE_T("compl"), JUCE_T("const"), JUCE_T("false"),
  36931. JUCE_T("float"), JUCE_T("short"), JUCE_T("throw"), JUCE_T("union"), JUCE_T("using"), JUCE_T("or_eq"), 0 };
  36932. static const juce_wchar* const keywords6Char[] =
  36933. { JUCE_T("return"), JUCE_T("struct"), JUCE_T("and_eq"), JUCE_T("bitand"), JUCE_T("delete"), JUCE_T("double"), JUCE_T("extern"),
  36934. JUCE_T("friend"), JUCE_T("inline"), JUCE_T("not_eq"), JUCE_T("public"), JUCE_T("sizeof"), JUCE_T("static"), JUCE_T("signed"),
  36935. JUCE_T("switch"), JUCE_T("typeid"), JUCE_T("wchar_t"), JUCE_T("xor_eq"), 0};
  36936. static const juce_wchar* const keywordsOther[] =
  36937. { JUCE_T("const_cast"), JUCE_T("continue"), JUCE_T("default"), JUCE_T("explicit"), JUCE_T("mutable"), JUCE_T("namespace"),
  36938. JUCE_T("operator"), JUCE_T("private"), JUCE_T("protected"), JUCE_T("register"), JUCE_T("reinterpret_cast"), JUCE_T("static_cast"),
  36939. JUCE_T("template"), JUCE_T("typedef"), JUCE_T("typename"), JUCE_T("unsigned"), JUCE_T("virtual"), JUCE_T("volatile"),
  36940. JUCE_T("@implementation"), JUCE_T("@interface"), JUCE_T("@end"), JUCE_T("@synthesize"), JUCE_T("@dynamic"), JUCE_T("@public"),
  36941. JUCE_T("@private"), JUCE_T("@property"), JUCE_T("@protected"), JUCE_T("@class"), 0 };
  36942. const juce_wchar* const* k;
  36943. switch (tokenLength)
  36944. {
  36945. case 2: k = keywords2Char; break;
  36946. case 3: k = keywords3Char; break;
  36947. case 4: k = keywords4Char; break;
  36948. case 5: k = keywords5Char; break;
  36949. case 6: k = keywords6Char; break;
  36950. default:
  36951. if (tokenLength < 2 || tokenLength > 16)
  36952. return false;
  36953. k = keywordsOther;
  36954. break;
  36955. }
  36956. int i = 0;
  36957. while (k[i] != 0)
  36958. {
  36959. if (k[i][0] == token[0] && CharacterFunctions::compare (k[i], token) == 0)
  36960. return true;
  36961. ++i;
  36962. }
  36963. return false;
  36964. }
  36965. static int parseIdentifier (CodeDocument::Iterator& source) throw()
  36966. {
  36967. int tokenLength = 0;
  36968. juce_wchar possibleIdentifier [19];
  36969. while (isIdentifierBody (source.peekNextChar()))
  36970. {
  36971. const juce_wchar c = source.nextChar();
  36972. if (tokenLength < numElementsInArray (possibleIdentifier) - 1)
  36973. possibleIdentifier [tokenLength] = c;
  36974. ++tokenLength;
  36975. }
  36976. if (tokenLength > 1 && tokenLength <= 16)
  36977. {
  36978. possibleIdentifier [tokenLength] = 0;
  36979. if (isReservedKeyword (possibleIdentifier, tokenLength))
  36980. return CPlusPlusCodeTokeniser::tokenType_builtInKeyword;
  36981. }
  36982. return CPlusPlusCodeTokeniser::tokenType_identifier;
  36983. }
  36984. static bool skipNumberSuffix (CodeDocument::Iterator& source)
  36985. {
  36986. const juce_wchar c = source.peekNextChar();
  36987. if (c == 'l' || c == 'L' || c == 'u' || c == 'U')
  36988. source.skip();
  36989. if (CharacterFunctions::isLetterOrDigit (source.peekNextChar()))
  36990. return false;
  36991. return true;
  36992. }
  36993. static bool isHexDigit (const juce_wchar c) throw()
  36994. {
  36995. return (c >= '0' && c <= '9')
  36996. || (c >= 'a' && c <= 'f')
  36997. || (c >= 'A' && c <= 'F');
  36998. }
  36999. static bool parseHexLiteral (CodeDocument::Iterator& source) throw()
  37000. {
  37001. if (source.nextChar() != '0')
  37002. return false;
  37003. juce_wchar c = source.nextChar();
  37004. if (c != 'x' && c != 'X')
  37005. return false;
  37006. int numDigits = 0;
  37007. while (isHexDigit (source.peekNextChar()))
  37008. {
  37009. ++numDigits;
  37010. source.skip();
  37011. }
  37012. if (numDigits == 0)
  37013. return false;
  37014. return skipNumberSuffix (source);
  37015. }
  37016. static bool isOctalDigit (const juce_wchar c) throw()
  37017. {
  37018. return c >= '0' && c <= '7';
  37019. }
  37020. static bool parseOctalLiteral (CodeDocument::Iterator& source) throw()
  37021. {
  37022. if (source.nextChar() != '0')
  37023. return false;
  37024. if (! isOctalDigit (source.nextChar()))
  37025. return false;
  37026. while (isOctalDigit (source.peekNextChar()))
  37027. source.skip();
  37028. return skipNumberSuffix (source);
  37029. }
  37030. static bool isDecimalDigit (const juce_wchar c) throw()
  37031. {
  37032. return c >= '0' && c <= '9';
  37033. }
  37034. static bool parseDecimalLiteral (CodeDocument::Iterator& source) throw()
  37035. {
  37036. int numChars = 0;
  37037. while (isDecimalDigit (source.peekNextChar()))
  37038. {
  37039. ++numChars;
  37040. source.skip();
  37041. }
  37042. if (numChars == 0)
  37043. return false;
  37044. return skipNumberSuffix (source);
  37045. }
  37046. static bool parseFloatLiteral (CodeDocument::Iterator& source) throw()
  37047. {
  37048. int numDigits = 0;
  37049. while (isDecimalDigit (source.peekNextChar()))
  37050. {
  37051. source.skip();
  37052. ++numDigits;
  37053. }
  37054. const bool hasPoint = (source.peekNextChar() == '.');
  37055. if (hasPoint)
  37056. {
  37057. source.skip();
  37058. while (isDecimalDigit (source.peekNextChar()))
  37059. {
  37060. source.skip();
  37061. ++numDigits;
  37062. }
  37063. }
  37064. if (numDigits == 0)
  37065. return false;
  37066. juce_wchar c = source.peekNextChar();
  37067. const bool hasExponent = (c == 'e' || c == 'E');
  37068. if (hasExponent)
  37069. {
  37070. source.skip();
  37071. c = source.peekNextChar();
  37072. if (c == '+' || c == '-')
  37073. source.skip();
  37074. int numExpDigits = 0;
  37075. while (isDecimalDigit (source.peekNextChar()))
  37076. {
  37077. source.skip();
  37078. ++numExpDigits;
  37079. }
  37080. if (numExpDigits == 0)
  37081. return false;
  37082. }
  37083. c = source.peekNextChar();
  37084. if (c == 'f' || c == 'F')
  37085. source.skip();
  37086. else if (! (hasExponent || hasPoint))
  37087. return false;
  37088. return true;
  37089. }
  37090. static int parseNumber (CodeDocument::Iterator& source)
  37091. {
  37092. const CodeDocument::Iterator original (source);
  37093. if (parseFloatLiteral (source))
  37094. return CPlusPlusCodeTokeniser::tokenType_floatLiteral;
  37095. source = original;
  37096. if (parseHexLiteral (source))
  37097. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37098. source = original;
  37099. if (parseOctalLiteral (source))
  37100. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37101. source = original;
  37102. if (parseDecimalLiteral (source))
  37103. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37104. source = original;
  37105. source.skip();
  37106. return CPlusPlusCodeTokeniser::tokenType_error;
  37107. }
  37108. static void skipQuotedString (CodeDocument::Iterator& source) throw()
  37109. {
  37110. const juce_wchar quote = source.nextChar();
  37111. for (;;)
  37112. {
  37113. const juce_wchar c = source.nextChar();
  37114. if (c == quote || c == 0)
  37115. break;
  37116. if (c == '\\')
  37117. source.skip();
  37118. }
  37119. }
  37120. static void skipComment (CodeDocument::Iterator& source) throw()
  37121. {
  37122. bool lastWasStar = false;
  37123. for (;;)
  37124. {
  37125. const juce_wchar c = source.nextChar();
  37126. if (c == 0 || (c == '/' && lastWasStar))
  37127. break;
  37128. lastWasStar = (c == '*');
  37129. }
  37130. }
  37131. }
  37132. int CPlusPlusCodeTokeniser::readNextToken (CodeDocument::Iterator& source)
  37133. {
  37134. int result = tokenType_error;
  37135. source.skipWhitespace();
  37136. juce_wchar firstChar = source.peekNextChar();
  37137. switch (firstChar)
  37138. {
  37139. case 0:
  37140. source.skip();
  37141. break;
  37142. case '0':
  37143. case '1':
  37144. case '2':
  37145. case '3':
  37146. case '4':
  37147. case '5':
  37148. case '6':
  37149. case '7':
  37150. case '8':
  37151. case '9':
  37152. result = CppTokeniser::parseNumber (source);
  37153. break;
  37154. case '.':
  37155. result = CppTokeniser::parseNumber (source);
  37156. if (result == tokenType_error)
  37157. result = tokenType_punctuation;
  37158. break;
  37159. case ',':
  37160. case ';':
  37161. case ':':
  37162. source.skip();
  37163. result = tokenType_punctuation;
  37164. break;
  37165. case '(':
  37166. case ')':
  37167. case '{':
  37168. case '}':
  37169. case '[':
  37170. case ']':
  37171. source.skip();
  37172. result = tokenType_bracket;
  37173. break;
  37174. case '"':
  37175. case '\'':
  37176. CppTokeniser::skipQuotedString (source);
  37177. result = tokenType_stringLiteral;
  37178. break;
  37179. case '+':
  37180. result = tokenType_operator;
  37181. source.skip();
  37182. if (source.peekNextChar() == '+')
  37183. source.skip();
  37184. else if (source.peekNextChar() == '=')
  37185. source.skip();
  37186. break;
  37187. case '-':
  37188. source.skip();
  37189. result = CppTokeniser::parseNumber (source);
  37190. if (result == tokenType_error)
  37191. {
  37192. result = tokenType_operator;
  37193. if (source.peekNextChar() == '-')
  37194. source.skip();
  37195. else if (source.peekNextChar() == '=')
  37196. source.skip();
  37197. }
  37198. break;
  37199. case '*':
  37200. case '%':
  37201. case '=':
  37202. case '!':
  37203. result = tokenType_operator;
  37204. source.skip();
  37205. if (source.peekNextChar() == '=')
  37206. source.skip();
  37207. break;
  37208. case '/':
  37209. result = tokenType_operator;
  37210. source.skip();
  37211. if (source.peekNextChar() == '=')
  37212. {
  37213. source.skip();
  37214. }
  37215. else if (source.peekNextChar() == '/')
  37216. {
  37217. result = tokenType_comment;
  37218. source.skipToEndOfLine();
  37219. }
  37220. else if (source.peekNextChar() == '*')
  37221. {
  37222. source.skip();
  37223. result = tokenType_comment;
  37224. CppTokeniser::skipComment (source);
  37225. }
  37226. break;
  37227. case '?':
  37228. case '~':
  37229. source.skip();
  37230. result = tokenType_operator;
  37231. break;
  37232. case '<':
  37233. source.skip();
  37234. result = tokenType_operator;
  37235. if (source.peekNextChar() == '=')
  37236. {
  37237. source.skip();
  37238. }
  37239. else if (source.peekNextChar() == '<')
  37240. {
  37241. source.skip();
  37242. if (source.peekNextChar() == '=')
  37243. source.skip();
  37244. }
  37245. break;
  37246. case '>':
  37247. source.skip();
  37248. result = tokenType_operator;
  37249. if (source.peekNextChar() == '=')
  37250. {
  37251. source.skip();
  37252. }
  37253. else if (source.peekNextChar() == '<')
  37254. {
  37255. source.skip();
  37256. if (source.peekNextChar() == '=')
  37257. source.skip();
  37258. }
  37259. break;
  37260. case '|':
  37261. source.skip();
  37262. result = tokenType_operator;
  37263. if (source.peekNextChar() == '=')
  37264. {
  37265. source.skip();
  37266. }
  37267. else if (source.peekNextChar() == '|')
  37268. {
  37269. source.skip();
  37270. if (source.peekNextChar() == '=')
  37271. source.skip();
  37272. }
  37273. break;
  37274. case '&':
  37275. source.skip();
  37276. result = tokenType_operator;
  37277. if (source.peekNextChar() == '=')
  37278. {
  37279. source.skip();
  37280. }
  37281. else if (source.peekNextChar() == '&')
  37282. {
  37283. source.skip();
  37284. if (source.peekNextChar() == '=')
  37285. source.skip();
  37286. }
  37287. break;
  37288. case '^':
  37289. source.skip();
  37290. result = tokenType_operator;
  37291. if (source.peekNextChar() == '=')
  37292. {
  37293. source.skip();
  37294. }
  37295. else if (source.peekNextChar() == '^')
  37296. {
  37297. source.skip();
  37298. if (source.peekNextChar() == '=')
  37299. source.skip();
  37300. }
  37301. break;
  37302. case '#':
  37303. result = tokenType_preprocessor;
  37304. source.skipToEndOfLine();
  37305. break;
  37306. default:
  37307. if (CppTokeniser::isIdentifierStart (firstChar))
  37308. result = CppTokeniser::parseIdentifier (source);
  37309. else
  37310. source.skip();
  37311. break;
  37312. }
  37313. return result;
  37314. }
  37315. const StringArray CPlusPlusCodeTokeniser::getTokenTypes()
  37316. {
  37317. const char* const types[] =
  37318. {
  37319. "Error",
  37320. "Comment",
  37321. "C++ keyword",
  37322. "Identifier",
  37323. "Integer literal",
  37324. "Float literal",
  37325. "String literal",
  37326. "Operator",
  37327. "Bracket",
  37328. "Punctuation",
  37329. "Preprocessor line",
  37330. 0
  37331. };
  37332. return StringArray (types);
  37333. }
  37334. const Colour CPlusPlusCodeTokeniser::getDefaultColour (const int tokenType)
  37335. {
  37336. const uint32 colours[] =
  37337. {
  37338. 0xffcc0000, // error
  37339. 0xff00aa00, // comment
  37340. 0xff0000cc, // keyword
  37341. 0xff000000, // identifier
  37342. 0xff880000, // int literal
  37343. 0xff885500, // float literal
  37344. 0xff990099, // string literal
  37345. 0xff225500, // operator
  37346. 0xff000055, // bracket
  37347. 0xff004400, // punctuation
  37348. 0xff660000 // preprocessor
  37349. };
  37350. if (tokenType >= 0 && tokenType < numElementsInArray (colours))
  37351. return Colour (colours [tokenType]);
  37352. return Colours::black;
  37353. }
  37354. bool CPlusPlusCodeTokeniser::isReservedKeyword (const String& token) throw()
  37355. {
  37356. return CppTokeniser::isReservedKeyword (token, token.length());
  37357. }
  37358. END_JUCE_NAMESPACE
  37359. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  37360. /*** Start of inlined file: juce_ComboBox.cpp ***/
  37361. BEGIN_JUCE_NAMESPACE
  37362. ComboBox::ComboBox (const String& name)
  37363. : Component (name),
  37364. lastCurrentId (0),
  37365. isButtonDown (false),
  37366. separatorPending (false),
  37367. menuActive (false),
  37368. label (0)
  37369. {
  37370. noChoicesMessage = TRANS("(no choices)");
  37371. setRepaintsOnMouseActivity (true);
  37372. lookAndFeelChanged();
  37373. currentId.addListener (this);
  37374. }
  37375. ComboBox::~ComboBox()
  37376. {
  37377. currentId.removeListener (this);
  37378. if (menuActive)
  37379. PopupMenu::dismissAllActiveMenus();
  37380. label = 0;
  37381. deleteAllChildren();
  37382. }
  37383. void ComboBox::setEditableText (const bool isEditable)
  37384. {
  37385. if (label->isEditableOnSingleClick() != isEditable || label->isEditableOnDoubleClick() != isEditable)
  37386. {
  37387. label->setEditable (isEditable, isEditable, false);
  37388. setWantsKeyboardFocus (! isEditable);
  37389. resized();
  37390. }
  37391. }
  37392. bool ComboBox::isTextEditable() const throw()
  37393. {
  37394. return label->isEditable();
  37395. }
  37396. void ComboBox::setJustificationType (const Justification& justification) throw()
  37397. {
  37398. label->setJustificationType (justification);
  37399. }
  37400. const Justification ComboBox::getJustificationType() const throw()
  37401. {
  37402. return label->getJustificationType();
  37403. }
  37404. void ComboBox::setTooltip (const String& newTooltip)
  37405. {
  37406. SettableTooltipClient::setTooltip (newTooltip);
  37407. label->setTooltip (newTooltip);
  37408. }
  37409. void ComboBox::addItem (const String& newItemText,
  37410. const int newItemId) throw()
  37411. {
  37412. // you can't add empty strings to the list..
  37413. jassert (newItemText.isNotEmpty());
  37414. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  37415. jassert (newItemId != 0);
  37416. // you shouldn't use duplicate item IDs!
  37417. jassert (getItemForId (newItemId) == 0);
  37418. if (newItemText.isNotEmpty() && newItemId != 0)
  37419. {
  37420. if (separatorPending)
  37421. {
  37422. separatorPending = false;
  37423. ItemInfo* const item = new ItemInfo();
  37424. item->itemId = 0;
  37425. item->isEnabled = false;
  37426. item->isHeading = false;
  37427. items.add (item);
  37428. }
  37429. ItemInfo* const item = new ItemInfo();
  37430. item->name = newItemText;
  37431. item->itemId = newItemId;
  37432. item->isEnabled = true;
  37433. item->isHeading = false;
  37434. items.add (item);
  37435. }
  37436. }
  37437. void ComboBox::addSeparator() throw()
  37438. {
  37439. separatorPending = (items.size() > 0);
  37440. }
  37441. void ComboBox::addSectionHeading (const String& headingName) throw()
  37442. {
  37443. // you can't add empty strings to the list..
  37444. jassert (headingName.isNotEmpty());
  37445. if (headingName.isNotEmpty())
  37446. {
  37447. if (separatorPending)
  37448. {
  37449. separatorPending = false;
  37450. ItemInfo* const item = new ItemInfo();
  37451. item->itemId = 0;
  37452. item->isEnabled = false;
  37453. item->isHeading = false;
  37454. items.add (item);
  37455. }
  37456. ItemInfo* const item = new ItemInfo();
  37457. item->name = headingName;
  37458. item->itemId = 0;
  37459. item->isEnabled = true;
  37460. item->isHeading = true;
  37461. items.add (item);
  37462. }
  37463. }
  37464. void ComboBox::setItemEnabled (const int itemId,
  37465. const bool shouldBeEnabled) throw()
  37466. {
  37467. ItemInfo* const item = getItemForId (itemId);
  37468. if (item != 0)
  37469. item->isEnabled = shouldBeEnabled;
  37470. }
  37471. void ComboBox::changeItemText (const int itemId,
  37472. const String& newText) throw()
  37473. {
  37474. ItemInfo* const item = getItemForId (itemId);
  37475. jassert (item != 0);
  37476. if (item != 0)
  37477. item->name = newText;
  37478. }
  37479. void ComboBox::clear (const bool dontSendChangeMessage)
  37480. {
  37481. items.clear();
  37482. separatorPending = false;
  37483. if (! label->isEditable())
  37484. setSelectedItemIndex (-1, dontSendChangeMessage);
  37485. }
  37486. bool ComboBox::ItemInfo::isSeparator() const throw()
  37487. {
  37488. return name.isEmpty();
  37489. }
  37490. bool ComboBox::ItemInfo::isRealItem() const throw()
  37491. {
  37492. return ! (isHeading || name.isEmpty());
  37493. }
  37494. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  37495. {
  37496. if (itemId != 0)
  37497. {
  37498. for (int i = items.size(); --i >= 0;)
  37499. if (items.getUnchecked(i)->itemId == itemId)
  37500. return items.getUnchecked(i);
  37501. }
  37502. return 0;
  37503. }
  37504. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  37505. {
  37506. int n = 0;
  37507. for (int i = 0; i < items.size(); ++i)
  37508. {
  37509. ItemInfo* const item = items.getUnchecked(i);
  37510. if (item->isRealItem())
  37511. if (n++ == index)
  37512. return item;
  37513. }
  37514. return 0;
  37515. }
  37516. int ComboBox::getNumItems() const throw()
  37517. {
  37518. int n = 0;
  37519. for (int i = items.size(); --i >= 0;)
  37520. if (items.getUnchecked(i)->isRealItem())
  37521. ++n;
  37522. return n;
  37523. }
  37524. const String ComboBox::getItemText (const int index) const throw()
  37525. {
  37526. const ItemInfo* const item = getItemForIndex (index);
  37527. if (item != 0)
  37528. return item->name;
  37529. return String::empty;
  37530. }
  37531. int ComboBox::getItemId (const int index) const throw()
  37532. {
  37533. const ItemInfo* const item = getItemForIndex (index);
  37534. return (item != 0) ? item->itemId : 0;
  37535. }
  37536. int ComboBox::indexOfItemId (const int itemId) const throw()
  37537. {
  37538. int n = 0;
  37539. for (int i = 0; i < items.size(); ++i)
  37540. {
  37541. const ItemInfo* const item = items.getUnchecked(i);
  37542. if (item->isRealItem())
  37543. {
  37544. if (item->itemId == itemId)
  37545. return n;
  37546. ++n;
  37547. }
  37548. }
  37549. return -1;
  37550. }
  37551. int ComboBox::getSelectedItemIndex() const throw()
  37552. {
  37553. int index = indexOfItemId (currentId.getValue());
  37554. if (getText() != getItemText (index))
  37555. index = -1;
  37556. return index;
  37557. }
  37558. void ComboBox::setSelectedItemIndex (const int index,
  37559. const bool dontSendChangeMessage) throw()
  37560. {
  37561. setSelectedId (getItemId (index), dontSendChangeMessage);
  37562. }
  37563. int ComboBox::getSelectedId() const throw()
  37564. {
  37565. const ItemInfo* const item = getItemForId (currentId.getValue());
  37566. return (item != 0 && getText() == item->name)
  37567. ? item->itemId
  37568. : 0;
  37569. }
  37570. void ComboBox::setSelectedId (const int newItemId,
  37571. const bool dontSendChangeMessage) throw()
  37572. {
  37573. const ItemInfo* const item = getItemForId (newItemId);
  37574. const String newItemText (item != 0 ? item->name : String::empty);
  37575. if (lastCurrentId != newItemId || label->getText() != newItemText)
  37576. {
  37577. if (! dontSendChangeMessage)
  37578. triggerAsyncUpdate();
  37579. label->setText (newItemText, false);
  37580. lastCurrentId = newItemId;
  37581. currentId = newItemId;
  37582. repaint(); // for the benefit of the 'none selected' text
  37583. }
  37584. }
  37585. void ComboBox::valueChanged (Value&)
  37586. {
  37587. if (lastCurrentId != (int) currentId.getValue())
  37588. setSelectedId (currentId.getValue(), false);
  37589. }
  37590. const String ComboBox::getText() const throw()
  37591. {
  37592. return label->getText();
  37593. }
  37594. void ComboBox::setText (const String& newText,
  37595. const bool dontSendChangeMessage) throw()
  37596. {
  37597. for (int i = items.size(); --i >= 0;)
  37598. {
  37599. const ItemInfo* const item = items.getUnchecked(i);
  37600. if (item->isRealItem()
  37601. && item->name == newText)
  37602. {
  37603. setSelectedId (item->itemId, dontSendChangeMessage);
  37604. return;
  37605. }
  37606. }
  37607. lastCurrentId = 0;
  37608. currentId = 0;
  37609. if (label->getText() != newText)
  37610. {
  37611. label->setText (newText, false);
  37612. if (! dontSendChangeMessage)
  37613. triggerAsyncUpdate();
  37614. }
  37615. repaint();
  37616. }
  37617. void ComboBox::showEditor()
  37618. {
  37619. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  37620. label->showEditor();
  37621. }
  37622. void ComboBox::setTextWhenNothingSelected (const String& newMessage) throw()
  37623. {
  37624. if (textWhenNothingSelected != newMessage)
  37625. {
  37626. textWhenNothingSelected = newMessage;
  37627. repaint();
  37628. }
  37629. }
  37630. const String ComboBox::getTextWhenNothingSelected() const throw()
  37631. {
  37632. return textWhenNothingSelected;
  37633. }
  37634. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage) throw()
  37635. {
  37636. noChoicesMessage = newMessage;
  37637. }
  37638. const String ComboBox::getTextWhenNoChoicesAvailable() const throw()
  37639. {
  37640. return noChoicesMessage;
  37641. }
  37642. void ComboBox::paint (Graphics& g)
  37643. {
  37644. getLookAndFeel().drawComboBox (g,
  37645. getWidth(),
  37646. getHeight(),
  37647. isButtonDown,
  37648. label->getRight(),
  37649. 0,
  37650. getWidth() - label->getRight(),
  37651. getHeight(),
  37652. *this);
  37653. if (textWhenNothingSelected.isNotEmpty()
  37654. && label->getText().isEmpty()
  37655. && ! label->isBeingEdited())
  37656. {
  37657. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  37658. g.setFont (label->getFont());
  37659. g.drawFittedText (textWhenNothingSelected,
  37660. label->getX() + 2, label->getY() + 1,
  37661. label->getWidth() - 4, label->getHeight() - 2,
  37662. label->getJustificationType(),
  37663. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  37664. }
  37665. }
  37666. void ComboBox::resized()
  37667. {
  37668. if (getHeight() > 0 && getWidth() > 0)
  37669. getLookAndFeel().positionComboBoxText (*this, *label);
  37670. }
  37671. void ComboBox::enablementChanged()
  37672. {
  37673. repaint();
  37674. }
  37675. void ComboBox::lookAndFeelChanged()
  37676. {
  37677. repaint();
  37678. Label* const newLabel = getLookAndFeel().createComboBoxTextBox (*this);
  37679. if (label != 0)
  37680. {
  37681. newLabel->setEditable (label->isEditable());
  37682. newLabel->setJustificationType (label->getJustificationType());
  37683. newLabel->setTooltip (label->getTooltip());
  37684. newLabel->setText (label->getText(), false);
  37685. }
  37686. label = newLabel;
  37687. addAndMakeVisible (newLabel);
  37688. newLabel->addListener (this);
  37689. newLabel->addMouseListener (this, false);
  37690. newLabel->setColour (Label::backgroundColourId, Colours::transparentBlack);
  37691. newLabel->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  37692. newLabel->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  37693. newLabel->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  37694. newLabel->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  37695. newLabel->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  37696. resized();
  37697. }
  37698. void ComboBox::colourChanged()
  37699. {
  37700. lookAndFeelChanged();
  37701. }
  37702. bool ComboBox::keyPressed (const KeyPress& key)
  37703. {
  37704. bool used = false;
  37705. if (key.isKeyCode (KeyPress::upKey)
  37706. || key.isKeyCode (KeyPress::leftKey))
  37707. {
  37708. setSelectedItemIndex (jmax (0, getSelectedItemIndex() - 1));
  37709. used = true;
  37710. }
  37711. else if (key.isKeyCode (KeyPress::downKey)
  37712. || key.isKeyCode (KeyPress::rightKey))
  37713. {
  37714. setSelectedItemIndex (jmin (getSelectedItemIndex() + 1, getNumItems() - 1));
  37715. used = true;
  37716. }
  37717. else if (key.isKeyCode (KeyPress::returnKey))
  37718. {
  37719. showPopup();
  37720. used = true;
  37721. }
  37722. return used;
  37723. }
  37724. bool ComboBox::keyStateChanged (const bool isKeyDown)
  37725. {
  37726. // only forward key events that aren't used by this component
  37727. return isKeyDown
  37728. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  37729. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  37730. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  37731. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey));
  37732. }
  37733. void ComboBox::focusGained (FocusChangeType)
  37734. {
  37735. repaint();
  37736. }
  37737. void ComboBox::focusLost (FocusChangeType)
  37738. {
  37739. repaint();
  37740. }
  37741. void ComboBox::labelTextChanged (Label*)
  37742. {
  37743. triggerAsyncUpdate();
  37744. }
  37745. class ComboBox::Callback : public ModalComponentManager::Callback
  37746. {
  37747. public:
  37748. Callback (ComboBox* const box_)
  37749. : box (box_)
  37750. {
  37751. }
  37752. void modalStateFinished (int returnValue)
  37753. {
  37754. if (box != 0)
  37755. {
  37756. box->menuActive = false;
  37757. if (returnValue != 0)
  37758. box->setSelectedId (returnValue);
  37759. }
  37760. }
  37761. private:
  37762. Component::SafePointer<ComboBox> box;
  37763. Callback (const Callback&);
  37764. Callback& operator= (const Callback&);
  37765. };
  37766. void ComboBox::showPopup()
  37767. {
  37768. if (! menuActive)
  37769. {
  37770. const int selectedId = getSelectedId();
  37771. PopupMenu menu;
  37772. menu.setLookAndFeel (&getLookAndFeel());
  37773. for (int i = 0; i < items.size(); ++i)
  37774. {
  37775. const ItemInfo* const item = items.getUnchecked(i);
  37776. if (item->isSeparator())
  37777. menu.addSeparator();
  37778. else if (item->isHeading)
  37779. menu.addSectionHeader (item->name);
  37780. else
  37781. menu.addItem (item->itemId, item->name,
  37782. item->isEnabled, item->itemId == selectedId);
  37783. }
  37784. if (items.size() == 0)
  37785. menu.addItem (1, noChoicesMessage, false);
  37786. menuActive = true;
  37787. menu.showAt (this, selectedId, getWidth(), 1, jlimit (12, 24, getHeight()),
  37788. new Callback (this));
  37789. }
  37790. }
  37791. void ComboBox::mouseDown (const MouseEvent& e)
  37792. {
  37793. beginDragAutoRepeat (300);
  37794. isButtonDown = isEnabled();
  37795. if (isButtonDown
  37796. && (e.eventComponent == this || ! label->isEditable()))
  37797. {
  37798. showPopup();
  37799. }
  37800. }
  37801. void ComboBox::mouseDrag (const MouseEvent& e)
  37802. {
  37803. beginDragAutoRepeat (50);
  37804. if (isButtonDown && ! e.mouseWasClicked())
  37805. showPopup();
  37806. }
  37807. void ComboBox::mouseUp (const MouseEvent& e2)
  37808. {
  37809. if (isButtonDown)
  37810. {
  37811. isButtonDown = false;
  37812. repaint();
  37813. const MouseEvent e (e2.getEventRelativeTo (this));
  37814. if (reallyContains (e.x, e.y, true)
  37815. && (e2.eventComponent == this || ! label->isEditable()))
  37816. {
  37817. showPopup();
  37818. }
  37819. }
  37820. }
  37821. void ComboBox::addListener (ComboBoxListener* const listener) throw()
  37822. {
  37823. listeners.add (listener);
  37824. }
  37825. void ComboBox::removeListener (ComboBoxListener* const listener) throw()
  37826. {
  37827. listeners.remove (listener);
  37828. }
  37829. void ComboBox::handleAsyncUpdate()
  37830. {
  37831. Component::BailOutChecker checker (this);
  37832. listeners.callChecked (checker, &ComboBoxListener::comboBoxChanged, this);
  37833. }
  37834. END_JUCE_NAMESPACE
  37835. /*** End of inlined file: juce_ComboBox.cpp ***/
  37836. /*** Start of inlined file: juce_Label.cpp ***/
  37837. BEGIN_JUCE_NAMESPACE
  37838. Label::Label (const String& componentName,
  37839. const String& labelText)
  37840. : Component (componentName),
  37841. textValue (labelText),
  37842. lastTextValue (labelText),
  37843. font (15.0f),
  37844. justification (Justification::centredLeft),
  37845. ownerComponent (0),
  37846. horizontalBorderSize (5),
  37847. verticalBorderSize (1),
  37848. minimumHorizontalScale (0.7f),
  37849. editSingleClick (false),
  37850. editDoubleClick (false),
  37851. lossOfFocusDiscardsChanges (false)
  37852. {
  37853. setColour (TextEditor::textColourId, Colours::black);
  37854. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  37855. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  37856. textValue.addListener (this);
  37857. }
  37858. Label::~Label()
  37859. {
  37860. textValue.removeListener (this);
  37861. if (ownerComponent != 0)
  37862. ownerComponent->removeComponentListener (this);
  37863. editor = 0;
  37864. }
  37865. void Label::setText (const String& newText,
  37866. const bool broadcastChangeMessage)
  37867. {
  37868. hideEditor (true);
  37869. if (lastTextValue != newText)
  37870. {
  37871. lastTextValue = newText;
  37872. textValue = newText;
  37873. repaint();
  37874. textWasChanged();
  37875. if (ownerComponent != 0)
  37876. componentMovedOrResized (*ownerComponent, true, true);
  37877. if (broadcastChangeMessage)
  37878. callChangeListeners();
  37879. }
  37880. }
  37881. const String Label::getText (const bool returnActiveEditorContents) const throw()
  37882. {
  37883. return (returnActiveEditorContents && isBeingEdited())
  37884. ? editor->getText()
  37885. : textValue.toString();
  37886. }
  37887. void Label::valueChanged (Value&)
  37888. {
  37889. if (lastTextValue != textValue.toString())
  37890. setText (textValue.toString(), true);
  37891. }
  37892. void Label::setFont (const Font& newFont) throw()
  37893. {
  37894. if (font != newFont)
  37895. {
  37896. font = newFont;
  37897. repaint();
  37898. }
  37899. }
  37900. const Font& Label::getFont() const throw()
  37901. {
  37902. return font;
  37903. }
  37904. void Label::setEditable (const bool editOnSingleClick,
  37905. const bool editOnDoubleClick,
  37906. const bool lossOfFocusDiscardsChanges_) throw()
  37907. {
  37908. editSingleClick = editOnSingleClick;
  37909. editDoubleClick = editOnDoubleClick;
  37910. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  37911. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  37912. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  37913. }
  37914. void Label::setJustificationType (const Justification& newJustification) throw()
  37915. {
  37916. if (justification != newJustification)
  37917. {
  37918. justification = newJustification;
  37919. repaint();
  37920. }
  37921. }
  37922. void Label::setBorderSize (int h, int v)
  37923. {
  37924. if (horizontalBorderSize != h || verticalBorderSize != v)
  37925. {
  37926. horizontalBorderSize = h;
  37927. verticalBorderSize = v;
  37928. repaint();
  37929. }
  37930. }
  37931. Component* Label::getAttachedComponent() const
  37932. {
  37933. return static_cast<Component*> (ownerComponent);
  37934. }
  37935. void Label::attachToComponent (Component* owner,
  37936. const bool onLeft)
  37937. {
  37938. if (ownerComponent != 0)
  37939. ownerComponent->removeComponentListener (this);
  37940. ownerComponent = owner;
  37941. leftOfOwnerComp = onLeft;
  37942. if (ownerComponent != 0)
  37943. {
  37944. setVisible (owner->isVisible());
  37945. ownerComponent->addComponentListener (this);
  37946. componentParentHierarchyChanged (*ownerComponent);
  37947. componentMovedOrResized (*ownerComponent, true, true);
  37948. }
  37949. }
  37950. void Label::componentMovedOrResized (Component& component, bool /*wasMoved*/, bool /*wasResized*/)
  37951. {
  37952. if (leftOfOwnerComp)
  37953. {
  37954. setSize (jmin (getFont().getStringWidth (textValue.toString()) + 8, component.getX()),
  37955. component.getHeight());
  37956. setTopRightPosition (component.getX(), component.getY());
  37957. }
  37958. else
  37959. {
  37960. setSize (component.getWidth(),
  37961. 8 + roundToInt (getFont().getHeight()));
  37962. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  37963. }
  37964. }
  37965. void Label::componentParentHierarchyChanged (Component& component)
  37966. {
  37967. if (component.getParentComponent() != 0)
  37968. component.getParentComponent()->addChildComponent (this);
  37969. }
  37970. void Label::componentVisibilityChanged (Component& component)
  37971. {
  37972. setVisible (component.isVisible());
  37973. }
  37974. void Label::textWasEdited()
  37975. {
  37976. }
  37977. void Label::textWasChanged()
  37978. {
  37979. }
  37980. void Label::showEditor()
  37981. {
  37982. if (editor == 0)
  37983. {
  37984. addAndMakeVisible (editor = createEditorComponent());
  37985. editor->setText (getText(), false);
  37986. editor->addListener (this);
  37987. editor->grabKeyboardFocus();
  37988. editor->setHighlightedRegion (Range<int> (0, textValue.toString().length()));
  37989. editor->addListener (this);
  37990. resized();
  37991. repaint();
  37992. editorShown (editor);
  37993. enterModalState (false);
  37994. editor->grabKeyboardFocus();
  37995. }
  37996. }
  37997. void Label::editorShown (TextEditor* /*editorComponent*/)
  37998. {
  37999. }
  38000. void Label::editorAboutToBeHidden (TextEditor* /*editorComponent*/)
  38001. {
  38002. }
  38003. bool Label::updateFromTextEditorContents()
  38004. {
  38005. jassert (editor != 0);
  38006. const String newText (editor->getText());
  38007. if (textValue.toString() != newText)
  38008. {
  38009. lastTextValue = newText;
  38010. textValue = newText;
  38011. repaint();
  38012. textWasChanged();
  38013. if (ownerComponent != 0)
  38014. componentMovedOrResized (*ownerComponent, true, true);
  38015. return true;
  38016. }
  38017. return false;
  38018. }
  38019. void Label::hideEditor (const bool discardCurrentEditorContents)
  38020. {
  38021. if (editor != 0)
  38022. {
  38023. Component::SafePointer<Component> deletionChecker (this);
  38024. editorAboutToBeHidden (editor);
  38025. const bool changed = (! discardCurrentEditorContents)
  38026. && updateFromTextEditorContents();
  38027. editor = 0;
  38028. repaint();
  38029. if (changed)
  38030. textWasEdited();
  38031. if (deletionChecker != 0)
  38032. exitModalState (0);
  38033. if (changed && deletionChecker != 0)
  38034. callChangeListeners();
  38035. }
  38036. }
  38037. void Label::inputAttemptWhenModal()
  38038. {
  38039. if (editor != 0)
  38040. {
  38041. if (lossOfFocusDiscardsChanges)
  38042. textEditorEscapeKeyPressed (*editor);
  38043. else
  38044. textEditorReturnKeyPressed (*editor);
  38045. }
  38046. }
  38047. bool Label::isBeingEdited() const throw()
  38048. {
  38049. return editor != 0;
  38050. }
  38051. TextEditor* Label::createEditorComponent()
  38052. {
  38053. TextEditor* const ed = new TextEditor (getName());
  38054. ed->setFont (font);
  38055. // copy these colours from our own settings..
  38056. const int cols[] = { TextEditor::backgroundColourId,
  38057. TextEditor::textColourId,
  38058. TextEditor::highlightColourId,
  38059. TextEditor::highlightedTextColourId,
  38060. TextEditor::caretColourId,
  38061. TextEditor::outlineColourId,
  38062. TextEditor::focusedOutlineColourId,
  38063. TextEditor::shadowColourId };
  38064. for (int i = 0; i < numElementsInArray (cols); ++i)
  38065. ed->setColour (cols[i], findColour (cols[i]));
  38066. return ed;
  38067. }
  38068. void Label::paint (Graphics& g)
  38069. {
  38070. getLookAndFeel().drawLabel (g, *this);
  38071. }
  38072. void Label::mouseUp (const MouseEvent& e)
  38073. {
  38074. if (editSingleClick
  38075. && e.mouseWasClicked()
  38076. && contains (e.x, e.y)
  38077. && ! e.mods.isPopupMenu())
  38078. {
  38079. showEditor();
  38080. }
  38081. }
  38082. void Label::mouseDoubleClick (const MouseEvent& e)
  38083. {
  38084. if (editDoubleClick && ! e.mods.isPopupMenu())
  38085. showEditor();
  38086. }
  38087. void Label::resized()
  38088. {
  38089. if (editor != 0)
  38090. editor->setBoundsInset (BorderSize (0));
  38091. }
  38092. void Label::focusGained (FocusChangeType cause)
  38093. {
  38094. if (editSingleClick && cause == focusChangedByTabKey)
  38095. showEditor();
  38096. }
  38097. void Label::enablementChanged()
  38098. {
  38099. repaint();
  38100. }
  38101. void Label::colourChanged()
  38102. {
  38103. repaint();
  38104. }
  38105. void Label::setMinimumHorizontalScale (const float newScale)
  38106. {
  38107. if (minimumHorizontalScale != newScale)
  38108. {
  38109. minimumHorizontalScale = newScale;
  38110. repaint();
  38111. }
  38112. }
  38113. // We'll use a custom focus traverser here to make sure focus goes from the
  38114. // text editor to another component rather than back to the label itself.
  38115. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  38116. {
  38117. public:
  38118. LabelKeyboardFocusTraverser() {}
  38119. Component* getNextComponent (Component* current)
  38120. {
  38121. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  38122. ? current->getParentComponent() : current);
  38123. }
  38124. Component* getPreviousComponent (Component* current)
  38125. {
  38126. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  38127. ? current->getParentComponent() : current);
  38128. }
  38129. };
  38130. KeyboardFocusTraverser* Label::createFocusTraverser()
  38131. {
  38132. return new LabelKeyboardFocusTraverser();
  38133. }
  38134. void Label::addListener (LabelListener* const listener) throw()
  38135. {
  38136. listeners.add (listener);
  38137. }
  38138. void Label::removeListener (LabelListener* const listener) throw()
  38139. {
  38140. listeners.remove (listener);
  38141. }
  38142. void Label::callChangeListeners()
  38143. {
  38144. Component::BailOutChecker checker (this);
  38145. listeners.callChecked (checker, &LabelListener::labelTextChanged, this);
  38146. }
  38147. void Label::textEditorTextChanged (TextEditor& ed)
  38148. {
  38149. if (editor != 0)
  38150. {
  38151. jassert (&ed == editor);
  38152. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  38153. {
  38154. if (lossOfFocusDiscardsChanges)
  38155. textEditorEscapeKeyPressed (ed);
  38156. else
  38157. textEditorReturnKeyPressed (ed);
  38158. }
  38159. }
  38160. }
  38161. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  38162. {
  38163. if (editor != 0)
  38164. {
  38165. jassert (&ed == editor);
  38166. (void) ed;
  38167. const bool changed = updateFromTextEditorContents();
  38168. hideEditor (true);
  38169. if (changed)
  38170. {
  38171. Component::SafePointer<Component> deletionChecker (this);
  38172. textWasEdited();
  38173. if (deletionChecker != 0)
  38174. callChangeListeners();
  38175. }
  38176. }
  38177. }
  38178. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  38179. {
  38180. if (editor != 0)
  38181. {
  38182. jassert (&ed == editor);
  38183. (void) ed;
  38184. editor->setText (textValue.toString(), false);
  38185. hideEditor (true);
  38186. }
  38187. }
  38188. void Label::textEditorFocusLost (TextEditor& ed)
  38189. {
  38190. textEditorTextChanged (ed);
  38191. }
  38192. END_JUCE_NAMESPACE
  38193. /*** End of inlined file: juce_Label.cpp ***/
  38194. /*** Start of inlined file: juce_ListBox.cpp ***/
  38195. BEGIN_JUCE_NAMESPACE
  38196. class ListBoxRowComponent : public Component,
  38197. public TooltipClient
  38198. {
  38199. public:
  38200. ListBoxRowComponent (ListBox& owner_)
  38201. : owner (owner_),
  38202. row (-1),
  38203. selected (false),
  38204. isDragging (false)
  38205. {
  38206. }
  38207. ~ListBoxRowComponent()
  38208. {
  38209. deleteAllChildren();
  38210. }
  38211. void paint (Graphics& g)
  38212. {
  38213. if (owner.getModel() != 0)
  38214. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  38215. }
  38216. void update (const int row_, const bool selected_)
  38217. {
  38218. if (row != row_ || selected != selected_)
  38219. {
  38220. repaint();
  38221. row = row_;
  38222. selected = selected_;
  38223. }
  38224. if (owner.getModel() != 0)
  38225. {
  38226. Component* const customComp = owner.getModel()->refreshComponentForRow (row_, selected_, getChildComponent (0));
  38227. if (customComp != 0)
  38228. {
  38229. addAndMakeVisible (customComp);
  38230. customComp->setBounds (getLocalBounds());
  38231. for (int i = getNumChildComponents(); --i >= 0;)
  38232. if (getChildComponent (i) != customComp)
  38233. delete getChildComponent (i);
  38234. }
  38235. else
  38236. {
  38237. deleteAllChildren();
  38238. }
  38239. }
  38240. }
  38241. void mouseDown (const MouseEvent& e)
  38242. {
  38243. isDragging = false;
  38244. selectRowOnMouseUp = false;
  38245. if (isEnabled())
  38246. {
  38247. if (! selected)
  38248. {
  38249. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  38250. if (owner.getModel() != 0)
  38251. owner.getModel()->listBoxItemClicked (row, e);
  38252. }
  38253. else
  38254. {
  38255. selectRowOnMouseUp = true;
  38256. }
  38257. }
  38258. }
  38259. void mouseUp (const MouseEvent& e)
  38260. {
  38261. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  38262. {
  38263. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  38264. if (owner.getModel() != 0)
  38265. owner.getModel()->listBoxItemClicked (row, e);
  38266. }
  38267. }
  38268. void mouseDoubleClick (const MouseEvent& e)
  38269. {
  38270. if (owner.getModel() != 0 && isEnabled())
  38271. owner.getModel()->listBoxItemDoubleClicked (row, e);
  38272. }
  38273. void mouseDrag (const MouseEvent& e)
  38274. {
  38275. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  38276. {
  38277. const SparseSet<int> selectedRows (owner.getSelectedRows());
  38278. if (selectedRows.size() > 0)
  38279. {
  38280. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  38281. if (dragDescription.isNotEmpty())
  38282. {
  38283. isDragging = true;
  38284. owner.startDragAndDrop (e, dragDescription);
  38285. }
  38286. }
  38287. }
  38288. }
  38289. void resized()
  38290. {
  38291. if (getNumChildComponents() > 0)
  38292. getChildComponent(0)->setBounds (getLocalBounds());
  38293. }
  38294. const String getTooltip()
  38295. {
  38296. if (owner.getModel() != 0)
  38297. return owner.getModel()->getTooltipForRow (row);
  38298. return String::empty;
  38299. }
  38300. juce_UseDebuggingNewOperator
  38301. bool neededFlag;
  38302. private:
  38303. ListBox& owner;
  38304. int row;
  38305. bool selected, isDragging, selectRowOnMouseUp;
  38306. ListBoxRowComponent (const ListBoxRowComponent&);
  38307. ListBoxRowComponent& operator= (const ListBoxRowComponent&);
  38308. };
  38309. class ListViewport : public Viewport
  38310. {
  38311. public:
  38312. int firstIndex, firstWholeIndex, lastWholeIndex;
  38313. bool hasUpdated;
  38314. ListViewport (ListBox& owner_)
  38315. : owner (owner_)
  38316. {
  38317. setWantsKeyboardFocus (false);
  38318. setViewedComponent (new Component());
  38319. getViewedComponent()->addMouseListener (this, false);
  38320. getViewedComponent()->setWantsKeyboardFocus (false);
  38321. }
  38322. ~ListViewport()
  38323. {
  38324. getViewedComponent()->removeMouseListener (this);
  38325. getViewedComponent()->deleteAllChildren();
  38326. }
  38327. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  38328. {
  38329. return static_cast <ListBoxRowComponent*>
  38330. (getViewedComponent()->getChildComponent (row % jmax (1, getViewedComponent()->getNumChildComponents())));
  38331. }
  38332. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  38333. {
  38334. const int index = getIndexOfChildComponent (rowComponent);
  38335. const int num = getViewedComponent()->getNumChildComponents();
  38336. for (int i = num; --i >= 0;)
  38337. if (((firstIndex + i) % jmax (1, num)) == index)
  38338. return firstIndex + i;
  38339. return -1;
  38340. }
  38341. Component* getComponentForRowIfOnscreen (const int row) const throw()
  38342. {
  38343. return (row >= firstIndex && row < firstIndex + getViewedComponent()->getNumChildComponents())
  38344. ? getComponentForRow (row) : 0;
  38345. }
  38346. void visibleAreaChanged (int, int, int, int)
  38347. {
  38348. updateVisibleArea (true);
  38349. if (owner.getModel() != 0)
  38350. owner.getModel()->listWasScrolled();
  38351. }
  38352. void updateVisibleArea (const bool makeSureItUpdatesContent)
  38353. {
  38354. hasUpdated = false;
  38355. const int newX = getViewedComponent()->getX();
  38356. int newY = getViewedComponent()->getY();
  38357. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  38358. const int newH = owner.totalItems * owner.getRowHeight();
  38359. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  38360. newY = getMaximumVisibleHeight() - newH;
  38361. getViewedComponent()->setBounds (newX, newY, newW, newH);
  38362. if (makeSureItUpdatesContent && ! hasUpdated)
  38363. updateContents();
  38364. }
  38365. void updateContents()
  38366. {
  38367. hasUpdated = true;
  38368. const int rowHeight = owner.getRowHeight();
  38369. if (rowHeight > 0)
  38370. {
  38371. const int y = getViewPositionY();
  38372. const int w = getViewedComponent()->getWidth();
  38373. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  38374. while (numNeeded > getViewedComponent()->getNumChildComponents())
  38375. getViewedComponent()->addAndMakeVisible (new ListBoxRowComponent (owner));
  38376. jassert (numNeeded >= 0);
  38377. while (numNeeded < getViewedComponent()->getNumChildComponents())
  38378. {
  38379. Component* const rowToRemove
  38380. = getViewedComponent()->getChildComponent (getViewedComponent()->getNumChildComponents() - 1);
  38381. delete rowToRemove;
  38382. }
  38383. firstIndex = y / rowHeight;
  38384. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  38385. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  38386. for (int i = 0; i < numNeeded; ++i)
  38387. {
  38388. const int row = i + firstIndex;
  38389. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  38390. if (rowComp != 0)
  38391. {
  38392. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  38393. rowComp->update (row, owner.isRowSelected (row));
  38394. }
  38395. }
  38396. }
  38397. if (owner.headerComponent != 0)
  38398. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  38399. owner.outlineThickness,
  38400. jmax (owner.getWidth() - owner.outlineThickness * 2,
  38401. getViewedComponent()->getWidth()),
  38402. owner.headerComponent->getHeight());
  38403. }
  38404. void paint (Graphics& g)
  38405. {
  38406. if (isOpaque())
  38407. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  38408. }
  38409. bool keyPressed (const KeyPress& key)
  38410. {
  38411. if (key.isKeyCode (KeyPress::upKey)
  38412. || key.isKeyCode (KeyPress::downKey)
  38413. || key.isKeyCode (KeyPress::pageUpKey)
  38414. || key.isKeyCode (KeyPress::pageDownKey)
  38415. || key.isKeyCode (KeyPress::homeKey)
  38416. || key.isKeyCode (KeyPress::endKey))
  38417. {
  38418. // we want to avoid these keypresses going to the viewport, and instead allow
  38419. // them to pass up to our listbox..
  38420. return false;
  38421. }
  38422. return Viewport::keyPressed (key);
  38423. }
  38424. juce_UseDebuggingNewOperator
  38425. private:
  38426. ListBox& owner;
  38427. ListViewport (const ListViewport&);
  38428. ListViewport& operator= (const ListViewport&);
  38429. };
  38430. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  38431. : Component (name),
  38432. model (model_),
  38433. totalItems (0),
  38434. rowHeight (22),
  38435. minimumRowWidth (0),
  38436. outlineThickness (0),
  38437. lastRowSelected (-1),
  38438. mouseMoveSelects (false),
  38439. multipleSelection (false),
  38440. hasDoneInitialUpdate (false)
  38441. {
  38442. addAndMakeVisible (viewport = new ListViewport (*this));
  38443. setWantsKeyboardFocus (true);
  38444. colourChanged();
  38445. }
  38446. ListBox::~ListBox()
  38447. {
  38448. headerComponent = 0;
  38449. viewport = 0;
  38450. }
  38451. void ListBox::setModel (ListBoxModel* const newModel)
  38452. {
  38453. if (model != newModel)
  38454. {
  38455. model = newModel;
  38456. updateContent();
  38457. }
  38458. }
  38459. void ListBox::setMultipleSelectionEnabled (bool b)
  38460. {
  38461. multipleSelection = b;
  38462. }
  38463. void ListBox::setMouseMoveSelectsRows (bool b)
  38464. {
  38465. mouseMoveSelects = b;
  38466. if (b)
  38467. addMouseListener (this, true);
  38468. }
  38469. void ListBox::paint (Graphics& g)
  38470. {
  38471. if (! hasDoneInitialUpdate)
  38472. updateContent();
  38473. g.fillAll (findColour (backgroundColourId));
  38474. }
  38475. void ListBox::paintOverChildren (Graphics& g)
  38476. {
  38477. if (outlineThickness > 0)
  38478. {
  38479. g.setColour (findColour (outlineColourId));
  38480. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  38481. }
  38482. }
  38483. void ListBox::resized()
  38484. {
  38485. viewport->setBoundsInset (BorderSize (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  38486. outlineThickness,
  38487. outlineThickness,
  38488. outlineThickness));
  38489. viewport->setSingleStepSizes (20, getRowHeight());
  38490. viewport->updateVisibleArea (false);
  38491. }
  38492. void ListBox::visibilityChanged()
  38493. {
  38494. viewport->updateVisibleArea (true);
  38495. }
  38496. Viewport* ListBox::getViewport() const throw()
  38497. {
  38498. return viewport;
  38499. }
  38500. void ListBox::updateContent()
  38501. {
  38502. hasDoneInitialUpdate = true;
  38503. totalItems = (model != 0) ? model->getNumRows() : 0;
  38504. bool selectionChanged = false;
  38505. if (selected [selected.size() - 1] >= totalItems)
  38506. {
  38507. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  38508. lastRowSelected = getSelectedRow (0);
  38509. selectionChanged = true;
  38510. }
  38511. viewport->updateVisibleArea (isVisible());
  38512. viewport->resized();
  38513. if (selectionChanged && model != 0)
  38514. model->selectedRowsChanged (lastRowSelected);
  38515. }
  38516. void ListBox::selectRow (const int row,
  38517. bool dontScroll,
  38518. bool deselectOthersFirst)
  38519. {
  38520. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  38521. }
  38522. void ListBox::selectRowInternal (const int row,
  38523. bool dontScroll,
  38524. bool deselectOthersFirst,
  38525. bool isMouseClick)
  38526. {
  38527. if (! multipleSelection)
  38528. deselectOthersFirst = true;
  38529. if ((! isRowSelected (row))
  38530. || (deselectOthersFirst && getNumSelectedRows() > 1))
  38531. {
  38532. if (((unsigned int) row) < (unsigned int) totalItems)
  38533. {
  38534. if (deselectOthersFirst)
  38535. selected.clear();
  38536. selected.addRange (Range<int> (row, row + 1));
  38537. if (getHeight() == 0 || getWidth() == 0)
  38538. dontScroll = true;
  38539. viewport->hasUpdated = false;
  38540. if (row < viewport->firstWholeIndex && ! dontScroll)
  38541. {
  38542. viewport->setViewPosition (viewport->getViewPositionX(),
  38543. row * getRowHeight());
  38544. }
  38545. else if (row >= viewport->lastWholeIndex && ! dontScroll)
  38546. {
  38547. const int rowsOnScreen = viewport->lastWholeIndex - viewport->firstWholeIndex;
  38548. if (row >= lastRowSelected + rowsOnScreen
  38549. && rowsOnScreen < totalItems - 1
  38550. && ! isMouseClick)
  38551. {
  38552. viewport->setViewPosition (viewport->getViewPositionX(),
  38553. jlimit (0, jmax (0, totalItems - rowsOnScreen), row)
  38554. * getRowHeight());
  38555. }
  38556. else
  38557. {
  38558. viewport->setViewPosition (viewport->getViewPositionX(),
  38559. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  38560. }
  38561. }
  38562. if (! viewport->hasUpdated)
  38563. viewport->updateContents();
  38564. lastRowSelected = row;
  38565. model->selectedRowsChanged (row);
  38566. }
  38567. else
  38568. {
  38569. if (deselectOthersFirst)
  38570. deselectAllRows();
  38571. }
  38572. }
  38573. }
  38574. void ListBox::deselectRow (const int row)
  38575. {
  38576. if (selected.contains (row))
  38577. {
  38578. selected.removeRange (Range <int> (row, row + 1));
  38579. if (row == lastRowSelected)
  38580. lastRowSelected = getSelectedRow (0);
  38581. viewport->updateContents();
  38582. model->selectedRowsChanged (lastRowSelected);
  38583. }
  38584. }
  38585. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  38586. const bool sendNotificationEventToModel)
  38587. {
  38588. selected = setOfRowsToBeSelected;
  38589. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  38590. if (! isRowSelected (lastRowSelected))
  38591. lastRowSelected = getSelectedRow (0);
  38592. viewport->updateContents();
  38593. if ((model != 0) && sendNotificationEventToModel)
  38594. model->selectedRowsChanged (lastRowSelected);
  38595. }
  38596. const SparseSet<int> ListBox::getSelectedRows() const
  38597. {
  38598. return selected;
  38599. }
  38600. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  38601. {
  38602. if (multipleSelection && (firstRow != lastRow))
  38603. {
  38604. const int numRows = totalItems - 1;
  38605. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  38606. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  38607. selected.addRange (Range <int> (jmin (firstRow, lastRow),
  38608. jmax (firstRow, lastRow) + 1));
  38609. selected.removeRange (Range <int> (lastRow, lastRow + 1));
  38610. }
  38611. selectRowInternal (lastRow, false, false, true);
  38612. }
  38613. void ListBox::flipRowSelection (const int row)
  38614. {
  38615. if (isRowSelected (row))
  38616. deselectRow (row);
  38617. else
  38618. selectRowInternal (row, false, false, true);
  38619. }
  38620. void ListBox::deselectAllRows()
  38621. {
  38622. if (! selected.isEmpty())
  38623. {
  38624. selected.clear();
  38625. lastRowSelected = -1;
  38626. viewport->updateContents();
  38627. if (model != 0)
  38628. model->selectedRowsChanged (lastRowSelected);
  38629. }
  38630. }
  38631. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  38632. const ModifierKeys& mods)
  38633. {
  38634. if (multipleSelection && mods.isCommandDown())
  38635. {
  38636. flipRowSelection (row);
  38637. }
  38638. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  38639. {
  38640. selectRangeOfRows (lastRowSelected, row);
  38641. }
  38642. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  38643. {
  38644. selectRowInternal (row, false, true, true);
  38645. }
  38646. }
  38647. int ListBox::getNumSelectedRows() const
  38648. {
  38649. return selected.size();
  38650. }
  38651. int ListBox::getSelectedRow (const int index) const
  38652. {
  38653. return (((unsigned int) index) < (unsigned int) selected.size())
  38654. ? selected [index] : -1;
  38655. }
  38656. bool ListBox::isRowSelected (const int row) const
  38657. {
  38658. return selected.contains (row);
  38659. }
  38660. int ListBox::getLastRowSelected() const
  38661. {
  38662. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  38663. }
  38664. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  38665. {
  38666. if (((unsigned int) x) < (unsigned int) getWidth())
  38667. {
  38668. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  38669. if (((unsigned int) row) < (unsigned int) totalItems)
  38670. return row;
  38671. }
  38672. return -1;
  38673. }
  38674. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  38675. {
  38676. if (((unsigned int) x) < (unsigned int) getWidth())
  38677. {
  38678. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  38679. return jlimit (0, totalItems, row);
  38680. }
  38681. return -1;
  38682. }
  38683. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  38684. {
  38685. Component* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  38686. return listRowComp != 0 ? listRowComp->getChildComponent (0) : 0;
  38687. }
  38688. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  38689. {
  38690. return viewport->getRowNumberOfComponent (rowComponent);
  38691. }
  38692. const Rectangle<int> ListBox::getRowPosition (const int rowNumber,
  38693. const bool relativeToComponentTopLeft) const throw()
  38694. {
  38695. int y = viewport->getY() + rowHeight * rowNumber;
  38696. if (relativeToComponentTopLeft)
  38697. y -= viewport->getViewPositionY();
  38698. return Rectangle<int> (viewport->getX(), y,
  38699. viewport->getViewedComponent()->getWidth(), rowHeight);
  38700. }
  38701. void ListBox::setVerticalPosition (const double proportion)
  38702. {
  38703. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  38704. viewport->setViewPosition (viewport->getViewPositionX(),
  38705. jmax (0, roundToInt (proportion * offscreen)));
  38706. }
  38707. double ListBox::getVerticalPosition() const
  38708. {
  38709. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  38710. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  38711. : 0;
  38712. }
  38713. int ListBox::getVisibleRowWidth() const throw()
  38714. {
  38715. return viewport->getViewWidth();
  38716. }
  38717. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  38718. {
  38719. if (row < viewport->firstWholeIndex)
  38720. {
  38721. viewport->setViewPosition (viewport->getViewPositionX(),
  38722. row * getRowHeight());
  38723. }
  38724. else if (row >= viewport->lastWholeIndex)
  38725. {
  38726. viewport->setViewPosition (viewport->getViewPositionX(),
  38727. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  38728. }
  38729. }
  38730. bool ListBox::keyPressed (const KeyPress& key)
  38731. {
  38732. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  38733. const bool multiple = multipleSelection
  38734. && (lastRowSelected >= 0)
  38735. && (key.getModifiers().isShiftDown()
  38736. || key.getModifiers().isCtrlDown()
  38737. || key.getModifiers().isCommandDown());
  38738. if (key.isKeyCode (KeyPress::upKey))
  38739. {
  38740. if (multiple)
  38741. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  38742. else
  38743. selectRow (jmax (0, lastRowSelected - 1));
  38744. }
  38745. else if (key.isKeyCode (KeyPress::returnKey)
  38746. && isRowSelected (lastRowSelected))
  38747. {
  38748. if (model != 0)
  38749. model->returnKeyPressed (lastRowSelected);
  38750. }
  38751. else if (key.isKeyCode (KeyPress::pageUpKey))
  38752. {
  38753. if (multiple)
  38754. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  38755. else
  38756. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  38757. }
  38758. else if (key.isKeyCode (KeyPress::pageDownKey))
  38759. {
  38760. if (multiple)
  38761. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  38762. else
  38763. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  38764. }
  38765. else if (key.isKeyCode (KeyPress::homeKey))
  38766. {
  38767. if (multiple && key.getModifiers().isShiftDown())
  38768. selectRangeOfRows (lastRowSelected, 0);
  38769. else
  38770. selectRow (0);
  38771. }
  38772. else if (key.isKeyCode (KeyPress::endKey))
  38773. {
  38774. if (multiple && key.getModifiers().isShiftDown())
  38775. selectRangeOfRows (lastRowSelected, totalItems - 1);
  38776. else
  38777. selectRow (totalItems - 1);
  38778. }
  38779. else if (key.isKeyCode (KeyPress::downKey))
  38780. {
  38781. if (multiple)
  38782. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  38783. else
  38784. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  38785. }
  38786. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  38787. && isRowSelected (lastRowSelected))
  38788. {
  38789. if (model != 0)
  38790. model->deleteKeyPressed (lastRowSelected);
  38791. }
  38792. else if (multiple && key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  38793. {
  38794. selectRangeOfRows (0, std::numeric_limits<int>::max());
  38795. }
  38796. else
  38797. {
  38798. return false;
  38799. }
  38800. return true;
  38801. }
  38802. bool ListBox::keyStateChanged (const bool isKeyDown)
  38803. {
  38804. return isKeyDown
  38805. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  38806. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  38807. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  38808. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  38809. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  38810. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  38811. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey));
  38812. }
  38813. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  38814. {
  38815. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  38816. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  38817. }
  38818. void ListBox::mouseMove (const MouseEvent& e)
  38819. {
  38820. if (mouseMoveSelects)
  38821. {
  38822. const MouseEvent e2 (e.getEventRelativeTo (this));
  38823. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  38824. }
  38825. }
  38826. void ListBox::mouseExit (const MouseEvent& e)
  38827. {
  38828. mouseMove (e);
  38829. }
  38830. void ListBox::mouseUp (const MouseEvent& e)
  38831. {
  38832. if (e.mouseWasClicked() && model != 0)
  38833. model->backgroundClicked();
  38834. }
  38835. void ListBox::setRowHeight (const int newHeight)
  38836. {
  38837. rowHeight = jmax (1, newHeight);
  38838. viewport->setSingleStepSizes (20, rowHeight);
  38839. updateContent();
  38840. }
  38841. int ListBox::getNumRowsOnScreen() const throw()
  38842. {
  38843. return viewport->getMaximumVisibleHeight() / rowHeight;
  38844. }
  38845. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  38846. {
  38847. minimumRowWidth = newMinimumWidth;
  38848. updateContent();
  38849. }
  38850. int ListBox::getVisibleContentWidth() const throw()
  38851. {
  38852. return viewport->getMaximumVisibleWidth();
  38853. }
  38854. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  38855. {
  38856. return viewport->getVerticalScrollBar();
  38857. }
  38858. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  38859. {
  38860. return viewport->getHorizontalScrollBar();
  38861. }
  38862. void ListBox::colourChanged()
  38863. {
  38864. setOpaque (findColour (backgroundColourId).isOpaque());
  38865. viewport->setOpaque (isOpaque());
  38866. repaint();
  38867. }
  38868. void ListBox::setOutlineThickness (const int outlineThickness_)
  38869. {
  38870. outlineThickness = outlineThickness_;
  38871. resized();
  38872. }
  38873. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  38874. {
  38875. if (newHeaderComponent != headerComponent)
  38876. {
  38877. headerComponent = newHeaderComponent;
  38878. addAndMakeVisible (newHeaderComponent);
  38879. ListBox::resized();
  38880. }
  38881. }
  38882. void ListBox::repaintRow (const int rowNumber) throw()
  38883. {
  38884. repaint (getRowPosition (rowNumber, true));
  38885. }
  38886. const Image ListBox::createSnapshotOfSelectedRows (int& imageX, int& imageY)
  38887. {
  38888. Rectangle<int> imageArea;
  38889. const int firstRow = getRowContainingPosition (0, 0);
  38890. int i;
  38891. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  38892. {
  38893. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  38894. if (rowComp != 0 && isRowSelected (firstRow + i))
  38895. {
  38896. const Point<int> pos (rowComp->relativePositionToOtherComponent (this, Point<int>()));
  38897. const Rectangle<int> rowRect (pos.getX(), pos.getY(), rowComp->getWidth(), rowComp->getHeight());
  38898. imageArea = imageArea.getUnion (rowRect);
  38899. }
  38900. }
  38901. imageArea = imageArea.getIntersection (getLocalBounds());
  38902. imageX = imageArea.getX();
  38903. imageY = imageArea.getY();
  38904. Image snapshot (Image::ARGB, imageArea.getWidth(), imageArea.getHeight(), true, Image::NativeImage);
  38905. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  38906. {
  38907. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  38908. if (rowComp != 0 && isRowSelected (firstRow + i))
  38909. {
  38910. const Point<int> pos (rowComp->relativePositionToOtherComponent (this, Point<int>()));
  38911. Graphics g (snapshot);
  38912. g.setOrigin (pos.getX() - imageX, pos.getY() - imageY);
  38913. if (g.reduceClipRegion (0, 0, rowComp->getWidth(), rowComp->getHeight()))
  38914. rowComp->paintEntireComponent (g);
  38915. }
  38916. }
  38917. return snapshot;
  38918. }
  38919. void ListBox::startDragAndDrop (const MouseEvent& e, const String& dragDescription)
  38920. {
  38921. DragAndDropContainer* const dragContainer
  38922. = DragAndDropContainer::findParentDragContainerFor (this);
  38923. if (dragContainer != 0)
  38924. {
  38925. int x, y;
  38926. Image dragImage (createSnapshotOfSelectedRows (x, y));
  38927. dragImage.multiplyAllAlphas (0.6f);
  38928. MouseEvent e2 (e.getEventRelativeTo (this));
  38929. const Point<int> p (x - e2.x, y - e2.y);
  38930. dragContainer->startDragging (dragDescription, this, dragImage, true, &p);
  38931. }
  38932. else
  38933. {
  38934. // to be able to do a drag-and-drop operation, the listbox needs to
  38935. // be inside a component which is also a DragAndDropContainer.
  38936. jassertfalse;
  38937. }
  38938. }
  38939. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  38940. {
  38941. (void) existingComponentToUpdate;
  38942. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  38943. return 0;
  38944. }
  38945. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&)
  38946. {
  38947. }
  38948. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&)
  38949. {
  38950. }
  38951. void ListBoxModel::backgroundClicked()
  38952. {
  38953. }
  38954. void ListBoxModel::selectedRowsChanged (int)
  38955. {
  38956. }
  38957. void ListBoxModel::deleteKeyPressed (int)
  38958. {
  38959. }
  38960. void ListBoxModel::returnKeyPressed (int)
  38961. {
  38962. }
  38963. void ListBoxModel::listWasScrolled()
  38964. {
  38965. }
  38966. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  38967. {
  38968. return String::empty;
  38969. }
  38970. const String ListBoxModel::getTooltipForRow (int)
  38971. {
  38972. return String::empty;
  38973. }
  38974. END_JUCE_NAMESPACE
  38975. /*** End of inlined file: juce_ListBox.cpp ***/
  38976. /*** Start of inlined file: juce_ProgressBar.cpp ***/
  38977. BEGIN_JUCE_NAMESPACE
  38978. ProgressBar::ProgressBar (double& progress_)
  38979. : progress (progress_),
  38980. displayPercentage (true),
  38981. lastCallbackTime (0)
  38982. {
  38983. currentValue = jlimit (0.0, 1.0, progress);
  38984. }
  38985. ProgressBar::~ProgressBar()
  38986. {
  38987. }
  38988. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  38989. {
  38990. displayPercentage = shouldDisplayPercentage;
  38991. repaint();
  38992. }
  38993. void ProgressBar::setTextToDisplay (const String& text)
  38994. {
  38995. displayPercentage = false;
  38996. displayedMessage = text;
  38997. }
  38998. void ProgressBar::lookAndFeelChanged()
  38999. {
  39000. setOpaque (findColour (backgroundColourId).isOpaque());
  39001. }
  39002. void ProgressBar::colourChanged()
  39003. {
  39004. lookAndFeelChanged();
  39005. }
  39006. void ProgressBar::paint (Graphics& g)
  39007. {
  39008. String text;
  39009. if (displayPercentage)
  39010. {
  39011. if (currentValue >= 0 && currentValue <= 1.0)
  39012. text << roundToInt (currentValue * 100.0) << '%';
  39013. }
  39014. else
  39015. {
  39016. text = displayedMessage;
  39017. }
  39018. getLookAndFeel().drawProgressBar (g, *this,
  39019. getWidth(), getHeight(),
  39020. currentValue, text);
  39021. }
  39022. void ProgressBar::visibilityChanged()
  39023. {
  39024. if (isVisible())
  39025. startTimer (30);
  39026. else
  39027. stopTimer();
  39028. }
  39029. void ProgressBar::timerCallback()
  39030. {
  39031. double newProgress = progress;
  39032. const uint32 now = Time::getMillisecondCounter();
  39033. const int timeSinceLastCallback = (int) (now - lastCallbackTime);
  39034. lastCallbackTime = now;
  39035. if (currentValue != newProgress
  39036. || newProgress < 0 || newProgress >= 1.0
  39037. || currentMessage != displayedMessage)
  39038. {
  39039. if (currentValue < newProgress
  39040. && newProgress >= 0 && newProgress < 1.0
  39041. && currentValue >= 0 && currentValue < 1.0)
  39042. {
  39043. newProgress = jmin (currentValue + 0.0008 * timeSinceLastCallback,
  39044. newProgress);
  39045. }
  39046. currentValue = newProgress;
  39047. currentMessage = displayedMessage;
  39048. repaint();
  39049. }
  39050. }
  39051. END_JUCE_NAMESPACE
  39052. /*** End of inlined file: juce_ProgressBar.cpp ***/
  39053. /*** Start of inlined file: juce_Slider.cpp ***/
  39054. BEGIN_JUCE_NAMESPACE
  39055. class SliderPopupDisplayComponent : public BubbleComponent
  39056. {
  39057. public:
  39058. SliderPopupDisplayComponent (Slider* const owner_)
  39059. : owner (owner_),
  39060. font (15.0f, Font::bold)
  39061. {
  39062. setAlwaysOnTop (true);
  39063. }
  39064. ~SliderPopupDisplayComponent()
  39065. {
  39066. }
  39067. void paintContent (Graphics& g, int w, int h)
  39068. {
  39069. g.setFont (font);
  39070. g.setColour (Colours::black);
  39071. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  39072. }
  39073. void getContentSize (int& w, int& h)
  39074. {
  39075. w = font.getStringWidth (text) + 18;
  39076. h = (int) (font.getHeight() * 1.6f);
  39077. }
  39078. void updatePosition (const String& newText)
  39079. {
  39080. if (text != newText)
  39081. {
  39082. text = newText;
  39083. repaint();
  39084. }
  39085. BubbleComponent::setPosition (owner);
  39086. }
  39087. juce_UseDebuggingNewOperator
  39088. private:
  39089. Slider* owner;
  39090. Font font;
  39091. String text;
  39092. SliderPopupDisplayComponent (const SliderPopupDisplayComponent&);
  39093. SliderPopupDisplayComponent& operator= (const SliderPopupDisplayComponent&);
  39094. };
  39095. Slider::Slider (const String& name)
  39096. : Component (name),
  39097. lastCurrentValue (0),
  39098. lastValueMin (0),
  39099. lastValueMax (0),
  39100. minimum (0),
  39101. maximum (10),
  39102. interval (0),
  39103. skewFactor (1.0),
  39104. velocityModeSensitivity (1.0),
  39105. velocityModeOffset (0.0),
  39106. velocityModeThreshold (1),
  39107. rotaryStart (float_Pi * 1.2f),
  39108. rotaryEnd (float_Pi * 2.8f),
  39109. numDecimalPlaces (7),
  39110. sliderRegionStart (0),
  39111. sliderRegionSize (1),
  39112. sliderBeingDragged (-1),
  39113. pixelsForFullDragExtent (250),
  39114. style (LinearHorizontal),
  39115. textBoxPos (TextBoxLeft),
  39116. textBoxWidth (80),
  39117. textBoxHeight (20),
  39118. incDecButtonMode (incDecButtonsNotDraggable),
  39119. editableText (true),
  39120. doubleClickToValue (false),
  39121. isVelocityBased (false),
  39122. userKeyOverridesVelocity (true),
  39123. rotaryStop (true),
  39124. incDecButtonsSideBySide (false),
  39125. sendChangeOnlyOnRelease (false),
  39126. popupDisplayEnabled (false),
  39127. menuEnabled (false),
  39128. menuShown (false),
  39129. scrollWheelEnabled (true),
  39130. snapsToMousePos (true),
  39131. valueBox (0),
  39132. incButton (0),
  39133. decButton (0),
  39134. popupDisplay (0),
  39135. parentForPopupDisplay (0)
  39136. {
  39137. setWantsKeyboardFocus (false);
  39138. setRepaintsOnMouseActivity (true);
  39139. lookAndFeelChanged();
  39140. updateText();
  39141. currentValue.addListener (this);
  39142. valueMin.addListener (this);
  39143. valueMax.addListener (this);
  39144. }
  39145. Slider::~Slider()
  39146. {
  39147. currentValue.removeListener (this);
  39148. valueMin.removeListener (this);
  39149. valueMax.removeListener (this);
  39150. popupDisplay = 0;
  39151. deleteAllChildren();
  39152. }
  39153. void Slider::handleAsyncUpdate()
  39154. {
  39155. cancelPendingUpdate();
  39156. Component::BailOutChecker checker (this);
  39157. listeners.callChecked (checker, &SliderListener::sliderValueChanged, this);
  39158. }
  39159. void Slider::sendDragStart()
  39160. {
  39161. startedDragging();
  39162. Component::BailOutChecker checker (this);
  39163. listeners.callChecked (checker, &SliderListener::sliderDragStarted, this);
  39164. }
  39165. void Slider::sendDragEnd()
  39166. {
  39167. stoppedDragging();
  39168. sliderBeingDragged = -1;
  39169. Component::BailOutChecker checker (this);
  39170. listeners.callChecked (checker, &SliderListener::sliderDragEnded, this);
  39171. }
  39172. void Slider::addListener (SliderListener* const listener)
  39173. {
  39174. listeners.add (listener);
  39175. }
  39176. void Slider::removeListener (SliderListener* const listener)
  39177. {
  39178. listeners.remove (listener);
  39179. }
  39180. void Slider::setSliderStyle (const SliderStyle newStyle)
  39181. {
  39182. if (style != newStyle)
  39183. {
  39184. style = newStyle;
  39185. repaint();
  39186. lookAndFeelChanged();
  39187. }
  39188. }
  39189. void Slider::setRotaryParameters (const float startAngleRadians,
  39190. const float endAngleRadians,
  39191. const bool stopAtEnd)
  39192. {
  39193. // make sure the values are sensible..
  39194. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  39195. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  39196. jassert (rotaryStart < rotaryEnd);
  39197. rotaryStart = startAngleRadians;
  39198. rotaryEnd = endAngleRadians;
  39199. rotaryStop = stopAtEnd;
  39200. }
  39201. void Slider::setVelocityBasedMode (const bool velBased)
  39202. {
  39203. isVelocityBased = velBased;
  39204. }
  39205. void Slider::setVelocityModeParameters (const double sensitivity,
  39206. const int threshold,
  39207. const double offset,
  39208. const bool userCanPressKeyToSwapMode)
  39209. {
  39210. jassert (threshold >= 0);
  39211. jassert (sensitivity > 0);
  39212. jassert (offset >= 0);
  39213. velocityModeSensitivity = sensitivity;
  39214. velocityModeOffset = offset;
  39215. velocityModeThreshold = threshold;
  39216. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  39217. }
  39218. void Slider::setSkewFactor (const double factor)
  39219. {
  39220. skewFactor = factor;
  39221. }
  39222. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint)
  39223. {
  39224. if (maximum > minimum)
  39225. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  39226. / (maximum - minimum));
  39227. }
  39228. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  39229. {
  39230. jassert (distanceForFullScaleDrag > 0);
  39231. pixelsForFullDragExtent = distanceForFullScaleDrag;
  39232. }
  39233. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  39234. {
  39235. if (incDecButtonMode != mode)
  39236. {
  39237. incDecButtonMode = mode;
  39238. lookAndFeelChanged();
  39239. }
  39240. }
  39241. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  39242. const bool isReadOnly,
  39243. const int textEntryBoxWidth,
  39244. const int textEntryBoxHeight)
  39245. {
  39246. if (textBoxPos != newPosition
  39247. || editableText != (! isReadOnly)
  39248. || textBoxWidth != textEntryBoxWidth
  39249. || textBoxHeight != textEntryBoxHeight)
  39250. {
  39251. textBoxPos = newPosition;
  39252. editableText = ! isReadOnly;
  39253. textBoxWidth = textEntryBoxWidth;
  39254. textBoxHeight = textEntryBoxHeight;
  39255. repaint();
  39256. lookAndFeelChanged();
  39257. }
  39258. }
  39259. void Slider::setTextBoxIsEditable (const bool shouldBeEditable)
  39260. {
  39261. editableText = shouldBeEditable;
  39262. if (valueBox != 0)
  39263. valueBox->setEditable (shouldBeEditable && isEnabled());
  39264. }
  39265. void Slider::showTextBox()
  39266. {
  39267. jassert (editableText); // this should probably be avoided in read-only sliders.
  39268. if (valueBox != 0)
  39269. valueBox->showEditor();
  39270. }
  39271. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  39272. {
  39273. if (valueBox != 0)
  39274. {
  39275. valueBox->hideEditor (discardCurrentEditorContents);
  39276. if (discardCurrentEditorContents)
  39277. updateText();
  39278. }
  39279. }
  39280. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease)
  39281. {
  39282. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  39283. }
  39284. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse)
  39285. {
  39286. snapsToMousePos = shouldSnapToMouse;
  39287. }
  39288. void Slider::setPopupDisplayEnabled (const bool enabled,
  39289. Component* const parentComponentToUse)
  39290. {
  39291. popupDisplayEnabled = enabled;
  39292. parentForPopupDisplay = parentComponentToUse;
  39293. }
  39294. void Slider::colourChanged()
  39295. {
  39296. lookAndFeelChanged();
  39297. }
  39298. void Slider::lookAndFeelChanged()
  39299. {
  39300. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  39301. : getTextFromValue (currentValue.getValue()));
  39302. deleteAllChildren();
  39303. valueBox = 0;
  39304. LookAndFeel& lf = getLookAndFeel();
  39305. if (textBoxPos != NoTextBox)
  39306. {
  39307. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  39308. valueBox->setWantsKeyboardFocus (false);
  39309. valueBox->setText (previousTextBoxContent, false);
  39310. valueBox->setEditable (editableText && isEnabled());
  39311. valueBox->addListener (this);
  39312. if (style == LinearBar)
  39313. valueBox->addMouseListener (this, false);
  39314. valueBox->setTooltip (getTooltip());
  39315. }
  39316. if (style == IncDecButtons)
  39317. {
  39318. addAndMakeVisible (incButton = lf.createSliderButton (true));
  39319. incButton->addButtonListener (this);
  39320. addAndMakeVisible (decButton = lf.createSliderButton (false));
  39321. decButton->addButtonListener (this);
  39322. if (incDecButtonMode != incDecButtonsNotDraggable)
  39323. {
  39324. incButton->addMouseListener (this, false);
  39325. decButton->addMouseListener (this, false);
  39326. }
  39327. else
  39328. {
  39329. incButton->setRepeatSpeed (300, 100, 20);
  39330. incButton->addMouseListener (decButton, false);
  39331. decButton->setRepeatSpeed (300, 100, 20);
  39332. decButton->addMouseListener (incButton, false);
  39333. }
  39334. incButton->setTooltip (getTooltip());
  39335. decButton->setTooltip (getTooltip());
  39336. }
  39337. setComponentEffect (lf.getSliderEffect());
  39338. resized();
  39339. repaint();
  39340. }
  39341. void Slider::setRange (const double newMin,
  39342. const double newMax,
  39343. const double newInt)
  39344. {
  39345. if (minimum != newMin
  39346. || maximum != newMax
  39347. || interval != newInt)
  39348. {
  39349. minimum = newMin;
  39350. maximum = newMax;
  39351. interval = newInt;
  39352. // figure out the number of DPs needed to display all values at this
  39353. // interval setting.
  39354. numDecimalPlaces = 7;
  39355. if (newInt != 0)
  39356. {
  39357. int v = abs ((int) (newInt * 10000000));
  39358. while ((v % 10) == 0)
  39359. {
  39360. --numDecimalPlaces;
  39361. v /= 10;
  39362. }
  39363. }
  39364. // keep the current values inside the new range..
  39365. if (style != TwoValueHorizontal && style != TwoValueVertical)
  39366. {
  39367. setValue (getValue(), false, false);
  39368. }
  39369. else
  39370. {
  39371. setMinValue (getMinValue(), false, false);
  39372. setMaxValue (getMaxValue(), false, false);
  39373. }
  39374. updateText();
  39375. }
  39376. }
  39377. void Slider::triggerChangeMessage (const bool synchronous)
  39378. {
  39379. if (synchronous)
  39380. handleAsyncUpdate();
  39381. else
  39382. triggerAsyncUpdate();
  39383. valueChanged();
  39384. }
  39385. void Slider::valueChanged (Value& value)
  39386. {
  39387. if (value.refersToSameSourceAs (currentValue))
  39388. {
  39389. if (style != TwoValueHorizontal && style != TwoValueVertical)
  39390. setValue (currentValue.getValue(), false, false);
  39391. }
  39392. else if (value.refersToSameSourceAs (valueMin))
  39393. setMinValue (valueMin.getValue(), false, false, true);
  39394. else if (value.refersToSameSourceAs (valueMax))
  39395. setMaxValue (valueMax.getValue(), false, false, true);
  39396. }
  39397. double Slider::getValue() const
  39398. {
  39399. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  39400. // methods to get the two values.
  39401. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  39402. return currentValue.getValue();
  39403. }
  39404. void Slider::setValue (double newValue,
  39405. const bool sendUpdateMessage,
  39406. const bool sendMessageSynchronously)
  39407. {
  39408. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  39409. // methods to set the two values.
  39410. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  39411. newValue = constrainedValue (newValue);
  39412. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  39413. {
  39414. jassert ((double) valueMin.getValue() <= (double) valueMax.getValue());
  39415. newValue = jlimit ((double) valueMin.getValue(),
  39416. (double) valueMax.getValue(),
  39417. newValue);
  39418. }
  39419. if (newValue != lastCurrentValue)
  39420. {
  39421. if (valueBox != 0)
  39422. valueBox->hideEditor (true);
  39423. lastCurrentValue = newValue;
  39424. currentValue = newValue;
  39425. updateText();
  39426. repaint();
  39427. if (popupDisplay != 0)
  39428. {
  39429. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39430. ->updatePosition (getTextFromValue (newValue));
  39431. popupDisplay->repaint();
  39432. }
  39433. if (sendUpdateMessage)
  39434. triggerChangeMessage (sendMessageSynchronously);
  39435. }
  39436. }
  39437. double Slider::getMinValue() const
  39438. {
  39439. // The minimum value only applies to sliders that are in two- or three-value mode.
  39440. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39441. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39442. return valueMin.getValue();
  39443. }
  39444. double Slider::getMaxValue() const
  39445. {
  39446. // The maximum value only applies to sliders that are in two- or three-value mode.
  39447. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39448. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39449. return valueMax.getValue();
  39450. }
  39451. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  39452. {
  39453. // The minimum value only applies to sliders that are in two- or three-value mode.
  39454. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39455. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39456. newValue = constrainedValue (newValue);
  39457. if (style == TwoValueHorizontal || style == TwoValueVertical)
  39458. {
  39459. if (allowNudgingOfOtherValues && newValue > (double) valueMax.getValue())
  39460. setMaxValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39461. newValue = jmin ((double) valueMax.getValue(), newValue);
  39462. }
  39463. else
  39464. {
  39465. if (allowNudgingOfOtherValues && newValue > lastCurrentValue)
  39466. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39467. newValue = jmin (lastCurrentValue, newValue);
  39468. }
  39469. if (lastValueMin != newValue)
  39470. {
  39471. lastValueMin = newValue;
  39472. valueMin = newValue;
  39473. repaint();
  39474. if (popupDisplay != 0)
  39475. {
  39476. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39477. ->updatePosition (getTextFromValue (newValue));
  39478. popupDisplay->repaint();
  39479. }
  39480. if (sendUpdateMessage)
  39481. triggerChangeMessage (sendMessageSynchronously);
  39482. }
  39483. }
  39484. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  39485. {
  39486. // The maximum value only applies to sliders that are in two- or three-value mode.
  39487. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39488. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39489. newValue = constrainedValue (newValue);
  39490. if (style == TwoValueHorizontal || style == TwoValueVertical)
  39491. {
  39492. if (allowNudgingOfOtherValues && newValue < (double) valueMin.getValue())
  39493. setMinValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39494. newValue = jmax ((double) valueMin.getValue(), newValue);
  39495. }
  39496. else
  39497. {
  39498. if (allowNudgingOfOtherValues && newValue < lastCurrentValue)
  39499. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39500. newValue = jmax (lastCurrentValue, newValue);
  39501. }
  39502. if (lastValueMax != newValue)
  39503. {
  39504. lastValueMax = newValue;
  39505. valueMax = newValue;
  39506. repaint();
  39507. if (popupDisplay != 0)
  39508. {
  39509. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39510. ->updatePosition (getTextFromValue (valueMax.getValue()));
  39511. popupDisplay->repaint();
  39512. }
  39513. if (sendUpdateMessage)
  39514. triggerChangeMessage (sendMessageSynchronously);
  39515. }
  39516. }
  39517. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  39518. const double valueToSetOnDoubleClick)
  39519. {
  39520. doubleClickToValue = isDoubleClickEnabled;
  39521. doubleClickReturnValue = valueToSetOnDoubleClick;
  39522. }
  39523. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const
  39524. {
  39525. isEnabled_ = doubleClickToValue;
  39526. return doubleClickReturnValue;
  39527. }
  39528. void Slider::updateText()
  39529. {
  39530. if (valueBox != 0)
  39531. valueBox->setText (getTextFromValue (currentValue.getValue()), false);
  39532. }
  39533. void Slider::setTextValueSuffix (const String& suffix)
  39534. {
  39535. if (textSuffix != suffix)
  39536. {
  39537. textSuffix = suffix;
  39538. updateText();
  39539. }
  39540. }
  39541. const String Slider::getTextValueSuffix() const
  39542. {
  39543. return textSuffix;
  39544. }
  39545. const String Slider::getTextFromValue (double v)
  39546. {
  39547. if (getNumDecimalPlacesToDisplay() > 0)
  39548. return String (v, getNumDecimalPlacesToDisplay()) + getTextValueSuffix();
  39549. else
  39550. return String (roundToInt (v)) + getTextValueSuffix();
  39551. }
  39552. double Slider::getValueFromText (const String& text)
  39553. {
  39554. String t (text.trimStart());
  39555. if (t.endsWith (textSuffix))
  39556. t = t.substring (0, t.length() - textSuffix.length());
  39557. while (t.startsWithChar ('+'))
  39558. t = t.substring (1).trimStart();
  39559. return t.initialSectionContainingOnly ("0123456789.,-")
  39560. .getDoubleValue();
  39561. }
  39562. double Slider::proportionOfLengthToValue (double proportion)
  39563. {
  39564. if (skewFactor != 1.0 && proportion > 0.0)
  39565. proportion = exp (log (proportion) / skewFactor);
  39566. return minimum + (maximum - minimum) * proportion;
  39567. }
  39568. double Slider::valueToProportionOfLength (double value)
  39569. {
  39570. const double n = (value - minimum) / (maximum - minimum);
  39571. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  39572. }
  39573. double Slider::snapValue (double attemptedValue, const bool)
  39574. {
  39575. return attemptedValue;
  39576. }
  39577. void Slider::startedDragging()
  39578. {
  39579. }
  39580. void Slider::stoppedDragging()
  39581. {
  39582. }
  39583. void Slider::valueChanged()
  39584. {
  39585. }
  39586. void Slider::enablementChanged()
  39587. {
  39588. repaint();
  39589. }
  39590. void Slider::setPopupMenuEnabled (const bool menuEnabled_)
  39591. {
  39592. menuEnabled = menuEnabled_;
  39593. }
  39594. void Slider::setScrollWheelEnabled (const bool enabled)
  39595. {
  39596. scrollWheelEnabled = enabled;
  39597. }
  39598. void Slider::labelTextChanged (Label* label)
  39599. {
  39600. const double newValue = snapValue (getValueFromText (label->getText()), false);
  39601. if (newValue != (double) currentValue.getValue())
  39602. {
  39603. sendDragStart();
  39604. setValue (newValue, true, true);
  39605. sendDragEnd();
  39606. }
  39607. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  39608. }
  39609. void Slider::buttonClicked (Button* button)
  39610. {
  39611. if (style == IncDecButtons)
  39612. {
  39613. sendDragStart();
  39614. if (button == incButton)
  39615. setValue (snapValue (getValue() + interval, false), true, true);
  39616. else if (button == decButton)
  39617. setValue (snapValue (getValue() - interval, false), true, true);
  39618. sendDragEnd();
  39619. }
  39620. }
  39621. double Slider::constrainedValue (double value) const
  39622. {
  39623. if (interval > 0)
  39624. value = minimum + interval * std::floor ((value - minimum) / interval + 0.5);
  39625. if (value <= minimum || maximum <= minimum)
  39626. value = minimum;
  39627. else if (value >= maximum)
  39628. value = maximum;
  39629. return value;
  39630. }
  39631. float Slider::getLinearSliderPos (const double value)
  39632. {
  39633. double sliderPosProportional;
  39634. if (maximum > minimum)
  39635. {
  39636. if (value < minimum)
  39637. {
  39638. sliderPosProportional = 0.0;
  39639. }
  39640. else if (value > maximum)
  39641. {
  39642. sliderPosProportional = 1.0;
  39643. }
  39644. else
  39645. {
  39646. sliderPosProportional = valueToProportionOfLength (value);
  39647. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  39648. }
  39649. }
  39650. else
  39651. {
  39652. sliderPosProportional = 0.5;
  39653. }
  39654. if (isVertical() || style == IncDecButtons)
  39655. sliderPosProportional = 1.0 - sliderPosProportional;
  39656. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  39657. }
  39658. bool Slider::isHorizontal() const
  39659. {
  39660. return style == LinearHorizontal
  39661. || style == LinearBar
  39662. || style == TwoValueHorizontal
  39663. || style == ThreeValueHorizontal;
  39664. }
  39665. bool Slider::isVertical() const
  39666. {
  39667. return style == LinearVertical
  39668. || style == TwoValueVertical
  39669. || style == ThreeValueVertical;
  39670. }
  39671. bool Slider::incDecDragDirectionIsHorizontal() const
  39672. {
  39673. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  39674. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  39675. }
  39676. float Slider::getPositionOfValue (const double value)
  39677. {
  39678. if (isHorizontal() || isVertical())
  39679. {
  39680. return getLinearSliderPos (value);
  39681. }
  39682. else
  39683. {
  39684. jassertfalse; // not a valid call on a slider that doesn't work linearly!
  39685. return 0.0f;
  39686. }
  39687. }
  39688. void Slider::paint (Graphics& g)
  39689. {
  39690. if (style != IncDecButtons)
  39691. {
  39692. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  39693. {
  39694. const float sliderPos = (float) valueToProportionOfLength (lastCurrentValue);
  39695. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  39696. getLookAndFeel().drawRotarySlider (g,
  39697. sliderRect.getX(),
  39698. sliderRect.getY(),
  39699. sliderRect.getWidth(),
  39700. sliderRect.getHeight(),
  39701. sliderPos,
  39702. rotaryStart, rotaryEnd,
  39703. *this);
  39704. }
  39705. else
  39706. {
  39707. getLookAndFeel().drawLinearSlider (g,
  39708. sliderRect.getX(),
  39709. sliderRect.getY(),
  39710. sliderRect.getWidth(),
  39711. sliderRect.getHeight(),
  39712. getLinearSliderPos (lastCurrentValue),
  39713. getLinearSliderPos (lastValueMin),
  39714. getLinearSliderPos (lastValueMax),
  39715. style,
  39716. *this);
  39717. }
  39718. if (style == LinearBar && valueBox == 0)
  39719. {
  39720. g.setColour (findColour (Slider::textBoxOutlineColourId));
  39721. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  39722. }
  39723. }
  39724. }
  39725. void Slider::resized()
  39726. {
  39727. int minXSpace = 0;
  39728. int minYSpace = 0;
  39729. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  39730. minXSpace = 30;
  39731. else
  39732. minYSpace = 15;
  39733. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  39734. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  39735. if (style == LinearBar)
  39736. {
  39737. if (valueBox != 0)
  39738. valueBox->setBounds (getLocalBounds());
  39739. }
  39740. else
  39741. {
  39742. if (textBoxPos == NoTextBox)
  39743. {
  39744. sliderRect = getLocalBounds();
  39745. }
  39746. else if (textBoxPos == TextBoxLeft)
  39747. {
  39748. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  39749. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  39750. }
  39751. else if (textBoxPos == TextBoxRight)
  39752. {
  39753. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  39754. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  39755. }
  39756. else if (textBoxPos == TextBoxAbove)
  39757. {
  39758. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  39759. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  39760. }
  39761. else if (textBoxPos == TextBoxBelow)
  39762. {
  39763. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  39764. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  39765. }
  39766. }
  39767. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  39768. if (style == LinearBar)
  39769. {
  39770. const int barIndent = 1;
  39771. sliderRegionStart = barIndent;
  39772. sliderRegionSize = getWidth() - barIndent * 2;
  39773. sliderRect.setBounds (sliderRegionStart, barIndent,
  39774. sliderRegionSize, getHeight() - barIndent * 2);
  39775. }
  39776. else if (isHorizontal())
  39777. {
  39778. sliderRegionStart = sliderRect.getX() + indent;
  39779. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  39780. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  39781. sliderRegionSize, sliderRect.getHeight());
  39782. }
  39783. else if (isVertical())
  39784. {
  39785. sliderRegionStart = sliderRect.getY() + indent;
  39786. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  39787. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  39788. sliderRect.getWidth(), sliderRegionSize);
  39789. }
  39790. else
  39791. {
  39792. sliderRegionStart = 0;
  39793. sliderRegionSize = 100;
  39794. }
  39795. if (style == IncDecButtons)
  39796. {
  39797. Rectangle<int> buttonRect (sliderRect);
  39798. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  39799. buttonRect.expand (-2, 0);
  39800. else
  39801. buttonRect.expand (0, -2);
  39802. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  39803. if (incDecButtonsSideBySide)
  39804. {
  39805. decButton->setBounds (buttonRect.getX(),
  39806. buttonRect.getY(),
  39807. buttonRect.getWidth() / 2,
  39808. buttonRect.getHeight());
  39809. decButton->setConnectedEdges (Button::ConnectedOnRight);
  39810. incButton->setBounds (buttonRect.getCentreX(),
  39811. buttonRect.getY(),
  39812. buttonRect.getWidth() / 2,
  39813. buttonRect.getHeight());
  39814. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  39815. }
  39816. else
  39817. {
  39818. incButton->setBounds (buttonRect.getX(),
  39819. buttonRect.getY(),
  39820. buttonRect.getWidth(),
  39821. buttonRect.getHeight() / 2);
  39822. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  39823. decButton->setBounds (buttonRect.getX(),
  39824. buttonRect.getCentreY(),
  39825. buttonRect.getWidth(),
  39826. buttonRect.getHeight() / 2);
  39827. decButton->setConnectedEdges (Button::ConnectedOnTop);
  39828. }
  39829. }
  39830. }
  39831. void Slider::focusOfChildComponentChanged (FocusChangeType)
  39832. {
  39833. repaint();
  39834. }
  39835. void Slider::mouseDown (const MouseEvent& e)
  39836. {
  39837. mouseWasHidden = false;
  39838. incDecDragged = false;
  39839. mouseXWhenLastDragged = e.x;
  39840. mouseYWhenLastDragged = e.y;
  39841. mouseDragStartX = e.getMouseDownX();
  39842. mouseDragStartY = e.getMouseDownY();
  39843. if (isEnabled())
  39844. {
  39845. if (e.mods.isPopupMenu() && menuEnabled)
  39846. {
  39847. menuShown = true;
  39848. PopupMenu m;
  39849. m.setLookAndFeel (&getLookAndFeel());
  39850. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  39851. m.addSeparator();
  39852. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  39853. {
  39854. PopupMenu rotaryMenu;
  39855. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  39856. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  39857. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  39858. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  39859. }
  39860. const int r = m.show();
  39861. if (r == 1)
  39862. {
  39863. setVelocityBasedMode (! isVelocityBased);
  39864. }
  39865. else if (r == 2)
  39866. {
  39867. setSliderStyle (Rotary);
  39868. }
  39869. else if (r == 3)
  39870. {
  39871. setSliderStyle (RotaryHorizontalDrag);
  39872. }
  39873. else if (r == 4)
  39874. {
  39875. setSliderStyle (RotaryVerticalDrag);
  39876. }
  39877. }
  39878. else if (maximum > minimum)
  39879. {
  39880. menuShown = false;
  39881. if (valueBox != 0)
  39882. valueBox->hideEditor (true);
  39883. sliderBeingDragged = 0;
  39884. if (style == TwoValueHorizontal
  39885. || style == TwoValueVertical
  39886. || style == ThreeValueHorizontal
  39887. || style == ThreeValueVertical)
  39888. {
  39889. const float mousePos = (float) (isVertical() ? e.y : e.x);
  39890. const float normalPosDistance = std::abs (getLinearSliderPos (currentValue.getValue()) - mousePos);
  39891. const float minPosDistance = std::abs (getLinearSliderPos (valueMin.getValue()) - 0.1f - mousePos);
  39892. const float maxPosDistance = std::abs (getLinearSliderPos (valueMax.getValue()) + 0.1f - mousePos);
  39893. if (style == TwoValueHorizontal || style == TwoValueVertical)
  39894. {
  39895. if (maxPosDistance <= minPosDistance)
  39896. sliderBeingDragged = 2;
  39897. else
  39898. sliderBeingDragged = 1;
  39899. }
  39900. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  39901. {
  39902. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  39903. sliderBeingDragged = 1;
  39904. else if (normalPosDistance >= maxPosDistance)
  39905. sliderBeingDragged = 2;
  39906. }
  39907. }
  39908. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  39909. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  39910. * valueToProportionOfLength (currentValue.getValue());
  39911. valueWhenLastDragged = ((sliderBeingDragged == 2) ? valueMax
  39912. : ((sliderBeingDragged == 1) ? valueMin
  39913. : currentValue)).getValue();
  39914. valueOnMouseDown = valueWhenLastDragged;
  39915. if (popupDisplayEnabled)
  39916. {
  39917. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  39918. popupDisplay = popup;
  39919. if (parentForPopupDisplay != 0)
  39920. {
  39921. parentForPopupDisplay->addChildComponent (popup);
  39922. }
  39923. else
  39924. {
  39925. popup->addToDesktop (0);
  39926. }
  39927. popup->setVisible (true);
  39928. }
  39929. sendDragStart();
  39930. mouseDrag (e);
  39931. }
  39932. }
  39933. }
  39934. void Slider::mouseUp (const MouseEvent&)
  39935. {
  39936. if (isEnabled()
  39937. && (! menuShown)
  39938. && (maximum > minimum)
  39939. && (style != IncDecButtons || incDecDragged))
  39940. {
  39941. restoreMouseIfHidden();
  39942. if (sendChangeOnlyOnRelease && valueOnMouseDown != (double) currentValue.getValue())
  39943. triggerChangeMessage (false);
  39944. sendDragEnd();
  39945. popupDisplay = 0;
  39946. if (style == IncDecButtons)
  39947. {
  39948. incButton->setState (Button::buttonNormal);
  39949. decButton->setState (Button::buttonNormal);
  39950. }
  39951. }
  39952. }
  39953. void Slider::restoreMouseIfHidden()
  39954. {
  39955. if (mouseWasHidden)
  39956. {
  39957. mouseWasHidden = false;
  39958. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  39959. Desktop::getInstance().getMouseSource(i)->enableUnboundedMouseMovement (false);
  39960. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  39961. : ((sliderBeingDragged == 1) ? getMinValue()
  39962. : (double) currentValue.getValue());
  39963. Point<int> mousePos;
  39964. if (style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  39965. {
  39966. mousePos = Desktop::getLastMouseDownPosition();
  39967. if (style == RotaryHorizontalDrag)
  39968. {
  39969. const double posDiff = valueToProportionOfLength (pos) - valueToProportionOfLength (valueOnMouseDown);
  39970. mousePos += Point<int> (roundToInt (pixelsForFullDragExtent * posDiff), 0);
  39971. }
  39972. else
  39973. {
  39974. const double posDiff = valueToProportionOfLength (valueOnMouseDown) - valueToProportionOfLength (pos);
  39975. mousePos += Point<int> (0, roundToInt (pixelsForFullDragExtent * posDiff));
  39976. }
  39977. }
  39978. else
  39979. {
  39980. const int pixelPos = (int) getLinearSliderPos (pos);
  39981. mousePos = relativePositionToGlobal (Point<int> (isHorizontal() ? pixelPos : (getWidth() / 2),
  39982. isVertical() ? pixelPos : (getHeight() / 2)));
  39983. }
  39984. Desktop::setMousePosition (mousePos);
  39985. }
  39986. }
  39987. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  39988. {
  39989. if (isEnabled()
  39990. && style != IncDecButtons
  39991. && style != Rotary
  39992. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  39993. {
  39994. restoreMouseIfHidden();
  39995. }
  39996. }
  39997. static double smallestAngleBetween (double a1, double a2)
  39998. {
  39999. return jmin (std::abs (a1 - a2),
  40000. std::abs (a1 + double_Pi * 2.0 - a2),
  40001. std::abs (a2 + double_Pi * 2.0 - a1));
  40002. }
  40003. void Slider::mouseDrag (const MouseEvent& e)
  40004. {
  40005. if (isEnabled()
  40006. && (! menuShown)
  40007. && (maximum > minimum))
  40008. {
  40009. if (style == Rotary)
  40010. {
  40011. int dx = e.x - sliderRect.getCentreX();
  40012. int dy = e.y - sliderRect.getCentreY();
  40013. if (dx * dx + dy * dy > 25)
  40014. {
  40015. double angle = std::atan2 ((double) dx, (double) -dy);
  40016. while (angle < 0.0)
  40017. angle += double_Pi * 2.0;
  40018. if (rotaryStop && ! e.mouseWasClicked())
  40019. {
  40020. if (std::abs (angle - lastAngle) > double_Pi)
  40021. {
  40022. if (angle >= lastAngle)
  40023. angle -= double_Pi * 2.0;
  40024. else
  40025. angle += double_Pi * 2.0;
  40026. }
  40027. if (angle >= lastAngle)
  40028. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  40029. else
  40030. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  40031. }
  40032. else
  40033. {
  40034. while (angle < rotaryStart)
  40035. angle += double_Pi * 2.0;
  40036. if (angle > rotaryEnd)
  40037. {
  40038. if (smallestAngleBetween (angle, rotaryStart) <= smallestAngleBetween (angle, rotaryEnd))
  40039. angle = rotaryStart;
  40040. else
  40041. angle = rotaryEnd;
  40042. }
  40043. }
  40044. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  40045. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  40046. lastAngle = angle;
  40047. }
  40048. }
  40049. else
  40050. {
  40051. if (style == LinearBar && e.mouseWasClicked()
  40052. && valueBox != 0 && valueBox->isEditable())
  40053. return;
  40054. if (style == IncDecButtons && ! incDecDragged)
  40055. {
  40056. if (e.getDistanceFromDragStart() < 10 || e.mouseWasClicked())
  40057. return;
  40058. incDecDragged = true;
  40059. mouseDragStartX = e.x;
  40060. mouseDragStartY = e.y;
  40061. }
  40062. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  40063. : false))
  40064. || ((maximum - minimum) / sliderRegionSize < interval))
  40065. {
  40066. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  40067. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  40068. if (style == RotaryHorizontalDrag
  40069. || style == RotaryVerticalDrag
  40070. || style == IncDecButtons
  40071. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  40072. && ! snapsToMousePos))
  40073. {
  40074. const int mouseDiff = (style == RotaryHorizontalDrag
  40075. || style == LinearHorizontal
  40076. || style == LinearBar
  40077. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40078. ? e.x - mouseDragStartX
  40079. : mouseDragStartY - e.y;
  40080. double newPos = valueToProportionOfLength (valueOnMouseDown)
  40081. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  40082. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  40083. if (style == IncDecButtons)
  40084. {
  40085. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  40086. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  40087. }
  40088. }
  40089. else
  40090. {
  40091. if (isVertical())
  40092. scaledMousePos = 1.0 - scaledMousePos;
  40093. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  40094. }
  40095. }
  40096. else
  40097. {
  40098. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  40099. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40100. ? e.x - mouseXWhenLastDragged
  40101. : e.y - mouseYWhenLastDragged;
  40102. const double maxSpeed = jmax (200, sliderRegionSize);
  40103. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  40104. if (speed != 0)
  40105. {
  40106. speed = 0.2 * velocityModeSensitivity
  40107. * (1.0 + std::sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  40108. + jmax (0.0, (double) (speed - velocityModeThreshold))
  40109. / maxSpeed))));
  40110. if (mouseDiff < 0)
  40111. speed = -speed;
  40112. if (isVertical() || style == RotaryVerticalDrag
  40113. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  40114. speed = -speed;
  40115. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  40116. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  40117. e.source.enableUnboundedMouseMovement (true, false);
  40118. mouseWasHidden = true;
  40119. }
  40120. }
  40121. }
  40122. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  40123. if (sliderBeingDragged == 0)
  40124. {
  40125. setValue (snapValue (valueWhenLastDragged, true),
  40126. ! sendChangeOnlyOnRelease, true);
  40127. }
  40128. else if (sliderBeingDragged == 1)
  40129. {
  40130. setMinValue (snapValue (valueWhenLastDragged, true),
  40131. ! sendChangeOnlyOnRelease, false, true);
  40132. if (e.mods.isShiftDown())
  40133. setMaxValue (getMinValue() + minMaxDiff, false, false, true);
  40134. else
  40135. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40136. }
  40137. else
  40138. {
  40139. jassert (sliderBeingDragged == 2);
  40140. setMaxValue (snapValue (valueWhenLastDragged, true),
  40141. ! sendChangeOnlyOnRelease, false, true);
  40142. if (e.mods.isShiftDown())
  40143. setMinValue (getMaxValue() - minMaxDiff, false, false, true);
  40144. else
  40145. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40146. }
  40147. mouseXWhenLastDragged = e.x;
  40148. mouseYWhenLastDragged = e.y;
  40149. }
  40150. }
  40151. void Slider::mouseDoubleClick (const MouseEvent&)
  40152. {
  40153. if (doubleClickToValue
  40154. && isEnabled()
  40155. && style != IncDecButtons
  40156. && minimum <= doubleClickReturnValue
  40157. && maximum >= doubleClickReturnValue)
  40158. {
  40159. sendDragStart();
  40160. setValue (doubleClickReturnValue, true, true);
  40161. sendDragEnd();
  40162. }
  40163. }
  40164. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  40165. {
  40166. if (scrollWheelEnabled && isEnabled()
  40167. && style != TwoValueHorizontal
  40168. && style != TwoValueVertical)
  40169. {
  40170. if (maximum > minimum && ! e.mods.isAnyMouseButtonDown())
  40171. {
  40172. if (valueBox != 0)
  40173. valueBox->hideEditor (false);
  40174. const double value = (double) currentValue.getValue();
  40175. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  40176. const double currentPos = valueToProportionOfLength (value);
  40177. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  40178. double delta = (newValue != value)
  40179. ? jmax (std::abs (newValue - value), interval) : 0;
  40180. if (value > newValue)
  40181. delta = -delta;
  40182. sendDragStart();
  40183. setValue (snapValue (value + delta, false), true, true);
  40184. sendDragEnd();
  40185. }
  40186. }
  40187. else
  40188. {
  40189. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  40190. }
  40191. }
  40192. void SliderListener::sliderDragStarted (Slider*)
  40193. {
  40194. }
  40195. void SliderListener::sliderDragEnded (Slider*)
  40196. {
  40197. }
  40198. END_JUCE_NAMESPACE
  40199. /*** End of inlined file: juce_Slider.cpp ***/
  40200. /*** Start of inlined file: juce_TableHeaderComponent.cpp ***/
  40201. BEGIN_JUCE_NAMESPACE
  40202. class DragOverlayComp : public Component
  40203. {
  40204. public:
  40205. DragOverlayComp (const Image& image_)
  40206. : image (image_)
  40207. {
  40208. image.duplicateIfShared();
  40209. image.multiplyAllAlphas (0.8f);
  40210. setAlwaysOnTop (true);
  40211. }
  40212. ~DragOverlayComp()
  40213. {
  40214. }
  40215. void paint (Graphics& g)
  40216. {
  40217. g.drawImageAt (image, 0, 0);
  40218. }
  40219. private:
  40220. Image image;
  40221. DragOverlayComp (const DragOverlayComp&);
  40222. DragOverlayComp& operator= (const DragOverlayComp&);
  40223. };
  40224. TableHeaderComponent::TableHeaderComponent()
  40225. : columnsChanged (false),
  40226. columnsResized (false),
  40227. sortChanged (false),
  40228. menuActive (true),
  40229. stretchToFit (false),
  40230. columnIdBeingResized (0),
  40231. columnIdBeingDragged (0),
  40232. columnIdUnderMouse (0),
  40233. lastDeliberateWidth (0)
  40234. {
  40235. }
  40236. TableHeaderComponent::~TableHeaderComponent()
  40237. {
  40238. dragOverlayComp = 0;
  40239. }
  40240. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  40241. {
  40242. menuActive = hasMenu;
  40243. }
  40244. bool TableHeaderComponent::isPopupMenuActive() const { return menuActive; }
  40245. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const
  40246. {
  40247. if (onlyCountVisibleColumns)
  40248. {
  40249. int num = 0;
  40250. for (int i = columns.size(); --i >= 0;)
  40251. if (columns.getUnchecked(i)->isVisible())
  40252. ++num;
  40253. return num;
  40254. }
  40255. else
  40256. {
  40257. return columns.size();
  40258. }
  40259. }
  40260. const String TableHeaderComponent::getColumnName (const int columnId) const
  40261. {
  40262. const ColumnInfo* const ci = getInfoForId (columnId);
  40263. return ci != 0 ? ci->name : String::empty;
  40264. }
  40265. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  40266. {
  40267. ColumnInfo* const ci = getInfoForId (columnId);
  40268. if (ci != 0 && ci->name != newName)
  40269. {
  40270. ci->name = newName;
  40271. sendColumnsChanged();
  40272. }
  40273. }
  40274. void TableHeaderComponent::addColumn (const String& columnName,
  40275. const int columnId,
  40276. const int width,
  40277. const int minimumWidth,
  40278. const int maximumWidth,
  40279. const int propertyFlags,
  40280. const int insertIndex)
  40281. {
  40282. // can't have a duplicate or null ID!
  40283. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  40284. jassert (width > 0);
  40285. ColumnInfo* const ci = new ColumnInfo();
  40286. ci->name = columnName;
  40287. ci->id = columnId;
  40288. ci->width = width;
  40289. ci->lastDeliberateWidth = width;
  40290. ci->minimumWidth = minimumWidth;
  40291. ci->maximumWidth = maximumWidth;
  40292. if (ci->maximumWidth < 0)
  40293. ci->maximumWidth = std::numeric_limits<int>::max();
  40294. jassert (ci->maximumWidth >= ci->minimumWidth);
  40295. ci->propertyFlags = propertyFlags;
  40296. columns.insert (insertIndex, ci);
  40297. sendColumnsChanged();
  40298. }
  40299. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  40300. {
  40301. const int index = getIndexOfColumnId (columnIdToRemove, false);
  40302. if (index >= 0)
  40303. {
  40304. columns.remove (index);
  40305. sortChanged = true;
  40306. sendColumnsChanged();
  40307. }
  40308. }
  40309. void TableHeaderComponent::removeAllColumns()
  40310. {
  40311. if (columns.size() > 0)
  40312. {
  40313. columns.clear();
  40314. sendColumnsChanged();
  40315. }
  40316. }
  40317. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  40318. {
  40319. const int currentIndex = getIndexOfColumnId (columnId, false);
  40320. newIndex = visibleIndexToTotalIndex (newIndex);
  40321. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  40322. {
  40323. columns.move (currentIndex, newIndex);
  40324. sendColumnsChanged();
  40325. }
  40326. }
  40327. int TableHeaderComponent::getColumnWidth (const int columnId) const
  40328. {
  40329. const ColumnInfo* const ci = getInfoForId (columnId);
  40330. return ci != 0 ? ci->width : 0;
  40331. }
  40332. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  40333. {
  40334. ColumnInfo* const ci = getInfoForId (columnId);
  40335. if (ci != 0 && ci->width != newWidth)
  40336. {
  40337. const int numColumns = getNumColumns (true);
  40338. ci->lastDeliberateWidth = ci->width
  40339. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  40340. if (stretchToFit)
  40341. {
  40342. const int index = getIndexOfColumnId (columnId, true) + 1;
  40343. if (((unsigned int) index) < (unsigned int) numColumns)
  40344. {
  40345. const int x = getColumnPosition (index).getX();
  40346. if (lastDeliberateWidth == 0)
  40347. lastDeliberateWidth = getTotalWidth();
  40348. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  40349. }
  40350. }
  40351. repaint();
  40352. columnsResized = true;
  40353. triggerAsyncUpdate();
  40354. }
  40355. }
  40356. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const
  40357. {
  40358. int n = 0;
  40359. for (int i = 0; i < columns.size(); ++i)
  40360. {
  40361. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  40362. {
  40363. if (columns.getUnchecked(i)->id == columnId)
  40364. return n;
  40365. ++n;
  40366. }
  40367. }
  40368. return -1;
  40369. }
  40370. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const
  40371. {
  40372. if (onlyCountVisibleColumns)
  40373. index = visibleIndexToTotalIndex (index);
  40374. const ColumnInfo* const ci = columns [index];
  40375. return (ci != 0) ? ci->id : 0;
  40376. }
  40377. const Rectangle<int> TableHeaderComponent::getColumnPosition (const int index) const
  40378. {
  40379. int x = 0, width = 0, n = 0;
  40380. for (int i = 0; i < columns.size(); ++i)
  40381. {
  40382. x += width;
  40383. if (columns.getUnchecked(i)->isVisible())
  40384. {
  40385. width = columns.getUnchecked(i)->width;
  40386. if (n++ == index)
  40387. break;
  40388. }
  40389. else
  40390. {
  40391. width = 0;
  40392. }
  40393. }
  40394. return Rectangle<int> (x, 0, width, getHeight());
  40395. }
  40396. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const
  40397. {
  40398. if (xToFind >= 0)
  40399. {
  40400. int x = 0;
  40401. for (int i = 0; i < columns.size(); ++i)
  40402. {
  40403. const ColumnInfo* const ci = columns.getUnchecked(i);
  40404. if (ci->isVisible())
  40405. {
  40406. x += ci->width;
  40407. if (xToFind < x)
  40408. return ci->id;
  40409. }
  40410. }
  40411. }
  40412. return 0;
  40413. }
  40414. int TableHeaderComponent::getTotalWidth() const
  40415. {
  40416. int w = 0;
  40417. for (int i = columns.size(); --i >= 0;)
  40418. if (columns.getUnchecked(i)->isVisible())
  40419. w += columns.getUnchecked(i)->width;
  40420. return w;
  40421. }
  40422. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  40423. {
  40424. stretchToFit = shouldStretchToFit;
  40425. lastDeliberateWidth = getTotalWidth();
  40426. resized();
  40427. }
  40428. bool TableHeaderComponent::isStretchToFitActive() const
  40429. {
  40430. return stretchToFit;
  40431. }
  40432. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  40433. {
  40434. if (stretchToFit && getWidth() > 0
  40435. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  40436. {
  40437. lastDeliberateWidth = targetTotalWidth;
  40438. resizeColumnsToFit (0, targetTotalWidth);
  40439. }
  40440. }
  40441. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  40442. {
  40443. targetTotalWidth = jmax (targetTotalWidth, 0);
  40444. StretchableObjectResizer sor;
  40445. int i;
  40446. for (i = firstColumnIndex; i < columns.size(); ++i)
  40447. {
  40448. ColumnInfo* const ci = columns.getUnchecked(i);
  40449. if (ci->isVisible())
  40450. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  40451. }
  40452. sor.resizeToFit (targetTotalWidth);
  40453. int visIndex = 0;
  40454. for (i = firstColumnIndex; i < columns.size(); ++i)
  40455. {
  40456. ColumnInfo* const ci = columns.getUnchecked(i);
  40457. if (ci->isVisible())
  40458. {
  40459. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  40460. (int) std::floor (sor.getItemSize (visIndex++)));
  40461. if (newWidth != ci->width)
  40462. {
  40463. ci->width = newWidth;
  40464. repaint();
  40465. columnsResized = true;
  40466. triggerAsyncUpdate();
  40467. }
  40468. }
  40469. }
  40470. }
  40471. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  40472. {
  40473. ColumnInfo* const ci = getInfoForId (columnId);
  40474. if (ci != 0 && shouldBeVisible != ci->isVisible())
  40475. {
  40476. if (shouldBeVisible)
  40477. ci->propertyFlags |= visible;
  40478. else
  40479. ci->propertyFlags &= ~visible;
  40480. sendColumnsChanged();
  40481. resized();
  40482. }
  40483. }
  40484. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  40485. {
  40486. const ColumnInfo* const ci = getInfoForId (columnId);
  40487. return ci != 0 && ci->isVisible();
  40488. }
  40489. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  40490. {
  40491. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  40492. {
  40493. for (int i = columns.size(); --i >= 0;)
  40494. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  40495. ColumnInfo* const ci = getInfoForId (columnId);
  40496. if (ci != 0)
  40497. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  40498. reSortTable();
  40499. }
  40500. }
  40501. int TableHeaderComponent::getSortColumnId() const
  40502. {
  40503. for (int i = columns.size(); --i >= 0;)
  40504. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  40505. return columns.getUnchecked(i)->id;
  40506. return 0;
  40507. }
  40508. bool TableHeaderComponent::isSortedForwards() const
  40509. {
  40510. for (int i = columns.size(); --i >= 0;)
  40511. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  40512. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  40513. return true;
  40514. }
  40515. void TableHeaderComponent::reSortTable()
  40516. {
  40517. sortChanged = true;
  40518. repaint();
  40519. triggerAsyncUpdate();
  40520. }
  40521. const String TableHeaderComponent::toString() const
  40522. {
  40523. String s;
  40524. XmlElement doc ("TABLELAYOUT");
  40525. doc.setAttribute ("sortedCol", getSortColumnId());
  40526. doc.setAttribute ("sortForwards", isSortedForwards());
  40527. for (int i = 0; i < columns.size(); ++i)
  40528. {
  40529. const ColumnInfo* const ci = columns.getUnchecked (i);
  40530. XmlElement* const e = doc.createNewChildElement ("COLUMN");
  40531. e->setAttribute ("id", ci->id);
  40532. e->setAttribute ("visible", ci->isVisible());
  40533. e->setAttribute ("width", ci->width);
  40534. }
  40535. return doc.createDocument (String::empty, true, false);
  40536. }
  40537. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  40538. {
  40539. XmlDocument doc (storedVersion);
  40540. ScopedPointer <XmlElement> storedXml (doc.getDocumentElement());
  40541. int index = 0;
  40542. if (storedXml != 0 && storedXml->hasTagName ("TABLELAYOUT"))
  40543. {
  40544. forEachXmlChildElement (*storedXml, col)
  40545. {
  40546. const int tabId = col->getIntAttribute ("id");
  40547. ColumnInfo* const ci = getInfoForId (tabId);
  40548. if (ci != 0)
  40549. {
  40550. columns.move (columns.indexOf (ci), index);
  40551. ci->width = col->getIntAttribute ("width");
  40552. setColumnVisible (tabId, col->getBoolAttribute ("visible"));
  40553. }
  40554. ++index;
  40555. }
  40556. columnsResized = true;
  40557. sendColumnsChanged();
  40558. setSortColumnId (storedXml->getIntAttribute ("sortedCol"),
  40559. storedXml->getBoolAttribute ("sortForwards", true));
  40560. }
  40561. }
  40562. void TableHeaderComponent::addListener (TableHeaderListener* const newListener)
  40563. {
  40564. listeners.addIfNotAlreadyThere (newListener);
  40565. }
  40566. void TableHeaderComponent::removeListener (TableHeaderListener* const listenerToRemove)
  40567. {
  40568. listeners.removeValue (listenerToRemove);
  40569. }
  40570. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  40571. {
  40572. const ColumnInfo* const ci = getInfoForId (columnId);
  40573. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  40574. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  40575. }
  40576. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  40577. {
  40578. for (int i = 0; i < columns.size(); ++i)
  40579. {
  40580. const ColumnInfo* const ci = columns.getUnchecked(i);
  40581. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  40582. menu.addItem (ci->id, ci->name,
  40583. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  40584. isColumnVisible (ci->id));
  40585. }
  40586. }
  40587. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  40588. {
  40589. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  40590. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  40591. }
  40592. void TableHeaderComponent::paint (Graphics& g)
  40593. {
  40594. LookAndFeel& lf = getLookAndFeel();
  40595. lf.drawTableHeaderBackground (g, *this);
  40596. const Rectangle<int> clip (g.getClipBounds());
  40597. int x = 0;
  40598. for (int i = 0; i < columns.size(); ++i)
  40599. {
  40600. const ColumnInfo* const ci = columns.getUnchecked(i);
  40601. if (ci->isVisible())
  40602. {
  40603. if (x + ci->width > clip.getX()
  40604. && (ci->id != columnIdBeingDragged
  40605. || dragOverlayComp == 0
  40606. || ! dragOverlayComp->isVisible()))
  40607. {
  40608. g.saveState();
  40609. g.setOrigin (x, 0);
  40610. g.reduceClipRegion (0, 0, ci->width, getHeight());
  40611. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  40612. ci->id == columnIdUnderMouse,
  40613. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  40614. ci->propertyFlags);
  40615. g.restoreState();
  40616. }
  40617. x += ci->width;
  40618. if (x >= clip.getRight())
  40619. break;
  40620. }
  40621. }
  40622. }
  40623. void TableHeaderComponent::resized()
  40624. {
  40625. }
  40626. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  40627. {
  40628. updateColumnUnderMouse (e.x, e.y);
  40629. }
  40630. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  40631. {
  40632. updateColumnUnderMouse (e.x, e.y);
  40633. }
  40634. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  40635. {
  40636. updateColumnUnderMouse (e.x, e.y);
  40637. }
  40638. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  40639. {
  40640. repaint();
  40641. columnIdBeingResized = 0;
  40642. columnIdBeingDragged = 0;
  40643. if (columnIdUnderMouse != 0)
  40644. {
  40645. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  40646. if (e.mods.isPopupMenu())
  40647. columnClicked (columnIdUnderMouse, e.mods);
  40648. }
  40649. if (menuActive && e.mods.isPopupMenu())
  40650. showColumnChooserMenu (columnIdUnderMouse);
  40651. }
  40652. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  40653. {
  40654. if (columnIdBeingResized == 0
  40655. && columnIdBeingDragged == 0
  40656. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  40657. {
  40658. dragOverlayComp = 0;
  40659. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  40660. if (columnIdBeingResized != 0)
  40661. {
  40662. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  40663. initialColumnWidth = ci->width;
  40664. }
  40665. else
  40666. {
  40667. beginDrag (e);
  40668. }
  40669. }
  40670. if (columnIdBeingResized != 0)
  40671. {
  40672. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  40673. if (ci != 0)
  40674. {
  40675. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  40676. initialColumnWidth + e.getDistanceFromDragStartX());
  40677. if (stretchToFit)
  40678. {
  40679. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  40680. int minWidthOnRight = 0;
  40681. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  40682. if (columns.getUnchecked (i)->isVisible())
  40683. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  40684. const Rectangle<int> currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  40685. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  40686. }
  40687. setColumnWidth (columnIdBeingResized, w);
  40688. }
  40689. }
  40690. else if (columnIdBeingDragged != 0)
  40691. {
  40692. if (e.y >= -50 && e.y < getHeight() + 50)
  40693. {
  40694. if (dragOverlayComp != 0)
  40695. {
  40696. dragOverlayComp->setVisible (true);
  40697. dragOverlayComp->setBounds (jlimit (0,
  40698. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  40699. e.x - draggingColumnOffset),
  40700. 0,
  40701. dragOverlayComp->getWidth(),
  40702. getHeight());
  40703. for (int i = columns.size(); --i >= 0;)
  40704. {
  40705. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  40706. int newIndex = currentIndex;
  40707. if (newIndex > 0)
  40708. {
  40709. // if the previous column isn't draggable, we can't move our column
  40710. // past it, because that'd change the undraggable column's position..
  40711. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  40712. if ((previous->propertyFlags & draggable) != 0)
  40713. {
  40714. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  40715. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  40716. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  40717. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  40718. {
  40719. --newIndex;
  40720. }
  40721. }
  40722. }
  40723. if (newIndex < columns.size() - 1)
  40724. {
  40725. // if the next column isn't draggable, we can't move our column
  40726. // past it, because that'd change the undraggable column's position..
  40727. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  40728. if ((nextCol->propertyFlags & draggable) != 0)
  40729. {
  40730. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  40731. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  40732. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  40733. > abs (dragOverlayComp->getRight() - rightOfNext))
  40734. {
  40735. ++newIndex;
  40736. }
  40737. }
  40738. }
  40739. if (newIndex != currentIndex)
  40740. moveColumn (columnIdBeingDragged, newIndex);
  40741. else
  40742. break;
  40743. }
  40744. }
  40745. }
  40746. else
  40747. {
  40748. endDrag (draggingColumnOriginalIndex);
  40749. }
  40750. }
  40751. }
  40752. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  40753. {
  40754. if (columnIdBeingDragged == 0)
  40755. {
  40756. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  40757. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  40758. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  40759. {
  40760. columnIdBeingDragged = 0;
  40761. }
  40762. else
  40763. {
  40764. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  40765. const Rectangle<int> columnRect (getColumnPosition (draggingColumnOriginalIndex));
  40766. const int temp = columnIdBeingDragged;
  40767. columnIdBeingDragged = 0;
  40768. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  40769. columnIdBeingDragged = temp;
  40770. dragOverlayComp->setBounds (columnRect);
  40771. for (int i = listeners.size(); --i >= 0;)
  40772. {
  40773. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  40774. i = jmin (i, listeners.size() - 1);
  40775. }
  40776. }
  40777. }
  40778. }
  40779. void TableHeaderComponent::endDrag (const int finalIndex)
  40780. {
  40781. if (columnIdBeingDragged != 0)
  40782. {
  40783. moveColumn (columnIdBeingDragged, finalIndex);
  40784. columnIdBeingDragged = 0;
  40785. repaint();
  40786. for (int i = listeners.size(); --i >= 0;)
  40787. {
  40788. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  40789. i = jmin (i, listeners.size() - 1);
  40790. }
  40791. }
  40792. }
  40793. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  40794. {
  40795. mouseDrag (e);
  40796. for (int i = columns.size(); --i >= 0;)
  40797. if (columns.getUnchecked (i)->isVisible())
  40798. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  40799. columnIdBeingResized = 0;
  40800. repaint();
  40801. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  40802. updateColumnUnderMouse (e.x, e.y);
  40803. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  40804. columnClicked (columnIdUnderMouse, e.mods);
  40805. dragOverlayComp = 0;
  40806. }
  40807. const MouseCursor TableHeaderComponent::getMouseCursor()
  40808. {
  40809. if (columnIdBeingResized != 0 || (getResizeDraggerAt (getMouseXYRelative().getX()) != 0 && ! isMouseButtonDown()))
  40810. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  40811. return Component::getMouseCursor();
  40812. }
  40813. bool TableHeaderComponent::ColumnInfo::isVisible() const
  40814. {
  40815. return (propertyFlags & TableHeaderComponent::visible) != 0;
  40816. }
  40817. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const
  40818. {
  40819. for (int i = columns.size(); --i >= 0;)
  40820. if (columns.getUnchecked(i)->id == id)
  40821. return columns.getUnchecked(i);
  40822. return 0;
  40823. }
  40824. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const
  40825. {
  40826. int n = 0;
  40827. for (int i = 0; i < columns.size(); ++i)
  40828. {
  40829. if (columns.getUnchecked(i)->isVisible())
  40830. {
  40831. if (n == visibleIndex)
  40832. return i;
  40833. ++n;
  40834. }
  40835. }
  40836. return -1;
  40837. }
  40838. void TableHeaderComponent::sendColumnsChanged()
  40839. {
  40840. if (stretchToFit && lastDeliberateWidth > 0)
  40841. resizeAllColumnsToFit (lastDeliberateWidth);
  40842. repaint();
  40843. columnsChanged = true;
  40844. triggerAsyncUpdate();
  40845. }
  40846. void TableHeaderComponent::handleAsyncUpdate()
  40847. {
  40848. const bool changed = columnsChanged || sortChanged;
  40849. const bool sized = columnsResized || changed;
  40850. const bool sorted = sortChanged;
  40851. columnsChanged = false;
  40852. columnsResized = false;
  40853. sortChanged = false;
  40854. if (sorted)
  40855. {
  40856. for (int i = listeners.size(); --i >= 0;)
  40857. {
  40858. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  40859. i = jmin (i, listeners.size() - 1);
  40860. }
  40861. }
  40862. if (changed)
  40863. {
  40864. for (int i = listeners.size(); --i >= 0;)
  40865. {
  40866. listeners.getUnchecked(i)->tableColumnsChanged (this);
  40867. i = jmin (i, listeners.size() - 1);
  40868. }
  40869. }
  40870. if (sized)
  40871. {
  40872. for (int i = listeners.size(); --i >= 0;)
  40873. {
  40874. listeners.getUnchecked(i)->tableColumnsResized (this);
  40875. i = jmin (i, listeners.size() - 1);
  40876. }
  40877. }
  40878. }
  40879. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const
  40880. {
  40881. if (((unsigned int) mouseX) < (unsigned int) getWidth())
  40882. {
  40883. const int draggableDistance = 3;
  40884. int x = 0;
  40885. for (int i = 0; i < columns.size(); ++i)
  40886. {
  40887. const ColumnInfo* const ci = columns.getUnchecked(i);
  40888. if (ci->isVisible())
  40889. {
  40890. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  40891. && (ci->propertyFlags & resizable) != 0)
  40892. return ci->id;
  40893. x += ci->width;
  40894. }
  40895. }
  40896. }
  40897. return 0;
  40898. }
  40899. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  40900. {
  40901. const int newCol = (reallyContains (x, y, true) && getResizeDraggerAt (x) == 0)
  40902. ? getColumnIdAtX (x) : 0;
  40903. if (newCol != columnIdUnderMouse)
  40904. {
  40905. columnIdUnderMouse = newCol;
  40906. repaint();
  40907. }
  40908. }
  40909. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  40910. {
  40911. PopupMenu m;
  40912. addMenuItems (m, columnIdClicked);
  40913. if (m.getNumItems() > 0)
  40914. {
  40915. m.setLookAndFeel (&getLookAndFeel());
  40916. const int result = m.show();
  40917. if (result != 0)
  40918. reactToMenuItem (result, columnIdClicked);
  40919. }
  40920. }
  40921. void TableHeaderListener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  40922. {
  40923. }
  40924. END_JUCE_NAMESPACE
  40925. /*** End of inlined file: juce_TableHeaderComponent.cpp ***/
  40926. /*** Start of inlined file: juce_TableListBox.cpp ***/
  40927. BEGIN_JUCE_NAMESPACE
  40928. static const char* const tableColumnPropertyTag = "_tableColumnID";
  40929. class TableListRowComp : public Component,
  40930. public TooltipClient
  40931. {
  40932. public:
  40933. TableListRowComp (TableListBox& owner_)
  40934. : owner (owner_),
  40935. row (-1),
  40936. isSelected (false)
  40937. {
  40938. }
  40939. ~TableListRowComp()
  40940. {
  40941. deleteAllChildren();
  40942. }
  40943. void paint (Graphics& g)
  40944. {
  40945. TableListBoxModel* const model = owner.getModel();
  40946. if (model != 0)
  40947. {
  40948. const TableHeaderComponent* const header = owner.getHeader();
  40949. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  40950. const int numColumns = header->getNumColumns (true);
  40951. for (int i = 0; i < numColumns; ++i)
  40952. {
  40953. if (! columnsWithComponents [i])
  40954. {
  40955. const int columnId = header->getColumnIdOfIndex (i, true);
  40956. Rectangle<int> columnRect (header->getColumnPosition (i));
  40957. columnRect.setSize (columnRect.getWidth(), getHeight());
  40958. g.saveState();
  40959. g.reduceClipRegion (columnRect);
  40960. g.setOrigin (columnRect.getX(), 0);
  40961. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  40962. g.restoreState();
  40963. }
  40964. }
  40965. }
  40966. }
  40967. void update (const int newRow, const bool isNowSelected)
  40968. {
  40969. if (newRow != row || isNowSelected != isSelected)
  40970. {
  40971. row = newRow;
  40972. isSelected = isNowSelected;
  40973. repaint();
  40974. }
  40975. if (row < owner.getNumRows())
  40976. {
  40977. jassert (row >= 0);
  40978. const Identifier tagPropertyName ("_tableLastUseNum");
  40979. const int newTag = Random::getSystemRandom().nextInt();
  40980. const TableHeaderComponent* const header = owner.getHeader();
  40981. const int numColumns = header->getNumColumns (true);
  40982. int i;
  40983. columnsWithComponents.clear();
  40984. if (owner.getModel() != 0)
  40985. {
  40986. for (i = 0; i < numColumns; ++i)
  40987. {
  40988. const int columnId = header->getColumnIdOfIndex (i, true);
  40989. Component* const newComp
  40990. = owner.getModel()->refreshComponentForCell (row, columnId, isSelected,
  40991. findChildComponentForColumn (columnId));
  40992. if (newComp != 0)
  40993. {
  40994. addAndMakeVisible (newComp);
  40995. newComp->getProperties().set (tagPropertyName, newTag);
  40996. newComp->getProperties().set (tableColumnPropertyTag, columnId);
  40997. const Rectangle<int> columnRect (header->getColumnPosition (i));
  40998. newComp->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  40999. columnsWithComponents.setBit (i);
  41000. }
  41001. }
  41002. }
  41003. for (i = getNumChildComponents(); --i >= 0;)
  41004. {
  41005. Component* const c = getChildComponent (i);
  41006. if ((int) c->getProperties() [tagPropertyName] != newTag)
  41007. delete c;
  41008. }
  41009. }
  41010. else
  41011. {
  41012. columnsWithComponents.clear();
  41013. deleteAllChildren();
  41014. }
  41015. }
  41016. void resized()
  41017. {
  41018. for (int i = getNumChildComponents(); --i >= 0;)
  41019. {
  41020. Component* const c = getChildComponent (i);
  41021. const int columnId = c->getProperties() [tableColumnPropertyTag];
  41022. if (columnId != 0)
  41023. {
  41024. const Rectangle<int> columnRect (owner.getHeader()->getColumnPosition (owner.getHeader()->getIndexOfColumnId (columnId, true)));
  41025. c->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  41026. }
  41027. }
  41028. }
  41029. void mouseDown (const MouseEvent& e)
  41030. {
  41031. isDragging = false;
  41032. selectRowOnMouseUp = false;
  41033. if (isEnabled())
  41034. {
  41035. if (! isSelected)
  41036. {
  41037. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  41038. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  41039. if (columnId != 0 && owner.getModel() != 0)
  41040. owner.getModel()->cellClicked (row, columnId, e);
  41041. }
  41042. else
  41043. {
  41044. selectRowOnMouseUp = true;
  41045. }
  41046. }
  41047. }
  41048. void mouseDrag (const MouseEvent& e)
  41049. {
  41050. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  41051. {
  41052. const SparseSet<int> selectedRows (owner.getSelectedRows());
  41053. if (selectedRows.size() > 0)
  41054. {
  41055. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  41056. if (dragDescription.isNotEmpty())
  41057. {
  41058. isDragging = true;
  41059. owner.startDragAndDrop (e, dragDescription);
  41060. }
  41061. }
  41062. }
  41063. }
  41064. void mouseUp (const MouseEvent& e)
  41065. {
  41066. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  41067. {
  41068. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  41069. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  41070. if (columnId != 0 && owner.getModel() != 0)
  41071. owner.getModel()->cellClicked (row, columnId, e);
  41072. }
  41073. }
  41074. void mouseDoubleClick (const MouseEvent& e)
  41075. {
  41076. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  41077. if (columnId != 0 && owner.getModel() != 0)
  41078. owner.getModel()->cellDoubleClicked (row, columnId, e);
  41079. }
  41080. const String getTooltip()
  41081. {
  41082. const int columnId = owner.getHeader()->getColumnIdAtX (getMouseXYRelative().getX());
  41083. if (columnId != 0 && owner.getModel() != 0)
  41084. return owner.getModel()->getCellTooltip (row, columnId);
  41085. return String::empty;
  41086. }
  41087. juce_UseDebuggingNewOperator
  41088. private:
  41089. TableListBox& owner;
  41090. int row;
  41091. bool isSelected, isDragging, selectRowOnMouseUp;
  41092. BigInteger columnsWithComponents;
  41093. Component* findChildComponentForColumn (const int columnId) const
  41094. {
  41095. for (int i = getNumChildComponents(); --i >= 0;)
  41096. {
  41097. Component* const c = getChildComponent (i);
  41098. if ((int) c->getProperties() [tableColumnPropertyTag] == columnId)
  41099. return c;
  41100. }
  41101. return 0;
  41102. }
  41103. TableListRowComp (const TableListRowComp&);
  41104. TableListRowComp& operator= (const TableListRowComp&);
  41105. };
  41106. class TableListBoxHeader : public TableHeaderComponent
  41107. {
  41108. public:
  41109. TableListBoxHeader (TableListBox& owner_)
  41110. : owner (owner_)
  41111. {
  41112. }
  41113. ~TableListBoxHeader()
  41114. {
  41115. }
  41116. void addMenuItems (PopupMenu& menu, int columnIdClicked)
  41117. {
  41118. if (owner.isAutoSizeMenuOptionShown())
  41119. {
  41120. menu.addItem (0xf836743, TRANS("Auto-size this column"), columnIdClicked != 0);
  41121. menu.addItem (0xf836744, TRANS("Auto-size all columns"), owner.getHeader()->getNumColumns (true) > 0);
  41122. menu.addSeparator();
  41123. }
  41124. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  41125. }
  41126. void reactToMenuItem (int menuReturnId, int columnIdClicked)
  41127. {
  41128. if (menuReturnId == 0xf836743)
  41129. {
  41130. owner.autoSizeColumn (columnIdClicked);
  41131. }
  41132. else if (menuReturnId == 0xf836744)
  41133. {
  41134. owner.autoSizeAllColumns();
  41135. }
  41136. else
  41137. {
  41138. TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked);
  41139. }
  41140. }
  41141. juce_UseDebuggingNewOperator
  41142. private:
  41143. TableListBox& owner;
  41144. TableListBoxHeader (const TableListBoxHeader&);
  41145. TableListBoxHeader& operator= (const TableListBoxHeader&);
  41146. };
  41147. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  41148. : ListBox (name, 0),
  41149. model (model_),
  41150. autoSizeOptionsShown (true)
  41151. {
  41152. ListBox::model = this;
  41153. header = new TableListBoxHeader (*this);
  41154. header->setSize (100, 28);
  41155. header->addListener (this);
  41156. setHeaderComponent (header);
  41157. }
  41158. TableListBox::~TableListBox()
  41159. {
  41160. deleteAllChildren();
  41161. }
  41162. void TableListBox::setModel (TableListBoxModel* const newModel)
  41163. {
  41164. if (model != newModel)
  41165. {
  41166. model = newModel;
  41167. updateContent();
  41168. }
  41169. }
  41170. int TableListBox::getHeaderHeight() const
  41171. {
  41172. return header->getHeight();
  41173. }
  41174. void TableListBox::setHeaderHeight (const int newHeight)
  41175. {
  41176. header->setSize (header->getWidth(), newHeight);
  41177. resized();
  41178. }
  41179. void TableListBox::autoSizeColumn (const int columnId)
  41180. {
  41181. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  41182. if (width > 0)
  41183. header->setColumnWidth (columnId, width);
  41184. }
  41185. void TableListBox::autoSizeAllColumns()
  41186. {
  41187. for (int i = 0; i < header->getNumColumns (true); ++i)
  41188. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  41189. }
  41190. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  41191. {
  41192. autoSizeOptionsShown = shouldBeShown;
  41193. }
  41194. bool TableListBox::isAutoSizeMenuOptionShown() const
  41195. {
  41196. return autoSizeOptionsShown;
  41197. }
  41198. const Rectangle<int> TableListBox::getCellPosition (const int columnId,
  41199. const int rowNumber,
  41200. const bool relativeToComponentTopLeft) const
  41201. {
  41202. Rectangle<int> headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41203. if (relativeToComponentTopLeft)
  41204. headerCell.translate (header->getX(), 0);
  41205. const Rectangle<int> row (getRowPosition (rowNumber, relativeToComponentTopLeft));
  41206. return Rectangle<int> (headerCell.getX(), row.getY(),
  41207. headerCell.getWidth(), row.getHeight());
  41208. }
  41209. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  41210. {
  41211. ScrollBar* const scrollbar = getHorizontalScrollBar();
  41212. if (scrollbar != 0)
  41213. {
  41214. const Rectangle<int> pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41215. double x = scrollbar->getCurrentRangeStart();
  41216. const double w = scrollbar->getCurrentRangeSize();
  41217. if (pos.getX() < x)
  41218. x = pos.getX();
  41219. else if (pos.getRight() > x + w)
  41220. x += jmax (0.0, pos.getRight() - (x + w));
  41221. scrollbar->setCurrentRangeStart (x);
  41222. }
  41223. }
  41224. int TableListBox::getNumRows()
  41225. {
  41226. return model != 0 ? model->getNumRows() : 0;
  41227. }
  41228. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  41229. {
  41230. }
  41231. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected_, Component* existingComponentToUpdate)
  41232. {
  41233. if (existingComponentToUpdate == 0)
  41234. existingComponentToUpdate = new TableListRowComp (*this);
  41235. static_cast <TableListRowComp*> (existingComponentToUpdate)->update (rowNumber, isRowSelected_);
  41236. return existingComponentToUpdate;
  41237. }
  41238. void TableListBox::selectedRowsChanged (int row)
  41239. {
  41240. if (model != 0)
  41241. model->selectedRowsChanged (row);
  41242. }
  41243. void TableListBox::deleteKeyPressed (int row)
  41244. {
  41245. if (model != 0)
  41246. model->deleteKeyPressed (row);
  41247. }
  41248. void TableListBox::returnKeyPressed (int row)
  41249. {
  41250. if (model != 0)
  41251. model->returnKeyPressed (row);
  41252. }
  41253. void TableListBox::backgroundClicked()
  41254. {
  41255. if (model != 0)
  41256. model->backgroundClicked();
  41257. }
  41258. void TableListBox::listWasScrolled()
  41259. {
  41260. if (model != 0)
  41261. model->listWasScrolled();
  41262. }
  41263. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  41264. {
  41265. setMinimumContentWidth (header->getTotalWidth());
  41266. repaint();
  41267. updateColumnComponents();
  41268. }
  41269. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  41270. {
  41271. setMinimumContentWidth (header->getTotalWidth());
  41272. repaint();
  41273. updateColumnComponents();
  41274. }
  41275. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  41276. {
  41277. if (model != 0)
  41278. model->sortOrderChanged (header->getSortColumnId(),
  41279. header->isSortedForwards());
  41280. }
  41281. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  41282. {
  41283. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  41284. repaint();
  41285. }
  41286. void TableListBox::resized()
  41287. {
  41288. ListBox::resized();
  41289. header->resizeAllColumnsToFit (getVisibleContentWidth());
  41290. setMinimumContentWidth (header->getTotalWidth());
  41291. }
  41292. void TableListBox::updateColumnComponents() const
  41293. {
  41294. const int firstRow = getRowContainingPosition (0, 0);
  41295. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  41296. {
  41297. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  41298. if (rowComp != 0)
  41299. rowComp->resized();
  41300. }
  41301. }
  41302. void TableListBoxModel::cellClicked (int, int, const MouseEvent&)
  41303. {
  41304. }
  41305. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&)
  41306. {
  41307. }
  41308. void TableListBoxModel::backgroundClicked()
  41309. {
  41310. }
  41311. void TableListBoxModel::sortOrderChanged (int, const bool)
  41312. {
  41313. }
  41314. int TableListBoxModel::getColumnAutoSizeWidth (int)
  41315. {
  41316. return 0;
  41317. }
  41318. void TableListBoxModel::selectedRowsChanged (int)
  41319. {
  41320. }
  41321. void TableListBoxModel::deleteKeyPressed (int)
  41322. {
  41323. }
  41324. void TableListBoxModel::returnKeyPressed (int)
  41325. {
  41326. }
  41327. void TableListBoxModel::listWasScrolled()
  41328. {
  41329. }
  41330. const String TableListBoxModel::getCellTooltip (int /*rowNumber*/, int /*columnId*/)
  41331. {
  41332. return String::empty;
  41333. }
  41334. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  41335. {
  41336. return String::empty;
  41337. }
  41338. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  41339. {
  41340. (void) existingComponentToUpdate;
  41341. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  41342. return 0;
  41343. }
  41344. END_JUCE_NAMESPACE
  41345. /*** End of inlined file: juce_TableListBox.cpp ***/
  41346. /*** Start of inlined file: juce_TextEditor.cpp ***/
  41347. BEGIN_JUCE_NAMESPACE
  41348. // a word or space that can't be broken down any further
  41349. struct TextAtom
  41350. {
  41351. String atomText;
  41352. float width;
  41353. uint16 numChars;
  41354. bool isWhitespace() const { return CharacterFunctions::isWhitespace (atomText[0]); }
  41355. bool isNewLine() const { return atomText[0] == '\r' || atomText[0] == '\n'; }
  41356. const String getText (const juce_wchar passwordCharacter) const
  41357. {
  41358. if (passwordCharacter == 0)
  41359. return atomText;
  41360. else
  41361. return String::repeatedString (String::charToString (passwordCharacter),
  41362. atomText.length());
  41363. }
  41364. const String getTrimmedText (const juce_wchar passwordCharacter) const
  41365. {
  41366. if (passwordCharacter == 0)
  41367. return atomText.substring (0, numChars);
  41368. else if (isNewLine())
  41369. return String::empty;
  41370. else
  41371. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  41372. }
  41373. };
  41374. // a run of text with a single font and colour
  41375. class TextEditor::UniformTextSection
  41376. {
  41377. public:
  41378. UniformTextSection (const String& text,
  41379. const Font& font_,
  41380. const Colour& colour_,
  41381. const juce_wchar passwordCharacter)
  41382. : font (font_),
  41383. colour (colour_)
  41384. {
  41385. initialiseAtoms (text, passwordCharacter);
  41386. }
  41387. UniformTextSection (const UniformTextSection& other)
  41388. : font (other.font),
  41389. colour (other.colour)
  41390. {
  41391. atoms.ensureStorageAllocated (other.atoms.size());
  41392. for (int i = 0; i < other.atoms.size(); ++i)
  41393. atoms.add (new TextAtom (*other.atoms.getUnchecked(i)));
  41394. }
  41395. ~UniformTextSection()
  41396. {
  41397. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  41398. }
  41399. void clear()
  41400. {
  41401. for (int i = atoms.size(); --i >= 0;)
  41402. delete getAtom(i);
  41403. atoms.clear();
  41404. }
  41405. int getNumAtoms() const
  41406. {
  41407. return atoms.size();
  41408. }
  41409. TextAtom* getAtom (const int index) const throw()
  41410. {
  41411. return atoms.getUnchecked (index);
  41412. }
  41413. void append (const UniformTextSection& other, const juce_wchar passwordCharacter)
  41414. {
  41415. if (other.atoms.size() > 0)
  41416. {
  41417. TextAtom* const lastAtom = atoms.getLast();
  41418. int i = 0;
  41419. if (lastAtom != 0)
  41420. {
  41421. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  41422. {
  41423. TextAtom* const first = other.getAtom(0);
  41424. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  41425. {
  41426. lastAtom->atomText += first->atomText;
  41427. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  41428. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  41429. delete first;
  41430. ++i;
  41431. }
  41432. }
  41433. }
  41434. atoms.ensureStorageAllocated (atoms.size() + other.atoms.size() - i);
  41435. while (i < other.atoms.size())
  41436. {
  41437. atoms.add (other.getAtom(i));
  41438. ++i;
  41439. }
  41440. }
  41441. }
  41442. UniformTextSection* split (const int indexToBreakAt,
  41443. const juce_wchar passwordCharacter)
  41444. {
  41445. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  41446. font, colour,
  41447. passwordCharacter);
  41448. int index = 0;
  41449. for (int i = 0; i < atoms.size(); ++i)
  41450. {
  41451. TextAtom* const atom = getAtom(i);
  41452. const int nextIndex = index + atom->numChars;
  41453. if (index == indexToBreakAt)
  41454. {
  41455. int j;
  41456. for (j = i; j < atoms.size(); ++j)
  41457. section2->atoms.add (getAtom (j));
  41458. for (j = atoms.size(); --j >= i;)
  41459. atoms.remove (j);
  41460. break;
  41461. }
  41462. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  41463. {
  41464. TextAtom* const secondAtom = new TextAtom();
  41465. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  41466. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  41467. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  41468. section2->atoms.add (secondAtom);
  41469. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  41470. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  41471. atom->numChars = (uint16) (indexToBreakAt - index);
  41472. int j;
  41473. for (j = i + 1; j < atoms.size(); ++j)
  41474. section2->atoms.add (getAtom (j));
  41475. for (j = atoms.size(); --j > i;)
  41476. atoms.remove (j);
  41477. break;
  41478. }
  41479. index = nextIndex;
  41480. }
  41481. return section2;
  41482. }
  41483. void appendAllText (String::Concatenator& concatenator) const
  41484. {
  41485. for (int i = 0; i < atoms.size(); ++i)
  41486. concatenator.append (getAtom(i)->atomText);
  41487. }
  41488. void appendSubstring (String::Concatenator& concatenator,
  41489. const Range<int>& range) const
  41490. {
  41491. int index = 0;
  41492. for (int i = 0; i < atoms.size(); ++i)
  41493. {
  41494. const TextAtom* const atom = getAtom (i);
  41495. const int nextIndex = index + atom->numChars;
  41496. if (range.getStart() < nextIndex)
  41497. {
  41498. if (range.getEnd() <= index)
  41499. break;
  41500. const Range<int> r ((range - index).getIntersectionWith (Range<int> (0, (int) atom->numChars)));
  41501. if (! r.isEmpty())
  41502. concatenator.append (atom->atomText.substring (r.getStart(), r.getEnd()));
  41503. }
  41504. index = nextIndex;
  41505. }
  41506. }
  41507. int getTotalLength() const
  41508. {
  41509. int total = 0;
  41510. for (int i = atoms.size(); --i >= 0;)
  41511. total += getAtom(i)->numChars;
  41512. return total;
  41513. }
  41514. void setFont (const Font& newFont,
  41515. const juce_wchar passwordCharacter)
  41516. {
  41517. if (font != newFont)
  41518. {
  41519. font = newFont;
  41520. for (int i = atoms.size(); --i >= 0;)
  41521. {
  41522. TextAtom* const atom = atoms.getUnchecked(i);
  41523. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  41524. }
  41525. }
  41526. }
  41527. juce_UseDebuggingNewOperator
  41528. Font font;
  41529. Colour colour;
  41530. private:
  41531. Array <TextAtom*> atoms;
  41532. void initialiseAtoms (const String& textToParse,
  41533. const juce_wchar passwordCharacter)
  41534. {
  41535. int i = 0;
  41536. const int len = textToParse.length();
  41537. const juce_wchar* const text = textToParse;
  41538. while (i < len)
  41539. {
  41540. int start = i;
  41541. // create a whitespace atom unless it starts with non-ws
  41542. if (CharacterFunctions::isWhitespace (text[i])
  41543. && text[i] != '\r'
  41544. && text[i] != '\n')
  41545. {
  41546. while (i < len
  41547. && CharacterFunctions::isWhitespace (text[i])
  41548. && text[i] != '\r'
  41549. && text[i] != '\n')
  41550. {
  41551. ++i;
  41552. }
  41553. }
  41554. else
  41555. {
  41556. if (text[i] == '\r')
  41557. {
  41558. ++i;
  41559. if ((i < len) && (text[i] == '\n'))
  41560. {
  41561. ++start;
  41562. ++i;
  41563. }
  41564. }
  41565. else if (text[i] == '\n')
  41566. {
  41567. ++i;
  41568. }
  41569. else
  41570. {
  41571. while ((i < len) && ! CharacterFunctions::isWhitespace (text[i]))
  41572. ++i;
  41573. }
  41574. }
  41575. TextAtom* const atom = new TextAtom();
  41576. atom->atomText = String (text + start, i - start);
  41577. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  41578. atom->numChars = (uint16) (i - start);
  41579. atoms.add (atom);
  41580. }
  41581. }
  41582. UniformTextSection& operator= (const UniformTextSection& other);
  41583. };
  41584. class TextEditor::Iterator
  41585. {
  41586. public:
  41587. Iterator (const Array <UniformTextSection*>& sections_,
  41588. const float wordWrapWidth_,
  41589. const juce_wchar passwordCharacter_)
  41590. : indexInText (0),
  41591. lineY (0),
  41592. lineHeight (0),
  41593. maxDescent (0),
  41594. atomX (0),
  41595. atomRight (0),
  41596. atom (0),
  41597. currentSection (0),
  41598. sections (sections_),
  41599. sectionIndex (0),
  41600. atomIndex (0),
  41601. wordWrapWidth (wordWrapWidth_),
  41602. passwordCharacter (passwordCharacter_)
  41603. {
  41604. jassert (wordWrapWidth_ > 0);
  41605. if (sections.size() > 0)
  41606. {
  41607. currentSection = sections.getUnchecked (sectionIndex);
  41608. if (currentSection != 0)
  41609. beginNewLine();
  41610. }
  41611. }
  41612. Iterator (const Iterator& other)
  41613. : indexInText (other.indexInText),
  41614. lineY (other.lineY),
  41615. lineHeight (other.lineHeight),
  41616. maxDescent (other.maxDescent),
  41617. atomX (other.atomX),
  41618. atomRight (other.atomRight),
  41619. atom (other.atom),
  41620. currentSection (other.currentSection),
  41621. sections (other.sections),
  41622. sectionIndex (other.sectionIndex),
  41623. atomIndex (other.atomIndex),
  41624. wordWrapWidth (other.wordWrapWidth),
  41625. passwordCharacter (other.passwordCharacter),
  41626. tempAtom (other.tempAtom)
  41627. {
  41628. }
  41629. ~Iterator()
  41630. {
  41631. }
  41632. bool next()
  41633. {
  41634. if (atom == &tempAtom)
  41635. {
  41636. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  41637. if (numRemaining > 0)
  41638. {
  41639. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  41640. atomX = 0;
  41641. if (tempAtom.numChars > 0)
  41642. lineY += lineHeight;
  41643. indexInText += tempAtom.numChars;
  41644. GlyphArrangement g;
  41645. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  41646. int split;
  41647. for (split = 0; split < g.getNumGlyphs(); ++split)
  41648. if (shouldWrap (g.getGlyph (split).getRight()))
  41649. break;
  41650. if (split > 0 && split <= numRemaining)
  41651. {
  41652. tempAtom.numChars = (uint16) split;
  41653. tempAtom.width = g.getGlyph (split - 1).getRight();
  41654. atomRight = atomX + tempAtom.width;
  41655. return true;
  41656. }
  41657. }
  41658. }
  41659. bool forceNewLine = false;
  41660. if (sectionIndex >= sections.size())
  41661. {
  41662. moveToEndOfLastAtom();
  41663. return false;
  41664. }
  41665. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  41666. {
  41667. if (atomIndex >= currentSection->getNumAtoms())
  41668. {
  41669. if (++sectionIndex >= sections.size())
  41670. {
  41671. moveToEndOfLastAtom();
  41672. return false;
  41673. }
  41674. atomIndex = 0;
  41675. currentSection = sections.getUnchecked (sectionIndex);
  41676. }
  41677. else
  41678. {
  41679. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  41680. if (! lastAtom->isWhitespace())
  41681. {
  41682. // handle the case where the last atom in a section is actually part of the same
  41683. // word as the first atom of the next section...
  41684. float right = atomRight + lastAtom->width;
  41685. float lineHeight2 = lineHeight;
  41686. float maxDescent2 = maxDescent;
  41687. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  41688. {
  41689. const UniformTextSection* const s = sections.getUnchecked (section);
  41690. if (s->getNumAtoms() == 0)
  41691. break;
  41692. const TextAtom* const nextAtom = s->getAtom (0);
  41693. if (nextAtom->isWhitespace())
  41694. break;
  41695. right += nextAtom->width;
  41696. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  41697. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  41698. if (shouldWrap (right))
  41699. {
  41700. lineHeight = lineHeight2;
  41701. maxDescent = maxDescent2;
  41702. forceNewLine = true;
  41703. break;
  41704. }
  41705. if (s->getNumAtoms() > 1)
  41706. break;
  41707. }
  41708. }
  41709. }
  41710. }
  41711. if (atom != 0)
  41712. {
  41713. atomX = atomRight;
  41714. indexInText += atom->numChars;
  41715. if (atom->isNewLine())
  41716. beginNewLine();
  41717. }
  41718. atom = currentSection->getAtom (atomIndex);
  41719. atomRight = atomX + atom->width;
  41720. ++atomIndex;
  41721. if (shouldWrap (atomRight) || forceNewLine)
  41722. {
  41723. if (atom->isWhitespace())
  41724. {
  41725. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  41726. atomRight = jmin (atomRight, wordWrapWidth);
  41727. }
  41728. else
  41729. {
  41730. atomRight = atom->width;
  41731. if (shouldWrap (atomRight)) // atom too big to fit on a line, so break it up..
  41732. {
  41733. tempAtom = *atom;
  41734. tempAtom.width = 0;
  41735. tempAtom.numChars = 0;
  41736. atom = &tempAtom;
  41737. if (atomX > 0)
  41738. beginNewLine();
  41739. return next();
  41740. }
  41741. beginNewLine();
  41742. return true;
  41743. }
  41744. }
  41745. return true;
  41746. }
  41747. void beginNewLine()
  41748. {
  41749. atomX = 0;
  41750. lineY += lineHeight;
  41751. int tempSectionIndex = sectionIndex;
  41752. int tempAtomIndex = atomIndex;
  41753. const UniformTextSection* section = sections.getUnchecked (tempSectionIndex);
  41754. lineHeight = section->font.getHeight();
  41755. maxDescent = section->font.getDescent();
  41756. float x = (atom != 0) ? atom->width : 0;
  41757. while (! shouldWrap (x))
  41758. {
  41759. if (tempSectionIndex >= sections.size())
  41760. break;
  41761. bool checkSize = false;
  41762. if (tempAtomIndex >= section->getNumAtoms())
  41763. {
  41764. if (++tempSectionIndex >= sections.size())
  41765. break;
  41766. tempAtomIndex = 0;
  41767. section = sections.getUnchecked (tempSectionIndex);
  41768. checkSize = true;
  41769. }
  41770. const TextAtom* const nextAtom = section->getAtom (tempAtomIndex);
  41771. if (nextAtom == 0)
  41772. break;
  41773. x += nextAtom->width;
  41774. if (shouldWrap (x) || nextAtom->isNewLine())
  41775. break;
  41776. if (checkSize)
  41777. {
  41778. lineHeight = jmax (lineHeight, section->font.getHeight());
  41779. maxDescent = jmax (maxDescent, section->font.getDescent());
  41780. }
  41781. ++tempAtomIndex;
  41782. }
  41783. }
  41784. void draw (Graphics& g, const UniformTextSection*& lastSection) const
  41785. {
  41786. if (passwordCharacter != 0 || ! atom->isWhitespace())
  41787. {
  41788. if (lastSection != currentSection)
  41789. {
  41790. lastSection = currentSection;
  41791. g.setColour (currentSection->colour);
  41792. g.setFont (currentSection->font);
  41793. }
  41794. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  41795. GlyphArrangement ga;
  41796. ga.addLineOfText (currentSection->font,
  41797. atom->getTrimmedText (passwordCharacter),
  41798. atomX,
  41799. (float) roundToInt (lineY + lineHeight - maxDescent));
  41800. ga.draw (g);
  41801. }
  41802. }
  41803. void drawSelection (Graphics& g,
  41804. const Range<int>& selection) const
  41805. {
  41806. const int startX = roundToInt (indexToX (selection.getStart()));
  41807. const int endX = roundToInt (indexToX (selection.getEnd()));
  41808. const int y = roundToInt (lineY);
  41809. const int nextY = roundToInt (lineY + lineHeight);
  41810. g.fillRect (startX, y, endX - startX, nextY - y);
  41811. }
  41812. void drawSelectedText (Graphics& g,
  41813. const Range<int>& selection,
  41814. const Colour& selectedTextColour) const
  41815. {
  41816. if (passwordCharacter != 0 || ! atom->isWhitespace())
  41817. {
  41818. GlyphArrangement ga;
  41819. ga.addLineOfText (currentSection->font,
  41820. atom->getTrimmedText (passwordCharacter),
  41821. atomX,
  41822. (float) roundToInt (lineY + lineHeight - maxDescent));
  41823. if (selection.getEnd() < indexInText + atom->numChars)
  41824. {
  41825. GlyphArrangement ga2 (ga);
  41826. ga2.removeRangeOfGlyphs (0, selection.getEnd() - indexInText);
  41827. ga.removeRangeOfGlyphs (selection.getEnd() - indexInText, -1);
  41828. g.setColour (currentSection->colour);
  41829. ga2.draw (g);
  41830. }
  41831. if (selection.getStart() > indexInText)
  41832. {
  41833. GlyphArrangement ga2 (ga);
  41834. ga2.removeRangeOfGlyphs (selection.getStart() - indexInText, -1);
  41835. ga.removeRangeOfGlyphs (0, selection.getStart() - indexInText);
  41836. g.setColour (currentSection->colour);
  41837. ga2.draw (g);
  41838. }
  41839. g.setColour (selectedTextColour);
  41840. ga.draw (g);
  41841. }
  41842. }
  41843. float indexToX (const int indexToFind) const
  41844. {
  41845. if (indexToFind <= indexInText)
  41846. return atomX;
  41847. if (indexToFind >= indexInText + atom->numChars)
  41848. return atomRight;
  41849. GlyphArrangement g;
  41850. g.addLineOfText (currentSection->font,
  41851. atom->getText (passwordCharacter),
  41852. atomX, 0.0f);
  41853. if (indexToFind - indexInText >= g.getNumGlyphs())
  41854. return atomRight;
  41855. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  41856. }
  41857. int xToIndex (const float xToFind) const
  41858. {
  41859. if (xToFind <= atomX || atom->isNewLine())
  41860. return indexInText;
  41861. if (xToFind >= atomRight)
  41862. return indexInText + atom->numChars;
  41863. GlyphArrangement g;
  41864. g.addLineOfText (currentSection->font,
  41865. atom->getText (passwordCharacter),
  41866. atomX, 0.0f);
  41867. int j;
  41868. for (j = 0; j < g.getNumGlyphs(); ++j)
  41869. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  41870. break;
  41871. return indexInText + j;
  41872. }
  41873. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_)
  41874. {
  41875. while (next())
  41876. {
  41877. if (indexInText + atom->numChars > index)
  41878. {
  41879. cx = indexToX (index);
  41880. cy = lineY;
  41881. lineHeight_ = lineHeight;
  41882. return true;
  41883. }
  41884. }
  41885. cx = atomX;
  41886. cy = lineY;
  41887. lineHeight_ = lineHeight;
  41888. return false;
  41889. }
  41890. juce_UseDebuggingNewOperator
  41891. int indexInText;
  41892. float lineY, lineHeight, maxDescent;
  41893. float atomX, atomRight;
  41894. const TextAtom* atom;
  41895. const UniformTextSection* currentSection;
  41896. private:
  41897. const Array <UniformTextSection*>& sections;
  41898. int sectionIndex, atomIndex;
  41899. const float wordWrapWidth;
  41900. const juce_wchar passwordCharacter;
  41901. TextAtom tempAtom;
  41902. Iterator& operator= (const Iterator&);
  41903. void moveToEndOfLastAtom()
  41904. {
  41905. if (atom != 0)
  41906. {
  41907. atomX = atomRight;
  41908. if (atom->isNewLine())
  41909. {
  41910. atomX = 0.0f;
  41911. lineY += lineHeight;
  41912. }
  41913. }
  41914. }
  41915. bool shouldWrap (const float x) const
  41916. {
  41917. return (x - 0.0001f) >= wordWrapWidth;
  41918. }
  41919. };
  41920. class TextEditor::InsertAction : public UndoableAction
  41921. {
  41922. TextEditor& owner;
  41923. const String text;
  41924. const int insertIndex, oldCaretPos, newCaretPos;
  41925. const Font font;
  41926. const Colour colour;
  41927. InsertAction (const InsertAction&);
  41928. InsertAction& operator= (const InsertAction&);
  41929. public:
  41930. InsertAction (TextEditor& owner_,
  41931. const String& text_,
  41932. const int insertIndex_,
  41933. const Font& font_,
  41934. const Colour& colour_,
  41935. const int oldCaretPos_,
  41936. const int newCaretPos_)
  41937. : owner (owner_),
  41938. text (text_),
  41939. insertIndex (insertIndex_),
  41940. oldCaretPos (oldCaretPos_),
  41941. newCaretPos (newCaretPos_),
  41942. font (font_),
  41943. colour (colour_)
  41944. {
  41945. }
  41946. ~InsertAction()
  41947. {
  41948. }
  41949. bool perform()
  41950. {
  41951. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  41952. return true;
  41953. }
  41954. bool undo()
  41955. {
  41956. owner.remove (Range<int> (insertIndex, insertIndex + text.length()), 0, oldCaretPos);
  41957. return true;
  41958. }
  41959. int getSizeInUnits()
  41960. {
  41961. return text.length() + 16;
  41962. }
  41963. };
  41964. class TextEditor::RemoveAction : public UndoableAction
  41965. {
  41966. TextEditor& owner;
  41967. const Range<int> range;
  41968. const int oldCaretPos, newCaretPos;
  41969. Array <UniformTextSection*> removedSections;
  41970. RemoveAction (const RemoveAction&);
  41971. RemoveAction& operator= (const RemoveAction&);
  41972. public:
  41973. RemoveAction (TextEditor& owner_,
  41974. const Range<int> range_,
  41975. const int oldCaretPos_,
  41976. const int newCaretPos_,
  41977. const Array <UniformTextSection*>& removedSections_)
  41978. : owner (owner_),
  41979. range (range_),
  41980. oldCaretPos (oldCaretPos_),
  41981. newCaretPos (newCaretPos_),
  41982. removedSections (removedSections_)
  41983. {
  41984. }
  41985. ~RemoveAction()
  41986. {
  41987. for (int i = removedSections.size(); --i >= 0;)
  41988. {
  41989. UniformTextSection* const section = removedSections.getUnchecked (i);
  41990. section->clear();
  41991. delete section;
  41992. }
  41993. }
  41994. bool perform()
  41995. {
  41996. owner.remove (range, 0, newCaretPos);
  41997. return true;
  41998. }
  41999. bool undo()
  42000. {
  42001. owner.reinsert (range.getStart(), removedSections);
  42002. owner.moveCursorTo (oldCaretPos, false);
  42003. return true;
  42004. }
  42005. int getSizeInUnits()
  42006. {
  42007. int n = 0;
  42008. for (int i = removedSections.size(); --i >= 0;)
  42009. n += removedSections.getUnchecked (i)->getTotalLength();
  42010. return n + 16;
  42011. }
  42012. };
  42013. class TextEditor::TextHolderComponent : public Component,
  42014. public Timer,
  42015. public Value::Listener
  42016. {
  42017. public:
  42018. TextHolderComponent (TextEditor& owner_)
  42019. : owner (owner_)
  42020. {
  42021. setWantsKeyboardFocus (false);
  42022. setInterceptsMouseClicks (false, true);
  42023. owner.getTextValue().addListener (this);
  42024. }
  42025. ~TextHolderComponent()
  42026. {
  42027. owner.getTextValue().removeListener (this);
  42028. }
  42029. void paint (Graphics& g)
  42030. {
  42031. owner.drawContent (g);
  42032. }
  42033. void timerCallback()
  42034. {
  42035. owner.timerCallbackInt();
  42036. }
  42037. const MouseCursor getMouseCursor()
  42038. {
  42039. return owner.getMouseCursor();
  42040. }
  42041. void valueChanged (Value&)
  42042. {
  42043. owner.textWasChangedByValue();
  42044. }
  42045. private:
  42046. TextEditor& owner;
  42047. TextHolderComponent (const TextHolderComponent&);
  42048. TextHolderComponent& operator= (const TextHolderComponent&);
  42049. };
  42050. class TextEditorViewport : public Viewport
  42051. {
  42052. public:
  42053. TextEditorViewport (TextEditor* const owner_)
  42054. : owner (owner_), lastWordWrapWidth (0), rentrant (false)
  42055. {
  42056. }
  42057. ~TextEditorViewport()
  42058. {
  42059. }
  42060. void visibleAreaChanged (int, int, int, int)
  42061. {
  42062. if (! rentrant) // it's rare, but possible to get into a feedback loop as the viewport's scrollbars
  42063. // appear and disappear, causing the wrap width to change.
  42064. {
  42065. const float wordWrapWidth = owner->getWordWrapWidth();
  42066. if (wordWrapWidth != lastWordWrapWidth)
  42067. {
  42068. lastWordWrapWidth = wordWrapWidth;
  42069. rentrant = true;
  42070. owner->updateTextHolderSize();
  42071. rentrant = false;
  42072. }
  42073. }
  42074. }
  42075. private:
  42076. TextEditor* const owner;
  42077. float lastWordWrapWidth;
  42078. bool rentrant;
  42079. TextEditorViewport (const TextEditorViewport&);
  42080. TextEditorViewport& operator= (const TextEditorViewport&);
  42081. };
  42082. namespace TextEditorDefs
  42083. {
  42084. const int flashSpeedIntervalMs = 380;
  42085. const int textChangeMessageId = 0x10003001;
  42086. const int returnKeyMessageId = 0x10003002;
  42087. const int escapeKeyMessageId = 0x10003003;
  42088. const int focusLossMessageId = 0x10003004;
  42089. const int maxActionsPerTransaction = 100;
  42090. }
  42091. TextEditor::TextEditor (const String& name,
  42092. const juce_wchar passwordCharacter_)
  42093. : Component (name),
  42094. borderSize (1, 1, 1, 3),
  42095. readOnly (false),
  42096. multiline (false),
  42097. wordWrap (false),
  42098. returnKeyStartsNewLine (false),
  42099. caretVisible (true),
  42100. popupMenuEnabled (true),
  42101. selectAllTextWhenFocused (false),
  42102. scrollbarVisible (true),
  42103. wasFocused (false),
  42104. caretFlashState (true),
  42105. keepCursorOnScreen (true),
  42106. tabKeyUsed (false),
  42107. menuActive (false),
  42108. valueTextNeedsUpdating (false),
  42109. cursorX (0),
  42110. cursorY (0),
  42111. cursorHeight (0),
  42112. maxTextLength (0),
  42113. leftIndent (4),
  42114. topIndent (4),
  42115. lastTransactionTime (0),
  42116. currentFont (14.0f),
  42117. totalNumChars (0),
  42118. caretPosition (0),
  42119. passwordCharacter (passwordCharacter_),
  42120. dragType (notDragging)
  42121. {
  42122. setOpaque (true);
  42123. addAndMakeVisible (viewport = new TextEditorViewport (this));
  42124. viewport->setViewedComponent (textHolder = new TextHolderComponent (*this));
  42125. viewport->setWantsKeyboardFocus (false);
  42126. viewport->setScrollBarsShown (false, false);
  42127. setMouseCursor (MouseCursor::IBeamCursor);
  42128. setWantsKeyboardFocus (true);
  42129. }
  42130. TextEditor::~TextEditor()
  42131. {
  42132. textValue.referTo (Value());
  42133. clearInternal (0);
  42134. viewport = 0;
  42135. textHolder = 0;
  42136. }
  42137. void TextEditor::newTransaction()
  42138. {
  42139. lastTransactionTime = Time::getApproximateMillisecondCounter();
  42140. undoManager.beginNewTransaction();
  42141. }
  42142. void TextEditor::doUndoRedo (const bool isRedo)
  42143. {
  42144. if (! isReadOnly())
  42145. {
  42146. if (isRedo ? undoManager.redo()
  42147. : undoManager.undo())
  42148. {
  42149. scrollToMakeSureCursorIsVisible();
  42150. repaint();
  42151. textChanged();
  42152. }
  42153. }
  42154. }
  42155. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  42156. const bool shouldWordWrap)
  42157. {
  42158. if (multiline != shouldBeMultiLine
  42159. || wordWrap != (shouldWordWrap && shouldBeMultiLine))
  42160. {
  42161. multiline = shouldBeMultiLine;
  42162. wordWrap = shouldWordWrap && shouldBeMultiLine;
  42163. viewport->setScrollBarsShown (scrollbarVisible && multiline,
  42164. scrollbarVisible && multiline);
  42165. viewport->setViewPosition (0, 0);
  42166. resized();
  42167. scrollToMakeSureCursorIsVisible();
  42168. }
  42169. }
  42170. bool TextEditor::isMultiLine() const
  42171. {
  42172. return multiline;
  42173. }
  42174. void TextEditor::setScrollbarsShown (bool shown)
  42175. {
  42176. if (scrollbarVisible != shown)
  42177. {
  42178. scrollbarVisible = shown;
  42179. shown = shown && isMultiLine();
  42180. viewport->setScrollBarsShown (shown, shown);
  42181. }
  42182. }
  42183. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  42184. {
  42185. if (readOnly != shouldBeReadOnly)
  42186. {
  42187. readOnly = shouldBeReadOnly;
  42188. enablementChanged();
  42189. }
  42190. }
  42191. bool TextEditor::isReadOnly() const
  42192. {
  42193. return readOnly || ! isEnabled();
  42194. }
  42195. bool TextEditor::isTextInputActive() const
  42196. {
  42197. return ! isReadOnly();
  42198. }
  42199. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  42200. {
  42201. returnKeyStartsNewLine = shouldStartNewLine;
  42202. }
  42203. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed)
  42204. {
  42205. tabKeyUsed = shouldTabKeyBeUsed;
  42206. }
  42207. void TextEditor::setPopupMenuEnabled (const bool b)
  42208. {
  42209. popupMenuEnabled = b;
  42210. }
  42211. void TextEditor::setSelectAllWhenFocused (const bool b)
  42212. {
  42213. selectAllTextWhenFocused = b;
  42214. }
  42215. const Font TextEditor::getFont() const
  42216. {
  42217. return currentFont;
  42218. }
  42219. void TextEditor::setFont (const Font& newFont)
  42220. {
  42221. currentFont = newFont;
  42222. scrollToMakeSureCursorIsVisible();
  42223. }
  42224. void TextEditor::applyFontToAllText (const Font& newFont)
  42225. {
  42226. currentFont = newFont;
  42227. const Colour overallColour (findColour (textColourId));
  42228. for (int i = sections.size(); --i >= 0;)
  42229. {
  42230. UniformTextSection* const uts = sections.getUnchecked (i);
  42231. uts->setFont (newFont, passwordCharacter);
  42232. uts->colour = overallColour;
  42233. }
  42234. coalesceSimilarSections();
  42235. updateTextHolderSize();
  42236. scrollToMakeSureCursorIsVisible();
  42237. repaint();
  42238. }
  42239. void TextEditor::colourChanged()
  42240. {
  42241. setOpaque (findColour (backgroundColourId).isOpaque());
  42242. repaint();
  42243. }
  42244. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible)
  42245. {
  42246. caretVisible = shouldCaretBeVisible;
  42247. if (shouldCaretBeVisible)
  42248. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42249. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  42250. : MouseCursor::NormalCursor);
  42251. }
  42252. void TextEditor::setInputRestrictions (const int maxLen,
  42253. const String& chars)
  42254. {
  42255. maxTextLength = jmax (0, maxLen);
  42256. allowedCharacters = chars;
  42257. }
  42258. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse)
  42259. {
  42260. textToShowWhenEmpty = text;
  42261. colourForTextWhenEmpty = colourToUse;
  42262. }
  42263. void TextEditor::setPasswordCharacter (const juce_wchar newPasswordCharacter)
  42264. {
  42265. if (passwordCharacter != newPasswordCharacter)
  42266. {
  42267. passwordCharacter = newPasswordCharacter;
  42268. resized();
  42269. repaint();
  42270. }
  42271. }
  42272. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  42273. {
  42274. viewport->setScrollBarThickness (newThicknessPixels);
  42275. }
  42276. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  42277. {
  42278. viewport->setScrollBarButtonVisibility (buttonsVisible);
  42279. }
  42280. void TextEditor::clear()
  42281. {
  42282. clearInternal (0);
  42283. updateTextHolderSize();
  42284. undoManager.clearUndoHistory();
  42285. }
  42286. void TextEditor::setText (const String& newText,
  42287. const bool sendTextChangeMessage)
  42288. {
  42289. const int newLength = newText.length();
  42290. if (newLength != getTotalNumChars() || getText() != newText)
  42291. {
  42292. const int oldCursorPos = caretPosition;
  42293. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  42294. clearInternal (0);
  42295. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  42296. // if you're adding text with line-feeds to a single-line text editor, it
  42297. // ain't gonna look right!
  42298. jassert (multiline || ! newText.containsAnyOf ("\r\n"));
  42299. if (cursorWasAtEnd && ! isMultiLine())
  42300. moveCursorTo (getTotalNumChars(), false);
  42301. else
  42302. moveCursorTo (oldCursorPos, false);
  42303. if (sendTextChangeMessage)
  42304. textChanged();
  42305. updateTextHolderSize();
  42306. scrollToMakeSureCursorIsVisible();
  42307. undoManager.clearUndoHistory();
  42308. repaint();
  42309. }
  42310. }
  42311. Value& TextEditor::getTextValue()
  42312. {
  42313. if (valueTextNeedsUpdating)
  42314. {
  42315. valueTextNeedsUpdating = false;
  42316. textValue = getText();
  42317. }
  42318. return textValue;
  42319. }
  42320. void TextEditor::textWasChangedByValue()
  42321. {
  42322. if (textValue.getValueSource().getReferenceCount() > 1)
  42323. setText (textValue.getValue());
  42324. }
  42325. void TextEditor::textChanged()
  42326. {
  42327. updateTextHolderSize();
  42328. postCommandMessage (TextEditorDefs::textChangeMessageId);
  42329. if (textValue.getValueSource().getReferenceCount() > 1)
  42330. {
  42331. valueTextNeedsUpdating = false;
  42332. textValue = getText();
  42333. }
  42334. }
  42335. void TextEditor::returnPressed()
  42336. {
  42337. postCommandMessage (TextEditorDefs::returnKeyMessageId);
  42338. }
  42339. void TextEditor::escapePressed()
  42340. {
  42341. postCommandMessage (TextEditorDefs::escapeKeyMessageId);
  42342. }
  42343. void TextEditor::addListener (TextEditorListener* const newListener)
  42344. {
  42345. listeners.add (newListener);
  42346. }
  42347. void TextEditor::removeListener (TextEditorListener* const listenerToRemove)
  42348. {
  42349. listeners.remove (listenerToRemove);
  42350. }
  42351. void TextEditor::timerCallbackInt()
  42352. {
  42353. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  42354. if (caretFlashState != newState)
  42355. {
  42356. caretFlashState = newState;
  42357. if (caretFlashState)
  42358. wasFocused = true;
  42359. if (caretVisible
  42360. && hasKeyboardFocus (false)
  42361. && ! isReadOnly())
  42362. {
  42363. repaintCaret();
  42364. }
  42365. }
  42366. const unsigned int now = Time::getApproximateMillisecondCounter();
  42367. if (now > lastTransactionTime + 200)
  42368. newTransaction();
  42369. }
  42370. void TextEditor::repaintCaret()
  42371. {
  42372. if (! findColour (caretColourId).isTransparent())
  42373. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundToInt (cursorX) - 1,
  42374. borderSize.getTop() + textHolder->getY() + topIndent + roundToInt (cursorY) - 1,
  42375. 4,
  42376. roundToInt (cursorHeight) + 2);
  42377. }
  42378. void TextEditor::repaintText (const Range<int>& range)
  42379. {
  42380. if (! range.isEmpty())
  42381. {
  42382. float x = 0, y = 0, lh = currentFont.getHeight();
  42383. const float wordWrapWidth = getWordWrapWidth();
  42384. if (wordWrapWidth > 0)
  42385. {
  42386. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42387. i.getCharPosition (range.getStart(), x, y, lh);
  42388. const int y1 = (int) y;
  42389. int y2;
  42390. if (range.getEnd() >= getTotalNumChars())
  42391. {
  42392. y2 = textHolder->getHeight();
  42393. }
  42394. else
  42395. {
  42396. i.getCharPosition (range.getEnd(), x, y, lh);
  42397. y2 = (int) (y + lh * 2.0f);
  42398. }
  42399. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  42400. }
  42401. }
  42402. }
  42403. void TextEditor::moveCaret (int newCaretPos)
  42404. {
  42405. if (newCaretPos < 0)
  42406. newCaretPos = 0;
  42407. else if (newCaretPos > getTotalNumChars())
  42408. newCaretPos = getTotalNumChars();
  42409. if (newCaretPos != getCaretPosition())
  42410. {
  42411. repaintCaret();
  42412. caretFlashState = true;
  42413. caretPosition = newCaretPos;
  42414. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42415. scrollToMakeSureCursorIsVisible();
  42416. repaintCaret();
  42417. }
  42418. }
  42419. void TextEditor::setCaretPosition (const int newIndex)
  42420. {
  42421. moveCursorTo (newIndex, false);
  42422. }
  42423. int TextEditor::getCaretPosition() const
  42424. {
  42425. return caretPosition;
  42426. }
  42427. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  42428. const int desiredCaretY)
  42429. {
  42430. updateCaretPosition();
  42431. int vx = roundToInt (cursorX) - desiredCaretX;
  42432. int vy = roundToInt (cursorY) - desiredCaretY;
  42433. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  42434. {
  42435. vx += desiredCaretX - proportionOfWidth (0.2f);
  42436. }
  42437. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  42438. {
  42439. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  42440. }
  42441. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  42442. if (! isMultiLine())
  42443. {
  42444. vy = viewport->getViewPositionY();
  42445. }
  42446. else
  42447. {
  42448. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  42449. const int curH = roundToInt (cursorHeight);
  42450. if (desiredCaretY < 0)
  42451. {
  42452. vy = jmax (0, desiredCaretY + vy);
  42453. }
  42454. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  42455. {
  42456. vy += desiredCaretY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  42457. }
  42458. }
  42459. viewport->setViewPosition (vx, vy);
  42460. }
  42461. const Rectangle<int> TextEditor::getCaretRectangle()
  42462. {
  42463. updateCaretPosition();
  42464. return Rectangle<int> (roundToInt (cursorX) - viewport->getX(),
  42465. roundToInt (cursorY) - viewport->getY(),
  42466. 1, roundToInt (cursorHeight));
  42467. }
  42468. float TextEditor::getWordWrapWidth() const
  42469. {
  42470. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  42471. : 1.0e10f;
  42472. }
  42473. void TextEditor::updateTextHolderSize()
  42474. {
  42475. const float wordWrapWidth = getWordWrapWidth();
  42476. if (wordWrapWidth > 0)
  42477. {
  42478. float maxWidth = 0.0f;
  42479. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42480. while (i.next())
  42481. maxWidth = jmax (maxWidth, i.atomRight);
  42482. const int w = leftIndent + roundToInt (maxWidth);
  42483. const int h = topIndent + roundToInt (jmax (i.lineY + i.lineHeight,
  42484. currentFont.getHeight()));
  42485. textHolder->setSize (w + 1, h + 1);
  42486. }
  42487. }
  42488. int TextEditor::getTextWidth() const
  42489. {
  42490. return textHolder->getWidth();
  42491. }
  42492. int TextEditor::getTextHeight() const
  42493. {
  42494. return textHolder->getHeight();
  42495. }
  42496. void TextEditor::setIndents (const int newLeftIndent,
  42497. const int newTopIndent)
  42498. {
  42499. leftIndent = newLeftIndent;
  42500. topIndent = newTopIndent;
  42501. }
  42502. void TextEditor::setBorder (const BorderSize& border)
  42503. {
  42504. borderSize = border;
  42505. resized();
  42506. }
  42507. const BorderSize TextEditor::getBorder() const
  42508. {
  42509. return borderSize;
  42510. }
  42511. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor)
  42512. {
  42513. keepCursorOnScreen = shouldScrollToShowCursor;
  42514. }
  42515. void TextEditor::updateCaretPosition()
  42516. {
  42517. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  42518. getCharPosition (caretPosition, cursorX, cursorY, cursorHeight);
  42519. }
  42520. void TextEditor::scrollToMakeSureCursorIsVisible()
  42521. {
  42522. updateCaretPosition();
  42523. if (keepCursorOnScreen)
  42524. {
  42525. int x = viewport->getViewPositionX();
  42526. int y = viewport->getViewPositionY();
  42527. const int relativeCursorX = roundToInt (cursorX) - x;
  42528. const int relativeCursorY = roundToInt (cursorY) - y;
  42529. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  42530. {
  42531. x += relativeCursorX - proportionOfWidth (0.2f);
  42532. }
  42533. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  42534. {
  42535. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  42536. }
  42537. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  42538. if (! isMultiLine())
  42539. {
  42540. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  42541. }
  42542. else
  42543. {
  42544. const int curH = roundToInt (cursorHeight);
  42545. if (relativeCursorY < 0)
  42546. {
  42547. y = jmax (0, relativeCursorY + y);
  42548. }
  42549. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  42550. {
  42551. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  42552. }
  42553. }
  42554. viewport->setViewPosition (x, y);
  42555. }
  42556. }
  42557. void TextEditor::moveCursorTo (const int newPosition,
  42558. const bool isSelecting)
  42559. {
  42560. if (isSelecting)
  42561. {
  42562. moveCaret (newPosition);
  42563. const Range<int> oldSelection (selection);
  42564. if (dragType == notDragging)
  42565. {
  42566. if (abs (getCaretPosition() - selection.getStart()) < abs (getCaretPosition() - selection.getEnd()))
  42567. dragType = draggingSelectionStart;
  42568. else
  42569. dragType = draggingSelectionEnd;
  42570. }
  42571. if (dragType == draggingSelectionStart)
  42572. {
  42573. if (getCaretPosition() >= selection.getEnd())
  42574. dragType = draggingSelectionEnd;
  42575. selection = Range<int>::between (getCaretPosition(), selection.getEnd());
  42576. }
  42577. else
  42578. {
  42579. if (getCaretPosition() < selection.getStart())
  42580. dragType = draggingSelectionStart;
  42581. selection = Range<int>::between (getCaretPosition(), selection.getStart());
  42582. }
  42583. repaintText (selection.getUnionWith (oldSelection));
  42584. }
  42585. else
  42586. {
  42587. dragType = notDragging;
  42588. repaintText (selection);
  42589. moveCaret (newPosition);
  42590. selection = Range<int>::emptyRange (getCaretPosition());
  42591. }
  42592. }
  42593. int TextEditor::getTextIndexAt (const int x,
  42594. const int y)
  42595. {
  42596. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  42597. (float) (y + viewport->getViewPositionY() - topIndent));
  42598. }
  42599. void TextEditor::insertTextAtCaret (const String& newText_)
  42600. {
  42601. String newText (newText_);
  42602. if (allowedCharacters.isNotEmpty())
  42603. newText = newText.retainCharacters (allowedCharacters);
  42604. if ((! returnKeyStartsNewLine) && newText == "\n")
  42605. {
  42606. returnPressed();
  42607. return;
  42608. }
  42609. if (! isMultiLine())
  42610. newText = newText.replaceCharacters ("\r\n", " ");
  42611. else
  42612. newText = newText.replace ("\r\n", "\n");
  42613. const int newCaretPos = selection.getStart() + newText.length();
  42614. const int insertIndex = selection.getStart();
  42615. remove (selection, getUndoManager(),
  42616. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  42617. if (maxTextLength > 0)
  42618. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  42619. if (newText.isNotEmpty())
  42620. insert (newText,
  42621. insertIndex,
  42622. currentFont,
  42623. findColour (textColourId),
  42624. getUndoManager(),
  42625. newCaretPos);
  42626. textChanged();
  42627. }
  42628. void TextEditor::setHighlightedRegion (const Range<int>& newSelection)
  42629. {
  42630. moveCursorTo (newSelection.getStart(), false);
  42631. moveCursorTo (newSelection.getEnd(), true);
  42632. }
  42633. void TextEditor::copy()
  42634. {
  42635. if (passwordCharacter == 0)
  42636. {
  42637. const String selectedText (getHighlightedText());
  42638. if (selectedText.isNotEmpty())
  42639. SystemClipboard::copyTextToClipboard (selectedText);
  42640. }
  42641. }
  42642. void TextEditor::paste()
  42643. {
  42644. if (! isReadOnly())
  42645. {
  42646. const String clip (SystemClipboard::getTextFromClipboard());
  42647. if (clip.isNotEmpty())
  42648. insertTextAtCaret (clip);
  42649. }
  42650. }
  42651. void TextEditor::cut()
  42652. {
  42653. if (! isReadOnly())
  42654. {
  42655. moveCaret (selection.getEnd());
  42656. insertTextAtCaret (String::empty);
  42657. }
  42658. }
  42659. void TextEditor::drawContent (Graphics& g)
  42660. {
  42661. const float wordWrapWidth = getWordWrapWidth();
  42662. if (wordWrapWidth > 0)
  42663. {
  42664. g.setOrigin (leftIndent, topIndent);
  42665. const Rectangle<int> clip (g.getClipBounds());
  42666. Colour selectedTextColour;
  42667. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42668. while (i.lineY + 200.0 < clip.getY() && i.next())
  42669. {}
  42670. if (! selection.isEmpty())
  42671. {
  42672. g.setColour (findColour (highlightColourId)
  42673. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  42674. selectedTextColour = findColour (highlightedTextColourId);
  42675. Iterator i2 (i);
  42676. while (i2.next() && i2.lineY < clip.getBottom())
  42677. {
  42678. if (i2.lineY + i2.lineHeight >= clip.getY()
  42679. && selection.intersects (Range<int> (i2.indexInText, i2.indexInText + i2.atom->numChars)))
  42680. {
  42681. i2.drawSelection (g, selection);
  42682. }
  42683. }
  42684. }
  42685. const UniformTextSection* lastSection = 0;
  42686. while (i.next() && i.lineY < clip.getBottom())
  42687. {
  42688. if (i.lineY + i.lineHeight >= clip.getY())
  42689. {
  42690. if (selection.intersects (Range<int> (i.indexInText, i.indexInText + i.atom->numChars)))
  42691. {
  42692. i.drawSelectedText (g, selection, selectedTextColour);
  42693. lastSection = 0;
  42694. }
  42695. else
  42696. {
  42697. i.draw (g, lastSection);
  42698. }
  42699. }
  42700. }
  42701. }
  42702. }
  42703. void TextEditor::paint (Graphics& g)
  42704. {
  42705. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  42706. }
  42707. void TextEditor::paintOverChildren (Graphics& g)
  42708. {
  42709. if (caretFlashState
  42710. && hasKeyboardFocus (false)
  42711. && caretVisible
  42712. && ! isReadOnly())
  42713. {
  42714. g.setColour (findColour (caretColourId));
  42715. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  42716. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  42717. 2.0f, cursorHeight);
  42718. }
  42719. if (textToShowWhenEmpty.isNotEmpty()
  42720. && (! hasKeyboardFocus (false))
  42721. && getTotalNumChars() == 0)
  42722. {
  42723. g.setColour (colourForTextWhenEmpty);
  42724. g.setFont (getFont());
  42725. if (isMultiLine())
  42726. {
  42727. g.drawText (textToShowWhenEmpty,
  42728. 0, 0, getWidth(), getHeight(),
  42729. Justification::centred, true);
  42730. }
  42731. else
  42732. {
  42733. g.drawText (textToShowWhenEmpty,
  42734. leftIndent, topIndent,
  42735. viewport->getWidth() - leftIndent,
  42736. viewport->getHeight() - topIndent,
  42737. Justification::centredLeft, true);
  42738. }
  42739. }
  42740. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  42741. }
  42742. class TextEditorMenuPerformer : public ModalComponentManager::Callback
  42743. {
  42744. public:
  42745. TextEditorMenuPerformer (TextEditor* const editor_)
  42746. : editor (editor_)
  42747. {
  42748. }
  42749. void modalStateFinished (int returnValue)
  42750. {
  42751. if (editor != 0 && returnValue != 0)
  42752. editor->performPopupMenuAction (returnValue);
  42753. }
  42754. private:
  42755. Component::SafePointer<TextEditor> editor;
  42756. TextEditorMenuPerformer (const TextEditorMenuPerformer&);
  42757. TextEditorMenuPerformer& operator= (const TextEditorMenuPerformer&);
  42758. };
  42759. void TextEditor::mouseDown (const MouseEvent& e)
  42760. {
  42761. beginDragAutoRepeat (100);
  42762. newTransaction();
  42763. if (wasFocused || ! selectAllTextWhenFocused)
  42764. {
  42765. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  42766. {
  42767. moveCursorTo (getTextIndexAt (e.x, e.y),
  42768. e.mods.isShiftDown());
  42769. }
  42770. else
  42771. {
  42772. PopupMenu m;
  42773. m.setLookAndFeel (&getLookAndFeel());
  42774. addPopupMenuItems (m, &e);
  42775. m.show (0, 0, 0, 0, new TextEditorMenuPerformer (this));
  42776. }
  42777. }
  42778. }
  42779. void TextEditor::mouseDrag (const MouseEvent& e)
  42780. {
  42781. if (wasFocused || ! selectAllTextWhenFocused)
  42782. {
  42783. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  42784. {
  42785. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  42786. }
  42787. }
  42788. }
  42789. void TextEditor::mouseUp (const MouseEvent& e)
  42790. {
  42791. newTransaction();
  42792. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42793. if (wasFocused || ! selectAllTextWhenFocused)
  42794. {
  42795. if (e.mouseWasClicked() && ! (popupMenuEnabled && e.mods.isPopupMenu()))
  42796. {
  42797. moveCaret (getTextIndexAt (e.x, e.y));
  42798. }
  42799. }
  42800. wasFocused = true;
  42801. }
  42802. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  42803. {
  42804. int tokenEnd = getTextIndexAt (e.x, e.y);
  42805. int tokenStart = tokenEnd;
  42806. if (e.getNumberOfClicks() > 3)
  42807. {
  42808. tokenStart = 0;
  42809. tokenEnd = getTotalNumChars();
  42810. }
  42811. else
  42812. {
  42813. const String t (getText());
  42814. const int totalLength = getTotalNumChars();
  42815. while (tokenEnd < totalLength)
  42816. {
  42817. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  42818. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]) || t [tokenEnd] > 128)
  42819. ++tokenEnd;
  42820. else
  42821. break;
  42822. }
  42823. tokenStart = tokenEnd;
  42824. while (tokenStart > 0)
  42825. {
  42826. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  42827. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]) || t [tokenStart - 1] > 128)
  42828. --tokenStart;
  42829. else
  42830. break;
  42831. }
  42832. if (e.getNumberOfClicks() > 2)
  42833. {
  42834. while (tokenEnd < totalLength)
  42835. {
  42836. if (t [tokenEnd] != '\r' && t [tokenEnd] != '\n')
  42837. ++tokenEnd;
  42838. else
  42839. break;
  42840. }
  42841. while (tokenStart > 0)
  42842. {
  42843. if (t [tokenStart - 1] != '\r' && t [tokenStart - 1] != '\n')
  42844. --tokenStart;
  42845. else
  42846. break;
  42847. }
  42848. }
  42849. }
  42850. moveCursorTo (tokenEnd, false);
  42851. moveCursorTo (tokenStart, true);
  42852. }
  42853. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  42854. {
  42855. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  42856. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  42857. }
  42858. bool TextEditor::keyPressed (const KeyPress& key)
  42859. {
  42860. if (isReadOnly() && key != KeyPress ('c', ModifierKeys::commandModifier, 0))
  42861. return false;
  42862. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  42863. if (key.isKeyCode (KeyPress::leftKey)
  42864. || key.isKeyCode (KeyPress::upKey))
  42865. {
  42866. newTransaction();
  42867. int newPos;
  42868. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  42869. newPos = indexAtPosition (cursorX, cursorY - 1);
  42870. else if (moveInWholeWordSteps)
  42871. newPos = findWordBreakBefore (getCaretPosition());
  42872. else
  42873. newPos = getCaretPosition() - 1;
  42874. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  42875. }
  42876. else if (key.isKeyCode (KeyPress::rightKey)
  42877. || key.isKeyCode (KeyPress::downKey))
  42878. {
  42879. newTransaction();
  42880. int newPos;
  42881. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  42882. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  42883. else if (moveInWholeWordSteps)
  42884. newPos = findWordBreakAfter (getCaretPosition());
  42885. else
  42886. newPos = getCaretPosition() + 1;
  42887. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  42888. }
  42889. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  42890. {
  42891. newTransaction();
  42892. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  42893. key.getModifiers().isShiftDown());
  42894. }
  42895. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  42896. {
  42897. newTransaction();
  42898. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  42899. key.getModifiers().isShiftDown());
  42900. }
  42901. else if (key.isKeyCode (KeyPress::homeKey))
  42902. {
  42903. newTransaction();
  42904. if (isMultiLine() && ! moveInWholeWordSteps)
  42905. moveCursorTo (indexAtPosition (0.0f, cursorY),
  42906. key.getModifiers().isShiftDown());
  42907. else
  42908. moveCursorTo (0, key.getModifiers().isShiftDown());
  42909. }
  42910. else if (key.isKeyCode (KeyPress::endKey))
  42911. {
  42912. newTransaction();
  42913. if (isMultiLine() && ! moveInWholeWordSteps)
  42914. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  42915. key.getModifiers().isShiftDown());
  42916. else
  42917. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  42918. }
  42919. else if (key.isKeyCode (KeyPress::backspaceKey))
  42920. {
  42921. if (moveInWholeWordSteps)
  42922. {
  42923. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  42924. }
  42925. else
  42926. {
  42927. if (selection.isEmpty() && selection.getStart() > 0)
  42928. selection.setStart (selection.getEnd() - 1);
  42929. }
  42930. cut();
  42931. }
  42932. else if (key.isKeyCode (KeyPress::deleteKey))
  42933. {
  42934. if (key.getModifiers().isShiftDown())
  42935. copy();
  42936. if (selection.isEmpty() && selection.getStart() < getTotalNumChars())
  42937. selection.setEnd (selection.getStart() + 1);
  42938. cut();
  42939. }
  42940. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0)
  42941. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  42942. {
  42943. newTransaction();
  42944. copy();
  42945. }
  42946. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  42947. {
  42948. newTransaction();
  42949. copy();
  42950. cut();
  42951. }
  42952. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0)
  42953. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  42954. {
  42955. newTransaction();
  42956. paste();
  42957. }
  42958. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  42959. {
  42960. newTransaction();
  42961. doUndoRedo (false);
  42962. }
  42963. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0))
  42964. {
  42965. newTransaction();
  42966. doUndoRedo (true);
  42967. }
  42968. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  42969. {
  42970. newTransaction();
  42971. moveCursorTo (getTotalNumChars(), false);
  42972. moveCursorTo (0, true);
  42973. }
  42974. else if (key == KeyPress::returnKey)
  42975. {
  42976. newTransaction();
  42977. insertTextAtCaret ("\n");
  42978. }
  42979. else if (key.isKeyCode (KeyPress::escapeKey))
  42980. {
  42981. newTransaction();
  42982. moveCursorTo (getCaretPosition(), false);
  42983. escapePressed();
  42984. }
  42985. else if (key.getTextCharacter() >= ' '
  42986. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  42987. {
  42988. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  42989. lastTransactionTime = Time::getApproximateMillisecondCounter();
  42990. }
  42991. else
  42992. {
  42993. return false;
  42994. }
  42995. return true;
  42996. }
  42997. bool TextEditor::keyStateChanged (const bool isKeyDown)
  42998. {
  42999. if (! isKeyDown)
  43000. return false;
  43001. #if JUCE_WINDOWS
  43002. if (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0).isCurrentlyDown())
  43003. return false; // We need to explicitly allow alt-F4 to pass through on Windows
  43004. #endif
  43005. // (overridden to avoid forwarding key events to the parent)
  43006. return ! ModifierKeys::getCurrentModifiers().isCommandDown();
  43007. }
  43008. const int baseMenuItemID = 0x7fff0000;
  43009. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  43010. {
  43011. const bool writable = ! isReadOnly();
  43012. if (passwordCharacter == 0)
  43013. {
  43014. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  43015. m.addItem (baseMenuItemID + 2, TRANS("copy"), ! selection.isEmpty());
  43016. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  43017. }
  43018. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  43019. m.addSeparator();
  43020. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  43021. m.addSeparator();
  43022. if (getUndoManager() != 0)
  43023. {
  43024. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  43025. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  43026. }
  43027. }
  43028. void TextEditor::performPopupMenuAction (const int menuItemID)
  43029. {
  43030. switch (menuItemID)
  43031. {
  43032. case baseMenuItemID + 1:
  43033. copy();
  43034. cut();
  43035. break;
  43036. case baseMenuItemID + 2:
  43037. copy();
  43038. break;
  43039. case baseMenuItemID + 3:
  43040. paste();
  43041. break;
  43042. case baseMenuItemID + 4:
  43043. cut();
  43044. break;
  43045. case baseMenuItemID + 5:
  43046. moveCursorTo (getTotalNumChars(), false);
  43047. moveCursorTo (0, true);
  43048. break;
  43049. case baseMenuItemID + 6:
  43050. doUndoRedo (false);
  43051. break;
  43052. case baseMenuItemID + 7:
  43053. doUndoRedo (true);
  43054. break;
  43055. default:
  43056. break;
  43057. }
  43058. }
  43059. void TextEditor::focusGained (FocusChangeType)
  43060. {
  43061. newTransaction();
  43062. caretFlashState = true;
  43063. if (selectAllTextWhenFocused)
  43064. {
  43065. moveCursorTo (0, false);
  43066. moveCursorTo (getTotalNumChars(), true);
  43067. }
  43068. repaint();
  43069. if (caretVisible)
  43070. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43071. ComponentPeer* const peer = getPeer();
  43072. if (peer != 0 && ! isReadOnly())
  43073. peer->textInputRequired (getScreenPosition() - peer->getScreenPosition());
  43074. }
  43075. void TextEditor::focusLost (FocusChangeType)
  43076. {
  43077. newTransaction();
  43078. wasFocused = false;
  43079. textHolder->stopTimer();
  43080. caretFlashState = false;
  43081. postCommandMessage (TextEditorDefs::focusLossMessageId);
  43082. repaint();
  43083. }
  43084. void TextEditor::resized()
  43085. {
  43086. viewport->setBoundsInset (borderSize);
  43087. viewport->setSingleStepSizes (16, roundToInt (currentFont.getHeight()));
  43088. updateTextHolderSize();
  43089. if (! isMultiLine())
  43090. {
  43091. scrollToMakeSureCursorIsVisible();
  43092. }
  43093. else
  43094. {
  43095. updateCaretPosition();
  43096. }
  43097. }
  43098. void TextEditor::handleCommandMessage (const int commandId)
  43099. {
  43100. Component::BailOutChecker checker (this);
  43101. switch (commandId)
  43102. {
  43103. case TextEditorDefs::textChangeMessageId:
  43104. listeners.callChecked (checker, &TextEditorListener::textEditorTextChanged, (TextEditor&) *this);
  43105. break;
  43106. case TextEditorDefs::returnKeyMessageId:
  43107. listeners.callChecked (checker, &TextEditorListener::textEditorReturnKeyPressed, (TextEditor&) *this);
  43108. break;
  43109. case TextEditorDefs::escapeKeyMessageId:
  43110. listeners.callChecked (checker, &TextEditorListener::textEditorEscapeKeyPressed, (TextEditor&) *this);
  43111. break;
  43112. case TextEditorDefs::focusLossMessageId:
  43113. listeners.callChecked (checker, &TextEditorListener::textEditorFocusLost, (TextEditor&) *this);
  43114. break;
  43115. default:
  43116. jassertfalse;
  43117. break;
  43118. }
  43119. }
  43120. void TextEditor::enablementChanged()
  43121. {
  43122. setMouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  43123. : MouseCursor::IBeamCursor);
  43124. repaint();
  43125. }
  43126. UndoManager* TextEditor::getUndoManager() throw()
  43127. {
  43128. return isReadOnly() ? 0 : &undoManager;
  43129. }
  43130. void TextEditor::clearInternal (UndoManager* const um)
  43131. {
  43132. remove (Range<int> (0, getTotalNumChars()), um, caretPosition);
  43133. }
  43134. void TextEditor::insert (const String& text,
  43135. const int insertIndex,
  43136. const Font& font,
  43137. const Colour& colour,
  43138. UndoManager* const um,
  43139. const int caretPositionToMoveTo)
  43140. {
  43141. if (text.isNotEmpty())
  43142. {
  43143. if (um != 0)
  43144. {
  43145. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43146. newTransaction();
  43147. um->perform (new InsertAction (*this, text, insertIndex, font, colour,
  43148. caretPosition, caretPositionToMoveTo));
  43149. }
  43150. else
  43151. {
  43152. repaintText (Range<int> (insertIndex, getTotalNumChars())); // must do this before and after changing the data, in case
  43153. // a line gets moved due to word wrap
  43154. int index = 0;
  43155. int nextIndex = 0;
  43156. for (int i = 0; i < sections.size(); ++i)
  43157. {
  43158. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43159. if (insertIndex == index)
  43160. {
  43161. sections.insert (i, new UniformTextSection (text,
  43162. font, colour,
  43163. passwordCharacter));
  43164. break;
  43165. }
  43166. else if (insertIndex > index && insertIndex < nextIndex)
  43167. {
  43168. splitSection (i, insertIndex - index);
  43169. sections.insert (i + 1, new UniformTextSection (text,
  43170. font, colour,
  43171. passwordCharacter));
  43172. break;
  43173. }
  43174. index = nextIndex;
  43175. }
  43176. if (nextIndex == insertIndex)
  43177. sections.add (new UniformTextSection (text,
  43178. font, colour,
  43179. passwordCharacter));
  43180. coalesceSimilarSections();
  43181. totalNumChars = -1;
  43182. valueTextNeedsUpdating = true;
  43183. moveCursorTo (caretPositionToMoveTo, false);
  43184. repaintText (Range<int> (insertIndex, getTotalNumChars()));
  43185. }
  43186. }
  43187. }
  43188. void TextEditor::reinsert (const int insertIndex,
  43189. const Array <UniformTextSection*>& sectionsToInsert)
  43190. {
  43191. int index = 0;
  43192. int nextIndex = 0;
  43193. for (int i = 0; i < sections.size(); ++i)
  43194. {
  43195. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43196. if (insertIndex == index)
  43197. {
  43198. for (int j = sectionsToInsert.size(); --j >= 0;)
  43199. sections.insert (i, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43200. break;
  43201. }
  43202. else if (insertIndex > index && insertIndex < nextIndex)
  43203. {
  43204. splitSection (i, insertIndex - index);
  43205. for (int j = sectionsToInsert.size(); --j >= 0;)
  43206. sections.insert (i + 1, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43207. break;
  43208. }
  43209. index = nextIndex;
  43210. }
  43211. if (nextIndex == insertIndex)
  43212. {
  43213. for (int j = 0; j < sectionsToInsert.size(); ++j)
  43214. sections.add (new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43215. }
  43216. coalesceSimilarSections();
  43217. totalNumChars = -1;
  43218. valueTextNeedsUpdating = true;
  43219. }
  43220. void TextEditor::remove (const Range<int>& range,
  43221. UndoManager* const um,
  43222. const int caretPositionToMoveTo)
  43223. {
  43224. if (! range.isEmpty())
  43225. {
  43226. int index = 0;
  43227. for (int i = 0; i < sections.size(); ++i)
  43228. {
  43229. const int nextIndex = index + sections.getUnchecked(i)->getTotalLength();
  43230. if (range.getStart() > index && range.getStart() < nextIndex)
  43231. {
  43232. splitSection (i, range.getStart() - index);
  43233. --i;
  43234. }
  43235. else if (range.getEnd() > index && range.getEnd() < nextIndex)
  43236. {
  43237. splitSection (i, range.getEnd() - index);
  43238. --i;
  43239. }
  43240. else
  43241. {
  43242. index = nextIndex;
  43243. if (index > range.getEnd())
  43244. break;
  43245. }
  43246. }
  43247. index = 0;
  43248. if (um != 0)
  43249. {
  43250. Array <UniformTextSection*> removedSections;
  43251. for (int i = 0; i < sections.size(); ++i)
  43252. {
  43253. if (range.getEnd() <= range.getStart())
  43254. break;
  43255. UniformTextSection* const section = sections.getUnchecked (i);
  43256. const int nextIndex = index + section->getTotalLength();
  43257. if (range.getStart() <= index && range.getEnd() >= nextIndex)
  43258. removedSections.add (new UniformTextSection (*section));
  43259. index = nextIndex;
  43260. }
  43261. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43262. newTransaction();
  43263. um->perform (new RemoveAction (*this, range, caretPosition,
  43264. caretPositionToMoveTo, removedSections));
  43265. }
  43266. else
  43267. {
  43268. Range<int> remainingRange (range);
  43269. for (int i = 0; i < sections.size(); ++i)
  43270. {
  43271. UniformTextSection* const section = sections.getUnchecked (i);
  43272. const int nextIndex = index + section->getTotalLength();
  43273. if (remainingRange.getStart() <= index && remainingRange.getEnd() >= nextIndex)
  43274. {
  43275. sections.remove(i);
  43276. section->clear();
  43277. delete section;
  43278. remainingRange.setEnd (remainingRange.getEnd() - (nextIndex - index));
  43279. if (remainingRange.isEmpty())
  43280. break;
  43281. --i;
  43282. }
  43283. else
  43284. {
  43285. index = nextIndex;
  43286. }
  43287. }
  43288. coalesceSimilarSections();
  43289. totalNumChars = -1;
  43290. valueTextNeedsUpdating = true;
  43291. moveCursorTo (caretPositionToMoveTo, false);
  43292. repaintText (Range<int> (range.getStart(), getTotalNumChars()));
  43293. }
  43294. }
  43295. }
  43296. const String TextEditor::getText() const
  43297. {
  43298. String t;
  43299. t.preallocateStorage (getTotalNumChars());
  43300. String::Concatenator concatenator (t);
  43301. for (int i = 0; i < sections.size(); ++i)
  43302. sections.getUnchecked (i)->appendAllText (concatenator);
  43303. return t;
  43304. }
  43305. const String TextEditor::getTextInRange (const Range<int>& range) const
  43306. {
  43307. String t;
  43308. if (! range.isEmpty())
  43309. {
  43310. t.preallocateStorage (jmin (getTotalNumChars(), range.getLength()));
  43311. String::Concatenator concatenator (t);
  43312. int index = 0;
  43313. for (int i = 0; i < sections.size(); ++i)
  43314. {
  43315. const UniformTextSection* const s = sections.getUnchecked (i);
  43316. const int nextIndex = index + s->getTotalLength();
  43317. if (range.getStart() < nextIndex)
  43318. {
  43319. if (range.getEnd() <= index)
  43320. break;
  43321. s->appendSubstring (concatenator, range - index);
  43322. }
  43323. index = nextIndex;
  43324. }
  43325. }
  43326. return t;
  43327. }
  43328. const String TextEditor::getHighlightedText() const
  43329. {
  43330. return getTextInRange (selection);
  43331. }
  43332. int TextEditor::getTotalNumChars() const
  43333. {
  43334. if (totalNumChars < 0)
  43335. {
  43336. totalNumChars = 0;
  43337. for (int i = sections.size(); --i >= 0;)
  43338. totalNumChars += sections.getUnchecked (i)->getTotalLength();
  43339. }
  43340. return totalNumChars;
  43341. }
  43342. bool TextEditor::isEmpty() const
  43343. {
  43344. return getTotalNumChars() == 0;
  43345. }
  43346. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const
  43347. {
  43348. const float wordWrapWidth = getWordWrapWidth();
  43349. if (wordWrapWidth > 0 && sections.size() > 0)
  43350. {
  43351. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43352. i.getCharPosition (index, cx, cy, lineHeight);
  43353. }
  43354. else
  43355. {
  43356. cx = cy = 0;
  43357. lineHeight = currentFont.getHeight();
  43358. }
  43359. }
  43360. int TextEditor::indexAtPosition (const float x, const float y)
  43361. {
  43362. const float wordWrapWidth = getWordWrapWidth();
  43363. if (wordWrapWidth > 0)
  43364. {
  43365. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43366. while (i.next())
  43367. {
  43368. if (i.lineY + i.lineHeight > y)
  43369. {
  43370. if (i.lineY > y)
  43371. return jmax (0, i.indexInText - 1);
  43372. if (i.atomX >= x)
  43373. return i.indexInText;
  43374. if (x < i.atomRight)
  43375. return i.xToIndex (x);
  43376. }
  43377. }
  43378. }
  43379. return getTotalNumChars();
  43380. }
  43381. static int getCharacterCategory (const juce_wchar character)
  43382. {
  43383. return CharacterFunctions::isLetterOrDigit (character)
  43384. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  43385. }
  43386. int TextEditor::findWordBreakAfter (const int position) const
  43387. {
  43388. const String t (getTextInRange (Range<int> (position, position + 512)));
  43389. const int totalLength = t.length();
  43390. int i = 0;
  43391. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  43392. ++i;
  43393. const int type = getCharacterCategory (t[i]);
  43394. while (i < totalLength && type == getCharacterCategory (t[i]))
  43395. ++i;
  43396. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  43397. ++i;
  43398. return position + i;
  43399. }
  43400. int TextEditor::findWordBreakBefore (const int position) const
  43401. {
  43402. if (position <= 0)
  43403. return 0;
  43404. const int startOfBuffer = jmax (0, position - 512);
  43405. const String t (getTextInRange (Range<int> (startOfBuffer, position)));
  43406. int i = position - startOfBuffer;
  43407. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  43408. --i;
  43409. if (i > 0)
  43410. {
  43411. const int type = getCharacterCategory (t [i - 1]);
  43412. while (i > 0 && type == getCharacterCategory (t [i - 1]))
  43413. --i;
  43414. }
  43415. jassert (startOfBuffer + i >= 0);
  43416. return startOfBuffer + i;
  43417. }
  43418. void TextEditor::splitSection (const int sectionIndex,
  43419. const int charToSplitAt)
  43420. {
  43421. jassert (sections[sectionIndex] != 0);
  43422. sections.insert (sectionIndex + 1,
  43423. sections.getUnchecked (sectionIndex)->split (charToSplitAt, passwordCharacter));
  43424. }
  43425. void TextEditor::coalesceSimilarSections()
  43426. {
  43427. for (int i = 0; i < sections.size() - 1; ++i)
  43428. {
  43429. UniformTextSection* const s1 = sections.getUnchecked (i);
  43430. UniformTextSection* const s2 = sections.getUnchecked (i + 1);
  43431. if (s1->font == s2->font
  43432. && s1->colour == s2->colour)
  43433. {
  43434. s1->append (*s2, passwordCharacter);
  43435. sections.remove (i + 1);
  43436. delete s2;
  43437. --i;
  43438. }
  43439. }
  43440. }
  43441. END_JUCE_NAMESPACE
  43442. /*** End of inlined file: juce_TextEditor.cpp ***/
  43443. /*** Start of inlined file: juce_Toolbar.cpp ***/
  43444. BEGIN_JUCE_NAMESPACE
  43445. const char* const Toolbar::toolbarDragDescriptor = "_toolbarItem_";
  43446. class ToolbarSpacerComp : public ToolbarItemComponent
  43447. {
  43448. public:
  43449. ToolbarSpacerComp (const int itemId_, const float fixedSize_, const bool drawBar_)
  43450. : ToolbarItemComponent (itemId_, String::empty, false),
  43451. fixedSize (fixedSize_),
  43452. drawBar (drawBar_)
  43453. {
  43454. }
  43455. ~ToolbarSpacerComp()
  43456. {
  43457. }
  43458. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  43459. int& preferredSize, int& minSize, int& maxSize)
  43460. {
  43461. if (fixedSize <= 0)
  43462. {
  43463. preferredSize = toolbarThickness * 2;
  43464. minSize = 4;
  43465. maxSize = 32768;
  43466. }
  43467. else
  43468. {
  43469. maxSize = roundToInt (toolbarThickness * fixedSize);
  43470. minSize = drawBar ? maxSize : jmin (4, maxSize);
  43471. preferredSize = maxSize;
  43472. if (getEditingMode() == editableOnPalette)
  43473. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  43474. }
  43475. return true;
  43476. }
  43477. void paintButtonArea (Graphics&, int, int, bool, bool)
  43478. {
  43479. }
  43480. void contentAreaChanged (const Rectangle<int>&)
  43481. {
  43482. }
  43483. int getResizeOrder() const throw()
  43484. {
  43485. return fixedSize <= 0 ? 0 : 1;
  43486. }
  43487. void paint (Graphics& g)
  43488. {
  43489. const int w = getWidth();
  43490. const int h = getHeight();
  43491. if (drawBar)
  43492. {
  43493. g.setColour (findColour (Toolbar::separatorColourId, true));
  43494. const float thickness = 0.2f;
  43495. if (isToolbarVertical())
  43496. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  43497. else
  43498. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  43499. }
  43500. if (getEditingMode() != normalMode && ! drawBar)
  43501. {
  43502. g.setColour (findColour (Toolbar::separatorColourId, true));
  43503. const int indentX = jmin (2, (w - 3) / 2);
  43504. const int indentY = jmin (2, (h - 3) / 2);
  43505. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  43506. if (fixedSize <= 0)
  43507. {
  43508. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  43509. if (isToolbarVertical())
  43510. {
  43511. x1 = w * 0.5f;
  43512. y1 = h * 0.4f;
  43513. x2 = x1;
  43514. y2 = indentX * 2.0f;
  43515. x3 = x1;
  43516. y3 = h * 0.6f;
  43517. x4 = x1;
  43518. y4 = h - y2;
  43519. hw = w * 0.15f;
  43520. hl = w * 0.2f;
  43521. }
  43522. else
  43523. {
  43524. x1 = w * 0.4f;
  43525. y1 = h * 0.5f;
  43526. x2 = indentX * 2.0f;
  43527. y2 = y1;
  43528. x3 = w * 0.6f;
  43529. y3 = y1;
  43530. x4 = w - x2;
  43531. y4 = y1;
  43532. hw = h * 0.15f;
  43533. hl = h * 0.2f;
  43534. }
  43535. Path p;
  43536. p.addArrow (Line<float> (x1, y1, x2, y2), 1.5f, hw, hl);
  43537. p.addArrow (Line<float> (x3, y3, x4, y4), 1.5f, hw, hl);
  43538. g.fillPath (p);
  43539. }
  43540. }
  43541. }
  43542. juce_UseDebuggingNewOperator
  43543. private:
  43544. const float fixedSize;
  43545. const bool drawBar;
  43546. ToolbarSpacerComp (const ToolbarSpacerComp&);
  43547. ToolbarSpacerComp& operator= (const ToolbarSpacerComp&);
  43548. };
  43549. class MissingItemsComponent : public PopupMenuCustomComponent
  43550. {
  43551. public:
  43552. MissingItemsComponent (Toolbar& owner_, const int height_)
  43553. : PopupMenuCustomComponent (true),
  43554. owner (owner_),
  43555. height (height_)
  43556. {
  43557. for (int i = owner_.items.size(); --i >= 0;)
  43558. {
  43559. ToolbarItemComponent* const tc = owner_.items.getUnchecked(i);
  43560. if (dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  43561. {
  43562. oldIndexes.insert (0, i);
  43563. addAndMakeVisible (tc, 0);
  43564. }
  43565. }
  43566. layout (400);
  43567. }
  43568. ~MissingItemsComponent()
  43569. {
  43570. // deleting the toolbar while its menu it open??
  43571. jassert (owner.isValidComponent());
  43572. for (int i = 0; i < getNumChildComponents(); ++i)
  43573. {
  43574. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  43575. if (tc != 0)
  43576. {
  43577. tc->setVisible (false);
  43578. const int index = oldIndexes.remove (i);
  43579. owner.addChildComponent (tc, index);
  43580. --i;
  43581. }
  43582. }
  43583. owner.resized();
  43584. }
  43585. void layout (const int preferredWidth)
  43586. {
  43587. const int indent = 8;
  43588. int x = indent;
  43589. int y = indent;
  43590. int maxX = 0;
  43591. for (int i = 0; i < getNumChildComponents(); ++i)
  43592. {
  43593. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  43594. if (tc != 0)
  43595. {
  43596. int preferredSize = 1, minSize = 1, maxSize = 1;
  43597. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  43598. {
  43599. if (x + preferredSize > preferredWidth && x > indent)
  43600. {
  43601. x = indent;
  43602. y += height;
  43603. }
  43604. tc->setBounds (x, y, preferredSize, height);
  43605. x += preferredSize;
  43606. maxX = jmax (maxX, x);
  43607. }
  43608. }
  43609. }
  43610. setSize (maxX + 8, y + height + 8);
  43611. }
  43612. void getIdealSize (int& idealWidth, int& idealHeight)
  43613. {
  43614. idealWidth = getWidth();
  43615. idealHeight = getHeight();
  43616. }
  43617. juce_UseDebuggingNewOperator
  43618. private:
  43619. Toolbar& owner;
  43620. const int height;
  43621. Array <int> oldIndexes;
  43622. MissingItemsComponent (const MissingItemsComponent&);
  43623. MissingItemsComponent& operator= (const MissingItemsComponent&);
  43624. };
  43625. Toolbar::Toolbar()
  43626. : vertical (false),
  43627. isEditingActive (false),
  43628. toolbarStyle (Toolbar::iconsOnly)
  43629. {
  43630. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  43631. missingItemsButton->setAlwaysOnTop (true);
  43632. missingItemsButton->addButtonListener (this);
  43633. }
  43634. Toolbar::~Toolbar()
  43635. {
  43636. animator.cancelAllAnimations (true);
  43637. deleteAllChildren();
  43638. }
  43639. void Toolbar::setVertical (const bool shouldBeVertical)
  43640. {
  43641. if (vertical != shouldBeVertical)
  43642. {
  43643. vertical = shouldBeVertical;
  43644. resized();
  43645. }
  43646. }
  43647. void Toolbar::clear()
  43648. {
  43649. for (int i = items.size(); --i >= 0;)
  43650. {
  43651. ToolbarItemComponent* const tc = items.getUnchecked(i);
  43652. items.remove (i);
  43653. delete tc;
  43654. }
  43655. resized();
  43656. }
  43657. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  43658. {
  43659. if (itemId == ToolbarItemFactory::separatorBarId)
  43660. return new ToolbarSpacerComp (itemId, 0.1f, true);
  43661. else if (itemId == ToolbarItemFactory::spacerId)
  43662. return new ToolbarSpacerComp (itemId, 0.5f, false);
  43663. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  43664. return new ToolbarSpacerComp (itemId, 0, false);
  43665. return factory.createItem (itemId);
  43666. }
  43667. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  43668. const int itemId,
  43669. const int insertIndex)
  43670. {
  43671. // An ID can't be zero - this might indicate a mistake somewhere?
  43672. jassert (itemId != 0);
  43673. ToolbarItemComponent* const tc = createItem (factory, itemId);
  43674. if (tc != 0)
  43675. {
  43676. #if JUCE_DEBUG
  43677. Array <int> allowedIds;
  43678. factory.getAllToolbarItemIds (allowedIds);
  43679. // If your factory can create an item for a given ID, it must also return
  43680. // that ID from its getAllToolbarItemIds() method!
  43681. jassert (allowedIds.contains (itemId));
  43682. #endif
  43683. items.insert (insertIndex, tc);
  43684. addAndMakeVisible (tc, insertIndex);
  43685. }
  43686. }
  43687. void Toolbar::addItem (ToolbarItemFactory& factory,
  43688. const int itemId,
  43689. const int insertIndex)
  43690. {
  43691. addItemInternal (factory, itemId, insertIndex);
  43692. resized();
  43693. }
  43694. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  43695. {
  43696. Array <int> ids;
  43697. factoryToUse.getDefaultItemSet (ids);
  43698. clear();
  43699. for (int i = 0; i < ids.size(); ++i)
  43700. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  43701. resized();
  43702. }
  43703. void Toolbar::removeToolbarItem (const int itemIndex)
  43704. {
  43705. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  43706. if (tc != 0)
  43707. {
  43708. items.removeValue (tc);
  43709. delete tc;
  43710. resized();
  43711. }
  43712. }
  43713. int Toolbar::getNumItems() const throw()
  43714. {
  43715. return items.size();
  43716. }
  43717. int Toolbar::getItemId (const int itemIndex) const throw()
  43718. {
  43719. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  43720. return tc != 0 ? tc->getItemId() : 0;
  43721. }
  43722. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  43723. {
  43724. return items [itemIndex];
  43725. }
  43726. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  43727. {
  43728. for (;;)
  43729. {
  43730. index += delta;
  43731. ToolbarItemComponent* const tc = getItemComponent (index);
  43732. if (tc == 0)
  43733. break;
  43734. if (tc->isActive)
  43735. return tc;
  43736. }
  43737. return 0;
  43738. }
  43739. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  43740. {
  43741. if (toolbarStyle != newStyle)
  43742. {
  43743. toolbarStyle = newStyle;
  43744. updateAllItemPositions (false);
  43745. }
  43746. }
  43747. const String Toolbar::toString() const
  43748. {
  43749. String s ("TB:");
  43750. for (int i = 0; i < getNumItems(); ++i)
  43751. s << getItemId(i) << ' ';
  43752. return s.trimEnd();
  43753. }
  43754. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  43755. const String& savedVersion)
  43756. {
  43757. if (! savedVersion.startsWith ("TB:"))
  43758. return false;
  43759. StringArray tokens;
  43760. tokens.addTokens (savedVersion.substring (3), false);
  43761. clear();
  43762. for (int i = 0; i < tokens.size(); ++i)
  43763. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  43764. resized();
  43765. return true;
  43766. }
  43767. void Toolbar::paint (Graphics& g)
  43768. {
  43769. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  43770. }
  43771. int Toolbar::getThickness() const throw()
  43772. {
  43773. return vertical ? getWidth() : getHeight();
  43774. }
  43775. int Toolbar::getLength() const throw()
  43776. {
  43777. return vertical ? getHeight() : getWidth();
  43778. }
  43779. void Toolbar::setEditingActive (const bool active)
  43780. {
  43781. if (isEditingActive != active)
  43782. {
  43783. isEditingActive = active;
  43784. updateAllItemPositions (false);
  43785. }
  43786. }
  43787. void Toolbar::resized()
  43788. {
  43789. updateAllItemPositions (false);
  43790. }
  43791. void Toolbar::updateAllItemPositions (const bool animate)
  43792. {
  43793. if (getWidth() > 0 && getHeight() > 0)
  43794. {
  43795. StretchableObjectResizer resizer;
  43796. int i;
  43797. for (i = 0; i < items.size(); ++i)
  43798. {
  43799. ToolbarItemComponent* const tc = items.getUnchecked(i);
  43800. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  43801. : ToolbarItemComponent::normalMode);
  43802. tc->setStyle (toolbarStyle);
  43803. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  43804. int preferredSize = 1, minSize = 1, maxSize = 1;
  43805. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  43806. preferredSize, minSize, maxSize))
  43807. {
  43808. tc->isActive = true;
  43809. resizer.addItem (preferredSize, minSize, maxSize,
  43810. spacer != 0 ? spacer->getResizeOrder() : 2);
  43811. }
  43812. else
  43813. {
  43814. tc->isActive = false;
  43815. tc->setVisible (false);
  43816. }
  43817. }
  43818. resizer.resizeToFit (getLength());
  43819. int totalLength = 0;
  43820. for (i = 0; i < resizer.getNumItems(); ++i)
  43821. totalLength += (int) resizer.getItemSize (i);
  43822. const bool itemsOffTheEnd = totalLength > getLength();
  43823. const int extrasButtonSize = getThickness() / 2;
  43824. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  43825. missingItemsButton->setVisible (itemsOffTheEnd);
  43826. missingItemsButton->setEnabled (! isEditingActive);
  43827. if (vertical)
  43828. missingItemsButton->setCentrePosition (getWidth() / 2,
  43829. getHeight() - 4 - extrasButtonSize / 2);
  43830. else
  43831. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  43832. getHeight() / 2);
  43833. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  43834. : missingItemsButton->getX()) - 4
  43835. : getLength();
  43836. int pos = 0, activeIndex = 0;
  43837. for (i = 0; i < items.size(); ++i)
  43838. {
  43839. ToolbarItemComponent* const tc = items.getUnchecked(i);
  43840. if (tc->isActive)
  43841. {
  43842. const int size = (int) resizer.getItemSize (activeIndex++);
  43843. Rectangle<int> newBounds;
  43844. if (vertical)
  43845. newBounds.setBounds (0, pos, getWidth(), size);
  43846. else
  43847. newBounds.setBounds (pos, 0, size, getHeight());
  43848. if (animate)
  43849. {
  43850. animator.animateComponent (tc, newBounds, 200, 3.0, 0.0);
  43851. }
  43852. else
  43853. {
  43854. animator.cancelAnimation (tc, false);
  43855. tc->setBounds (newBounds);
  43856. }
  43857. pos += size;
  43858. tc->setVisible (pos <= maxLength
  43859. && ((! tc->isBeingDragged)
  43860. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  43861. }
  43862. }
  43863. }
  43864. }
  43865. void Toolbar::buttonClicked (Button*)
  43866. {
  43867. jassert (missingItemsButton->isShowing());
  43868. if (missingItemsButton->isShowing())
  43869. {
  43870. PopupMenu m;
  43871. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  43872. m.showAt (missingItemsButton);
  43873. }
  43874. }
  43875. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  43876. Component* /*sourceComponent*/)
  43877. {
  43878. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  43879. }
  43880. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  43881. {
  43882. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  43883. if (tc != 0)
  43884. {
  43885. if (getNumItems() == 0)
  43886. {
  43887. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  43888. {
  43889. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  43890. if (palette != 0)
  43891. palette->replaceComponent (tc);
  43892. }
  43893. else
  43894. {
  43895. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  43896. }
  43897. items.add (tc);
  43898. addChildComponent (tc);
  43899. updateAllItemPositions (false);
  43900. }
  43901. else
  43902. {
  43903. for (int i = getNumItems(); --i >= 0;)
  43904. {
  43905. int currentIndex = getIndexOfChildComponent (tc);
  43906. if (currentIndex < 0)
  43907. {
  43908. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  43909. {
  43910. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  43911. if (palette != 0)
  43912. palette->replaceComponent (tc);
  43913. }
  43914. else
  43915. {
  43916. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  43917. }
  43918. items.add (tc);
  43919. addChildComponent (tc);
  43920. currentIndex = getIndexOfChildComponent (tc);
  43921. updateAllItemPositions (true);
  43922. }
  43923. int newIndex = currentIndex;
  43924. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  43925. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  43926. const Rectangle<int> current (animator.getComponentDestination (getChildComponent (newIndex)));
  43927. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  43928. if (prev != 0)
  43929. {
  43930. const Rectangle<int> previousPos (animator.getComponentDestination (prev));
  43931. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  43932. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  43933. {
  43934. newIndex = getIndexOfChildComponent (prev);
  43935. }
  43936. }
  43937. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  43938. if (next != 0)
  43939. {
  43940. const Rectangle<int> nextPos (animator.getComponentDestination (next));
  43941. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  43942. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  43943. {
  43944. newIndex = getIndexOfChildComponent (next) + 1;
  43945. }
  43946. }
  43947. if (newIndex != currentIndex)
  43948. {
  43949. items.removeValue (tc);
  43950. removeChildComponent (tc);
  43951. addChildComponent (tc, newIndex);
  43952. items.insert (newIndex, tc);
  43953. updateAllItemPositions (true);
  43954. }
  43955. else
  43956. {
  43957. break;
  43958. }
  43959. }
  43960. }
  43961. }
  43962. }
  43963. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  43964. {
  43965. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  43966. if (tc != 0)
  43967. {
  43968. if (isParentOf (tc))
  43969. {
  43970. items.removeValue (tc);
  43971. removeChildComponent (tc);
  43972. updateAllItemPositions (true);
  43973. }
  43974. }
  43975. }
  43976. void Toolbar::itemDropped (const String&, Component*, int, int)
  43977. {
  43978. }
  43979. void Toolbar::mouseDown (const MouseEvent& e)
  43980. {
  43981. if (e.mods.isPopupMenu())
  43982. {
  43983. }
  43984. }
  43985. class ToolbarCustomisationDialog : public DialogWindow
  43986. {
  43987. public:
  43988. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  43989. Toolbar* const toolbar_,
  43990. const int optionFlags)
  43991. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  43992. toolbar (toolbar_)
  43993. {
  43994. setContentComponent (new CustomiserPanel (factory, toolbar, optionFlags), true, true);
  43995. setResizable (true, true);
  43996. setResizeLimits (400, 300, 1500, 1000);
  43997. positionNearBar();
  43998. }
  43999. ~ToolbarCustomisationDialog()
  44000. {
  44001. setContentComponent (0, true);
  44002. }
  44003. void closeButtonPressed()
  44004. {
  44005. setVisible (false);
  44006. }
  44007. bool canModalEventBeSentToComponent (const Component* comp)
  44008. {
  44009. return toolbar->isParentOf (comp);
  44010. }
  44011. void positionNearBar()
  44012. {
  44013. const Rectangle<int> screenSize (toolbar->getParentMonitorArea());
  44014. const int tbx = toolbar->getScreenX();
  44015. const int tby = toolbar->getScreenY();
  44016. const int gap = 8;
  44017. int x, y;
  44018. if (toolbar->isVertical())
  44019. {
  44020. y = tby;
  44021. if (tbx > screenSize.getCentreX())
  44022. x = tbx - getWidth() - gap;
  44023. else
  44024. x = tbx + toolbar->getWidth() + gap;
  44025. }
  44026. else
  44027. {
  44028. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  44029. if (tby > screenSize.getCentreY())
  44030. y = tby - getHeight() - gap;
  44031. else
  44032. y = tby + toolbar->getHeight() + gap;
  44033. }
  44034. setTopLeftPosition (x, y);
  44035. }
  44036. private:
  44037. Toolbar* const toolbar;
  44038. class CustomiserPanel : public Component,
  44039. private ComboBoxListener,
  44040. private ButtonListener
  44041. {
  44042. public:
  44043. CustomiserPanel (ToolbarItemFactory& factory_,
  44044. Toolbar* const toolbar_,
  44045. const int optionFlags)
  44046. : factory (factory_),
  44047. toolbar (toolbar_),
  44048. styleBox (0),
  44049. defaultButton (0)
  44050. {
  44051. addAndMakeVisible (palette = new ToolbarItemPalette (factory, toolbar));
  44052. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  44053. | Toolbar::allowIconsWithTextChoice
  44054. | Toolbar::allowTextOnlyChoice)) != 0)
  44055. {
  44056. addAndMakeVisible (styleBox = new ComboBox (String::empty));
  44057. styleBox->setEditableText (false);
  44058. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0)
  44059. styleBox->addItem (TRANS("Show icons only"), 1);
  44060. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0)
  44061. styleBox->addItem (TRANS("Show icons and descriptions"), 2);
  44062. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0)
  44063. styleBox->addItem (TRANS("Show descriptions only"), 3);
  44064. if (toolbar_->getStyle() == Toolbar::iconsOnly)
  44065. styleBox->setSelectedId (1);
  44066. else if (toolbar_->getStyle() == Toolbar::iconsWithText)
  44067. styleBox->setSelectedId (2);
  44068. else if (toolbar_->getStyle() == Toolbar::textOnly)
  44069. styleBox->setSelectedId (3);
  44070. styleBox->addListener (this);
  44071. }
  44072. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  44073. {
  44074. addAndMakeVisible (defaultButton = new TextButton (TRANS ("Restore to default set of items")));
  44075. defaultButton->addButtonListener (this);
  44076. }
  44077. addAndMakeVisible (instructions = new Label (String::empty,
  44078. 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.")));
  44079. instructions->setFont (Font (13.0f));
  44080. setSize (500, 300);
  44081. }
  44082. ~CustomiserPanel()
  44083. {
  44084. deleteAllChildren();
  44085. }
  44086. void comboBoxChanged (ComboBox*)
  44087. {
  44088. if (styleBox->getSelectedId() == 1)
  44089. toolbar->setStyle (Toolbar::iconsOnly);
  44090. else if (styleBox->getSelectedId() == 2)
  44091. toolbar->setStyle (Toolbar::iconsWithText);
  44092. else if (styleBox->getSelectedId() == 3)
  44093. toolbar->setStyle (Toolbar::textOnly);
  44094. palette->resized(); // to make it update the styles
  44095. }
  44096. void buttonClicked (Button*)
  44097. {
  44098. toolbar->addDefaultItems (factory);
  44099. }
  44100. void paint (Graphics& g)
  44101. {
  44102. Colour background;
  44103. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  44104. if (dw != 0)
  44105. background = dw->getBackgroundColour();
  44106. g.setColour (background.contrasting().withAlpha (0.3f));
  44107. g.fillRect (palette->getX(), palette->getBottom() - 1, palette->getWidth(), 1);
  44108. }
  44109. void resized()
  44110. {
  44111. palette->setBounds (0, 0, getWidth(), getHeight() - 120);
  44112. if (styleBox != 0)
  44113. styleBox->setBounds (10, getHeight() - 110, 200, 22);
  44114. if (defaultButton != 0)
  44115. {
  44116. defaultButton->changeWidthToFitText (22);
  44117. defaultButton->setTopLeftPosition (240, getHeight() - 110);
  44118. }
  44119. instructions->setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  44120. }
  44121. private:
  44122. ToolbarItemFactory& factory;
  44123. Toolbar* const toolbar;
  44124. Label* instructions;
  44125. ToolbarItemPalette* palette;
  44126. ComboBox* styleBox;
  44127. TextButton* defaultButton;
  44128. };
  44129. };
  44130. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  44131. {
  44132. setEditingActive (true);
  44133. ToolbarCustomisationDialog dw (factory, this, optionFlags);
  44134. dw.runModalLoop();
  44135. jassert (isValidComponent()); // ? deleting the toolbar while it's being edited?
  44136. setEditingActive (false);
  44137. }
  44138. END_JUCE_NAMESPACE
  44139. /*** End of inlined file: juce_Toolbar.cpp ***/
  44140. /*** Start of inlined file: juce_ToolbarItemComponent.cpp ***/
  44141. BEGIN_JUCE_NAMESPACE
  44142. ToolbarItemFactory::ToolbarItemFactory()
  44143. {
  44144. }
  44145. ToolbarItemFactory::~ToolbarItemFactory()
  44146. {
  44147. }
  44148. class ItemDragAndDropOverlayComponent : public Component
  44149. {
  44150. public:
  44151. ItemDragAndDropOverlayComponent()
  44152. : isDragging (false)
  44153. {
  44154. setAlwaysOnTop (true);
  44155. setRepaintsOnMouseActivity (true);
  44156. setMouseCursor (MouseCursor::DraggingHandCursor);
  44157. }
  44158. ~ItemDragAndDropOverlayComponent()
  44159. {
  44160. }
  44161. void paint (Graphics& g)
  44162. {
  44163. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44164. if (isMouseOverOrDragging()
  44165. && tc != 0
  44166. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44167. {
  44168. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  44169. g.drawRect (0, 0, getWidth(), getHeight(),
  44170. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  44171. }
  44172. }
  44173. void mouseDown (const MouseEvent& e)
  44174. {
  44175. isDragging = false;
  44176. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44177. if (tc != 0)
  44178. {
  44179. tc->dragOffsetX = e.x;
  44180. tc->dragOffsetY = e.y;
  44181. }
  44182. }
  44183. void mouseDrag (const MouseEvent& e)
  44184. {
  44185. if (! (isDragging || e.mouseWasClicked()))
  44186. {
  44187. isDragging = true;
  44188. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  44189. if (dnd != 0)
  44190. {
  44191. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), Image(), true);
  44192. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44193. if (tc != 0)
  44194. {
  44195. tc->isBeingDragged = true;
  44196. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44197. tc->setVisible (false);
  44198. }
  44199. }
  44200. }
  44201. }
  44202. void mouseUp (const MouseEvent&)
  44203. {
  44204. isDragging = false;
  44205. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44206. if (tc != 0)
  44207. {
  44208. tc->isBeingDragged = false;
  44209. Toolbar* const tb = tc->getToolbar();
  44210. if (tb != 0)
  44211. tb->updateAllItemPositions (true);
  44212. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44213. delete tc;
  44214. }
  44215. }
  44216. void parentSizeChanged()
  44217. {
  44218. setBounds (0, 0, getParentWidth(), getParentHeight());
  44219. }
  44220. juce_UseDebuggingNewOperator
  44221. private:
  44222. bool isDragging;
  44223. ItemDragAndDropOverlayComponent (const ItemDragAndDropOverlayComponent&);
  44224. ItemDragAndDropOverlayComponent& operator= (const ItemDragAndDropOverlayComponent&);
  44225. };
  44226. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  44227. const String& labelText,
  44228. const bool isBeingUsedAsAButton_)
  44229. : Button (labelText),
  44230. itemId (itemId_),
  44231. mode (normalMode),
  44232. toolbarStyle (Toolbar::iconsOnly),
  44233. dragOffsetX (0),
  44234. dragOffsetY (0),
  44235. isActive (true),
  44236. isBeingDragged (false),
  44237. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  44238. {
  44239. // Your item ID can't be 0!
  44240. jassert (itemId_ != 0);
  44241. }
  44242. ToolbarItemComponent::~ToolbarItemComponent()
  44243. {
  44244. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  44245. overlayComp = 0;
  44246. }
  44247. Toolbar* ToolbarItemComponent::getToolbar() const
  44248. {
  44249. return dynamic_cast <Toolbar*> (getParentComponent());
  44250. }
  44251. bool ToolbarItemComponent::isToolbarVertical() const
  44252. {
  44253. const Toolbar* const t = getToolbar();
  44254. return t != 0 && t->isVertical();
  44255. }
  44256. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  44257. {
  44258. if (toolbarStyle != newStyle)
  44259. {
  44260. toolbarStyle = newStyle;
  44261. repaint();
  44262. resized();
  44263. }
  44264. }
  44265. void ToolbarItemComponent::paintButton (Graphics& g, const bool over, const bool down)
  44266. {
  44267. if (isBeingUsedAsAButton)
  44268. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  44269. over, down, *this);
  44270. if (toolbarStyle != Toolbar::iconsOnly)
  44271. {
  44272. const int indent = contentArea.getX();
  44273. int y = indent;
  44274. int h = getHeight() - indent * 2;
  44275. if (toolbarStyle == Toolbar::iconsWithText)
  44276. {
  44277. y = contentArea.getBottom() + indent / 2;
  44278. h -= contentArea.getHeight();
  44279. }
  44280. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  44281. getButtonText(), *this);
  44282. }
  44283. if (! contentArea.isEmpty())
  44284. {
  44285. g.saveState();
  44286. g.setOrigin (contentArea.getX(), contentArea.getY());
  44287. g.reduceClipRegion (0, 0, contentArea.getWidth(), contentArea.getHeight());
  44288. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), over, down);
  44289. g.restoreState();
  44290. }
  44291. }
  44292. void ToolbarItemComponent::resized()
  44293. {
  44294. if (toolbarStyle != Toolbar::textOnly)
  44295. {
  44296. const int indent = jmin (proportionOfWidth (0.08f),
  44297. proportionOfHeight (0.08f));
  44298. contentArea = Rectangle<int> (indent, indent,
  44299. getWidth() - indent * 2,
  44300. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  44301. : (getHeight() - indent * 2));
  44302. }
  44303. else
  44304. {
  44305. contentArea = Rectangle<int>();
  44306. }
  44307. contentAreaChanged (contentArea);
  44308. }
  44309. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  44310. {
  44311. if (mode != newMode)
  44312. {
  44313. mode = newMode;
  44314. repaint();
  44315. if (mode == normalMode)
  44316. {
  44317. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  44318. overlayComp = 0;
  44319. }
  44320. else if (overlayComp == 0)
  44321. {
  44322. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  44323. overlayComp->parentSizeChanged();
  44324. }
  44325. resized();
  44326. }
  44327. }
  44328. END_JUCE_NAMESPACE
  44329. /*** End of inlined file: juce_ToolbarItemComponent.cpp ***/
  44330. /*** Start of inlined file: juce_ToolbarItemPalette.cpp ***/
  44331. BEGIN_JUCE_NAMESPACE
  44332. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  44333. Toolbar* const toolbar_)
  44334. : factory (factory_),
  44335. toolbar (toolbar_)
  44336. {
  44337. Component* const itemHolder = new Component();
  44338. Array <int> allIds;
  44339. factory_.getAllToolbarItemIds (allIds);
  44340. for (int i = 0; i < allIds.size(); ++i)
  44341. {
  44342. ToolbarItemComponent* const tc = Toolbar::createItem (factory_, allIds.getUnchecked (i));
  44343. jassert (tc != 0);
  44344. if (tc != 0)
  44345. {
  44346. itemHolder->addAndMakeVisible (tc);
  44347. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  44348. }
  44349. }
  44350. viewport = new Viewport();
  44351. viewport->setViewedComponent (itemHolder);
  44352. addAndMakeVisible (viewport);
  44353. }
  44354. ToolbarItemPalette::~ToolbarItemPalette()
  44355. {
  44356. viewport->getViewedComponent()->deleteAllChildren();
  44357. deleteAllChildren();
  44358. }
  44359. void ToolbarItemPalette::resized()
  44360. {
  44361. viewport->setBoundsInset (BorderSize (1));
  44362. Component* const itemHolder = viewport->getViewedComponent();
  44363. const int indent = 8;
  44364. const int preferredWidth = viewport->getWidth() - viewport->getScrollBarThickness() - indent;
  44365. const int height = toolbar->getThickness();
  44366. int x = indent;
  44367. int y = indent;
  44368. int maxX = 0;
  44369. for (int i = 0; i < itemHolder->getNumChildComponents(); ++i)
  44370. {
  44371. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (itemHolder->getChildComponent (i));
  44372. if (tc != 0)
  44373. {
  44374. tc->setStyle (toolbar->getStyle());
  44375. int preferredSize = 1, minSize = 1, maxSize = 1;
  44376. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  44377. {
  44378. if (x + preferredSize > preferredWidth && x > indent)
  44379. {
  44380. x = indent;
  44381. y += height;
  44382. }
  44383. tc->setBounds (x, y, preferredSize, height);
  44384. x += preferredSize + 8;
  44385. maxX = jmax (maxX, x);
  44386. }
  44387. }
  44388. }
  44389. itemHolder->setSize (maxX, y + height + 8);
  44390. }
  44391. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  44392. {
  44393. ToolbarItemComponent* const tc = Toolbar::createItem (factory, comp->getItemId());
  44394. jassert (tc != 0);
  44395. if (tc != 0)
  44396. {
  44397. tc->setBounds (comp->getBounds());
  44398. tc->setStyle (toolbar->getStyle());
  44399. tc->setEditingMode (comp->getEditingMode());
  44400. viewport->getViewedComponent()->addAndMakeVisible (tc, getIndexOfChildComponent (comp));
  44401. }
  44402. }
  44403. END_JUCE_NAMESPACE
  44404. /*** End of inlined file: juce_ToolbarItemPalette.cpp ***/
  44405. /*** Start of inlined file: juce_TreeView.cpp ***/
  44406. BEGIN_JUCE_NAMESPACE
  44407. class TreeViewContentComponent : public Component,
  44408. public TooltipClient
  44409. {
  44410. public:
  44411. TreeViewContentComponent (TreeView& owner_)
  44412. : owner (owner_),
  44413. buttonUnderMouse (0),
  44414. isDragging (false)
  44415. {
  44416. }
  44417. ~TreeViewContentComponent()
  44418. {
  44419. deleteAllChildren();
  44420. }
  44421. void mouseDown (const MouseEvent& e)
  44422. {
  44423. updateButtonUnderMouse (e);
  44424. isDragging = false;
  44425. needSelectionOnMouseUp = false;
  44426. Rectangle<int> pos;
  44427. TreeViewItem* const item = findItemAt (e.y, pos);
  44428. if (item == 0)
  44429. return;
  44430. // (if the open/close buttons are hidden, we'll treat clicks to the left of the item
  44431. // as selection clicks)
  44432. if (e.x < pos.getX() && owner.openCloseButtonsVisible)
  44433. {
  44434. if (e.x >= pos.getX() - owner.getIndentSize())
  44435. item->setOpen (! item->isOpen());
  44436. // (clicks to the left of an open/close button are ignored)
  44437. }
  44438. else
  44439. {
  44440. // mouse-down inside the body of the item..
  44441. if (! owner.isMultiSelectEnabled())
  44442. item->setSelected (true, true);
  44443. else if (item->isSelected())
  44444. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  44445. else
  44446. selectBasedOnModifiers (item, e.mods);
  44447. if (e.x >= pos.getX())
  44448. item->itemClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  44449. }
  44450. }
  44451. void mouseUp (const MouseEvent& e)
  44452. {
  44453. updateButtonUnderMouse (e);
  44454. if (needSelectionOnMouseUp && e.mouseWasClicked())
  44455. {
  44456. Rectangle<int> pos;
  44457. TreeViewItem* const item = findItemAt (e.y, pos);
  44458. if (item != 0)
  44459. selectBasedOnModifiers (item, e.mods);
  44460. }
  44461. }
  44462. void mouseDoubleClick (const MouseEvent& e)
  44463. {
  44464. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  44465. {
  44466. Rectangle<int> pos;
  44467. TreeViewItem* const item = findItemAt (e.y, pos);
  44468. if (item != 0 && (e.x >= pos.getX() || ! owner.openCloseButtonsVisible))
  44469. item->itemDoubleClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  44470. }
  44471. }
  44472. void mouseDrag (const MouseEvent& e)
  44473. {
  44474. if (isEnabled()
  44475. && ! (isDragging || e.mouseWasClicked()
  44476. || e.getDistanceFromDragStart() < 5
  44477. || e.mods.isPopupMenu()))
  44478. {
  44479. isDragging = true;
  44480. Rectangle<int> pos;
  44481. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  44482. if (item != 0 && e.getMouseDownX() >= pos.getX())
  44483. {
  44484. const String dragDescription (item->getDragSourceDescription());
  44485. if (dragDescription.isNotEmpty())
  44486. {
  44487. DragAndDropContainer* const dragContainer
  44488. = DragAndDropContainer::findParentDragContainerFor (this);
  44489. if (dragContainer != 0)
  44490. {
  44491. pos.setSize (pos.getWidth(), item->itemHeight);
  44492. Image dragImage (Component::createComponentSnapshot (pos, true));
  44493. dragImage.multiplyAllAlphas (0.6f);
  44494. Point<int> imageOffset (pos.getPosition() - e.getPosition());
  44495. dragContainer->startDragging (dragDescription, &owner, dragImage, true, &imageOffset);
  44496. }
  44497. else
  44498. {
  44499. // to be able to do a drag-and-drop operation, the treeview needs to
  44500. // be inside a component which is also a DragAndDropContainer.
  44501. jassertfalse;
  44502. }
  44503. }
  44504. }
  44505. }
  44506. }
  44507. void mouseMove (const MouseEvent& e)
  44508. {
  44509. updateButtonUnderMouse (e);
  44510. }
  44511. void mouseExit (const MouseEvent& e)
  44512. {
  44513. updateButtonUnderMouse (e);
  44514. }
  44515. void paint (Graphics& g)
  44516. {
  44517. if (owner.rootItem != 0)
  44518. {
  44519. owner.handleAsyncUpdate();
  44520. if (! owner.rootItemVisible)
  44521. g.setOrigin (0, -owner.rootItem->itemHeight);
  44522. owner.rootItem->paintRecursively (g, getWidth());
  44523. }
  44524. }
  44525. TreeViewItem* findItemAt (int y, Rectangle<int>& itemPosition) const
  44526. {
  44527. if (owner.rootItem != 0)
  44528. {
  44529. owner.handleAsyncUpdate();
  44530. if (! owner.rootItemVisible)
  44531. y += owner.rootItem->itemHeight;
  44532. TreeViewItem* const ti = owner.rootItem->findItemRecursively (y);
  44533. if (ti != 0)
  44534. itemPosition = ti->getItemPosition (false);
  44535. return ti;
  44536. }
  44537. return 0;
  44538. }
  44539. void updateComponents()
  44540. {
  44541. const int visibleTop = -getY();
  44542. const int visibleBottom = visibleTop + getParentHeight();
  44543. BigInteger itemsToKeep;
  44544. {
  44545. TreeViewItem* item = owner.rootItem;
  44546. int y = (item != 0 && ! owner.rootItemVisible) ? -item->itemHeight : 0;
  44547. while (item != 0 && y < visibleBottom)
  44548. {
  44549. y += item->itemHeight;
  44550. if (y >= visibleTop)
  44551. {
  44552. const int index = rowComponentIds.indexOf (item->uid);
  44553. if (index < 0)
  44554. {
  44555. Component* const comp = item->createItemComponent();
  44556. if (comp != 0)
  44557. {
  44558. addAndMakeVisible (comp);
  44559. itemsToKeep.setBit (rowComponentItems.size());
  44560. rowComponentItems.add (item);
  44561. rowComponentIds.add (item->uid);
  44562. rowComponents.add (comp);
  44563. }
  44564. }
  44565. else
  44566. {
  44567. itemsToKeep.setBit (index);
  44568. }
  44569. }
  44570. item = item->getNextVisibleItem (true);
  44571. }
  44572. }
  44573. for (int i = rowComponentItems.size(); --i >= 0;)
  44574. {
  44575. Component* const comp = rowComponents.getUnchecked(i);
  44576. bool keep = false;
  44577. if (isParentOf (comp))
  44578. {
  44579. if (itemsToKeep[i])
  44580. {
  44581. const TreeViewItem* const item = rowComponentItems.getUnchecked(i);
  44582. Rectangle<int> pos (item->getItemPosition (false));
  44583. pos.setSize (pos.getWidth(), item->itemHeight);
  44584. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  44585. {
  44586. keep = true;
  44587. comp->setBounds (pos);
  44588. }
  44589. }
  44590. if ((! keep) && isMouseDraggingInChildCompOf (comp))
  44591. {
  44592. keep = true;
  44593. comp->setSize (0, 0);
  44594. }
  44595. }
  44596. if (! keep)
  44597. {
  44598. delete comp;
  44599. rowComponents.remove (i);
  44600. rowComponentIds.remove (i);
  44601. rowComponentItems.remove (i);
  44602. }
  44603. }
  44604. }
  44605. void updateButtonUnderMouse (const MouseEvent& e)
  44606. {
  44607. TreeViewItem* newItem = 0;
  44608. if (owner.openCloseButtonsVisible)
  44609. {
  44610. Rectangle<int> pos;
  44611. TreeViewItem* item = findItemAt (e.y, pos);
  44612. if (item != 0 && e.x < pos.getX() && e.x >= pos.getX() - owner.getIndentSize())
  44613. {
  44614. newItem = item;
  44615. if (! newItem->mightContainSubItems())
  44616. newItem = 0;
  44617. }
  44618. }
  44619. if (buttonUnderMouse != newItem)
  44620. {
  44621. if (buttonUnderMouse != 0 && containsItem (buttonUnderMouse))
  44622. {
  44623. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  44624. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  44625. }
  44626. buttonUnderMouse = newItem;
  44627. if (buttonUnderMouse != 0)
  44628. {
  44629. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  44630. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  44631. }
  44632. }
  44633. }
  44634. bool isMouseOverButton (TreeViewItem* const item) const throw()
  44635. {
  44636. return item == buttonUnderMouse;
  44637. }
  44638. void resized()
  44639. {
  44640. owner.itemsChanged();
  44641. }
  44642. const String getTooltip()
  44643. {
  44644. Rectangle<int> pos;
  44645. TreeViewItem* const item = findItemAt (getMouseXYRelative().getY(), pos);
  44646. if (item != 0)
  44647. return item->getTooltip();
  44648. return owner.getTooltip();
  44649. }
  44650. juce_UseDebuggingNewOperator
  44651. private:
  44652. TreeView& owner;
  44653. Array <TreeViewItem*> rowComponentItems;
  44654. Array <int> rowComponentIds;
  44655. Array <Component*> rowComponents;
  44656. TreeViewItem* buttonUnderMouse;
  44657. bool isDragging, needSelectionOnMouseUp;
  44658. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  44659. {
  44660. TreeViewItem* firstSelected = 0;
  44661. if (modifiers.isShiftDown() && ((firstSelected = owner.getSelectedItem (0)) != 0))
  44662. {
  44663. TreeViewItem* const lastSelected = owner.getSelectedItem (owner.getNumSelectedItems() - 1);
  44664. jassert (lastSelected != 0);
  44665. int rowStart = firstSelected->getRowNumberInTree();
  44666. int rowEnd = lastSelected->getRowNumberInTree();
  44667. if (rowStart > rowEnd)
  44668. swapVariables (rowStart, rowEnd);
  44669. int ourRow = item->getRowNumberInTree();
  44670. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  44671. if (ourRow > otherEnd)
  44672. swapVariables (ourRow, otherEnd);
  44673. for (int i = ourRow; i <= otherEnd; ++i)
  44674. owner.getItemOnRow (i)->setSelected (true, false);
  44675. }
  44676. else
  44677. {
  44678. const bool cmd = modifiers.isCommandDown();
  44679. item->setSelected ((! cmd) || ! item->isSelected(), ! cmd);
  44680. }
  44681. }
  44682. bool containsItem (TreeViewItem* const item) const
  44683. {
  44684. for (int i = rowComponentItems.size(); --i >= 0;)
  44685. if (rowComponentItems.getUnchecked(i) == item)
  44686. return true;
  44687. return false;
  44688. }
  44689. static bool isMouseDraggingInChildCompOf (Component* const comp)
  44690. {
  44691. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  44692. {
  44693. MouseInputSource* const source = Desktop::getInstance().getMouseSource(i);
  44694. if (source->isDragging())
  44695. {
  44696. Component* const underMouse = source->getComponentUnderMouse();
  44697. if (underMouse != 0 && (comp == underMouse || comp->isParentOf (underMouse)))
  44698. return true;
  44699. }
  44700. }
  44701. return false;
  44702. }
  44703. TreeViewContentComponent (const TreeViewContentComponent&);
  44704. TreeViewContentComponent& operator= (const TreeViewContentComponent&);
  44705. };
  44706. class TreeView::TreeViewport : public Viewport
  44707. {
  44708. public:
  44709. TreeViewport() throw() : lastX (-1) {}
  44710. ~TreeViewport() throw() {}
  44711. void updateComponents (const bool triggerResize = false)
  44712. {
  44713. TreeViewContentComponent* const tvc = static_cast <TreeViewContentComponent*> (getViewedComponent());
  44714. if (tvc != 0)
  44715. {
  44716. if (triggerResize)
  44717. tvc->resized();
  44718. else
  44719. tvc->updateComponents();
  44720. }
  44721. repaint();
  44722. }
  44723. void visibleAreaChanged (int x, int, int, int)
  44724. {
  44725. const bool hasScrolledSideways = (x != lastX);
  44726. lastX = x;
  44727. updateComponents (hasScrolledSideways);
  44728. }
  44729. juce_UseDebuggingNewOperator
  44730. private:
  44731. int lastX;
  44732. TreeViewport (const TreeViewport&);
  44733. TreeViewport& operator= (const TreeViewport&);
  44734. };
  44735. TreeView::TreeView (const String& componentName)
  44736. : Component (componentName),
  44737. rootItem (0),
  44738. indentSize (24),
  44739. defaultOpenness (false),
  44740. needsRecalculating (true),
  44741. rootItemVisible (true),
  44742. multiSelectEnabled (false),
  44743. openCloseButtonsVisible (true)
  44744. {
  44745. addAndMakeVisible (viewport = new TreeViewport());
  44746. viewport->setViewedComponent (new TreeViewContentComponent (*this));
  44747. viewport->setWantsKeyboardFocus (false);
  44748. setWantsKeyboardFocus (true);
  44749. }
  44750. TreeView::~TreeView()
  44751. {
  44752. if (rootItem != 0)
  44753. rootItem->setOwnerView (0);
  44754. }
  44755. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  44756. {
  44757. if (rootItem != newRootItem)
  44758. {
  44759. if (newRootItem != 0)
  44760. {
  44761. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  44762. if (newRootItem->ownerView != 0)
  44763. newRootItem->ownerView->setRootItem (0);
  44764. }
  44765. if (rootItem != 0)
  44766. rootItem->setOwnerView (0);
  44767. rootItem = newRootItem;
  44768. if (newRootItem != 0)
  44769. newRootItem->setOwnerView (this);
  44770. needsRecalculating = true;
  44771. handleAsyncUpdate();
  44772. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  44773. {
  44774. rootItem->setOpen (false); // force a re-open
  44775. rootItem->setOpen (true);
  44776. }
  44777. }
  44778. }
  44779. void TreeView::deleteRootItem()
  44780. {
  44781. const ScopedPointer <TreeViewItem> deleter (rootItem);
  44782. setRootItem (0);
  44783. }
  44784. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  44785. {
  44786. rootItemVisible = shouldBeVisible;
  44787. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  44788. {
  44789. rootItem->setOpen (false); // force a re-open
  44790. rootItem->setOpen (true);
  44791. }
  44792. itemsChanged();
  44793. }
  44794. void TreeView::colourChanged()
  44795. {
  44796. setOpaque (findColour (backgroundColourId).isOpaque());
  44797. repaint();
  44798. }
  44799. void TreeView::setIndentSize (const int newIndentSize)
  44800. {
  44801. if (indentSize != newIndentSize)
  44802. {
  44803. indentSize = newIndentSize;
  44804. resized();
  44805. }
  44806. }
  44807. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  44808. {
  44809. if (defaultOpenness != isOpenByDefault)
  44810. {
  44811. defaultOpenness = isOpenByDefault;
  44812. itemsChanged();
  44813. }
  44814. }
  44815. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  44816. {
  44817. multiSelectEnabled = canMultiSelect;
  44818. }
  44819. void TreeView::setOpenCloseButtonsVisible (const bool shouldBeVisible)
  44820. {
  44821. if (openCloseButtonsVisible != shouldBeVisible)
  44822. {
  44823. openCloseButtonsVisible = shouldBeVisible;
  44824. itemsChanged();
  44825. }
  44826. }
  44827. Viewport* TreeView::getViewport() const throw()
  44828. {
  44829. return viewport;
  44830. }
  44831. void TreeView::clearSelectedItems()
  44832. {
  44833. if (rootItem != 0)
  44834. rootItem->deselectAllRecursively();
  44835. }
  44836. int TreeView::getNumSelectedItems() const throw()
  44837. {
  44838. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively() : 0;
  44839. }
  44840. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  44841. {
  44842. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  44843. }
  44844. int TreeView::getNumRowsInTree() const
  44845. {
  44846. if (rootItem != 0)
  44847. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  44848. return 0;
  44849. }
  44850. TreeViewItem* TreeView::getItemOnRow (int index) const
  44851. {
  44852. if (! rootItemVisible)
  44853. ++index;
  44854. if (rootItem != 0 && index >= 0)
  44855. return rootItem->getItemOnRow (index);
  44856. return 0;
  44857. }
  44858. TreeViewItem* TreeView::getItemAt (int y) const throw()
  44859. {
  44860. TreeViewContentComponent* const tc = static_cast <TreeViewContentComponent*> (viewport->getViewedComponent());
  44861. Rectangle<int> pos;
  44862. return tc->findItemAt (relativePositionToOtherComponent (tc, Point<int> (0, y)).getY(), pos);
  44863. }
  44864. TreeViewItem* TreeView::findItemFromIdentifierString (const String& identifierString) const
  44865. {
  44866. if (rootItem == 0)
  44867. return 0;
  44868. return rootItem->findItemFromIdentifierString (identifierString);
  44869. }
  44870. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  44871. {
  44872. XmlElement* e = 0;
  44873. if (rootItem != 0)
  44874. {
  44875. e = rootItem->getOpennessState();
  44876. if (e != 0 && alsoIncludeScrollPosition)
  44877. e->setAttribute ("scrollPos", viewport->getViewPositionY());
  44878. }
  44879. return e;
  44880. }
  44881. void TreeView::restoreOpennessState (const XmlElement& newState)
  44882. {
  44883. if (rootItem != 0)
  44884. {
  44885. rootItem->restoreOpennessState (newState);
  44886. if (newState.hasAttribute ("scrollPos"))
  44887. viewport->setViewPosition (viewport->getViewPositionX(),
  44888. newState.getIntAttribute ("scrollPos"));
  44889. }
  44890. }
  44891. void TreeView::paint (Graphics& g)
  44892. {
  44893. g.fillAll (findColour (backgroundColourId));
  44894. }
  44895. void TreeView::resized()
  44896. {
  44897. viewport->setBounds (getLocalBounds());
  44898. itemsChanged();
  44899. handleAsyncUpdate();
  44900. }
  44901. void TreeView::enablementChanged()
  44902. {
  44903. repaint();
  44904. }
  44905. void TreeView::moveSelectedRow (int delta)
  44906. {
  44907. if (delta == 0)
  44908. return;
  44909. int rowSelected = 0;
  44910. TreeViewItem* const firstSelected = getSelectedItem (0);
  44911. if (firstSelected != 0)
  44912. rowSelected = firstSelected->getRowNumberInTree();
  44913. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  44914. for (;;)
  44915. {
  44916. TreeViewItem* item = getItemOnRow (rowSelected);
  44917. if (item != 0)
  44918. {
  44919. if (! item->canBeSelected())
  44920. {
  44921. // if the row we want to highlight doesn't allow it, try skipping
  44922. // to the next item..
  44923. const int nextRowToTry = jlimit (0, getNumRowsInTree() - 1,
  44924. rowSelected + (delta < 0 ? -1 : 1));
  44925. if (rowSelected != nextRowToTry)
  44926. {
  44927. rowSelected = nextRowToTry;
  44928. continue;
  44929. }
  44930. else
  44931. {
  44932. break;
  44933. }
  44934. }
  44935. item->setSelected (true, true);
  44936. scrollToKeepItemVisible (item);
  44937. }
  44938. break;
  44939. }
  44940. }
  44941. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  44942. {
  44943. if (item != 0 && item->ownerView == this)
  44944. {
  44945. handleAsyncUpdate();
  44946. item = item->getDeepestOpenParentItem();
  44947. int y = item->y;
  44948. int viewTop = viewport->getViewPositionY();
  44949. if (y < viewTop)
  44950. {
  44951. viewport->setViewPosition (viewport->getViewPositionX(), y);
  44952. }
  44953. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  44954. {
  44955. viewport->setViewPosition (viewport->getViewPositionX(),
  44956. (y + item->itemHeight) - viewport->getViewHeight());
  44957. }
  44958. }
  44959. }
  44960. bool TreeView::keyPressed (const KeyPress& key)
  44961. {
  44962. if (key.isKeyCode (KeyPress::upKey))
  44963. {
  44964. moveSelectedRow (-1);
  44965. }
  44966. else if (key.isKeyCode (KeyPress::downKey))
  44967. {
  44968. moveSelectedRow (1);
  44969. }
  44970. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  44971. {
  44972. if (rootItem != 0)
  44973. {
  44974. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  44975. if (key.isKeyCode (KeyPress::pageUpKey))
  44976. rowsOnScreen = -rowsOnScreen;
  44977. moveSelectedRow (rowsOnScreen);
  44978. }
  44979. }
  44980. else if (key.isKeyCode (KeyPress::homeKey))
  44981. {
  44982. moveSelectedRow (-0x3fffffff);
  44983. }
  44984. else if (key.isKeyCode (KeyPress::endKey))
  44985. {
  44986. moveSelectedRow (0x3fffffff);
  44987. }
  44988. else if (key.isKeyCode (KeyPress::returnKey))
  44989. {
  44990. TreeViewItem* const firstSelected = getSelectedItem (0);
  44991. if (firstSelected != 0)
  44992. firstSelected->setOpen (! firstSelected->isOpen());
  44993. }
  44994. else if (key.isKeyCode (KeyPress::leftKey))
  44995. {
  44996. TreeViewItem* const firstSelected = getSelectedItem (0);
  44997. if (firstSelected != 0)
  44998. {
  44999. if (firstSelected->isOpen())
  45000. {
  45001. firstSelected->setOpen (false);
  45002. }
  45003. else
  45004. {
  45005. TreeViewItem* parent = firstSelected->parentItem;
  45006. if ((! rootItemVisible) && parent == rootItem)
  45007. parent = 0;
  45008. if (parent != 0)
  45009. {
  45010. parent->setSelected (true, true);
  45011. scrollToKeepItemVisible (parent);
  45012. }
  45013. }
  45014. }
  45015. }
  45016. else if (key.isKeyCode (KeyPress::rightKey))
  45017. {
  45018. TreeViewItem* const firstSelected = getSelectedItem (0);
  45019. if (firstSelected != 0)
  45020. {
  45021. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  45022. moveSelectedRow (1);
  45023. else
  45024. firstSelected->setOpen (true);
  45025. }
  45026. }
  45027. else
  45028. {
  45029. return false;
  45030. }
  45031. return true;
  45032. }
  45033. void TreeView::itemsChanged() throw()
  45034. {
  45035. needsRecalculating = true;
  45036. repaint();
  45037. triggerAsyncUpdate();
  45038. }
  45039. void TreeView::handleAsyncUpdate()
  45040. {
  45041. if (needsRecalculating)
  45042. {
  45043. needsRecalculating = false;
  45044. const ScopedLock sl (nodeAlterationLock);
  45045. if (rootItem != 0)
  45046. rootItem->updatePositions (rootItemVisible ? 0 : -rootItem->itemHeight);
  45047. viewport->updateComponents();
  45048. if (rootItem != 0)
  45049. {
  45050. viewport->getViewedComponent()
  45051. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  45052. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  45053. }
  45054. else
  45055. {
  45056. viewport->getViewedComponent()->setSize (0, 0);
  45057. }
  45058. }
  45059. }
  45060. class TreeView::InsertPointHighlight : public Component
  45061. {
  45062. public:
  45063. InsertPointHighlight()
  45064. : lastItem (0)
  45065. {
  45066. setSize (100, 12);
  45067. setAlwaysOnTop (true);
  45068. setInterceptsMouseClicks (false, false);
  45069. }
  45070. ~InsertPointHighlight() {}
  45071. void setTargetPosition (TreeViewItem* const item, int insertIndex, const int x, const int y, const int width) throw()
  45072. {
  45073. lastItem = item;
  45074. lastIndex = insertIndex;
  45075. const int offset = getHeight() / 2;
  45076. setBounds (x - offset, y - offset, width - (x - offset), getHeight());
  45077. }
  45078. void paint (Graphics& g)
  45079. {
  45080. Path p;
  45081. const float h = (float) getHeight();
  45082. p.addEllipse (2.0f, 2.0f, h - 4.0f, h - 4.0f);
  45083. p.startNewSubPath (h - 2.0f, h / 2.0f);
  45084. p.lineTo ((float) getWidth(), h / 2.0f);
  45085. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45086. g.strokePath (p, PathStrokeType (2.0f));
  45087. }
  45088. TreeViewItem* lastItem;
  45089. int lastIndex;
  45090. private:
  45091. InsertPointHighlight (const InsertPointHighlight&);
  45092. InsertPointHighlight& operator= (const InsertPointHighlight&);
  45093. };
  45094. class TreeView::TargetGroupHighlight : public Component
  45095. {
  45096. public:
  45097. TargetGroupHighlight()
  45098. {
  45099. setAlwaysOnTop (true);
  45100. setInterceptsMouseClicks (false, false);
  45101. }
  45102. ~TargetGroupHighlight() {}
  45103. void setTargetPosition (TreeViewItem* const item) throw()
  45104. {
  45105. Rectangle<int> r (item->getItemPosition (true));
  45106. r.setHeight (item->getItemHeight());
  45107. setBounds (r);
  45108. }
  45109. void paint (Graphics& g)
  45110. {
  45111. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45112. g.drawRoundedRectangle (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 3.0f, 2.0f);
  45113. }
  45114. private:
  45115. TargetGroupHighlight (const TargetGroupHighlight&);
  45116. TargetGroupHighlight& operator= (const TargetGroupHighlight&);
  45117. };
  45118. void TreeView::showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw()
  45119. {
  45120. beginDragAutoRepeat (1000 / 30);
  45121. if (dragInsertPointHighlight == 0)
  45122. {
  45123. addAndMakeVisible (dragInsertPointHighlight = new InsertPointHighlight());
  45124. addAndMakeVisible (dragTargetGroupHighlight = new TargetGroupHighlight());
  45125. }
  45126. dragInsertPointHighlight->setTargetPosition (item, insertIndex, x, y, viewport->getViewWidth());
  45127. dragTargetGroupHighlight->setTargetPosition (item);
  45128. }
  45129. void TreeView::hideDragHighlight() throw()
  45130. {
  45131. dragInsertPointHighlight = 0;
  45132. dragTargetGroupHighlight = 0;
  45133. }
  45134. TreeViewItem* TreeView::getInsertPosition (int& x, int& y, int& insertIndex,
  45135. const StringArray& files, const String& sourceDescription,
  45136. Component* sourceComponent) const throw()
  45137. {
  45138. insertIndex = 0;
  45139. TreeViewItem* item = getItemAt (y);
  45140. if (item == 0)
  45141. return 0;
  45142. Rectangle<int> itemPos (item->getItemPosition (true));
  45143. insertIndex = item->getIndexInParent();
  45144. const int oldY = y;
  45145. y = itemPos.getY();
  45146. if (item->getNumSubItems() == 0 || ! item->isOpen())
  45147. {
  45148. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45149. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45150. {
  45151. // Check if we're trying to drag into an empty group item..
  45152. if (oldY > itemPos.getY() + itemPos.getHeight() / 4
  45153. && oldY < itemPos.getBottom() - itemPos.getHeight() / 4)
  45154. {
  45155. insertIndex = 0;
  45156. x = itemPos.getX() + getIndentSize();
  45157. y = itemPos.getBottom();
  45158. return item;
  45159. }
  45160. }
  45161. }
  45162. if (oldY > itemPos.getCentreY())
  45163. {
  45164. y += item->getItemHeight();
  45165. while (item->isLastOfSiblings() && item->parentItem != 0
  45166. && item->parentItem->parentItem != 0)
  45167. {
  45168. if (x > itemPos.getX())
  45169. break;
  45170. item = item->parentItem;
  45171. itemPos = item->getItemPosition (true);
  45172. insertIndex = item->getIndexInParent();
  45173. }
  45174. ++insertIndex;
  45175. }
  45176. x = itemPos.getX();
  45177. return item->parentItem;
  45178. }
  45179. void TreeView::handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45180. {
  45181. const bool scrolled = viewport->autoScroll (x, y, 20, 10);
  45182. int insertIndex;
  45183. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45184. if (item != 0)
  45185. {
  45186. if (scrolled || dragInsertPointHighlight == 0
  45187. || dragInsertPointHighlight->lastItem != item
  45188. || dragInsertPointHighlight->lastIndex != insertIndex)
  45189. {
  45190. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45191. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45192. showDragHighlight (item, insertIndex, x, y);
  45193. else
  45194. hideDragHighlight();
  45195. }
  45196. }
  45197. else
  45198. {
  45199. hideDragHighlight();
  45200. }
  45201. }
  45202. void TreeView::handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45203. {
  45204. hideDragHighlight();
  45205. int insertIndex;
  45206. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45207. if (item != 0)
  45208. {
  45209. if (files.size() > 0)
  45210. {
  45211. if (item->isInterestedInFileDrag (files))
  45212. item->filesDropped (files, insertIndex);
  45213. }
  45214. else
  45215. {
  45216. if (item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45217. item->itemDropped (sourceDescription, sourceComponent, insertIndex);
  45218. }
  45219. }
  45220. }
  45221. bool TreeView::isInterestedInFileDrag (const StringArray&)
  45222. {
  45223. return true;
  45224. }
  45225. void TreeView::fileDragEnter (const StringArray& files, int x, int y)
  45226. {
  45227. fileDragMove (files, x, y);
  45228. }
  45229. void TreeView::fileDragMove (const StringArray& files, int x, int y)
  45230. {
  45231. handleDrag (files, String::empty, 0, x, y);
  45232. }
  45233. void TreeView::fileDragExit (const StringArray&)
  45234. {
  45235. hideDragHighlight();
  45236. }
  45237. void TreeView::filesDropped (const StringArray& files, int x, int y)
  45238. {
  45239. handleDrop (files, String::empty, 0, x, y);
  45240. }
  45241. bool TreeView::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45242. {
  45243. return true;
  45244. }
  45245. void TreeView::itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45246. {
  45247. itemDragMove (sourceDescription, sourceComponent, x, y);
  45248. }
  45249. void TreeView::itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45250. {
  45251. handleDrag (StringArray(), sourceDescription, sourceComponent, x, y);
  45252. }
  45253. void TreeView::itemDragExit (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45254. {
  45255. hideDragHighlight();
  45256. }
  45257. void TreeView::itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45258. {
  45259. handleDrop (StringArray(), sourceDescription, sourceComponent, x, y);
  45260. }
  45261. enum TreeViewOpenness
  45262. {
  45263. opennessDefault = 0,
  45264. opennessClosed = 1,
  45265. opennessOpen = 2
  45266. };
  45267. TreeViewItem::TreeViewItem()
  45268. : ownerView (0),
  45269. parentItem (0),
  45270. y (0),
  45271. itemHeight (0),
  45272. totalHeight (0),
  45273. selected (false),
  45274. redrawNeeded (true),
  45275. drawLinesInside (true),
  45276. drawsInLeftMargin (false),
  45277. openness (opennessDefault)
  45278. {
  45279. static int nextUID = 0;
  45280. uid = nextUID++;
  45281. }
  45282. TreeViewItem::~TreeViewItem()
  45283. {
  45284. }
  45285. const String TreeViewItem::getUniqueName() const
  45286. {
  45287. return String::empty;
  45288. }
  45289. void TreeViewItem::itemOpennessChanged (bool)
  45290. {
  45291. }
  45292. int TreeViewItem::getNumSubItems() const throw()
  45293. {
  45294. return subItems.size();
  45295. }
  45296. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  45297. {
  45298. return subItems [index];
  45299. }
  45300. void TreeViewItem::clearSubItems()
  45301. {
  45302. if (subItems.size() > 0)
  45303. {
  45304. if (ownerView != 0)
  45305. {
  45306. const ScopedLock sl (ownerView->nodeAlterationLock);
  45307. subItems.clear();
  45308. treeHasChanged();
  45309. }
  45310. else
  45311. {
  45312. subItems.clear();
  45313. }
  45314. }
  45315. }
  45316. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  45317. {
  45318. if (newItem != 0)
  45319. {
  45320. newItem->parentItem = this;
  45321. newItem->setOwnerView (ownerView);
  45322. newItem->y = 0;
  45323. newItem->itemHeight = newItem->getItemHeight();
  45324. newItem->totalHeight = 0;
  45325. newItem->itemWidth = newItem->getItemWidth();
  45326. newItem->totalWidth = 0;
  45327. if (ownerView != 0)
  45328. {
  45329. const ScopedLock sl (ownerView->nodeAlterationLock);
  45330. subItems.insert (insertPosition, newItem);
  45331. treeHasChanged();
  45332. if (newItem->isOpen())
  45333. newItem->itemOpennessChanged (true);
  45334. }
  45335. else
  45336. {
  45337. subItems.insert (insertPosition, newItem);
  45338. if (newItem->isOpen())
  45339. newItem->itemOpennessChanged (true);
  45340. }
  45341. }
  45342. }
  45343. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  45344. {
  45345. if (ownerView != 0)
  45346. {
  45347. const ScopedLock sl (ownerView->nodeAlterationLock);
  45348. if (((unsigned int) index) < (unsigned int) subItems.size())
  45349. {
  45350. subItems.remove (index, deleteItem);
  45351. treeHasChanged();
  45352. }
  45353. }
  45354. else
  45355. {
  45356. subItems.remove (index, deleteItem);
  45357. }
  45358. }
  45359. bool TreeViewItem::isOpen() const throw()
  45360. {
  45361. if (openness == opennessDefault)
  45362. return ownerView != 0 && ownerView->defaultOpenness;
  45363. else
  45364. return openness == opennessOpen;
  45365. }
  45366. void TreeViewItem::setOpen (const bool shouldBeOpen)
  45367. {
  45368. if (isOpen() != shouldBeOpen)
  45369. {
  45370. openness = shouldBeOpen ? opennessOpen
  45371. : opennessClosed;
  45372. treeHasChanged();
  45373. itemOpennessChanged (isOpen());
  45374. }
  45375. }
  45376. bool TreeViewItem::isSelected() const throw()
  45377. {
  45378. return selected;
  45379. }
  45380. void TreeViewItem::deselectAllRecursively()
  45381. {
  45382. setSelected (false, false);
  45383. for (int i = 0; i < subItems.size(); ++i)
  45384. subItems.getUnchecked(i)->deselectAllRecursively();
  45385. }
  45386. void TreeViewItem::setSelected (const bool shouldBeSelected,
  45387. const bool deselectOtherItemsFirst)
  45388. {
  45389. if (shouldBeSelected && ! canBeSelected())
  45390. return;
  45391. if (deselectOtherItemsFirst)
  45392. getTopLevelItem()->deselectAllRecursively();
  45393. if (shouldBeSelected != selected)
  45394. {
  45395. selected = shouldBeSelected;
  45396. if (ownerView != 0)
  45397. ownerView->repaint();
  45398. itemSelectionChanged (shouldBeSelected);
  45399. }
  45400. }
  45401. void TreeViewItem::paintItem (Graphics&, int, int)
  45402. {
  45403. }
  45404. void TreeViewItem::paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver)
  45405. {
  45406. ownerView->getLookAndFeel()
  45407. .drawTreeviewPlusMinusBox (g, 0, 0, width, height, ! isOpen(), isMouseOver);
  45408. }
  45409. void TreeViewItem::itemClicked (const MouseEvent&)
  45410. {
  45411. }
  45412. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  45413. {
  45414. if (mightContainSubItems())
  45415. setOpen (! isOpen());
  45416. }
  45417. void TreeViewItem::itemSelectionChanged (bool)
  45418. {
  45419. }
  45420. const String TreeViewItem::getTooltip()
  45421. {
  45422. return String::empty;
  45423. }
  45424. const String TreeViewItem::getDragSourceDescription()
  45425. {
  45426. return String::empty;
  45427. }
  45428. bool TreeViewItem::isInterestedInFileDrag (const StringArray&)
  45429. {
  45430. return false;
  45431. }
  45432. void TreeViewItem::filesDropped (const StringArray& /*files*/, int /*insertIndex*/)
  45433. {
  45434. }
  45435. bool TreeViewItem::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45436. {
  45437. return false;
  45438. }
  45439. void TreeViewItem::itemDropped (const String& /*sourceDescription*/, Component* /*sourceComponent*/, int /*insertIndex*/)
  45440. {
  45441. }
  45442. const Rectangle<int> TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  45443. {
  45444. const int indentX = getIndentX();
  45445. int width = itemWidth;
  45446. if (ownerView != 0 && width < 0)
  45447. width = ownerView->viewport->getViewWidth() - indentX;
  45448. Rectangle<int> r (indentX, y, jmax (0, width), totalHeight);
  45449. if (relativeToTreeViewTopLeft)
  45450. r -= ownerView->viewport->getViewPosition();
  45451. return r;
  45452. }
  45453. void TreeViewItem::treeHasChanged() const throw()
  45454. {
  45455. if (ownerView != 0)
  45456. ownerView->itemsChanged();
  45457. }
  45458. void TreeViewItem::repaintItem() const
  45459. {
  45460. if (ownerView != 0 && areAllParentsOpen())
  45461. {
  45462. Rectangle<int> r (getItemPosition (true));
  45463. r.setLeft (0);
  45464. ownerView->viewport->repaint (r);
  45465. }
  45466. }
  45467. bool TreeViewItem::areAllParentsOpen() const throw()
  45468. {
  45469. return parentItem == 0
  45470. || (parentItem->isOpen() && parentItem->areAllParentsOpen());
  45471. }
  45472. void TreeViewItem::updatePositions (int newY)
  45473. {
  45474. y = newY;
  45475. itemHeight = getItemHeight();
  45476. totalHeight = itemHeight;
  45477. itemWidth = getItemWidth();
  45478. totalWidth = jmax (itemWidth, 0) + getIndentX();
  45479. if (isOpen())
  45480. {
  45481. newY += totalHeight;
  45482. for (int i = 0; i < subItems.size(); ++i)
  45483. {
  45484. TreeViewItem* const ti = subItems.getUnchecked(i);
  45485. ti->updatePositions (newY);
  45486. newY += ti->totalHeight;
  45487. totalHeight += ti->totalHeight;
  45488. totalWidth = jmax (totalWidth, ti->totalWidth);
  45489. }
  45490. }
  45491. }
  45492. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  45493. {
  45494. TreeViewItem* result = this;
  45495. TreeViewItem* item = this;
  45496. while (item->parentItem != 0)
  45497. {
  45498. item = item->parentItem;
  45499. if (! item->isOpen())
  45500. result = item;
  45501. }
  45502. return result;
  45503. }
  45504. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  45505. {
  45506. ownerView = newOwner;
  45507. for (int i = subItems.size(); --i >= 0;)
  45508. subItems.getUnchecked(i)->setOwnerView (newOwner);
  45509. }
  45510. int TreeViewItem::getIndentX() const throw()
  45511. {
  45512. const int indentWidth = ownerView->getIndentSize();
  45513. int x = ownerView->rootItemVisible ? indentWidth : 0;
  45514. if (! ownerView->openCloseButtonsVisible)
  45515. x -= indentWidth;
  45516. TreeViewItem* p = parentItem;
  45517. while (p != 0)
  45518. {
  45519. x += indentWidth;
  45520. p = p->parentItem;
  45521. }
  45522. return x;
  45523. }
  45524. void TreeViewItem::setDrawsInLeftMargin (bool canDrawInLeftMargin) throw()
  45525. {
  45526. drawsInLeftMargin = canDrawInLeftMargin;
  45527. }
  45528. void TreeViewItem::paintRecursively (Graphics& g, int width)
  45529. {
  45530. jassert (ownerView != 0);
  45531. if (ownerView == 0)
  45532. return;
  45533. const int indent = getIndentX();
  45534. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  45535. g.setColour (ownerView->findColour (TreeView::linesColourId));
  45536. const float halfH = itemHeight * 0.5f;
  45537. int depth = 0;
  45538. TreeViewItem* p = parentItem;
  45539. while (p != 0)
  45540. {
  45541. ++depth;
  45542. p = p->parentItem;
  45543. }
  45544. if (! ownerView->rootItemVisible)
  45545. --depth;
  45546. const int indentWidth = ownerView->getIndentSize();
  45547. if (depth >= 0 && ownerView->openCloseButtonsVisible)
  45548. {
  45549. float x = (depth + 0.5f) * indentWidth;
  45550. if (depth >= 0)
  45551. {
  45552. if (parentItem != 0 && parentItem->drawLinesInside)
  45553. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  45554. if ((parentItem != 0 && parentItem->drawLinesInside)
  45555. || (parentItem == 0 && drawLinesInside))
  45556. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  45557. }
  45558. p = parentItem;
  45559. int d = depth;
  45560. while (p != 0 && --d >= 0)
  45561. {
  45562. x -= (float) indentWidth;
  45563. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  45564. && ! p->isLastOfSiblings())
  45565. {
  45566. g.drawLine (x, 0, x, (float) itemHeight);
  45567. }
  45568. p = p->parentItem;
  45569. }
  45570. if (mightContainSubItems())
  45571. {
  45572. g.saveState();
  45573. g.setOrigin (depth * indentWidth, 0);
  45574. g.reduceClipRegion (0, 0, indentWidth, itemHeight);
  45575. paintOpenCloseButton (g, indentWidth, itemHeight,
  45576. static_cast <TreeViewContentComponent*> (ownerView->viewport->getViewedComponent())
  45577. ->isMouseOverButton (this));
  45578. g.restoreState();
  45579. }
  45580. }
  45581. {
  45582. g.saveState();
  45583. g.setOrigin (indent, 0);
  45584. if (g.reduceClipRegion (drawsInLeftMargin ? -indent : 0, 0,
  45585. drawsInLeftMargin ? itemW + indent : itemW, itemHeight))
  45586. paintItem (g, itemW, itemHeight);
  45587. g.restoreState();
  45588. }
  45589. if (isOpen())
  45590. {
  45591. const Rectangle<int> clip (g.getClipBounds());
  45592. for (int i = 0; i < subItems.size(); ++i)
  45593. {
  45594. TreeViewItem* const ti = subItems.getUnchecked(i);
  45595. const int relY = ti->y - y;
  45596. if (relY >= clip.getBottom())
  45597. break;
  45598. if (relY + ti->totalHeight >= clip.getY())
  45599. {
  45600. g.saveState();
  45601. g.setOrigin (0, relY);
  45602. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  45603. ti->paintRecursively (g, width);
  45604. g.restoreState();
  45605. }
  45606. }
  45607. }
  45608. }
  45609. bool TreeViewItem::isLastOfSiblings() const throw()
  45610. {
  45611. return parentItem == 0
  45612. || parentItem->subItems.getLast() == this;
  45613. }
  45614. int TreeViewItem::getIndexInParent() const throw()
  45615. {
  45616. if (parentItem == 0)
  45617. return 0;
  45618. return parentItem->subItems.indexOf (this);
  45619. }
  45620. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  45621. {
  45622. return (parentItem == 0) ? this
  45623. : parentItem->getTopLevelItem();
  45624. }
  45625. int TreeViewItem::getNumRows() const throw()
  45626. {
  45627. int num = 1;
  45628. if (isOpen())
  45629. {
  45630. for (int i = subItems.size(); --i >= 0;)
  45631. num += subItems.getUnchecked(i)->getNumRows();
  45632. }
  45633. return num;
  45634. }
  45635. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  45636. {
  45637. if (index == 0)
  45638. return this;
  45639. if (index > 0 && isOpen())
  45640. {
  45641. --index;
  45642. for (int i = 0; i < subItems.size(); ++i)
  45643. {
  45644. TreeViewItem* const item = subItems.getUnchecked(i);
  45645. if (index == 0)
  45646. return item;
  45647. const int numRows = item->getNumRows();
  45648. if (numRows > index)
  45649. return item->getItemOnRow (index);
  45650. index -= numRows;
  45651. }
  45652. }
  45653. return 0;
  45654. }
  45655. TreeViewItem* TreeViewItem::findItemRecursively (int targetY) throw()
  45656. {
  45657. if (((unsigned int) targetY) < (unsigned int) totalHeight)
  45658. {
  45659. const int h = itemHeight;
  45660. if (targetY < h)
  45661. return this;
  45662. if (isOpen())
  45663. {
  45664. targetY -= h;
  45665. for (int i = 0; i < subItems.size(); ++i)
  45666. {
  45667. TreeViewItem* const ti = subItems.getUnchecked(i);
  45668. if (targetY < ti->totalHeight)
  45669. return ti->findItemRecursively (targetY);
  45670. targetY -= ti->totalHeight;
  45671. }
  45672. }
  45673. }
  45674. return 0;
  45675. }
  45676. int TreeViewItem::countSelectedItemsRecursively() const throw()
  45677. {
  45678. int total = 0;
  45679. if (isSelected())
  45680. ++total;
  45681. for (int i = subItems.size(); --i >= 0;)
  45682. total += subItems.getUnchecked(i)->countSelectedItemsRecursively();
  45683. return total;
  45684. }
  45685. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  45686. {
  45687. if (isSelected())
  45688. {
  45689. if (index == 0)
  45690. return this;
  45691. --index;
  45692. }
  45693. if (index >= 0)
  45694. {
  45695. for (int i = 0; i < subItems.size(); ++i)
  45696. {
  45697. TreeViewItem* const item = subItems.getUnchecked(i);
  45698. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  45699. if (found != 0)
  45700. return found;
  45701. index -= item->countSelectedItemsRecursively();
  45702. }
  45703. }
  45704. return 0;
  45705. }
  45706. int TreeViewItem::getRowNumberInTree() const throw()
  45707. {
  45708. if (parentItem != 0 && ownerView != 0)
  45709. {
  45710. int n = 1 + parentItem->getRowNumberInTree();
  45711. int ourIndex = parentItem->subItems.indexOf (this);
  45712. jassert (ourIndex >= 0);
  45713. while (--ourIndex >= 0)
  45714. n += parentItem->subItems [ourIndex]->getNumRows();
  45715. if (parentItem->parentItem == 0
  45716. && ! ownerView->rootItemVisible)
  45717. --n;
  45718. return n;
  45719. }
  45720. else
  45721. {
  45722. return 0;
  45723. }
  45724. }
  45725. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  45726. {
  45727. drawLinesInside = drawLines;
  45728. }
  45729. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  45730. {
  45731. if (recurse && isOpen() && subItems.size() > 0)
  45732. return subItems [0];
  45733. if (parentItem != 0)
  45734. {
  45735. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  45736. if (nextIndex >= parentItem->subItems.size())
  45737. return parentItem->getNextVisibleItem (false);
  45738. return parentItem->subItems [nextIndex];
  45739. }
  45740. return 0;
  45741. }
  45742. const String TreeViewItem::getItemIdentifierString() const
  45743. {
  45744. String s;
  45745. if (parentItem != 0)
  45746. s = parentItem->getItemIdentifierString();
  45747. return s + "/" + getUniqueName().replaceCharacter ('/', '\\');
  45748. }
  45749. TreeViewItem* TreeViewItem::findItemFromIdentifierString (const String& identifierString)
  45750. {
  45751. const String thisId (getUniqueName());
  45752. if (thisId == identifierString)
  45753. return this;
  45754. if (identifierString.startsWith (thisId + "/"))
  45755. {
  45756. const String remainingPath (identifierString.substring (thisId.length() + 1));
  45757. bool wasOpen = isOpen();
  45758. setOpen (true);
  45759. for (int i = subItems.size(); --i >= 0;)
  45760. {
  45761. TreeViewItem* item = subItems.getUnchecked(i)->findItemFromIdentifierString (remainingPath);
  45762. if (item != 0)
  45763. return item;
  45764. }
  45765. setOpen (wasOpen);
  45766. }
  45767. return 0;
  45768. }
  45769. void TreeViewItem::restoreOpennessState (const XmlElement& e) throw()
  45770. {
  45771. if (e.hasTagName ("CLOSED"))
  45772. {
  45773. setOpen (false);
  45774. }
  45775. else if (e.hasTagName ("OPEN"))
  45776. {
  45777. setOpen (true);
  45778. forEachXmlChildElement (e, n)
  45779. {
  45780. const String id (n->getStringAttribute ("id"));
  45781. for (int i = 0; i < subItems.size(); ++i)
  45782. {
  45783. TreeViewItem* const ti = subItems.getUnchecked(i);
  45784. if (ti->getUniqueName() == id)
  45785. {
  45786. ti->restoreOpennessState (*n);
  45787. break;
  45788. }
  45789. }
  45790. }
  45791. }
  45792. }
  45793. XmlElement* TreeViewItem::getOpennessState() const throw()
  45794. {
  45795. const String name (getUniqueName());
  45796. if (name.isNotEmpty())
  45797. {
  45798. XmlElement* e;
  45799. if (isOpen())
  45800. {
  45801. e = new XmlElement ("OPEN");
  45802. for (int i = 0; i < subItems.size(); ++i)
  45803. e->addChildElement (subItems.getUnchecked(i)->getOpennessState());
  45804. }
  45805. else
  45806. {
  45807. e = new XmlElement ("CLOSED");
  45808. }
  45809. e->setAttribute ("id", name);
  45810. return e;
  45811. }
  45812. else
  45813. {
  45814. // trying to save the openness for an element that has no name - this won't
  45815. // work because it needs the names to identify what to open.
  45816. jassertfalse;
  45817. }
  45818. return 0;
  45819. }
  45820. END_JUCE_NAMESPACE
  45821. /*** End of inlined file: juce_TreeView.cpp ***/
  45822. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  45823. BEGIN_JUCE_NAMESPACE
  45824. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  45825. : fileList (listToShow)
  45826. {
  45827. }
  45828. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  45829. {
  45830. }
  45831. FileBrowserListener::~FileBrowserListener()
  45832. {
  45833. }
  45834. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener)
  45835. {
  45836. listeners.add (listener);
  45837. }
  45838. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener)
  45839. {
  45840. listeners.remove (listener);
  45841. }
  45842. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  45843. {
  45844. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  45845. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  45846. }
  45847. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  45848. {
  45849. if (fileList.getDirectory().exists())
  45850. {
  45851. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  45852. listeners.callChecked (checker, &FileBrowserListener::fileClicked, file, e);
  45853. }
  45854. }
  45855. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  45856. {
  45857. if (fileList.getDirectory().exists())
  45858. {
  45859. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  45860. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, file);
  45861. }
  45862. }
  45863. END_JUCE_NAMESPACE
  45864. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  45865. /*** Start of inlined file: juce_DirectoryContentsList.cpp ***/
  45866. BEGIN_JUCE_NAMESPACE
  45867. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  45868. TimeSliceThread& thread_)
  45869. : fileFilter (fileFilter_),
  45870. thread (thread_),
  45871. fileTypeFlags (File::ignoreHiddenFiles | File::findFiles),
  45872. fileFindHandle (0),
  45873. shouldStop (true)
  45874. {
  45875. }
  45876. DirectoryContentsList::~DirectoryContentsList()
  45877. {
  45878. clear();
  45879. }
  45880. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  45881. {
  45882. setTypeFlags (shouldIgnoreHiddenFiles ? (fileTypeFlags | File::ignoreHiddenFiles)
  45883. : (fileTypeFlags & ~File::ignoreHiddenFiles));
  45884. }
  45885. bool DirectoryContentsList::ignoresHiddenFiles() const
  45886. {
  45887. return (fileTypeFlags & File::ignoreHiddenFiles) != 0;
  45888. }
  45889. const File& DirectoryContentsList::getDirectory() const
  45890. {
  45891. return root;
  45892. }
  45893. void DirectoryContentsList::setDirectory (const File& directory,
  45894. const bool includeDirectories,
  45895. const bool includeFiles)
  45896. {
  45897. jassert (includeDirectories || includeFiles); // you have to speciify at least one of these!
  45898. if (directory != root)
  45899. {
  45900. clear();
  45901. root = directory;
  45902. // (this forces a refresh when setTypeFlags() is called, rather than triggering two refreshes)
  45903. fileTypeFlags &= ~(File::findDirectories | File::findFiles);
  45904. }
  45905. int newFlags = fileTypeFlags;
  45906. if (includeDirectories) newFlags |= File::findDirectories; else newFlags &= ~File::findDirectories;
  45907. if (includeFiles) newFlags |= File::findFiles; else newFlags &= ~File::findFiles;
  45908. setTypeFlags (newFlags);
  45909. }
  45910. void DirectoryContentsList::setTypeFlags (const int newFlags)
  45911. {
  45912. if (fileTypeFlags != newFlags)
  45913. {
  45914. fileTypeFlags = newFlags;
  45915. refresh();
  45916. }
  45917. }
  45918. void DirectoryContentsList::clear()
  45919. {
  45920. shouldStop = true;
  45921. thread.removeTimeSliceClient (this);
  45922. fileFindHandle = 0;
  45923. if (files.size() > 0)
  45924. {
  45925. files.clear();
  45926. changed();
  45927. }
  45928. }
  45929. void DirectoryContentsList::refresh()
  45930. {
  45931. clear();
  45932. if (root.isDirectory())
  45933. {
  45934. fileFindHandle = new DirectoryIterator (root, false, "*", fileTypeFlags);
  45935. shouldStop = false;
  45936. thread.addTimeSliceClient (this);
  45937. }
  45938. }
  45939. int DirectoryContentsList::getNumFiles() const
  45940. {
  45941. return files.size();
  45942. }
  45943. bool DirectoryContentsList::getFileInfo (const int index,
  45944. FileInfo& result) const
  45945. {
  45946. const ScopedLock sl (fileListLock);
  45947. const FileInfo* const info = files [index];
  45948. if (info != 0)
  45949. {
  45950. result = *info;
  45951. return true;
  45952. }
  45953. return false;
  45954. }
  45955. const File DirectoryContentsList::getFile (const int index) const
  45956. {
  45957. const ScopedLock sl (fileListLock);
  45958. const FileInfo* const info = files [index];
  45959. if (info != 0)
  45960. return root.getChildFile (info->filename);
  45961. return File::nonexistent;
  45962. }
  45963. bool DirectoryContentsList::isStillLoading() const
  45964. {
  45965. return fileFindHandle != 0;
  45966. }
  45967. void DirectoryContentsList::changed()
  45968. {
  45969. sendChangeMessage (this);
  45970. }
  45971. bool DirectoryContentsList::useTimeSlice()
  45972. {
  45973. const uint32 startTime = Time::getApproximateMillisecondCounter();
  45974. bool hasChanged = false;
  45975. for (int i = 100; --i >= 0;)
  45976. {
  45977. if (! checkNextFile (hasChanged))
  45978. {
  45979. if (hasChanged)
  45980. changed();
  45981. return false;
  45982. }
  45983. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  45984. break;
  45985. }
  45986. if (hasChanged)
  45987. changed();
  45988. return true;
  45989. }
  45990. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  45991. {
  45992. if (fileFindHandle != 0)
  45993. {
  45994. bool fileFoundIsDir, isHidden, isReadOnly;
  45995. int64 fileSize;
  45996. Time modTime, creationTime;
  45997. if (fileFindHandle->next (&fileFoundIsDir, &isHidden, &fileSize,
  45998. &modTime, &creationTime, &isReadOnly))
  45999. {
  46000. if (addFile (fileFindHandle->getFile(), fileFoundIsDir,
  46001. fileSize, modTime, creationTime, isReadOnly))
  46002. {
  46003. hasChanged = true;
  46004. }
  46005. return true;
  46006. }
  46007. else
  46008. {
  46009. fileFindHandle = 0;
  46010. }
  46011. }
  46012. return false;
  46013. }
  46014. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  46015. const DirectoryContentsList::FileInfo* const second)
  46016. {
  46017. #if JUCE_WINDOWS
  46018. if (first->isDirectory != second->isDirectory)
  46019. return first->isDirectory ? -1 : 1;
  46020. #endif
  46021. return first->filename.compareIgnoreCase (second->filename);
  46022. }
  46023. bool DirectoryContentsList::addFile (const File& file,
  46024. const bool isDir,
  46025. const int64 fileSize,
  46026. const Time& modTime,
  46027. const Time& creationTime,
  46028. const bool isReadOnly)
  46029. {
  46030. if (fileFilter == 0
  46031. || ((! isDir) && fileFilter->isFileSuitable (file))
  46032. || (isDir && fileFilter->isDirectorySuitable (file)))
  46033. {
  46034. ScopedPointer <FileInfo> info (new FileInfo());
  46035. info->filename = file.getFileName();
  46036. info->fileSize = fileSize;
  46037. info->modificationTime = modTime;
  46038. info->creationTime = creationTime;
  46039. info->isDirectory = isDir;
  46040. info->isReadOnly = isReadOnly;
  46041. const ScopedLock sl (fileListLock);
  46042. for (int i = files.size(); --i >= 0;)
  46043. if (files.getUnchecked(i)->filename == info->filename)
  46044. return false;
  46045. files.addSorted (*this, info.release());
  46046. return true;
  46047. }
  46048. return false;
  46049. }
  46050. END_JUCE_NAMESPACE
  46051. /*** End of inlined file: juce_DirectoryContentsList.cpp ***/
  46052. /*** Start of inlined file: juce_FileBrowserComponent.cpp ***/
  46053. BEGIN_JUCE_NAMESPACE
  46054. FileBrowserComponent::FileBrowserComponent (int flags_,
  46055. const File& initialFileOrDirectory,
  46056. const FileFilter* fileFilter_,
  46057. FilePreviewComponent* previewComp_)
  46058. : FileFilter (String::empty),
  46059. fileFilter (fileFilter_),
  46060. flags (flags_),
  46061. previewComp (previewComp_),
  46062. thread ("Juce FileBrowser")
  46063. {
  46064. // You need to specify one or other of the open/save flags..
  46065. jassert ((flags & (saveMode | openMode)) != 0);
  46066. jassert ((flags & (saveMode | openMode)) != (saveMode | openMode));
  46067. // You need to specify at least one of these flags..
  46068. jassert ((flags & (canSelectFiles | canSelectDirectories)) != 0);
  46069. String filename;
  46070. if (initialFileOrDirectory == File::nonexistent)
  46071. {
  46072. currentRoot = File::getCurrentWorkingDirectory();
  46073. }
  46074. else if (initialFileOrDirectory.isDirectory())
  46075. {
  46076. currentRoot = initialFileOrDirectory;
  46077. }
  46078. else
  46079. {
  46080. chosenFiles.add (initialFileOrDirectory);
  46081. currentRoot = initialFileOrDirectory.getParentDirectory();
  46082. filename = initialFileOrDirectory.getFileName();
  46083. }
  46084. fileList = new DirectoryContentsList (this, thread);
  46085. if ((flags & useTreeView) != 0)
  46086. {
  46087. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  46088. if ((flags & canSelectMultipleItems) != 0)
  46089. tree->setMultiSelectEnabled (true);
  46090. addAndMakeVisible (tree);
  46091. fileListComponent = tree;
  46092. }
  46093. else
  46094. {
  46095. FileListComponent* const list = new FileListComponent (*fileList);
  46096. list->setOutlineThickness (1);
  46097. if ((flags & canSelectMultipleItems) != 0)
  46098. list->setMultipleSelectionEnabled (true);
  46099. addAndMakeVisible (list);
  46100. fileListComponent = list;
  46101. }
  46102. fileListComponent->addListener (this);
  46103. addAndMakeVisible (currentPathBox = new ComboBox ("path"));
  46104. currentPathBox->setEditableText (true);
  46105. StringArray rootNames, rootPaths;
  46106. const BigInteger separators (getRoots (rootNames, rootPaths));
  46107. for (int i = 0; i < rootNames.size(); ++i)
  46108. {
  46109. if (separators [i])
  46110. currentPathBox->addSeparator();
  46111. currentPathBox->addItem (rootNames[i], i + 1);
  46112. }
  46113. currentPathBox->addSeparator();
  46114. currentPathBox->addListener (this);
  46115. addAndMakeVisible (filenameBox = new TextEditor());
  46116. filenameBox->setMultiLine (false);
  46117. filenameBox->setSelectAllWhenFocused (true);
  46118. filenameBox->setText (filename, false);
  46119. filenameBox->addListener (this);
  46120. filenameBox->setReadOnly ((flags & (filenameBoxIsReadOnly | canSelectMultipleItems)) != 0);
  46121. Label* label = new Label ("f", TRANS("file:"));
  46122. addAndMakeVisible (label);
  46123. label->attachToComponent (filenameBox, true);
  46124. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  46125. goUpButton->addButtonListener (this);
  46126. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  46127. if (previewComp != 0)
  46128. addAndMakeVisible (previewComp);
  46129. setRoot (currentRoot);
  46130. thread.startThread (4);
  46131. }
  46132. FileBrowserComponent::~FileBrowserComponent()
  46133. {
  46134. if (previewComp != 0)
  46135. removeChildComponent (previewComp);
  46136. deleteAllChildren();
  46137. fileList = 0;
  46138. thread.stopThread (10000);
  46139. }
  46140. void FileBrowserComponent::addListener (FileBrowserListener* const newListener)
  46141. {
  46142. listeners.add (newListener);
  46143. }
  46144. void FileBrowserComponent::removeListener (FileBrowserListener* const listener)
  46145. {
  46146. listeners.remove (listener);
  46147. }
  46148. bool FileBrowserComponent::isSaveMode() const throw()
  46149. {
  46150. return (flags & saveMode) != 0;
  46151. }
  46152. int FileBrowserComponent::getNumSelectedFiles() const throw()
  46153. {
  46154. if (chosenFiles.size() == 0 && currentFileIsValid())
  46155. return 1;
  46156. return chosenFiles.size();
  46157. }
  46158. const File FileBrowserComponent::getSelectedFile (int index) const throw()
  46159. {
  46160. if ((flags & canSelectDirectories) != 0 && filenameBox->getText().isEmpty())
  46161. return currentRoot;
  46162. if (! filenameBox->isReadOnly())
  46163. return currentRoot.getChildFile (filenameBox->getText());
  46164. return chosenFiles[index];
  46165. }
  46166. bool FileBrowserComponent::currentFileIsValid() const
  46167. {
  46168. if (isSaveMode())
  46169. return ! getSelectedFile (0).isDirectory();
  46170. else
  46171. return getSelectedFile (0).exists();
  46172. }
  46173. const File FileBrowserComponent::getHighlightedFile() const throw()
  46174. {
  46175. return fileListComponent->getSelectedFile (0);
  46176. }
  46177. void FileBrowserComponent::deselectAllFiles()
  46178. {
  46179. fileListComponent->deselectAllFiles();
  46180. }
  46181. bool FileBrowserComponent::isFileSuitable (const File& file) const
  46182. {
  46183. return (flags & canSelectFiles) != 0 ? (fileFilter == 0 || fileFilter->isFileSuitable (file))
  46184. : false;
  46185. }
  46186. bool FileBrowserComponent::isDirectorySuitable (const File&) const
  46187. {
  46188. return true;
  46189. }
  46190. bool FileBrowserComponent::isFileOrDirSuitable (const File& f) const
  46191. {
  46192. if (f.isDirectory())
  46193. return (flags & canSelectDirectories) != 0 && (fileFilter == 0 || fileFilter->isDirectorySuitable (f));
  46194. return (flags & canSelectFiles) != 0 && f.exists()
  46195. && (fileFilter == 0 || fileFilter->isFileSuitable (f));
  46196. }
  46197. const File FileBrowserComponent::getRoot() const
  46198. {
  46199. return currentRoot;
  46200. }
  46201. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  46202. {
  46203. if (currentRoot != newRootDirectory)
  46204. {
  46205. fileListComponent->scrollToTop();
  46206. String path (newRootDirectory.getFullPathName());
  46207. if (path.isEmpty())
  46208. path = File::separatorString;
  46209. StringArray rootNames, rootPaths;
  46210. getRoots (rootNames, rootPaths);
  46211. if (! rootPaths.contains (path, true))
  46212. {
  46213. bool alreadyListed = false;
  46214. for (int i = currentPathBox->getNumItems(); --i >= 0;)
  46215. {
  46216. if (currentPathBox->getItemText (i).equalsIgnoreCase (path))
  46217. {
  46218. alreadyListed = true;
  46219. break;
  46220. }
  46221. }
  46222. if (! alreadyListed)
  46223. currentPathBox->addItem (path, currentPathBox->getNumItems() + 2);
  46224. }
  46225. }
  46226. currentRoot = newRootDirectory;
  46227. fileList->setDirectory (currentRoot, true, true);
  46228. String currentRootName (currentRoot.getFullPathName());
  46229. if (currentRootName.isEmpty())
  46230. currentRootName = File::separatorString;
  46231. currentPathBox->setText (currentRootName, true);
  46232. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  46233. && currentRoot.getParentDirectory() != currentRoot);
  46234. }
  46235. void FileBrowserComponent::goUp()
  46236. {
  46237. setRoot (getRoot().getParentDirectory());
  46238. }
  46239. void FileBrowserComponent::refresh()
  46240. {
  46241. fileList->refresh();
  46242. }
  46243. const String FileBrowserComponent::getActionVerb() const
  46244. {
  46245. return isSaveMode() ? TRANS("Save") : TRANS("Open");
  46246. }
  46247. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  46248. {
  46249. return previewComp;
  46250. }
  46251. void FileBrowserComponent::resized()
  46252. {
  46253. getLookAndFeel()
  46254. .layoutFileBrowserComponent (*this, fileListComponent,
  46255. previewComp, currentPathBox,
  46256. filenameBox, goUpButton);
  46257. }
  46258. void FileBrowserComponent::sendListenerChangeMessage()
  46259. {
  46260. Component::BailOutChecker checker (this);
  46261. if (previewComp != 0)
  46262. previewComp->selectedFileChanged (getSelectedFile (0));
  46263. // You shouldn't delete the browser when the file gets changed!
  46264. jassert (! checker.shouldBailOut());
  46265. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46266. }
  46267. void FileBrowserComponent::selectionChanged()
  46268. {
  46269. StringArray newFilenames;
  46270. bool resetChosenFiles = true;
  46271. for (int i = 0; i < fileListComponent->getNumSelectedFiles(); ++i)
  46272. {
  46273. const File f (fileListComponent->getSelectedFile (i));
  46274. if (isFileOrDirSuitable (f))
  46275. {
  46276. if (resetChosenFiles)
  46277. {
  46278. chosenFiles.clear();
  46279. resetChosenFiles = false;
  46280. }
  46281. chosenFiles.add (f);
  46282. newFilenames.add (f.getRelativePathFrom (getRoot()));
  46283. }
  46284. }
  46285. if (newFilenames.size() > 0)
  46286. filenameBox->setText (newFilenames.joinIntoString (", "), false);
  46287. sendListenerChangeMessage();
  46288. }
  46289. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  46290. {
  46291. Component::BailOutChecker checker (this);
  46292. listeners.callChecked (checker, &FileBrowserListener::fileClicked, f, e);
  46293. }
  46294. void FileBrowserComponent::fileDoubleClicked (const File& f)
  46295. {
  46296. if (f.isDirectory())
  46297. {
  46298. setRoot (f);
  46299. if ((flags & canSelectDirectories) != 0)
  46300. filenameBox->setText (String::empty);
  46301. }
  46302. else
  46303. {
  46304. Component::BailOutChecker checker (this);
  46305. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, f);
  46306. }
  46307. }
  46308. bool FileBrowserComponent::keyPressed (const KeyPress& key)
  46309. {
  46310. (void) key;
  46311. #if JUCE_LINUX || JUCE_WINDOWS
  46312. if (key.getModifiers().isCommandDown()
  46313. && (key.getKeyCode() == 'H' || key.getKeyCode() == 'h'))
  46314. {
  46315. fileList->setIgnoresHiddenFiles (! fileList->ignoresHiddenFiles());
  46316. fileList->refresh();
  46317. return true;
  46318. }
  46319. #endif
  46320. return false;
  46321. }
  46322. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  46323. {
  46324. sendListenerChangeMessage();
  46325. }
  46326. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  46327. {
  46328. if (filenameBox->getText().containsChar (File::separator))
  46329. {
  46330. const File f (currentRoot.getChildFile (filenameBox->getText()));
  46331. if (f.isDirectory())
  46332. {
  46333. setRoot (f);
  46334. chosenFiles.clear();
  46335. filenameBox->setText (String::empty);
  46336. }
  46337. else
  46338. {
  46339. setRoot (f.getParentDirectory());
  46340. chosenFiles.clear();
  46341. chosenFiles.add (f);
  46342. filenameBox->setText (f.getFileName());
  46343. }
  46344. }
  46345. else
  46346. {
  46347. fileDoubleClicked (getSelectedFile (0));
  46348. }
  46349. }
  46350. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  46351. {
  46352. }
  46353. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  46354. {
  46355. if (! isSaveMode())
  46356. selectionChanged();
  46357. }
  46358. void FileBrowserComponent::buttonClicked (Button*)
  46359. {
  46360. goUp();
  46361. }
  46362. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  46363. {
  46364. const String newText (currentPathBox->getText().trim().unquoted());
  46365. if (newText.isNotEmpty())
  46366. {
  46367. const int index = currentPathBox->getSelectedId() - 1;
  46368. StringArray rootNames, rootPaths;
  46369. getRoots (rootNames, rootPaths);
  46370. if (rootPaths [index].isNotEmpty())
  46371. {
  46372. setRoot (File (rootPaths [index]));
  46373. }
  46374. else
  46375. {
  46376. File f (newText);
  46377. for (;;)
  46378. {
  46379. if (f.isDirectory())
  46380. {
  46381. setRoot (f);
  46382. break;
  46383. }
  46384. if (f.getParentDirectory() == f)
  46385. break;
  46386. f = f.getParentDirectory();
  46387. }
  46388. }
  46389. }
  46390. }
  46391. const BigInteger FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  46392. {
  46393. BigInteger separators;
  46394. #if JUCE_WINDOWS
  46395. Array<File> roots;
  46396. File::findFileSystemRoots (roots);
  46397. rootPaths.clear();
  46398. for (int i = 0; i < roots.size(); ++i)
  46399. {
  46400. const File& drive = roots.getReference(i);
  46401. String name (drive.getFullPathName());
  46402. rootPaths.add (name);
  46403. if (drive.isOnHardDisk())
  46404. {
  46405. String volume (drive.getVolumeLabel());
  46406. if (volume.isEmpty())
  46407. volume = TRANS("Hard Drive");
  46408. name << " [" << drive.getVolumeLabel() << ']';
  46409. }
  46410. else if (drive.isOnCDRomDrive())
  46411. {
  46412. name << TRANS(" [CD/DVD drive]");
  46413. }
  46414. rootNames.add (name);
  46415. }
  46416. separators.setBit (rootPaths.size());
  46417. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  46418. rootNames.add ("Documents");
  46419. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46420. rootNames.add ("Desktop");
  46421. #endif
  46422. #if JUCE_MAC
  46423. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  46424. rootNames.add ("Home folder");
  46425. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  46426. rootNames.add ("Documents");
  46427. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46428. rootNames.add ("Desktop");
  46429. separators.setBit (rootPaths.size());
  46430. Array <File> volumes;
  46431. File vol ("/Volumes");
  46432. vol.findChildFiles (volumes, File::findDirectories, false);
  46433. for (int i = 0; i < volumes.size(); ++i)
  46434. {
  46435. const File& volume = volumes.getReference(i);
  46436. if (volume.isDirectory() && ! volume.getFileName().startsWithChar ('.'))
  46437. {
  46438. rootPaths.add (volume.getFullPathName());
  46439. rootNames.add (volume.getFileName());
  46440. }
  46441. }
  46442. #endif
  46443. #if JUCE_LINUX
  46444. rootPaths.add ("/");
  46445. rootNames.add ("/");
  46446. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  46447. rootNames.add ("Home folder");
  46448. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46449. rootNames.add ("Desktop");
  46450. #endif
  46451. return separators;
  46452. }
  46453. END_JUCE_NAMESPACE
  46454. /*** End of inlined file: juce_FileBrowserComponent.cpp ***/
  46455. /*** Start of inlined file: juce_FileChooser.cpp ***/
  46456. BEGIN_JUCE_NAMESPACE
  46457. FileChooser::FileChooser (const String& chooserBoxTitle,
  46458. const File& currentFileOrDirectory,
  46459. const String& fileFilters,
  46460. const bool useNativeDialogBox_)
  46461. : title (chooserBoxTitle),
  46462. filters (fileFilters),
  46463. startingFile (currentFileOrDirectory),
  46464. useNativeDialogBox (useNativeDialogBox_)
  46465. {
  46466. #if JUCE_LINUX
  46467. useNativeDialogBox = false;
  46468. #endif
  46469. if (! fileFilters.containsNonWhitespaceChars())
  46470. filters = "*";
  46471. }
  46472. FileChooser::~FileChooser()
  46473. {
  46474. }
  46475. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  46476. {
  46477. return showDialog (false, true, false, false, false, previewComponent);
  46478. }
  46479. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  46480. {
  46481. return showDialog (false, true, false, false, true, previewComponent);
  46482. }
  46483. bool FileChooser::browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent)
  46484. {
  46485. return showDialog (true, true, false, false, true, previewComponent);
  46486. }
  46487. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  46488. {
  46489. return showDialog (false, true, true, warnAboutOverwritingExistingFiles, false, 0);
  46490. }
  46491. bool FileChooser::browseForDirectory()
  46492. {
  46493. return showDialog (true, false, false, false, false, 0);
  46494. }
  46495. const File FileChooser::getResult() const
  46496. {
  46497. // if you've used a multiple-file select, you should use the getResults() method
  46498. // to retrieve all the files that were chosen.
  46499. jassert (results.size() <= 1);
  46500. return results.getFirst();
  46501. }
  46502. const Array<File>& FileChooser::getResults() const
  46503. {
  46504. return results;
  46505. }
  46506. bool FileChooser::showDialog (const bool selectsDirectories,
  46507. const bool selectsFiles,
  46508. const bool isSave,
  46509. const bool warnAboutOverwritingExistingFiles,
  46510. const bool selectMultipleFiles,
  46511. FilePreviewComponent* const previewComponent)
  46512. {
  46513. Component::SafePointer<Component> previouslyFocused (Component::getCurrentlyFocusedComponent());
  46514. results.clear();
  46515. // the preview component needs to be the right size before you pass it in here..
  46516. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  46517. && previewComponent->getHeight() > 10));
  46518. #if JUCE_WINDOWS
  46519. if (useNativeDialogBox && ! (selectsFiles && selectsDirectories))
  46520. #elif JUCE_MAC
  46521. if (useNativeDialogBox && (previewComponent == 0))
  46522. #else
  46523. if (false)
  46524. #endif
  46525. {
  46526. showPlatformDialog (results, title, startingFile, filters,
  46527. selectsDirectories, selectsFiles, isSave,
  46528. warnAboutOverwritingExistingFiles,
  46529. selectMultipleFiles,
  46530. previewComponent);
  46531. }
  46532. else
  46533. {
  46534. WildcardFileFilter wildcard (selectsFiles ? filters : String::empty,
  46535. selectsDirectories ? "*" : String::empty,
  46536. String::empty);
  46537. int flags = isSave ? FileBrowserComponent::saveMode
  46538. : FileBrowserComponent::openMode;
  46539. if (selectsFiles)
  46540. flags |= FileBrowserComponent::canSelectFiles;
  46541. if (selectsDirectories)
  46542. {
  46543. flags |= FileBrowserComponent::canSelectDirectories;
  46544. if (! isSave)
  46545. flags |= FileBrowserComponent::filenameBoxIsReadOnly;
  46546. }
  46547. if (selectMultipleFiles)
  46548. flags |= FileBrowserComponent::canSelectMultipleItems;
  46549. FileBrowserComponent browserComponent (flags, startingFile, &wildcard, previewComponent);
  46550. FileChooserDialogBox box (title, String::empty,
  46551. browserComponent,
  46552. warnAboutOverwritingExistingFiles,
  46553. browserComponent.findColour (AlertWindow::backgroundColourId));
  46554. if (box.show())
  46555. {
  46556. for (int i = 0; i < browserComponent.getNumSelectedFiles(); ++i)
  46557. results.add (browserComponent.getSelectedFile (i));
  46558. }
  46559. }
  46560. if (previouslyFocused != 0)
  46561. previouslyFocused->grabKeyboardFocus();
  46562. return results.size() > 0;
  46563. }
  46564. FilePreviewComponent::FilePreviewComponent()
  46565. {
  46566. }
  46567. FilePreviewComponent::~FilePreviewComponent()
  46568. {
  46569. }
  46570. END_JUCE_NAMESPACE
  46571. /*** End of inlined file: juce_FileChooser.cpp ***/
  46572. /*** Start of inlined file: juce_FileChooserDialogBox.cpp ***/
  46573. BEGIN_JUCE_NAMESPACE
  46574. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  46575. const String& instructions,
  46576. FileBrowserComponent& chooserComponent,
  46577. const bool warnAboutOverwritingExistingFiles_,
  46578. const Colour& backgroundColour)
  46579. : ResizableWindow (name, backgroundColour, true),
  46580. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  46581. {
  46582. content = new ContentComponent();
  46583. content->setName (name);
  46584. content->instructions = instructions;
  46585. content->chooserComponent = &chooserComponent;
  46586. content->addAndMakeVisible (&chooserComponent);
  46587. content->okButton = new TextButton (chooserComponent.getActionVerb());
  46588. content->addAndMakeVisible (content->okButton);
  46589. content->okButton->addButtonListener (this);
  46590. content->okButton->setEnabled (chooserComponent.currentFileIsValid());
  46591. content->okButton->addShortcut (KeyPress (KeyPress::returnKey, 0, 0));
  46592. content->cancelButton = new TextButton (TRANS("Cancel"));
  46593. content->addAndMakeVisible (content->cancelButton);
  46594. content->cancelButton->addButtonListener (this);
  46595. content->cancelButton->addShortcut (KeyPress (KeyPress::escapeKey, 0, 0));
  46596. setContentComponent (content);
  46597. setResizable (true, true);
  46598. setResizeLimits (300, 300, 1200, 1000);
  46599. content->chooserComponent->addListener (this);
  46600. }
  46601. FileChooserDialogBox::~FileChooserDialogBox()
  46602. {
  46603. content->chooserComponent->removeListener (this);
  46604. }
  46605. bool FileChooserDialogBox::show (int w, int h)
  46606. {
  46607. return showAt (-1, -1, w, h);
  46608. }
  46609. bool FileChooserDialogBox::showAt (int x, int y, int w, int h)
  46610. {
  46611. if (w <= 0)
  46612. {
  46613. Component* const previewComp = content->chooserComponent->getPreviewComponent();
  46614. if (previewComp != 0)
  46615. w = 400 + previewComp->getWidth();
  46616. else
  46617. w = 600;
  46618. }
  46619. if (h <= 0)
  46620. h = 500;
  46621. if (x < 0 || y < 0)
  46622. centreWithSize (w, h);
  46623. else
  46624. setBounds (x, y, w, h);
  46625. const bool ok = (runModalLoop() != 0);
  46626. setVisible (false);
  46627. return ok;
  46628. }
  46629. void FileChooserDialogBox::buttonClicked (Button* button)
  46630. {
  46631. if (button == content->okButton)
  46632. {
  46633. if (warnAboutOverwritingExistingFiles
  46634. && content->chooserComponent->isSaveMode()
  46635. && content->chooserComponent->getSelectedFile(0).exists())
  46636. {
  46637. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  46638. TRANS("File already exists"),
  46639. TRANS("There's already a file called:")
  46640. + "\n\n" + content->chooserComponent->getSelectedFile(0).getFullPathName()
  46641. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  46642. TRANS("overwrite"),
  46643. TRANS("cancel")))
  46644. {
  46645. return;
  46646. }
  46647. }
  46648. exitModalState (1);
  46649. }
  46650. else if (button == content->cancelButton)
  46651. closeButtonPressed();
  46652. }
  46653. void FileChooserDialogBox::closeButtonPressed()
  46654. {
  46655. setVisible (false);
  46656. }
  46657. void FileChooserDialogBox::selectionChanged()
  46658. {
  46659. content->okButton->setEnabled (content->chooserComponent->currentFileIsValid());
  46660. }
  46661. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  46662. {
  46663. }
  46664. void FileChooserDialogBox::fileDoubleClicked (const File&)
  46665. {
  46666. selectionChanged();
  46667. content->okButton->triggerClick();
  46668. }
  46669. FileChooserDialogBox::ContentComponent::ContentComponent()
  46670. {
  46671. setInterceptsMouseClicks (false, true);
  46672. }
  46673. FileChooserDialogBox::ContentComponent::~ContentComponent()
  46674. {
  46675. delete okButton;
  46676. delete cancelButton;
  46677. }
  46678. void FileChooserDialogBox::ContentComponent::paint (Graphics& g)
  46679. {
  46680. g.setColour (getLookAndFeel().findColour (FileChooserDialogBox::titleTextColourId));
  46681. text.draw (g);
  46682. }
  46683. void FileChooserDialogBox::ContentComponent::resized()
  46684. {
  46685. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  46686. const Rectangle<float> bb (text.getBoundingBox (0, text.getNumGlyphs(), false));
  46687. const int y = roundToInt (bb.getBottom()) + 10;
  46688. const int buttonHeight = 26;
  46689. const int buttonY = getHeight() - buttonHeight - 8;
  46690. chooserComponent->setBounds (0, y, getWidth(), buttonY - y - 20);
  46691. okButton->setBounds (proportionOfWidth (0.25f), buttonY,
  46692. proportionOfWidth (0.2f), buttonHeight);
  46693. cancelButton->setBounds (proportionOfWidth (0.55f), buttonY,
  46694. proportionOfWidth (0.2f), buttonHeight);
  46695. }
  46696. END_JUCE_NAMESPACE
  46697. /*** End of inlined file: juce_FileChooserDialogBox.cpp ***/
  46698. /*** Start of inlined file: juce_FileFilter.cpp ***/
  46699. BEGIN_JUCE_NAMESPACE
  46700. FileFilter::FileFilter (const String& filterDescription)
  46701. : description (filterDescription)
  46702. {
  46703. }
  46704. FileFilter::~FileFilter()
  46705. {
  46706. }
  46707. const String& FileFilter::getDescription() const throw()
  46708. {
  46709. return description;
  46710. }
  46711. END_JUCE_NAMESPACE
  46712. /*** End of inlined file: juce_FileFilter.cpp ***/
  46713. /*** Start of inlined file: juce_FileListComponent.cpp ***/
  46714. BEGIN_JUCE_NAMESPACE
  46715. const Image juce_createIconForFile (const File& file);
  46716. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  46717. : ListBox (String::empty, 0),
  46718. DirectoryContentsDisplayComponent (listToShow)
  46719. {
  46720. setModel (this);
  46721. fileList.addChangeListener (this);
  46722. }
  46723. FileListComponent::~FileListComponent()
  46724. {
  46725. fileList.removeChangeListener (this);
  46726. deleteAllChildren();
  46727. }
  46728. int FileListComponent::getNumSelectedFiles() const
  46729. {
  46730. return getNumSelectedRows();
  46731. }
  46732. const File FileListComponent::getSelectedFile (int index) const
  46733. {
  46734. return fileList.getFile (getSelectedRow (index));
  46735. }
  46736. void FileListComponent::deselectAllFiles()
  46737. {
  46738. deselectAllRows();
  46739. }
  46740. void FileListComponent::scrollToTop()
  46741. {
  46742. getVerticalScrollBar()->setCurrentRangeStart (0);
  46743. }
  46744. void FileListComponent::changeListenerCallback (void*)
  46745. {
  46746. updateContent();
  46747. if (lastDirectory != fileList.getDirectory())
  46748. {
  46749. lastDirectory = fileList.getDirectory();
  46750. deselectAllRows();
  46751. }
  46752. }
  46753. class FileListItemComponent : public Component,
  46754. public TimeSliceClient,
  46755. public AsyncUpdater
  46756. {
  46757. public:
  46758. FileListItemComponent (FileListComponent& owner_, TimeSliceThread& thread_)
  46759. : owner (owner_), thread (thread_),
  46760. highlighted (false), index (0), icon (0)
  46761. {
  46762. }
  46763. ~FileListItemComponent()
  46764. {
  46765. thread.removeTimeSliceClient (this);
  46766. clearIcon();
  46767. }
  46768. void paint (Graphics& g)
  46769. {
  46770. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  46771. file.getFileName(),
  46772. &icon,
  46773. fileSize, modTime,
  46774. isDirectory, highlighted,
  46775. index);
  46776. }
  46777. void mouseDown (const MouseEvent& e)
  46778. {
  46779. owner.selectRowsBasedOnModifierKeys (index, e.mods);
  46780. owner.sendMouseClickMessage (file, e);
  46781. }
  46782. void mouseDoubleClick (const MouseEvent&)
  46783. {
  46784. owner.sendDoubleClickMessage (file);
  46785. }
  46786. void update (const File& root,
  46787. const DirectoryContentsList::FileInfo* const fileInfo,
  46788. const int index_,
  46789. const bool highlighted_)
  46790. {
  46791. thread.removeTimeSliceClient (this);
  46792. if (highlighted_ != highlighted
  46793. || index_ != index)
  46794. {
  46795. index = index_;
  46796. highlighted = highlighted_;
  46797. repaint();
  46798. }
  46799. File newFile;
  46800. String newFileSize;
  46801. String newModTime;
  46802. if (fileInfo != 0)
  46803. {
  46804. newFile = root.getChildFile (fileInfo->filename);
  46805. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  46806. newModTime = fileInfo->modificationTime.formatted ("%d %b '%y %H:%M");
  46807. }
  46808. if (newFile != file
  46809. || fileSize != newFileSize
  46810. || modTime != newModTime)
  46811. {
  46812. file = newFile;
  46813. fileSize = newFileSize;
  46814. modTime = newModTime;
  46815. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  46816. repaint();
  46817. clearIcon();
  46818. }
  46819. if (file != File::nonexistent && icon.isNull() && ! isDirectory)
  46820. {
  46821. updateIcon (true);
  46822. if (! icon.isValid())
  46823. thread.addTimeSliceClient (this);
  46824. }
  46825. }
  46826. bool useTimeSlice()
  46827. {
  46828. updateIcon (false);
  46829. return false;
  46830. }
  46831. void handleAsyncUpdate()
  46832. {
  46833. repaint();
  46834. }
  46835. juce_UseDebuggingNewOperator
  46836. private:
  46837. FileListComponent& owner;
  46838. TimeSliceThread& thread;
  46839. bool highlighted;
  46840. int index;
  46841. File file;
  46842. String fileSize;
  46843. String modTime;
  46844. Image icon;
  46845. bool isDirectory;
  46846. void clearIcon()
  46847. {
  46848. icon = Image();
  46849. }
  46850. void updateIcon (const bool onlyUpdateIfCached)
  46851. {
  46852. if (icon.isNull())
  46853. {
  46854. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  46855. Image im (ImageCache::getFromHashCode (hashCode));
  46856. if (im.isNull() && ! onlyUpdateIfCached)
  46857. {
  46858. im = juce_createIconForFile (file);
  46859. if (im.isValid())
  46860. ImageCache::addImageToCache (im, hashCode);
  46861. }
  46862. if (im.isValid())
  46863. {
  46864. icon = im;
  46865. triggerAsyncUpdate();
  46866. }
  46867. }
  46868. }
  46869. };
  46870. int FileListComponent::getNumRows()
  46871. {
  46872. return fileList.getNumFiles();
  46873. }
  46874. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  46875. {
  46876. }
  46877. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  46878. {
  46879. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  46880. if (comp == 0)
  46881. {
  46882. delete existingComponentToUpdate;
  46883. comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  46884. }
  46885. DirectoryContentsList::FileInfo fileInfo;
  46886. if (fileList.getFileInfo (row, fileInfo))
  46887. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  46888. else
  46889. comp->update (fileList.getDirectory(), 0, row, isSelected);
  46890. return comp;
  46891. }
  46892. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  46893. {
  46894. sendSelectionChangeMessage();
  46895. }
  46896. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  46897. {
  46898. }
  46899. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  46900. {
  46901. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  46902. }
  46903. END_JUCE_NAMESPACE
  46904. /*** End of inlined file: juce_FileListComponent.cpp ***/
  46905. /*** Start of inlined file: juce_FilenameComponent.cpp ***/
  46906. BEGIN_JUCE_NAMESPACE
  46907. FilenameComponent::FilenameComponent (const String& name,
  46908. const File& currentFile,
  46909. const bool canEditFilename,
  46910. const bool isDirectory,
  46911. const bool isForSaving,
  46912. const String& fileBrowserWildcard,
  46913. const String& enforcedSuffix_,
  46914. const String& textWhenNothingSelected)
  46915. : Component (name),
  46916. maxRecentFiles (30),
  46917. isDir (isDirectory),
  46918. isSaving (isForSaving),
  46919. isFileDragOver (false),
  46920. wildcard (fileBrowserWildcard),
  46921. enforcedSuffix (enforcedSuffix_)
  46922. {
  46923. addAndMakeVisible (&filenameBox);
  46924. filenameBox.setEditableText (canEditFilename);
  46925. filenameBox.addListener (this);
  46926. filenameBox.setTextWhenNothingSelected (textWhenNothingSelected);
  46927. filenameBox.setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  46928. setBrowseButtonText ("...");
  46929. setCurrentFile (currentFile, true);
  46930. }
  46931. FilenameComponent::~FilenameComponent()
  46932. {
  46933. }
  46934. void FilenameComponent::paintOverChildren (Graphics& g)
  46935. {
  46936. if (isFileDragOver)
  46937. {
  46938. g.setColour (Colours::red.withAlpha (0.2f));
  46939. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  46940. }
  46941. }
  46942. void FilenameComponent::resized()
  46943. {
  46944. getLookAndFeel().layoutFilenameComponent (*this, &filenameBox, browseButton);
  46945. }
  46946. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  46947. {
  46948. browseButtonText = newBrowseButtonText;
  46949. lookAndFeelChanged();
  46950. }
  46951. void FilenameComponent::lookAndFeelChanged()
  46952. {
  46953. browseButton = 0;
  46954. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  46955. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  46956. resized();
  46957. browseButton->addButtonListener (this);
  46958. }
  46959. void FilenameComponent::setTooltip (const String& newTooltip)
  46960. {
  46961. SettableTooltipClient::setTooltip (newTooltip);
  46962. filenameBox.setTooltip (newTooltip);
  46963. }
  46964. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  46965. {
  46966. defaultBrowseFile = newDefaultDirectory;
  46967. }
  46968. void FilenameComponent::buttonClicked (Button*)
  46969. {
  46970. FileChooser fc (TRANS("Choose a new file"),
  46971. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  46972. : getCurrentFile(),
  46973. wildcard);
  46974. if (isDir ? fc.browseForDirectory()
  46975. : (isSaving ? fc.browseForFileToSave (false)
  46976. : fc.browseForFileToOpen()))
  46977. {
  46978. setCurrentFile (fc.getResult(), true);
  46979. }
  46980. }
  46981. void FilenameComponent::comboBoxChanged (ComboBox*)
  46982. {
  46983. setCurrentFile (getCurrentFile(), true);
  46984. }
  46985. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  46986. {
  46987. return true;
  46988. }
  46989. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  46990. {
  46991. isFileDragOver = false;
  46992. repaint();
  46993. const File f (filenames[0]);
  46994. if (f.exists() && (f.isDirectory() == isDir))
  46995. setCurrentFile (f, true);
  46996. }
  46997. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  46998. {
  46999. isFileDragOver = true;
  47000. repaint();
  47001. }
  47002. void FilenameComponent::fileDragExit (const StringArray&)
  47003. {
  47004. isFileDragOver = false;
  47005. repaint();
  47006. }
  47007. const File FilenameComponent::getCurrentFile() const
  47008. {
  47009. File f (filenameBox.getText());
  47010. if (enforcedSuffix.isNotEmpty())
  47011. f = f.withFileExtension (enforcedSuffix);
  47012. return f;
  47013. }
  47014. void FilenameComponent::setCurrentFile (File newFile,
  47015. const bool addToRecentlyUsedList,
  47016. const bool sendChangeNotification)
  47017. {
  47018. if (enforcedSuffix.isNotEmpty())
  47019. newFile = newFile.withFileExtension (enforcedSuffix);
  47020. if (newFile.getFullPathName() != lastFilename)
  47021. {
  47022. lastFilename = newFile.getFullPathName();
  47023. if (addToRecentlyUsedList)
  47024. addRecentlyUsedFile (newFile);
  47025. filenameBox.setText (lastFilename, true);
  47026. if (sendChangeNotification)
  47027. triggerAsyncUpdate();
  47028. }
  47029. }
  47030. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  47031. {
  47032. filenameBox.setEditableText (shouldBeEditable);
  47033. }
  47034. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  47035. {
  47036. StringArray names;
  47037. for (int i = 0; i < filenameBox.getNumItems(); ++i)
  47038. names.add (filenameBox.getItemText (i));
  47039. return names;
  47040. }
  47041. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  47042. {
  47043. if (filenames != getRecentlyUsedFilenames())
  47044. {
  47045. filenameBox.clear();
  47046. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  47047. filenameBox.addItem (filenames[i], i + 1);
  47048. }
  47049. }
  47050. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  47051. {
  47052. maxRecentFiles = jmax (1, newMaximum);
  47053. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  47054. }
  47055. void FilenameComponent::addRecentlyUsedFile (const File& file)
  47056. {
  47057. StringArray files (getRecentlyUsedFilenames());
  47058. if (file.getFullPathName().isNotEmpty())
  47059. {
  47060. files.removeString (file.getFullPathName(), true);
  47061. files.insert (0, file.getFullPathName());
  47062. setRecentlyUsedFilenames (files);
  47063. }
  47064. }
  47065. void FilenameComponent::addListener (FilenameComponentListener* const listener)
  47066. {
  47067. listeners.add (listener);
  47068. }
  47069. void FilenameComponent::removeListener (FilenameComponentListener* const listener)
  47070. {
  47071. listeners.remove (listener);
  47072. }
  47073. void FilenameComponent::handleAsyncUpdate()
  47074. {
  47075. Component::BailOutChecker checker (this);
  47076. listeners.callChecked (checker, &FilenameComponentListener::filenameComponentChanged, this);
  47077. }
  47078. END_JUCE_NAMESPACE
  47079. /*** End of inlined file: juce_FilenameComponent.cpp ***/
  47080. /*** Start of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47081. BEGIN_JUCE_NAMESPACE
  47082. FileSearchPathListComponent::FileSearchPathListComponent()
  47083. {
  47084. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  47085. listBox->setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  47086. listBox->setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  47087. listBox->setOutlineThickness (1);
  47088. addAndMakeVisible (addButton = new TextButton ("+"));
  47089. addButton->addButtonListener (this);
  47090. addButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47091. addAndMakeVisible (removeButton = new TextButton ("-"));
  47092. removeButton->addButtonListener (this);
  47093. removeButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47094. addAndMakeVisible (changeButton = new TextButton (TRANS("change...")));
  47095. changeButton->addButtonListener (this);
  47096. addAndMakeVisible (upButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  47097. upButton->addButtonListener (this);
  47098. {
  47099. Path arrowPath;
  47100. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  47101. DrawablePath arrowImage;
  47102. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47103. arrowImage.setPath (arrowPath);
  47104. upButton->setImages (&arrowImage);
  47105. }
  47106. addAndMakeVisible (downButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  47107. downButton->addButtonListener (this);
  47108. {
  47109. Path arrowPath;
  47110. arrowPath.addArrow (Line<float> (50.0f, 0.0f, 50.0f, 100.0f), 40.0f, 100.0f, 50.0f);
  47111. DrawablePath arrowImage;
  47112. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47113. arrowImage.setPath (arrowPath);
  47114. downButton->setImages (&arrowImage);
  47115. }
  47116. updateButtons();
  47117. }
  47118. FileSearchPathListComponent::~FileSearchPathListComponent()
  47119. {
  47120. deleteAllChildren();
  47121. }
  47122. void FileSearchPathListComponent::updateButtons()
  47123. {
  47124. const bool anythingSelected = listBox->getNumSelectedRows() > 0;
  47125. removeButton->setEnabled (anythingSelected);
  47126. changeButton->setEnabled (anythingSelected);
  47127. upButton->setEnabled (anythingSelected);
  47128. downButton->setEnabled (anythingSelected);
  47129. }
  47130. void FileSearchPathListComponent::changed()
  47131. {
  47132. listBox->updateContent();
  47133. listBox->repaint();
  47134. updateButtons();
  47135. }
  47136. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  47137. {
  47138. if (newPath.toString() != path.toString())
  47139. {
  47140. path = newPath;
  47141. changed();
  47142. }
  47143. }
  47144. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47145. {
  47146. defaultBrowseTarget = newDefaultDirectory;
  47147. }
  47148. int FileSearchPathListComponent::getNumRows()
  47149. {
  47150. return path.getNumPaths();
  47151. }
  47152. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  47153. {
  47154. if (rowIsSelected)
  47155. g.fillAll (findColour (TextEditor::highlightColourId));
  47156. g.setColour (findColour (ListBox::textColourId));
  47157. Font f (height * 0.7f);
  47158. f.setHorizontalScale (0.9f);
  47159. g.setFont (f);
  47160. g.drawText (path [rowNumber].getFullPathName(),
  47161. 4, 0, width - 6, height,
  47162. Justification::centredLeft, true);
  47163. }
  47164. void FileSearchPathListComponent::deleteKeyPressed (int row)
  47165. {
  47166. if (((unsigned int) row) < (unsigned int) path.getNumPaths())
  47167. {
  47168. path.remove (row);
  47169. changed();
  47170. }
  47171. }
  47172. void FileSearchPathListComponent::returnKeyPressed (int row)
  47173. {
  47174. FileChooser chooser (TRANS("Change folder..."), path [row], "*");
  47175. if (chooser.browseForDirectory())
  47176. {
  47177. path.remove (row);
  47178. path.add (chooser.getResult(), row);
  47179. changed();
  47180. }
  47181. }
  47182. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  47183. {
  47184. returnKeyPressed (row);
  47185. }
  47186. void FileSearchPathListComponent::selectedRowsChanged (int)
  47187. {
  47188. updateButtons();
  47189. }
  47190. void FileSearchPathListComponent::paint (Graphics& g)
  47191. {
  47192. g.fillAll (findColour (backgroundColourId));
  47193. }
  47194. void FileSearchPathListComponent::resized()
  47195. {
  47196. const int buttonH = 22;
  47197. const int buttonY = getHeight() - buttonH - 4;
  47198. listBox->setBounds (2, 2, getWidth() - 4, buttonY - 5);
  47199. addButton->setBounds (2, buttonY, buttonH, buttonH);
  47200. removeButton->setBounds (addButton->getRight(), buttonY, buttonH, buttonH);
  47201. changeButton->changeWidthToFitText (buttonH);
  47202. downButton->setSize (buttonH * 2, buttonH);
  47203. upButton->setSize (buttonH * 2, buttonH);
  47204. downButton->setTopRightPosition (getWidth() - 2, buttonY);
  47205. upButton->setTopRightPosition (downButton->getX() - 4, buttonY);
  47206. changeButton->setTopRightPosition (upButton->getX() - 8, buttonY);
  47207. }
  47208. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  47209. {
  47210. return true;
  47211. }
  47212. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  47213. {
  47214. for (int i = filenames.size(); --i >= 0;)
  47215. {
  47216. const File f (filenames[i]);
  47217. if (f.isDirectory())
  47218. {
  47219. const int row = listBox->getRowContainingPosition (0, mouseY - listBox->getY());
  47220. path.add (f, row);
  47221. changed();
  47222. }
  47223. }
  47224. }
  47225. void FileSearchPathListComponent::buttonClicked (Button* button)
  47226. {
  47227. const int currentRow = listBox->getSelectedRow();
  47228. if (button == removeButton)
  47229. {
  47230. deleteKeyPressed (currentRow);
  47231. }
  47232. else if (button == addButton)
  47233. {
  47234. File start (defaultBrowseTarget);
  47235. if (start == File::nonexistent)
  47236. start = path [0];
  47237. if (start == File::nonexistent)
  47238. start = File::getCurrentWorkingDirectory();
  47239. FileChooser chooser (TRANS("Add a folder..."), start, "*");
  47240. if (chooser.browseForDirectory())
  47241. {
  47242. path.add (chooser.getResult(), currentRow);
  47243. }
  47244. }
  47245. else if (button == changeButton)
  47246. {
  47247. returnKeyPressed (currentRow);
  47248. }
  47249. else if (button == upButton)
  47250. {
  47251. if (currentRow > 0 && currentRow < path.getNumPaths())
  47252. {
  47253. const File f (path[currentRow]);
  47254. path.remove (currentRow);
  47255. path.add (f, currentRow - 1);
  47256. listBox->selectRow (currentRow - 1);
  47257. }
  47258. }
  47259. else if (button == downButton)
  47260. {
  47261. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  47262. {
  47263. const File f (path[currentRow]);
  47264. path.remove (currentRow);
  47265. path.add (f, currentRow + 1);
  47266. listBox->selectRow (currentRow + 1);
  47267. }
  47268. }
  47269. changed();
  47270. }
  47271. END_JUCE_NAMESPACE
  47272. /*** End of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47273. /*** Start of inlined file: juce_FileTreeComponent.cpp ***/
  47274. BEGIN_JUCE_NAMESPACE
  47275. const Image juce_createIconForFile (const File& file);
  47276. class FileListTreeItem : public TreeViewItem,
  47277. public TimeSliceClient,
  47278. public AsyncUpdater,
  47279. public ChangeListener
  47280. {
  47281. public:
  47282. FileListTreeItem (FileTreeComponent& owner_,
  47283. DirectoryContentsList* const parentContentsList_,
  47284. const int indexInContentsList_,
  47285. const File& file_,
  47286. TimeSliceThread& thread_)
  47287. : file (file_),
  47288. owner (owner_),
  47289. parentContentsList (parentContentsList_),
  47290. indexInContentsList (indexInContentsList_),
  47291. subContentsList (0),
  47292. canDeleteSubContentsList (false),
  47293. thread (thread_),
  47294. icon (0)
  47295. {
  47296. DirectoryContentsList::FileInfo fileInfo;
  47297. if (parentContentsList_ != 0
  47298. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  47299. {
  47300. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  47301. modTime = fileInfo.modificationTime.formatted ("%d %b '%y %H:%M");
  47302. isDirectory = fileInfo.isDirectory;
  47303. }
  47304. else
  47305. {
  47306. isDirectory = true;
  47307. }
  47308. }
  47309. ~FileListTreeItem()
  47310. {
  47311. thread.removeTimeSliceClient (this);
  47312. clearSubItems();
  47313. if (canDeleteSubContentsList)
  47314. delete subContentsList;
  47315. }
  47316. bool mightContainSubItems() { return isDirectory; }
  47317. const String getUniqueName() const { return file.getFullPathName(); }
  47318. int getItemHeight() const { return 22; }
  47319. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  47320. void itemOpennessChanged (bool isNowOpen)
  47321. {
  47322. if (isNowOpen)
  47323. {
  47324. clearSubItems();
  47325. isDirectory = file.isDirectory();
  47326. if (isDirectory)
  47327. {
  47328. if (subContentsList == 0)
  47329. {
  47330. jassert (parentContentsList != 0);
  47331. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  47332. l->setDirectory (file, true, true);
  47333. setSubContentsList (l);
  47334. canDeleteSubContentsList = true;
  47335. }
  47336. changeListenerCallback (0);
  47337. }
  47338. }
  47339. }
  47340. void setSubContentsList (DirectoryContentsList* newList)
  47341. {
  47342. jassert (subContentsList == 0);
  47343. subContentsList = newList;
  47344. newList->addChangeListener (this);
  47345. }
  47346. void changeListenerCallback (void*)
  47347. {
  47348. clearSubItems();
  47349. if (isOpen() && subContentsList != 0)
  47350. {
  47351. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  47352. {
  47353. FileListTreeItem* const item
  47354. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  47355. addSubItem (item);
  47356. }
  47357. }
  47358. }
  47359. void paintItem (Graphics& g, int width, int height)
  47360. {
  47361. if (file != File::nonexistent)
  47362. {
  47363. updateIcon (true);
  47364. if (icon.isNull())
  47365. thread.addTimeSliceClient (this);
  47366. }
  47367. owner.getLookAndFeel()
  47368. .drawFileBrowserRow (g, width, height,
  47369. file.getFileName(),
  47370. &icon, fileSize, modTime,
  47371. isDirectory, isSelected(),
  47372. indexInContentsList);
  47373. }
  47374. void itemClicked (const MouseEvent& e)
  47375. {
  47376. owner.sendMouseClickMessage (file, e);
  47377. }
  47378. void itemDoubleClicked (const MouseEvent& e)
  47379. {
  47380. TreeViewItem::itemDoubleClicked (e);
  47381. owner.sendDoubleClickMessage (file);
  47382. }
  47383. void itemSelectionChanged (bool)
  47384. {
  47385. owner.sendSelectionChangeMessage();
  47386. }
  47387. bool useTimeSlice()
  47388. {
  47389. updateIcon (false);
  47390. thread.removeTimeSliceClient (this);
  47391. return false;
  47392. }
  47393. void handleAsyncUpdate()
  47394. {
  47395. owner.repaint();
  47396. }
  47397. const File file;
  47398. juce_UseDebuggingNewOperator
  47399. private:
  47400. FileTreeComponent& owner;
  47401. DirectoryContentsList* parentContentsList;
  47402. int indexInContentsList;
  47403. DirectoryContentsList* subContentsList;
  47404. bool isDirectory, canDeleteSubContentsList;
  47405. TimeSliceThread& thread;
  47406. Image icon;
  47407. String fileSize;
  47408. String modTime;
  47409. void updateIcon (const bool onlyUpdateIfCached)
  47410. {
  47411. if (icon.isNull())
  47412. {
  47413. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  47414. Image im (ImageCache::getFromHashCode (hashCode));
  47415. if (im.isNull() && ! onlyUpdateIfCached)
  47416. {
  47417. im = juce_createIconForFile (file);
  47418. if (im.isValid())
  47419. ImageCache::addImageToCache (im, hashCode);
  47420. }
  47421. if (im.isValid())
  47422. {
  47423. icon = im;
  47424. triggerAsyncUpdate();
  47425. }
  47426. }
  47427. }
  47428. };
  47429. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  47430. : DirectoryContentsDisplayComponent (listToShow)
  47431. {
  47432. FileListTreeItem* const root
  47433. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  47434. listToShow.getTimeSliceThread());
  47435. root->setSubContentsList (&listToShow);
  47436. setRootItemVisible (false);
  47437. setRootItem (root);
  47438. }
  47439. FileTreeComponent::~FileTreeComponent()
  47440. {
  47441. deleteRootItem();
  47442. }
  47443. const File FileTreeComponent::getSelectedFile (const int index) const
  47444. {
  47445. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  47446. return item != 0 ? item->file
  47447. : File::nonexistent;
  47448. }
  47449. void FileTreeComponent::deselectAllFiles()
  47450. {
  47451. clearSelectedItems();
  47452. }
  47453. void FileTreeComponent::scrollToTop()
  47454. {
  47455. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  47456. }
  47457. void FileTreeComponent::setDragAndDropDescription (const String& description)
  47458. {
  47459. dragAndDropDescription = description;
  47460. }
  47461. END_JUCE_NAMESPACE
  47462. /*** End of inlined file: juce_FileTreeComponent.cpp ***/
  47463. /*** Start of inlined file: juce_ImagePreviewComponent.cpp ***/
  47464. BEGIN_JUCE_NAMESPACE
  47465. ImagePreviewComponent::ImagePreviewComponent()
  47466. {
  47467. }
  47468. ImagePreviewComponent::~ImagePreviewComponent()
  47469. {
  47470. }
  47471. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  47472. {
  47473. const int availableW = proportionOfWidth (0.97f);
  47474. const int availableH = getHeight() - 13 * 4;
  47475. const double scale = jmin (1.0,
  47476. availableW / (double) w,
  47477. availableH / (double) h);
  47478. w = roundToInt (scale * w);
  47479. h = roundToInt (scale * h);
  47480. }
  47481. void ImagePreviewComponent::selectedFileChanged (const File& file)
  47482. {
  47483. if (fileToLoad != file)
  47484. {
  47485. fileToLoad = file;
  47486. startTimer (100);
  47487. }
  47488. }
  47489. void ImagePreviewComponent::timerCallback()
  47490. {
  47491. stopTimer();
  47492. currentThumbnail = Image();
  47493. currentDetails = String::empty;
  47494. repaint();
  47495. ScopedPointer <FileInputStream> in (fileToLoad.createInputStream());
  47496. if (in != 0)
  47497. {
  47498. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  47499. if (format != 0)
  47500. {
  47501. currentThumbnail = format->decodeImage (*in);
  47502. if (currentThumbnail.isValid())
  47503. {
  47504. int w = currentThumbnail.getWidth();
  47505. int h = currentThumbnail.getHeight();
  47506. currentDetails
  47507. << fileToLoad.getFileName() << "\n"
  47508. << format->getFormatName() << "\n"
  47509. << w << " x " << h << " pixels\n"
  47510. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  47511. getThumbSize (w, h);
  47512. currentThumbnail = currentThumbnail.rescaled (w, h);
  47513. }
  47514. }
  47515. }
  47516. }
  47517. void ImagePreviewComponent::paint (Graphics& g)
  47518. {
  47519. if (currentThumbnail.isValid())
  47520. {
  47521. g.setFont (13.0f);
  47522. int w = currentThumbnail.getWidth();
  47523. int h = currentThumbnail.getHeight();
  47524. getThumbSize (w, h);
  47525. const int numLines = 4;
  47526. const int totalH = 13 * numLines + h + 4;
  47527. const int y = (getHeight() - totalH) / 2;
  47528. g.drawImageWithin (currentThumbnail,
  47529. (getWidth() - w) / 2, y, w, h,
  47530. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  47531. false);
  47532. g.drawFittedText (currentDetails,
  47533. 0, y + h + 4, getWidth(), 100,
  47534. Justification::centredTop, numLines);
  47535. }
  47536. }
  47537. END_JUCE_NAMESPACE
  47538. /*** End of inlined file: juce_ImagePreviewComponent.cpp ***/
  47539. /*** Start of inlined file: juce_WildcardFileFilter.cpp ***/
  47540. BEGIN_JUCE_NAMESPACE
  47541. WildcardFileFilter::WildcardFileFilter (const String& fileWildcardPatterns,
  47542. const String& directoryWildcardPatterns,
  47543. const String& description_)
  47544. : FileFilter (description_.isEmpty() ? fileWildcardPatterns
  47545. : (description_ + " (" + fileWildcardPatterns + ")"))
  47546. {
  47547. parse (fileWildcardPatterns, fileWildcards);
  47548. parse (directoryWildcardPatterns, directoryWildcards);
  47549. }
  47550. WildcardFileFilter::~WildcardFileFilter()
  47551. {
  47552. }
  47553. bool WildcardFileFilter::isFileSuitable (const File& file) const
  47554. {
  47555. return match (file, fileWildcards);
  47556. }
  47557. bool WildcardFileFilter::isDirectorySuitable (const File& file) const
  47558. {
  47559. return match (file, directoryWildcards);
  47560. }
  47561. void WildcardFileFilter::parse (const String& pattern, StringArray& result)
  47562. {
  47563. result.addTokens (pattern.toLowerCase(), ";,", "\"'");
  47564. result.trim();
  47565. result.removeEmptyStrings();
  47566. // special case for *.*, because people use it to mean "any file", but it
  47567. // would actually ignore files with no extension.
  47568. for (int i = result.size(); --i >= 0;)
  47569. if (result[i] == "*.*")
  47570. result.set (i, "*");
  47571. }
  47572. bool WildcardFileFilter::match (const File& file, const StringArray& wildcards)
  47573. {
  47574. const String filename (file.getFileName());
  47575. for (int i = wildcards.size(); --i >= 0;)
  47576. if (filename.matchesWildcard (wildcards[i], true))
  47577. return true;
  47578. return false;
  47579. }
  47580. END_JUCE_NAMESPACE
  47581. /*** End of inlined file: juce_WildcardFileFilter.cpp ***/
  47582. /*** Start of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  47583. BEGIN_JUCE_NAMESPACE
  47584. KeyboardFocusTraverser::KeyboardFocusTraverser()
  47585. {
  47586. }
  47587. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  47588. {
  47589. }
  47590. namespace KeyboardFocusHelpers
  47591. {
  47592. // This will sort a set of components, so that they are ordered in terms of
  47593. // left-to-right and then top-to-bottom.
  47594. class ScreenPositionComparator
  47595. {
  47596. public:
  47597. ScreenPositionComparator() {}
  47598. static int compareElements (const Component* const first, const Component* const second)
  47599. {
  47600. int explicitOrder1 = first->getExplicitFocusOrder();
  47601. if (explicitOrder1 <= 0)
  47602. explicitOrder1 = std::numeric_limits<int>::max() / 2;
  47603. int explicitOrder2 = second->getExplicitFocusOrder();
  47604. if (explicitOrder2 <= 0)
  47605. explicitOrder2 = std::numeric_limits<int>::max() / 2;
  47606. if (explicitOrder1 != explicitOrder2)
  47607. return explicitOrder1 - explicitOrder2;
  47608. const int diff = first->getY() - second->getY();
  47609. return (diff == 0) ? first->getX() - second->getX()
  47610. : diff;
  47611. }
  47612. };
  47613. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  47614. {
  47615. if (parent->getNumChildComponents() > 0)
  47616. {
  47617. Array <Component*> localComps;
  47618. ScreenPositionComparator comparator;
  47619. int i;
  47620. for (i = parent->getNumChildComponents(); --i >= 0;)
  47621. {
  47622. Component* const c = parent->getChildComponent (i);
  47623. if (c->isVisible() && c->isEnabled())
  47624. localComps.addSorted (comparator, c);
  47625. }
  47626. for (i = 0; i < localComps.size(); ++i)
  47627. {
  47628. Component* const c = localComps.getUnchecked (i);
  47629. if (c->getWantsKeyboardFocus())
  47630. comps.add (c);
  47631. if (! c->isFocusContainer())
  47632. findAllFocusableComponents (c, comps);
  47633. }
  47634. }
  47635. }
  47636. }
  47637. static Component* getIncrementedComponent (Component* const current, const int delta)
  47638. {
  47639. Component* focusContainer = current->getParentComponent();
  47640. if (focusContainer != 0)
  47641. {
  47642. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  47643. focusContainer = focusContainer->getParentComponent();
  47644. if (focusContainer != 0)
  47645. {
  47646. Array <Component*> comps;
  47647. KeyboardFocusHelpers::findAllFocusableComponents (focusContainer, comps);
  47648. if (comps.size() > 0)
  47649. {
  47650. const int index = comps.indexOf (current);
  47651. return comps [(index + comps.size() + delta) % comps.size()];
  47652. }
  47653. }
  47654. }
  47655. return 0;
  47656. }
  47657. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  47658. {
  47659. return getIncrementedComponent (current, 1);
  47660. }
  47661. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  47662. {
  47663. return getIncrementedComponent (current, -1);
  47664. }
  47665. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  47666. {
  47667. Array <Component*> comps;
  47668. if (parentComponent != 0)
  47669. KeyboardFocusHelpers::findAllFocusableComponents (parentComponent, comps);
  47670. return comps.getFirst();
  47671. }
  47672. END_JUCE_NAMESPACE
  47673. /*** End of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  47674. /*** Start of inlined file: juce_KeyListener.cpp ***/
  47675. BEGIN_JUCE_NAMESPACE
  47676. bool KeyListener::keyStateChanged (const bool, Component*)
  47677. {
  47678. return false;
  47679. }
  47680. END_JUCE_NAMESPACE
  47681. /*** End of inlined file: juce_KeyListener.cpp ***/
  47682. /*** Start of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  47683. BEGIN_JUCE_NAMESPACE
  47684. // N.B. these two includes are put here deliberately to avoid problems with
  47685. // old GCCs failing on long include paths
  47686. const int maxKeys = 3;
  47687. class KeyMappingChangeButton : public Button
  47688. {
  47689. public:
  47690. KeyMappingChangeButton (KeyMappingEditorComponent* const owner_,
  47691. const CommandID commandID_,
  47692. const String& keyName,
  47693. const int keyNum_)
  47694. : Button (keyName),
  47695. owner (owner_),
  47696. commandID (commandID_),
  47697. keyNum (keyNum_)
  47698. {
  47699. setWantsKeyboardFocus (false);
  47700. setTriggeredOnMouseDown (keyNum >= 0);
  47701. if (keyNum_ < 0)
  47702. setTooltip (TRANS("adds a new key-mapping"));
  47703. else
  47704. setTooltip (TRANS("click to change this key-mapping"));
  47705. }
  47706. ~KeyMappingChangeButton()
  47707. {
  47708. }
  47709. void paintButton (Graphics& g, bool /*isOver*/, bool /*isDown*/)
  47710. {
  47711. getLookAndFeel().drawKeymapChangeButton (g, getWidth(), getHeight(), *this,
  47712. keyNum >= 0 ? getName() : String::empty);
  47713. }
  47714. void clicked()
  47715. {
  47716. if (keyNum >= 0)
  47717. {
  47718. // existing key clicked..
  47719. PopupMenu m;
  47720. m.addItem (1, TRANS("change this key-mapping"));
  47721. m.addSeparator();
  47722. m.addItem (2, TRANS("remove this key-mapping"));
  47723. const int res = m.show();
  47724. if (res == 1)
  47725. {
  47726. owner->assignNewKey (commandID, keyNum);
  47727. }
  47728. else if (res == 2)
  47729. {
  47730. owner->getMappings()->removeKeyPress (commandID, keyNum);
  47731. }
  47732. }
  47733. else
  47734. {
  47735. // + button pressed..
  47736. owner->assignNewKey (commandID, -1);
  47737. }
  47738. }
  47739. void fitToContent (const int h) throw()
  47740. {
  47741. if (keyNum < 0)
  47742. {
  47743. setSize (h, h);
  47744. }
  47745. else
  47746. {
  47747. Font f (h * 0.6f);
  47748. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  47749. }
  47750. }
  47751. juce_UseDebuggingNewOperator
  47752. private:
  47753. KeyMappingEditorComponent* const owner;
  47754. const CommandID commandID;
  47755. const int keyNum;
  47756. KeyMappingChangeButton (const KeyMappingChangeButton&);
  47757. KeyMappingChangeButton& operator= (const KeyMappingChangeButton&);
  47758. };
  47759. class KeyMappingItemComponent : public Component
  47760. {
  47761. public:
  47762. KeyMappingItemComponent (KeyMappingEditorComponent* const owner_,
  47763. const CommandID commandID_)
  47764. : owner (owner_),
  47765. commandID (commandID_)
  47766. {
  47767. setInterceptsMouseClicks (false, true);
  47768. const bool isReadOnly = owner_->isCommandReadOnly (commandID);
  47769. const Array <KeyPress> keyPresses (owner_->getMappings()->getKeyPressesAssignedToCommand (commandID));
  47770. for (int i = 0; i < jmin (maxKeys, keyPresses.size()); ++i)
  47771. {
  47772. KeyMappingChangeButton* const kb
  47773. = new KeyMappingChangeButton (owner_, commandID,
  47774. owner_->getDescriptionForKeyPress (keyPresses.getReference (i)), i);
  47775. kb->setEnabled (! isReadOnly);
  47776. addAndMakeVisible (kb);
  47777. }
  47778. KeyMappingChangeButton* const kb
  47779. = new KeyMappingChangeButton (owner_, commandID, String::empty, -1);
  47780. addChildComponent (kb);
  47781. kb->setVisible (keyPresses.size() < maxKeys && ! isReadOnly);
  47782. }
  47783. ~KeyMappingItemComponent()
  47784. {
  47785. deleteAllChildren();
  47786. }
  47787. void paint (Graphics& g)
  47788. {
  47789. g.setFont (getHeight() * 0.7f);
  47790. g.setColour (findColour (KeyMappingEditorComponent::textColourId));
  47791. g.drawFittedText (owner->getMappings()->getCommandManager()->getNameOfCommand (commandID),
  47792. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  47793. Justification::centredLeft, true);
  47794. }
  47795. void resized()
  47796. {
  47797. int x = getWidth() - 4;
  47798. for (int i = getNumChildComponents(); --i >= 0;)
  47799. {
  47800. KeyMappingChangeButton* const kb = dynamic_cast <KeyMappingChangeButton*> (getChildComponent (i));
  47801. kb->fitToContent (getHeight() - 2);
  47802. kb->setTopRightPosition (x, 1);
  47803. x -= kb->getWidth() + 5;
  47804. }
  47805. }
  47806. juce_UseDebuggingNewOperator
  47807. private:
  47808. KeyMappingEditorComponent* const owner;
  47809. const CommandID commandID;
  47810. KeyMappingItemComponent (const KeyMappingItemComponent&);
  47811. KeyMappingItemComponent& operator= (const KeyMappingItemComponent&);
  47812. };
  47813. class KeyMappingTreeViewItem : public TreeViewItem
  47814. {
  47815. public:
  47816. KeyMappingTreeViewItem (KeyMappingEditorComponent* const owner_,
  47817. const CommandID commandID_)
  47818. : owner (owner_),
  47819. commandID (commandID_)
  47820. {
  47821. }
  47822. ~KeyMappingTreeViewItem()
  47823. {
  47824. }
  47825. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  47826. bool mightContainSubItems() { return false; }
  47827. int getItemHeight() const { return 20; }
  47828. Component* createItemComponent()
  47829. {
  47830. return new KeyMappingItemComponent (owner, commandID);
  47831. }
  47832. juce_UseDebuggingNewOperator
  47833. private:
  47834. KeyMappingEditorComponent* const owner;
  47835. const CommandID commandID;
  47836. KeyMappingTreeViewItem (const KeyMappingTreeViewItem&);
  47837. KeyMappingTreeViewItem& operator= (const KeyMappingTreeViewItem&);
  47838. };
  47839. class KeyCategoryTreeViewItem : public TreeViewItem
  47840. {
  47841. public:
  47842. KeyCategoryTreeViewItem (KeyMappingEditorComponent* const owner_,
  47843. const String& name)
  47844. : owner (owner_),
  47845. categoryName (name)
  47846. {
  47847. }
  47848. ~KeyCategoryTreeViewItem()
  47849. {
  47850. }
  47851. const String getUniqueName() const { return categoryName + "_cat"; }
  47852. bool mightContainSubItems() { return true; }
  47853. int getItemHeight() const { return 28; }
  47854. void paintItem (Graphics& g, int width, int height)
  47855. {
  47856. g.setFont (height * 0.6f, Font::bold);
  47857. g.setColour (owner->findColour (KeyMappingEditorComponent::textColourId));
  47858. g.drawText (categoryName,
  47859. 2, 0, width - 2, height,
  47860. Justification::centredLeft, true);
  47861. }
  47862. void itemOpennessChanged (bool isNowOpen)
  47863. {
  47864. if (isNowOpen)
  47865. {
  47866. if (getNumSubItems() == 0)
  47867. {
  47868. Array <CommandID> commands (owner->getMappings()->getCommandManager()->getCommandsInCategory (categoryName));
  47869. for (int i = 0; i < commands.size(); ++i)
  47870. {
  47871. if (owner->shouldCommandBeIncluded (commands[i]))
  47872. addSubItem (new KeyMappingTreeViewItem (owner, commands[i]));
  47873. }
  47874. }
  47875. }
  47876. else
  47877. {
  47878. clearSubItems();
  47879. }
  47880. }
  47881. juce_UseDebuggingNewOperator
  47882. private:
  47883. KeyMappingEditorComponent* owner;
  47884. String categoryName;
  47885. KeyCategoryTreeViewItem (const KeyCategoryTreeViewItem&);
  47886. KeyCategoryTreeViewItem& operator= (const KeyCategoryTreeViewItem&);
  47887. };
  47888. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet* const mappingManager,
  47889. const bool showResetToDefaultButton)
  47890. : mappings (mappingManager)
  47891. {
  47892. jassert (mappingManager != 0); // can't be null!
  47893. mappingManager->addChangeListener (this);
  47894. setLinesDrawnForSubItems (false);
  47895. resetButton = 0;
  47896. if (showResetToDefaultButton)
  47897. {
  47898. addAndMakeVisible (resetButton = new TextButton (TRANS("reset to defaults")));
  47899. resetButton->addButtonListener (this);
  47900. }
  47901. addAndMakeVisible (tree = new TreeView());
  47902. tree->setColour (TreeView::backgroundColourId, findColour (backgroundColourId));
  47903. tree->setRootItemVisible (false);
  47904. tree->setDefaultOpenness (true);
  47905. tree->setRootItem (this);
  47906. }
  47907. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  47908. {
  47909. mappings->removeChangeListener (this);
  47910. deleteAllChildren();
  47911. }
  47912. bool KeyMappingEditorComponent::mightContainSubItems()
  47913. {
  47914. return true;
  47915. }
  47916. const String KeyMappingEditorComponent::getUniqueName() const
  47917. {
  47918. return "keys";
  47919. }
  47920. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  47921. const Colour& textColour)
  47922. {
  47923. setColour (backgroundColourId, mainBackground);
  47924. setColour (textColourId, textColour);
  47925. tree->setColour (TreeView::backgroundColourId, mainBackground);
  47926. }
  47927. void KeyMappingEditorComponent::parentHierarchyChanged()
  47928. {
  47929. changeListenerCallback (0);
  47930. }
  47931. void KeyMappingEditorComponent::resized()
  47932. {
  47933. int h = getHeight();
  47934. if (resetButton != 0)
  47935. {
  47936. const int buttonHeight = 20;
  47937. h -= buttonHeight + 8;
  47938. int x = getWidth() - 8;
  47939. resetButton->changeWidthToFitText (buttonHeight);
  47940. resetButton->setTopRightPosition (x, h + 6);
  47941. }
  47942. tree->setBounds (0, 0, getWidth(), h);
  47943. }
  47944. void KeyMappingEditorComponent::buttonClicked (Button* button)
  47945. {
  47946. if (button == resetButton)
  47947. {
  47948. if (AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  47949. TRANS("Reset to defaults"),
  47950. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  47951. TRANS("Reset")))
  47952. {
  47953. mappings->resetToDefaultMappings();
  47954. }
  47955. }
  47956. }
  47957. void KeyMappingEditorComponent::changeListenerCallback (void*)
  47958. {
  47959. ScopedPointer <XmlElement> oldOpenness (tree->getOpennessState (true));
  47960. clearSubItems();
  47961. const StringArray categories (mappings->getCommandManager()->getCommandCategories());
  47962. for (int i = 0; i < categories.size(); ++i)
  47963. {
  47964. const Array <CommandID> commands (mappings->getCommandManager()->getCommandsInCategory (categories[i]));
  47965. int count = 0;
  47966. for (int j = 0; j < commands.size(); ++j)
  47967. if (shouldCommandBeIncluded (commands[j]))
  47968. ++count;
  47969. if (count > 0)
  47970. addSubItem (new KeyCategoryTreeViewItem (this, categories[i]));
  47971. }
  47972. if (oldOpenness != 0)
  47973. tree->restoreOpennessState (*oldOpenness);
  47974. }
  47975. class KeyEntryWindow : public AlertWindow
  47976. {
  47977. public:
  47978. KeyEntryWindow (KeyMappingEditorComponent* const owner_)
  47979. : AlertWindow (TRANS("New key-mapping"),
  47980. TRANS("Please press a key combination now..."),
  47981. AlertWindow::NoIcon),
  47982. owner (owner_)
  47983. {
  47984. addButton (TRANS("ok"), 1);
  47985. addButton (TRANS("cancel"), 0);
  47986. // (avoid return + escape keys getting processed by the buttons..)
  47987. for (int i = getNumChildComponents(); --i >= 0;)
  47988. getChildComponent (i)->setWantsKeyboardFocus (false);
  47989. setWantsKeyboardFocus (true);
  47990. grabKeyboardFocus();
  47991. }
  47992. ~KeyEntryWindow()
  47993. {
  47994. }
  47995. bool keyPressed (const KeyPress& key)
  47996. {
  47997. lastPress = key;
  47998. String message (TRANS("Key: ") + owner->getDescriptionForKeyPress (key));
  47999. const CommandID previousCommand = owner->getMappings()->findCommandForKeyPress (key);
  48000. if (previousCommand != 0)
  48001. {
  48002. message << "\n\n"
  48003. << TRANS("(Currently assigned to \"")
  48004. << owner->getMappings()->getCommandManager()->getNameOfCommand (previousCommand)
  48005. << "\")";
  48006. }
  48007. setMessage (message);
  48008. return true;
  48009. }
  48010. bool keyStateChanged (bool)
  48011. {
  48012. return true;
  48013. }
  48014. KeyPress lastPress;
  48015. juce_UseDebuggingNewOperator
  48016. private:
  48017. KeyMappingEditorComponent* owner;
  48018. KeyEntryWindow (const KeyEntryWindow&);
  48019. KeyEntryWindow& operator= (const KeyEntryWindow&);
  48020. };
  48021. void KeyMappingEditorComponent::assignNewKey (const CommandID commandID, const int index)
  48022. {
  48023. KeyEntryWindow entryWindow (this);
  48024. if (entryWindow.runModalLoop() != 0)
  48025. {
  48026. entryWindow.setVisible (false);
  48027. if (entryWindow.lastPress.isValid())
  48028. {
  48029. const CommandID previousCommand = mappings->findCommandForKeyPress (entryWindow.lastPress);
  48030. if (previousCommand != 0)
  48031. {
  48032. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  48033. TRANS("Change key-mapping"),
  48034. TRANS("This key is already assigned to the command \"")
  48035. + mappings->getCommandManager()->getNameOfCommand (previousCommand)
  48036. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  48037. TRANS("re-assign"),
  48038. TRANS("cancel")))
  48039. {
  48040. return;
  48041. }
  48042. }
  48043. mappings->removeKeyPress (entryWindow.lastPress);
  48044. if (index >= 0)
  48045. mappings->removeKeyPress (commandID, index);
  48046. mappings->addKeyPress (commandID, entryWindow.lastPress, index);
  48047. }
  48048. }
  48049. }
  48050. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  48051. {
  48052. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  48053. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0);
  48054. }
  48055. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  48056. {
  48057. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  48058. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0);
  48059. }
  48060. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  48061. {
  48062. return key.getTextDescription();
  48063. }
  48064. END_JUCE_NAMESPACE
  48065. /*** End of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48066. /*** Start of inlined file: juce_KeyPress.cpp ***/
  48067. BEGIN_JUCE_NAMESPACE
  48068. KeyPress::KeyPress() throw()
  48069. : keyCode (0),
  48070. mods (0),
  48071. textCharacter (0)
  48072. {
  48073. }
  48074. KeyPress::KeyPress (const int keyCode_,
  48075. const ModifierKeys& mods_,
  48076. const juce_wchar textCharacter_) throw()
  48077. : keyCode (keyCode_),
  48078. mods (mods_),
  48079. textCharacter (textCharacter_)
  48080. {
  48081. }
  48082. KeyPress::KeyPress (const int keyCode_) throw()
  48083. : keyCode (keyCode_),
  48084. textCharacter (0)
  48085. {
  48086. }
  48087. KeyPress::KeyPress (const KeyPress& other) throw()
  48088. : keyCode (other.keyCode),
  48089. mods (other.mods),
  48090. textCharacter (other.textCharacter)
  48091. {
  48092. }
  48093. KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  48094. {
  48095. keyCode = other.keyCode;
  48096. mods = other.mods;
  48097. textCharacter = other.textCharacter;
  48098. return *this;
  48099. }
  48100. bool KeyPress::operator== (const KeyPress& other) const throw()
  48101. {
  48102. return mods.getRawFlags() == other.mods.getRawFlags()
  48103. && (textCharacter == other.textCharacter
  48104. || textCharacter == 0
  48105. || other.textCharacter == 0)
  48106. && (keyCode == other.keyCode
  48107. || (keyCode < 256
  48108. && other.keyCode < 256
  48109. && CharacterFunctions::toLowerCase ((juce_wchar) keyCode)
  48110. == CharacterFunctions::toLowerCase ((juce_wchar) other.keyCode)));
  48111. }
  48112. bool KeyPress::operator!= (const KeyPress& other) const throw()
  48113. {
  48114. return ! operator== (other);
  48115. }
  48116. bool KeyPress::isCurrentlyDown() const
  48117. {
  48118. return isKeyCurrentlyDown (keyCode)
  48119. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  48120. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  48121. }
  48122. namespace KeyPressHelpers
  48123. {
  48124. struct KeyNameAndCode
  48125. {
  48126. const char* name;
  48127. int code;
  48128. };
  48129. static const KeyNameAndCode translations[] =
  48130. {
  48131. { "spacebar", KeyPress::spaceKey },
  48132. { "return", KeyPress::returnKey },
  48133. { "escape", KeyPress::escapeKey },
  48134. { "backspace", KeyPress::backspaceKey },
  48135. { "cursor left", KeyPress::leftKey },
  48136. { "cursor right", KeyPress::rightKey },
  48137. { "cursor up", KeyPress::upKey },
  48138. { "cursor down", KeyPress::downKey },
  48139. { "page up", KeyPress::pageUpKey },
  48140. { "page down", KeyPress::pageDownKey },
  48141. { "home", KeyPress::homeKey },
  48142. { "end", KeyPress::endKey },
  48143. { "delete", KeyPress::deleteKey },
  48144. { "insert", KeyPress::insertKey },
  48145. { "tab", KeyPress::tabKey },
  48146. { "play", KeyPress::playKey },
  48147. { "stop", KeyPress::stopKey },
  48148. { "fast forward", KeyPress::fastForwardKey },
  48149. { "rewind", KeyPress::rewindKey }
  48150. };
  48151. static const String numberPadPrefix() { return "numpad "; }
  48152. }
  48153. const KeyPress KeyPress::createFromDescription (const String& desc)
  48154. {
  48155. int modifiers = 0;
  48156. if (desc.containsWholeWordIgnoreCase ("ctrl")
  48157. || desc.containsWholeWordIgnoreCase ("control")
  48158. || desc.containsWholeWordIgnoreCase ("ctl"))
  48159. modifiers |= ModifierKeys::ctrlModifier;
  48160. if (desc.containsWholeWordIgnoreCase ("shift")
  48161. || desc.containsWholeWordIgnoreCase ("shft"))
  48162. modifiers |= ModifierKeys::shiftModifier;
  48163. if (desc.containsWholeWordIgnoreCase ("alt")
  48164. || desc.containsWholeWordIgnoreCase ("option"))
  48165. modifiers |= ModifierKeys::altModifier;
  48166. if (desc.containsWholeWordIgnoreCase ("command")
  48167. || desc.containsWholeWordIgnoreCase ("cmd"))
  48168. modifiers |= ModifierKeys::commandModifier;
  48169. int key = 0;
  48170. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48171. {
  48172. if (desc.containsWholeWordIgnoreCase (String (KeyPressHelpers::translations[i].name)))
  48173. {
  48174. key = KeyPressHelpers::translations[i].code;
  48175. break;
  48176. }
  48177. }
  48178. if (key == 0)
  48179. {
  48180. // see if it's a numpad key..
  48181. if (desc.containsIgnoreCase (KeyPressHelpers::numberPadPrefix()))
  48182. {
  48183. const juce_wchar lastChar = desc.trimEnd().getLastCharacter();
  48184. if (lastChar >= '0' && lastChar <= '9')
  48185. key = numberPad0 + lastChar - '0';
  48186. else if (lastChar == '+')
  48187. key = numberPadAdd;
  48188. else if (lastChar == '-')
  48189. key = numberPadSubtract;
  48190. else if (lastChar == '*')
  48191. key = numberPadMultiply;
  48192. else if (lastChar == '/')
  48193. key = numberPadDivide;
  48194. else if (lastChar == '.')
  48195. key = numberPadDecimalPoint;
  48196. else if (lastChar == '=')
  48197. key = numberPadEquals;
  48198. else if (desc.endsWith ("separator"))
  48199. key = numberPadSeparator;
  48200. else if (desc.endsWith ("delete"))
  48201. key = numberPadDelete;
  48202. }
  48203. if (key == 0)
  48204. {
  48205. // see if it's a function key..
  48206. for (int i = 1; i <= 12; ++i)
  48207. if (desc.containsWholeWordIgnoreCase ("f" + String (i)))
  48208. key = F1Key + i - 1;
  48209. if (key == 0)
  48210. {
  48211. // give up and use the hex code..
  48212. const int hexCode = desc.fromFirstOccurrenceOf ("#", false, false)
  48213. .toLowerCase()
  48214. .retainCharacters ("0123456789abcdef")
  48215. .getHexValue32();
  48216. if (hexCode > 0)
  48217. key = hexCode;
  48218. else
  48219. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  48220. }
  48221. }
  48222. }
  48223. return KeyPress (key, ModifierKeys (modifiers), 0);
  48224. }
  48225. const String KeyPress::getTextDescription() const
  48226. {
  48227. String desc;
  48228. if (keyCode > 0)
  48229. {
  48230. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  48231. // want to store it as being a slash, not shift+whatever.
  48232. if (textCharacter == '/')
  48233. return "/";
  48234. if (mods.isCtrlDown())
  48235. desc << "ctrl + ";
  48236. if (mods.isShiftDown())
  48237. desc << "shift + ";
  48238. #if JUCE_MAC
  48239. // only do this on the mac, because on Windows ctrl and command are the same,
  48240. // and this would get confusing
  48241. if (mods.isCommandDown())
  48242. desc << "command + ";
  48243. if (mods.isAltDown())
  48244. desc << "option + ";
  48245. #else
  48246. if (mods.isAltDown())
  48247. desc << "alt + ";
  48248. #endif
  48249. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48250. if (keyCode == KeyPressHelpers::translations[i].code)
  48251. return desc + KeyPressHelpers::translations[i].name;
  48252. if (keyCode >= F1Key && keyCode <= F16Key)
  48253. desc << 'F' << (1 + keyCode - F1Key);
  48254. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  48255. desc << KeyPressHelpers::numberPadPrefix() << (keyCode - numberPad0);
  48256. else if (keyCode >= 33 && keyCode < 176)
  48257. desc += CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  48258. else if (keyCode == numberPadAdd)
  48259. desc << KeyPressHelpers::numberPadPrefix() << '+';
  48260. else if (keyCode == numberPadSubtract)
  48261. desc << KeyPressHelpers::numberPadPrefix() << '-';
  48262. else if (keyCode == numberPadMultiply)
  48263. desc << KeyPressHelpers::numberPadPrefix() << '*';
  48264. else if (keyCode == numberPadDivide)
  48265. desc << KeyPressHelpers::numberPadPrefix() << '/';
  48266. else if (keyCode == numberPadSeparator)
  48267. desc << KeyPressHelpers::numberPadPrefix() << "separator";
  48268. else if (keyCode == numberPadDecimalPoint)
  48269. desc << KeyPressHelpers::numberPadPrefix() << '.';
  48270. else if (keyCode == numberPadDelete)
  48271. desc << KeyPressHelpers::numberPadPrefix() << "delete";
  48272. else
  48273. desc << '#' << String::toHexString (keyCode);
  48274. }
  48275. return desc;
  48276. }
  48277. END_JUCE_NAMESPACE
  48278. /*** End of inlined file: juce_KeyPress.cpp ***/
  48279. /*** Start of inlined file: juce_KeyPressMappingSet.cpp ***/
  48280. BEGIN_JUCE_NAMESPACE
  48281. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_)
  48282. : commandManager (commandManager_)
  48283. {
  48284. // A manager is needed to get the descriptions of commands, and will be called when
  48285. // a command is invoked. So you can't leave this null..
  48286. jassert (commandManager_ != 0);
  48287. Desktop::getInstance().addFocusChangeListener (this);
  48288. }
  48289. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other)
  48290. : commandManager (other.commandManager)
  48291. {
  48292. Desktop::getInstance().addFocusChangeListener (this);
  48293. }
  48294. KeyPressMappingSet::~KeyPressMappingSet()
  48295. {
  48296. Desktop::getInstance().removeFocusChangeListener (this);
  48297. }
  48298. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const
  48299. {
  48300. for (int i = 0; i < mappings.size(); ++i)
  48301. if (mappings.getUnchecked(i)->commandID == commandID)
  48302. return mappings.getUnchecked (i)->keypresses;
  48303. return Array <KeyPress> ();
  48304. }
  48305. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  48306. const KeyPress& newKeyPress,
  48307. int insertIndex)
  48308. {
  48309. // If you specify an upper-case letter but no shift key, how is the user supposed to press it!?
  48310. // Stick to lower-case letters when defining a keypress, to avoid ambiguity.
  48311. jassert (! (CharacterFunctions::isUpperCase (newKeyPress.getTextCharacter())
  48312. && ! newKeyPress.getModifiers().isShiftDown()));
  48313. if (findCommandForKeyPress (newKeyPress) != commandID)
  48314. {
  48315. removeKeyPress (newKeyPress);
  48316. if (newKeyPress.isValid())
  48317. {
  48318. for (int i = mappings.size(); --i >= 0;)
  48319. {
  48320. if (mappings.getUnchecked(i)->commandID == commandID)
  48321. {
  48322. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  48323. sendChangeMessage (this);
  48324. return;
  48325. }
  48326. }
  48327. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48328. if (ci != 0)
  48329. {
  48330. CommandMapping* const cm = new CommandMapping();
  48331. cm->commandID = commandID;
  48332. cm->keypresses.add (newKeyPress);
  48333. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  48334. mappings.add (cm);
  48335. sendChangeMessage (this);
  48336. }
  48337. }
  48338. }
  48339. }
  48340. void KeyPressMappingSet::resetToDefaultMappings()
  48341. {
  48342. mappings.clear();
  48343. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  48344. {
  48345. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  48346. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48347. {
  48348. addKeyPress (ci->commandID,
  48349. ci->defaultKeypresses.getReference (j));
  48350. }
  48351. }
  48352. sendChangeMessage (this);
  48353. }
  48354. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID)
  48355. {
  48356. clearAllKeyPresses (commandID);
  48357. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48358. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48359. {
  48360. addKeyPress (ci->commandID,
  48361. ci->defaultKeypresses.getReference (j));
  48362. }
  48363. }
  48364. void KeyPressMappingSet::clearAllKeyPresses()
  48365. {
  48366. if (mappings.size() > 0)
  48367. {
  48368. sendChangeMessage (this);
  48369. mappings.clear();
  48370. }
  48371. }
  48372. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID)
  48373. {
  48374. for (int i = mappings.size(); --i >= 0;)
  48375. {
  48376. if (mappings.getUnchecked(i)->commandID == commandID)
  48377. {
  48378. mappings.remove (i);
  48379. sendChangeMessage (this);
  48380. }
  48381. }
  48382. }
  48383. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress)
  48384. {
  48385. if (keypress.isValid())
  48386. {
  48387. for (int i = mappings.size(); --i >= 0;)
  48388. {
  48389. CommandMapping* const cm = mappings.getUnchecked(i);
  48390. for (int j = cm->keypresses.size(); --j >= 0;)
  48391. {
  48392. if (keypress == cm->keypresses [j])
  48393. {
  48394. cm->keypresses.remove (j);
  48395. sendChangeMessage (this);
  48396. }
  48397. }
  48398. }
  48399. }
  48400. }
  48401. void KeyPressMappingSet::removeKeyPress (const CommandID commandID, const int keyPressIndex)
  48402. {
  48403. for (int i = mappings.size(); --i >= 0;)
  48404. {
  48405. if (mappings.getUnchecked(i)->commandID == commandID)
  48406. {
  48407. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  48408. sendChangeMessage (this);
  48409. break;
  48410. }
  48411. }
  48412. }
  48413. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  48414. {
  48415. for (int i = 0; i < mappings.size(); ++i)
  48416. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  48417. return mappings.getUnchecked(i)->commandID;
  48418. return 0;
  48419. }
  48420. bool KeyPressMappingSet::containsMapping (const CommandID commandID, const KeyPress& keyPress) const throw()
  48421. {
  48422. for (int i = mappings.size(); --i >= 0;)
  48423. if (mappings.getUnchecked(i)->commandID == commandID)
  48424. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  48425. return false;
  48426. }
  48427. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  48428. const KeyPress& key,
  48429. const bool isKeyDown,
  48430. const int millisecsSinceKeyPressed,
  48431. Component* const originatingComponent) const
  48432. {
  48433. ApplicationCommandTarget::InvocationInfo info (commandID);
  48434. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  48435. info.isKeyDown = isKeyDown;
  48436. info.keyPress = key;
  48437. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  48438. info.originatingComponent = originatingComponent;
  48439. commandManager->invoke (info, false);
  48440. }
  48441. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  48442. {
  48443. if (xmlVersion.hasTagName ("KEYMAPPINGS"))
  48444. {
  48445. if (xmlVersion.getBoolAttribute ("basedOnDefaults", true))
  48446. {
  48447. // if the XML was created as a set of differences from the default mappings,
  48448. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  48449. resetToDefaultMappings();
  48450. }
  48451. else
  48452. {
  48453. // if the XML was created calling createXml (false), then we need to clear all
  48454. // the keys and treat the xml as describing the entire set of mappings.
  48455. clearAllKeyPresses();
  48456. }
  48457. forEachXmlChildElement (xmlVersion, map)
  48458. {
  48459. const CommandID commandId = map->getStringAttribute ("commandId").getHexValue32();
  48460. if (commandId != 0)
  48461. {
  48462. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute ("key")));
  48463. if (map->hasTagName ("MAPPING"))
  48464. {
  48465. addKeyPress (commandId, key);
  48466. }
  48467. else if (map->hasTagName ("UNMAPPING"))
  48468. {
  48469. if (containsMapping (commandId, key))
  48470. removeKeyPress (key);
  48471. }
  48472. }
  48473. }
  48474. return true;
  48475. }
  48476. return false;
  48477. }
  48478. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  48479. {
  48480. ScopedPointer <KeyPressMappingSet> defaultSet;
  48481. if (saveDifferencesFromDefaultSet)
  48482. {
  48483. defaultSet = new KeyPressMappingSet (commandManager);
  48484. defaultSet->resetToDefaultMappings();
  48485. }
  48486. XmlElement* const doc = new XmlElement ("KEYMAPPINGS");
  48487. doc->setAttribute ("basedOnDefaults", saveDifferencesFromDefaultSet);
  48488. int i;
  48489. for (i = 0; i < mappings.size(); ++i)
  48490. {
  48491. const CommandMapping* const cm = mappings.getUnchecked(i);
  48492. for (int j = 0; j < cm->keypresses.size(); ++j)
  48493. {
  48494. if (defaultSet == 0
  48495. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  48496. {
  48497. XmlElement* const map = doc->createNewChildElement ("MAPPING");
  48498. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  48499. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  48500. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  48501. }
  48502. }
  48503. }
  48504. if (defaultSet != 0)
  48505. {
  48506. for (i = 0; i < defaultSet->mappings.size(); ++i)
  48507. {
  48508. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  48509. for (int j = 0; j < cm->keypresses.size(); ++j)
  48510. {
  48511. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  48512. {
  48513. XmlElement* const map = doc->createNewChildElement ("UNMAPPING");
  48514. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  48515. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  48516. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  48517. }
  48518. }
  48519. }
  48520. }
  48521. return doc;
  48522. }
  48523. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  48524. Component* originatingComponent)
  48525. {
  48526. bool used = false;
  48527. const CommandID commandID = findCommandForKeyPress (key);
  48528. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48529. if (ci != 0
  48530. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  48531. {
  48532. ApplicationCommandInfo info (0);
  48533. if (commandManager->getTargetForCommand (commandID, info) != 0
  48534. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  48535. {
  48536. invokeCommand (commandID, key, true, 0, originatingComponent);
  48537. used = true;
  48538. }
  48539. else
  48540. {
  48541. if (originatingComponent != 0)
  48542. originatingComponent->getLookAndFeel().playAlertSound();
  48543. }
  48544. }
  48545. return used;
  48546. }
  48547. bool KeyPressMappingSet::keyStateChanged (const bool /*isKeyDown*/, Component* originatingComponent)
  48548. {
  48549. bool used = false;
  48550. const uint32 now = Time::getMillisecondCounter();
  48551. for (int i = mappings.size(); --i >= 0;)
  48552. {
  48553. CommandMapping* const cm = mappings.getUnchecked(i);
  48554. if (cm->wantsKeyUpDownCallbacks)
  48555. {
  48556. for (int j = cm->keypresses.size(); --j >= 0;)
  48557. {
  48558. const KeyPress key (cm->keypresses.getReference (j));
  48559. const bool isDown = key.isCurrentlyDown();
  48560. int keyPressEntryIndex = 0;
  48561. bool wasDown = false;
  48562. for (int k = keysDown.size(); --k >= 0;)
  48563. {
  48564. if (key == keysDown.getUnchecked(k)->key)
  48565. {
  48566. keyPressEntryIndex = k;
  48567. wasDown = true;
  48568. used = true;
  48569. break;
  48570. }
  48571. }
  48572. if (isDown != wasDown)
  48573. {
  48574. int millisecs = 0;
  48575. if (isDown)
  48576. {
  48577. KeyPressTime* const k = new KeyPressTime();
  48578. k->key = key;
  48579. k->timeWhenPressed = now;
  48580. keysDown.add (k);
  48581. }
  48582. else
  48583. {
  48584. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  48585. if (now > pressTime)
  48586. millisecs = now - pressTime;
  48587. keysDown.remove (keyPressEntryIndex);
  48588. }
  48589. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  48590. used = true;
  48591. }
  48592. }
  48593. }
  48594. }
  48595. return used;
  48596. }
  48597. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  48598. {
  48599. if (focusedComponent != 0)
  48600. focusedComponent->keyStateChanged (false);
  48601. }
  48602. END_JUCE_NAMESPACE
  48603. /*** End of inlined file: juce_KeyPressMappingSet.cpp ***/
  48604. /*** Start of inlined file: juce_ModifierKeys.cpp ***/
  48605. BEGIN_JUCE_NAMESPACE
  48606. ModifierKeys::ModifierKeys (const int flags_) throw()
  48607. : flags (flags_)
  48608. {
  48609. }
  48610. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  48611. : flags (other.flags)
  48612. {
  48613. }
  48614. ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  48615. {
  48616. flags = other.flags;
  48617. return *this;
  48618. }
  48619. ModifierKeys ModifierKeys::currentModifiers;
  48620. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  48621. {
  48622. return currentModifiers;
  48623. }
  48624. int ModifierKeys::getNumMouseButtonsDown() const throw()
  48625. {
  48626. int num = 0;
  48627. if (isLeftButtonDown()) ++num;
  48628. if (isRightButtonDown()) ++num;
  48629. if (isMiddleButtonDown()) ++num;
  48630. return num;
  48631. }
  48632. END_JUCE_NAMESPACE
  48633. /*** End of inlined file: juce_ModifierKeys.cpp ***/
  48634. /*** Start of inlined file: juce_ComponentAnimator.cpp ***/
  48635. BEGIN_JUCE_NAMESPACE
  48636. class ComponentAnimator::AnimationTask
  48637. {
  48638. public:
  48639. AnimationTask (Component* const comp)
  48640. : component (comp)
  48641. {
  48642. }
  48643. Component::SafePointer<Component> component;
  48644. Rectangle<int> destination;
  48645. int msElapsed, msTotal;
  48646. double startSpeed, midSpeed, endSpeed, lastProgress;
  48647. double left, top, right, bottom;
  48648. bool useTimeslice (const int elapsed)
  48649. {
  48650. if (component == 0)
  48651. return false;
  48652. msElapsed += elapsed;
  48653. double newProgress = msElapsed / (double) msTotal;
  48654. if (newProgress >= 0 && newProgress < 1.0)
  48655. {
  48656. newProgress = timeToDistance (newProgress);
  48657. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  48658. jassert (newProgress >= lastProgress);
  48659. lastProgress = newProgress;
  48660. left += (destination.getX() - left) * delta;
  48661. top += (destination.getY() - top) * delta;
  48662. right += (destination.getRight() - right) * delta;
  48663. bottom += (destination.getBottom() - bottom) * delta;
  48664. if (delta < 1.0)
  48665. {
  48666. const Rectangle<int> newBounds (roundToInt (left),
  48667. roundToInt (top),
  48668. roundToInt (right - left),
  48669. roundToInt (bottom - top));
  48670. if (newBounds != destination)
  48671. {
  48672. component->setBounds (newBounds);
  48673. return true;
  48674. }
  48675. }
  48676. }
  48677. component->setBounds (destination);
  48678. return false;
  48679. }
  48680. void moveToFinalDestination()
  48681. {
  48682. if (component != 0)
  48683. component->setBounds (destination);
  48684. }
  48685. private:
  48686. inline double timeToDistance (const double time) const
  48687. {
  48688. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  48689. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  48690. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  48691. }
  48692. };
  48693. ComponentAnimator::ComponentAnimator()
  48694. : lastTime (0)
  48695. {
  48696. }
  48697. ComponentAnimator::~ComponentAnimator()
  48698. {
  48699. cancelAllAnimations (false);
  48700. jassert (tasks.size() == 0);
  48701. }
  48702. ComponentAnimator::AnimationTask* ComponentAnimator::findTaskFor (Component* const component) const
  48703. {
  48704. for (int i = tasks.size(); --i >= 0;)
  48705. if (component == tasks.getUnchecked(i)->component.getComponent())
  48706. return tasks.getUnchecked(i);
  48707. return 0;
  48708. }
  48709. void ComponentAnimator::animateComponent (Component* const component,
  48710. const Rectangle<int>& finalPosition,
  48711. const int millisecondsToSpendMoving,
  48712. const double startSpeed,
  48713. const double endSpeed)
  48714. {
  48715. if (component != 0)
  48716. {
  48717. AnimationTask* at = findTaskFor (component);
  48718. if (at == 0)
  48719. {
  48720. at = new AnimationTask (component);
  48721. tasks.add (at);
  48722. sendChangeMessage (this);
  48723. }
  48724. at->msElapsed = 0;
  48725. at->lastProgress = 0;
  48726. at->msTotal = jmax (1, millisecondsToSpendMoving);
  48727. at->destination = finalPosition;
  48728. // the speeds must be 0 or greater!
  48729. jassert (startSpeed >= 0 && endSpeed >= 0)
  48730. const double invTotalDistance = 4.0 / (startSpeed + endSpeed + 2.0);
  48731. at->startSpeed = jmax (0.0, startSpeed * invTotalDistance);
  48732. at->midSpeed = invTotalDistance;
  48733. at->endSpeed = jmax (0.0, endSpeed * invTotalDistance);
  48734. at->left = component->getX();
  48735. at->top = component->getY();
  48736. at->right = component->getRight();
  48737. at->bottom = component->getBottom();
  48738. if (! isTimerRunning())
  48739. {
  48740. lastTime = Time::getMillisecondCounter();
  48741. startTimer (1000 / 50);
  48742. }
  48743. }
  48744. }
  48745. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  48746. {
  48747. for (int i = tasks.size(); --i >= 0;)
  48748. {
  48749. AnimationTask* const at = tasks.getUnchecked(i);
  48750. if (moveComponentsToTheirFinalPositions)
  48751. at->moveToFinalDestination();
  48752. delete at;
  48753. tasks.remove (i);
  48754. sendChangeMessage (this);
  48755. }
  48756. }
  48757. void ComponentAnimator::cancelAnimation (Component* const component,
  48758. const bool moveComponentToItsFinalPosition)
  48759. {
  48760. AnimationTask* const at = findTaskFor (component);
  48761. if (at != 0)
  48762. {
  48763. if (moveComponentToItsFinalPosition)
  48764. at->moveToFinalDestination();
  48765. tasks.removeValue (at);
  48766. delete at;
  48767. sendChangeMessage (this);
  48768. }
  48769. }
  48770. const Rectangle<int> ComponentAnimator::getComponentDestination (Component* const component)
  48771. {
  48772. AnimationTask* const at = findTaskFor (component);
  48773. if (at != 0)
  48774. return at->destination;
  48775. else if (component != 0)
  48776. return component->getBounds();
  48777. return Rectangle<int>();
  48778. }
  48779. bool ComponentAnimator::isAnimating (Component* component) const
  48780. {
  48781. return findTaskFor (component) != 0;
  48782. }
  48783. void ComponentAnimator::timerCallback()
  48784. {
  48785. const uint32 timeNow = Time::getMillisecondCounter();
  48786. if (lastTime == 0 || lastTime == timeNow)
  48787. lastTime = timeNow;
  48788. const int elapsed = timeNow - lastTime;
  48789. for (int i = tasks.size(); --i >= 0;)
  48790. {
  48791. AnimationTask* const at = tasks.getUnchecked(i);
  48792. if (! at->useTimeslice (elapsed))
  48793. {
  48794. tasks.remove (i);
  48795. delete at;
  48796. sendChangeMessage (this);
  48797. }
  48798. }
  48799. lastTime = timeNow;
  48800. if (tasks.size() == 0)
  48801. stopTimer();
  48802. }
  48803. END_JUCE_NAMESPACE
  48804. /*** End of inlined file: juce_ComponentAnimator.cpp ***/
  48805. /*** Start of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  48806. BEGIN_JUCE_NAMESPACE
  48807. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  48808. : minW (0),
  48809. maxW (0x3fffffff),
  48810. minH (0),
  48811. maxH (0x3fffffff),
  48812. minOffTop (0),
  48813. minOffLeft (0),
  48814. minOffBottom (0),
  48815. minOffRight (0),
  48816. aspectRatio (0.0)
  48817. {
  48818. }
  48819. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  48820. {
  48821. }
  48822. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  48823. {
  48824. minW = minimumWidth;
  48825. }
  48826. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  48827. {
  48828. maxW = maximumWidth;
  48829. }
  48830. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  48831. {
  48832. minH = minimumHeight;
  48833. }
  48834. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  48835. {
  48836. maxH = maximumHeight;
  48837. }
  48838. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  48839. {
  48840. jassert (maxW >= minimumWidth);
  48841. jassert (maxH >= minimumHeight);
  48842. jassert (minimumWidth > 0 && minimumHeight > 0);
  48843. minW = minimumWidth;
  48844. minH = minimumHeight;
  48845. if (minW > maxW)
  48846. maxW = minW;
  48847. if (minH > maxH)
  48848. maxH = minH;
  48849. }
  48850. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  48851. {
  48852. jassert (maximumWidth >= minW);
  48853. jassert (maximumHeight >= minH);
  48854. jassert (maximumWidth > 0 && maximumHeight > 0);
  48855. maxW = jmax (minW, maximumWidth);
  48856. maxH = jmax (minH, maximumHeight);
  48857. }
  48858. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  48859. const int minimumHeight,
  48860. const int maximumWidth,
  48861. const int maximumHeight) throw()
  48862. {
  48863. jassert (maximumWidth >= minimumWidth);
  48864. jassert (maximumHeight >= minimumHeight);
  48865. jassert (maximumWidth > 0 && maximumHeight > 0);
  48866. jassert (minimumWidth > 0 && minimumHeight > 0);
  48867. minW = jmax (0, minimumWidth);
  48868. minH = jmax (0, minimumHeight);
  48869. maxW = jmax (minW, maximumWidth);
  48870. maxH = jmax (minH, maximumHeight);
  48871. }
  48872. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  48873. const int minimumWhenOffTheLeft,
  48874. const int minimumWhenOffTheBottom,
  48875. const int minimumWhenOffTheRight) throw()
  48876. {
  48877. minOffTop = minimumWhenOffTheTop;
  48878. minOffLeft = minimumWhenOffTheLeft;
  48879. minOffBottom = minimumWhenOffTheBottom;
  48880. minOffRight = minimumWhenOffTheRight;
  48881. }
  48882. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  48883. {
  48884. aspectRatio = jmax (0.0, widthOverHeight);
  48885. }
  48886. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  48887. {
  48888. return aspectRatio;
  48889. }
  48890. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  48891. const Rectangle<int>& targetBounds,
  48892. const bool isStretchingTop,
  48893. const bool isStretchingLeft,
  48894. const bool isStretchingBottom,
  48895. const bool isStretchingRight)
  48896. {
  48897. jassert (component != 0);
  48898. Rectangle<int> limits, bounds (targetBounds);
  48899. BorderSize border;
  48900. Component* const parent = component->getParentComponent();
  48901. if (parent == 0)
  48902. {
  48903. ComponentPeer* peer = component->getPeer();
  48904. if (peer != 0)
  48905. border = peer->getFrameSize();
  48906. limits = Desktop::getInstance().getMonitorAreaContaining (bounds.getCentre());
  48907. }
  48908. else
  48909. {
  48910. limits.setSize (parent->getWidth(), parent->getHeight());
  48911. }
  48912. border.addTo (bounds);
  48913. checkBounds (bounds,
  48914. border.addedTo (component->getBounds()), limits,
  48915. isStretchingTop, isStretchingLeft,
  48916. isStretchingBottom, isStretchingRight);
  48917. border.subtractFrom (bounds);
  48918. applyBoundsToComponent (component, bounds);
  48919. }
  48920. void ComponentBoundsConstrainer::checkComponentBounds (Component* component)
  48921. {
  48922. setBoundsForComponent (component, component->getBounds(),
  48923. false, false, false, false);
  48924. }
  48925. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  48926. const Rectangle<int>& bounds)
  48927. {
  48928. component->setBounds (bounds);
  48929. }
  48930. void ComponentBoundsConstrainer::resizeStart()
  48931. {
  48932. }
  48933. void ComponentBoundsConstrainer::resizeEnd()
  48934. {
  48935. }
  48936. void ComponentBoundsConstrainer::checkBounds (Rectangle<int>& bounds,
  48937. const Rectangle<int>& old,
  48938. const Rectangle<int>& limits,
  48939. const bool isStretchingTop,
  48940. const bool isStretchingLeft,
  48941. const bool isStretchingBottom,
  48942. const bool isStretchingRight)
  48943. {
  48944. int x = bounds.getX();
  48945. int y = bounds.getY();
  48946. int w = bounds.getWidth();
  48947. int h = bounds.getHeight();
  48948. // constrain the size if it's being stretched..
  48949. if (isStretchingLeft)
  48950. {
  48951. x = jlimit (old.getRight() - maxW, old.getRight() - minW, x);
  48952. w = old.getRight() - x;
  48953. }
  48954. if (isStretchingRight)
  48955. {
  48956. w = jlimit (minW, maxW, w);
  48957. }
  48958. if (isStretchingTop)
  48959. {
  48960. y = jlimit (old.getBottom() - maxH, old.getBottom() - minH, y);
  48961. h = old.getBottom() - y;
  48962. }
  48963. if (isStretchingBottom)
  48964. {
  48965. h = jlimit (minH, maxH, h);
  48966. }
  48967. // constrain the aspect ratio if one has been specified..
  48968. if (aspectRatio > 0.0 && w > 0 && h > 0)
  48969. {
  48970. bool adjustWidth;
  48971. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  48972. {
  48973. adjustWidth = true;
  48974. }
  48975. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  48976. {
  48977. adjustWidth = false;
  48978. }
  48979. else
  48980. {
  48981. const double oldRatio = (old.getHeight() > 0) ? std::abs (old.getWidth() / (double) old.getHeight()) : 0.0;
  48982. const double newRatio = std::abs (w / (double) h);
  48983. adjustWidth = (oldRatio > newRatio);
  48984. }
  48985. if (adjustWidth)
  48986. {
  48987. w = roundToInt (h * aspectRatio);
  48988. if (w > maxW || w < minW)
  48989. {
  48990. w = jlimit (minW, maxW, w);
  48991. h = roundToInt (w / aspectRatio);
  48992. }
  48993. }
  48994. else
  48995. {
  48996. h = roundToInt (w / aspectRatio);
  48997. if (h > maxH || h < minH)
  48998. {
  48999. h = jlimit (minH, maxH, h);
  49000. w = roundToInt (h * aspectRatio);
  49001. }
  49002. }
  49003. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49004. {
  49005. x = old.getX() + (old.getWidth() - w) / 2;
  49006. }
  49007. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49008. {
  49009. y = old.getY() + (old.getHeight() - h) / 2;
  49010. }
  49011. else
  49012. {
  49013. if (isStretchingLeft)
  49014. x = old.getRight() - w;
  49015. if (isStretchingTop)
  49016. y = old.getBottom() - h;
  49017. }
  49018. }
  49019. // ...and constrain the position if limits have been set for that.
  49020. if (minOffTop > 0 || minOffLeft > 0 || minOffBottom > 0 || minOffRight > 0)
  49021. {
  49022. if (minOffTop > 0)
  49023. {
  49024. const int limit = limits.getY() + jmin (minOffTop - h, 0);
  49025. if (y < limit)
  49026. {
  49027. if (isStretchingTop)
  49028. h -= (limit - y);
  49029. y = limit;
  49030. }
  49031. }
  49032. if (minOffLeft > 0)
  49033. {
  49034. const int limit = limits.getX() + jmin (minOffLeft - w, 0);
  49035. if (x < limit)
  49036. {
  49037. if (isStretchingLeft)
  49038. w -= (limit - x);
  49039. x = limit;
  49040. }
  49041. }
  49042. if (minOffBottom > 0)
  49043. {
  49044. const int limit = limits.getBottom() - jmin (minOffBottom, h);
  49045. if (y > limit)
  49046. {
  49047. if (isStretchingBottom)
  49048. h += (limit - y);
  49049. else
  49050. y = limit;
  49051. }
  49052. }
  49053. if (minOffRight > 0)
  49054. {
  49055. const int limit = limits.getRight() - jmin (minOffRight, w);
  49056. if (x > limit)
  49057. {
  49058. if (isStretchingRight)
  49059. w += (limit - x);
  49060. else
  49061. x = limit;
  49062. }
  49063. }
  49064. }
  49065. jassert (w >= 0 && h >= 0);
  49066. bounds = Rectangle<int> (x, y, w, h);
  49067. }
  49068. END_JUCE_NAMESPACE
  49069. /*** End of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49070. /*** Start of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49071. BEGIN_JUCE_NAMESPACE
  49072. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  49073. : component (component_),
  49074. lastPeer (0),
  49075. reentrant (false)
  49076. {
  49077. jassert (component != 0); // can't use this with a null pointer..
  49078. component->addComponentListener (this);
  49079. registerWithParentComps();
  49080. }
  49081. ComponentMovementWatcher::~ComponentMovementWatcher()
  49082. {
  49083. component->removeComponentListener (this);
  49084. unregister();
  49085. }
  49086. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  49087. {
  49088. // agh! don't delete the target component without deleting this object first!
  49089. jassert (component != 0);
  49090. if (! reentrant)
  49091. {
  49092. reentrant = true;
  49093. ComponentPeer* const peer = component->getPeer();
  49094. if (peer != lastPeer)
  49095. {
  49096. componentPeerChanged();
  49097. if (component == 0)
  49098. return;
  49099. lastPeer = peer;
  49100. }
  49101. unregister();
  49102. registerWithParentComps();
  49103. reentrant = false;
  49104. componentMovedOrResized (*component, true, true);
  49105. }
  49106. }
  49107. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  49108. {
  49109. // agh! don't delete the target component without deleting this object first!
  49110. jassert (component != 0);
  49111. if (wasMoved)
  49112. {
  49113. const Point<int> pos (component->relativePositionToOtherComponent (component->getTopLevelComponent(), Point<int>()));
  49114. wasMoved = lastBounds.getPosition() != pos;
  49115. lastBounds.setPosition (pos);
  49116. }
  49117. wasResized = (lastBounds.getWidth() != component->getWidth() || lastBounds.getHeight() != component->getHeight());
  49118. lastBounds.setSize (component->getWidth(), component->getHeight());
  49119. if (wasMoved || wasResized)
  49120. componentMovedOrResized (wasMoved, wasResized);
  49121. }
  49122. void ComponentMovementWatcher::registerWithParentComps() throw()
  49123. {
  49124. Component* p = component->getParentComponent();
  49125. while (p != 0)
  49126. {
  49127. p->addComponentListener (this);
  49128. registeredParentComps.add (p);
  49129. p = p->getParentComponent();
  49130. }
  49131. }
  49132. void ComponentMovementWatcher::unregister() throw()
  49133. {
  49134. for (int i = registeredParentComps.size(); --i >= 0;)
  49135. registeredParentComps.getUnchecked(i)->removeComponentListener (this);
  49136. registeredParentComps.clear();
  49137. }
  49138. END_JUCE_NAMESPACE
  49139. /*** End of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49140. /*** Start of inlined file: juce_GroupComponent.cpp ***/
  49141. BEGIN_JUCE_NAMESPACE
  49142. GroupComponent::GroupComponent (const String& componentName,
  49143. const String& labelText)
  49144. : Component (componentName),
  49145. text (labelText),
  49146. justification (Justification::left)
  49147. {
  49148. setInterceptsMouseClicks (false, true);
  49149. }
  49150. GroupComponent::~GroupComponent()
  49151. {
  49152. }
  49153. void GroupComponent::setText (const String& newText)
  49154. {
  49155. if (text != newText)
  49156. {
  49157. text = newText;
  49158. repaint();
  49159. }
  49160. }
  49161. const String GroupComponent::getText() const
  49162. {
  49163. return text;
  49164. }
  49165. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  49166. {
  49167. if (justification != newJustification)
  49168. {
  49169. justification = newJustification;
  49170. repaint();
  49171. }
  49172. }
  49173. void GroupComponent::paint (Graphics& g)
  49174. {
  49175. getLookAndFeel()
  49176. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  49177. text, justification,
  49178. *this);
  49179. }
  49180. void GroupComponent::enablementChanged()
  49181. {
  49182. repaint();
  49183. }
  49184. void GroupComponent::colourChanged()
  49185. {
  49186. repaint();
  49187. }
  49188. END_JUCE_NAMESPACE
  49189. /*** End of inlined file: juce_GroupComponent.cpp ***/
  49190. /*** Start of inlined file: juce_MultiDocumentPanel.cpp ***/
  49191. BEGIN_JUCE_NAMESPACE
  49192. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  49193. : DocumentWindow (String::empty, backgroundColour,
  49194. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  49195. {
  49196. }
  49197. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  49198. {
  49199. }
  49200. void MultiDocumentPanelWindow::maximiseButtonPressed()
  49201. {
  49202. MultiDocumentPanel* const owner = getOwner();
  49203. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  49204. if (owner != 0)
  49205. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  49206. }
  49207. void MultiDocumentPanelWindow::closeButtonPressed()
  49208. {
  49209. MultiDocumentPanel* const owner = getOwner();
  49210. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  49211. if (owner != 0)
  49212. owner->closeDocument (getContentComponent(), true);
  49213. }
  49214. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  49215. {
  49216. DocumentWindow::activeWindowStatusChanged();
  49217. updateOrder();
  49218. }
  49219. void MultiDocumentPanelWindow::broughtToFront()
  49220. {
  49221. DocumentWindow::broughtToFront();
  49222. updateOrder();
  49223. }
  49224. void MultiDocumentPanelWindow::updateOrder()
  49225. {
  49226. MultiDocumentPanel* const owner = getOwner();
  49227. if (owner != 0)
  49228. owner->updateOrder();
  49229. }
  49230. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  49231. {
  49232. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  49233. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  49234. }
  49235. class MDITabbedComponentInternal : public TabbedComponent
  49236. {
  49237. public:
  49238. MDITabbedComponentInternal()
  49239. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  49240. {
  49241. }
  49242. ~MDITabbedComponentInternal()
  49243. {
  49244. }
  49245. void currentTabChanged (int, const String&)
  49246. {
  49247. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  49248. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  49249. if (owner != 0)
  49250. owner->updateOrder();
  49251. }
  49252. };
  49253. MultiDocumentPanel::MultiDocumentPanel()
  49254. : mode (MaximisedWindowsWithTabs),
  49255. tabComponent (0),
  49256. backgroundColour (Colours::lightblue),
  49257. maximumNumDocuments (0),
  49258. numDocsBeforeTabsUsed (0)
  49259. {
  49260. setOpaque (true);
  49261. }
  49262. MultiDocumentPanel::~MultiDocumentPanel()
  49263. {
  49264. closeAllDocuments (false);
  49265. }
  49266. static bool shouldDeleteComp (Component* const c)
  49267. {
  49268. return c->getProperties() ["mdiDocumentDelete_"];
  49269. }
  49270. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  49271. {
  49272. while (components.size() > 0)
  49273. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  49274. return false;
  49275. return true;
  49276. }
  49277. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  49278. {
  49279. return new MultiDocumentPanelWindow (backgroundColour);
  49280. }
  49281. void MultiDocumentPanel::addWindow (Component* component)
  49282. {
  49283. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  49284. dw->setResizable (true, false);
  49285. dw->setContentComponent (component, false, true);
  49286. dw->setName (component->getName());
  49287. const var bkg (component->getProperties() ["mdiDocumentBkg_"]);
  49288. dw->setBackgroundColour (bkg.isVoid() ? backgroundColour : Colour ((int) bkg));
  49289. int x = 4;
  49290. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  49291. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  49292. x += 16;
  49293. dw->setTopLeftPosition (x, x);
  49294. const var pos (component->getProperties() ["mdiDocumentPos_"]);
  49295. if (pos.toString().isNotEmpty())
  49296. dw->restoreWindowStateFromString (pos.toString());
  49297. addAndMakeVisible (dw);
  49298. dw->toFront (true);
  49299. }
  49300. bool MultiDocumentPanel::addDocument (Component* const component,
  49301. const Colour& docColour,
  49302. const bool deleteWhenRemoved)
  49303. {
  49304. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  49305. // with a frame-within-a-frame! Just pass in the bare content component.
  49306. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  49307. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  49308. return false;
  49309. components.add (component);
  49310. component->getProperties().set ("mdiDocumentDelete_", deleteWhenRemoved);
  49311. component->getProperties().set ("mdiDocumentBkg_", (int) docColour.getARGB());
  49312. component->addComponentListener (this);
  49313. if (mode == FloatingWindows)
  49314. {
  49315. if (isFullscreenWhenOneDocument())
  49316. {
  49317. if (components.size() == 1)
  49318. {
  49319. addAndMakeVisible (component);
  49320. }
  49321. else
  49322. {
  49323. if (components.size() == 2)
  49324. addWindow (components.getFirst());
  49325. addWindow (component);
  49326. }
  49327. }
  49328. else
  49329. {
  49330. addWindow (component);
  49331. }
  49332. }
  49333. else
  49334. {
  49335. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  49336. {
  49337. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  49338. Array <Component*> temp (components);
  49339. for (int i = 0; i < temp.size(); ++i)
  49340. tabComponent->addTab (temp[i]->getName(), docColour, temp[i], false);
  49341. resized();
  49342. }
  49343. else
  49344. {
  49345. if (tabComponent != 0)
  49346. tabComponent->addTab (component->getName(), docColour, component, false);
  49347. else
  49348. addAndMakeVisible (component);
  49349. }
  49350. setActiveDocument (component);
  49351. }
  49352. resized();
  49353. activeDocumentChanged();
  49354. return true;
  49355. }
  49356. bool MultiDocumentPanel::closeDocument (Component* component,
  49357. const bool checkItsOkToCloseFirst)
  49358. {
  49359. if (components.contains (component))
  49360. {
  49361. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  49362. return false;
  49363. component->removeComponentListener (this);
  49364. const bool shouldDelete = shouldDeleteComp (component);
  49365. component->getProperties().remove ("mdiDocumentDelete_");
  49366. component->getProperties().remove ("mdiDocumentBkg_");
  49367. if (mode == FloatingWindows)
  49368. {
  49369. for (int i = getNumChildComponents(); --i >= 0;)
  49370. {
  49371. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49372. if (dw != 0 && dw->getContentComponent() == component)
  49373. {
  49374. dw->setContentComponent (0, false);
  49375. delete dw;
  49376. break;
  49377. }
  49378. }
  49379. if (shouldDelete)
  49380. delete component;
  49381. components.removeValue (component);
  49382. if (isFullscreenWhenOneDocument() && components.size() == 1)
  49383. {
  49384. for (int i = getNumChildComponents(); --i >= 0;)
  49385. {
  49386. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49387. if (dw != 0)
  49388. {
  49389. dw->setContentComponent (0, false);
  49390. delete dw;
  49391. }
  49392. }
  49393. addAndMakeVisible (components.getFirst());
  49394. }
  49395. }
  49396. else
  49397. {
  49398. jassert (components.indexOf (component) >= 0);
  49399. if (tabComponent != 0)
  49400. {
  49401. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  49402. if (tabComponent->getTabContentComponent (i) == component)
  49403. tabComponent->removeTab (i);
  49404. }
  49405. else
  49406. {
  49407. removeChildComponent (component);
  49408. }
  49409. if (shouldDelete)
  49410. delete component;
  49411. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  49412. deleteAndZero (tabComponent);
  49413. components.removeValue (component);
  49414. if (components.size() > 0 && tabComponent == 0)
  49415. addAndMakeVisible (components.getFirst());
  49416. }
  49417. resized();
  49418. activeDocumentChanged();
  49419. }
  49420. else
  49421. {
  49422. jassertfalse;
  49423. }
  49424. return true;
  49425. }
  49426. int MultiDocumentPanel::getNumDocuments() const throw()
  49427. {
  49428. return components.size();
  49429. }
  49430. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  49431. {
  49432. return components [index];
  49433. }
  49434. Component* MultiDocumentPanel::getActiveDocument() const throw()
  49435. {
  49436. if (mode == FloatingWindows)
  49437. {
  49438. for (int i = getNumChildComponents(); --i >= 0;)
  49439. {
  49440. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49441. if (dw != 0 && dw->isActiveWindow())
  49442. return dw->getContentComponent();
  49443. }
  49444. }
  49445. return components.getLast();
  49446. }
  49447. void MultiDocumentPanel::setActiveDocument (Component* component)
  49448. {
  49449. if (mode == FloatingWindows)
  49450. {
  49451. component = getContainerComp (component);
  49452. if (component != 0)
  49453. component->toFront (true);
  49454. }
  49455. else if (tabComponent != 0)
  49456. {
  49457. jassert (components.indexOf (component) >= 0);
  49458. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  49459. {
  49460. if (tabComponent->getTabContentComponent (i) == component)
  49461. {
  49462. tabComponent->setCurrentTabIndex (i);
  49463. break;
  49464. }
  49465. }
  49466. }
  49467. else
  49468. {
  49469. component->grabKeyboardFocus();
  49470. }
  49471. }
  49472. void MultiDocumentPanel::activeDocumentChanged()
  49473. {
  49474. }
  49475. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  49476. {
  49477. maximumNumDocuments = newNumber;
  49478. }
  49479. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  49480. {
  49481. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  49482. }
  49483. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  49484. {
  49485. return numDocsBeforeTabsUsed != 0;
  49486. }
  49487. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  49488. {
  49489. if (mode != newLayoutMode)
  49490. {
  49491. mode = newLayoutMode;
  49492. if (mode == FloatingWindows)
  49493. {
  49494. deleteAndZero (tabComponent);
  49495. }
  49496. else
  49497. {
  49498. for (int i = getNumChildComponents(); --i >= 0;)
  49499. {
  49500. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49501. if (dw != 0)
  49502. {
  49503. dw->getContentComponent()->getProperties().set ("mdiDocumentPos_", dw->getWindowStateAsString());
  49504. dw->setContentComponent (0, false);
  49505. delete dw;
  49506. }
  49507. }
  49508. }
  49509. resized();
  49510. const Array <Component*> tempComps (components);
  49511. components.clear();
  49512. for (int i = 0; i < tempComps.size(); ++i)
  49513. {
  49514. Component* const c = tempComps.getUnchecked(i);
  49515. addDocument (c,
  49516. Colour ((int) c->getProperties().getWithDefault ("mdiDocumentBkg_", (int) Colours::white.getARGB())),
  49517. shouldDeleteComp (c));
  49518. }
  49519. }
  49520. }
  49521. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  49522. {
  49523. if (backgroundColour != newBackgroundColour)
  49524. {
  49525. backgroundColour = newBackgroundColour;
  49526. setOpaque (newBackgroundColour.isOpaque());
  49527. repaint();
  49528. }
  49529. }
  49530. void MultiDocumentPanel::paint (Graphics& g)
  49531. {
  49532. g.fillAll (backgroundColour);
  49533. }
  49534. void MultiDocumentPanel::resized()
  49535. {
  49536. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  49537. {
  49538. for (int i = getNumChildComponents(); --i >= 0;)
  49539. getChildComponent (i)->setBounds (getLocalBounds());
  49540. }
  49541. setWantsKeyboardFocus (components.size() == 0);
  49542. }
  49543. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  49544. {
  49545. if (mode == FloatingWindows)
  49546. {
  49547. for (int i = 0; i < getNumChildComponents(); ++i)
  49548. {
  49549. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49550. if (dw != 0 && dw->getContentComponent() == c)
  49551. {
  49552. c = dw;
  49553. break;
  49554. }
  49555. }
  49556. }
  49557. return c;
  49558. }
  49559. void MultiDocumentPanel::componentNameChanged (Component&)
  49560. {
  49561. if (mode == FloatingWindows)
  49562. {
  49563. for (int i = 0; i < getNumChildComponents(); ++i)
  49564. {
  49565. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49566. if (dw != 0)
  49567. dw->setName (dw->getContentComponent()->getName());
  49568. }
  49569. }
  49570. else if (tabComponent != 0)
  49571. {
  49572. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  49573. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  49574. }
  49575. }
  49576. void MultiDocumentPanel::updateOrder()
  49577. {
  49578. const Array <Component*> oldList (components);
  49579. if (mode == FloatingWindows)
  49580. {
  49581. components.clear();
  49582. for (int i = 0; i < getNumChildComponents(); ++i)
  49583. {
  49584. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  49585. if (dw != 0)
  49586. components.add (dw->getContentComponent());
  49587. }
  49588. }
  49589. else
  49590. {
  49591. if (tabComponent != 0)
  49592. {
  49593. Component* const current = tabComponent->getCurrentContentComponent();
  49594. if (current != 0)
  49595. {
  49596. components.removeValue (current);
  49597. components.add (current);
  49598. }
  49599. }
  49600. }
  49601. if (components != oldList)
  49602. activeDocumentChanged();
  49603. }
  49604. END_JUCE_NAMESPACE
  49605. /*** End of inlined file: juce_MultiDocumentPanel.cpp ***/
  49606. /*** Start of inlined file: juce_ResizableBorderComponent.cpp ***/
  49607. BEGIN_JUCE_NAMESPACE
  49608. ResizableBorderComponent::Zone::Zone (int zoneFlags) throw()
  49609. : zone (zoneFlags)
  49610. {
  49611. }
  49612. ResizableBorderComponent::Zone::Zone (const ResizableBorderComponent::Zone& other) throw() : zone (other.zone) {}
  49613. ResizableBorderComponent::Zone& ResizableBorderComponent::Zone::operator= (const ResizableBorderComponent::Zone& other) throw() { zone = other.zone; return *this; }
  49614. bool ResizableBorderComponent::Zone::operator== (const ResizableBorderComponent::Zone& other) const throw() { return zone == other.zone; }
  49615. bool ResizableBorderComponent::Zone::operator!= (const ResizableBorderComponent::Zone& other) const throw() { return zone != other.zone; }
  49616. const ResizableBorderComponent::Zone ResizableBorderComponent::Zone::fromPositionOnBorder (const Rectangle<int>& totalSize,
  49617. const BorderSize& border,
  49618. const Point<int>& position)
  49619. {
  49620. int z = 0;
  49621. if (totalSize.contains (position)
  49622. && ! border.subtractedFrom (totalSize).contains (position))
  49623. {
  49624. const int minW = jmax (totalSize.getWidth() / 10, jmin (10, totalSize.getWidth() / 3));
  49625. if (position.getX() < jmax (border.getLeft(), minW))
  49626. z |= left;
  49627. else if (position.getX() >= totalSize.getWidth() - jmax (border.getRight(), minW))
  49628. z |= right;
  49629. const int minH = jmax (totalSize.getHeight() / 10, jmin (10, totalSize.getHeight() / 3));
  49630. if (position.getY() < jmax (border.getTop(), minH))
  49631. z |= top;
  49632. else if (position.getY() >= totalSize.getHeight() - jmax (border.getBottom(), minH))
  49633. z |= bottom;
  49634. }
  49635. return Zone (z);
  49636. }
  49637. const MouseCursor ResizableBorderComponent::Zone::getMouseCursor() const throw()
  49638. {
  49639. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  49640. switch (zone)
  49641. {
  49642. case (left | top): mc = MouseCursor::TopLeftCornerResizeCursor; break;
  49643. case top: mc = MouseCursor::TopEdgeResizeCursor; break;
  49644. case (right | top): mc = MouseCursor::TopRightCornerResizeCursor; break;
  49645. case left: mc = MouseCursor::LeftEdgeResizeCursor; break;
  49646. case right: mc = MouseCursor::RightEdgeResizeCursor; break;
  49647. case (left | bottom): mc = MouseCursor::BottomLeftCornerResizeCursor; break;
  49648. case bottom: mc = MouseCursor::BottomEdgeResizeCursor; break;
  49649. case (right | bottom): mc = MouseCursor::BottomRightCornerResizeCursor; break;
  49650. default: break;
  49651. }
  49652. return mc;
  49653. }
  49654. const Rectangle<int> ResizableBorderComponent::Zone::resizeRectangleBy (Rectangle<int> b, const Point<int>& offset) const throw()
  49655. {
  49656. if (isDraggingWholeObject())
  49657. return b + offset;
  49658. if (isDraggingLeftEdge())
  49659. b.setLeft (b.getX() + offset.getX());
  49660. if (isDraggingRightEdge())
  49661. b.setWidth (jmax (0, b.getWidth() + offset.getX()));
  49662. if (isDraggingTopEdge())
  49663. b.setTop (b.getY() + offset.getY());
  49664. if (isDraggingBottomEdge())
  49665. b.setHeight (jmax (0, b.getHeight() + offset.getY()));
  49666. return b;
  49667. }
  49668. const Rectangle<float> ResizableBorderComponent::Zone::resizeRectangleBy (Rectangle<float> b, const Point<float>& offset) const throw()
  49669. {
  49670. if (isDraggingWholeObject())
  49671. return b + offset;
  49672. if (isDraggingLeftEdge())
  49673. b.setLeft (b.getX() + offset.getX());
  49674. if (isDraggingRightEdge())
  49675. b.setWidth (jmax (0.0f, b.getWidth() + offset.getX()));
  49676. if (isDraggingTopEdge())
  49677. b.setTop (b.getY() + offset.getY());
  49678. if (isDraggingBottomEdge())
  49679. b.setHeight (jmax (0.0f, b.getHeight() + offset.getY()));
  49680. return b;
  49681. }
  49682. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  49683. ComponentBoundsConstrainer* const constrainer_)
  49684. : component (componentToResize),
  49685. constrainer (constrainer_),
  49686. borderSize (5),
  49687. mouseZone (0)
  49688. {
  49689. }
  49690. ResizableBorderComponent::~ResizableBorderComponent()
  49691. {
  49692. }
  49693. void ResizableBorderComponent::paint (Graphics& g)
  49694. {
  49695. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  49696. }
  49697. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  49698. {
  49699. updateMouseZone (e);
  49700. }
  49701. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  49702. {
  49703. updateMouseZone (e);
  49704. }
  49705. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  49706. {
  49707. if (component == 0)
  49708. {
  49709. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  49710. return;
  49711. }
  49712. updateMouseZone (e);
  49713. originalBounds = component->getBounds();
  49714. if (constrainer != 0)
  49715. constrainer->resizeStart();
  49716. }
  49717. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  49718. {
  49719. if (component == 0)
  49720. {
  49721. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  49722. return;
  49723. }
  49724. const Rectangle<int> bounds (mouseZone.resizeRectangleBy (originalBounds, e.getOffsetFromDragStart()));
  49725. if (constrainer != 0)
  49726. constrainer->setBoundsForComponent (component, bounds,
  49727. mouseZone.isDraggingTopEdge(),
  49728. mouseZone.isDraggingLeftEdge(),
  49729. mouseZone.isDraggingBottomEdge(),
  49730. mouseZone.isDraggingRightEdge());
  49731. else
  49732. component->setBounds (bounds);
  49733. }
  49734. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  49735. {
  49736. if (constrainer != 0)
  49737. constrainer->resizeEnd();
  49738. }
  49739. bool ResizableBorderComponent::hitTest (int x, int y)
  49740. {
  49741. return x < borderSize.getLeft()
  49742. || x >= getWidth() - borderSize.getRight()
  49743. || y < borderSize.getTop()
  49744. || y >= getHeight() - borderSize.getBottom();
  49745. }
  49746. void ResizableBorderComponent::setBorderThickness (const BorderSize& newBorderSize)
  49747. {
  49748. if (borderSize != newBorderSize)
  49749. {
  49750. borderSize = newBorderSize;
  49751. repaint();
  49752. }
  49753. }
  49754. const BorderSize ResizableBorderComponent::getBorderThickness() const
  49755. {
  49756. return borderSize;
  49757. }
  49758. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e)
  49759. {
  49760. Zone newZone (Zone::fromPositionOnBorder (getLocalBounds(), borderSize, e.getPosition()));
  49761. if (mouseZone != newZone)
  49762. {
  49763. mouseZone = newZone;
  49764. setMouseCursor (newZone.getMouseCursor());
  49765. }
  49766. }
  49767. END_JUCE_NAMESPACE
  49768. /*** End of inlined file: juce_ResizableBorderComponent.cpp ***/
  49769. /*** Start of inlined file: juce_ResizableCornerComponent.cpp ***/
  49770. BEGIN_JUCE_NAMESPACE
  49771. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  49772. ComponentBoundsConstrainer* const constrainer_)
  49773. : component (componentToResize),
  49774. constrainer (constrainer_)
  49775. {
  49776. setRepaintsOnMouseActivity (true);
  49777. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  49778. }
  49779. ResizableCornerComponent::~ResizableCornerComponent()
  49780. {
  49781. }
  49782. void ResizableCornerComponent::paint (Graphics& g)
  49783. {
  49784. getLookAndFeel()
  49785. .drawCornerResizer (g, getWidth(), getHeight(),
  49786. isMouseOverOrDragging(),
  49787. isMouseButtonDown());
  49788. }
  49789. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  49790. {
  49791. if (component == 0)
  49792. {
  49793. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  49794. return;
  49795. }
  49796. originalBounds = component->getBounds();
  49797. if (constrainer != 0)
  49798. constrainer->resizeStart();
  49799. }
  49800. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  49801. {
  49802. if (component == 0)
  49803. {
  49804. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  49805. return;
  49806. }
  49807. Rectangle<int> r (originalBounds.withSize (originalBounds.getWidth() + e.getDistanceFromDragStartX(),
  49808. originalBounds.getHeight() + e.getDistanceFromDragStartY()));
  49809. if (constrainer != 0)
  49810. constrainer->setBoundsForComponent (component, r, false, false, true, true);
  49811. else
  49812. component->setBounds (r);
  49813. }
  49814. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  49815. {
  49816. if (constrainer != 0)
  49817. constrainer->resizeStart();
  49818. }
  49819. bool ResizableCornerComponent::hitTest (int x, int y)
  49820. {
  49821. if (getWidth() <= 0)
  49822. return false;
  49823. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  49824. return y >= yAtX - getHeight() / 4;
  49825. }
  49826. END_JUCE_NAMESPACE
  49827. /*** End of inlined file: juce_ResizableCornerComponent.cpp ***/
  49828. /*** Start of inlined file: juce_ScrollBar.cpp ***/
  49829. BEGIN_JUCE_NAMESPACE
  49830. class ScrollBar::ScrollbarButton : public Button
  49831. {
  49832. public:
  49833. int direction;
  49834. ScrollbarButton (const int direction_, ScrollBar& owner_)
  49835. : Button (String::empty),
  49836. direction (direction_),
  49837. owner (owner_)
  49838. {
  49839. setWantsKeyboardFocus (false);
  49840. }
  49841. ~ScrollbarButton()
  49842. {
  49843. }
  49844. void paintButton (Graphics& g, bool over, bool down)
  49845. {
  49846. getLookAndFeel()
  49847. .drawScrollbarButton (g, owner,
  49848. getWidth(), getHeight(),
  49849. direction,
  49850. owner.isVertical(),
  49851. over, down);
  49852. }
  49853. void clicked()
  49854. {
  49855. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  49856. }
  49857. juce_UseDebuggingNewOperator
  49858. private:
  49859. ScrollBar& owner;
  49860. ScrollbarButton (const ScrollbarButton&);
  49861. ScrollbarButton& operator= (const ScrollbarButton&);
  49862. };
  49863. ScrollBar::ScrollBar (const bool vertical_,
  49864. const bool buttonsAreVisible)
  49865. : totalRange (0.0, 1.0),
  49866. visibleRange (0.0, 0.1),
  49867. singleStepSize (0.1),
  49868. thumbAreaStart (0),
  49869. thumbAreaSize (0),
  49870. thumbStart (0),
  49871. thumbSize (0),
  49872. initialDelayInMillisecs (100),
  49873. repeatDelayInMillisecs (50),
  49874. minimumDelayInMillisecs (10),
  49875. vertical (vertical_),
  49876. isDraggingThumb (false),
  49877. autohides (true)
  49878. {
  49879. setButtonVisibility (buttonsAreVisible);
  49880. setRepaintsOnMouseActivity (true);
  49881. setFocusContainer (true);
  49882. }
  49883. ScrollBar::~ScrollBar()
  49884. {
  49885. upButton = 0;
  49886. downButton = 0;
  49887. }
  49888. void ScrollBar::setRangeLimits (const Range<double>& newRangeLimit)
  49889. {
  49890. if (totalRange != newRangeLimit)
  49891. {
  49892. totalRange = newRangeLimit;
  49893. setCurrentRange (visibleRange);
  49894. updateThumbPosition();
  49895. }
  49896. }
  49897. void ScrollBar::setRangeLimits (const double newMinimum, const double newMaximum)
  49898. {
  49899. jassert (newMaximum >= newMinimum); // these can't be the wrong way round!
  49900. setRangeLimits (Range<double> (newMinimum, newMaximum));
  49901. }
  49902. void ScrollBar::setCurrentRange (const Range<double>& newRange)
  49903. {
  49904. const Range<double> constrainedRange (totalRange.constrainRange (newRange));
  49905. if (visibleRange != constrainedRange)
  49906. {
  49907. visibleRange = constrainedRange;
  49908. updateThumbPosition();
  49909. triggerAsyncUpdate();
  49910. }
  49911. }
  49912. void ScrollBar::setCurrentRange (const double newStart, const double newSize)
  49913. {
  49914. setCurrentRange (Range<double> (newStart, newStart + newSize));
  49915. }
  49916. void ScrollBar::setCurrentRangeStart (const double newStart)
  49917. {
  49918. setCurrentRange (visibleRange.movedToStartAt (newStart));
  49919. }
  49920. void ScrollBar::setSingleStepSize (const double newSingleStepSize)
  49921. {
  49922. singleStepSize = newSingleStepSize;
  49923. }
  49924. void ScrollBar::moveScrollbarInSteps (const int howManySteps)
  49925. {
  49926. setCurrentRange (visibleRange + howManySteps * singleStepSize);
  49927. }
  49928. void ScrollBar::moveScrollbarInPages (const int howManyPages)
  49929. {
  49930. setCurrentRange (visibleRange + howManyPages * visibleRange.getLength());
  49931. }
  49932. void ScrollBar::scrollToTop()
  49933. {
  49934. setCurrentRange (visibleRange.movedToStartAt (getMinimumRangeLimit()));
  49935. }
  49936. void ScrollBar::scrollToBottom()
  49937. {
  49938. setCurrentRange (visibleRange.movedToEndAt (getMaximumRangeLimit()));
  49939. }
  49940. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  49941. const int repeatDelayInMillisecs_,
  49942. const int minimumDelayInMillisecs_)
  49943. {
  49944. initialDelayInMillisecs = initialDelayInMillisecs_;
  49945. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  49946. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  49947. if (upButton != 0)
  49948. {
  49949. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  49950. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  49951. }
  49952. }
  49953. void ScrollBar::addListener (ScrollBarListener* const listener)
  49954. {
  49955. listeners.add (listener);
  49956. }
  49957. void ScrollBar::removeListener (ScrollBarListener* const listener)
  49958. {
  49959. listeners.remove (listener);
  49960. }
  49961. void ScrollBar::handleAsyncUpdate()
  49962. {
  49963. double start = visibleRange.getStart(); // (need to use a temp variable for VC7 compatibility)
  49964. listeners.call (&ScrollBarListener::scrollBarMoved, this, start);
  49965. }
  49966. void ScrollBar::updateThumbPosition()
  49967. {
  49968. int newThumbSize = roundToInt (totalRange.getLength() > 0 ? (visibleRange.getLength() * thumbAreaSize) / totalRange.getLength()
  49969. : thumbAreaSize);
  49970. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  49971. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  49972. if (newThumbSize > thumbAreaSize)
  49973. newThumbSize = thumbAreaSize;
  49974. int newThumbStart = thumbAreaStart;
  49975. if (totalRange.getLength() > visibleRange.getLength())
  49976. newThumbStart += roundToInt (((visibleRange.getStart() - totalRange.getStart()) * (thumbAreaSize - newThumbSize))
  49977. / (totalRange.getLength() - visibleRange.getLength()));
  49978. setVisible ((! autohides) || (totalRange.getLength() > visibleRange.getLength() && visibleRange.getLength() > 0.0));
  49979. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  49980. {
  49981. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  49982. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  49983. if (vertical)
  49984. repaint (0, repaintStart, getWidth(), repaintSize);
  49985. else
  49986. repaint (repaintStart, 0, repaintSize, getHeight());
  49987. thumbStart = newThumbStart;
  49988. thumbSize = newThumbSize;
  49989. }
  49990. }
  49991. void ScrollBar::setOrientation (const bool shouldBeVertical)
  49992. {
  49993. if (vertical != shouldBeVertical)
  49994. {
  49995. vertical = shouldBeVertical;
  49996. if (upButton != 0)
  49997. {
  49998. upButton->direction = vertical ? 0 : 3;
  49999. downButton->direction = vertical ? 2 : 1;
  50000. }
  50001. updateThumbPosition();
  50002. }
  50003. }
  50004. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  50005. {
  50006. upButton = 0;
  50007. downButton = 0;
  50008. if (buttonsAreVisible)
  50009. {
  50010. addAndMakeVisible (upButton = new ScrollbarButton (vertical ? 0 : 3, *this));
  50011. addAndMakeVisible (downButton = new ScrollbarButton (vertical ? 2 : 1, *this));
  50012. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50013. }
  50014. updateThumbPosition();
  50015. }
  50016. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  50017. {
  50018. autohides = shouldHideWhenFullRange;
  50019. updateThumbPosition();
  50020. }
  50021. bool ScrollBar::autoHides() const throw()
  50022. {
  50023. return autohides;
  50024. }
  50025. void ScrollBar::paint (Graphics& g)
  50026. {
  50027. if (thumbAreaSize > 0)
  50028. {
  50029. LookAndFeel& lf = getLookAndFeel();
  50030. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  50031. ? thumbSize : 0;
  50032. if (vertical)
  50033. {
  50034. lf.drawScrollbar (g, *this,
  50035. 0, thumbAreaStart,
  50036. getWidth(), thumbAreaSize,
  50037. vertical,
  50038. thumbStart, thumb,
  50039. isMouseOver(), isMouseButtonDown());
  50040. }
  50041. else
  50042. {
  50043. lf.drawScrollbar (g, *this,
  50044. thumbAreaStart, 0,
  50045. thumbAreaSize, getHeight(),
  50046. vertical,
  50047. thumbStart, thumb,
  50048. isMouseOver(), isMouseButtonDown());
  50049. }
  50050. }
  50051. }
  50052. void ScrollBar::lookAndFeelChanged()
  50053. {
  50054. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  50055. }
  50056. void ScrollBar::resized()
  50057. {
  50058. const int length = ((vertical) ? getHeight() : getWidth());
  50059. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  50060. : 0;
  50061. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50062. {
  50063. thumbAreaStart = length >> 1;
  50064. thumbAreaSize = 0;
  50065. }
  50066. else
  50067. {
  50068. thumbAreaStart = buttonSize;
  50069. thumbAreaSize = length - (buttonSize << 1);
  50070. }
  50071. if (upButton != 0)
  50072. {
  50073. if (vertical)
  50074. {
  50075. upButton->setBounds (0, 0, getWidth(), buttonSize);
  50076. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  50077. }
  50078. else
  50079. {
  50080. upButton->setBounds (0, 0, buttonSize, getHeight());
  50081. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  50082. }
  50083. }
  50084. updateThumbPosition();
  50085. }
  50086. void ScrollBar::mouseDown (const MouseEvent& e)
  50087. {
  50088. isDraggingThumb = false;
  50089. lastMousePos = vertical ? e.y : e.x;
  50090. dragStartMousePos = lastMousePos;
  50091. dragStartRange = visibleRange.getStart();
  50092. if (dragStartMousePos < thumbStart)
  50093. {
  50094. moveScrollbarInPages (-1);
  50095. startTimer (400);
  50096. }
  50097. else if (dragStartMousePos >= thumbStart + thumbSize)
  50098. {
  50099. moveScrollbarInPages (1);
  50100. startTimer (400);
  50101. }
  50102. else
  50103. {
  50104. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50105. && (thumbAreaSize > thumbSize);
  50106. }
  50107. }
  50108. void ScrollBar::mouseDrag (const MouseEvent& e)
  50109. {
  50110. if (isDraggingThumb)
  50111. {
  50112. const int deltaPixels = ((vertical) ? e.y : e.x) - dragStartMousePos;
  50113. setCurrentRangeStart (dragStartRange
  50114. + deltaPixels * (totalRange.getLength() - visibleRange.getLength())
  50115. / (thumbAreaSize - thumbSize));
  50116. }
  50117. else
  50118. {
  50119. lastMousePos = (vertical) ? e.y : e.x;
  50120. }
  50121. }
  50122. void ScrollBar::mouseUp (const MouseEvent&)
  50123. {
  50124. isDraggingThumb = false;
  50125. stopTimer();
  50126. repaint();
  50127. }
  50128. void ScrollBar::mouseWheelMove (const MouseEvent&,
  50129. float wheelIncrementX,
  50130. float wheelIncrementY)
  50131. {
  50132. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  50133. if (increment < 0)
  50134. increment = jmin (increment * 10.0f, -1.0f);
  50135. else if (increment > 0)
  50136. increment = jmax (increment * 10.0f, 1.0f);
  50137. setCurrentRange (visibleRange - singleStepSize * increment);
  50138. }
  50139. void ScrollBar::timerCallback()
  50140. {
  50141. if (isMouseButtonDown())
  50142. {
  50143. startTimer (40);
  50144. if (lastMousePos < thumbStart)
  50145. setCurrentRange (visibleRange - visibleRange.getLength());
  50146. else if (lastMousePos > thumbStart + thumbSize)
  50147. setCurrentRangeStart (visibleRange.getEnd());
  50148. }
  50149. else
  50150. {
  50151. stopTimer();
  50152. }
  50153. }
  50154. bool ScrollBar::keyPressed (const KeyPress& key)
  50155. {
  50156. if (! isVisible())
  50157. return false;
  50158. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  50159. moveScrollbarInSteps (-1);
  50160. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  50161. moveScrollbarInSteps (1);
  50162. else if (key.isKeyCode (KeyPress::pageUpKey))
  50163. moveScrollbarInPages (-1);
  50164. else if (key.isKeyCode (KeyPress::pageDownKey))
  50165. moveScrollbarInPages (1);
  50166. else if (key.isKeyCode (KeyPress::homeKey))
  50167. scrollToTop();
  50168. else if (key.isKeyCode (KeyPress::endKey))
  50169. scrollToBottom();
  50170. else
  50171. return false;
  50172. return true;
  50173. }
  50174. END_JUCE_NAMESPACE
  50175. /*** End of inlined file: juce_ScrollBar.cpp ***/
  50176. /*** Start of inlined file: juce_StretchableLayoutManager.cpp ***/
  50177. BEGIN_JUCE_NAMESPACE
  50178. StretchableLayoutManager::StretchableLayoutManager()
  50179. : totalSize (0)
  50180. {
  50181. }
  50182. StretchableLayoutManager::~StretchableLayoutManager()
  50183. {
  50184. }
  50185. void StretchableLayoutManager::clearAllItems()
  50186. {
  50187. items.clear();
  50188. totalSize = 0;
  50189. }
  50190. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  50191. const double minimumSize,
  50192. const double maximumSize,
  50193. const double preferredSize)
  50194. {
  50195. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  50196. if (layout == 0)
  50197. {
  50198. layout = new ItemLayoutProperties();
  50199. layout->itemIndex = itemIndex;
  50200. int i;
  50201. for (i = 0; i < items.size(); ++i)
  50202. if (items.getUnchecked (i)->itemIndex > itemIndex)
  50203. break;
  50204. items.insert (i, layout);
  50205. }
  50206. layout->minSize = minimumSize;
  50207. layout->maxSize = maximumSize;
  50208. layout->preferredSize = preferredSize;
  50209. layout->currentSize = 0;
  50210. }
  50211. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  50212. double& minimumSize,
  50213. double& maximumSize,
  50214. double& preferredSize) const
  50215. {
  50216. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50217. if (layout != 0)
  50218. {
  50219. minimumSize = layout->minSize;
  50220. maximumSize = layout->maxSize;
  50221. preferredSize = layout->preferredSize;
  50222. return true;
  50223. }
  50224. return false;
  50225. }
  50226. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  50227. {
  50228. totalSize = newTotalSize;
  50229. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  50230. }
  50231. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  50232. {
  50233. int pos = 0;
  50234. for (int i = 0; i < itemIndex; ++i)
  50235. {
  50236. const ItemLayoutProperties* const layout = getInfoFor (i);
  50237. if (layout != 0)
  50238. pos += layout->currentSize;
  50239. }
  50240. return pos;
  50241. }
  50242. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  50243. {
  50244. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50245. if (layout != 0)
  50246. return layout->currentSize;
  50247. return 0;
  50248. }
  50249. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  50250. {
  50251. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50252. if (layout != 0)
  50253. return -layout->currentSize / (double) totalSize;
  50254. return 0;
  50255. }
  50256. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  50257. int newPosition)
  50258. {
  50259. for (int i = items.size(); --i >= 0;)
  50260. {
  50261. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  50262. if (layout->itemIndex == itemIndex)
  50263. {
  50264. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  50265. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  50266. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  50267. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  50268. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  50269. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  50270. endPos += layout->currentSize;
  50271. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  50272. updatePrefSizesToMatchCurrentPositions();
  50273. break;
  50274. }
  50275. }
  50276. }
  50277. void StretchableLayoutManager::layOutComponents (Component** const components,
  50278. int numComponents,
  50279. int x, int y, int w, int h,
  50280. const bool vertically,
  50281. const bool resizeOtherDimension)
  50282. {
  50283. setTotalSize (vertically ? h : w);
  50284. int pos = vertically ? y : x;
  50285. for (int i = 0; i < numComponents; ++i)
  50286. {
  50287. const ItemLayoutProperties* const layout = getInfoFor (i);
  50288. if (layout != 0)
  50289. {
  50290. Component* const c = components[i];
  50291. if (c != 0)
  50292. {
  50293. if (i == numComponents - 1)
  50294. {
  50295. // if it's the last item, crop it to exactly fit the available space..
  50296. if (resizeOtherDimension)
  50297. {
  50298. if (vertically)
  50299. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  50300. else
  50301. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  50302. }
  50303. else
  50304. {
  50305. if (vertically)
  50306. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  50307. else
  50308. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  50309. }
  50310. }
  50311. else
  50312. {
  50313. if (resizeOtherDimension)
  50314. {
  50315. if (vertically)
  50316. c->setBounds (x, pos, w, layout->currentSize);
  50317. else
  50318. c->setBounds (pos, y, layout->currentSize, h);
  50319. }
  50320. else
  50321. {
  50322. if (vertically)
  50323. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  50324. else
  50325. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  50326. }
  50327. }
  50328. }
  50329. pos += layout->currentSize;
  50330. }
  50331. }
  50332. }
  50333. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  50334. {
  50335. for (int i = items.size(); --i >= 0;)
  50336. if (items.getUnchecked(i)->itemIndex == itemIndex)
  50337. return items.getUnchecked(i);
  50338. return 0;
  50339. }
  50340. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  50341. const int endIndex,
  50342. const int availableSpace,
  50343. int startPos)
  50344. {
  50345. // calculate the total sizes
  50346. int i;
  50347. double totalIdealSize = 0.0;
  50348. int totalMinimums = 0;
  50349. for (i = startIndex; i < endIndex; ++i)
  50350. {
  50351. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50352. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  50353. totalMinimums += layout->currentSize;
  50354. totalIdealSize += sizeToRealSize (layout->preferredSize, availableSpace);
  50355. }
  50356. if (totalIdealSize <= 0)
  50357. totalIdealSize = 1.0;
  50358. // now calc the best sizes..
  50359. int extraSpace = availableSpace - totalMinimums;
  50360. while (extraSpace > 0)
  50361. {
  50362. int numWantingMoreSpace = 0;
  50363. int numHavingTakenExtraSpace = 0;
  50364. // first figure out how many comps want a slice of the extra space..
  50365. for (i = startIndex; i < endIndex; ++i)
  50366. {
  50367. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50368. double sizeWanted = sizeToRealSize (layout->preferredSize, availableSpace);
  50369. const int bestSize = jlimit (layout->currentSize,
  50370. jmax (layout->currentSize,
  50371. sizeToRealSize (layout->maxSize, totalSize)),
  50372. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  50373. if (bestSize > layout->currentSize)
  50374. ++numWantingMoreSpace;
  50375. }
  50376. // ..share out the extra space..
  50377. for (i = startIndex; i < endIndex; ++i)
  50378. {
  50379. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50380. double sizeWanted = sizeToRealSize (layout->preferredSize, availableSpace);
  50381. int bestSize = jlimit (layout->currentSize,
  50382. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  50383. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  50384. const int extraWanted = bestSize - layout->currentSize;
  50385. if (extraWanted > 0)
  50386. {
  50387. const int extraAllowed = jmin (extraWanted,
  50388. extraSpace / jmax (1, numWantingMoreSpace));
  50389. if (extraAllowed > 0)
  50390. {
  50391. ++numHavingTakenExtraSpace;
  50392. --numWantingMoreSpace;
  50393. layout->currentSize += extraAllowed;
  50394. extraSpace -= extraAllowed;
  50395. }
  50396. }
  50397. }
  50398. if (numHavingTakenExtraSpace <= 0)
  50399. break;
  50400. }
  50401. // ..and calculate the end position
  50402. for (i = startIndex; i < endIndex; ++i)
  50403. {
  50404. ItemLayoutProperties* const layout = items.getUnchecked(i);
  50405. startPos += layout->currentSize;
  50406. }
  50407. return startPos;
  50408. }
  50409. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  50410. const int endIndex) const
  50411. {
  50412. int totalMinimums = 0;
  50413. for (int i = startIndex; i < endIndex; ++i)
  50414. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  50415. return totalMinimums;
  50416. }
  50417. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  50418. {
  50419. int totalMaximums = 0;
  50420. for (int i = startIndex; i < endIndex; ++i)
  50421. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  50422. return totalMaximums;
  50423. }
  50424. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  50425. {
  50426. for (int i = 0; i < items.size(); ++i)
  50427. {
  50428. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50429. layout->preferredSize
  50430. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  50431. : getItemCurrentAbsoluteSize (i);
  50432. }
  50433. }
  50434. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  50435. {
  50436. if (size < 0)
  50437. size *= -totalSpace;
  50438. return roundToInt (size);
  50439. }
  50440. END_JUCE_NAMESPACE
  50441. /*** End of inlined file: juce_StretchableLayoutManager.cpp ***/
  50442. /*** Start of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  50443. BEGIN_JUCE_NAMESPACE
  50444. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  50445. const int itemIndex_,
  50446. const bool isVertical_)
  50447. : layout (layout_),
  50448. itemIndex (itemIndex_),
  50449. isVertical (isVertical_)
  50450. {
  50451. setRepaintsOnMouseActivity (true);
  50452. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  50453. : MouseCursor::UpDownResizeCursor));
  50454. }
  50455. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  50456. {
  50457. }
  50458. void StretchableLayoutResizerBar::paint (Graphics& g)
  50459. {
  50460. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  50461. getWidth(), getHeight(),
  50462. isVertical,
  50463. isMouseOver(),
  50464. isMouseButtonDown());
  50465. }
  50466. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  50467. {
  50468. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  50469. }
  50470. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  50471. {
  50472. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  50473. : e.getDistanceFromDragStartY());
  50474. layout->setItemPosition (itemIndex, desiredPos);
  50475. hasBeenMoved();
  50476. }
  50477. void StretchableLayoutResizerBar::hasBeenMoved()
  50478. {
  50479. if (getParentComponent() != 0)
  50480. getParentComponent()->resized();
  50481. }
  50482. END_JUCE_NAMESPACE
  50483. /*** End of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  50484. /*** Start of inlined file: juce_StretchableObjectResizer.cpp ***/
  50485. BEGIN_JUCE_NAMESPACE
  50486. StretchableObjectResizer::StretchableObjectResizer()
  50487. {
  50488. }
  50489. StretchableObjectResizer::~StretchableObjectResizer()
  50490. {
  50491. }
  50492. void StretchableObjectResizer::addItem (const double size,
  50493. const double minSize, const double maxSize,
  50494. const int order)
  50495. {
  50496. // the order must be >= 0 but less than the maximum integer value.
  50497. jassert (order >= 0 && order < std::numeric_limits<int>::max());
  50498. Item* const item = new Item();
  50499. item->size = size;
  50500. item->minSize = minSize;
  50501. item->maxSize = maxSize;
  50502. item->order = order;
  50503. items.add (item);
  50504. }
  50505. double StretchableObjectResizer::getItemSize (const int index) const throw()
  50506. {
  50507. const Item* const it = items [index];
  50508. return it != 0 ? it->size : 0;
  50509. }
  50510. void StretchableObjectResizer::resizeToFit (const double targetSize)
  50511. {
  50512. int order = 0;
  50513. for (;;)
  50514. {
  50515. double currentSize = 0;
  50516. double minSize = 0;
  50517. double maxSize = 0;
  50518. int nextHighestOrder = std::numeric_limits<int>::max();
  50519. for (int i = 0; i < items.size(); ++i)
  50520. {
  50521. const Item* const it = items.getUnchecked(i);
  50522. currentSize += it->size;
  50523. if (it->order <= order)
  50524. {
  50525. minSize += it->minSize;
  50526. maxSize += it->maxSize;
  50527. }
  50528. else
  50529. {
  50530. minSize += it->size;
  50531. maxSize += it->size;
  50532. nextHighestOrder = jmin (nextHighestOrder, it->order);
  50533. }
  50534. }
  50535. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  50536. if (thisIterationTarget >= currentSize)
  50537. {
  50538. const double availableExtraSpace = maxSize - currentSize;
  50539. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  50540. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  50541. for (int i = 0; i < items.size(); ++i)
  50542. {
  50543. Item* const it = items.getUnchecked(i);
  50544. if (it->order <= order)
  50545. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  50546. }
  50547. }
  50548. else
  50549. {
  50550. const double amountOfSlack = currentSize - minSize;
  50551. const double targetAmountOfSlack = thisIterationTarget - minSize;
  50552. const double scale = targetAmountOfSlack / amountOfSlack;
  50553. for (int i = 0; i < items.size(); ++i)
  50554. {
  50555. Item* const it = items.getUnchecked(i);
  50556. if (it->order <= order)
  50557. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  50558. }
  50559. }
  50560. if (nextHighestOrder < std::numeric_limits<int>::max())
  50561. order = nextHighestOrder;
  50562. else
  50563. break;
  50564. }
  50565. }
  50566. END_JUCE_NAMESPACE
  50567. /*** End of inlined file: juce_StretchableObjectResizer.cpp ***/
  50568. /*** Start of inlined file: juce_TabbedButtonBar.cpp ***/
  50569. BEGIN_JUCE_NAMESPACE
  50570. TabBarButton::TabBarButton (const String& name,
  50571. TabbedButtonBar* const owner_,
  50572. const int index)
  50573. : Button (name),
  50574. owner (owner_),
  50575. tabIndex (index),
  50576. overlapPixels (0)
  50577. {
  50578. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  50579. setComponentEffect (&shadow);
  50580. setWantsKeyboardFocus (false);
  50581. }
  50582. TabBarButton::~TabBarButton()
  50583. {
  50584. }
  50585. void TabBarButton::paintButton (Graphics& g,
  50586. bool isMouseOverButton,
  50587. bool isButtonDown)
  50588. {
  50589. int x, y, w, h;
  50590. getActiveArea (x, y, w, h);
  50591. g.setOrigin (x, y);
  50592. getLookAndFeel()
  50593. .drawTabButton (g, w, h,
  50594. owner->getTabBackgroundColour (tabIndex),
  50595. tabIndex, getButtonText(), *this,
  50596. owner->getOrientation(),
  50597. isMouseOverButton, isButtonDown,
  50598. getToggleState());
  50599. }
  50600. void TabBarButton::clicked (const ModifierKeys& mods)
  50601. {
  50602. if (mods.isPopupMenu())
  50603. owner->popupMenuClickOnTab (tabIndex, getButtonText());
  50604. else
  50605. owner->setCurrentTabIndex (tabIndex);
  50606. }
  50607. bool TabBarButton::hitTest (int mx, int my)
  50608. {
  50609. int x, y, w, h;
  50610. getActiveArea (x, y, w, h);
  50611. if (owner->getOrientation() == TabbedButtonBar::TabsAtLeft
  50612. || owner->getOrientation() == TabbedButtonBar::TabsAtRight)
  50613. {
  50614. if (((unsigned int) mx) < (unsigned int) getWidth()
  50615. && my >= y + overlapPixels
  50616. && my < y + h - overlapPixels)
  50617. return true;
  50618. }
  50619. else
  50620. {
  50621. if (mx >= x + overlapPixels && mx < x + w - overlapPixels
  50622. && ((unsigned int) my) < (unsigned int) getHeight())
  50623. return true;
  50624. }
  50625. Path p;
  50626. getLookAndFeel()
  50627. .createTabButtonShape (p, w, h, tabIndex, getButtonText(), *this,
  50628. owner->getOrientation(),
  50629. false, false, getToggleState());
  50630. return p.contains ((float) (mx - x),
  50631. (float) (my - y));
  50632. }
  50633. int TabBarButton::getBestTabLength (const int depth)
  50634. {
  50635. return jlimit (depth * 2,
  50636. depth * 7,
  50637. getLookAndFeel().getTabButtonBestWidth (tabIndex, getButtonText(), depth, *this));
  50638. }
  50639. void TabBarButton::getActiveArea (int& x, int& y, int& w, int& h)
  50640. {
  50641. x = 0;
  50642. y = 0;
  50643. int r = getWidth();
  50644. int b = getHeight();
  50645. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  50646. if (owner->getOrientation() != TabbedButtonBar::TabsAtLeft)
  50647. r -= spaceAroundImage;
  50648. if (owner->getOrientation() != TabbedButtonBar::TabsAtRight)
  50649. x += spaceAroundImage;
  50650. if (owner->getOrientation() != TabbedButtonBar::TabsAtBottom)
  50651. y += spaceAroundImage;
  50652. if (owner->getOrientation() != TabbedButtonBar::TabsAtTop)
  50653. b -= spaceAroundImage;
  50654. w = r - x;
  50655. h = b - y;
  50656. }
  50657. class TabAreaBehindFrontButtonComponent : public Component
  50658. {
  50659. public:
  50660. TabAreaBehindFrontButtonComponent (TabbedButtonBar* const owner_)
  50661. : owner (owner_)
  50662. {
  50663. setInterceptsMouseClicks (false, false);
  50664. }
  50665. ~TabAreaBehindFrontButtonComponent()
  50666. {
  50667. }
  50668. void paint (Graphics& g)
  50669. {
  50670. getLookAndFeel()
  50671. .drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  50672. *owner, owner->getOrientation());
  50673. }
  50674. void enablementChanged()
  50675. {
  50676. repaint();
  50677. }
  50678. private:
  50679. TabbedButtonBar* const owner;
  50680. TabAreaBehindFrontButtonComponent (const TabAreaBehindFrontButtonComponent&);
  50681. TabAreaBehindFrontButtonComponent& operator= (const TabAreaBehindFrontButtonComponent&);
  50682. };
  50683. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  50684. : orientation (orientation_),
  50685. currentTabIndex (-1)
  50686. {
  50687. setInterceptsMouseClicks (false, true);
  50688. addAndMakeVisible (behindFrontTab = new TabAreaBehindFrontButtonComponent (this));
  50689. setFocusContainer (true);
  50690. }
  50691. TabbedButtonBar::~TabbedButtonBar()
  50692. {
  50693. extraTabsButton = 0;
  50694. deleteAllChildren();
  50695. }
  50696. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  50697. {
  50698. orientation = newOrientation;
  50699. for (int i = getNumChildComponents(); --i >= 0;)
  50700. getChildComponent (i)->resized();
  50701. resized();
  50702. }
  50703. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int index)
  50704. {
  50705. return new TabBarButton (name, this, index);
  50706. }
  50707. void TabbedButtonBar::clearTabs()
  50708. {
  50709. tabs.clear();
  50710. tabColours.clear();
  50711. currentTabIndex = -1;
  50712. extraTabsButton = 0;
  50713. removeChildComponent (behindFrontTab);
  50714. deleteAllChildren();
  50715. addChildComponent (behindFrontTab);
  50716. setCurrentTabIndex (-1);
  50717. }
  50718. void TabbedButtonBar::addTab (const String& tabName,
  50719. const Colour& tabBackgroundColour,
  50720. int insertIndex)
  50721. {
  50722. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  50723. if (tabName.isNotEmpty())
  50724. {
  50725. if (((unsigned int) insertIndex) > (unsigned int) tabs.size())
  50726. insertIndex = tabs.size();
  50727. for (int i = tabs.size(); --i >= insertIndex;)
  50728. {
  50729. TabBarButton* const tb = getTabButton (i);
  50730. if (tb != 0)
  50731. tb->tabIndex++;
  50732. }
  50733. tabs.insert (insertIndex, tabName);
  50734. tabColours.insert (insertIndex, tabBackgroundColour);
  50735. TabBarButton* const tb = createTabButton (tabName, insertIndex);
  50736. jassert (tb != 0); // your createTabButton() mustn't return zero!
  50737. addAndMakeVisible (tb, insertIndex);
  50738. resized();
  50739. if (currentTabIndex < 0)
  50740. setCurrentTabIndex (0);
  50741. }
  50742. }
  50743. void TabbedButtonBar::setTabName (const int tabIndex,
  50744. const String& newName)
  50745. {
  50746. if (((unsigned int) tabIndex) < (unsigned int) tabs.size()
  50747. && tabs[tabIndex] != newName)
  50748. {
  50749. tabs.set (tabIndex, newName);
  50750. TabBarButton* const tb = getTabButton (tabIndex);
  50751. if (tb != 0)
  50752. tb->setButtonText (newName);
  50753. resized();
  50754. }
  50755. }
  50756. void TabbedButtonBar::removeTab (const int tabIndex)
  50757. {
  50758. if (((unsigned int) tabIndex) < (unsigned int) tabs.size())
  50759. {
  50760. const int oldTabIndex = currentTabIndex;
  50761. if (currentTabIndex == tabIndex)
  50762. currentTabIndex = -1;
  50763. tabs.remove (tabIndex);
  50764. tabColours.remove (tabIndex);
  50765. delete getTabButton (tabIndex);
  50766. for (int i = tabIndex + 1; i <= tabs.size(); ++i)
  50767. {
  50768. TabBarButton* const tb = getTabButton (i);
  50769. if (tb != 0)
  50770. tb->tabIndex--;
  50771. }
  50772. resized();
  50773. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  50774. }
  50775. }
  50776. void TabbedButtonBar::moveTab (const int currentIndex,
  50777. const int newIndex)
  50778. {
  50779. tabs.move (currentIndex, newIndex);
  50780. tabColours.move (currentIndex, newIndex);
  50781. resized();
  50782. }
  50783. int TabbedButtonBar::getNumTabs() const
  50784. {
  50785. return tabs.size();
  50786. }
  50787. const StringArray TabbedButtonBar::getTabNames() const
  50788. {
  50789. return tabs;
  50790. }
  50791. void TabbedButtonBar::setCurrentTabIndex (int newIndex, const bool sendChangeMessage_)
  50792. {
  50793. if (currentTabIndex != newIndex)
  50794. {
  50795. if (((unsigned int) newIndex) >= (unsigned int) tabs.size())
  50796. newIndex = -1;
  50797. currentTabIndex = newIndex;
  50798. for (int i = 0; i < getNumChildComponents(); ++i)
  50799. {
  50800. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  50801. if (tb != 0)
  50802. tb->setToggleState (tb->tabIndex == newIndex, false);
  50803. }
  50804. resized();
  50805. if (sendChangeMessage_)
  50806. sendChangeMessage (this);
  50807. currentTabChanged (newIndex, newIndex >= 0 ? tabs [newIndex] : String::empty);
  50808. }
  50809. }
  50810. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  50811. {
  50812. for (int i = getNumChildComponents(); --i >= 0;)
  50813. {
  50814. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  50815. if (tb != 0 && tb->tabIndex == index)
  50816. return tb;
  50817. }
  50818. return 0;
  50819. }
  50820. void TabbedButtonBar::lookAndFeelChanged()
  50821. {
  50822. extraTabsButton = 0;
  50823. resized();
  50824. }
  50825. void TabbedButtonBar::resized()
  50826. {
  50827. const double minimumScale = 0.7;
  50828. int depth = getWidth();
  50829. int length = getHeight();
  50830. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  50831. swapVariables (depth, length);
  50832. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  50833. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  50834. int i, totalLength = overlap;
  50835. int numVisibleButtons = tabs.size();
  50836. for (i = 0; i < getNumChildComponents(); ++i)
  50837. {
  50838. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  50839. if (tb != 0)
  50840. {
  50841. totalLength += tb->getBestTabLength (depth) - overlap;
  50842. tb->overlapPixels = overlap / 2;
  50843. }
  50844. }
  50845. double scale = 1.0;
  50846. if (totalLength > length)
  50847. scale = jmax (minimumScale, length / (double) totalLength);
  50848. const bool isTooBig = totalLength * scale > length;
  50849. int tabsButtonPos = 0;
  50850. if (isTooBig)
  50851. {
  50852. if (extraTabsButton == 0)
  50853. {
  50854. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  50855. extraTabsButton->addButtonListener (this);
  50856. extraTabsButton->setAlwaysOnTop (true);
  50857. extraTabsButton->setTriggeredOnMouseDown (true);
  50858. }
  50859. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  50860. extraTabsButton->setSize (buttonSize, buttonSize);
  50861. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  50862. {
  50863. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  50864. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  50865. }
  50866. else
  50867. {
  50868. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  50869. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  50870. }
  50871. totalLength = 0;
  50872. for (i = 0; i < tabs.size(); ++i)
  50873. {
  50874. TabBarButton* const tb = getTabButton (i);
  50875. if (tb != 0)
  50876. {
  50877. const int newLength = totalLength + tb->getBestTabLength (depth);
  50878. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  50879. {
  50880. totalLength += overlap;
  50881. break;
  50882. }
  50883. numVisibleButtons = i + 1;
  50884. totalLength = newLength - overlap;
  50885. }
  50886. }
  50887. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  50888. }
  50889. else
  50890. {
  50891. extraTabsButton = 0;
  50892. }
  50893. int pos = 0;
  50894. TabBarButton* frontTab = 0;
  50895. for (i = 0; i < tabs.size(); ++i)
  50896. {
  50897. TabBarButton* const tb = getTabButton (i);
  50898. if (tb != 0)
  50899. {
  50900. const int bestLength = roundToInt (scale * tb->getBestTabLength (depth));
  50901. if (i < numVisibleButtons)
  50902. {
  50903. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  50904. tb->setBounds (pos, 0, bestLength, getHeight());
  50905. else
  50906. tb->setBounds (0, pos, getWidth(), bestLength);
  50907. tb->toBack();
  50908. if (tb->tabIndex == currentTabIndex)
  50909. frontTab = tb;
  50910. tb->setVisible (true);
  50911. }
  50912. else
  50913. {
  50914. tb->setVisible (false);
  50915. }
  50916. pos += bestLength - overlap;
  50917. }
  50918. }
  50919. behindFrontTab->setBounds (getLocalBounds());
  50920. if (frontTab != 0)
  50921. {
  50922. frontTab->toFront (false);
  50923. behindFrontTab->toBehind (frontTab);
  50924. }
  50925. }
  50926. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  50927. {
  50928. return tabColours [tabIndex];
  50929. }
  50930. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  50931. {
  50932. if (((unsigned int) tabIndex) < (unsigned int) tabColours.size()
  50933. && tabColours [tabIndex] != newColour)
  50934. {
  50935. tabColours.set (tabIndex, newColour);
  50936. repaint();
  50937. }
  50938. }
  50939. void TabbedButtonBar::buttonClicked (Button* button)
  50940. {
  50941. if (button == extraTabsButton)
  50942. {
  50943. PopupMenu m;
  50944. for (int i = 0; i < tabs.size(); ++i)
  50945. {
  50946. TabBarButton* const tb = getTabButton (i);
  50947. if (tb != 0 && ! tb->isVisible())
  50948. m.addItem (tb->tabIndex + 1, tabs[i], true, i == currentTabIndex);
  50949. }
  50950. const int res = m.showAt (extraTabsButton);
  50951. if (res != 0)
  50952. setCurrentTabIndex (res - 1);
  50953. }
  50954. }
  50955. void TabbedButtonBar::currentTabChanged (const int, const String&)
  50956. {
  50957. }
  50958. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  50959. {
  50960. }
  50961. END_JUCE_NAMESPACE
  50962. /*** End of inlined file: juce_TabbedButtonBar.cpp ***/
  50963. /*** Start of inlined file: juce_TabbedComponent.cpp ***/
  50964. BEGIN_JUCE_NAMESPACE
  50965. class TabCompButtonBar : public TabbedButtonBar
  50966. {
  50967. public:
  50968. TabCompButtonBar (TabbedComponent* const owner_,
  50969. const TabbedButtonBar::Orientation orientation_)
  50970. : TabbedButtonBar (orientation_),
  50971. owner (owner_)
  50972. {
  50973. }
  50974. ~TabCompButtonBar()
  50975. {
  50976. }
  50977. void currentTabChanged (int newCurrentTabIndex, const String& newTabName)
  50978. {
  50979. owner->changeCallback (newCurrentTabIndex, newTabName);
  50980. }
  50981. void popupMenuClickOnTab (int tabIndex, const String& tabName)
  50982. {
  50983. owner->popupMenuClickOnTab (tabIndex, tabName);
  50984. }
  50985. const Colour getTabBackgroundColour (const int tabIndex)
  50986. {
  50987. return owner->tabs->getTabBackgroundColour (tabIndex);
  50988. }
  50989. TabBarButton* createTabButton (const String& tabName, int tabIndex)
  50990. {
  50991. return owner->createTabButton (tabName, tabIndex);
  50992. }
  50993. juce_UseDebuggingNewOperator
  50994. private:
  50995. TabbedComponent* const owner;
  50996. TabCompButtonBar (const TabCompButtonBar&);
  50997. TabCompButtonBar& operator= (const TabCompButtonBar&);
  50998. };
  50999. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  51000. : panelComponent (0),
  51001. tabDepth (30),
  51002. outlineThickness (1),
  51003. edgeIndent (0)
  51004. {
  51005. addAndMakeVisible (tabs = new TabCompButtonBar (this, orientation));
  51006. }
  51007. TabbedComponent::~TabbedComponent()
  51008. {
  51009. clearTabs();
  51010. delete tabs;
  51011. }
  51012. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  51013. {
  51014. tabs->setOrientation (orientation);
  51015. resized();
  51016. }
  51017. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  51018. {
  51019. return tabs->getOrientation();
  51020. }
  51021. void TabbedComponent::setTabBarDepth (const int newDepth)
  51022. {
  51023. if (tabDepth != newDepth)
  51024. {
  51025. tabDepth = newDepth;
  51026. resized();
  51027. }
  51028. }
  51029. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int tabIndex)
  51030. {
  51031. return new TabBarButton (tabName, tabs, tabIndex);
  51032. }
  51033. const Identifier TabbedComponent::deleteComponentId ("deleteByTabComp_");
  51034. void TabbedComponent::clearTabs()
  51035. {
  51036. if (panelComponent != 0)
  51037. {
  51038. panelComponent->setVisible (false);
  51039. removeChildComponent (panelComponent);
  51040. panelComponent = 0;
  51041. }
  51042. tabs->clearTabs();
  51043. for (int i = contentComponents.size(); --i >= 0;)
  51044. {
  51045. Component* const c = contentComponents.getUnchecked(i);
  51046. // be careful not to delete these components until they've been removed from the tab component
  51047. jassert (c == 0 || c->isValidComponent());
  51048. if (c != 0 && (bool) c->getProperties() [deleteComponentId])
  51049. delete c;
  51050. }
  51051. contentComponents.clear();
  51052. }
  51053. void TabbedComponent::addTab (const String& tabName,
  51054. const Colour& tabBackgroundColour,
  51055. Component* const contentComponent,
  51056. const bool deleteComponentWhenNotNeeded,
  51057. const int insertIndex)
  51058. {
  51059. contentComponents.insert (insertIndex, contentComponent);
  51060. if (contentComponent != 0)
  51061. contentComponent->getProperties().set (deleteComponentId, deleteComponentWhenNotNeeded);
  51062. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  51063. }
  51064. void TabbedComponent::setTabName (const int tabIndex, const String& newName)
  51065. {
  51066. tabs->setTabName (tabIndex, newName);
  51067. }
  51068. void TabbedComponent::removeTab (const int tabIndex)
  51069. {
  51070. Component* const c = contentComponents [tabIndex];
  51071. if (c != 0 && (bool) c->getProperties() [deleteComponentId])
  51072. {
  51073. if (c == panelComponent)
  51074. panelComponent = 0;
  51075. delete c;
  51076. }
  51077. contentComponents.remove (tabIndex);
  51078. tabs->removeTab (tabIndex);
  51079. }
  51080. int TabbedComponent::getNumTabs() const
  51081. {
  51082. return tabs->getNumTabs();
  51083. }
  51084. const StringArray TabbedComponent::getTabNames() const
  51085. {
  51086. return tabs->getTabNames();
  51087. }
  51088. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  51089. {
  51090. return contentComponents [tabIndex];
  51091. }
  51092. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  51093. {
  51094. return tabs->getTabBackgroundColour (tabIndex);
  51095. }
  51096. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51097. {
  51098. tabs->setTabBackgroundColour (tabIndex, newColour);
  51099. if (getCurrentTabIndex() == tabIndex)
  51100. repaint();
  51101. }
  51102. void TabbedComponent::setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage)
  51103. {
  51104. tabs->setCurrentTabIndex (newTabIndex, sendChangeMessage);
  51105. }
  51106. int TabbedComponent::getCurrentTabIndex() const
  51107. {
  51108. return tabs->getCurrentTabIndex();
  51109. }
  51110. const String& TabbedComponent::getCurrentTabName() const
  51111. {
  51112. return tabs->getCurrentTabName();
  51113. }
  51114. void TabbedComponent::setOutline (int thickness)
  51115. {
  51116. outlineThickness = thickness;
  51117. repaint();
  51118. }
  51119. void TabbedComponent::setIndent (const int indentThickness)
  51120. {
  51121. edgeIndent = indentThickness;
  51122. }
  51123. void TabbedComponent::paint (Graphics& g)
  51124. {
  51125. g.fillAll (findColour (backgroundColourId));
  51126. const TabbedButtonBar::Orientation o = getOrientation();
  51127. int x = 0;
  51128. int y = 0;
  51129. int r = getWidth();
  51130. int b = getHeight();
  51131. if (o == TabbedButtonBar::TabsAtTop)
  51132. y += tabDepth;
  51133. else if (o == TabbedButtonBar::TabsAtBottom)
  51134. b -= tabDepth;
  51135. else if (o == TabbedButtonBar::TabsAtLeft)
  51136. x += tabDepth;
  51137. else if (o == TabbedButtonBar::TabsAtRight)
  51138. r -= tabDepth;
  51139. g.reduceClipRegion (x, y, r - x, b - y);
  51140. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  51141. if (outlineThickness > 0)
  51142. {
  51143. if (o == TabbedButtonBar::TabsAtTop)
  51144. --y;
  51145. else if (o == TabbedButtonBar::TabsAtBottom)
  51146. ++b;
  51147. else if (o == TabbedButtonBar::TabsAtLeft)
  51148. --x;
  51149. else if (o == TabbedButtonBar::TabsAtRight)
  51150. ++r;
  51151. g.setColour (findColour (outlineColourId));
  51152. g.drawRect (x, y, r - x, b - y, outlineThickness);
  51153. }
  51154. }
  51155. void TabbedComponent::resized()
  51156. {
  51157. const TabbedButtonBar::Orientation o = getOrientation();
  51158. const int indent = edgeIndent + outlineThickness;
  51159. BorderSize indents (indent);
  51160. if (o == TabbedButtonBar::TabsAtTop)
  51161. {
  51162. tabs->setBounds (0, 0, getWidth(), tabDepth);
  51163. indents.setTop (tabDepth + edgeIndent);
  51164. }
  51165. else if (o == TabbedButtonBar::TabsAtBottom)
  51166. {
  51167. tabs->setBounds (0, getHeight() - tabDepth, getWidth(), tabDepth);
  51168. indents.setBottom (tabDepth + edgeIndent);
  51169. }
  51170. else if (o == TabbedButtonBar::TabsAtLeft)
  51171. {
  51172. tabs->setBounds (0, 0, tabDepth, getHeight());
  51173. indents.setLeft (tabDepth + edgeIndent);
  51174. }
  51175. else if (o == TabbedButtonBar::TabsAtRight)
  51176. {
  51177. tabs->setBounds (getWidth() - tabDepth, 0, tabDepth, getHeight());
  51178. indents.setRight (tabDepth + edgeIndent);
  51179. }
  51180. const Rectangle<int> bounds (indents.subtractedFrom (getLocalBounds()));
  51181. for (int i = contentComponents.size(); --i >= 0;)
  51182. if (contentComponents.getUnchecked (i) != 0)
  51183. contentComponents.getUnchecked (i)->setBounds (bounds);
  51184. }
  51185. void TabbedComponent::lookAndFeelChanged()
  51186. {
  51187. for (int i = contentComponents.size(); --i >= 0;)
  51188. if (contentComponents.getUnchecked (i) != 0)
  51189. contentComponents.getUnchecked (i)->lookAndFeelChanged();
  51190. }
  51191. void TabbedComponent::changeCallback (const int newCurrentTabIndex,
  51192. const String& newTabName)
  51193. {
  51194. if (panelComponent != 0)
  51195. {
  51196. panelComponent->setVisible (false);
  51197. removeChildComponent (panelComponent);
  51198. panelComponent = 0;
  51199. }
  51200. if (getCurrentTabIndex() >= 0)
  51201. {
  51202. panelComponent = contentComponents [getCurrentTabIndex()];
  51203. if (panelComponent != 0)
  51204. {
  51205. // do these ops as two stages instead of addAndMakeVisible() so that the
  51206. // component has always got a parent when it gets the visibilityChanged() callback
  51207. addChildComponent (panelComponent);
  51208. panelComponent->setVisible (true);
  51209. panelComponent->toFront (true);
  51210. }
  51211. repaint();
  51212. }
  51213. resized();
  51214. currentTabChanged (newCurrentTabIndex, newTabName);
  51215. }
  51216. void TabbedComponent::currentTabChanged (const int, const String&)
  51217. {
  51218. }
  51219. void TabbedComponent::popupMenuClickOnTab (const int, const String&)
  51220. {
  51221. }
  51222. END_JUCE_NAMESPACE
  51223. /*** End of inlined file: juce_TabbedComponent.cpp ***/
  51224. /*** Start of inlined file: juce_Viewport.cpp ***/
  51225. BEGIN_JUCE_NAMESPACE
  51226. Viewport::Viewport (const String& componentName)
  51227. : Component (componentName),
  51228. scrollBarThickness (0),
  51229. singleStepX (16),
  51230. singleStepY (16),
  51231. showHScrollbar (true),
  51232. showVScrollbar (true),
  51233. verticalScrollBar (true),
  51234. horizontalScrollBar (false)
  51235. {
  51236. // content holder is used to clip the contents so they don't overlap the scrollbars
  51237. addAndMakeVisible (&contentHolder);
  51238. contentHolder.setInterceptsMouseClicks (false, true);
  51239. addChildComponent (&verticalScrollBar);
  51240. addChildComponent (&horizontalScrollBar);
  51241. verticalScrollBar.addListener (this);
  51242. horizontalScrollBar.addListener (this);
  51243. setInterceptsMouseClicks (false, true);
  51244. setWantsKeyboardFocus (true);
  51245. }
  51246. Viewport::~Viewport()
  51247. {
  51248. contentHolder.deleteAllChildren();
  51249. }
  51250. void Viewport::visibleAreaChanged (int, int, int, int)
  51251. {
  51252. }
  51253. void Viewport::setViewedComponent (Component* const newViewedComponent)
  51254. {
  51255. if (contentComp.getComponent() != newViewedComponent)
  51256. {
  51257. {
  51258. ScopedPointer<Component> oldCompDeleter (contentComp);
  51259. contentComp = 0;
  51260. }
  51261. contentComp = newViewedComponent;
  51262. if (contentComp != 0)
  51263. {
  51264. contentComp->setTopLeftPosition (0, 0);
  51265. contentHolder.addAndMakeVisible (contentComp);
  51266. contentComp->addComponentListener (this);
  51267. }
  51268. updateVisibleArea();
  51269. }
  51270. }
  51271. int Viewport::getMaximumVisibleWidth() const
  51272. {
  51273. return contentHolder.getWidth();
  51274. }
  51275. int Viewport::getMaximumVisibleHeight() const
  51276. {
  51277. return contentHolder.getHeight();
  51278. }
  51279. void Viewport::setViewPosition (const int xPixelsOffset, const int yPixelsOffset)
  51280. {
  51281. if (contentComp != 0)
  51282. contentComp->setTopLeftPosition (jmax (jmin (0, contentHolder.getWidth() - contentComp->getWidth()), jmin (0, -xPixelsOffset)),
  51283. jmax (jmin (0, contentHolder.getHeight() - contentComp->getHeight()), jmin (0, -yPixelsOffset)));
  51284. }
  51285. void Viewport::setViewPosition (const Point<int>& newPosition)
  51286. {
  51287. setViewPosition (newPosition.getX(), newPosition.getY());
  51288. }
  51289. void Viewport::setViewPositionProportionately (const double x, const double y)
  51290. {
  51291. if (contentComp != 0)
  51292. setViewPosition (jmax (0, roundToInt (x * (contentComp->getWidth() - getWidth()))),
  51293. jmax (0, roundToInt (y * (contentComp->getHeight() - getHeight()))));
  51294. }
  51295. bool Viewport::autoScroll (const int mouseX, const int mouseY, const int activeBorderThickness, const int maximumSpeed)
  51296. {
  51297. if (contentComp != 0)
  51298. {
  51299. int dx = 0, dy = 0;
  51300. if (horizontalScrollBar.isVisible() || contentComp->getX() < 0 || contentComp->getRight() > getWidth())
  51301. {
  51302. if (mouseX < activeBorderThickness)
  51303. dx = activeBorderThickness - mouseX;
  51304. else if (mouseX >= contentHolder.getWidth() - activeBorderThickness)
  51305. dx = (contentHolder.getWidth() - activeBorderThickness) - mouseX;
  51306. if (dx < 0)
  51307. dx = jmax (dx, -maximumSpeed, contentHolder.getWidth() - contentComp->getRight());
  51308. else
  51309. dx = jmin (dx, maximumSpeed, -contentComp->getX());
  51310. }
  51311. if (verticalScrollBar.isVisible() || contentComp->getY() < 0 || contentComp->getBottom() > getHeight())
  51312. {
  51313. if (mouseY < activeBorderThickness)
  51314. dy = activeBorderThickness - mouseY;
  51315. else if (mouseY >= contentHolder.getHeight() - activeBorderThickness)
  51316. dy = (contentHolder.getHeight() - activeBorderThickness) - mouseY;
  51317. if (dy < 0)
  51318. dy = jmax (dy, -maximumSpeed, contentHolder.getHeight() - contentComp->getBottom());
  51319. else
  51320. dy = jmin (dy, maximumSpeed, -contentComp->getY());
  51321. }
  51322. if (dx != 0 || dy != 0)
  51323. {
  51324. contentComp->setTopLeftPosition (contentComp->getX() + dx,
  51325. contentComp->getY() + dy);
  51326. return true;
  51327. }
  51328. }
  51329. return false;
  51330. }
  51331. void Viewport::componentMovedOrResized (Component&, bool, bool)
  51332. {
  51333. updateVisibleArea();
  51334. }
  51335. void Viewport::resized()
  51336. {
  51337. updateVisibleArea();
  51338. }
  51339. void Viewport::updateVisibleArea()
  51340. {
  51341. const int scrollbarWidth = getScrollBarThickness();
  51342. const bool canShowAnyBars = getWidth() > scrollbarWidth && getHeight() > scrollbarWidth;
  51343. const bool canShowHBar = showHScrollbar && canShowAnyBars;
  51344. const bool canShowVBar = showVScrollbar && canShowAnyBars;
  51345. bool hBarVisible = canShowHBar && ! horizontalScrollBar.autoHides();
  51346. bool vBarVisible = canShowVBar && ! verticalScrollBar.autoHides();
  51347. Rectangle<int> contentArea (getLocalBounds());
  51348. if (contentComp != 0 && ! contentArea.contains (contentComp->getBounds()))
  51349. {
  51350. hBarVisible = canShowHBar && (hBarVisible || contentComp->getX() < 0 || contentComp->getRight() > contentArea.getWidth());
  51351. vBarVisible = canShowVBar && (vBarVisible || contentComp->getY() < 0 || contentComp->getBottom() > contentArea.getHeight());
  51352. if (vBarVisible)
  51353. contentArea.setWidth (getWidth() - scrollbarWidth);
  51354. if (hBarVisible)
  51355. contentArea.setHeight (getHeight() - scrollbarWidth);
  51356. if (! contentArea.contains (contentComp->getBounds()))
  51357. {
  51358. hBarVisible = canShowHBar && (hBarVisible || contentComp->getRight() > contentArea.getWidth());
  51359. vBarVisible = canShowVBar && (vBarVisible || contentComp->getBottom() > contentArea.getHeight());
  51360. }
  51361. }
  51362. if (vBarVisible)
  51363. contentArea.setWidth (getWidth() - scrollbarWidth);
  51364. if (hBarVisible)
  51365. contentArea.setHeight (getHeight() - scrollbarWidth);
  51366. contentHolder.setBounds (contentArea);
  51367. Rectangle<int> contentBounds;
  51368. if (contentComp != 0)
  51369. contentBounds = contentComp->getBounds();
  51370. const Point<int> visibleOrigin (-contentBounds.getPosition());
  51371. if (hBarVisible)
  51372. {
  51373. horizontalScrollBar.setBounds (0, contentArea.getHeight(), contentArea.getWidth(), scrollbarWidth);
  51374. horizontalScrollBar.setRangeLimits (0.0, contentBounds.getWidth());
  51375. horizontalScrollBar.setCurrentRange (visibleOrigin.getX(), contentArea.getWidth());
  51376. horizontalScrollBar.setSingleStepSize (singleStepX);
  51377. horizontalScrollBar.cancelPendingUpdate();
  51378. }
  51379. if (vBarVisible)
  51380. {
  51381. verticalScrollBar.setBounds (contentArea.getWidth(), 0, scrollbarWidth, contentArea.getHeight());
  51382. verticalScrollBar.setRangeLimits (0.0, contentBounds.getHeight());
  51383. verticalScrollBar.setCurrentRange (visibleOrigin.getY(), contentArea.getHeight());
  51384. verticalScrollBar.setSingleStepSize (singleStepY);
  51385. verticalScrollBar.cancelPendingUpdate();
  51386. }
  51387. // Force the visibility *after* setting the ranges to avoid flicker caused by edge conditions in the numbers.
  51388. horizontalScrollBar.setVisible (hBarVisible);
  51389. verticalScrollBar.setVisible (vBarVisible);
  51390. const Rectangle<int> visibleArea (visibleOrigin.getX(), visibleOrigin.getY(),
  51391. jmin (contentBounds.getWidth() - visibleOrigin.getX(), contentArea.getWidth()),
  51392. jmin (contentBounds.getHeight() - visibleOrigin.getY(), contentArea.getHeight()));
  51393. if (lastVisibleArea != visibleArea)
  51394. {
  51395. lastVisibleArea = visibleArea;
  51396. visibleAreaChanged (visibleArea.getX(), visibleArea.getY(), visibleArea.getWidth(), visibleArea.getHeight());
  51397. }
  51398. horizontalScrollBar.handleUpdateNowIfNeeded();
  51399. verticalScrollBar.handleUpdateNowIfNeeded();
  51400. }
  51401. void Viewport::setSingleStepSizes (const int stepX, const int stepY)
  51402. {
  51403. if (singleStepX != stepX || singleStepY != stepY)
  51404. {
  51405. singleStepX = stepX;
  51406. singleStepY = stepY;
  51407. updateVisibleArea();
  51408. }
  51409. }
  51410. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  51411. const bool showHorizontalScrollbarIfNeeded)
  51412. {
  51413. if (showVScrollbar != showVerticalScrollbarIfNeeded
  51414. || showHScrollbar != showHorizontalScrollbarIfNeeded)
  51415. {
  51416. showVScrollbar = showVerticalScrollbarIfNeeded;
  51417. showHScrollbar = showHorizontalScrollbarIfNeeded;
  51418. updateVisibleArea();
  51419. }
  51420. }
  51421. void Viewport::setScrollBarThickness (const int thickness)
  51422. {
  51423. if (scrollBarThickness != thickness)
  51424. {
  51425. scrollBarThickness = thickness;
  51426. updateVisibleArea();
  51427. }
  51428. }
  51429. int Viewport::getScrollBarThickness() const
  51430. {
  51431. return scrollBarThickness > 0 ? scrollBarThickness
  51432. : getLookAndFeel().getDefaultScrollbarWidth();
  51433. }
  51434. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  51435. {
  51436. verticalScrollBar.setButtonVisibility (buttonsVisible);
  51437. horizontalScrollBar.setButtonVisibility (buttonsVisible);
  51438. }
  51439. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  51440. {
  51441. const int newRangeStartInt = roundToInt (newRangeStart);
  51442. if (scrollBarThatHasMoved == &horizontalScrollBar)
  51443. {
  51444. setViewPosition (newRangeStartInt, getViewPositionY());
  51445. }
  51446. else if (scrollBarThatHasMoved == &verticalScrollBar)
  51447. {
  51448. setViewPosition (getViewPositionX(), newRangeStartInt);
  51449. }
  51450. }
  51451. void Viewport::mouseWheelMove (const MouseEvent& e, const float wheelIncrementX, const float wheelIncrementY)
  51452. {
  51453. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  51454. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  51455. }
  51456. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  51457. {
  51458. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  51459. {
  51460. const bool hasVertBar = verticalScrollBar.isVisible();
  51461. const bool hasHorzBar = horizontalScrollBar.isVisible();
  51462. if (hasHorzBar || hasVertBar)
  51463. {
  51464. if (wheelIncrementX != 0)
  51465. {
  51466. wheelIncrementX *= 14.0f * singleStepX;
  51467. wheelIncrementX = (wheelIncrementX < 0) ? jmin (wheelIncrementX, -1.0f)
  51468. : jmax (wheelIncrementX, 1.0f);
  51469. }
  51470. if (wheelIncrementY != 0)
  51471. {
  51472. wheelIncrementY *= 14.0f * singleStepY;
  51473. wheelIncrementY = (wheelIncrementY < 0) ? jmin (wheelIncrementY, -1.0f)
  51474. : jmax (wheelIncrementY, 1.0f);
  51475. }
  51476. Point<int> pos (getViewPosition());
  51477. if (wheelIncrementX != 0 && wheelIncrementY != 0 && hasHorzBar && hasVertBar)
  51478. {
  51479. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  51480. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  51481. }
  51482. else if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  51483. {
  51484. if (wheelIncrementX == 0 && ! hasVertBar)
  51485. wheelIncrementX = wheelIncrementY;
  51486. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  51487. }
  51488. else if (hasVertBar && wheelIncrementY != 0)
  51489. {
  51490. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  51491. }
  51492. if (pos != getViewPosition())
  51493. {
  51494. setViewPosition (pos);
  51495. return true;
  51496. }
  51497. }
  51498. }
  51499. return false;
  51500. }
  51501. bool Viewport::keyPressed (const KeyPress& key)
  51502. {
  51503. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  51504. || key.isKeyCode (KeyPress::downKey)
  51505. || key.isKeyCode (KeyPress::pageUpKey)
  51506. || key.isKeyCode (KeyPress::pageDownKey)
  51507. || key.isKeyCode (KeyPress::homeKey)
  51508. || key.isKeyCode (KeyPress::endKey);
  51509. if (verticalScrollBar.isVisible() && isUpDownKey)
  51510. return verticalScrollBar.keyPressed (key);
  51511. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  51512. || key.isKeyCode (KeyPress::rightKey);
  51513. if (horizontalScrollBar.isVisible() && (isUpDownKey || isLeftRightKey))
  51514. return horizontalScrollBar.keyPressed (key);
  51515. return false;
  51516. }
  51517. END_JUCE_NAMESPACE
  51518. /*** End of inlined file: juce_Viewport.cpp ***/
  51519. /*** Start of inlined file: juce_LookAndFeel.cpp ***/
  51520. BEGIN_JUCE_NAMESPACE
  51521. static const Colour createBaseColour (const Colour& buttonColour,
  51522. const bool hasKeyboardFocus,
  51523. const bool isMouseOverButton,
  51524. const bool isButtonDown) throw()
  51525. {
  51526. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  51527. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  51528. if (isButtonDown)
  51529. return baseColour.contrasting (0.2f);
  51530. else if (isMouseOverButton)
  51531. return baseColour.contrasting (0.1f);
  51532. return baseColour;
  51533. }
  51534. LookAndFeel::LookAndFeel()
  51535. {
  51536. /* if this fails it means you're trying to create a LookAndFeel object before
  51537. the static Colours have been initialised. That ain't gonna work. It probably
  51538. means that you're using a static LookAndFeel object and that your compiler has
  51539. decided to intialise it before the Colours class.
  51540. */
  51541. jassert (Colours::white == Colour (0xffffffff));
  51542. // set up the standard set of colours..
  51543. const int textButtonColour = 0xffbbbbff;
  51544. const int textHighlightColour = 0x401111ee;
  51545. const int standardOutlineColour = 0xb2808080;
  51546. static const int standardColours[] =
  51547. {
  51548. TextButton::buttonColourId, textButtonColour,
  51549. TextButton::buttonOnColourId, 0xff4444ff,
  51550. TextButton::textColourOnId, 0xff000000,
  51551. TextButton::textColourOffId, 0xff000000,
  51552. ComboBox::buttonColourId, 0xffbbbbff,
  51553. ComboBox::outlineColourId, standardOutlineColour,
  51554. ToggleButton::textColourId, 0xff000000,
  51555. TextEditor::backgroundColourId, 0xffffffff,
  51556. TextEditor::textColourId, 0xff000000,
  51557. TextEditor::highlightColourId, textHighlightColour,
  51558. TextEditor::highlightedTextColourId, 0xff000000,
  51559. TextEditor::caretColourId, 0xff000000,
  51560. TextEditor::outlineColourId, 0x00000000,
  51561. TextEditor::focusedOutlineColourId, textButtonColour,
  51562. TextEditor::shadowColourId, 0x38000000,
  51563. Label::backgroundColourId, 0x00000000,
  51564. Label::textColourId, 0xff000000,
  51565. Label::outlineColourId, 0x00000000,
  51566. ScrollBar::backgroundColourId, 0x00000000,
  51567. ScrollBar::thumbColourId, 0xffffffff,
  51568. ScrollBar::trackColourId, 0xffffffff,
  51569. TreeView::linesColourId, 0x4c000000,
  51570. TreeView::backgroundColourId, 0x00000000,
  51571. TreeView::dragAndDropIndicatorColourId, 0x80ff0000,
  51572. PopupMenu::backgroundColourId, 0xffffffff,
  51573. PopupMenu::textColourId, 0xff000000,
  51574. PopupMenu::headerTextColourId, 0xff000000,
  51575. PopupMenu::highlightedTextColourId, 0xffffffff,
  51576. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  51577. ComboBox::textColourId, 0xff000000,
  51578. ComboBox::backgroundColourId, 0xffffffff,
  51579. ComboBox::arrowColourId, 0x99000000,
  51580. ListBox::backgroundColourId, 0xffffffff,
  51581. ListBox::outlineColourId, standardOutlineColour,
  51582. ListBox::textColourId, 0xff000000,
  51583. Slider::backgroundColourId, 0x00000000,
  51584. Slider::thumbColourId, textButtonColour,
  51585. Slider::trackColourId, 0x7fffffff,
  51586. Slider::rotarySliderFillColourId, 0x7f0000ff,
  51587. Slider::rotarySliderOutlineColourId, 0x66000000,
  51588. Slider::textBoxTextColourId, 0xff000000,
  51589. Slider::textBoxBackgroundColourId, 0xffffffff,
  51590. Slider::textBoxHighlightColourId, textHighlightColour,
  51591. Slider::textBoxOutlineColourId, standardOutlineColour,
  51592. ResizableWindow::backgroundColourId, 0xff777777,
  51593. //DocumentWindow::textColourId, 0xff000000, // (this is deliberately not set)
  51594. AlertWindow::backgroundColourId, 0xffededed,
  51595. AlertWindow::textColourId, 0xff000000,
  51596. AlertWindow::outlineColourId, 0xff666666,
  51597. ProgressBar::backgroundColourId, 0xffeeeeee,
  51598. ProgressBar::foregroundColourId, 0xffaaaaee,
  51599. TooltipWindow::backgroundColourId, 0xffeeeebb,
  51600. TooltipWindow::textColourId, 0xff000000,
  51601. TooltipWindow::outlineColourId, 0x4c000000,
  51602. TabbedComponent::backgroundColourId, 0x00000000,
  51603. TabbedComponent::outlineColourId, 0xff777777,
  51604. TabbedButtonBar::tabOutlineColourId, 0x80000000,
  51605. TabbedButtonBar::frontOutlineColourId, 0x90000000,
  51606. Toolbar::backgroundColourId, 0xfff6f8f9,
  51607. Toolbar::separatorColourId, 0x4c000000,
  51608. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  51609. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  51610. Toolbar::labelTextColourId, 0xff000000,
  51611. Toolbar::editingModeOutlineColourId, 0xffff0000,
  51612. HyperlinkButton::textColourId, 0xcc1111ee,
  51613. GroupComponent::outlineColourId, 0x66000000,
  51614. GroupComponent::textColourId, 0xff000000,
  51615. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  51616. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  51617. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  51618. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  51619. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  51620. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  51621. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  51622. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  51623. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  51624. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  51625. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  51626. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  51627. CodeEditorComponent::backgroundColourId, 0xffffffff,
  51628. CodeEditorComponent::caretColourId, 0xff000000,
  51629. CodeEditorComponent::highlightColourId, textHighlightColour,
  51630. CodeEditorComponent::defaultTextColourId, 0xff000000,
  51631. ColourSelector::backgroundColourId, 0xffe5e5e5,
  51632. ColourSelector::labelTextColourId, 0xff000000,
  51633. KeyMappingEditorComponent::backgroundColourId, 0x00000000,
  51634. KeyMappingEditorComponent::textColourId, 0xff000000,
  51635. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  51636. FileChooserDialogBox::titleTextColourId, 0xff000000,
  51637. };
  51638. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  51639. setColour (standardColours [i], Colour (standardColours [i + 1]));
  51640. static String defaultSansName, defaultSerifName, defaultFixedName;
  51641. if (defaultSansName.isEmpty())
  51642. Font::getPlatformDefaultFontNames (defaultSansName, defaultSerifName, defaultFixedName);
  51643. defaultSans = defaultSansName;
  51644. defaultSerif = defaultSerifName;
  51645. defaultFixed = defaultFixedName;
  51646. }
  51647. LookAndFeel::~LookAndFeel()
  51648. {
  51649. }
  51650. const Colour LookAndFeel::findColour (const int colourId) const throw()
  51651. {
  51652. const int index = colourIds.indexOf (colourId);
  51653. if (index >= 0)
  51654. return colours [index];
  51655. jassertfalse;
  51656. return Colours::black;
  51657. }
  51658. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  51659. {
  51660. const int index = colourIds.indexOf (colourId);
  51661. if (index >= 0)
  51662. {
  51663. colours.set (index, colour);
  51664. }
  51665. else
  51666. {
  51667. colourIds.add (colourId);
  51668. colours.add (colour);
  51669. }
  51670. }
  51671. bool LookAndFeel::isColourSpecified (const int colourId) const throw()
  51672. {
  51673. return colourIds.contains (colourId);
  51674. }
  51675. static LookAndFeel* defaultLF = 0;
  51676. static LookAndFeel* currentDefaultLF = 0;
  51677. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  51678. {
  51679. // if this happens, your app hasn't initialised itself properly.. if you're
  51680. // trying to hack your own main() function, have a look at
  51681. // JUCEApplication::initialiseForGUI()
  51682. jassert (currentDefaultLF != 0);
  51683. return *currentDefaultLF;
  51684. }
  51685. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  51686. {
  51687. if (newDefaultLookAndFeel == 0)
  51688. {
  51689. if (defaultLF == 0)
  51690. defaultLF = new LookAndFeel();
  51691. newDefaultLookAndFeel = defaultLF;
  51692. }
  51693. currentDefaultLF = newDefaultLookAndFeel;
  51694. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  51695. {
  51696. Component* const c = Desktop::getInstance().getComponent (i);
  51697. if (c != 0)
  51698. c->sendLookAndFeelChange();
  51699. }
  51700. }
  51701. void LookAndFeel::clearDefaultLookAndFeel() throw()
  51702. {
  51703. if (currentDefaultLF == defaultLF)
  51704. currentDefaultLF = 0;
  51705. deleteAndZero (defaultLF);
  51706. }
  51707. const Typeface::Ptr LookAndFeel::getTypefaceForFont (const Font& font)
  51708. {
  51709. String faceName (font.getTypefaceName());
  51710. if (faceName == Font::getDefaultSansSerifFontName())
  51711. faceName = defaultSans;
  51712. else if (faceName == Font::getDefaultSerifFontName())
  51713. faceName = defaultSerif;
  51714. else if (faceName == Font::getDefaultMonospacedFontName())
  51715. faceName = defaultFixed;
  51716. Font f (font);
  51717. f.setTypefaceName (faceName);
  51718. return Typeface::createSystemTypefaceFor (f);
  51719. }
  51720. void LookAndFeel::setDefaultSansSerifTypefaceName (const String& newName)
  51721. {
  51722. defaultSans = newName;
  51723. }
  51724. const MouseCursor LookAndFeel::getMouseCursorFor (Component& component)
  51725. {
  51726. return component.getMouseCursor();
  51727. }
  51728. void LookAndFeel::drawButtonBackground (Graphics& g,
  51729. Button& button,
  51730. const Colour& backgroundColour,
  51731. bool isMouseOverButton,
  51732. bool isButtonDown)
  51733. {
  51734. const int width = button.getWidth();
  51735. const int height = button.getHeight();
  51736. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  51737. const float halfThickness = outlineThickness * 0.5f;
  51738. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  51739. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  51740. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  51741. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  51742. const Colour baseColour (createBaseColour (backgroundColour,
  51743. button.hasKeyboardFocus (true),
  51744. isMouseOverButton, isButtonDown)
  51745. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  51746. drawGlassLozenge (g,
  51747. indentL,
  51748. indentT,
  51749. width - indentL - indentR,
  51750. height - indentT - indentB,
  51751. baseColour, outlineThickness, -1.0f,
  51752. button.isConnectedOnLeft(),
  51753. button.isConnectedOnRight(),
  51754. button.isConnectedOnTop(),
  51755. button.isConnectedOnBottom());
  51756. }
  51757. const Font LookAndFeel::getFontForTextButton (TextButton& button)
  51758. {
  51759. return button.getFont();
  51760. }
  51761. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  51762. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  51763. {
  51764. Font font (getFontForTextButton (button));
  51765. g.setFont (font);
  51766. g.setColour (button.findColour (button.getToggleState() ? TextButton::textColourOnId
  51767. : TextButton::textColourOffId)
  51768. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  51769. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  51770. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  51771. const int fontHeight = roundToInt (font.getHeight() * 0.6f);
  51772. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  51773. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  51774. g.drawFittedText (button.getButtonText(),
  51775. leftIndent,
  51776. yIndent,
  51777. button.getWidth() - leftIndent - rightIndent,
  51778. button.getHeight() - yIndent * 2,
  51779. Justification::centred, 2);
  51780. }
  51781. void LookAndFeel::drawTickBox (Graphics& g,
  51782. Component& component,
  51783. float x, float y, float w, float h,
  51784. const bool ticked,
  51785. const bool isEnabled,
  51786. const bool isMouseOverButton,
  51787. const bool isButtonDown)
  51788. {
  51789. const float boxSize = w * 0.7f;
  51790. drawGlassSphere (g, x, y + (h - boxSize) * 0.5f, boxSize,
  51791. createBaseColour (component.findColour (TextButton::buttonColourId)
  51792. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  51793. true,
  51794. isMouseOverButton,
  51795. isButtonDown),
  51796. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  51797. if (ticked)
  51798. {
  51799. Path tick;
  51800. tick.startNewSubPath (1.5f, 3.0f);
  51801. tick.lineTo (3.0f, 6.0f);
  51802. tick.lineTo (6.0f, 0.0f);
  51803. g.setColour (isEnabled ? Colours::black : Colours::grey);
  51804. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  51805. .translated (x, y));
  51806. g.strokePath (tick, PathStrokeType (2.5f), trans);
  51807. }
  51808. }
  51809. void LookAndFeel::drawToggleButton (Graphics& g,
  51810. ToggleButton& button,
  51811. bool isMouseOverButton,
  51812. bool isButtonDown)
  51813. {
  51814. if (button.hasKeyboardFocus (true))
  51815. {
  51816. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  51817. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  51818. }
  51819. float fontSize = jmin (15.0f, button.getHeight() * 0.75f);
  51820. const float tickWidth = fontSize * 1.1f;
  51821. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  51822. tickWidth, tickWidth,
  51823. button.getToggleState(),
  51824. button.isEnabled(),
  51825. isMouseOverButton,
  51826. isButtonDown);
  51827. g.setColour (button.findColour (ToggleButton::textColourId));
  51828. g.setFont (fontSize);
  51829. if (! button.isEnabled())
  51830. g.setOpacity (0.5f);
  51831. const int textX = (int) tickWidth + 5;
  51832. g.drawFittedText (button.getButtonText(),
  51833. textX, 0,
  51834. button.getWidth() - textX - 2, button.getHeight(),
  51835. Justification::centredLeft, 10);
  51836. }
  51837. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  51838. {
  51839. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  51840. const int tickWidth = jmin (24, button.getHeight());
  51841. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  51842. button.getHeight());
  51843. }
  51844. AlertWindow* LookAndFeel::createAlertWindow (const String& title,
  51845. const String& message,
  51846. const String& button1,
  51847. const String& button2,
  51848. const String& button3,
  51849. AlertWindow::AlertIconType iconType,
  51850. int numButtons,
  51851. Component* associatedComponent)
  51852. {
  51853. AlertWindow* aw = new AlertWindow (title, message, iconType, associatedComponent);
  51854. if (numButtons == 1)
  51855. {
  51856. aw->addButton (button1, 0,
  51857. KeyPress (KeyPress::escapeKey, 0, 0),
  51858. KeyPress (KeyPress::returnKey, 0, 0));
  51859. }
  51860. else
  51861. {
  51862. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  51863. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  51864. if (button1ShortCut == button2ShortCut)
  51865. button2ShortCut = KeyPress();
  51866. if (numButtons == 2)
  51867. {
  51868. aw->addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  51869. aw->addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  51870. }
  51871. else if (numButtons == 3)
  51872. {
  51873. aw->addButton (button1, 1, button1ShortCut);
  51874. aw->addButton (button2, 2, button2ShortCut);
  51875. aw->addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  51876. }
  51877. }
  51878. return aw;
  51879. }
  51880. void LookAndFeel::drawAlertBox (Graphics& g,
  51881. AlertWindow& alert,
  51882. const Rectangle<int>& textArea,
  51883. TextLayout& textLayout)
  51884. {
  51885. g.fillAll (alert.findColour (AlertWindow::backgroundColourId));
  51886. int iconSpaceUsed = 0;
  51887. Justification alignment (Justification::horizontallyCentred);
  51888. const int iconWidth = 80;
  51889. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  51890. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  51891. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  51892. const Rectangle<int> iconRect (iconSize / -10, iconSize / -10,
  51893. iconSize, iconSize);
  51894. if (alert.getAlertType() != AlertWindow::NoIcon)
  51895. {
  51896. Path icon;
  51897. uint32 colour;
  51898. char character;
  51899. if (alert.getAlertType() == AlertWindow::WarningIcon)
  51900. {
  51901. colour = 0x55ff5555;
  51902. character = '!';
  51903. icon.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f, (float) iconRect.getY(),
  51904. (float) iconRect.getRight(), (float) iconRect.getBottom(),
  51905. (float) iconRect.getX(), (float) iconRect.getBottom());
  51906. icon = icon.createPathWithRoundedCorners (5.0f);
  51907. }
  51908. else
  51909. {
  51910. colour = alert.getAlertType() == AlertWindow::InfoIcon ? 0x605555ff : 0x40b69900;
  51911. character = alert.getAlertType() == AlertWindow::InfoIcon ? 'i' : '?';
  51912. icon.addEllipse ((float) iconRect.getX(), (float) iconRect.getY(),
  51913. (float) iconRect.getWidth(), (float) iconRect.getHeight());
  51914. }
  51915. GlyphArrangement ga;
  51916. ga.addFittedText (Font (iconRect.getHeight() * 0.9f, Font::bold),
  51917. String::charToString (character),
  51918. (float) iconRect.getX(), (float) iconRect.getY(),
  51919. (float) iconRect.getWidth(), (float) iconRect.getHeight(),
  51920. Justification::centred, false);
  51921. ga.createPath (icon);
  51922. icon.setUsingNonZeroWinding (false);
  51923. g.setColour (Colour (colour));
  51924. g.fillPath (icon);
  51925. iconSpaceUsed = iconWidth;
  51926. alignment = Justification::left;
  51927. }
  51928. g.setColour (alert.findColour (AlertWindow::textColourId));
  51929. textLayout.drawWithin (g,
  51930. textArea.getX() + iconSpaceUsed, textArea.getY(),
  51931. textArea.getWidth() - iconSpaceUsed, textArea.getHeight(),
  51932. alignment.getFlags() | Justification::top);
  51933. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  51934. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  51935. }
  51936. int LookAndFeel::getAlertBoxWindowFlags()
  51937. {
  51938. return ComponentPeer::windowAppearsOnTaskbar
  51939. | ComponentPeer::windowHasDropShadow;
  51940. }
  51941. int LookAndFeel::getAlertWindowButtonHeight()
  51942. {
  51943. return 28;
  51944. }
  51945. const Font LookAndFeel::getAlertWindowFont()
  51946. {
  51947. return Font (12.0f);
  51948. }
  51949. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  51950. int width, int height,
  51951. double progress, const String& textToShow)
  51952. {
  51953. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  51954. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  51955. g.fillAll (background);
  51956. if (progress >= 0.0f && progress < 1.0f)
  51957. {
  51958. drawGlassLozenge (g, 1.0f, 1.0f,
  51959. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  51960. (float) (height - 2),
  51961. foreground,
  51962. 0.5f, 0.0f,
  51963. true, true, true, true);
  51964. }
  51965. else
  51966. {
  51967. // spinning bar..
  51968. g.setColour (foreground);
  51969. const int stripeWidth = height * 2;
  51970. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  51971. Path p;
  51972. for (float x = (float) (- position); x < width + stripeWidth; x += stripeWidth)
  51973. p.addQuadrilateral (x, 0.0f,
  51974. x + stripeWidth * 0.5f, 0.0f,
  51975. x, (float) height,
  51976. x - stripeWidth * 0.5f, (float) height);
  51977. Image im (Image::ARGB, width, height, true);
  51978. {
  51979. Graphics g2 (im);
  51980. drawGlassLozenge (g2, 1.0f, 1.0f,
  51981. (float) (width - 2),
  51982. (float) (height - 2),
  51983. foreground,
  51984. 0.5f, 0.0f,
  51985. true, true, true, true);
  51986. }
  51987. g.setTiledImageFill (im, 0, 0, 0.85f);
  51988. g.fillPath (p);
  51989. }
  51990. if (textToShow.isNotEmpty())
  51991. {
  51992. g.setColour (Colour::contrasting (background, foreground));
  51993. g.setFont (height * 0.6f);
  51994. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  51995. }
  51996. }
  51997. void LookAndFeel::drawSpinningWaitAnimation (Graphics& g, const Colour& colour, int x, int y, int w, int h)
  51998. {
  51999. const float radius = jmin (w, h) * 0.4f;
  52000. const float thickness = radius * 0.15f;
  52001. Path p;
  52002. p.addRoundedRectangle (radius * 0.4f, thickness * -0.5f,
  52003. radius * 0.6f, thickness,
  52004. thickness * 0.5f);
  52005. const float cx = x + w * 0.5f;
  52006. const float cy = y + h * 0.5f;
  52007. const uint32 animationIndex = (Time::getMillisecondCounter() / (1000 / 10)) % 12;
  52008. for (int i = 0; i < 12; ++i)
  52009. {
  52010. const int n = (i + 12 - animationIndex) % 12;
  52011. g.setColour (colour.withMultipliedAlpha ((n + 1) / 12.0f));
  52012. g.fillPath (p, AffineTransform::rotation (i * (float_Pi / 6.0f))
  52013. .translated (cx, cy));
  52014. }
  52015. }
  52016. void LookAndFeel::drawScrollbarButton (Graphics& g,
  52017. ScrollBar& scrollbar,
  52018. int width, int height,
  52019. int buttonDirection,
  52020. bool /*isScrollbarVertical*/,
  52021. bool /*isMouseOverButton*/,
  52022. bool isButtonDown)
  52023. {
  52024. Path p;
  52025. if (buttonDirection == 0)
  52026. p.addTriangle (width * 0.5f, height * 0.2f,
  52027. width * 0.1f, height * 0.7f,
  52028. width * 0.9f, height * 0.7f);
  52029. else if (buttonDirection == 1)
  52030. p.addTriangle (width * 0.8f, height * 0.5f,
  52031. width * 0.3f, height * 0.1f,
  52032. width * 0.3f, height * 0.9f);
  52033. else if (buttonDirection == 2)
  52034. p.addTriangle (width * 0.5f, height * 0.8f,
  52035. width * 0.1f, height * 0.3f,
  52036. width * 0.9f, height * 0.3f);
  52037. else if (buttonDirection == 3)
  52038. p.addTriangle (width * 0.2f, height * 0.5f,
  52039. width * 0.7f, height * 0.1f,
  52040. width * 0.7f, height * 0.9f);
  52041. if (isButtonDown)
  52042. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  52043. else
  52044. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52045. g.fillPath (p);
  52046. g.setColour (Colour (0x80000000));
  52047. g.strokePath (p, PathStrokeType (0.5f));
  52048. }
  52049. void LookAndFeel::drawScrollbar (Graphics& g,
  52050. ScrollBar& scrollbar,
  52051. int x, int y,
  52052. int width, int height,
  52053. bool isScrollbarVertical,
  52054. int thumbStartPosition,
  52055. int thumbSize,
  52056. bool /*isMouseOver*/,
  52057. bool /*isMouseDown*/)
  52058. {
  52059. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  52060. Path slotPath, thumbPath;
  52061. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  52062. const float slotIndentx2 = slotIndent * 2.0f;
  52063. const float thumbIndent = slotIndent + 1.0f;
  52064. const float thumbIndentx2 = thumbIndent * 2.0f;
  52065. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  52066. if (isScrollbarVertical)
  52067. {
  52068. slotPath.addRoundedRectangle (x + slotIndent,
  52069. y + slotIndent,
  52070. width - slotIndentx2,
  52071. height - slotIndentx2,
  52072. (width - slotIndentx2) * 0.5f);
  52073. if (thumbSize > 0)
  52074. thumbPath.addRoundedRectangle (x + thumbIndent,
  52075. thumbStartPosition + thumbIndent,
  52076. width - thumbIndentx2,
  52077. thumbSize - thumbIndentx2,
  52078. (width - thumbIndentx2) * 0.5f);
  52079. gx1 = (float) x;
  52080. gx2 = x + width * 0.7f;
  52081. }
  52082. else
  52083. {
  52084. slotPath.addRoundedRectangle (x + slotIndent,
  52085. y + slotIndent,
  52086. width - slotIndentx2,
  52087. height - slotIndentx2,
  52088. (height - slotIndentx2) * 0.5f);
  52089. if (thumbSize > 0)
  52090. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  52091. y + thumbIndent,
  52092. thumbSize - thumbIndentx2,
  52093. height - thumbIndentx2,
  52094. (height - thumbIndentx2) * 0.5f);
  52095. gy1 = (float) y;
  52096. gy2 = y + height * 0.7f;
  52097. }
  52098. const Colour thumbColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52099. g.setGradientFill (ColourGradient (thumbColour.overlaidWith (Colour (0x44000000)), gx1, gy1,
  52100. thumbColour.overlaidWith (Colour (0x19000000)), gx2, gy2, false));
  52101. g.fillPath (slotPath);
  52102. if (isScrollbarVertical)
  52103. {
  52104. gx1 = x + width * 0.6f;
  52105. gx2 = (float) x + width;
  52106. }
  52107. else
  52108. {
  52109. gy1 = y + height * 0.6f;
  52110. gy2 = (float) y + height;
  52111. }
  52112. g.setGradientFill (ColourGradient (Colours::transparentBlack,gx1, gy1,
  52113. Colour (0x19000000), gx2, gy2, false));
  52114. g.fillPath (slotPath);
  52115. g.setColour (thumbColour);
  52116. g.fillPath (thumbPath);
  52117. g.setGradientFill (ColourGradient (Colour (0x10000000), gx1, gy1,
  52118. Colours::transparentBlack, gx2, gy2, false));
  52119. g.saveState();
  52120. if (isScrollbarVertical)
  52121. g.reduceClipRegion (x + width / 2, y, width, height);
  52122. else
  52123. g.reduceClipRegion (x, y + height / 2, width, height);
  52124. g.fillPath (thumbPath);
  52125. g.restoreState();
  52126. g.setColour (Colour (0x4c000000));
  52127. g.strokePath (thumbPath, PathStrokeType (0.4f));
  52128. }
  52129. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  52130. {
  52131. return 0;
  52132. }
  52133. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  52134. {
  52135. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  52136. }
  52137. int LookAndFeel::getDefaultScrollbarWidth()
  52138. {
  52139. return 18;
  52140. }
  52141. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  52142. {
  52143. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  52144. : scrollbar.getHeight());
  52145. }
  52146. const Path LookAndFeel::getTickShape (const float height)
  52147. {
  52148. static const unsigned char tickShapeData[] =
  52149. {
  52150. 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,
  52151. 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,
  52152. 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,
  52153. 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,
  52154. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  52155. };
  52156. Path p;
  52157. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  52158. p.scaleToFit (0, 0, height * 2.0f, height, true);
  52159. return p;
  52160. }
  52161. const Path LookAndFeel::getCrossShape (const float height)
  52162. {
  52163. static const unsigned char crossShapeData[] =
  52164. {
  52165. 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,
  52166. 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,
  52167. 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,
  52168. 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,
  52169. 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,
  52170. 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,
  52171. 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
  52172. };
  52173. Path p;
  52174. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  52175. p.scaleToFit (0, 0, height * 2.0f, height, true);
  52176. return p;
  52177. }
  52178. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool /*isMouseOver*/)
  52179. {
  52180. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  52181. x += (w - boxSize) >> 1;
  52182. y += (h - boxSize) >> 1;
  52183. w = boxSize;
  52184. h = boxSize;
  52185. g.setColour (Colour (0xe5ffffff));
  52186. g.fillRect (x, y, w, h);
  52187. g.setColour (Colour (0x80000000));
  52188. g.drawRect (x, y, w, h);
  52189. const float size = boxSize / 2 + 1.0f;
  52190. const float centre = (float) (boxSize / 2);
  52191. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  52192. if (isPlus)
  52193. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  52194. }
  52195. void LookAndFeel::drawBubble (Graphics& g,
  52196. float tipX, float tipY,
  52197. float boxX, float boxY,
  52198. float boxW, float boxH)
  52199. {
  52200. int side = 0;
  52201. if (tipX < boxX)
  52202. side = 1;
  52203. else if (tipX > boxX + boxW)
  52204. side = 3;
  52205. else if (tipY > boxY + boxH)
  52206. side = 2;
  52207. const float indent = 2.0f;
  52208. Path p;
  52209. p.addBubble (boxX + indent,
  52210. boxY + indent,
  52211. boxW - indent * 2.0f,
  52212. boxH - indent * 2.0f,
  52213. 5.0f,
  52214. tipX, tipY,
  52215. side,
  52216. 0.5f,
  52217. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  52218. //xxx need to take comp as param for colour
  52219. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  52220. g.fillPath (p);
  52221. //xxx as above
  52222. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  52223. g.strokePath (p, PathStrokeType (1.33f));
  52224. }
  52225. const Font LookAndFeel::getPopupMenuFont()
  52226. {
  52227. return Font (17.0f);
  52228. }
  52229. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  52230. const bool isSeparator,
  52231. int standardMenuItemHeight,
  52232. int& idealWidth,
  52233. int& idealHeight)
  52234. {
  52235. if (isSeparator)
  52236. {
  52237. idealWidth = 50;
  52238. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  52239. }
  52240. else
  52241. {
  52242. Font font (getPopupMenuFont());
  52243. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  52244. font.setHeight (standardMenuItemHeight / 1.3f);
  52245. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundToInt (font.getHeight() * 1.3f);
  52246. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  52247. }
  52248. }
  52249. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  52250. {
  52251. const Colour background (findColour (PopupMenu::backgroundColourId));
  52252. g.fillAll (background);
  52253. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  52254. for (int i = 0; i < height; i += 3)
  52255. g.fillRect (0, i, width, 1);
  52256. #if ! JUCE_MAC
  52257. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  52258. g.drawRect (0, 0, width, height);
  52259. #endif
  52260. }
  52261. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  52262. int width, int height,
  52263. bool isScrollUpArrow)
  52264. {
  52265. const Colour background (findColour (PopupMenu::backgroundColourId));
  52266. g.setGradientFill (ColourGradient (background, 0.0f, height * 0.5f,
  52267. background.withAlpha (0.0f),
  52268. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  52269. false));
  52270. g.fillRect (1, 1, width - 2, height - 2);
  52271. const float hw = width * 0.5f;
  52272. const float arrowW = height * 0.3f;
  52273. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  52274. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  52275. Path p;
  52276. p.addTriangle (hw - arrowW, y1,
  52277. hw + arrowW, y1,
  52278. hw, y2);
  52279. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  52280. g.fillPath (p);
  52281. }
  52282. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  52283. int width, int height,
  52284. const bool isSeparator,
  52285. const bool isActive,
  52286. const bool isHighlighted,
  52287. const bool isTicked,
  52288. const bool hasSubMenu,
  52289. const String& text,
  52290. const String& shortcutKeyText,
  52291. Image* image,
  52292. const Colour* const textColourToUse)
  52293. {
  52294. const float halfH = height * 0.5f;
  52295. if (isSeparator)
  52296. {
  52297. const float separatorIndent = 5.5f;
  52298. g.setColour (Colour (0x33000000));
  52299. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  52300. g.setColour (Colour (0x66ffffff));
  52301. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  52302. }
  52303. else
  52304. {
  52305. Colour textColour (findColour (PopupMenu::textColourId));
  52306. if (textColourToUse != 0)
  52307. textColour = *textColourToUse;
  52308. if (isHighlighted)
  52309. {
  52310. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  52311. g.fillRect (1, 1, width - 2, height - 2);
  52312. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  52313. }
  52314. else
  52315. {
  52316. g.setColour (textColour);
  52317. }
  52318. if (! isActive)
  52319. g.setOpacity (0.3f);
  52320. Font font (getPopupMenuFont());
  52321. if (font.getHeight() > height / 1.3f)
  52322. font.setHeight (height / 1.3f);
  52323. g.setFont (font);
  52324. const int leftBorder = (height * 5) / 4;
  52325. const int rightBorder = 4;
  52326. if (image != 0)
  52327. {
  52328. g.drawImageWithin (*image,
  52329. 2, 1, leftBorder - 4, height - 2,
  52330. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  52331. }
  52332. else if (isTicked)
  52333. {
  52334. const Path tick (getTickShape (1.0f));
  52335. const float th = font.getAscent();
  52336. const float ty = halfH - th * 0.5f;
  52337. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  52338. th, true));
  52339. }
  52340. g.drawFittedText (text,
  52341. leftBorder, 0,
  52342. width - (leftBorder + rightBorder), height,
  52343. Justification::centredLeft, 1);
  52344. if (shortcutKeyText.isNotEmpty())
  52345. {
  52346. Font f2 (font);
  52347. f2.setHeight (f2.getHeight() * 0.75f);
  52348. f2.setHorizontalScale (0.95f);
  52349. g.setFont (f2);
  52350. g.drawText (shortcutKeyText,
  52351. leftBorder,
  52352. 0,
  52353. width - (leftBorder + rightBorder + 4),
  52354. height,
  52355. Justification::centredRight,
  52356. true);
  52357. }
  52358. if (hasSubMenu)
  52359. {
  52360. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  52361. const float x = width - height * 0.6f;
  52362. Path p;
  52363. p.addTriangle (x, halfH - arrowH * 0.5f,
  52364. x, halfH + arrowH * 0.5f,
  52365. x + arrowH * 0.6f, halfH);
  52366. g.fillPath (p);
  52367. }
  52368. }
  52369. }
  52370. int LookAndFeel::getMenuWindowFlags()
  52371. {
  52372. return ComponentPeer::windowHasDropShadow;
  52373. }
  52374. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  52375. bool, MenuBarComponent& menuBar)
  52376. {
  52377. const Colour baseColour (createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  52378. if (menuBar.isEnabled())
  52379. {
  52380. drawShinyButtonShape (g,
  52381. -4.0f, 0.0f,
  52382. width + 8.0f, (float) height,
  52383. 0.0f,
  52384. baseColour,
  52385. 0.4f,
  52386. true, true, true, true);
  52387. }
  52388. else
  52389. {
  52390. g.fillAll (baseColour);
  52391. }
  52392. }
  52393. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  52394. {
  52395. return Font (menuBar.getHeight() * 0.7f);
  52396. }
  52397. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  52398. {
  52399. return getMenuBarFont (menuBar, itemIndex, itemText)
  52400. .getStringWidth (itemText) + menuBar.getHeight();
  52401. }
  52402. void LookAndFeel::drawMenuBarItem (Graphics& g,
  52403. int width, int height,
  52404. int itemIndex,
  52405. const String& itemText,
  52406. bool isMouseOverItem,
  52407. bool isMenuOpen,
  52408. bool /*isMouseOverBar*/,
  52409. MenuBarComponent& menuBar)
  52410. {
  52411. if (! menuBar.isEnabled())
  52412. {
  52413. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  52414. .withMultipliedAlpha (0.5f));
  52415. }
  52416. else if (isMenuOpen || isMouseOverItem)
  52417. {
  52418. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  52419. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  52420. }
  52421. else
  52422. {
  52423. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  52424. }
  52425. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  52426. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  52427. }
  52428. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  52429. TextEditor& textEditor)
  52430. {
  52431. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  52432. }
  52433. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  52434. {
  52435. if (textEditor.isEnabled())
  52436. {
  52437. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  52438. {
  52439. const int border = 2;
  52440. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  52441. g.drawRect (0, 0, width, height, border);
  52442. g.setOpacity (1.0f);
  52443. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  52444. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  52445. }
  52446. else
  52447. {
  52448. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  52449. g.drawRect (0, 0, width, height);
  52450. g.setOpacity (1.0f);
  52451. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  52452. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  52453. }
  52454. }
  52455. }
  52456. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  52457. const bool isButtonDown,
  52458. int buttonX, int buttonY,
  52459. int buttonW, int buttonH,
  52460. ComboBox& box)
  52461. {
  52462. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  52463. if (box.isEnabled() && box.hasKeyboardFocus (false))
  52464. {
  52465. g.setColour (box.findColour (TextButton::buttonColourId));
  52466. g.drawRect (0, 0, width, height, 2);
  52467. }
  52468. else
  52469. {
  52470. g.setColour (box.findColour (ComboBox::outlineColourId));
  52471. g.drawRect (0, 0, width, height);
  52472. }
  52473. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  52474. const Colour baseColour (createBaseColour (box.findColour (ComboBox::buttonColourId),
  52475. box.hasKeyboardFocus (true),
  52476. false, isButtonDown)
  52477. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  52478. drawGlassLozenge (g,
  52479. buttonX + outlineThickness, buttonY + outlineThickness,
  52480. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  52481. baseColour, outlineThickness, -1.0f,
  52482. true, true, true, true);
  52483. if (box.isEnabled())
  52484. {
  52485. const float arrowX = 0.3f;
  52486. const float arrowH = 0.2f;
  52487. Path p;
  52488. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  52489. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  52490. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  52491. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  52492. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  52493. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  52494. g.setColour (box.findColour (ComboBox::arrowColourId));
  52495. g.fillPath (p);
  52496. }
  52497. }
  52498. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  52499. {
  52500. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  52501. }
  52502. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  52503. {
  52504. return new Label (String::empty, String::empty);
  52505. }
  52506. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  52507. {
  52508. label.setBounds (1, 1,
  52509. box.getWidth() + 3 - box.getHeight(),
  52510. box.getHeight() - 2);
  52511. label.setFont (getComboBoxFont (box));
  52512. }
  52513. void LookAndFeel::drawLabel (Graphics& g, Label& label)
  52514. {
  52515. g.fillAll (label.findColour (Label::backgroundColourId));
  52516. if (! label.isBeingEdited())
  52517. {
  52518. const float alpha = label.isEnabled() ? 1.0f : 0.5f;
  52519. g.setColour (label.findColour (Label::textColourId).withMultipliedAlpha (alpha));
  52520. g.setFont (label.getFont());
  52521. g.drawFittedText (label.getText(),
  52522. label.getHorizontalBorderSize(),
  52523. label.getVerticalBorderSize(),
  52524. label.getWidth() - 2 * label.getHorizontalBorderSize(),
  52525. label.getHeight() - 2 * label.getVerticalBorderSize(),
  52526. label.getJustificationType(),
  52527. jmax (1, (int) (label.getHeight() / label.getFont().getHeight())),
  52528. label.getMinimumHorizontalScale());
  52529. g.setColour (label.findColour (Label::outlineColourId).withMultipliedAlpha (alpha));
  52530. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  52531. }
  52532. else if (label.isEnabled())
  52533. {
  52534. g.setColour (label.findColour (Label::outlineColourId));
  52535. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  52536. }
  52537. }
  52538. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  52539. int x, int y,
  52540. int width, int height,
  52541. float /*sliderPos*/,
  52542. float /*minSliderPos*/,
  52543. float /*maxSliderPos*/,
  52544. const Slider::SliderStyle /*style*/,
  52545. Slider& slider)
  52546. {
  52547. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  52548. const Colour trackColour (slider.findColour (Slider::trackColourId));
  52549. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  52550. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  52551. Path indent;
  52552. if (slider.isHorizontal())
  52553. {
  52554. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  52555. const float ih = sliderRadius;
  52556. g.setGradientFill (ColourGradient (gradCol1, 0.0f, iy,
  52557. gradCol2, 0.0f, iy + ih, false));
  52558. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  52559. width + sliderRadius, ih,
  52560. 5.0f);
  52561. g.fillPath (indent);
  52562. }
  52563. else
  52564. {
  52565. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  52566. const float iw = sliderRadius;
  52567. g.setGradientFill (ColourGradient (gradCol1, ix, 0.0f,
  52568. gradCol2, ix + iw, 0.0f, false));
  52569. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  52570. iw, height + sliderRadius,
  52571. 5.0f);
  52572. g.fillPath (indent);
  52573. }
  52574. g.setColour (Colour (0x4c000000));
  52575. g.strokePath (indent, PathStrokeType (0.5f));
  52576. }
  52577. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  52578. int x, int y,
  52579. int width, int height,
  52580. float sliderPos,
  52581. float minSliderPos,
  52582. float maxSliderPos,
  52583. const Slider::SliderStyle style,
  52584. Slider& slider)
  52585. {
  52586. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  52587. Colour knobColour (createBaseColour (slider.findColour (Slider::thumbColourId),
  52588. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  52589. slider.isMouseOverOrDragging() && slider.isEnabled(),
  52590. slider.isMouseButtonDown() && slider.isEnabled()));
  52591. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  52592. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  52593. {
  52594. float kx, ky;
  52595. if (style == Slider::LinearVertical)
  52596. {
  52597. kx = x + width * 0.5f;
  52598. ky = sliderPos;
  52599. }
  52600. else
  52601. {
  52602. kx = sliderPos;
  52603. ky = y + height * 0.5f;
  52604. }
  52605. drawGlassSphere (g,
  52606. kx - sliderRadius,
  52607. ky - sliderRadius,
  52608. sliderRadius * 2.0f,
  52609. knobColour, outlineThickness);
  52610. }
  52611. else
  52612. {
  52613. if (style == Slider::ThreeValueVertical)
  52614. {
  52615. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  52616. sliderPos - sliderRadius,
  52617. sliderRadius * 2.0f,
  52618. knobColour, outlineThickness);
  52619. }
  52620. else if (style == Slider::ThreeValueHorizontal)
  52621. {
  52622. drawGlassSphere (g,sliderPos - sliderRadius,
  52623. y + height * 0.5f - sliderRadius,
  52624. sliderRadius * 2.0f,
  52625. knobColour, outlineThickness);
  52626. }
  52627. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  52628. {
  52629. const float sr = jmin (sliderRadius, width * 0.4f);
  52630. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  52631. minSliderPos - sliderRadius,
  52632. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  52633. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  52634. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  52635. }
  52636. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  52637. {
  52638. const float sr = jmin (sliderRadius, height * 0.4f);
  52639. drawGlassPointer (g, minSliderPos - sr,
  52640. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  52641. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  52642. drawGlassPointer (g, maxSliderPos - sliderRadius,
  52643. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  52644. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  52645. }
  52646. }
  52647. }
  52648. void LookAndFeel::drawLinearSlider (Graphics& g,
  52649. int x, int y,
  52650. int width, int height,
  52651. float sliderPos,
  52652. float minSliderPos,
  52653. float maxSliderPos,
  52654. const Slider::SliderStyle style,
  52655. Slider& slider)
  52656. {
  52657. g.fillAll (slider.findColour (Slider::backgroundColourId));
  52658. if (style == Slider::LinearBar)
  52659. {
  52660. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  52661. Colour baseColour (createBaseColour (slider.findColour (Slider::thumbColourId)
  52662. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  52663. false,
  52664. isMouseOver,
  52665. isMouseOver || slider.isMouseButtonDown()));
  52666. drawShinyButtonShape (g,
  52667. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  52668. baseColour,
  52669. slider.isEnabled() ? 0.9f : 0.3f,
  52670. true, true, true, true);
  52671. }
  52672. else
  52673. {
  52674. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  52675. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  52676. }
  52677. }
  52678. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  52679. {
  52680. return jmin (7,
  52681. slider.getHeight() / 2,
  52682. slider.getWidth() / 2) + 2;
  52683. }
  52684. void LookAndFeel::drawRotarySlider (Graphics& g,
  52685. int x, int y,
  52686. int width, int height,
  52687. float sliderPos,
  52688. const float rotaryStartAngle,
  52689. const float rotaryEndAngle,
  52690. Slider& slider)
  52691. {
  52692. const float radius = jmin (width / 2, height / 2) - 2.0f;
  52693. const float centreX = x + width * 0.5f;
  52694. const float centreY = y + height * 0.5f;
  52695. const float rx = centreX - radius;
  52696. const float ry = centreY - radius;
  52697. const float rw = radius * 2.0f;
  52698. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  52699. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  52700. if (radius > 12.0f)
  52701. {
  52702. if (slider.isEnabled())
  52703. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  52704. else
  52705. g.setColour (Colour (0x80808080));
  52706. const float thickness = 0.7f;
  52707. {
  52708. Path filledArc;
  52709. filledArc.addPieSegment (rx, ry, rw, rw,
  52710. rotaryStartAngle,
  52711. angle,
  52712. thickness);
  52713. g.fillPath (filledArc);
  52714. }
  52715. if (thickness > 0)
  52716. {
  52717. const float innerRadius = radius * 0.2f;
  52718. Path p;
  52719. p.addTriangle (-innerRadius, 0.0f,
  52720. 0.0f, -radius * thickness * 1.1f,
  52721. innerRadius, 0.0f);
  52722. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  52723. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  52724. }
  52725. if (slider.isEnabled())
  52726. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  52727. else
  52728. g.setColour (Colour (0x80808080));
  52729. Path outlineArc;
  52730. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  52731. outlineArc.closeSubPath();
  52732. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  52733. }
  52734. else
  52735. {
  52736. if (slider.isEnabled())
  52737. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  52738. else
  52739. g.setColour (Colour (0x80808080));
  52740. Path p;
  52741. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  52742. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  52743. p.addLineSegment (Line<float> (0.0f, 0.0f, 0.0f, -radius), rw * 0.2f);
  52744. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  52745. }
  52746. }
  52747. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  52748. {
  52749. return new TextButton (isIncrement ? "+" : "-", String::empty);
  52750. }
  52751. class SliderLabelComp : public Label
  52752. {
  52753. public:
  52754. SliderLabelComp() : Label (String::empty, String::empty) {}
  52755. ~SliderLabelComp() {}
  52756. void mouseWheelMove (const MouseEvent&, float, float) {}
  52757. };
  52758. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  52759. {
  52760. Label* const l = new SliderLabelComp();
  52761. l->setJustificationType (Justification::centred);
  52762. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  52763. l->setColour (Label::backgroundColourId,
  52764. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  52765. : slider.findColour (Slider::textBoxBackgroundColourId));
  52766. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  52767. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  52768. l->setColour (TextEditor::backgroundColourId,
  52769. slider.findColour (Slider::textBoxBackgroundColourId)
  52770. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  52771. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  52772. return l;
  52773. }
  52774. ImageEffectFilter* LookAndFeel::getSliderEffect()
  52775. {
  52776. return 0;
  52777. }
  52778. static const TextLayout layoutTooltipText (const String& text) throw()
  52779. {
  52780. const float tooltipFontSize = 12.0f;
  52781. const int maxToolTipWidth = 400;
  52782. const Font f (tooltipFontSize, Font::bold);
  52783. TextLayout tl (text, f);
  52784. tl.layout (maxToolTipWidth, Justification::left, true);
  52785. return tl;
  52786. }
  52787. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  52788. {
  52789. const TextLayout tl (layoutTooltipText (tipText));
  52790. width = tl.getWidth() + 14;
  52791. height = tl.getHeight() + 6;
  52792. }
  52793. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  52794. {
  52795. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  52796. const Colour textCol (findColour (TooltipWindow::textColourId));
  52797. #if ! JUCE_MAC // The mac windows already have a non-optional 1 pix outline, so don't double it here..
  52798. g.setColour (findColour (TooltipWindow::outlineColourId));
  52799. g.drawRect (0, 0, width, height, 1);
  52800. #endif
  52801. const TextLayout tl (layoutTooltipText (text));
  52802. g.setColour (findColour (TooltipWindow::textColourId));
  52803. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  52804. }
  52805. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  52806. {
  52807. return new TextButton (text, TRANS("click to browse for a different file"));
  52808. }
  52809. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  52810. ComboBox* filenameBox,
  52811. Button* browseButton)
  52812. {
  52813. browseButton->setSize (80, filenameComp.getHeight());
  52814. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  52815. if (tb != 0)
  52816. tb->changeWidthToFitText();
  52817. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  52818. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  52819. }
  52820. void LookAndFeel::drawImageButton (Graphics& g, Image* image,
  52821. int imageX, int imageY, int imageW, int imageH,
  52822. const Colour& overlayColour,
  52823. float imageOpacity,
  52824. ImageButton& button)
  52825. {
  52826. if (! button.isEnabled())
  52827. imageOpacity *= 0.3f;
  52828. if (! overlayColour.isOpaque())
  52829. {
  52830. g.setOpacity (imageOpacity);
  52831. g.drawImage (*image, imageX, imageY, imageW, imageH,
  52832. 0, 0, image->getWidth(), image->getHeight(), false);
  52833. }
  52834. if (! overlayColour.isTransparent())
  52835. {
  52836. g.setColour (overlayColour);
  52837. g.drawImage (*image, imageX, imageY, imageW, imageH,
  52838. 0, 0, image->getWidth(), image->getHeight(), true);
  52839. }
  52840. }
  52841. void LookAndFeel::drawCornerResizer (Graphics& g,
  52842. int w, int h,
  52843. bool /*isMouseOver*/,
  52844. bool /*isMouseDragging*/)
  52845. {
  52846. const float lineThickness = jmin (w, h) * 0.075f;
  52847. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  52848. {
  52849. g.setColour (Colours::lightgrey);
  52850. g.drawLine (w * i,
  52851. h + 1.0f,
  52852. w + 1.0f,
  52853. h * i,
  52854. lineThickness);
  52855. g.setColour (Colours::darkgrey);
  52856. g.drawLine (w * i + lineThickness,
  52857. h + 1.0f,
  52858. w + 1.0f,
  52859. h * i + lineThickness,
  52860. lineThickness);
  52861. }
  52862. }
  52863. void LookAndFeel::drawResizableFrame (Graphics&, int /*w*/, int /*h*/,
  52864. const BorderSize& /*borders*/)
  52865. {
  52866. }
  52867. void LookAndFeel::fillResizableWindowBackground (Graphics& g, int /*w*/, int /*h*/,
  52868. const BorderSize& /*border*/, ResizableWindow& window)
  52869. {
  52870. g.fillAll (window.getBackgroundColour());
  52871. }
  52872. void LookAndFeel::drawResizableWindowBorder (Graphics& g, int w, int h,
  52873. const BorderSize& border, ResizableWindow&)
  52874. {
  52875. g.setColour (Colour (0x80000000));
  52876. g.drawRect (0, 0, w, h);
  52877. g.setColour (Colour (0x19000000));
  52878. g.drawRect (border.getLeft() - 1,
  52879. border.getTop() - 1,
  52880. w + 2 - border.getLeftAndRight(),
  52881. h + 2 - border.getTopAndBottom());
  52882. }
  52883. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  52884. Graphics& g, int w, int h,
  52885. int titleSpaceX, int titleSpaceW,
  52886. const Image* icon,
  52887. bool drawTitleTextOnLeft)
  52888. {
  52889. const bool isActive = window.isActiveWindow();
  52890. g.setGradientFill (ColourGradient (window.getBackgroundColour(),
  52891. 0.0f, 0.0f,
  52892. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  52893. 0.0f, (float) h, false));
  52894. g.fillAll();
  52895. Font font (h * 0.65f, Font::bold);
  52896. g.setFont (font);
  52897. int textW = font.getStringWidth (window.getName());
  52898. int iconW = 0;
  52899. int iconH = 0;
  52900. if (icon != 0)
  52901. {
  52902. iconH = (int) font.getHeight();
  52903. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  52904. }
  52905. textW = jmin (titleSpaceW, textW + iconW);
  52906. int textX = drawTitleTextOnLeft ? titleSpaceX
  52907. : jmax (titleSpaceX, (w - textW) / 2);
  52908. if (textX + textW > titleSpaceX + titleSpaceW)
  52909. textX = titleSpaceX + titleSpaceW - textW;
  52910. if (icon != 0)
  52911. {
  52912. g.setOpacity (isActive ? 1.0f : 0.6f);
  52913. g.drawImageWithin (*icon, textX, (h - iconH) / 2, iconW, iconH,
  52914. RectanglePlacement::centred, false);
  52915. textX += iconW;
  52916. textW -= iconW;
  52917. }
  52918. if (window.isColourSpecified (DocumentWindow::textColourId) || isColourSpecified (DocumentWindow::textColourId))
  52919. g.setColour (findColour (DocumentWindow::textColourId));
  52920. else
  52921. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  52922. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  52923. }
  52924. class GlassWindowButton : public Button
  52925. {
  52926. public:
  52927. GlassWindowButton (const String& name, const Colour& col,
  52928. const Path& normalShape_,
  52929. const Path& toggledShape_) throw()
  52930. : Button (name),
  52931. colour (col),
  52932. normalShape (normalShape_),
  52933. toggledShape (toggledShape_)
  52934. {
  52935. }
  52936. ~GlassWindowButton()
  52937. {
  52938. }
  52939. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  52940. {
  52941. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  52942. if (! isEnabled())
  52943. alpha *= 0.5f;
  52944. float x = 0, y = 0, diam;
  52945. if (getWidth() < getHeight())
  52946. {
  52947. diam = (float) getWidth();
  52948. y = (getHeight() - getWidth()) * 0.5f;
  52949. }
  52950. else
  52951. {
  52952. diam = (float) getHeight();
  52953. y = (getWidth() - getHeight()) * 0.5f;
  52954. }
  52955. x += diam * 0.05f;
  52956. y += diam * 0.05f;
  52957. diam *= 0.9f;
  52958. g.setGradientFill (ColourGradient (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  52959. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false));
  52960. g.fillEllipse (x, y, diam, diam);
  52961. x += 2.0f;
  52962. y += 2.0f;
  52963. diam -= 4.0f;
  52964. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  52965. Path& p = getToggleState() ? toggledShape : normalShape;
  52966. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  52967. diam * 0.4f, diam * 0.4f, true));
  52968. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  52969. g.fillPath (p, t);
  52970. }
  52971. juce_UseDebuggingNewOperator
  52972. private:
  52973. Colour colour;
  52974. Path normalShape, toggledShape;
  52975. GlassWindowButton (const GlassWindowButton&);
  52976. GlassWindowButton& operator= (const GlassWindowButton&);
  52977. };
  52978. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  52979. {
  52980. Path shape;
  52981. const float crossThickness = 0.25f;
  52982. if (buttonType == DocumentWindow::closeButton)
  52983. {
  52984. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), crossThickness * 1.4f);
  52985. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), crossThickness * 1.4f);
  52986. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  52987. }
  52988. else if (buttonType == DocumentWindow::minimiseButton)
  52989. {
  52990. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  52991. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  52992. }
  52993. else if (buttonType == DocumentWindow::maximiseButton)
  52994. {
  52995. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), crossThickness);
  52996. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  52997. Path fullscreenShape;
  52998. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  52999. fullscreenShape.lineTo (0.0f, 100.0f);
  53000. fullscreenShape.lineTo (0.0f, 0.0f);
  53001. fullscreenShape.lineTo (100.0f, 0.0f);
  53002. fullscreenShape.lineTo (100.0f, 45.0f);
  53003. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  53004. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  53005. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  53006. }
  53007. jassertfalse;
  53008. return 0;
  53009. }
  53010. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  53011. int titleBarX,
  53012. int titleBarY,
  53013. int titleBarW,
  53014. int titleBarH,
  53015. Button* minimiseButton,
  53016. Button* maximiseButton,
  53017. Button* closeButton,
  53018. bool positionTitleBarButtonsOnLeft)
  53019. {
  53020. const int buttonW = titleBarH - titleBarH / 8;
  53021. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  53022. : titleBarX + titleBarW - buttonW - buttonW / 4;
  53023. if (closeButton != 0)
  53024. {
  53025. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53026. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  53027. }
  53028. if (positionTitleBarButtonsOnLeft)
  53029. swapVariables (minimiseButton, maximiseButton);
  53030. if (maximiseButton != 0)
  53031. {
  53032. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53033. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  53034. }
  53035. if (minimiseButton != 0)
  53036. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53037. }
  53038. int LookAndFeel::getDefaultMenuBarHeight()
  53039. {
  53040. return 24;
  53041. }
  53042. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  53043. {
  53044. return new DropShadower (0.4f, 1, 5, 10);
  53045. }
  53046. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  53047. int w, int h,
  53048. bool /*isVerticalBar*/,
  53049. bool isMouseOver,
  53050. bool isMouseDragging)
  53051. {
  53052. float alpha = 0.5f;
  53053. if (isMouseOver || isMouseDragging)
  53054. {
  53055. g.fillAll (Colour (0x190000ff));
  53056. alpha = 1.0f;
  53057. }
  53058. const float cx = w * 0.5f;
  53059. const float cy = h * 0.5f;
  53060. const float cr = jmin (w, h) * 0.4f;
  53061. g.setGradientFill (ColourGradient (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  53062. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  53063. true));
  53064. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  53065. }
  53066. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  53067. const String& text,
  53068. const Justification& position,
  53069. GroupComponent& group)
  53070. {
  53071. const float textH = 15.0f;
  53072. const float indent = 3.0f;
  53073. const float textEdgeGap = 4.0f;
  53074. float cs = 5.0f;
  53075. Font f (textH);
  53076. Path p;
  53077. float x = indent;
  53078. float y = f.getAscent() - 3.0f;
  53079. float w = jmax (0.0f, width - x * 2.0f);
  53080. float h = jmax (0.0f, height - y - indent);
  53081. cs = jmin (cs, w * 0.5f, h * 0.5f);
  53082. const float cs2 = 2.0f * cs;
  53083. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  53084. float textX = cs + textEdgeGap;
  53085. if (position.testFlags (Justification::horizontallyCentred))
  53086. textX = cs + (w - cs2 - textW) * 0.5f;
  53087. else if (position.testFlags (Justification::right))
  53088. textX = w - cs - textW - textEdgeGap;
  53089. p.startNewSubPath (x + textX + textW, y);
  53090. p.lineTo (x + w - cs, y);
  53091. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  53092. p.lineTo (x + w, y + h - cs);
  53093. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  53094. p.lineTo (x + cs, y + h);
  53095. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  53096. p.lineTo (x, y + cs);
  53097. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  53098. p.lineTo (x + textX, y);
  53099. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  53100. g.setColour (group.findColour (GroupComponent::outlineColourId)
  53101. .withMultipliedAlpha (alpha));
  53102. g.strokePath (p, PathStrokeType (2.0f));
  53103. g.setColour (group.findColour (GroupComponent::textColourId)
  53104. .withMultipliedAlpha (alpha));
  53105. g.setFont (f);
  53106. g.drawText (text,
  53107. roundToInt (x + textX), 0,
  53108. roundToInt (textW),
  53109. roundToInt (textH),
  53110. Justification::centred, true);
  53111. }
  53112. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  53113. {
  53114. return 1 + tabDepth / 3;
  53115. }
  53116. int LookAndFeel::getTabButtonSpaceAroundImage()
  53117. {
  53118. return 4;
  53119. }
  53120. void LookAndFeel::createTabButtonShape (Path& p,
  53121. int width, int height,
  53122. int /*tabIndex*/,
  53123. const String& /*text*/,
  53124. Button& /*button*/,
  53125. TabbedButtonBar::Orientation orientation,
  53126. const bool /*isMouseOver*/,
  53127. const bool /*isMouseDown*/,
  53128. const bool /*isFrontTab*/)
  53129. {
  53130. const float w = (float) width;
  53131. const float h = (float) height;
  53132. float length = w;
  53133. float depth = h;
  53134. if (orientation == TabbedButtonBar::TabsAtLeft
  53135. || orientation == TabbedButtonBar::TabsAtRight)
  53136. {
  53137. swapVariables (length, depth);
  53138. }
  53139. const float indent = (float) getTabButtonOverlap ((int) depth);
  53140. const float overhang = 4.0f;
  53141. if (orientation == TabbedButtonBar::TabsAtLeft)
  53142. {
  53143. p.startNewSubPath (w, 0.0f);
  53144. p.lineTo (0.0f, indent);
  53145. p.lineTo (0.0f, h - indent);
  53146. p.lineTo (w, h);
  53147. p.lineTo (w + overhang, h + overhang);
  53148. p.lineTo (w + overhang, -overhang);
  53149. }
  53150. else if (orientation == TabbedButtonBar::TabsAtRight)
  53151. {
  53152. p.startNewSubPath (0.0f, 0.0f);
  53153. p.lineTo (w, indent);
  53154. p.lineTo (w, h - indent);
  53155. p.lineTo (0.0f, h);
  53156. p.lineTo (-overhang, h + overhang);
  53157. p.lineTo (-overhang, -overhang);
  53158. }
  53159. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53160. {
  53161. p.startNewSubPath (0.0f, 0.0f);
  53162. p.lineTo (indent, h);
  53163. p.lineTo (w - indent, h);
  53164. p.lineTo (w, 0.0f);
  53165. p.lineTo (w + overhang, -overhang);
  53166. p.lineTo (-overhang, -overhang);
  53167. }
  53168. else
  53169. {
  53170. p.startNewSubPath (0.0f, h);
  53171. p.lineTo (indent, 0.0f);
  53172. p.lineTo (w - indent, 0.0f);
  53173. p.lineTo (w, h);
  53174. p.lineTo (w + overhang, h + overhang);
  53175. p.lineTo (-overhang, h + overhang);
  53176. }
  53177. p.closeSubPath();
  53178. p = p.createPathWithRoundedCorners (3.0f);
  53179. }
  53180. void LookAndFeel::fillTabButtonShape (Graphics& g,
  53181. const Path& path,
  53182. const Colour& preferredColour,
  53183. int /*tabIndex*/,
  53184. const String& /*text*/,
  53185. Button& button,
  53186. TabbedButtonBar::Orientation /*orientation*/,
  53187. const bool /*isMouseOver*/,
  53188. const bool /*isMouseDown*/,
  53189. const bool isFrontTab)
  53190. {
  53191. g.setColour (isFrontTab ? preferredColour
  53192. : preferredColour.withMultipliedAlpha (0.9f));
  53193. g.fillPath (path);
  53194. g.setColour (button.findColour (isFrontTab ? TabbedButtonBar::frontOutlineColourId
  53195. : TabbedButtonBar::tabOutlineColourId, false)
  53196. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  53197. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  53198. }
  53199. void LookAndFeel::drawTabButtonText (Graphics& g,
  53200. int x, int y, int w, int h,
  53201. const Colour& preferredBackgroundColour,
  53202. int /*tabIndex*/,
  53203. const String& text,
  53204. Button& button,
  53205. TabbedButtonBar::Orientation orientation,
  53206. const bool isMouseOver,
  53207. const bool isMouseDown,
  53208. const bool isFrontTab)
  53209. {
  53210. int length = w;
  53211. int depth = h;
  53212. if (orientation == TabbedButtonBar::TabsAtLeft
  53213. || orientation == TabbedButtonBar::TabsAtRight)
  53214. {
  53215. swapVariables (length, depth);
  53216. }
  53217. Font font (depth * 0.6f);
  53218. font.setUnderline (button.hasKeyboardFocus (false));
  53219. GlyphArrangement textLayout;
  53220. textLayout.addFittedText (font, text.trim(),
  53221. 0.0f, 0.0f, (float) length, (float) depth,
  53222. Justification::centred,
  53223. jmax (1, depth / 12));
  53224. AffineTransform transform;
  53225. if (orientation == TabbedButtonBar::TabsAtLeft)
  53226. {
  53227. transform = transform.rotated (float_Pi * -0.5f)
  53228. .translated ((float) x, (float) (y + h));
  53229. }
  53230. else if (orientation == TabbedButtonBar::TabsAtRight)
  53231. {
  53232. transform = transform.rotated (float_Pi * 0.5f)
  53233. .translated ((float) (x + w), (float) y);
  53234. }
  53235. else
  53236. {
  53237. transform = transform.translated ((float) x, (float) y);
  53238. }
  53239. if (isFrontTab && (button.isColourSpecified (TabbedButtonBar::frontTextColourId) || isColourSpecified (TabbedButtonBar::frontTextColourId)))
  53240. g.setColour (findColour (TabbedButtonBar::frontTextColourId));
  53241. else if (button.isColourSpecified (TabbedButtonBar::tabTextColourId) || isColourSpecified (TabbedButtonBar::tabTextColourId))
  53242. g.setColour (findColour (TabbedButtonBar::tabTextColourId));
  53243. else
  53244. g.setColour (preferredBackgroundColour.contrasting());
  53245. if (! (isMouseOver || isMouseDown))
  53246. g.setOpacity (0.8f);
  53247. if (! button.isEnabled())
  53248. g.setOpacity (0.3f);
  53249. textLayout.draw (g, transform);
  53250. }
  53251. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  53252. const String& text,
  53253. int tabDepth,
  53254. Button&)
  53255. {
  53256. Font f (tabDepth * 0.6f);
  53257. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  53258. }
  53259. void LookAndFeel::drawTabButton (Graphics& g,
  53260. int w, int h,
  53261. const Colour& preferredColour,
  53262. int tabIndex,
  53263. const String& text,
  53264. Button& button,
  53265. TabbedButtonBar::Orientation orientation,
  53266. const bool isMouseOver,
  53267. const bool isMouseDown,
  53268. const bool isFrontTab)
  53269. {
  53270. int length = w;
  53271. int depth = h;
  53272. if (orientation == TabbedButtonBar::TabsAtLeft
  53273. || orientation == TabbedButtonBar::TabsAtRight)
  53274. {
  53275. swapVariables (length, depth);
  53276. }
  53277. Path tabShape;
  53278. createTabButtonShape (tabShape, w, h,
  53279. tabIndex, text, button, orientation,
  53280. isMouseOver, isMouseDown, isFrontTab);
  53281. fillTabButtonShape (g, tabShape, preferredColour,
  53282. tabIndex, text, button, orientation,
  53283. isMouseOver, isMouseDown, isFrontTab);
  53284. const int indent = getTabButtonOverlap (depth);
  53285. int x = 0, y = 0;
  53286. if (orientation == TabbedButtonBar::TabsAtLeft
  53287. || orientation == TabbedButtonBar::TabsAtRight)
  53288. {
  53289. y += indent;
  53290. h -= indent * 2;
  53291. }
  53292. else
  53293. {
  53294. x += indent;
  53295. w -= indent * 2;
  53296. }
  53297. drawTabButtonText (g, x, y, w, h, preferredColour,
  53298. tabIndex, text, button, orientation,
  53299. isMouseOver, isMouseDown, isFrontTab);
  53300. }
  53301. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  53302. int w, int h,
  53303. TabbedButtonBar& tabBar,
  53304. TabbedButtonBar::Orientation orientation)
  53305. {
  53306. const float shadowSize = 0.2f;
  53307. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  53308. Rectangle<int> shadowRect;
  53309. if (orientation == TabbedButtonBar::TabsAtLeft)
  53310. {
  53311. x1 = (float) w;
  53312. x2 = w * (1.0f - shadowSize);
  53313. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  53314. }
  53315. else if (orientation == TabbedButtonBar::TabsAtRight)
  53316. {
  53317. x2 = w * shadowSize;
  53318. shadowRect.setBounds (0, 0, (int) x2, h);
  53319. }
  53320. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53321. {
  53322. y2 = h * shadowSize;
  53323. shadowRect.setBounds (0, 0, w, (int) y2);
  53324. }
  53325. else
  53326. {
  53327. y1 = (float) h;
  53328. y2 = h * (1.0f - shadowSize);
  53329. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  53330. }
  53331. g.setGradientFill (ColourGradient (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  53332. Colours::transparentBlack, x2, y2, false));
  53333. shadowRect.expand (2, 2);
  53334. g.fillRect (shadowRect);
  53335. g.setColour (Colour (0x80000000));
  53336. if (orientation == TabbedButtonBar::TabsAtLeft)
  53337. {
  53338. g.fillRect (w - 1, 0, 1, h);
  53339. }
  53340. else if (orientation == TabbedButtonBar::TabsAtRight)
  53341. {
  53342. g.fillRect (0, 0, 1, h);
  53343. }
  53344. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53345. {
  53346. g.fillRect (0, 0, w, 1);
  53347. }
  53348. else
  53349. {
  53350. g.fillRect (0, h - 1, w, 1);
  53351. }
  53352. }
  53353. Button* LookAndFeel::createTabBarExtrasButton()
  53354. {
  53355. const float thickness = 7.0f;
  53356. const float indent = 22.0f;
  53357. Path p;
  53358. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  53359. DrawablePath ellipse;
  53360. ellipse.setPath (p);
  53361. ellipse.setFill (Colour (0x99ffffff));
  53362. p.clear();
  53363. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  53364. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  53365. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  53366. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  53367. p.setUsingNonZeroWinding (false);
  53368. DrawablePath dp;
  53369. dp.setPath (p);
  53370. dp.setFill (Colour (0x59000000));
  53371. DrawableComposite normalImage;
  53372. normalImage.insertDrawable (ellipse);
  53373. normalImage.insertDrawable (dp);
  53374. dp.setFill (Colour (0xcc000000));
  53375. DrawableComposite overImage;
  53376. overImage.insertDrawable (ellipse);
  53377. overImage.insertDrawable (dp);
  53378. DrawableButton* db = new DrawableButton ("tabs", DrawableButton::ImageFitted);
  53379. db->setImages (&normalImage, &overImage, 0);
  53380. return db;
  53381. }
  53382. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  53383. {
  53384. g.fillAll (Colours::white);
  53385. const int w = header.getWidth();
  53386. const int h = header.getHeight();
  53387. g.setGradientFill (ColourGradient (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  53388. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  53389. false));
  53390. g.fillRect (0, h / 2, w, h);
  53391. g.setColour (Colour (0x33000000));
  53392. g.fillRect (0, h - 1, w, 1);
  53393. for (int i = header.getNumColumns (true); --i >= 0;)
  53394. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  53395. }
  53396. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  53397. int width, int height,
  53398. bool isMouseOver, bool isMouseDown,
  53399. int columnFlags)
  53400. {
  53401. if (isMouseDown)
  53402. g.fillAll (Colour (0x8899aadd));
  53403. else if (isMouseOver)
  53404. g.fillAll (Colour (0x5599aadd));
  53405. int rightOfText = width - 4;
  53406. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  53407. {
  53408. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  53409. const float bottom = height - top;
  53410. const float w = height * 0.5f;
  53411. const float x = rightOfText - (w * 1.25f);
  53412. rightOfText = (int) x;
  53413. Path sortArrow;
  53414. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  53415. g.setColour (Colour (0x99000000));
  53416. g.fillPath (sortArrow);
  53417. }
  53418. g.setColour (Colours::black);
  53419. g.setFont (height * 0.5f, Font::bold);
  53420. const int textX = 4;
  53421. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  53422. }
  53423. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  53424. {
  53425. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  53426. g.setGradientFill (ColourGradient (background, 0.0f, 0.0f,
  53427. background.darker (0.1f),
  53428. toolbar.isVertical() ? w - 1.0f : 0.0f,
  53429. toolbar.isVertical() ? 0.0f : h - 1.0f,
  53430. false));
  53431. g.fillAll();
  53432. }
  53433. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  53434. {
  53435. return createTabBarExtrasButton();
  53436. }
  53437. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  53438. bool isMouseOver, bool isMouseDown,
  53439. ToolbarItemComponent& component)
  53440. {
  53441. if (isMouseDown)
  53442. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  53443. else if (isMouseOver)
  53444. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  53445. }
  53446. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  53447. const String& text, ToolbarItemComponent& component)
  53448. {
  53449. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  53450. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  53451. const float fontHeight = jmin (14.0f, height * 0.85f);
  53452. g.setFont (fontHeight);
  53453. g.drawFittedText (text,
  53454. x, y, width, height,
  53455. Justification::centred,
  53456. jmax (1, height / (int) fontHeight));
  53457. }
  53458. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  53459. bool isOpen, int width, int height)
  53460. {
  53461. const int buttonSize = (height * 3) / 4;
  53462. const int buttonIndent = (height - buttonSize) / 2;
  53463. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen, false);
  53464. const int textX = buttonIndent * 2 + buttonSize + 2;
  53465. g.setColour (Colours::black);
  53466. g.setFont (height * 0.7f, Font::bold);
  53467. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  53468. }
  53469. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  53470. PropertyComponent&)
  53471. {
  53472. g.setColour (Colour (0x66ffffff));
  53473. g.fillRect (0, 0, width, height - 1);
  53474. }
  53475. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  53476. PropertyComponent& component)
  53477. {
  53478. g.setColour (Colours::black);
  53479. if (! component.isEnabled())
  53480. g.setOpacity (0.6f);
  53481. g.setFont (jmin (height, 24) * 0.65f);
  53482. const Rectangle<int> r (getPropertyComponentContentPosition (component));
  53483. g.drawFittedText (component.getName(),
  53484. 3, r.getY(), r.getX() - 5, r.getHeight(),
  53485. Justification::centredLeft, 2);
  53486. }
  53487. const Rectangle<int> LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  53488. {
  53489. return Rectangle<int> (component.getWidth() / 3, 1,
  53490. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  53491. }
  53492. void LookAndFeel::drawCallOutBoxBackground (CallOutBox& box, Graphics& g, const Path& path)
  53493. {
  53494. Image content (Image::ARGB, box.getWidth(), box.getHeight(), true);
  53495. {
  53496. Graphics g2 (content);
  53497. g2.setColour (Colour::greyLevel (0.23f).withAlpha (0.9f));
  53498. g2.fillPath (path);
  53499. g2.setColour (Colours::white.withAlpha (0.8f));
  53500. g2.strokePath (path, PathStrokeType (2.0f));
  53501. }
  53502. DropShadowEffect shadow;
  53503. shadow.setShadowProperties (5.0f, 0.4f, 0, 2);
  53504. shadow.applyEffect (content, g);
  53505. }
  53506. void LookAndFeel::createFileChooserHeaderText (const String& title,
  53507. const String& instructions,
  53508. GlyphArrangement& text,
  53509. int width)
  53510. {
  53511. text.clear();
  53512. text.addJustifiedText (Font (17.0f, Font::bold), title,
  53513. 8.0f, 22.0f, width - 16.0f,
  53514. Justification::centred);
  53515. text.addJustifiedText (Font (14.0f), instructions,
  53516. 8.0f, 24.0f + 16.0f, width - 16.0f,
  53517. Justification::centred);
  53518. }
  53519. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  53520. const String& filename, Image* icon,
  53521. const String& fileSizeDescription,
  53522. const String& fileTimeDescription,
  53523. const bool isDirectory,
  53524. const bool isItemSelected,
  53525. const int /*itemIndex*/)
  53526. {
  53527. if (isItemSelected)
  53528. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  53529. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  53530. g.setFont (height * 0.7f);
  53531. Image im;
  53532. if (icon != 0)
  53533. im = *icon;
  53534. if (im.isNull())
  53535. im = isDirectory ? getDefaultFolderImage()
  53536. : getDefaultDocumentFileImage();
  53537. const int x = 32;
  53538. if (im.isValid())
  53539. {
  53540. g.drawImageWithin (im, 2, 2, x - 4, height - 4,
  53541. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  53542. false);
  53543. }
  53544. if (width > 450 && ! isDirectory)
  53545. {
  53546. const int sizeX = roundToInt (width * 0.7f);
  53547. const int dateX = roundToInt (width * 0.8f);
  53548. g.drawFittedText (filename,
  53549. x, 0, sizeX - x, height,
  53550. Justification::centredLeft, 1);
  53551. g.setFont (height * 0.5f);
  53552. g.setColour (Colours::darkgrey);
  53553. if (! isDirectory)
  53554. {
  53555. g.drawFittedText (fileSizeDescription,
  53556. sizeX, 0, dateX - sizeX - 8, height,
  53557. Justification::centredRight, 1);
  53558. g.drawFittedText (fileTimeDescription,
  53559. dateX, 0, width - 8 - dateX, height,
  53560. Justification::centredRight, 1);
  53561. }
  53562. }
  53563. else
  53564. {
  53565. g.drawFittedText (filename,
  53566. x, 0, width - x, height,
  53567. Justification::centredLeft, 1);
  53568. }
  53569. }
  53570. Button* LookAndFeel::createFileBrowserGoUpButton()
  53571. {
  53572. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  53573. Path arrowPath;
  53574. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  53575. DrawablePath arrowImage;
  53576. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  53577. arrowImage.setPath (arrowPath);
  53578. goUpButton->setImages (&arrowImage);
  53579. return goUpButton;
  53580. }
  53581. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  53582. DirectoryContentsDisplayComponent* fileListComponent,
  53583. FilePreviewComponent* previewComp,
  53584. ComboBox* currentPathBox,
  53585. TextEditor* filenameBox,
  53586. Button* goUpButton)
  53587. {
  53588. const int x = 8;
  53589. int w = browserComp.getWidth() - x - x;
  53590. if (previewComp != 0)
  53591. {
  53592. const int previewWidth = w / 3;
  53593. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  53594. w -= previewWidth + 4;
  53595. }
  53596. int y = 4;
  53597. const int controlsHeight = 22;
  53598. const int bottomSectionHeight = controlsHeight + 8;
  53599. const int upButtonWidth = 50;
  53600. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  53601. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  53602. y += controlsHeight + 4;
  53603. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  53604. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  53605. y = listAsComp->getBottom() + 4;
  53606. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  53607. }
  53608. const Image LookAndFeel::getDefaultFolderImage()
  53609. {
  53610. 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,
  53611. 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,
  53612. 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,
  53613. 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,
  53614. 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,
  53615. 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,
  53616. 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,
  53617. 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,
  53618. 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,
  53619. 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,
  53620. 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,
  53621. 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,
  53622. 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,
  53623. 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,
  53624. 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,
  53625. 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,
  53626. 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,
  53627. 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,
  53628. 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,
  53629. 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,
  53630. 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,
  53631. 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,
  53632. 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,
  53633. 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,
  53634. 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,
  53635. 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,
  53636. 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,
  53637. 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,
  53638. 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,
  53639. 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,
  53640. 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,
  53641. 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,
  53642. 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,
  53643. 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,
  53644. 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,
  53645. 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,
  53646. 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,
  53647. 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,
  53648. 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,
  53649. 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,
  53650. 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,
  53651. 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,
  53652. 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,
  53653. 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};
  53654. return ImageCache::getFromMemory (foldericon_png, sizeof (foldericon_png));
  53655. }
  53656. const Image LookAndFeel::getDefaultDocumentFileImage()
  53657. {
  53658. 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,
  53659. 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,
  53660. 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,
  53661. 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,
  53662. 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,
  53663. 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,
  53664. 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,
  53665. 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,
  53666. 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,
  53667. 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,
  53668. 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,
  53669. 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,
  53670. 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,
  53671. 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,
  53672. 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,
  53673. 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,
  53674. 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,
  53675. 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,
  53676. 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,
  53677. 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,
  53678. 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,
  53679. 174,66,96,130,0,0};
  53680. return ImageCache::getFromMemory (fileicon_png, sizeof (fileicon_png));
  53681. }
  53682. void LookAndFeel::playAlertSound()
  53683. {
  53684. PlatformUtilities::beep();
  53685. }
  53686. void LookAndFeel::drawLevelMeter (Graphics& g, int width, int height, float level)
  53687. {
  53688. g.setColour (Colours::white.withAlpha (0.7f));
  53689. g.fillRoundedRectangle (0.0f, 0.0f, (float) width, (float) height, 3.0f);
  53690. g.setColour (Colours::black.withAlpha (0.2f));
  53691. g.drawRoundedRectangle (1.0f, 1.0f, width - 2.0f, height - 2.0f, 3.0f, 1.0f);
  53692. const int totalBlocks = 7;
  53693. const int numBlocks = roundToInt (totalBlocks * level);
  53694. const float w = (width - 6.0f) / (float) totalBlocks;
  53695. for (int i = 0; i < totalBlocks; ++i)
  53696. {
  53697. if (i >= numBlocks)
  53698. g.setColour (Colours::lightblue.withAlpha (0.6f));
  53699. else
  53700. g.setColour (i < totalBlocks - 1 ? Colours::blue.withAlpha (0.5f)
  53701. : Colours::red);
  53702. g.fillRoundedRectangle (3.0f + i * w + w * 0.1f, 3.0f, w * 0.8f, height - 6.0f, w * 0.4f);
  53703. }
  53704. }
  53705. void LookAndFeel::drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription)
  53706. {
  53707. const Colour textColour (button.findColour (KeyMappingEditorComponent::textColourId, true));
  53708. if (keyDescription.isNotEmpty())
  53709. {
  53710. if (button.isEnabled())
  53711. {
  53712. const float alpha = button.isDown() ? 0.3f : (button.isOver() ? 0.15f : 0.08f);
  53713. g.fillAll (textColour.withAlpha (alpha));
  53714. g.setOpacity (0.3f);
  53715. g.drawBevel (0, 0, width, height, 2);
  53716. }
  53717. g.setColour (textColour);
  53718. g.setFont (height * 0.6f);
  53719. g.drawFittedText (keyDescription,
  53720. 3, 0, width - 6, height,
  53721. Justification::centred, 1);
  53722. }
  53723. else
  53724. {
  53725. const float thickness = 7.0f;
  53726. const float indent = 22.0f;
  53727. Path p;
  53728. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  53729. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  53730. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  53731. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  53732. p.setUsingNonZeroWinding (false);
  53733. g.setColour (textColour.withAlpha (button.isDown() ? 0.7f : (button.isOver() ? 0.5f : 0.3f)));
  53734. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, width - 4.0f, height - 4.0f, true));
  53735. }
  53736. if (button.hasKeyboardFocus (false))
  53737. {
  53738. g.setColour (textColour.withAlpha (0.4f));
  53739. g.drawRect (0, 0, width, height);
  53740. }
  53741. }
  53742. static void createRoundedPath (Path& p,
  53743. const float x, const float y,
  53744. const float w, const float h,
  53745. const float cs,
  53746. const bool curveTopLeft, const bool curveTopRight,
  53747. const bool curveBottomLeft, const bool curveBottomRight) throw()
  53748. {
  53749. const float cs2 = 2.0f * cs;
  53750. if (curveTopLeft)
  53751. {
  53752. p.startNewSubPath (x, y + cs);
  53753. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  53754. }
  53755. else
  53756. {
  53757. p.startNewSubPath (x, y);
  53758. }
  53759. if (curveTopRight)
  53760. {
  53761. p.lineTo (x + w - cs, y);
  53762. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  53763. }
  53764. else
  53765. {
  53766. p.lineTo (x + w, y);
  53767. }
  53768. if (curveBottomRight)
  53769. {
  53770. p.lineTo (x + w, y + h - cs);
  53771. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  53772. }
  53773. else
  53774. {
  53775. p.lineTo (x + w, y + h);
  53776. }
  53777. if (curveBottomLeft)
  53778. {
  53779. p.lineTo (x + cs, y + h);
  53780. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  53781. }
  53782. else
  53783. {
  53784. p.lineTo (x, y + h);
  53785. }
  53786. p.closeSubPath();
  53787. }
  53788. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  53789. float x, float y, float w, float h,
  53790. float maxCornerSize,
  53791. const Colour& baseColour,
  53792. const float strokeWidth,
  53793. const bool flatOnLeft,
  53794. const bool flatOnRight,
  53795. const bool flatOnTop,
  53796. const bool flatOnBottom) throw()
  53797. {
  53798. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  53799. return;
  53800. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  53801. Path outline;
  53802. createRoundedPath (outline, x, y, w, h, cs,
  53803. ! (flatOnLeft || flatOnTop),
  53804. ! (flatOnRight || flatOnTop),
  53805. ! (flatOnLeft || flatOnBottom),
  53806. ! (flatOnRight || flatOnBottom));
  53807. ColourGradient cg (baseColour, 0.0f, y,
  53808. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  53809. false);
  53810. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  53811. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  53812. g.setGradientFill (cg);
  53813. g.fillPath (outline);
  53814. g.setColour (Colour (0x80000000));
  53815. g.strokePath (outline, PathStrokeType (strokeWidth));
  53816. }
  53817. void LookAndFeel::drawGlassSphere (Graphics& g,
  53818. const float x, const float y,
  53819. const float diameter,
  53820. const Colour& colour,
  53821. const float outlineThickness) throw()
  53822. {
  53823. if (diameter <= outlineThickness)
  53824. return;
  53825. Path p;
  53826. p.addEllipse (x, y, diameter, diameter);
  53827. {
  53828. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  53829. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  53830. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  53831. g.setGradientFill (cg);
  53832. g.fillPath (p);
  53833. }
  53834. g.setGradientFill (ColourGradient (Colours::white, 0, y + diameter * 0.06f,
  53835. Colours::transparentWhite, 0, y + diameter * 0.3f, false));
  53836. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  53837. ColourGradient cg (Colours::transparentBlack,
  53838. x + diameter * 0.5f, y + diameter * 0.5f,
  53839. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  53840. x, y + diameter * 0.5f, true);
  53841. cg.addColour (0.7, Colours::transparentBlack);
  53842. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  53843. g.setGradientFill (cg);
  53844. g.fillPath (p);
  53845. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  53846. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  53847. }
  53848. void LookAndFeel::drawGlassPointer (Graphics& g,
  53849. const float x, const float y,
  53850. const float diameter,
  53851. const Colour& colour, const float outlineThickness,
  53852. const int direction) throw()
  53853. {
  53854. if (diameter <= outlineThickness)
  53855. return;
  53856. Path p;
  53857. p.startNewSubPath (x + diameter * 0.5f, y);
  53858. p.lineTo (x + diameter, y + diameter * 0.6f);
  53859. p.lineTo (x + diameter, y + diameter);
  53860. p.lineTo (x, y + diameter);
  53861. p.lineTo (x, y + diameter * 0.6f);
  53862. p.closeSubPath();
  53863. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  53864. {
  53865. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  53866. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  53867. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  53868. g.setGradientFill (cg);
  53869. g.fillPath (p);
  53870. }
  53871. ColourGradient cg (Colours::transparentBlack,
  53872. x + diameter * 0.5f, y + diameter * 0.5f,
  53873. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  53874. x - diameter * 0.2f, y + diameter * 0.5f, true);
  53875. cg.addColour (0.5, Colours::transparentBlack);
  53876. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  53877. g.setGradientFill (cg);
  53878. g.fillPath (p);
  53879. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  53880. g.strokePath (p, PathStrokeType (outlineThickness));
  53881. }
  53882. void LookAndFeel::drawGlassLozenge (Graphics& g,
  53883. const float x, const float y,
  53884. const float width, const float height,
  53885. const Colour& colour,
  53886. const float outlineThickness,
  53887. const float cornerSize,
  53888. const bool flatOnLeft,
  53889. const bool flatOnRight,
  53890. const bool flatOnTop,
  53891. const bool flatOnBottom) throw()
  53892. {
  53893. if (width <= outlineThickness || height <= outlineThickness)
  53894. return;
  53895. const int intX = (int) x;
  53896. const int intY = (int) y;
  53897. const int intW = (int) width;
  53898. const int intH = (int) height;
  53899. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  53900. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  53901. const int intEdge = (int) edgeBlurRadius;
  53902. Path outline;
  53903. createRoundedPath (outline, x, y, width, height, cs,
  53904. ! (flatOnLeft || flatOnTop),
  53905. ! (flatOnRight || flatOnTop),
  53906. ! (flatOnLeft || flatOnBottom),
  53907. ! (flatOnRight || flatOnBottom));
  53908. {
  53909. ColourGradient cg (colour.darker (0.2f), 0, y,
  53910. colour.darker (0.2f), 0, y + height, false);
  53911. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  53912. cg.addColour (0.4, colour);
  53913. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  53914. g.setGradientFill (cg);
  53915. g.fillPath (outline);
  53916. }
  53917. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  53918. colour.darker (0.2f), x, y + height * 0.5f, true);
  53919. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  53920. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  53921. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  53922. {
  53923. g.saveState();
  53924. g.setGradientFill (cg);
  53925. g.reduceClipRegion (intX, intY, intEdge, intH);
  53926. g.fillPath (outline);
  53927. g.restoreState();
  53928. }
  53929. if (! (flatOnRight || flatOnTop || flatOnBottom))
  53930. {
  53931. cg.point1.setX (x + width - edgeBlurRadius);
  53932. cg.point2.setX (x + width);
  53933. g.saveState();
  53934. g.setGradientFill (cg);
  53935. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  53936. g.fillPath (outline);
  53937. g.restoreState();
  53938. }
  53939. {
  53940. const float leftIndent = flatOnLeft ? 0.0f : cs * 0.4f;
  53941. const float rightIndent = flatOnRight ? 0.0f : cs * 0.4f;
  53942. Path highlight;
  53943. createRoundedPath (highlight,
  53944. x + leftIndent,
  53945. y + cs * 0.1f,
  53946. width - (leftIndent + rightIndent),
  53947. height * 0.4f, cs * 0.4f,
  53948. ! (flatOnLeft || flatOnTop),
  53949. ! (flatOnRight || flatOnTop),
  53950. ! (flatOnLeft || flatOnBottom),
  53951. ! (flatOnRight || flatOnBottom));
  53952. g.setGradientFill (ColourGradient (colour.brighter (10.0f), 0, y + height * 0.06f,
  53953. Colours::transparentWhite, 0, y + height * 0.4f, false));
  53954. g.fillPath (highlight);
  53955. }
  53956. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  53957. g.strokePath (outline, PathStrokeType (outlineThickness));
  53958. }
  53959. END_JUCE_NAMESPACE
  53960. /*** End of inlined file: juce_LookAndFeel.cpp ***/
  53961. /*** Start of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  53962. BEGIN_JUCE_NAMESPACE
  53963. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  53964. {
  53965. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  53966. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  53967. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  53968. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  53969. setColour (Slider::thumbColourId, Colours::white);
  53970. setColour (Slider::trackColourId, Colour (0x7f000000));
  53971. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  53972. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  53973. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  53974. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  53975. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  53976. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  53977. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  53978. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  53979. }
  53980. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  53981. {
  53982. }
  53983. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  53984. Button& button,
  53985. const Colour& backgroundColour,
  53986. bool isMouseOverButton,
  53987. bool isButtonDown)
  53988. {
  53989. const int width = button.getWidth();
  53990. const int height = button.getHeight();
  53991. const float indent = 2.0f;
  53992. const int cornerSize = jmin (roundToInt (width * 0.4f),
  53993. roundToInt (height * 0.4f));
  53994. Path p;
  53995. p.addRoundedRectangle (indent, indent,
  53996. width - indent * 2.0f,
  53997. height - indent * 2.0f,
  53998. (float) cornerSize);
  53999. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  54000. if (isMouseOverButton)
  54001. {
  54002. if (isButtonDown)
  54003. bc = bc.brighter();
  54004. else if (bc.getBrightness() > 0.5f)
  54005. bc = bc.darker (0.1f);
  54006. else
  54007. bc = bc.brighter (0.1f);
  54008. }
  54009. g.setColour (bc);
  54010. g.fillPath (p);
  54011. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  54012. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  54013. }
  54014. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  54015. Component& /*component*/,
  54016. float x, float y, float w, float h,
  54017. const bool ticked,
  54018. const bool isEnabled,
  54019. const bool /*isMouseOverButton*/,
  54020. const bool isButtonDown)
  54021. {
  54022. Path box;
  54023. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  54024. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  54025. : Colours::lightgrey.withAlpha (0.1f));
  54026. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f).translated (x, y));
  54027. g.fillPath (box, trans);
  54028. g.setColour (Colours::black.withAlpha (0.6f));
  54029. g.strokePath (box, PathStrokeType (0.9f), trans);
  54030. if (ticked)
  54031. {
  54032. Path tick;
  54033. tick.startNewSubPath (1.5f, 3.0f);
  54034. tick.lineTo (3.0f, 6.0f);
  54035. tick.lineTo (6.0f, 0.0f);
  54036. g.setColour (isEnabled ? Colours::black : Colours::grey);
  54037. g.strokePath (tick, PathStrokeType (2.5f), trans);
  54038. }
  54039. }
  54040. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  54041. ToggleButton& button,
  54042. bool isMouseOverButton,
  54043. bool isButtonDown)
  54044. {
  54045. if (button.hasKeyboardFocus (true))
  54046. {
  54047. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  54048. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  54049. }
  54050. const int tickWidth = jmin (20, button.getHeight() - 4);
  54051. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  54052. (float) tickWidth, (float) tickWidth,
  54053. button.getToggleState(),
  54054. button.isEnabled(),
  54055. isMouseOverButton,
  54056. isButtonDown);
  54057. g.setColour (button.findColour (ToggleButton::textColourId));
  54058. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  54059. if (! button.isEnabled())
  54060. g.setOpacity (0.5f);
  54061. const int textX = tickWidth + 5;
  54062. g.drawFittedText (button.getButtonText(),
  54063. textX, 4,
  54064. button.getWidth() - textX - 2, button.getHeight() - 8,
  54065. Justification::centredLeft, 10);
  54066. }
  54067. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  54068. int width, int height,
  54069. double progress, const String& textToShow)
  54070. {
  54071. if (progress < 0 || progress >= 1.0)
  54072. {
  54073. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  54074. }
  54075. else
  54076. {
  54077. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  54078. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  54079. g.fillAll (background);
  54080. g.setColour (foreground);
  54081. g.fillRect (1, 1,
  54082. jlimit (0, width - 2, roundToInt (progress * (width - 2))),
  54083. height - 2);
  54084. if (textToShow.isNotEmpty())
  54085. {
  54086. g.setColour (Colour::contrasting (background, foreground));
  54087. g.setFont (height * 0.6f);
  54088. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  54089. }
  54090. }
  54091. }
  54092. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  54093. ScrollBar& bar,
  54094. int width, int height,
  54095. int buttonDirection,
  54096. bool isScrollbarVertical,
  54097. bool isMouseOverButton,
  54098. bool isButtonDown)
  54099. {
  54100. if (isScrollbarVertical)
  54101. width -= 2;
  54102. else
  54103. height -= 2;
  54104. Path p;
  54105. if (buttonDirection == 0)
  54106. p.addTriangle (width * 0.5f, height * 0.2f,
  54107. width * 0.1f, height * 0.7f,
  54108. width * 0.9f, height * 0.7f);
  54109. else if (buttonDirection == 1)
  54110. p.addTriangle (width * 0.8f, height * 0.5f,
  54111. width * 0.3f, height * 0.1f,
  54112. width * 0.3f, height * 0.9f);
  54113. else if (buttonDirection == 2)
  54114. p.addTriangle (width * 0.5f, height * 0.8f,
  54115. width * 0.1f, height * 0.3f,
  54116. width * 0.9f, height * 0.3f);
  54117. else if (buttonDirection == 3)
  54118. p.addTriangle (width * 0.2f, height * 0.5f,
  54119. width * 0.7f, height * 0.1f,
  54120. width * 0.7f, height * 0.9f);
  54121. if (isButtonDown)
  54122. g.setColour (Colours::white);
  54123. else if (isMouseOverButton)
  54124. g.setColour (Colours::white.withAlpha (0.7f));
  54125. else
  54126. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  54127. g.fillPath (p);
  54128. g.setColour (Colours::black.withAlpha (0.5f));
  54129. g.strokePath (p, PathStrokeType (0.5f));
  54130. }
  54131. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  54132. ScrollBar& bar,
  54133. int x, int y,
  54134. int width, int height,
  54135. bool isScrollbarVertical,
  54136. int thumbStartPosition,
  54137. int thumbSize,
  54138. bool isMouseOver,
  54139. bool isMouseDown)
  54140. {
  54141. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  54142. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  54143. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  54144. if (thumbSize > 0.0f)
  54145. {
  54146. Rectangle<int> thumb;
  54147. if (isScrollbarVertical)
  54148. {
  54149. width -= 2;
  54150. g.fillRect (x + roundToInt (width * 0.35f), y,
  54151. roundToInt (width * 0.3f), height);
  54152. thumb.setBounds (x + 1, thumbStartPosition,
  54153. width - 2, thumbSize);
  54154. }
  54155. else
  54156. {
  54157. height -= 2;
  54158. g.fillRect (x, y + roundToInt (height * 0.35f),
  54159. width, roundToInt (height * 0.3f));
  54160. thumb.setBounds (thumbStartPosition, y + 1,
  54161. thumbSize, height - 2);
  54162. }
  54163. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  54164. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  54165. g.fillRect (thumb);
  54166. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  54167. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  54168. if (thumbSize > 16)
  54169. {
  54170. for (int i = 3; --i >= 0;)
  54171. {
  54172. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  54173. g.setColour (Colours::black.withAlpha (0.15f));
  54174. if (isScrollbarVertical)
  54175. {
  54176. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  54177. g.setColour (Colours::white.withAlpha (0.15f));
  54178. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  54179. }
  54180. else
  54181. {
  54182. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  54183. g.setColour (Colours::white.withAlpha (0.15f));
  54184. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  54185. }
  54186. }
  54187. }
  54188. }
  54189. }
  54190. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  54191. {
  54192. return &scrollbarShadow;
  54193. }
  54194. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  54195. {
  54196. g.fillAll (findColour (PopupMenu::backgroundColourId));
  54197. g.setColour (Colours::black.withAlpha (0.6f));
  54198. g.drawRect (0, 0, width, height);
  54199. }
  54200. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  54201. bool, MenuBarComponent& menuBar)
  54202. {
  54203. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  54204. }
  54205. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  54206. {
  54207. if (textEditor.isEnabled())
  54208. {
  54209. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  54210. g.drawRect (0, 0, width, height);
  54211. }
  54212. }
  54213. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  54214. const bool isButtonDown,
  54215. int buttonX, int buttonY,
  54216. int buttonW, int buttonH,
  54217. ComboBox& box)
  54218. {
  54219. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  54220. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  54221. : ComboBox::backgroundColourId));
  54222. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  54223. g.setColour (box.findColour (ComboBox::outlineColourId));
  54224. g.drawRect (0, 0, width, height);
  54225. const float arrowX = 0.2f;
  54226. const float arrowH = 0.3f;
  54227. if (box.isEnabled())
  54228. {
  54229. Path p;
  54230. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  54231. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  54232. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  54233. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  54234. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  54235. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  54236. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  54237. : ComboBox::buttonColourId));
  54238. g.fillPath (p);
  54239. }
  54240. }
  54241. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  54242. {
  54243. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  54244. f.setHorizontalScale (0.9f);
  54245. return f;
  54246. }
  54247. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  54248. {
  54249. Path p;
  54250. p.addTriangle (x1, y1, x2, y2, x3, y3);
  54251. g.setColour (fill);
  54252. g.fillPath (p);
  54253. g.setColour (outline);
  54254. g.strokePath (p, PathStrokeType (0.3f));
  54255. }
  54256. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  54257. int x, int y,
  54258. int w, int h,
  54259. float sliderPos,
  54260. float minSliderPos,
  54261. float maxSliderPos,
  54262. const Slider::SliderStyle style,
  54263. Slider& slider)
  54264. {
  54265. g.fillAll (slider.findColour (Slider::backgroundColourId));
  54266. if (style == Slider::LinearBar)
  54267. {
  54268. g.setColour (slider.findColour (Slider::thumbColourId));
  54269. g.fillRect (x, y, (int) sliderPos - x, h);
  54270. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  54271. g.drawRect (x, y, (int) sliderPos - x, h);
  54272. }
  54273. else
  54274. {
  54275. g.setColour (slider.findColour (Slider::trackColourId)
  54276. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  54277. if (slider.isHorizontal())
  54278. {
  54279. g.fillRect (x, y + roundToInt (h * 0.6f),
  54280. w, roundToInt (h * 0.2f));
  54281. }
  54282. else
  54283. {
  54284. g.fillRect (x + roundToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  54285. jmin (4, roundToInt (w * 0.2f)), h);
  54286. }
  54287. float alpha = 0.35f;
  54288. if (slider.isEnabled())
  54289. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  54290. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  54291. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  54292. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  54293. {
  54294. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  54295. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  54296. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  54297. fill, outline);
  54298. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  54299. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  54300. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  54301. fill, outline);
  54302. }
  54303. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  54304. {
  54305. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  54306. minSliderPos - 7.0f, y + h * 0.9f ,
  54307. minSliderPos, y + h * 0.9f,
  54308. fill, outline);
  54309. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  54310. maxSliderPos, y + h * 0.9f,
  54311. maxSliderPos + 7.0f, y + h * 0.9f,
  54312. fill, outline);
  54313. }
  54314. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  54315. {
  54316. drawTriangle (g, sliderPos, y + h * 0.9f,
  54317. sliderPos - 7.0f, y + h * 0.2f,
  54318. sliderPos + 7.0f, y + h * 0.2f,
  54319. fill, outline);
  54320. }
  54321. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  54322. {
  54323. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  54324. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  54325. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  54326. fill, outline);
  54327. }
  54328. }
  54329. }
  54330. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  54331. {
  54332. if (isIncrement)
  54333. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  54334. else
  54335. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  54336. }
  54337. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  54338. {
  54339. return &scrollbarShadow;
  54340. }
  54341. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  54342. {
  54343. return 8;
  54344. }
  54345. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  54346. int w, int h,
  54347. bool isMouseOver,
  54348. bool isMouseDragging)
  54349. {
  54350. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  54351. : Colours::darkgrey);
  54352. const float lineThickness = jmin (w, h) * 0.1f;
  54353. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  54354. {
  54355. g.drawLine (w * i,
  54356. h + 1.0f,
  54357. w + 1.0f,
  54358. h * i,
  54359. lineThickness);
  54360. }
  54361. }
  54362. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  54363. {
  54364. Path shape;
  54365. if (buttonType == DocumentWindow::closeButton)
  54366. {
  54367. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), 0.35f);
  54368. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), 0.35f);
  54369. ShapeButton* const b = new ShapeButton ("close",
  54370. Colour (0x7fff3333),
  54371. Colour (0xd7ff3333),
  54372. Colour (0xf7ff3333));
  54373. b->setShape (shape, true, true, true);
  54374. return b;
  54375. }
  54376. else if (buttonType == DocumentWindow::minimiseButton)
  54377. {
  54378. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  54379. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  54380. DrawablePath dp;
  54381. dp.setPath (shape);
  54382. dp.setFill (Colours::black.withAlpha (0.3f));
  54383. b->setImages (&dp);
  54384. return b;
  54385. }
  54386. else if (buttonType == DocumentWindow::maximiseButton)
  54387. {
  54388. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), 0.25f);
  54389. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  54390. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  54391. DrawablePath dp;
  54392. dp.setPath (shape);
  54393. dp.setFill (Colours::black.withAlpha (0.3f));
  54394. b->setImages (&dp);
  54395. return b;
  54396. }
  54397. jassertfalse;
  54398. return 0;
  54399. }
  54400. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  54401. int titleBarX,
  54402. int titleBarY,
  54403. int titleBarW,
  54404. int titleBarH,
  54405. Button* minimiseButton,
  54406. Button* maximiseButton,
  54407. Button* closeButton,
  54408. bool positionTitleBarButtonsOnLeft)
  54409. {
  54410. titleBarY += titleBarH / 8;
  54411. titleBarH -= titleBarH / 4;
  54412. const int buttonW = titleBarH;
  54413. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  54414. : titleBarX + titleBarW - buttonW - 4;
  54415. if (closeButton != 0)
  54416. {
  54417. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  54418. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  54419. : -(buttonW + buttonW / 5);
  54420. }
  54421. if (positionTitleBarButtonsOnLeft)
  54422. swapVariables (minimiseButton, maximiseButton);
  54423. if (maximiseButton != 0)
  54424. {
  54425. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  54426. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  54427. }
  54428. if (minimiseButton != 0)
  54429. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  54430. }
  54431. END_JUCE_NAMESPACE
  54432. /*** End of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  54433. /*** Start of inlined file: juce_MenuBarComponent.cpp ***/
  54434. BEGIN_JUCE_NAMESPACE
  54435. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  54436. : model (0),
  54437. itemUnderMouse (-1),
  54438. currentPopupIndex (-1),
  54439. topLevelIndexClicked (0),
  54440. lastMouseX (0),
  54441. lastMouseY (0)
  54442. {
  54443. setRepaintsOnMouseActivity (true);
  54444. setWantsKeyboardFocus (false);
  54445. setMouseClickGrabsKeyboardFocus (false);
  54446. setModel (model_);
  54447. }
  54448. MenuBarComponent::~MenuBarComponent()
  54449. {
  54450. setModel (0);
  54451. Desktop::getInstance().removeGlobalMouseListener (this);
  54452. }
  54453. MenuBarModel* MenuBarComponent::getModel() const throw()
  54454. {
  54455. return model;
  54456. }
  54457. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  54458. {
  54459. if (model != newModel)
  54460. {
  54461. if (model != 0)
  54462. model->removeListener (this);
  54463. model = newModel;
  54464. if (model != 0)
  54465. model->addListener (this);
  54466. repaint();
  54467. menuBarItemsChanged (0);
  54468. }
  54469. }
  54470. void MenuBarComponent::paint (Graphics& g)
  54471. {
  54472. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  54473. getLookAndFeel().drawMenuBarBackground (g,
  54474. getWidth(),
  54475. getHeight(),
  54476. isMouseOverBar,
  54477. *this);
  54478. if (model != 0)
  54479. {
  54480. for (int i = 0; i < menuNames.size(); ++i)
  54481. {
  54482. g.saveState();
  54483. g.setOrigin (xPositions [i], 0);
  54484. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  54485. getLookAndFeel().drawMenuBarItem (g,
  54486. xPositions[i + 1] - xPositions[i],
  54487. getHeight(),
  54488. i,
  54489. menuNames[i],
  54490. i == itemUnderMouse,
  54491. i == currentPopupIndex,
  54492. isMouseOverBar,
  54493. *this);
  54494. g.restoreState();
  54495. }
  54496. }
  54497. }
  54498. void MenuBarComponent::resized()
  54499. {
  54500. xPositions.clear();
  54501. int x = 2;
  54502. xPositions.add (x);
  54503. for (int i = 0; i < menuNames.size(); ++i)
  54504. {
  54505. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  54506. xPositions.add (x);
  54507. }
  54508. }
  54509. int MenuBarComponent::getItemAt (const int x, const int y)
  54510. {
  54511. for (int i = 0; i < xPositions.size(); ++i)
  54512. if (x >= xPositions[i] && x < xPositions[i + 1])
  54513. return reallyContains (x, y, true) ? i : -1;
  54514. return -1;
  54515. }
  54516. void MenuBarComponent::repaintMenuItem (int index)
  54517. {
  54518. if (((unsigned int) index) < (unsigned int) xPositions.size())
  54519. {
  54520. const int x1 = xPositions [index];
  54521. const int x2 = xPositions [index + 1];
  54522. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  54523. }
  54524. }
  54525. void MenuBarComponent::setItemUnderMouse (const int index)
  54526. {
  54527. if (itemUnderMouse != index)
  54528. {
  54529. repaintMenuItem (itemUnderMouse);
  54530. itemUnderMouse = index;
  54531. repaintMenuItem (itemUnderMouse);
  54532. }
  54533. }
  54534. void MenuBarComponent::setOpenItem (int index)
  54535. {
  54536. if (currentPopupIndex != index)
  54537. {
  54538. repaintMenuItem (currentPopupIndex);
  54539. currentPopupIndex = index;
  54540. repaintMenuItem (currentPopupIndex);
  54541. if (index >= 0)
  54542. Desktop::getInstance().addGlobalMouseListener (this);
  54543. else
  54544. Desktop::getInstance().removeGlobalMouseListener (this);
  54545. }
  54546. }
  54547. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  54548. {
  54549. setItemUnderMouse (getItemAt (x, y));
  54550. }
  54551. class MenuBarComponent::AsyncCallback : public ModalComponentManager::Callback
  54552. {
  54553. public:
  54554. AsyncCallback (MenuBarComponent* const bar_, const int topLevelIndex_)
  54555. : bar (bar_), topLevelIndex (topLevelIndex_)
  54556. {
  54557. }
  54558. ~AsyncCallback() {}
  54559. void modalStateFinished (int returnValue)
  54560. {
  54561. if (bar != 0)
  54562. bar->menuDismissed (topLevelIndex, returnValue);
  54563. }
  54564. private:
  54565. Component::SafePointer<MenuBarComponent> bar;
  54566. const int topLevelIndex;
  54567. AsyncCallback (const AsyncCallback&);
  54568. AsyncCallback& operator= (const AsyncCallback&);
  54569. };
  54570. void MenuBarComponent::showMenu (int index)
  54571. {
  54572. if (index != currentPopupIndex)
  54573. {
  54574. PopupMenu::dismissAllActiveMenus();
  54575. menuBarItemsChanged (0);
  54576. setOpenItem (index);
  54577. setItemUnderMouse (index);
  54578. if (index >= 0)
  54579. {
  54580. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  54581. menuNames [itemUnderMouse]));
  54582. if (m.lookAndFeel == 0)
  54583. m.setLookAndFeel (&getLookAndFeel());
  54584. const Rectangle<int> itemPos (xPositions [index], 0, xPositions [index + 1] - xPositions [index], getHeight());
  54585. m.showMenu (itemPos + getScreenPosition(),
  54586. 0, itemPos.getWidth(), 0, 0, true, this,
  54587. new AsyncCallback (this, index));
  54588. }
  54589. }
  54590. }
  54591. void MenuBarComponent::menuDismissed (int topLevelIndex, int itemId)
  54592. {
  54593. topLevelIndexClicked = topLevelIndex;
  54594. postCommandMessage (itemId);
  54595. }
  54596. void MenuBarComponent::handleCommandMessage (int commandId)
  54597. {
  54598. const Point<int> mousePos (getMouseXYRelative());
  54599. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  54600. if (! isCurrentlyBlockedByAnotherModalComponent())
  54601. setOpenItem (-1);
  54602. if (commandId != 0 && model != 0)
  54603. model->menuItemSelected (commandId, topLevelIndexClicked);
  54604. }
  54605. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  54606. {
  54607. if (e.eventComponent == this)
  54608. updateItemUnderMouse (e.x, e.y);
  54609. }
  54610. void MenuBarComponent::mouseExit (const MouseEvent& e)
  54611. {
  54612. if (e.eventComponent == this)
  54613. updateItemUnderMouse (e.x, e.y);
  54614. }
  54615. void MenuBarComponent::mouseDown (const MouseEvent& e)
  54616. {
  54617. if (currentPopupIndex < 0)
  54618. {
  54619. const MouseEvent e2 (e.getEventRelativeTo (this));
  54620. updateItemUnderMouse (e2.x, e2.y);
  54621. currentPopupIndex = -2;
  54622. showMenu (itemUnderMouse);
  54623. }
  54624. }
  54625. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  54626. {
  54627. const MouseEvent e2 (e.getEventRelativeTo (this));
  54628. const int item = getItemAt (e2.x, e2.y);
  54629. if (item >= 0)
  54630. showMenu (item);
  54631. }
  54632. void MenuBarComponent::mouseUp (const MouseEvent& e)
  54633. {
  54634. const MouseEvent e2 (e.getEventRelativeTo (this));
  54635. updateItemUnderMouse (e2.x, e2.y);
  54636. if (itemUnderMouse < 0 && getLocalBounds().contains (e2.x, e2.y))
  54637. {
  54638. setOpenItem (-1);
  54639. PopupMenu::dismissAllActiveMenus();
  54640. }
  54641. }
  54642. void MenuBarComponent::mouseMove (const MouseEvent& e)
  54643. {
  54644. const MouseEvent e2 (e.getEventRelativeTo (this));
  54645. if (lastMouseX != e2.x || lastMouseY != e2.y)
  54646. {
  54647. if (currentPopupIndex >= 0)
  54648. {
  54649. const int item = getItemAt (e2.x, e2.y);
  54650. if (item >= 0)
  54651. showMenu (item);
  54652. }
  54653. else
  54654. {
  54655. updateItemUnderMouse (e2.x, e2.y);
  54656. }
  54657. lastMouseX = e2.x;
  54658. lastMouseY = e2.y;
  54659. }
  54660. }
  54661. bool MenuBarComponent::keyPressed (const KeyPress& key)
  54662. {
  54663. bool used = false;
  54664. const int numMenus = menuNames.size();
  54665. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  54666. if (key.isKeyCode (KeyPress::leftKey))
  54667. {
  54668. showMenu ((currentIndex + numMenus - 1) % numMenus);
  54669. used = true;
  54670. }
  54671. else if (key.isKeyCode (KeyPress::rightKey))
  54672. {
  54673. showMenu ((currentIndex + 1) % numMenus);
  54674. used = true;
  54675. }
  54676. return used;
  54677. }
  54678. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  54679. {
  54680. StringArray newNames;
  54681. if (model != 0)
  54682. newNames = model->getMenuBarNames();
  54683. if (newNames != menuNames)
  54684. {
  54685. menuNames = newNames;
  54686. repaint();
  54687. resized();
  54688. }
  54689. }
  54690. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  54691. const ApplicationCommandTarget::InvocationInfo& info)
  54692. {
  54693. if (model == 0 || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  54694. return;
  54695. for (int i = 0; i < menuNames.size(); ++i)
  54696. {
  54697. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  54698. if (menu.containsCommandItem (info.commandID))
  54699. {
  54700. setItemUnderMouse (i);
  54701. startTimer (200);
  54702. break;
  54703. }
  54704. }
  54705. }
  54706. void MenuBarComponent::timerCallback()
  54707. {
  54708. stopTimer();
  54709. const Point<int> mousePos (getMouseXYRelative());
  54710. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  54711. }
  54712. END_JUCE_NAMESPACE
  54713. /*** End of inlined file: juce_MenuBarComponent.cpp ***/
  54714. /*** Start of inlined file: juce_MenuBarModel.cpp ***/
  54715. BEGIN_JUCE_NAMESPACE
  54716. MenuBarModel::MenuBarModel() throw()
  54717. : manager (0)
  54718. {
  54719. }
  54720. MenuBarModel::~MenuBarModel()
  54721. {
  54722. setApplicationCommandManagerToWatch (0);
  54723. }
  54724. void MenuBarModel::menuItemsChanged()
  54725. {
  54726. triggerAsyncUpdate();
  54727. }
  54728. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  54729. {
  54730. if (manager != newManager)
  54731. {
  54732. if (manager != 0)
  54733. manager->removeListener (this);
  54734. manager = newManager;
  54735. if (manager != 0)
  54736. manager->addListener (this);
  54737. }
  54738. }
  54739. void MenuBarModel::addListener (MenuBarModelListener* const newListener) throw()
  54740. {
  54741. listeners.add (newListener);
  54742. }
  54743. void MenuBarModel::removeListener (MenuBarModelListener* const listenerToRemove) throw()
  54744. {
  54745. // Trying to remove a listener that isn't on the list!
  54746. // If this assertion happens because this object is a dangling pointer, make sure you've not
  54747. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  54748. jassert (listeners.contains (listenerToRemove));
  54749. listeners.remove (listenerToRemove);
  54750. }
  54751. void MenuBarModel::handleAsyncUpdate()
  54752. {
  54753. listeners.call (&MenuBarModelListener::menuBarItemsChanged, this);
  54754. }
  54755. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  54756. {
  54757. listeners.call (&MenuBarModelListener::menuCommandInvoked, this, info);
  54758. }
  54759. void MenuBarModel::applicationCommandListChanged()
  54760. {
  54761. menuItemsChanged();
  54762. }
  54763. END_JUCE_NAMESPACE
  54764. /*** End of inlined file: juce_MenuBarModel.cpp ***/
  54765. /*** Start of inlined file: juce_PopupMenu.cpp ***/
  54766. BEGIN_JUCE_NAMESPACE
  54767. class PopupMenu::Item
  54768. {
  54769. public:
  54770. Item()
  54771. : itemId (0), active (true), isSeparator (true), isTicked (false),
  54772. usesColour (false), customComp (0), commandManager (0)
  54773. {
  54774. }
  54775. Item (const int itemId_,
  54776. const String& text_,
  54777. const bool active_,
  54778. const bool isTicked_,
  54779. const Image& im,
  54780. const Colour& textColour_,
  54781. const bool usesColour_,
  54782. PopupMenuCustomComponent* const customComp_,
  54783. const PopupMenu* const subMenu_,
  54784. ApplicationCommandManager* const commandManager_)
  54785. : itemId (itemId_), text (text_), textColour (textColour_),
  54786. active (active_), isSeparator (false), isTicked (isTicked_),
  54787. usesColour (usesColour_), image (im), customComp (customComp_),
  54788. commandManager (commandManager_)
  54789. {
  54790. if (subMenu_ != 0)
  54791. subMenu = new PopupMenu (*subMenu_);
  54792. if (commandManager_ != 0 && itemId_ != 0)
  54793. {
  54794. String shortcutKey;
  54795. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  54796. ->getKeyPressesAssignedToCommand (itemId_));
  54797. for (int i = 0; i < keyPresses.size(); ++i)
  54798. {
  54799. const String key (keyPresses.getReference(i).getTextDescription());
  54800. if (shortcutKey.isNotEmpty())
  54801. shortcutKey << ", ";
  54802. if (key.length() == 1)
  54803. shortcutKey << "shortcut: '" << key << '\'';
  54804. else
  54805. shortcutKey << key;
  54806. }
  54807. shortcutKey = shortcutKey.trim();
  54808. if (shortcutKey.isNotEmpty())
  54809. text << "<end>" << shortcutKey;
  54810. }
  54811. }
  54812. Item (const Item& other)
  54813. : itemId (other.itemId),
  54814. text (other.text),
  54815. textColour (other.textColour),
  54816. active (other.active),
  54817. isSeparator (other.isSeparator),
  54818. isTicked (other.isTicked),
  54819. usesColour (other.usesColour),
  54820. image (other.image),
  54821. customComp (other.customComp),
  54822. commandManager (other.commandManager)
  54823. {
  54824. if (other.subMenu != 0)
  54825. subMenu = new PopupMenu (*(other.subMenu));
  54826. }
  54827. ~Item()
  54828. {
  54829. customComp = 0;
  54830. }
  54831. bool canBeTriggered() const throw()
  54832. {
  54833. return active && ! (isSeparator || (subMenu != 0));
  54834. }
  54835. bool hasActiveSubMenu() const throw()
  54836. {
  54837. return active && (subMenu != 0);
  54838. }
  54839. const int itemId;
  54840. String text;
  54841. const Colour textColour;
  54842. const bool active, isSeparator, isTicked, usesColour;
  54843. Image image;
  54844. ReferenceCountedObjectPtr <PopupMenuCustomComponent> customComp;
  54845. ScopedPointer <PopupMenu> subMenu;
  54846. ApplicationCommandManager* const commandManager;
  54847. juce_UseDebuggingNewOperator
  54848. private:
  54849. Item& operator= (const Item&);
  54850. };
  54851. class PopupMenu::ItemComponent : public Component
  54852. {
  54853. public:
  54854. ItemComponent (const PopupMenu::Item& itemInfo_)
  54855. : itemInfo (itemInfo_),
  54856. isHighlighted (false)
  54857. {
  54858. if (itemInfo.customComp != 0)
  54859. addAndMakeVisible (itemInfo.customComp);
  54860. }
  54861. ~ItemComponent()
  54862. {
  54863. if (itemInfo.customComp != 0)
  54864. removeChildComponent (itemInfo.customComp);
  54865. }
  54866. void getIdealSize (int& idealWidth,
  54867. int& idealHeight,
  54868. const int standardItemHeight)
  54869. {
  54870. if (itemInfo.customComp != 0)
  54871. {
  54872. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  54873. }
  54874. else
  54875. {
  54876. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  54877. itemInfo.isSeparator,
  54878. standardItemHeight,
  54879. idealWidth,
  54880. idealHeight);
  54881. }
  54882. }
  54883. void paint (Graphics& g)
  54884. {
  54885. if (itemInfo.customComp == 0)
  54886. {
  54887. String mainText (itemInfo.text);
  54888. String endText;
  54889. const int endIndex = mainText.indexOf ("<end>");
  54890. if (endIndex >= 0)
  54891. {
  54892. endText = mainText.substring (endIndex + 5).trim();
  54893. mainText = mainText.substring (0, endIndex);
  54894. }
  54895. getLookAndFeel()
  54896. .drawPopupMenuItem (g, getWidth(), getHeight(),
  54897. itemInfo.isSeparator,
  54898. itemInfo.active,
  54899. isHighlighted,
  54900. itemInfo.isTicked,
  54901. itemInfo.subMenu != 0,
  54902. mainText, endText,
  54903. itemInfo.image.isValid() ? &itemInfo.image : 0,
  54904. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  54905. }
  54906. }
  54907. void resized()
  54908. {
  54909. if (getNumChildComponents() > 0)
  54910. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  54911. }
  54912. void setHighlighted (bool shouldBeHighlighted)
  54913. {
  54914. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  54915. if (isHighlighted != shouldBeHighlighted)
  54916. {
  54917. isHighlighted = shouldBeHighlighted;
  54918. if (itemInfo.customComp != 0)
  54919. {
  54920. itemInfo.customComp->isHighlighted = shouldBeHighlighted;
  54921. itemInfo.customComp->repaint();
  54922. }
  54923. repaint();
  54924. }
  54925. }
  54926. PopupMenu::Item itemInfo;
  54927. juce_UseDebuggingNewOperator
  54928. private:
  54929. bool isHighlighted;
  54930. ItemComponent (const ItemComponent&);
  54931. ItemComponent& operator= (const ItemComponent&);
  54932. };
  54933. namespace PopupMenuSettings
  54934. {
  54935. static const int scrollZone = 24;
  54936. static const int borderSize = 2;
  54937. static const int timerInterval = 50;
  54938. static const int dismissCommandId = 0x6287345f;
  54939. }
  54940. class PopupMenu::Window : public Component,
  54941. private Timer
  54942. {
  54943. public:
  54944. Window()
  54945. : Component ("menu"),
  54946. owner (0),
  54947. currentChild (0),
  54948. activeSubMenu (0),
  54949. managerOfChosenCommand (0),
  54950. minimumWidth (0),
  54951. maximumNumColumns (7),
  54952. standardItemHeight (0),
  54953. isOver (false),
  54954. hasBeenOver (false),
  54955. isDown (false),
  54956. needsToScroll (false),
  54957. hideOnExit (false),
  54958. disableMouseMoves (false),
  54959. hasAnyJuceCompHadFocus (false),
  54960. numColumns (0),
  54961. contentHeight (0),
  54962. childYOffset (0),
  54963. timeEnteredCurrentChildComp (0),
  54964. scrollAcceleration (1.0)
  54965. {
  54966. menuCreationTime = lastFocused = lastScroll = Time::getMillisecondCounter();
  54967. setWantsKeyboardFocus (true);
  54968. setMouseClickGrabsKeyboardFocus (false);
  54969. setOpaque (true);
  54970. setAlwaysOnTop (true);
  54971. Desktop::getInstance().addGlobalMouseListener (this);
  54972. getActiveWindows().add (this);
  54973. }
  54974. ~Window()
  54975. {
  54976. getActiveWindows().removeValue (this);
  54977. Desktop::getInstance().removeGlobalMouseListener (this);
  54978. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  54979. activeSubMenu = 0;
  54980. deleteAllChildren();
  54981. }
  54982. static Window* create (const PopupMenu& menu,
  54983. const bool dismissOnMouseUp,
  54984. Window* const owner_,
  54985. const Rectangle<int>& target,
  54986. const int minimumWidth,
  54987. const int maximumNumColumns,
  54988. const int standardItemHeight,
  54989. const bool alignToRectangle,
  54990. const int itemIdThatMustBeVisible,
  54991. ApplicationCommandManager** managerOfChosenCommand,
  54992. Component* const componentAttachedTo)
  54993. {
  54994. if (menu.items.size() > 0)
  54995. {
  54996. int totalItems = 0;
  54997. ScopedPointer <Window> mw (new Window());
  54998. mw->setLookAndFeel (menu.lookAndFeel);
  54999. mw->setWantsKeyboardFocus (false);
  55000. mw->minimumWidth = minimumWidth;
  55001. mw->maximumNumColumns = maximumNumColumns;
  55002. mw->standardItemHeight = standardItemHeight;
  55003. mw->dismissOnMouseUp = dismissOnMouseUp;
  55004. for (int i = 0; i < menu.items.size(); ++i)
  55005. {
  55006. PopupMenu::Item* const item = menu.items.getUnchecked(i);
  55007. mw->addItem (*item);
  55008. ++totalItems;
  55009. }
  55010. if (totalItems > 0)
  55011. {
  55012. mw->owner = owner_;
  55013. mw->managerOfChosenCommand = managerOfChosenCommand;
  55014. mw->componentAttachedTo = componentAttachedTo;
  55015. mw->componentAttachedToOriginal = componentAttachedTo;
  55016. mw->calculateWindowPos (target, alignToRectangle);
  55017. mw->setTopLeftPosition (mw->windowPos.getX(),
  55018. mw->windowPos.getY());
  55019. mw->updateYPositions();
  55020. if (itemIdThatMustBeVisible != 0)
  55021. {
  55022. const int y = target.getY() - mw->windowPos.getY();
  55023. mw->ensureItemIsVisible (itemIdThatMustBeVisible,
  55024. (((unsigned int) y) < (unsigned int) mw->windowPos.getHeight()) ? y : -1);
  55025. }
  55026. mw->resizeToBestWindowPos();
  55027. mw->addToDesktop (ComponentPeer::windowIsTemporary
  55028. | mw->getLookAndFeel().getMenuWindowFlags());
  55029. return mw.release();
  55030. }
  55031. }
  55032. return 0;
  55033. }
  55034. void paint (Graphics& g)
  55035. {
  55036. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  55037. }
  55038. void paintOverChildren (Graphics& g)
  55039. {
  55040. if (isScrolling())
  55041. {
  55042. LookAndFeel& lf = getLookAndFeel();
  55043. if (isScrollZoneActive (false))
  55044. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, true);
  55045. if (isScrollZoneActive (true))
  55046. {
  55047. g.setOrigin (0, getHeight() - PopupMenuSettings::scrollZone);
  55048. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, false);
  55049. }
  55050. }
  55051. }
  55052. bool isScrollZoneActive (bool bottomOne) const
  55053. {
  55054. return isScrolling()
  55055. && (bottomOne
  55056. ? childYOffset < contentHeight - windowPos.getHeight()
  55057. : childYOffset > 0);
  55058. }
  55059. void addItem (const PopupMenu::Item& item)
  55060. {
  55061. PopupMenu::ItemComponent* const mic = new PopupMenu::ItemComponent (item);
  55062. addAndMakeVisible (mic);
  55063. int itemW = 80;
  55064. int itemH = 16;
  55065. mic->getIdealSize (itemW, itemH, standardItemHeight);
  55066. mic->setSize (itemW, jlimit (2, 600, itemH));
  55067. mic->addMouseListener (this, false);
  55068. }
  55069. // hide this and all sub-comps
  55070. void hide (const PopupMenu::Item* const item)
  55071. {
  55072. if (isVisible())
  55073. {
  55074. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55075. activeSubMenu = 0;
  55076. currentChild = 0;
  55077. exitModalState (item != 0 ? item->itemId : 0);
  55078. setVisible (false);
  55079. if (item != 0
  55080. && item->commandManager != 0
  55081. && item->itemId != 0)
  55082. {
  55083. *managerOfChosenCommand = item->commandManager;
  55084. }
  55085. }
  55086. }
  55087. void dismissMenu (const PopupMenu::Item* const item)
  55088. {
  55089. if (owner != 0)
  55090. {
  55091. owner->dismissMenu (item);
  55092. }
  55093. else
  55094. {
  55095. if (item != 0)
  55096. {
  55097. // need a copy of this on the stack as the one passed in will get deleted during this call
  55098. const PopupMenu::Item mi (*item);
  55099. hide (&mi);
  55100. }
  55101. else
  55102. {
  55103. hide (0);
  55104. }
  55105. }
  55106. }
  55107. void mouseMove (const MouseEvent&)
  55108. {
  55109. timerCallback();
  55110. }
  55111. void mouseDown (const MouseEvent&)
  55112. {
  55113. timerCallback();
  55114. }
  55115. void mouseDrag (const MouseEvent&)
  55116. {
  55117. timerCallback();
  55118. }
  55119. void mouseUp (const MouseEvent&)
  55120. {
  55121. timerCallback();
  55122. }
  55123. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  55124. {
  55125. alterChildYPos (roundToInt (-10.0f * amountY * PopupMenuSettings::scrollZone));
  55126. lastMouse = Point<int> (-1, -1);
  55127. }
  55128. bool keyPressed (const KeyPress& key)
  55129. {
  55130. if (key.isKeyCode (KeyPress::downKey))
  55131. {
  55132. selectNextItem (1);
  55133. }
  55134. else if (key.isKeyCode (KeyPress::upKey))
  55135. {
  55136. selectNextItem (-1);
  55137. }
  55138. else if (key.isKeyCode (KeyPress::leftKey))
  55139. {
  55140. if (owner != 0)
  55141. {
  55142. Component::SafePointer<Window> parentWindow (owner);
  55143. PopupMenu::ItemComponent* currentChildOfParent = parentWindow->currentChild;
  55144. hide (0);
  55145. if (parentWindow != 0)
  55146. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  55147. disableTimerUntilMouseMoves();
  55148. }
  55149. else if (componentAttachedTo != 0)
  55150. {
  55151. componentAttachedTo->keyPressed (key);
  55152. }
  55153. }
  55154. else if (key.isKeyCode (KeyPress::rightKey))
  55155. {
  55156. disableTimerUntilMouseMoves();
  55157. if (showSubMenuFor (currentChild))
  55158. {
  55159. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55160. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  55161. activeSubMenu->selectNextItem (1);
  55162. }
  55163. else if (componentAttachedTo != 0)
  55164. {
  55165. componentAttachedTo->keyPressed (key);
  55166. }
  55167. }
  55168. else if (key.isKeyCode (KeyPress::returnKey))
  55169. {
  55170. triggerCurrentlyHighlightedItem();
  55171. }
  55172. else if (key.isKeyCode (KeyPress::escapeKey))
  55173. {
  55174. dismissMenu (0);
  55175. }
  55176. else
  55177. {
  55178. return false;
  55179. }
  55180. return true;
  55181. }
  55182. void inputAttemptWhenModal()
  55183. {
  55184. Component::SafePointer<Component> deletionChecker (this);
  55185. timerCallback();
  55186. if (deletionChecker != 0 && ! isOverAnyMenu())
  55187. {
  55188. if (componentAttachedTo != 0)
  55189. {
  55190. // we want to dismiss the menu, but if we do it synchronously, then
  55191. // the mouse-click will be allowed to pass through. That's good, except
  55192. // when the user clicks on the button that orginally popped the menu up,
  55193. // as they'll expect the menu to go away, and in fact it'll just
  55194. // come back. So only dismiss synchronously if they're not on the original
  55195. // comp that we're attached to.
  55196. const Point<int> mousePos (componentAttachedTo->getMouseXYRelative());
  55197. if (componentAttachedTo->reallyContains (mousePos.getX(), mousePos.getY(), true))
  55198. {
  55199. postCommandMessage (PopupMenuSettings::dismissCommandId); // dismiss asynchrounously
  55200. return;
  55201. }
  55202. }
  55203. dismissMenu (0);
  55204. }
  55205. }
  55206. void handleCommandMessage (int commandId)
  55207. {
  55208. Component::handleCommandMessage (commandId);
  55209. if (commandId == PopupMenuSettings::dismissCommandId)
  55210. dismissMenu (0);
  55211. }
  55212. void timerCallback()
  55213. {
  55214. if (! isVisible())
  55215. return;
  55216. if (componentAttachedTo != componentAttachedToOriginal)
  55217. {
  55218. dismissMenu (0);
  55219. return;
  55220. }
  55221. Window* currentlyModalWindow = dynamic_cast <Window*> (Component::getCurrentlyModalComponent());
  55222. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  55223. return;
  55224. startTimer (PopupMenuSettings::timerInterval); // do this in case it was called from a mouse
  55225. // move rather than a real timer callback
  55226. const Point<int> globalMousePos (Desktop::getMousePosition());
  55227. const Point<int> localMousePos (globalPositionToRelative (globalMousePos));
  55228. const uint32 now = Time::getMillisecondCounter();
  55229. if (now > timeEnteredCurrentChildComp + 100
  55230. && reallyContains (localMousePos.getX(), localMousePos.getY(), true)
  55231. && currentChild->isValidComponent()
  55232. && (! disableMouseMoves)
  55233. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  55234. {
  55235. showSubMenuFor (currentChild);
  55236. }
  55237. if (globalMousePos != lastMouse || now > lastMouseMoveTime + 350)
  55238. {
  55239. highlightItemUnderMouse (globalMousePos, localMousePos);
  55240. }
  55241. bool overScrollArea = false;
  55242. if (isScrolling()
  55243. && (isOver || (isDown && ((unsigned int) localMousePos.getX()) < (unsigned int) getWidth()))
  55244. && ((isScrollZoneActive (false) && localMousePos.getY() < PopupMenuSettings::scrollZone)
  55245. || (isScrollZoneActive (true) && localMousePos.getY() > getHeight() - PopupMenuSettings::scrollZone)))
  55246. {
  55247. if (now > lastScroll + 20)
  55248. {
  55249. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  55250. int amount = 0;
  55251. for (int i = 0; i < getNumChildComponents() && amount == 0; ++i)
  55252. amount = ((int) scrollAcceleration) * getChildComponent (i)->getHeight();
  55253. alterChildYPos (localMousePos.getY() < PopupMenuSettings::scrollZone ? -amount : amount);
  55254. lastScroll = now;
  55255. }
  55256. overScrollArea = true;
  55257. lastMouse = Point<int> (-1, -1); // trigger a mouse-move
  55258. }
  55259. else
  55260. {
  55261. scrollAcceleration = 1.0;
  55262. }
  55263. const bool wasDown = isDown;
  55264. bool isOverAny = isOverAnyMenu();
  55265. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  55266. {
  55267. activeSubMenu->updateMouseOverStatus (globalMousePos);
  55268. isOverAny = isOverAnyMenu();
  55269. }
  55270. if (hideOnExit && hasBeenOver && ! isOverAny)
  55271. {
  55272. hide (0);
  55273. }
  55274. else
  55275. {
  55276. isDown = hasBeenOver
  55277. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  55278. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  55279. bool anyFocused = Process::isForegroundProcess();
  55280. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  55281. {
  55282. // because no component at all may have focus, our test here will
  55283. // only be triggered when something has focus and then loses it.
  55284. anyFocused = ! hasAnyJuceCompHadFocus;
  55285. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  55286. {
  55287. if (ComponentPeer::getPeer (i)->isFocused())
  55288. {
  55289. anyFocused = true;
  55290. hasAnyJuceCompHadFocus = true;
  55291. break;
  55292. }
  55293. }
  55294. }
  55295. if (! anyFocused)
  55296. {
  55297. if (now > lastFocused + 10)
  55298. {
  55299. wasHiddenBecauseOfAppChange() = true;
  55300. dismissMenu (0);
  55301. return; // may have been deleted by the previous call..
  55302. }
  55303. }
  55304. else if (wasDown && now > menuCreationTime + 250
  55305. && ! (isDown || overScrollArea))
  55306. {
  55307. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  55308. if (isOver)
  55309. {
  55310. triggerCurrentlyHighlightedItem();
  55311. }
  55312. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  55313. {
  55314. dismissMenu (0);
  55315. }
  55316. return; // may have been deleted by the previous calls..
  55317. }
  55318. else
  55319. {
  55320. lastFocused = now;
  55321. }
  55322. }
  55323. }
  55324. static Array<Window*>& getActiveWindows()
  55325. {
  55326. static Array<Window*> activeMenuWindows;
  55327. return activeMenuWindows;
  55328. }
  55329. static bool& wasHiddenBecauseOfAppChange() throw()
  55330. {
  55331. static bool b = false;
  55332. return b;
  55333. }
  55334. juce_UseDebuggingNewOperator
  55335. private:
  55336. Window* owner;
  55337. PopupMenu::ItemComponent* currentChild;
  55338. ScopedPointer <Window> activeSubMenu;
  55339. ApplicationCommandManager** managerOfChosenCommand;
  55340. Component::SafePointer<Component> componentAttachedTo;
  55341. Component* componentAttachedToOriginal;
  55342. Rectangle<int> windowPos;
  55343. Point<int> lastMouse;
  55344. int minimumWidth, maximumNumColumns, standardItemHeight;
  55345. bool isOver, hasBeenOver, isDown, needsToScroll;
  55346. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  55347. int numColumns, contentHeight, childYOffset;
  55348. Array <int> columnWidths;
  55349. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  55350. double scrollAcceleration;
  55351. bool overlaps (const Rectangle<int>& r) const
  55352. {
  55353. return r.intersects (getBounds())
  55354. || (owner != 0 && owner->overlaps (r));
  55355. }
  55356. bool isOverAnyMenu() const
  55357. {
  55358. return (owner != 0) ? owner->isOverAnyMenu()
  55359. : isOverChildren();
  55360. }
  55361. bool isOverChildren() const
  55362. {
  55363. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55364. return isVisible()
  55365. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  55366. }
  55367. void updateMouseOverStatus (const Point<int>& globalMousePos)
  55368. {
  55369. const Point<int> relPos (globalPositionToRelative (globalMousePos));
  55370. isOver = reallyContains (relPos.getX(), relPos.getY(), true);
  55371. if (activeSubMenu != 0)
  55372. activeSubMenu->updateMouseOverStatus (globalMousePos);
  55373. }
  55374. bool treeContains (const Window* const window) const throw()
  55375. {
  55376. const Window* mw = this;
  55377. while (mw->owner != 0)
  55378. mw = mw->owner;
  55379. while (mw != 0)
  55380. {
  55381. if (mw == window)
  55382. return true;
  55383. mw = mw->activeSubMenu;
  55384. }
  55385. return false;
  55386. }
  55387. void calculateWindowPos (const Rectangle<int>& target, const bool alignToRectangle)
  55388. {
  55389. const Rectangle<int> mon (Desktop::getInstance()
  55390. .getMonitorAreaContaining (target.getCentre(),
  55391. #if JUCE_MAC
  55392. true));
  55393. #else
  55394. false)); // on windows, don't stop the menu overlapping the taskbar
  55395. #endif
  55396. int x, y, widthToUse, heightToUse;
  55397. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  55398. if (alignToRectangle)
  55399. {
  55400. x = target.getX();
  55401. const int spaceUnder = mon.getHeight() - (target.getBottom() - mon.getY());
  55402. const int spaceOver = target.getY() - mon.getY();
  55403. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  55404. y = target.getBottom();
  55405. else
  55406. y = target.getY() - heightToUse;
  55407. }
  55408. else
  55409. {
  55410. bool tendTowardsRight = target.getCentreX() < mon.getCentreX();
  55411. if (owner != 0)
  55412. {
  55413. if (owner->owner != 0)
  55414. {
  55415. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  55416. > owner->owner->getX() + owner->owner->getWidth() / 2);
  55417. if (ownerGoingRight && target.getRight() + widthToUse < mon.getRight() - 4)
  55418. tendTowardsRight = true;
  55419. else if ((! ownerGoingRight) && target.getX() > widthToUse + 4)
  55420. tendTowardsRight = false;
  55421. }
  55422. else if (target.getRight() + widthToUse < mon.getRight() - 32)
  55423. {
  55424. tendTowardsRight = true;
  55425. }
  55426. }
  55427. const int biggestSpace = jmax (mon.getRight() - target.getRight(),
  55428. target.getX() - mon.getX()) - 32;
  55429. if (biggestSpace < widthToUse)
  55430. {
  55431. layoutMenuItems (biggestSpace + target.getWidth() / 3, widthToUse, heightToUse);
  55432. if (numColumns > 1)
  55433. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  55434. tendTowardsRight = (mon.getRight() - target.getRight()) >= (target.getX() - mon.getX());
  55435. }
  55436. if (tendTowardsRight)
  55437. x = jmin (mon.getRight() - widthToUse - 4, target.getRight());
  55438. else
  55439. x = jmax (mon.getX() + 4, target.getX() - widthToUse);
  55440. y = target.getY();
  55441. if (target.getCentreY() > mon.getCentreY())
  55442. y = jmax (mon.getY(), target.getBottom() - heightToUse);
  55443. }
  55444. x = jmax (mon.getX() + 1, jmin (mon.getRight() - (widthToUse + 6), x));
  55445. y = jmax (mon.getY() + 1, jmin (mon.getBottom() - (heightToUse + 6), y));
  55446. windowPos.setBounds (x, y, widthToUse, heightToUse);
  55447. // sets this flag if it's big enough to obscure any of its parent menus
  55448. hideOnExit = (owner != 0)
  55449. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  55450. }
  55451. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  55452. {
  55453. numColumns = 0;
  55454. contentHeight = 0;
  55455. const int maxMenuH = getParentHeight() - 24;
  55456. int totalW;
  55457. do
  55458. {
  55459. ++numColumns;
  55460. totalW = workOutBestSize (maxMenuW);
  55461. if (totalW > maxMenuW)
  55462. {
  55463. numColumns = jmax (1, numColumns - 1);
  55464. totalW = workOutBestSize (maxMenuW); // to update col widths
  55465. break;
  55466. }
  55467. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  55468. {
  55469. break;
  55470. }
  55471. } while (numColumns < maximumNumColumns);
  55472. const int actualH = jmin (contentHeight, maxMenuH);
  55473. needsToScroll = contentHeight > actualH;
  55474. width = updateYPositions();
  55475. height = actualH + PopupMenuSettings::borderSize * 2;
  55476. }
  55477. int workOutBestSize (const int maxMenuW)
  55478. {
  55479. int totalW = 0;
  55480. contentHeight = 0;
  55481. int childNum = 0;
  55482. for (int col = 0; col < numColumns; ++col)
  55483. {
  55484. int i, colW = 50, colH = 0;
  55485. const int numChildren = jmin (getNumChildComponents() - childNum,
  55486. (getNumChildComponents() + numColumns - 1) / numColumns);
  55487. for (i = numChildren; --i >= 0;)
  55488. {
  55489. colW = jmax (colW, getChildComponent (childNum + i)->getWidth());
  55490. colH += getChildComponent (childNum + i)->getHeight();
  55491. }
  55492. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + PopupMenuSettings::borderSize * 2);
  55493. columnWidths.set (col, colW);
  55494. totalW += colW;
  55495. contentHeight = jmax (contentHeight, colH);
  55496. childNum += numChildren;
  55497. }
  55498. if (totalW < minimumWidth)
  55499. {
  55500. totalW = minimumWidth;
  55501. for (int col = 0; col < numColumns; ++col)
  55502. columnWidths.set (0, totalW / numColumns);
  55503. }
  55504. return totalW;
  55505. }
  55506. void ensureItemIsVisible (const int itemId, int wantedY)
  55507. {
  55508. jassert (itemId != 0)
  55509. for (int i = getNumChildComponents(); --i >= 0;)
  55510. {
  55511. PopupMenu::ItemComponent* const m = static_cast <PopupMenu::ItemComponent*> (getChildComponent (i));
  55512. if (m != 0
  55513. && m->itemInfo.itemId == itemId
  55514. && windowPos.getHeight() > PopupMenuSettings::scrollZone * 4)
  55515. {
  55516. const int currentY = m->getY();
  55517. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  55518. {
  55519. if (wantedY < 0)
  55520. wantedY = jlimit (PopupMenuSettings::scrollZone,
  55521. jmax (PopupMenuSettings::scrollZone,
  55522. windowPos.getHeight() - (PopupMenuSettings::scrollZone + m->getHeight())),
  55523. currentY);
  55524. const Rectangle<int> mon (Desktop::getInstance().getMonitorAreaContaining (windowPos.getPosition(), true));
  55525. int deltaY = wantedY - currentY;
  55526. windowPos.setSize (jmin (windowPos.getWidth(), mon.getWidth()),
  55527. jmin (windowPos.getHeight(), mon.getHeight()));
  55528. const int newY = jlimit (mon.getY(),
  55529. mon.getBottom() - windowPos.getHeight(),
  55530. windowPos.getY() + deltaY);
  55531. deltaY -= newY - windowPos.getY();
  55532. childYOffset -= deltaY;
  55533. windowPos.setPosition (windowPos.getX(), newY);
  55534. updateYPositions();
  55535. }
  55536. break;
  55537. }
  55538. }
  55539. }
  55540. void resizeToBestWindowPos()
  55541. {
  55542. Rectangle<int> r (windowPos);
  55543. if (childYOffset < 0)
  55544. {
  55545. r.setBounds (r.getX(), r.getY() - childYOffset,
  55546. r.getWidth(), r.getHeight() + childYOffset);
  55547. }
  55548. else if (childYOffset > 0)
  55549. {
  55550. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  55551. if (spaceAtBottom > 0)
  55552. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  55553. }
  55554. setBounds (r);
  55555. updateYPositions();
  55556. }
  55557. void alterChildYPos (const int delta)
  55558. {
  55559. if (isScrolling())
  55560. {
  55561. childYOffset += delta;
  55562. if (delta < 0)
  55563. {
  55564. childYOffset = jmax (childYOffset, 0);
  55565. }
  55566. else if (delta > 0)
  55567. {
  55568. childYOffset = jmin (childYOffset,
  55569. contentHeight - windowPos.getHeight() + PopupMenuSettings::borderSize);
  55570. }
  55571. updateYPositions();
  55572. }
  55573. else
  55574. {
  55575. childYOffset = 0;
  55576. }
  55577. resizeToBestWindowPos();
  55578. repaint();
  55579. }
  55580. int updateYPositions()
  55581. {
  55582. int x = 0;
  55583. int childNum = 0;
  55584. for (int col = 0; col < numColumns; ++col)
  55585. {
  55586. const int numChildren = jmin (getNumChildComponents() - childNum,
  55587. (getNumChildComponents() + numColumns - 1) / numColumns);
  55588. const int colW = columnWidths [col];
  55589. int y = PopupMenuSettings::borderSize - (childYOffset + (getY() - windowPos.getY()));
  55590. for (int i = 0; i < numChildren; ++i)
  55591. {
  55592. Component* const c = getChildComponent (childNum + i);
  55593. c->setBounds (x, y, colW, c->getHeight());
  55594. y += c->getHeight();
  55595. }
  55596. x += colW;
  55597. childNum += numChildren;
  55598. }
  55599. return x;
  55600. }
  55601. bool isScrolling() const throw()
  55602. {
  55603. return childYOffset != 0 || needsToScroll;
  55604. }
  55605. void setCurrentlyHighlightedChild (PopupMenu::ItemComponent* const child)
  55606. {
  55607. if (currentChild->isValidComponent())
  55608. currentChild->setHighlighted (false);
  55609. currentChild = child;
  55610. if (currentChild != 0)
  55611. {
  55612. currentChild->setHighlighted (true);
  55613. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  55614. }
  55615. }
  55616. bool showSubMenuFor (PopupMenu::ItemComponent* const childComp)
  55617. {
  55618. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55619. activeSubMenu = 0;
  55620. if (childComp->isValidComponent() && childComp->itemInfo.hasActiveSubMenu())
  55621. {
  55622. activeSubMenu = Window::create (*(childComp->itemInfo.subMenu),
  55623. dismissOnMouseUp,
  55624. this,
  55625. childComp->getScreenBounds(),
  55626. 0, maximumNumColumns,
  55627. standardItemHeight,
  55628. false, 0, managerOfChosenCommand,
  55629. componentAttachedTo);
  55630. if (activeSubMenu != 0)
  55631. {
  55632. activeSubMenu->setVisible (true);
  55633. activeSubMenu->enterModalState (false);
  55634. activeSubMenu->toFront (false);
  55635. return true;
  55636. }
  55637. }
  55638. return false;
  55639. }
  55640. void highlightItemUnderMouse (const Point<int>& globalMousePos, const Point<int>& localMousePos)
  55641. {
  55642. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  55643. if (isOver)
  55644. hasBeenOver = true;
  55645. if (lastMouse.getDistanceFrom (globalMousePos) > 2)
  55646. {
  55647. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  55648. if (disableMouseMoves && isOver)
  55649. disableMouseMoves = false;
  55650. }
  55651. if (disableMouseMoves || (activeSubMenu != 0 && activeSubMenu->isOverChildren()))
  55652. return;
  55653. bool isMovingTowardsMenu = false;
  55654. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent())
  55655. if (isOver && (activeSubMenu != 0) && globalMousePos != lastMouse)
  55656. {
  55657. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  55658. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  55659. // extends from the last mouse pos to the submenu's rectangle..
  55660. float subX = (float) activeSubMenu->getScreenX();
  55661. if (activeSubMenu->getX() > getX())
  55662. {
  55663. lastMouse -= Point<int> (2, 0); // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  55664. }
  55665. else
  55666. {
  55667. lastMouse += Point<int> (2, 0);
  55668. subX += activeSubMenu->getWidth();
  55669. }
  55670. Path areaTowardsSubMenu;
  55671. areaTowardsSubMenu.addTriangle ((float) lastMouse.getX(),
  55672. (float) lastMouse.getY(),
  55673. subX,
  55674. (float) activeSubMenu->getScreenY(),
  55675. subX,
  55676. (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  55677. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) globalMousePos.getX(), (float) globalMousePos.getY());
  55678. }
  55679. lastMouse = globalMousePos;
  55680. if (! isMovingTowardsMenu)
  55681. {
  55682. Component* c = getComponentAt (localMousePos.getX(), localMousePos.getY());
  55683. if (c == this)
  55684. c = 0;
  55685. PopupMenu::ItemComponent* mic = dynamic_cast <PopupMenu::ItemComponent*> (c);
  55686. if (mic == 0 && c != 0)
  55687. mic = c->findParentComponentOfClass ((PopupMenu::ItemComponent*) 0);
  55688. if (mic != currentChild
  55689. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  55690. {
  55691. if (isOver && (c != 0) && (activeSubMenu != 0))
  55692. {
  55693. activeSubMenu->hide (0);
  55694. }
  55695. if (! isOver)
  55696. mic = 0;
  55697. setCurrentlyHighlightedChild (mic);
  55698. }
  55699. }
  55700. }
  55701. void triggerCurrentlyHighlightedItem()
  55702. {
  55703. if (currentChild->isValidComponent()
  55704. && currentChild->itemInfo.canBeTriggered()
  55705. && (currentChild->itemInfo.customComp == 0
  55706. || currentChild->itemInfo.customComp->isTriggeredAutomatically))
  55707. {
  55708. dismissMenu (&currentChild->itemInfo);
  55709. }
  55710. }
  55711. void selectNextItem (const int delta)
  55712. {
  55713. disableTimerUntilMouseMoves();
  55714. PopupMenu::ItemComponent* mic = 0;
  55715. bool wasLastOne = (currentChild == 0);
  55716. const int numItems = getNumChildComponents();
  55717. for (int i = 0; i < numItems + 1; ++i)
  55718. {
  55719. int index = (delta > 0) ? i : (numItems - 1 - i);
  55720. index = (index + numItems) % numItems;
  55721. mic = dynamic_cast <PopupMenu::ItemComponent*> (getChildComponent (index));
  55722. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  55723. && wasLastOne)
  55724. break;
  55725. if (mic == currentChild)
  55726. wasLastOne = true;
  55727. }
  55728. setCurrentlyHighlightedChild (mic);
  55729. }
  55730. void disableTimerUntilMouseMoves()
  55731. {
  55732. disableMouseMoves = true;
  55733. if (owner != 0)
  55734. owner->disableTimerUntilMouseMoves();
  55735. }
  55736. Window (const Window&);
  55737. Window& operator= (const Window&);
  55738. };
  55739. PopupMenu::PopupMenu()
  55740. : lookAndFeel (0),
  55741. separatorPending (false)
  55742. {
  55743. }
  55744. PopupMenu::PopupMenu (const PopupMenu& other)
  55745. : lookAndFeel (other.lookAndFeel),
  55746. separatorPending (false)
  55747. {
  55748. items.addCopiesOf (other.items);
  55749. }
  55750. PopupMenu& PopupMenu::operator= (const PopupMenu& other)
  55751. {
  55752. if (this != &other)
  55753. {
  55754. lookAndFeel = other.lookAndFeel;
  55755. clear();
  55756. items.addCopiesOf (other.items);
  55757. }
  55758. return *this;
  55759. }
  55760. PopupMenu::~PopupMenu()
  55761. {
  55762. clear();
  55763. }
  55764. void PopupMenu::clear()
  55765. {
  55766. items.clear();
  55767. separatorPending = false;
  55768. }
  55769. void PopupMenu::addSeparatorIfPending()
  55770. {
  55771. if (separatorPending)
  55772. {
  55773. separatorPending = false;
  55774. if (items.size() > 0)
  55775. items.add (new Item());
  55776. }
  55777. }
  55778. void PopupMenu::addItem (const int itemResultId,
  55779. const String& itemText,
  55780. const bool isActive,
  55781. const bool isTicked,
  55782. const Image& iconToUse)
  55783. {
  55784. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  55785. // didn't pick anything, so you shouldn't use it as the id
  55786. // for an item..
  55787. addSeparatorIfPending();
  55788. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  55789. Colours::black, false, 0, 0, 0));
  55790. }
  55791. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  55792. const int commandID,
  55793. const String& displayName)
  55794. {
  55795. jassert (commandManager != 0 && commandID != 0);
  55796. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  55797. if (registeredInfo != 0)
  55798. {
  55799. ApplicationCommandInfo info (*registeredInfo);
  55800. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  55801. addSeparatorIfPending();
  55802. items.add (new Item (commandID,
  55803. displayName.isNotEmpty() ? displayName
  55804. : info.shortName,
  55805. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  55806. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  55807. Image(),
  55808. Colours::black,
  55809. false,
  55810. 0, 0,
  55811. commandManager));
  55812. }
  55813. }
  55814. void PopupMenu::addColouredItem (const int itemResultId,
  55815. const String& itemText,
  55816. const Colour& itemTextColour,
  55817. const bool isActive,
  55818. const bool isTicked,
  55819. const Image& iconToUse)
  55820. {
  55821. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  55822. // didn't pick anything, so you shouldn't use it as the id
  55823. // for an item..
  55824. addSeparatorIfPending();
  55825. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  55826. itemTextColour, true, 0, 0, 0));
  55827. }
  55828. void PopupMenu::addCustomItem (const int itemResultId,
  55829. PopupMenuCustomComponent* const customComponent)
  55830. {
  55831. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  55832. // didn't pick anything, so you shouldn't use it as the id
  55833. // for an item..
  55834. addSeparatorIfPending();
  55835. items.add (new Item (itemResultId, String::empty, true, false, Image(),
  55836. Colours::black, false, customComponent, 0, 0));
  55837. }
  55838. class NormalComponentWrapper : public PopupMenuCustomComponent
  55839. {
  55840. public:
  55841. NormalComponentWrapper (Component* const comp,
  55842. const int w, const int h,
  55843. const bool triggerMenuItemAutomaticallyWhenClicked)
  55844. : PopupMenuCustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  55845. width (w),
  55846. height (h)
  55847. {
  55848. addAndMakeVisible (comp);
  55849. }
  55850. ~NormalComponentWrapper() {}
  55851. void getIdealSize (int& idealWidth, int& idealHeight)
  55852. {
  55853. idealWidth = width;
  55854. idealHeight = height;
  55855. }
  55856. void resized()
  55857. {
  55858. if (getChildComponent(0) != 0)
  55859. getChildComponent(0)->setBounds (getLocalBounds());
  55860. }
  55861. juce_UseDebuggingNewOperator
  55862. private:
  55863. const int width, height;
  55864. NormalComponentWrapper (const NormalComponentWrapper&);
  55865. NormalComponentWrapper& operator= (const NormalComponentWrapper&);
  55866. };
  55867. void PopupMenu::addCustomItem (const int itemResultId,
  55868. Component* customComponent,
  55869. int idealWidth, int idealHeight,
  55870. const bool triggerMenuItemAutomaticallyWhenClicked)
  55871. {
  55872. addCustomItem (itemResultId,
  55873. new NormalComponentWrapper (customComponent,
  55874. idealWidth, idealHeight,
  55875. triggerMenuItemAutomaticallyWhenClicked));
  55876. }
  55877. void PopupMenu::addSubMenu (const String& subMenuName,
  55878. const PopupMenu& subMenu,
  55879. const bool isActive,
  55880. const Image& iconToUse,
  55881. const bool isTicked)
  55882. {
  55883. addSeparatorIfPending();
  55884. items.add (new Item (0, subMenuName, isActive && (subMenu.getNumItems() > 0), isTicked,
  55885. iconToUse, Colours::black, false, 0, &subMenu, 0));
  55886. }
  55887. void PopupMenu::addSeparator()
  55888. {
  55889. separatorPending = true;
  55890. }
  55891. class HeaderItemComponent : public PopupMenuCustomComponent
  55892. {
  55893. public:
  55894. HeaderItemComponent (const String& name)
  55895. : PopupMenuCustomComponent (false)
  55896. {
  55897. setName (name);
  55898. }
  55899. ~HeaderItemComponent()
  55900. {
  55901. }
  55902. void paint (Graphics& g)
  55903. {
  55904. Font f (getLookAndFeel().getPopupMenuFont());
  55905. f.setBold (true);
  55906. g.setFont (f);
  55907. g.setColour (findColour (PopupMenu::headerTextColourId));
  55908. g.drawFittedText (getName(),
  55909. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  55910. Justification::bottomLeft, 1);
  55911. }
  55912. void getIdealSize (int& idealWidth,
  55913. int& idealHeight)
  55914. {
  55915. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  55916. idealHeight += idealHeight / 2;
  55917. idealWidth += idealWidth / 4;
  55918. }
  55919. juce_UseDebuggingNewOperator
  55920. };
  55921. void PopupMenu::addSectionHeader (const String& title)
  55922. {
  55923. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  55924. }
  55925. // This invokes any command manager commands and deletes the menu window when it is dismissed
  55926. class PopupMenuCompletionCallback : public ModalComponentManager::Callback
  55927. {
  55928. public:
  55929. PopupMenuCompletionCallback()
  55930. : managerOfChosenCommand (0)
  55931. {
  55932. }
  55933. ~PopupMenuCompletionCallback() {}
  55934. void modalStateFinished (int result)
  55935. {
  55936. if (managerOfChosenCommand != 0 && result != 0)
  55937. {
  55938. ApplicationCommandTarget::InvocationInfo info (result);
  55939. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  55940. managerOfChosenCommand->invoke (info, true);
  55941. }
  55942. }
  55943. ApplicationCommandManager* managerOfChosenCommand;
  55944. ScopedPointer<Component> component;
  55945. private:
  55946. PopupMenuCompletionCallback (const PopupMenuCompletionCallback&);
  55947. PopupMenuCompletionCallback& operator= (const PopupMenuCompletionCallback&);
  55948. };
  55949. int PopupMenu::showMenu (const Rectangle<int>& target,
  55950. const int itemIdThatMustBeVisible,
  55951. const int minimumWidth,
  55952. const int maximumNumColumns,
  55953. const int standardItemHeight,
  55954. const bool alignToRectangle,
  55955. Component* const componentAttachedTo,
  55956. ModalComponentManager::Callback* userCallback)
  55957. {
  55958. ScopedPointer<ModalComponentManager::Callback> userCallbackDeleter (userCallback);
  55959. Component::SafePointer<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  55960. Component::SafePointer<Component> prevTopLevel ((prevFocused != 0) ? prevFocused->getTopLevelComponent() : 0);
  55961. Window::wasHiddenBecauseOfAppChange() = false;
  55962. PopupMenuCompletionCallback* callback = new PopupMenuCompletionCallback();
  55963. ScopedPointer<PopupMenuCompletionCallback> callbackDeleter (callback);
  55964. callback->component = Window::create (*this, ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  55965. 0, target, minimumWidth, maximumNumColumns > 0 ? maximumNumColumns : 7,
  55966. standardItemHeight, alignToRectangle, itemIdThatMustBeVisible,
  55967. &callback->managerOfChosenCommand, componentAttachedTo);
  55968. if (callback->component == 0)
  55969. return 0;
  55970. callbackDeleter.release();
  55971. callback->component->enterModalState (false, userCallbackDeleter.release());
  55972. callback->component->toFront (false); // need to do this after making it modal, or it could
  55973. // be stuck behind other comps that are already modal..
  55974. ModalComponentManager::getInstance()->attachCallback (callback->component, callback);
  55975. if (userCallback != 0)
  55976. return 0;
  55977. const int result = callback->component->runModalLoop();
  55978. if (! Window::wasHiddenBecauseOfAppChange())
  55979. {
  55980. if (prevTopLevel != 0)
  55981. prevTopLevel->toFront (true);
  55982. if (prevFocused != 0)
  55983. prevFocused->grabKeyboardFocus();
  55984. }
  55985. return result;
  55986. }
  55987. int PopupMenu::show (const int itemIdThatMustBeVisible,
  55988. const int minimumWidth,
  55989. const int maximumNumColumns,
  55990. const int standardItemHeight,
  55991. ModalComponentManager::Callback* callback)
  55992. {
  55993. const Point<int> mousePos (Desktop::getMousePosition());
  55994. return showAt (mousePos.getX(), mousePos.getY(),
  55995. itemIdThatMustBeVisible,
  55996. minimumWidth,
  55997. maximumNumColumns,
  55998. standardItemHeight,
  55999. callback);
  56000. }
  56001. int PopupMenu::showAt (const int screenX,
  56002. const int screenY,
  56003. const int itemIdThatMustBeVisible,
  56004. const int minimumWidth,
  56005. const int maximumNumColumns,
  56006. const int standardItemHeight,
  56007. ModalComponentManager::Callback* callback)
  56008. {
  56009. return showMenu (Rectangle<int> (screenX, screenY, 1, 1),
  56010. itemIdThatMustBeVisible,
  56011. minimumWidth, maximumNumColumns,
  56012. standardItemHeight,
  56013. false, 0, callback);
  56014. }
  56015. int PopupMenu::showAt (Component* componentToAttachTo,
  56016. const int itemIdThatMustBeVisible,
  56017. const int minimumWidth,
  56018. const int maximumNumColumns,
  56019. const int standardItemHeight,
  56020. ModalComponentManager::Callback* callback)
  56021. {
  56022. if (componentToAttachTo != 0)
  56023. {
  56024. return showMenu (componentToAttachTo->getScreenBounds(),
  56025. itemIdThatMustBeVisible,
  56026. minimumWidth,
  56027. maximumNumColumns,
  56028. standardItemHeight,
  56029. true, componentToAttachTo, callback);
  56030. }
  56031. else
  56032. {
  56033. return show (itemIdThatMustBeVisible,
  56034. minimumWidth,
  56035. maximumNumColumns,
  56036. standardItemHeight,
  56037. callback);
  56038. }
  56039. }
  56040. void JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus()
  56041. {
  56042. for (int i = Window::getActiveWindows().size(); --i >= 0;)
  56043. {
  56044. Window* const pmw = Window::getActiveWindows()[i];
  56045. if (pmw != 0)
  56046. pmw->dismissMenu (0);
  56047. }
  56048. }
  56049. int PopupMenu::getNumItems() const throw()
  56050. {
  56051. int num = 0;
  56052. for (int i = items.size(); --i >= 0;)
  56053. if (! (items.getUnchecked(i))->isSeparator)
  56054. ++num;
  56055. return num;
  56056. }
  56057. bool PopupMenu::containsCommandItem (const int commandID) const
  56058. {
  56059. for (int i = items.size(); --i >= 0;)
  56060. {
  56061. const Item* mi = items.getUnchecked (i);
  56062. if ((mi->itemId == commandID && mi->commandManager != 0)
  56063. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  56064. {
  56065. return true;
  56066. }
  56067. }
  56068. return false;
  56069. }
  56070. bool PopupMenu::containsAnyActiveItems() const throw()
  56071. {
  56072. for (int i = items.size(); --i >= 0;)
  56073. {
  56074. const Item* const mi = items.getUnchecked (i);
  56075. if (mi->subMenu != 0)
  56076. {
  56077. if (mi->subMenu->containsAnyActiveItems())
  56078. return true;
  56079. }
  56080. else if (mi->active)
  56081. {
  56082. return true;
  56083. }
  56084. }
  56085. return false;
  56086. }
  56087. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  56088. {
  56089. lookAndFeel = newLookAndFeel;
  56090. }
  56091. PopupMenuCustomComponent::PopupMenuCustomComponent (const bool isTriggeredAutomatically_)
  56092. : isHighlighted (false),
  56093. isTriggeredAutomatically (isTriggeredAutomatically_)
  56094. {
  56095. }
  56096. PopupMenuCustomComponent::~PopupMenuCustomComponent()
  56097. {
  56098. }
  56099. void PopupMenuCustomComponent::triggerMenuItem()
  56100. {
  56101. PopupMenu::ItemComponent* const mic = dynamic_cast <PopupMenu::ItemComponent*> (getParentComponent());
  56102. if (mic != 0)
  56103. {
  56104. PopupMenu::Window* const pmw = dynamic_cast <PopupMenu::Window*> (mic->getParentComponent());
  56105. if (pmw != 0)
  56106. {
  56107. pmw->dismissMenu (&mic->itemInfo);
  56108. }
  56109. else
  56110. {
  56111. // something must have gone wrong with the component hierarchy if this happens..
  56112. jassertfalse;
  56113. }
  56114. }
  56115. else
  56116. {
  56117. // why isn't this component inside a menu? Not much point triggering the item if
  56118. // there's no menu.
  56119. jassertfalse;
  56120. }
  56121. }
  56122. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_)
  56123. : subMenu (0),
  56124. itemId (0),
  56125. isSeparator (false),
  56126. isTicked (false),
  56127. isEnabled (false),
  56128. isCustomComponent (false),
  56129. isSectionHeader (false),
  56130. customColour (0),
  56131. customImage (0),
  56132. menu (menu_),
  56133. index (0)
  56134. {
  56135. }
  56136. PopupMenu::MenuItemIterator::~MenuItemIterator()
  56137. {
  56138. }
  56139. bool PopupMenu::MenuItemIterator::next()
  56140. {
  56141. if (index >= menu.items.size())
  56142. return false;
  56143. const Item* const item = menu.items.getUnchecked (index);
  56144. ++index;
  56145. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  56146. subMenu = item->subMenu;
  56147. itemId = item->itemId;
  56148. isSeparator = item->isSeparator;
  56149. isTicked = item->isTicked;
  56150. isEnabled = item->active;
  56151. isSectionHeader = dynamic_cast <HeaderItemComponent*> ((PopupMenuCustomComponent*) item->customComp) != 0;
  56152. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  56153. customColour = item->usesColour ? &(item->textColour) : 0;
  56154. customImage = item->image;
  56155. commandManager = item->commandManager;
  56156. return true;
  56157. }
  56158. END_JUCE_NAMESPACE
  56159. /*** End of inlined file: juce_PopupMenu.cpp ***/
  56160. /*** Start of inlined file: juce_ComponentDragger.cpp ***/
  56161. BEGIN_JUCE_NAMESPACE
  56162. ComponentDragger::ComponentDragger()
  56163. : constrainer (0)
  56164. {
  56165. }
  56166. ComponentDragger::~ComponentDragger()
  56167. {
  56168. }
  56169. void ComponentDragger::startDraggingComponent (Component* const componentToDrag,
  56170. ComponentBoundsConstrainer* const constrainer_)
  56171. {
  56172. jassert (componentToDrag->isValidComponent());
  56173. if (componentToDrag != 0)
  56174. {
  56175. constrainer = constrainer_;
  56176. originalPos = componentToDrag->relativePositionToGlobal (Point<int>());
  56177. }
  56178. }
  56179. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e)
  56180. {
  56181. jassert (componentToDrag->isValidComponent());
  56182. jassert (e.mods.isAnyMouseButtonDown()); // (the event has to be a drag event..)
  56183. if (componentToDrag != 0)
  56184. {
  56185. Rectangle<int> bounds (componentToDrag->getBounds().withPosition (originalPos));
  56186. const Component* const parentComp = componentToDrag->getParentComponent();
  56187. if (parentComp != 0)
  56188. bounds.setPosition (parentComp->globalPositionToRelative (originalPos));
  56189. bounds.setPosition (bounds.getPosition() + e.getOffsetFromDragStart());
  56190. if (constrainer != 0)
  56191. constrainer->setBoundsForComponent (componentToDrag, bounds, false, false, false, false);
  56192. else
  56193. componentToDrag->setBounds (bounds);
  56194. }
  56195. }
  56196. END_JUCE_NAMESPACE
  56197. /*** End of inlined file: juce_ComponentDragger.cpp ***/
  56198. /*** Start of inlined file: juce_DragAndDropContainer.cpp ***/
  56199. BEGIN_JUCE_NAMESPACE
  56200. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  56201. bool juce_performDragDropText (const String& text, bool& shouldStop);
  56202. class DragImageComponent : public Component,
  56203. public Timer
  56204. {
  56205. public:
  56206. DragImageComponent (const Image& im,
  56207. const String& desc,
  56208. Component* const sourceComponent,
  56209. Component* const mouseDragSource_,
  56210. DragAndDropContainer* const o,
  56211. const Point<int>& imageOffset_)
  56212. : image (im),
  56213. source (sourceComponent),
  56214. mouseDragSource (mouseDragSource_),
  56215. owner (o),
  56216. dragDesc (desc),
  56217. imageOffset (imageOffset_),
  56218. hasCheckedForExternalDrag (false),
  56219. drawImage (true)
  56220. {
  56221. setSize (im.getWidth(), im.getHeight());
  56222. if (mouseDragSource == 0)
  56223. mouseDragSource = source;
  56224. mouseDragSource->addMouseListener (this, false);
  56225. startTimer (200);
  56226. setInterceptsMouseClicks (false, false);
  56227. setAlwaysOnTop (true);
  56228. }
  56229. ~DragImageComponent()
  56230. {
  56231. if (owner->dragImageComponent == this)
  56232. owner->dragImageComponent.release();
  56233. if (mouseDragSource != 0)
  56234. {
  56235. mouseDragSource->removeMouseListener (this);
  56236. if (getCurrentlyOver() != 0 && getCurrentlyOver()->isInterestedInDragSource (dragDesc, source))
  56237. getCurrentlyOver()->itemDragExit (dragDesc, source);
  56238. }
  56239. }
  56240. void paint (Graphics& g)
  56241. {
  56242. if (isOpaque())
  56243. g.fillAll (Colours::white);
  56244. if (drawImage)
  56245. {
  56246. g.setOpacity (1.0f);
  56247. g.drawImageAt (image, 0, 0);
  56248. }
  56249. }
  56250. DragAndDropTarget* findTarget (const Point<int>& screenPos, Point<int>& relativePos)
  56251. {
  56252. Component* hit = getParentComponent();
  56253. if (hit == 0)
  56254. {
  56255. hit = Desktop::getInstance().findComponentAt (screenPos);
  56256. }
  56257. else
  56258. {
  56259. const Point<int> relPos (hit->globalPositionToRelative (screenPos));
  56260. hit = hit->getComponentAt (relPos.getX(), relPos.getY());
  56261. }
  56262. // (note: use a local copy of the dragDesc member in case the callback runs
  56263. // a modal loop and deletes this object before the method completes)
  56264. const String dragDescLocal (dragDesc);
  56265. while (hit != 0)
  56266. {
  56267. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  56268. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56269. {
  56270. relativePos = hit->globalPositionToRelative (screenPos);
  56271. return ddt;
  56272. }
  56273. hit = hit->getParentComponent();
  56274. }
  56275. return 0;
  56276. }
  56277. void mouseUp (const MouseEvent& e)
  56278. {
  56279. if (e.originalComponent != this)
  56280. {
  56281. if (mouseDragSource != 0)
  56282. mouseDragSource->removeMouseListener (this);
  56283. bool dropAccepted = false;
  56284. DragAndDropTarget* ddt = 0;
  56285. Point<int> relPos;
  56286. if (isVisible())
  56287. {
  56288. setVisible (false);
  56289. ddt = findTarget (e.getScreenPosition(), relPos);
  56290. // fade this component and remove it - it'll be deleted later by the timer callback
  56291. dropAccepted = ddt != 0;
  56292. setVisible (true);
  56293. if (dropAccepted || source == 0)
  56294. {
  56295. fadeOutComponent (120);
  56296. }
  56297. else
  56298. {
  56299. const Point<int> target (source->relativePositionToGlobal (Point<int> (source->getWidth() / 2,
  56300. source->getHeight() / 2)));
  56301. const Point<int> ourCentre (relativePositionToGlobal (Point<int> (getWidth() / 2,
  56302. getHeight() / 2)));
  56303. fadeOutComponent (120,
  56304. target.getX() - ourCentre.getX(),
  56305. target.getY() - ourCentre.getY());
  56306. }
  56307. }
  56308. if (getParentComponent() != 0)
  56309. getParentComponent()->removeChildComponent (this);
  56310. if (dropAccepted && ddt != 0)
  56311. {
  56312. // (note: use a local copy of the dragDesc member in case the callback runs
  56313. // a modal loop and deletes this object before the method completes)
  56314. const String dragDescLocal (dragDesc);
  56315. currentlyOverComp = 0;
  56316. ddt->itemDropped (dragDescLocal, source, relPos.getX(), relPos.getY());
  56317. }
  56318. // careful - this object could now be deleted..
  56319. }
  56320. }
  56321. void updateLocation (const bool canDoExternalDrag, const Point<int>& screenPos)
  56322. {
  56323. // (note: use a local copy of the dragDesc member in case the callback runs
  56324. // a modal loop and deletes this object before it returns)
  56325. const String dragDescLocal (dragDesc);
  56326. Point<int> newPos (screenPos + imageOffset);
  56327. if (getParentComponent() != 0)
  56328. newPos = getParentComponent()->globalPositionToRelative (newPos);
  56329. //if (newX != getX() || newY != getY())
  56330. {
  56331. setTopLeftPosition (newPos.getX(), newPos.getY());
  56332. Point<int> relPos;
  56333. DragAndDropTarget* const ddt = findTarget (screenPos, relPos);
  56334. Component* ddtComp = dynamic_cast <Component*> (ddt);
  56335. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  56336. if (ddtComp != currentlyOverComp)
  56337. {
  56338. if (currentlyOverComp != 0 && source != 0
  56339. && getCurrentlyOver()->isInterestedInDragSource (dragDescLocal, source))
  56340. {
  56341. getCurrentlyOver()->itemDragExit (dragDescLocal, source);
  56342. }
  56343. currentlyOverComp = ddtComp;
  56344. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56345. ddt->itemDragEnter (dragDescLocal, source, relPos.getX(), relPos.getY());
  56346. }
  56347. DragAndDropTarget* target = getCurrentlyOver();
  56348. if (target != 0 && target->isInterestedInDragSource (dragDescLocal, source))
  56349. target->itemDragMove (dragDescLocal, source, relPos.getX(), relPos.getY());
  56350. if (getCurrentlyOver() == 0 && canDoExternalDrag && ! hasCheckedForExternalDrag)
  56351. {
  56352. if (Desktop::getInstance().findComponentAt (screenPos) == 0)
  56353. {
  56354. hasCheckedForExternalDrag = true;
  56355. StringArray files;
  56356. bool canMoveFiles = false;
  56357. if (owner->shouldDropFilesWhenDraggedExternally (dragDescLocal, source, files, canMoveFiles)
  56358. && files.size() > 0)
  56359. {
  56360. Component::SafePointer<Component> cdw (this);
  56361. setVisible (false);
  56362. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  56363. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  56364. if (cdw != 0)
  56365. delete this;
  56366. return;
  56367. }
  56368. }
  56369. }
  56370. }
  56371. }
  56372. void mouseDrag (const MouseEvent& e)
  56373. {
  56374. if (e.originalComponent != this)
  56375. updateLocation (true, e.getScreenPosition());
  56376. }
  56377. void timerCallback()
  56378. {
  56379. if (source == 0)
  56380. {
  56381. delete this;
  56382. }
  56383. else if (! isMouseButtonDownAnywhere())
  56384. {
  56385. if (mouseDragSource != 0)
  56386. mouseDragSource->removeMouseListener (this);
  56387. delete this;
  56388. }
  56389. }
  56390. private:
  56391. Image image;
  56392. Component::SafePointer<Component> source;
  56393. Component::SafePointer<Component> mouseDragSource;
  56394. DragAndDropContainer* const owner;
  56395. Component::SafePointer<Component> currentlyOverComp;
  56396. DragAndDropTarget* getCurrentlyOver()
  56397. {
  56398. return dynamic_cast <DragAndDropTarget*> (static_cast <Component*> (currentlyOverComp));
  56399. }
  56400. String dragDesc;
  56401. const Point<int> imageOffset;
  56402. bool hasCheckedForExternalDrag, drawImage;
  56403. DragImageComponent (const DragImageComponent&);
  56404. DragImageComponent& operator= (const DragImageComponent&);
  56405. };
  56406. DragAndDropContainer::DragAndDropContainer()
  56407. {
  56408. }
  56409. DragAndDropContainer::~DragAndDropContainer()
  56410. {
  56411. dragImageComponent = 0;
  56412. }
  56413. void DragAndDropContainer::startDragging (const String& sourceDescription,
  56414. Component* sourceComponent,
  56415. const Image& dragImage_,
  56416. const bool allowDraggingToExternalWindows,
  56417. const Point<int>* imageOffsetFromMouse)
  56418. {
  56419. Image dragImage (dragImage_);
  56420. if (dragImageComponent == 0)
  56421. {
  56422. Component* const thisComp = dynamic_cast <Component*> (this);
  56423. if (thisComp == 0)
  56424. {
  56425. jassertfalse; // Your DragAndDropContainer needs to be a Component!
  56426. return;
  56427. }
  56428. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource (0);
  56429. if (draggingSource == 0 || ! draggingSource->isDragging())
  56430. {
  56431. jassertfalse; // You must call startDragging() from within a mouseDown or mouseDrag callback!
  56432. return;
  56433. }
  56434. const Point<int> lastMouseDown (Desktop::getLastMouseDownPosition());
  56435. Point<int> imageOffset;
  56436. if (dragImage.isNull())
  56437. {
  56438. dragImage = sourceComponent->createComponentSnapshot (sourceComponent->getLocalBounds())
  56439. .convertedToFormat (Image::ARGB);
  56440. dragImage.multiplyAllAlphas (0.6f);
  56441. const int lo = 150;
  56442. const int hi = 400;
  56443. Point<int> relPos (sourceComponent->globalPositionToRelative (lastMouseDown));
  56444. Point<int> clipped (dragImage.getBounds().getConstrainedPoint (relPos));
  56445. for (int y = dragImage.getHeight(); --y >= 0;)
  56446. {
  56447. const double dy = (y - clipped.getY()) * (y - clipped.getY());
  56448. for (int x = dragImage.getWidth(); --x >= 0;)
  56449. {
  56450. const int dx = x - clipped.getX();
  56451. const int distance = roundToInt (std::sqrt (dx * dx + dy));
  56452. if (distance > lo)
  56453. {
  56454. const float alpha = (distance > hi) ? 0
  56455. : (hi - distance) / (float) (hi - lo)
  56456. + Random::getSystemRandom().nextFloat() * 0.008f;
  56457. dragImage.multiplyAlphaAt (x, y, alpha);
  56458. }
  56459. }
  56460. }
  56461. imageOffset = -clipped;
  56462. }
  56463. else
  56464. {
  56465. if (imageOffsetFromMouse == 0)
  56466. imageOffset = -dragImage.getBounds().getCentre();
  56467. else
  56468. imageOffset = -(dragImage.getBounds().getConstrainedPoint (-*imageOffsetFromMouse));
  56469. }
  56470. dragImageComponent = new DragImageComponent (dragImage, sourceDescription, sourceComponent,
  56471. draggingSource->getComponentUnderMouse(), this, imageOffset);
  56472. currentDragDesc = sourceDescription;
  56473. if (allowDraggingToExternalWindows)
  56474. {
  56475. if (! Desktop::canUseSemiTransparentWindows())
  56476. dragImageComponent->setOpaque (true);
  56477. dragImageComponent->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  56478. | ComponentPeer::windowIsTemporary
  56479. | ComponentPeer::windowIgnoresKeyPresses);
  56480. }
  56481. else
  56482. thisComp->addChildComponent (dragImageComponent);
  56483. static_cast <DragImageComponent*> (static_cast <Component*> (dragImageComponent))->updateLocation (false, lastMouseDown);
  56484. dragImageComponent->setVisible (true);
  56485. }
  56486. }
  56487. bool DragAndDropContainer::isDragAndDropActive() const
  56488. {
  56489. return dragImageComponent != 0;
  56490. }
  56491. const String DragAndDropContainer::getCurrentDragDescription() const
  56492. {
  56493. return (dragImageComponent != 0) ? currentDragDesc
  56494. : String::empty;
  56495. }
  56496. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  56497. {
  56498. return c == 0 ? 0 : c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  56499. }
  56500. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  56501. {
  56502. return false;
  56503. }
  56504. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  56505. {
  56506. }
  56507. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  56508. {
  56509. }
  56510. void DragAndDropTarget::itemDragExit (const String&, Component*)
  56511. {
  56512. }
  56513. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  56514. {
  56515. return true;
  56516. }
  56517. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  56518. {
  56519. }
  56520. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  56521. {
  56522. }
  56523. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  56524. {
  56525. }
  56526. END_JUCE_NAMESPACE
  56527. /*** End of inlined file: juce_DragAndDropContainer.cpp ***/
  56528. /*** Start of inlined file: juce_MouseCursor.cpp ***/
  56529. BEGIN_JUCE_NAMESPACE
  56530. class MouseCursor::SharedCursorHandle
  56531. {
  56532. public:
  56533. explicit SharedCursorHandle (const MouseCursor::StandardCursorType type)
  56534. : handle (createStandardMouseCursor (type)),
  56535. refCount (1),
  56536. standardType (type),
  56537. isStandard (true)
  56538. {
  56539. }
  56540. SharedCursorHandle (const Image& image, const int hotSpotX, const int hotSpotY)
  56541. : handle (createMouseCursorFromImage (image, hotSpotX, hotSpotY)),
  56542. refCount (1),
  56543. standardType (MouseCursor::NormalCursor),
  56544. isStandard (false)
  56545. {
  56546. }
  56547. static SharedCursorHandle* createStandard (const MouseCursor::StandardCursorType type)
  56548. {
  56549. const ScopedLock sl (getLock());
  56550. for (int i = getCursors().size(); --i >= 0;)
  56551. {
  56552. SharedCursorHandle* const sc = getCursors().getUnchecked(i);
  56553. if (sc->standardType == type)
  56554. return sc->retain();
  56555. }
  56556. SharedCursorHandle* const sc = new SharedCursorHandle (type);
  56557. getCursors().add (sc);
  56558. return sc;
  56559. }
  56560. SharedCursorHandle* retain() throw()
  56561. {
  56562. ++refCount;
  56563. return this;
  56564. }
  56565. void release()
  56566. {
  56567. if (--refCount == 0)
  56568. {
  56569. if (isStandard)
  56570. {
  56571. const ScopedLock sl (getLock());
  56572. getCursors().removeValue (this);
  56573. }
  56574. delete this;
  56575. }
  56576. }
  56577. void* getHandle() const throw() { return handle; }
  56578. juce_UseDebuggingNewOperator
  56579. private:
  56580. void* const handle;
  56581. Atomic <int> refCount;
  56582. const MouseCursor::StandardCursorType standardType;
  56583. const bool isStandard;
  56584. static CriticalSection& getLock()
  56585. {
  56586. static CriticalSection lock;
  56587. return lock;
  56588. }
  56589. static Array <SharedCursorHandle*>& getCursors()
  56590. {
  56591. static Array <SharedCursorHandle*> cursors;
  56592. return cursors;
  56593. }
  56594. ~SharedCursorHandle()
  56595. {
  56596. deleteMouseCursor (handle, isStandard);
  56597. }
  56598. SharedCursorHandle& operator= (const SharedCursorHandle&);
  56599. };
  56600. MouseCursor::MouseCursor()
  56601. : cursorHandle (SharedCursorHandle::createStandard (NormalCursor))
  56602. {
  56603. jassert (cursorHandle != 0);
  56604. }
  56605. MouseCursor::MouseCursor (const StandardCursorType type)
  56606. : cursorHandle (SharedCursorHandle::createStandard (type))
  56607. {
  56608. jassert (cursorHandle != 0);
  56609. }
  56610. MouseCursor::MouseCursor (const Image& image, const int hotSpotX, const int hotSpotY)
  56611. : cursorHandle (new SharedCursorHandle (image, hotSpotX, hotSpotY))
  56612. {
  56613. }
  56614. MouseCursor::MouseCursor (const MouseCursor& other)
  56615. : cursorHandle (other.cursorHandle->retain())
  56616. {
  56617. }
  56618. MouseCursor::~MouseCursor()
  56619. {
  56620. cursorHandle->release();
  56621. }
  56622. MouseCursor& MouseCursor::operator= (const MouseCursor& other)
  56623. {
  56624. other.cursorHandle->retain();
  56625. cursorHandle->release();
  56626. cursorHandle = other.cursorHandle;
  56627. return *this;
  56628. }
  56629. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  56630. {
  56631. return getHandle() == other.getHandle();
  56632. }
  56633. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  56634. {
  56635. return getHandle() != other.getHandle();
  56636. }
  56637. void* MouseCursor::getHandle() const throw()
  56638. {
  56639. return cursorHandle->getHandle();
  56640. }
  56641. void MouseCursor::showWaitCursor()
  56642. {
  56643. Desktop::getInstance().getMainMouseSource().showMouseCursor (MouseCursor::WaitCursor);
  56644. }
  56645. void MouseCursor::hideWaitCursor()
  56646. {
  56647. Desktop::getInstance().getMainMouseSource().revealCursor();
  56648. }
  56649. END_JUCE_NAMESPACE
  56650. /*** End of inlined file: juce_MouseCursor.cpp ***/
  56651. /*** Start of inlined file: juce_MouseEvent.cpp ***/
  56652. BEGIN_JUCE_NAMESPACE
  56653. MouseEvent::MouseEvent (MouseInputSource& source_,
  56654. const Point<int>& position,
  56655. const ModifierKeys& mods_,
  56656. Component* const eventComponent_,
  56657. Component* const originator,
  56658. const Time& eventTime_,
  56659. const Point<int> mouseDownPos_,
  56660. const Time& mouseDownTime_,
  56661. const int numberOfClicks_,
  56662. const bool mouseWasDragged) throw()
  56663. : x (position.getX()),
  56664. y (position.getY()),
  56665. mods (mods_),
  56666. eventComponent (eventComponent_),
  56667. originalComponent (originator),
  56668. eventTime (eventTime_),
  56669. source (source_),
  56670. mouseDownPos (mouseDownPos_),
  56671. mouseDownTime (mouseDownTime_),
  56672. numberOfClicks (numberOfClicks_),
  56673. wasMovedSinceMouseDown (mouseWasDragged)
  56674. {
  56675. }
  56676. MouseEvent::~MouseEvent() throw()
  56677. {
  56678. }
  56679. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  56680. {
  56681. if (otherComponent == 0)
  56682. {
  56683. jassertfalse;
  56684. return *this;
  56685. }
  56686. return MouseEvent (source, eventComponent->relativePositionToOtherComponent (otherComponent, getPosition()),
  56687. mods, otherComponent, originalComponent, eventTime,
  56688. eventComponent->relativePositionToOtherComponent (otherComponent, mouseDownPos),
  56689. mouseDownTime, numberOfClicks, wasMovedSinceMouseDown);
  56690. }
  56691. const MouseEvent MouseEvent::withNewPosition (const Point<int>& newPosition) const throw()
  56692. {
  56693. return MouseEvent (source, newPosition, mods, eventComponent, originalComponent,
  56694. eventTime, mouseDownPos, mouseDownTime,
  56695. numberOfClicks, wasMovedSinceMouseDown);
  56696. }
  56697. bool MouseEvent::mouseWasClicked() const throw()
  56698. {
  56699. return ! wasMovedSinceMouseDown;
  56700. }
  56701. int MouseEvent::getMouseDownX() const throw()
  56702. {
  56703. return mouseDownPos.getX();
  56704. }
  56705. int MouseEvent::getMouseDownY() const throw()
  56706. {
  56707. return mouseDownPos.getY();
  56708. }
  56709. const Point<int> MouseEvent::getMouseDownPosition() const throw()
  56710. {
  56711. return mouseDownPos;
  56712. }
  56713. int MouseEvent::getDistanceFromDragStartX() const throw()
  56714. {
  56715. return x - mouseDownPos.getX();
  56716. }
  56717. int MouseEvent::getDistanceFromDragStartY() const throw()
  56718. {
  56719. return y - mouseDownPos.getY();
  56720. }
  56721. int MouseEvent::getDistanceFromDragStart() const throw()
  56722. {
  56723. return mouseDownPos.getDistanceFrom (getPosition());
  56724. }
  56725. const Point<int> MouseEvent::getOffsetFromDragStart() const throw()
  56726. {
  56727. return getPosition() - mouseDownPos;
  56728. }
  56729. int MouseEvent::getLengthOfMousePress() const throw()
  56730. {
  56731. if (mouseDownTime.toMilliseconds() > 0)
  56732. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  56733. return 0;
  56734. }
  56735. const Point<int> MouseEvent::getPosition() const throw()
  56736. {
  56737. return Point<int> (x, y);
  56738. }
  56739. int MouseEvent::getScreenX() const
  56740. {
  56741. return getScreenPosition().getX();
  56742. }
  56743. int MouseEvent::getScreenY() const
  56744. {
  56745. return getScreenPosition().getY();
  56746. }
  56747. const Point<int> MouseEvent::getScreenPosition() const
  56748. {
  56749. return eventComponent->relativePositionToGlobal (Point<int> (x, y));
  56750. }
  56751. int MouseEvent::getMouseDownScreenX() const
  56752. {
  56753. return getMouseDownScreenPosition().getX();
  56754. }
  56755. int MouseEvent::getMouseDownScreenY() const
  56756. {
  56757. return getMouseDownScreenPosition().getY();
  56758. }
  56759. const Point<int> MouseEvent::getMouseDownScreenPosition() const
  56760. {
  56761. return eventComponent->relativePositionToGlobal (mouseDownPos);
  56762. }
  56763. int MouseEvent::doubleClickTimeOutMs = 400;
  56764. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  56765. {
  56766. doubleClickTimeOutMs = newTime;
  56767. }
  56768. int MouseEvent::getDoubleClickTimeout() throw()
  56769. {
  56770. return doubleClickTimeOutMs;
  56771. }
  56772. END_JUCE_NAMESPACE
  56773. /*** End of inlined file: juce_MouseEvent.cpp ***/
  56774. /*** Start of inlined file: juce_MouseInputSource.cpp ***/
  56775. BEGIN_JUCE_NAMESPACE
  56776. class MouseInputSourceInternal : public AsyncUpdater
  56777. {
  56778. public:
  56779. MouseInputSourceInternal (MouseInputSource& source_, const int index_, const bool isMouseDevice_)
  56780. : index (index_), isMouseDevice (isMouseDevice_), source (source_), lastPeer (0), lastTime (0),
  56781. isUnboundedMouseModeOn (false), isCursorVisibleUntilOffscreen (false), currentCursorHandle (0),
  56782. mouseEventCounter (0)
  56783. {
  56784. zerostruct (mouseDowns);
  56785. }
  56786. ~MouseInputSourceInternal()
  56787. {
  56788. }
  56789. bool isDragging() const throw()
  56790. {
  56791. return buttonState.isAnyMouseButtonDown();
  56792. }
  56793. Component* getComponentUnderMouse() const
  56794. {
  56795. return static_cast <Component*> (componentUnderMouse);
  56796. }
  56797. const ModifierKeys getCurrentModifiers() const
  56798. {
  56799. return ModifierKeys::getCurrentModifiers().withoutMouseButtons().withFlags (buttonState.getRawFlags());
  56800. }
  56801. ComponentPeer* getPeer()
  56802. {
  56803. if (! ComponentPeer::isValidPeer (lastPeer))
  56804. lastPeer = 0;
  56805. return lastPeer;
  56806. }
  56807. Component* findComponentAt (const Point<int>& screenPos)
  56808. {
  56809. ComponentPeer* const peer = getPeer();
  56810. if (peer != 0)
  56811. {
  56812. Component* const comp = peer->getComponent();
  56813. const Point<int> relativePos (comp->globalPositionToRelative (screenPos));
  56814. // (the contains() call is needed to test for overlapping desktop windows)
  56815. if (comp->contains (relativePos.getX(), relativePos.getY()))
  56816. return comp->getComponentAt (relativePos);
  56817. }
  56818. return 0;
  56819. }
  56820. const Point<int> getScreenPosition() const throw()
  56821. {
  56822. return lastScreenPos + unboundedMouseOffset;
  56823. }
  56824. void sendMouseEnter (Component* const comp, const Point<int>& screenPos, const int64 time)
  56825. {
  56826. //DBG ("Mouse " + String (source.getIndex()) + " enter: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56827. comp->internalMouseEnter (source, comp->globalPositionToRelative (screenPos), time);
  56828. }
  56829. void sendMouseExit (Component* const comp, const Point<int>& screenPos, const int64 time)
  56830. {
  56831. //DBG ("Mouse " + String (source.getIndex()) + " exit: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56832. comp->internalMouseExit (source, comp->globalPositionToRelative (screenPos), time);
  56833. }
  56834. void sendMouseMove (Component* const comp, const Point<int>& screenPos, const int64 time)
  56835. {
  56836. //DBG ("Mouse " + String (source.getIndex()) + " move: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56837. comp->internalMouseMove (source, comp->globalPositionToRelative (screenPos), time);
  56838. }
  56839. void sendMouseDown (Component* const comp, const Point<int>& screenPos, const int64 time)
  56840. {
  56841. //DBG ("Mouse " + String (source.getIndex()) + " down: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56842. comp->internalMouseDown (source, comp->globalPositionToRelative (screenPos), time);
  56843. }
  56844. void sendMouseDrag (Component* const comp, const Point<int>& screenPos, const int64 time)
  56845. {
  56846. //DBG ("Mouse " + String (source.getIndex()) + " drag: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56847. comp->internalMouseDrag (source, comp->globalPositionToRelative (screenPos), time);
  56848. }
  56849. void sendMouseUp (Component* const comp, const Point<int>& screenPos, const int64 time)
  56850. {
  56851. //DBG ("Mouse " + String (source.getIndex()) + " up: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56852. comp->internalMouseUp (source, comp->globalPositionToRelative (screenPos), time, getCurrentModifiers());
  56853. }
  56854. void sendMouseWheel (Component* const comp, const Point<int>& screenPos, const int64 time, float x, float y)
  56855. {
  56856. //DBG ("Mouse " + String (source.getIndex()) + " wheel: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  56857. comp->internalMouseWheel (source, comp->globalPositionToRelative (screenPos), time, x, y);
  56858. }
  56859. // (returns true if the button change caused a modal event loop)
  56860. bool setButtons (const Point<int>& screenPos, const int64 time, const ModifierKeys& newButtonState)
  56861. {
  56862. if (buttonState == newButtonState)
  56863. return false;
  56864. setScreenPos (screenPos, time, false);
  56865. // (ignore secondary clicks when there's already a button down)
  56866. if (buttonState.isAnyMouseButtonDown() == newButtonState.isAnyMouseButtonDown())
  56867. {
  56868. buttonState = newButtonState;
  56869. return false;
  56870. }
  56871. const int lastCounter = mouseEventCounter;
  56872. if (buttonState.isAnyMouseButtonDown())
  56873. {
  56874. Component* const current = getComponentUnderMouse();
  56875. if (current != 0)
  56876. sendMouseUp (current, screenPos + unboundedMouseOffset, time);
  56877. enableUnboundedMouseMovement (false, false);
  56878. }
  56879. buttonState = newButtonState;
  56880. if (buttonState.isAnyMouseButtonDown())
  56881. {
  56882. Desktop::getInstance().incrementMouseClickCounter();
  56883. Component* const current = getComponentUnderMouse();
  56884. if (current != 0)
  56885. {
  56886. registerMouseDown (screenPos, time, current);
  56887. sendMouseDown (current, screenPos, time);
  56888. }
  56889. }
  56890. return lastCounter != mouseEventCounter;
  56891. }
  56892. void setComponentUnderMouse (Component* const newComponent, const Point<int>& screenPos, const int64 time)
  56893. {
  56894. Component* current = getComponentUnderMouse();
  56895. if (newComponent != current)
  56896. {
  56897. Component::SafePointer<Component> safeNewComp (newComponent);
  56898. const ModifierKeys originalButtonState (buttonState);
  56899. if (current != 0)
  56900. {
  56901. setButtons (screenPos, time, ModifierKeys());
  56902. sendMouseExit (current, screenPos, time);
  56903. buttonState = originalButtonState;
  56904. }
  56905. componentUnderMouse = safeNewComp;
  56906. current = getComponentUnderMouse();
  56907. if (current != 0)
  56908. sendMouseEnter (current, screenPos, time);
  56909. revealCursor (false);
  56910. setButtons (screenPos, time, originalButtonState);
  56911. }
  56912. }
  56913. void setPeer (ComponentPeer* const newPeer, const Point<int>& screenPos, const int64 time)
  56914. {
  56915. ModifierKeys::updateCurrentModifiers();
  56916. if (newPeer != lastPeer)
  56917. {
  56918. setComponentUnderMouse (0, screenPos, time);
  56919. lastPeer = newPeer;
  56920. setComponentUnderMouse (findComponentAt (screenPos), screenPos, time);
  56921. }
  56922. }
  56923. void setScreenPos (const Point<int>& newScreenPos, const int64 time, const bool forceUpdate)
  56924. {
  56925. if (! isDragging())
  56926. setComponentUnderMouse (findComponentAt (newScreenPos), newScreenPos, time);
  56927. if (newScreenPos != lastScreenPos || forceUpdate)
  56928. {
  56929. cancelPendingUpdate();
  56930. lastScreenPos = newScreenPos;
  56931. Component* const current = getComponentUnderMouse();
  56932. if (current != 0)
  56933. {
  56934. if (isDragging())
  56935. {
  56936. registerMouseDrag (newScreenPos);
  56937. sendMouseDrag (current, newScreenPos + unboundedMouseOffset, time);
  56938. if (isUnboundedMouseModeOn)
  56939. handleUnboundedDrag (current);
  56940. }
  56941. else
  56942. {
  56943. sendMouseMove (current, newScreenPos, time);
  56944. }
  56945. }
  56946. revealCursor (false);
  56947. }
  56948. }
  56949. void handleEvent (ComponentPeer* const newPeer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& newMods)
  56950. {
  56951. jassert (newPeer != 0);
  56952. lastTime = time;
  56953. ++mouseEventCounter;
  56954. const Point<int> screenPos (newPeer->relativePositionToGlobal (positionWithinPeer));
  56955. if (isDragging() && newMods.isAnyMouseButtonDown())
  56956. {
  56957. setScreenPos (screenPos, time, false);
  56958. }
  56959. else
  56960. {
  56961. setPeer (newPeer, screenPos, time);
  56962. ComponentPeer* peer = getPeer();
  56963. if (peer != 0)
  56964. {
  56965. if (setButtons (screenPos, time, newMods))
  56966. return; // some modal events have been dispatched, so the current event is now out-of-date
  56967. peer = getPeer();
  56968. if (peer != 0)
  56969. setScreenPos (screenPos, time, false);
  56970. }
  56971. }
  56972. }
  56973. void handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, int64 time, float x, float y)
  56974. {
  56975. jassert (peer != 0);
  56976. lastTime = time;
  56977. ++mouseEventCounter;
  56978. const Point<int> screenPos (peer->relativePositionToGlobal (positionWithinPeer));
  56979. setPeer (peer, screenPos, time);
  56980. setScreenPos (screenPos, time, false);
  56981. triggerFakeMove();
  56982. if (! isDragging())
  56983. {
  56984. Component* current = getComponentUnderMouse();
  56985. if (current != 0)
  56986. sendMouseWheel (current, screenPos, time, x, y);
  56987. }
  56988. }
  56989. const Time getLastMouseDownTime() const throw()
  56990. {
  56991. return Time (mouseDowns[0].time);
  56992. }
  56993. const Point<int> getLastMouseDownPosition() const throw()
  56994. {
  56995. return mouseDowns[0].position;
  56996. }
  56997. int getNumberOfMultipleClicks() const throw()
  56998. {
  56999. int numClicks = 0;
  57000. if (mouseDowns[0].time != 0)
  57001. {
  57002. if (! mouseMovedSignificantlySincePressed)
  57003. ++numClicks;
  57004. for (int i = 1; i < numElementsInArray (mouseDowns); ++i)
  57005. {
  57006. if (mouseDowns[0].time - mouseDowns[i].time < (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))
  57007. && abs (mouseDowns[0].position.getX() - mouseDowns[i].position.getX()) < 8
  57008. && abs (mouseDowns[0].position.getY() - mouseDowns[i].position.getY()) < 8)
  57009. {
  57010. ++numClicks;
  57011. }
  57012. else
  57013. {
  57014. break;
  57015. }
  57016. }
  57017. }
  57018. return numClicks;
  57019. }
  57020. bool hasMouseMovedSignificantlySincePressed() const throw()
  57021. {
  57022. return mouseMovedSignificantlySincePressed
  57023. || lastTime > mouseDowns[0].time + 300;
  57024. }
  57025. void triggerFakeMove()
  57026. {
  57027. triggerAsyncUpdate();
  57028. }
  57029. void handleAsyncUpdate()
  57030. {
  57031. if (! isDragging())
  57032. setScreenPos (Desktop::getMousePosition(), jmax (lastTime, Time::currentTimeMillis()), true);
  57033. }
  57034. void enableUnboundedMouseMovement (bool enable, bool keepCursorVisibleUntilOffscreen)
  57035. {
  57036. enable = enable && isDragging();
  57037. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  57038. if (enable != isUnboundedMouseModeOn)
  57039. {
  57040. if ((! enable) && ((! isCursorVisibleUntilOffscreen) || ! unboundedMouseOffset.isOrigin()))
  57041. {
  57042. // when released, return the mouse to within the component's bounds
  57043. Component* current = getComponentUnderMouse();
  57044. if (current != 0)
  57045. Desktop::setMousePosition (current->getScreenBounds()
  57046. .getConstrainedPoint (current->getMouseXYRelative()));
  57047. }
  57048. isUnboundedMouseModeOn = enable;
  57049. unboundedMouseOffset = Point<int>();
  57050. revealCursor (true);
  57051. }
  57052. }
  57053. void handleUnboundedDrag (Component* current)
  57054. {
  57055. const Rectangle<int> screenArea (current->getParentMonitorArea().expanded (-2, -2));
  57056. if (! screenArea.contains (lastScreenPos))
  57057. {
  57058. const Point<int> componentCentre (current->getScreenBounds().getCentre());
  57059. unboundedMouseOffset += (lastScreenPos - componentCentre);
  57060. Desktop::setMousePosition (componentCentre);
  57061. }
  57062. else if (isCursorVisibleUntilOffscreen
  57063. && (! unboundedMouseOffset.isOrigin())
  57064. && screenArea.contains (lastScreenPos + unboundedMouseOffset))
  57065. {
  57066. Desktop::setMousePosition (lastScreenPos + unboundedMouseOffset);
  57067. unboundedMouseOffset = Point<int>();
  57068. }
  57069. }
  57070. void showMouseCursor (MouseCursor cursor, bool forcedUpdate)
  57071. {
  57072. if (isUnboundedMouseModeOn && ((! unboundedMouseOffset.isOrigin()) || ! isCursorVisibleUntilOffscreen))
  57073. {
  57074. cursor = MouseCursor::NoCursor;
  57075. forcedUpdate = true;
  57076. }
  57077. if (forcedUpdate || cursor.getHandle() != currentCursorHandle)
  57078. {
  57079. currentCursorHandle = cursor.getHandle();
  57080. cursor.showInWindow (getPeer());
  57081. }
  57082. }
  57083. void hideCursor()
  57084. {
  57085. showMouseCursor (MouseCursor::NoCursor, true);
  57086. }
  57087. void revealCursor (bool forcedUpdate)
  57088. {
  57089. MouseCursor mc (MouseCursor::NormalCursor);
  57090. Component* current = getComponentUnderMouse();
  57091. if (current != 0)
  57092. mc = current->getLookAndFeel().getMouseCursorFor (*current);
  57093. showMouseCursor (mc, forcedUpdate);
  57094. }
  57095. int index;
  57096. bool isMouseDevice;
  57097. Point<int> lastScreenPos;
  57098. ModifierKeys buttonState;
  57099. private:
  57100. MouseInputSource& source;
  57101. Component::SafePointer<Component> componentUnderMouse;
  57102. ComponentPeer* lastPeer;
  57103. Point<int> unboundedMouseOffset;
  57104. bool isUnboundedMouseModeOn, isCursorVisibleUntilOffscreen;
  57105. void* currentCursorHandle;
  57106. int mouseEventCounter;
  57107. struct RecentMouseDown
  57108. {
  57109. Point<int> position;
  57110. int64 time;
  57111. Component* component;
  57112. };
  57113. RecentMouseDown mouseDowns[4];
  57114. bool mouseMovedSignificantlySincePressed;
  57115. int64 lastTime;
  57116. void registerMouseDown (const Point<int>& screenPos, const int64 time, Component* const component) throw()
  57117. {
  57118. for (int i = numElementsInArray (mouseDowns); --i > 0;)
  57119. mouseDowns[i] = mouseDowns[i - 1];
  57120. mouseDowns[0].position = screenPos;
  57121. mouseDowns[0].time = time;
  57122. mouseDowns[0].component = component;
  57123. mouseMovedSignificantlySincePressed = false;
  57124. }
  57125. void registerMouseDrag (const Point<int>& screenPos) throw()
  57126. {
  57127. mouseMovedSignificantlySincePressed = mouseMovedSignificantlySincePressed
  57128. || mouseDowns[0].position.getDistanceFrom (screenPos) >= 4;
  57129. }
  57130. MouseInputSourceInternal (const MouseInputSourceInternal&);
  57131. MouseInputSourceInternal& operator= (const MouseInputSourceInternal&);
  57132. };
  57133. MouseInputSource::MouseInputSource (const int index, const bool isMouseDevice)
  57134. {
  57135. pimpl = new MouseInputSourceInternal (*this, index, isMouseDevice);
  57136. }
  57137. MouseInputSource::~MouseInputSource()
  57138. {
  57139. }
  57140. bool MouseInputSource::isMouse() const { return pimpl->isMouseDevice; }
  57141. bool MouseInputSource::isTouch() const { return ! isMouse(); }
  57142. bool MouseInputSource::canHover() const { return isMouse(); }
  57143. bool MouseInputSource::hasMouseWheel() const { return isMouse(); }
  57144. int MouseInputSource::getIndex() const { return pimpl->index; }
  57145. bool MouseInputSource::isDragging() const { return pimpl->isDragging(); }
  57146. const Point<int> MouseInputSource::getScreenPosition() const { return pimpl->getScreenPosition(); }
  57147. const ModifierKeys MouseInputSource::getCurrentModifiers() const { return pimpl->getCurrentModifiers(); }
  57148. Component* MouseInputSource::getComponentUnderMouse() const { return pimpl->getComponentUnderMouse(); }
  57149. void MouseInputSource::triggerFakeMove() const { pimpl->triggerFakeMove(); }
  57150. int MouseInputSource::getNumberOfMultipleClicks() const throw() { return pimpl->getNumberOfMultipleClicks(); }
  57151. const Time MouseInputSource::getLastMouseDownTime() const throw() { return pimpl->getLastMouseDownTime(); }
  57152. const Point<int> MouseInputSource::getLastMouseDownPosition() const throw() { return pimpl->getLastMouseDownPosition(); }
  57153. bool MouseInputSource::hasMouseMovedSignificantlySincePressed() const throw() { return pimpl->hasMouseMovedSignificantlySincePressed(); }
  57154. bool MouseInputSource::canDoUnboundedMovement() const throw() { return isMouse(); }
  57155. void MouseInputSource::enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen) { pimpl->enableUnboundedMouseMovement (isEnabled, keepCursorVisibleUntilOffscreen); }
  57156. bool MouseInputSource::hasMouseCursor() const throw() { return isMouse(); }
  57157. void MouseInputSource::showMouseCursor (const MouseCursor& cursor) { pimpl->showMouseCursor (cursor, false); }
  57158. void MouseInputSource::hideCursor() { pimpl->hideCursor(); }
  57159. void MouseInputSource::revealCursor() { pimpl->revealCursor (false); }
  57160. void MouseInputSource::forceMouseCursorUpdate() { pimpl->revealCursor (true); }
  57161. void MouseInputSource::handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& mods)
  57162. {
  57163. pimpl->handleEvent (peer, positionWithinPeer, time, mods.withOnlyMouseButtons());
  57164. }
  57165. void MouseInputSource::handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  57166. {
  57167. pimpl->handleWheel (peer, positionWithinPeer, time, x, y);
  57168. }
  57169. END_JUCE_NAMESPACE
  57170. /*** End of inlined file: juce_MouseInputSource.cpp ***/
  57171. /*** Start of inlined file: juce_MouseHoverDetector.cpp ***/
  57172. BEGIN_JUCE_NAMESPACE
  57173. MouseHoverDetector::MouseHoverDetector (const int hoverTimeMillisecs_)
  57174. : source (0),
  57175. hoverTimeMillisecs (hoverTimeMillisecs_),
  57176. hasJustHovered (false)
  57177. {
  57178. internalTimer.owner = this;
  57179. }
  57180. MouseHoverDetector::~MouseHoverDetector()
  57181. {
  57182. setHoverComponent (0);
  57183. }
  57184. void MouseHoverDetector::setHoverTimeMillisecs (const int newTimeInMillisecs)
  57185. {
  57186. hoverTimeMillisecs = newTimeInMillisecs;
  57187. }
  57188. void MouseHoverDetector::setHoverComponent (Component* const newSourceComponent)
  57189. {
  57190. if (source != newSourceComponent)
  57191. {
  57192. internalTimer.stopTimer();
  57193. hasJustHovered = false;
  57194. if (source != 0)
  57195. {
  57196. // ! you need to delete the hover detector before deleting its component
  57197. jassert (source->isValidComponent());
  57198. source->removeMouseListener (&internalTimer);
  57199. }
  57200. source = newSourceComponent;
  57201. if (newSourceComponent != 0)
  57202. newSourceComponent->addMouseListener (&internalTimer, false);
  57203. }
  57204. }
  57205. void MouseHoverDetector::hoverTimerCallback()
  57206. {
  57207. internalTimer.stopTimer();
  57208. if (source != 0)
  57209. {
  57210. const Point<int> pos (source->getMouseXYRelative());
  57211. if (source->reallyContains (pos.getX(), pos.getY(), false))
  57212. {
  57213. hasJustHovered = true;
  57214. mouseHovered (pos.getX(), pos.getY());
  57215. }
  57216. }
  57217. }
  57218. void MouseHoverDetector::checkJustHoveredCallback()
  57219. {
  57220. if (hasJustHovered)
  57221. {
  57222. hasJustHovered = false;
  57223. mouseMovedAfterHover();
  57224. }
  57225. }
  57226. void MouseHoverDetector::HoverDetectorInternal::timerCallback()
  57227. {
  57228. owner->hoverTimerCallback();
  57229. }
  57230. void MouseHoverDetector::HoverDetectorInternal::mouseEnter (const MouseEvent&)
  57231. {
  57232. stopTimer();
  57233. owner->checkJustHoveredCallback();
  57234. }
  57235. void MouseHoverDetector::HoverDetectorInternal::mouseExit (const MouseEvent&)
  57236. {
  57237. stopTimer();
  57238. owner->checkJustHoveredCallback();
  57239. }
  57240. void MouseHoverDetector::HoverDetectorInternal::mouseDown (const MouseEvent&)
  57241. {
  57242. stopTimer();
  57243. owner->checkJustHoveredCallback();
  57244. }
  57245. void MouseHoverDetector::HoverDetectorInternal::mouseUp (const MouseEvent&)
  57246. {
  57247. stopTimer();
  57248. owner->checkJustHoveredCallback();
  57249. }
  57250. void MouseHoverDetector::HoverDetectorInternal::mouseMove (const MouseEvent& e)
  57251. {
  57252. if (lastX != e.x || lastY != e.y) // to avoid fake mouse-moves setting it off
  57253. {
  57254. lastX = e.x;
  57255. lastY = e.y;
  57256. if (owner->source != 0)
  57257. startTimer (owner->hoverTimeMillisecs);
  57258. owner->checkJustHoveredCallback();
  57259. }
  57260. }
  57261. void MouseHoverDetector::HoverDetectorInternal::mouseWheelMove (const MouseEvent&, float, float)
  57262. {
  57263. stopTimer();
  57264. owner->checkJustHoveredCallback();
  57265. }
  57266. END_JUCE_NAMESPACE
  57267. /*** End of inlined file: juce_MouseHoverDetector.cpp ***/
  57268. /*** Start of inlined file: juce_MouseListener.cpp ***/
  57269. BEGIN_JUCE_NAMESPACE
  57270. void MouseListener::mouseEnter (const MouseEvent&)
  57271. {
  57272. }
  57273. void MouseListener::mouseExit (const MouseEvent&)
  57274. {
  57275. }
  57276. void MouseListener::mouseDown (const MouseEvent&)
  57277. {
  57278. }
  57279. void MouseListener::mouseUp (const MouseEvent&)
  57280. {
  57281. }
  57282. void MouseListener::mouseDrag (const MouseEvent&)
  57283. {
  57284. }
  57285. void MouseListener::mouseMove (const MouseEvent&)
  57286. {
  57287. }
  57288. void MouseListener::mouseDoubleClick (const MouseEvent&)
  57289. {
  57290. }
  57291. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  57292. {
  57293. }
  57294. END_JUCE_NAMESPACE
  57295. /*** End of inlined file: juce_MouseListener.cpp ***/
  57296. /*** Start of inlined file: juce_BooleanPropertyComponent.cpp ***/
  57297. BEGIN_JUCE_NAMESPACE
  57298. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  57299. const String& buttonTextWhenTrue,
  57300. const String& buttonTextWhenFalse)
  57301. : PropertyComponent (name),
  57302. onText (buttonTextWhenTrue),
  57303. offText (buttonTextWhenFalse)
  57304. {
  57305. addAndMakeVisible (&button);
  57306. button.setClickingTogglesState (false);
  57307. button.addButtonListener (this);
  57308. }
  57309. BooleanPropertyComponent::BooleanPropertyComponent (const Value& valueToControl,
  57310. const String& name,
  57311. const String& buttonText)
  57312. : PropertyComponent (name),
  57313. onText (buttonText),
  57314. offText (buttonText)
  57315. {
  57316. addAndMakeVisible (&button);
  57317. button.setClickingTogglesState (false);
  57318. button.setButtonText (buttonText);
  57319. button.getToggleStateValue().referTo (valueToControl);
  57320. button.setClickingTogglesState (true);
  57321. }
  57322. BooleanPropertyComponent::~BooleanPropertyComponent()
  57323. {
  57324. }
  57325. void BooleanPropertyComponent::setState (const bool newState)
  57326. {
  57327. button.setToggleState (newState, true);
  57328. }
  57329. bool BooleanPropertyComponent::getState() const
  57330. {
  57331. return button.getToggleState();
  57332. }
  57333. void BooleanPropertyComponent::paint (Graphics& g)
  57334. {
  57335. PropertyComponent::paint (g);
  57336. g.setColour (Colours::white);
  57337. g.fillRect (button.getBounds());
  57338. g.setColour (findColour (ComboBox::outlineColourId));
  57339. g.drawRect (button.getBounds());
  57340. }
  57341. void BooleanPropertyComponent::refresh()
  57342. {
  57343. button.setToggleState (getState(), false);
  57344. button.setButtonText (button.getToggleState() ? onText : offText);
  57345. }
  57346. void BooleanPropertyComponent::buttonClicked (Button*)
  57347. {
  57348. setState (! getState());
  57349. }
  57350. END_JUCE_NAMESPACE
  57351. /*** End of inlined file: juce_BooleanPropertyComponent.cpp ***/
  57352. /*** Start of inlined file: juce_ButtonPropertyComponent.cpp ***/
  57353. BEGIN_JUCE_NAMESPACE
  57354. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  57355. const bool triggerOnMouseDown)
  57356. : PropertyComponent (name)
  57357. {
  57358. addAndMakeVisible (&button);
  57359. button.setTriggeredOnMouseDown (triggerOnMouseDown);
  57360. button.addButtonListener (this);
  57361. }
  57362. ButtonPropertyComponent::~ButtonPropertyComponent()
  57363. {
  57364. }
  57365. void ButtonPropertyComponent::refresh()
  57366. {
  57367. button.setButtonText (getButtonText());
  57368. }
  57369. void ButtonPropertyComponent::buttonClicked (Button*)
  57370. {
  57371. buttonClicked();
  57372. }
  57373. END_JUCE_NAMESPACE
  57374. /*** End of inlined file: juce_ButtonPropertyComponent.cpp ***/
  57375. /*** Start of inlined file: juce_ChoicePropertyComponent.cpp ***/
  57376. BEGIN_JUCE_NAMESPACE
  57377. class ChoicePropertyComponent::RemapperValueSource : public Value::ValueSource,
  57378. public Value::Listener
  57379. {
  57380. public:
  57381. RemapperValueSource (const Value& sourceValue_, const Array<var>& mappings_)
  57382. : sourceValue (sourceValue_),
  57383. mappings (mappings_)
  57384. {
  57385. sourceValue.addListener (this);
  57386. }
  57387. ~RemapperValueSource() {}
  57388. const var getValue() const
  57389. {
  57390. return mappings.indexOf (sourceValue.getValue()) + 1;
  57391. }
  57392. void setValue (const var& newValue)
  57393. {
  57394. const var remappedVal (mappings [(int) newValue - 1]);
  57395. if (remappedVal != sourceValue)
  57396. sourceValue = remappedVal;
  57397. }
  57398. void valueChanged (Value&)
  57399. {
  57400. sendChangeMessage (true);
  57401. }
  57402. juce_UseDebuggingNewOperator
  57403. protected:
  57404. Value sourceValue;
  57405. Array<var> mappings;
  57406. RemapperValueSource (const RemapperValueSource&);
  57407. const RemapperValueSource& operator= (const RemapperValueSource&);
  57408. };
  57409. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  57410. : PropertyComponent (name),
  57411. isCustomClass (true)
  57412. {
  57413. }
  57414. ChoicePropertyComponent::ChoicePropertyComponent (const Value& valueToControl,
  57415. const String& name,
  57416. const StringArray& choices_,
  57417. const Array <var>& correspondingValues)
  57418. : PropertyComponent (name),
  57419. choices (choices_),
  57420. isCustomClass (false)
  57421. {
  57422. // The array of corresponding values must contain one value for each of the items in
  57423. // the choices array!
  57424. jassert (correspondingValues.size() == choices.size());
  57425. createComboBox();
  57426. comboBox.getSelectedIdAsValue().referTo (Value (new RemapperValueSource (valueToControl, correspondingValues)));
  57427. }
  57428. ChoicePropertyComponent::~ChoicePropertyComponent()
  57429. {
  57430. }
  57431. void ChoicePropertyComponent::createComboBox()
  57432. {
  57433. addAndMakeVisible (&comboBox);
  57434. for (int i = 0; i < choices.size(); ++i)
  57435. {
  57436. if (choices[i].isNotEmpty())
  57437. comboBox.addItem (choices[i], i + 1);
  57438. else
  57439. comboBox.addSeparator();
  57440. }
  57441. comboBox.setEditableText (false);
  57442. }
  57443. void ChoicePropertyComponent::setIndex (const int /*newIndex*/)
  57444. {
  57445. jassertfalse; // you need to override this method in your subclass!
  57446. }
  57447. int ChoicePropertyComponent::getIndex() const
  57448. {
  57449. jassertfalse; // you need to override this method in your subclass!
  57450. return -1;
  57451. }
  57452. const StringArray& ChoicePropertyComponent::getChoices() const
  57453. {
  57454. return choices;
  57455. }
  57456. void ChoicePropertyComponent::refresh()
  57457. {
  57458. if (isCustomClass)
  57459. {
  57460. if (! comboBox.isVisible())
  57461. {
  57462. createComboBox();
  57463. comboBox.addListener (this);
  57464. }
  57465. comboBox.setSelectedId (getIndex() + 1, true);
  57466. }
  57467. }
  57468. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  57469. {
  57470. if (isCustomClass)
  57471. {
  57472. const int newIndex = comboBox.getSelectedId() - 1;
  57473. if (newIndex != getIndex())
  57474. setIndex (newIndex);
  57475. }
  57476. }
  57477. END_JUCE_NAMESPACE
  57478. /*** End of inlined file: juce_ChoicePropertyComponent.cpp ***/
  57479. /*** Start of inlined file: juce_PropertyComponent.cpp ***/
  57480. BEGIN_JUCE_NAMESPACE
  57481. PropertyComponent::PropertyComponent (const String& name,
  57482. const int preferredHeight_)
  57483. : Component (name),
  57484. preferredHeight (preferredHeight_)
  57485. {
  57486. jassert (name.isNotEmpty());
  57487. }
  57488. PropertyComponent::~PropertyComponent()
  57489. {
  57490. }
  57491. void PropertyComponent::paint (Graphics& g)
  57492. {
  57493. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  57494. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  57495. }
  57496. void PropertyComponent::resized()
  57497. {
  57498. if (getNumChildComponents() > 0)
  57499. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  57500. }
  57501. void PropertyComponent::enablementChanged()
  57502. {
  57503. repaint();
  57504. }
  57505. END_JUCE_NAMESPACE
  57506. /*** End of inlined file: juce_PropertyComponent.cpp ***/
  57507. /*** Start of inlined file: juce_PropertyPanel.cpp ***/
  57508. BEGIN_JUCE_NAMESPACE
  57509. class PropertyPanel::PropertyHolderComponent : public Component
  57510. {
  57511. public:
  57512. PropertyHolderComponent()
  57513. {
  57514. }
  57515. ~PropertyHolderComponent()
  57516. {
  57517. deleteAllChildren();
  57518. }
  57519. void paint (Graphics&)
  57520. {
  57521. }
  57522. void updateLayout (int width);
  57523. void refreshAll() const;
  57524. private:
  57525. PropertyHolderComponent (const PropertyHolderComponent&);
  57526. PropertyHolderComponent& operator= (const PropertyHolderComponent&);
  57527. };
  57528. class PropertySectionComponent : public Component
  57529. {
  57530. public:
  57531. PropertySectionComponent (const String& sectionTitle,
  57532. const Array <PropertyComponent*>& newProperties,
  57533. const bool open)
  57534. : Component (sectionTitle),
  57535. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  57536. isOpen_ (open)
  57537. {
  57538. for (int i = newProperties.size(); --i >= 0;)
  57539. {
  57540. addAndMakeVisible (newProperties.getUnchecked(i));
  57541. newProperties.getUnchecked(i)->refresh();
  57542. }
  57543. }
  57544. ~PropertySectionComponent()
  57545. {
  57546. deleteAllChildren();
  57547. }
  57548. void paint (Graphics& g)
  57549. {
  57550. if (titleHeight > 0)
  57551. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  57552. }
  57553. void resized()
  57554. {
  57555. int y = titleHeight;
  57556. for (int i = getNumChildComponents(); --i >= 0;)
  57557. {
  57558. PropertyComponent* const pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57559. if (pec != 0)
  57560. {
  57561. const int prefH = pec->getPreferredHeight();
  57562. pec->setBounds (1, y, getWidth() - 2, prefH);
  57563. y += prefH;
  57564. }
  57565. }
  57566. }
  57567. int getPreferredHeight() const
  57568. {
  57569. int y = titleHeight;
  57570. if (isOpen())
  57571. {
  57572. for (int i = 0; i < getNumChildComponents(); ++i)
  57573. {
  57574. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57575. if (pec != 0)
  57576. y += pec->getPreferredHeight();
  57577. }
  57578. }
  57579. return y;
  57580. }
  57581. void setOpen (const bool open)
  57582. {
  57583. if (isOpen_ != open)
  57584. {
  57585. isOpen_ = open;
  57586. for (int i = 0; i < getNumChildComponents(); ++i)
  57587. {
  57588. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57589. if (pec != 0)
  57590. pec->setVisible (open);
  57591. }
  57592. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  57593. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  57594. if (pp != 0)
  57595. pp->resized();
  57596. }
  57597. }
  57598. bool isOpen() const
  57599. {
  57600. return isOpen_;
  57601. }
  57602. void refreshAll() const
  57603. {
  57604. for (int i = 0; i < getNumChildComponents(); ++i)
  57605. {
  57606. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  57607. if (pec != 0)
  57608. pec->refresh();
  57609. }
  57610. }
  57611. void mouseDown (const MouseEvent&)
  57612. {
  57613. }
  57614. void mouseUp (const MouseEvent& e)
  57615. {
  57616. if (e.getMouseDownX() < titleHeight
  57617. && e.x < titleHeight
  57618. && e.y < titleHeight
  57619. && e.getNumberOfClicks() != 2)
  57620. {
  57621. setOpen (! isOpen());
  57622. }
  57623. }
  57624. void mouseDoubleClick (const MouseEvent& e)
  57625. {
  57626. if (e.y < titleHeight)
  57627. setOpen (! isOpen());
  57628. }
  57629. private:
  57630. int titleHeight;
  57631. bool isOpen_;
  57632. PropertySectionComponent (const PropertySectionComponent&);
  57633. PropertySectionComponent& operator= (const PropertySectionComponent&);
  57634. };
  57635. void PropertyPanel::PropertyHolderComponent::updateLayout (const int width)
  57636. {
  57637. int y = 0;
  57638. for (int i = getNumChildComponents(); --i >= 0;)
  57639. {
  57640. PropertySectionComponent* const section
  57641. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  57642. if (section != 0)
  57643. {
  57644. const int prefH = section->getPreferredHeight();
  57645. section->setBounds (0, y, width, prefH);
  57646. y += prefH;
  57647. }
  57648. }
  57649. setSize (width, y);
  57650. repaint();
  57651. }
  57652. void PropertyPanel::PropertyHolderComponent::refreshAll() const
  57653. {
  57654. for (int i = getNumChildComponents(); --i >= 0;)
  57655. {
  57656. PropertySectionComponent* const section
  57657. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  57658. if (section != 0)
  57659. section->refreshAll();
  57660. }
  57661. }
  57662. PropertyPanel::PropertyPanel()
  57663. {
  57664. messageWhenEmpty = TRANS("(nothing selected)");
  57665. addAndMakeVisible (&viewport);
  57666. viewport.setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  57667. viewport.setFocusContainer (true);
  57668. }
  57669. PropertyPanel::~PropertyPanel()
  57670. {
  57671. clear();
  57672. }
  57673. void PropertyPanel::paint (Graphics& g)
  57674. {
  57675. if (propertyHolderComponent->getNumChildComponents() == 0)
  57676. {
  57677. g.setColour (Colours::black.withAlpha (0.5f));
  57678. g.setFont (14.0f);
  57679. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  57680. Justification::centred, true);
  57681. }
  57682. }
  57683. void PropertyPanel::resized()
  57684. {
  57685. viewport.setBounds (getLocalBounds());
  57686. updatePropHolderLayout();
  57687. }
  57688. void PropertyPanel::clear()
  57689. {
  57690. if (propertyHolderComponent->getNumChildComponents() > 0)
  57691. {
  57692. propertyHolderComponent->deleteAllChildren();
  57693. repaint();
  57694. }
  57695. }
  57696. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  57697. {
  57698. if (propertyHolderComponent->getNumChildComponents() == 0)
  57699. repaint();
  57700. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (String::empty,
  57701. newProperties,
  57702. true), 0);
  57703. updatePropHolderLayout();
  57704. }
  57705. void PropertyPanel::addSection (const String& sectionTitle,
  57706. const Array <PropertyComponent*>& newProperties,
  57707. const bool shouldBeOpen)
  57708. {
  57709. jassert (sectionTitle.isNotEmpty());
  57710. if (propertyHolderComponent->getNumChildComponents() == 0)
  57711. repaint();
  57712. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (sectionTitle,
  57713. newProperties,
  57714. shouldBeOpen), 0);
  57715. updatePropHolderLayout();
  57716. }
  57717. void PropertyPanel::updatePropHolderLayout() const
  57718. {
  57719. const int maxWidth = viewport.getMaximumVisibleWidth();
  57720. propertyHolderComponent->updateLayout (maxWidth);
  57721. const int newMaxWidth = viewport.getMaximumVisibleWidth();
  57722. if (maxWidth != newMaxWidth)
  57723. {
  57724. // need to do this twice because of scrollbars changing the size, etc.
  57725. propertyHolderComponent->updateLayout (newMaxWidth);
  57726. }
  57727. }
  57728. void PropertyPanel::refreshAll() const
  57729. {
  57730. propertyHolderComponent->refreshAll();
  57731. }
  57732. const StringArray PropertyPanel::getSectionNames() const
  57733. {
  57734. StringArray s;
  57735. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57736. {
  57737. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57738. if (section != 0 && section->getName().isNotEmpty())
  57739. s.add (section->getName());
  57740. }
  57741. return s;
  57742. }
  57743. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  57744. {
  57745. int index = 0;
  57746. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57747. {
  57748. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57749. if (section != 0 && section->getName().isNotEmpty())
  57750. {
  57751. if (index == sectionIndex)
  57752. return section->isOpen();
  57753. ++index;
  57754. }
  57755. }
  57756. return false;
  57757. }
  57758. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  57759. {
  57760. int index = 0;
  57761. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57762. {
  57763. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57764. if (section != 0 && section->getName().isNotEmpty())
  57765. {
  57766. if (index == sectionIndex)
  57767. {
  57768. section->setOpen (shouldBeOpen);
  57769. break;
  57770. }
  57771. ++index;
  57772. }
  57773. }
  57774. }
  57775. void PropertyPanel::setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled)
  57776. {
  57777. int index = 0;
  57778. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  57779. {
  57780. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  57781. if (section != 0 && section->getName().isNotEmpty())
  57782. {
  57783. if (index == sectionIndex)
  57784. {
  57785. section->setEnabled (shouldBeEnabled);
  57786. break;
  57787. }
  57788. ++index;
  57789. }
  57790. }
  57791. }
  57792. XmlElement* PropertyPanel::getOpennessState() const
  57793. {
  57794. XmlElement* const xml = new XmlElement ("PROPERTYPANELSTATE");
  57795. xml->setAttribute ("scrollPos", viewport.getViewPositionY());
  57796. const StringArray sections (getSectionNames());
  57797. for (int i = 0; i < sections.size(); ++i)
  57798. {
  57799. if (sections[i].isNotEmpty())
  57800. {
  57801. XmlElement* const e = xml->createNewChildElement ("SECTION");
  57802. e->setAttribute ("name", sections[i]);
  57803. e->setAttribute ("open", isSectionOpen (i) ? 1 : 0);
  57804. }
  57805. }
  57806. return xml;
  57807. }
  57808. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  57809. {
  57810. if (xml.hasTagName ("PROPERTYPANELSTATE"))
  57811. {
  57812. const StringArray sections (getSectionNames());
  57813. forEachXmlChildElementWithTagName (xml, e, "SECTION")
  57814. {
  57815. setSectionOpen (sections.indexOf (e->getStringAttribute ("name")),
  57816. e->getBoolAttribute ("open"));
  57817. }
  57818. viewport.setViewPosition (viewport.getViewPositionX(),
  57819. xml.getIntAttribute ("scrollPos", viewport.getViewPositionY()));
  57820. }
  57821. }
  57822. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  57823. {
  57824. if (messageWhenEmpty != newMessage)
  57825. {
  57826. messageWhenEmpty = newMessage;
  57827. repaint();
  57828. }
  57829. }
  57830. const String& PropertyPanel::getMessageWhenEmpty() const
  57831. {
  57832. return messageWhenEmpty;
  57833. }
  57834. END_JUCE_NAMESPACE
  57835. /*** End of inlined file: juce_PropertyPanel.cpp ***/
  57836. /*** Start of inlined file: juce_SliderPropertyComponent.cpp ***/
  57837. BEGIN_JUCE_NAMESPACE
  57838. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  57839. const double rangeMin,
  57840. const double rangeMax,
  57841. const double interval,
  57842. const double skewFactor)
  57843. : PropertyComponent (name)
  57844. {
  57845. addAndMakeVisible (&slider);
  57846. slider.setRange (rangeMin, rangeMax, interval);
  57847. slider.setSkewFactor (skewFactor);
  57848. slider.setSliderStyle (Slider::LinearBar);
  57849. slider.addListener (this);
  57850. }
  57851. SliderPropertyComponent::SliderPropertyComponent (const Value& valueToControl,
  57852. const String& name,
  57853. const double rangeMin,
  57854. const double rangeMax,
  57855. const double interval,
  57856. const double skewFactor)
  57857. : PropertyComponent (name)
  57858. {
  57859. addAndMakeVisible (&slider);
  57860. slider.setRange (rangeMin, rangeMax, interval);
  57861. slider.setSkewFactor (skewFactor);
  57862. slider.setSliderStyle (Slider::LinearBar);
  57863. slider.getValueObject().referTo (valueToControl);
  57864. }
  57865. SliderPropertyComponent::~SliderPropertyComponent()
  57866. {
  57867. }
  57868. void SliderPropertyComponent::setValue (const double /*newValue*/)
  57869. {
  57870. }
  57871. double SliderPropertyComponent::getValue() const
  57872. {
  57873. return slider.getValue();
  57874. }
  57875. void SliderPropertyComponent::refresh()
  57876. {
  57877. slider.setValue (getValue(), false);
  57878. }
  57879. void SliderPropertyComponent::sliderValueChanged (Slider*)
  57880. {
  57881. if (getValue() != slider.getValue())
  57882. setValue (slider.getValue());
  57883. }
  57884. END_JUCE_NAMESPACE
  57885. /*** End of inlined file: juce_SliderPropertyComponent.cpp ***/
  57886. /*** Start of inlined file: juce_TextPropertyComponent.cpp ***/
  57887. BEGIN_JUCE_NAMESPACE
  57888. class TextPropLabel : public Label
  57889. {
  57890. TextPropertyComponent& owner;
  57891. int maxChars;
  57892. bool isMultiline;
  57893. public:
  57894. TextPropLabel (TextPropertyComponent& owner_,
  57895. const int maxChars_, const bool isMultiline_)
  57896. : Label (String::empty, String::empty),
  57897. owner (owner_),
  57898. maxChars (maxChars_),
  57899. isMultiline (isMultiline_)
  57900. {
  57901. setEditable (true, true, false);
  57902. setColour (backgroundColourId, Colours::white);
  57903. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  57904. }
  57905. ~TextPropLabel()
  57906. {
  57907. }
  57908. TextEditor* createEditorComponent()
  57909. {
  57910. TextEditor* const textEditor = Label::createEditorComponent();
  57911. textEditor->setInputRestrictions (maxChars);
  57912. if (isMultiline)
  57913. {
  57914. textEditor->setMultiLine (true, true);
  57915. textEditor->setReturnKeyStartsNewLine (true);
  57916. }
  57917. return textEditor;
  57918. }
  57919. void textWasEdited()
  57920. {
  57921. owner.textWasEdited();
  57922. }
  57923. };
  57924. TextPropertyComponent::TextPropertyComponent (const String& name,
  57925. const int maxNumChars,
  57926. const bool isMultiLine)
  57927. : PropertyComponent (name)
  57928. {
  57929. createEditor (maxNumChars, isMultiLine);
  57930. }
  57931. TextPropertyComponent::TextPropertyComponent (const Value& valueToControl,
  57932. const String& name,
  57933. const int maxNumChars,
  57934. const bool isMultiLine)
  57935. : PropertyComponent (name)
  57936. {
  57937. createEditor (maxNumChars, isMultiLine);
  57938. textEditor->getTextValue().referTo (valueToControl);
  57939. }
  57940. TextPropertyComponent::~TextPropertyComponent()
  57941. {
  57942. deleteAllChildren();
  57943. }
  57944. void TextPropertyComponent::setText (const String& newText)
  57945. {
  57946. textEditor->setText (newText, true);
  57947. }
  57948. const String TextPropertyComponent::getText() const
  57949. {
  57950. return textEditor->getText();
  57951. }
  57952. void TextPropertyComponent::createEditor (const int maxNumChars, const bool isMultiLine)
  57953. {
  57954. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  57955. if (isMultiLine)
  57956. {
  57957. textEditor->setJustificationType (Justification::topLeft);
  57958. preferredHeight = 120;
  57959. }
  57960. }
  57961. void TextPropertyComponent::refresh()
  57962. {
  57963. textEditor->setText (getText(), false);
  57964. }
  57965. void TextPropertyComponent::textWasEdited()
  57966. {
  57967. const String newText (textEditor->getText());
  57968. if (getText() != newText)
  57969. setText (newText);
  57970. }
  57971. END_JUCE_NAMESPACE
  57972. /*** End of inlined file: juce_TextPropertyComponent.cpp ***/
  57973. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  57974. BEGIN_JUCE_NAMESPACE
  57975. class SimpleDeviceManagerInputLevelMeter : public Component,
  57976. public Timer
  57977. {
  57978. public:
  57979. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager* const manager_)
  57980. : manager (manager_),
  57981. level (0)
  57982. {
  57983. startTimer (50);
  57984. manager->enableInputLevelMeasurement (true);
  57985. }
  57986. ~SimpleDeviceManagerInputLevelMeter()
  57987. {
  57988. manager->enableInputLevelMeasurement (false);
  57989. }
  57990. void timerCallback()
  57991. {
  57992. const float newLevel = (float) manager->getCurrentInputLevel();
  57993. if (std::abs (level - newLevel) > 0.005f)
  57994. {
  57995. level = newLevel;
  57996. repaint();
  57997. }
  57998. }
  57999. void paint (Graphics& g)
  58000. {
  58001. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(),
  58002. (float) exp (log (level) / 3.0)); // (add a bit of a skew to make the level more obvious)
  58003. }
  58004. private:
  58005. AudioDeviceManager* const manager;
  58006. float level;
  58007. SimpleDeviceManagerInputLevelMeter (const SimpleDeviceManagerInputLevelMeter&);
  58008. SimpleDeviceManagerInputLevelMeter& operator= (const SimpleDeviceManagerInputLevelMeter&);
  58009. };
  58010. class AudioDeviceSelectorComponent::MidiInputSelectorComponentListBox : public ListBox,
  58011. public ListBoxModel
  58012. {
  58013. public:
  58014. MidiInputSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  58015. const String& noItemsMessage_,
  58016. const int minNumber_,
  58017. const int maxNumber_)
  58018. : ListBox (String::empty, 0),
  58019. deviceManager (deviceManager_),
  58020. noItemsMessage (noItemsMessage_),
  58021. minNumber (minNumber_),
  58022. maxNumber (maxNumber_)
  58023. {
  58024. items = MidiInput::getDevices();
  58025. setModel (this);
  58026. setOutlineThickness (1);
  58027. }
  58028. ~MidiInputSelectorComponentListBox()
  58029. {
  58030. }
  58031. int getNumRows()
  58032. {
  58033. return items.size();
  58034. }
  58035. void paintListBoxItem (int row,
  58036. Graphics& g,
  58037. int width, int height,
  58038. bool rowIsSelected)
  58039. {
  58040. if (((unsigned int) row) < (unsigned int) items.size())
  58041. {
  58042. if (rowIsSelected)
  58043. g.fillAll (findColour (TextEditor::highlightColourId)
  58044. .withMultipliedAlpha (0.3f));
  58045. const String item (items [row]);
  58046. bool enabled = deviceManager.isMidiInputEnabled (item);
  58047. const int x = getTickX();
  58048. const float tickW = height * 0.75f;
  58049. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  58050. enabled, true, true, false);
  58051. g.setFont (height * 0.6f);
  58052. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  58053. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  58054. }
  58055. }
  58056. void listBoxItemClicked (int row, const MouseEvent& e)
  58057. {
  58058. selectRow (row);
  58059. if (e.x < getTickX())
  58060. flipEnablement (row);
  58061. }
  58062. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  58063. {
  58064. flipEnablement (row);
  58065. }
  58066. void returnKeyPressed (int row)
  58067. {
  58068. flipEnablement (row);
  58069. }
  58070. void paint (Graphics& g)
  58071. {
  58072. ListBox::paint (g);
  58073. if (items.size() == 0)
  58074. {
  58075. g.setColour (Colours::grey);
  58076. g.setFont (13.0f);
  58077. g.drawText (noItemsMessage,
  58078. 0, 0, getWidth(), getHeight() / 2,
  58079. Justification::centred, true);
  58080. }
  58081. }
  58082. int getBestHeight (const int preferredHeight)
  58083. {
  58084. const int extra = getOutlineThickness() * 2;
  58085. return jmax (getRowHeight() * 2 + extra,
  58086. jmin (getRowHeight() * getNumRows() + extra,
  58087. preferredHeight));
  58088. }
  58089. juce_UseDebuggingNewOperator
  58090. private:
  58091. AudioDeviceManager& deviceManager;
  58092. const String noItemsMessage;
  58093. StringArray items;
  58094. int minNumber, maxNumber;
  58095. void flipEnablement (const int row)
  58096. {
  58097. if (((unsigned int) row) < (unsigned int) items.size())
  58098. {
  58099. const String item (items [row]);
  58100. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  58101. }
  58102. }
  58103. int getTickX() const
  58104. {
  58105. return getRowHeight() + 5;
  58106. }
  58107. MidiInputSelectorComponentListBox (const MidiInputSelectorComponentListBox&);
  58108. MidiInputSelectorComponentListBox& operator= (const MidiInputSelectorComponentListBox&);
  58109. };
  58110. class AudioDeviceSettingsPanel : public Component,
  58111. public ComboBoxListener,
  58112. public ChangeListener,
  58113. public ButtonListener
  58114. {
  58115. public:
  58116. AudioDeviceSettingsPanel (AudioIODeviceType* type_,
  58117. AudioIODeviceType::DeviceSetupDetails& setup_,
  58118. const bool hideAdvancedOptionsWithButton)
  58119. : type (type_),
  58120. setup (setup_)
  58121. {
  58122. if (hideAdvancedOptionsWithButton)
  58123. {
  58124. addAndMakeVisible (showAdvancedSettingsButton = new TextButton (TRANS("Show advanced settings...")));
  58125. showAdvancedSettingsButton->addButtonListener (this);
  58126. }
  58127. type->scanForDevices();
  58128. setup.manager->addChangeListener (this);
  58129. changeListenerCallback (0);
  58130. }
  58131. ~AudioDeviceSettingsPanel()
  58132. {
  58133. setup.manager->removeChangeListener (this);
  58134. }
  58135. void resized()
  58136. {
  58137. const int lx = proportionOfWidth (0.35f);
  58138. const int w = proportionOfWidth (0.4f);
  58139. const int h = 24;
  58140. const int space = 6;
  58141. const int dh = h + space;
  58142. int y = 0;
  58143. if (outputDeviceDropDown != 0)
  58144. {
  58145. outputDeviceDropDown->setBounds (lx, y, w, h);
  58146. if (testButton != 0)
  58147. testButton->setBounds (proportionOfWidth (0.77f),
  58148. outputDeviceDropDown->getY(),
  58149. proportionOfWidth (0.18f),
  58150. h);
  58151. y += dh;
  58152. }
  58153. if (inputDeviceDropDown != 0)
  58154. {
  58155. inputDeviceDropDown->setBounds (lx, y, w, h);
  58156. inputLevelMeter->setBounds (proportionOfWidth (0.77f),
  58157. inputDeviceDropDown->getY(),
  58158. proportionOfWidth (0.18f),
  58159. h);
  58160. y += dh;
  58161. }
  58162. const int maxBoxHeight = 100;//(getHeight() - y - dh * 2) / numBoxes;
  58163. if (outputChanList != 0)
  58164. {
  58165. const int bh = outputChanList->getBestHeight (maxBoxHeight);
  58166. outputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58167. y += bh + space;
  58168. }
  58169. if (inputChanList != 0)
  58170. {
  58171. const int bh = inputChanList->getBestHeight (maxBoxHeight);
  58172. inputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58173. y += bh + space;
  58174. }
  58175. y += space * 2;
  58176. if (showAdvancedSettingsButton != 0)
  58177. {
  58178. showAdvancedSettingsButton->changeWidthToFitText (h);
  58179. showAdvancedSettingsButton->setTopLeftPosition (lx, y);
  58180. }
  58181. if (sampleRateDropDown != 0)
  58182. {
  58183. sampleRateDropDown->setVisible (showAdvancedSettingsButton == 0
  58184. || ! showAdvancedSettingsButton->isVisible());
  58185. sampleRateDropDown->setBounds (lx, y, w, h);
  58186. y += dh;
  58187. }
  58188. if (bufferSizeDropDown != 0)
  58189. {
  58190. bufferSizeDropDown->setVisible (showAdvancedSettingsButton == 0
  58191. || ! showAdvancedSettingsButton->isVisible());
  58192. bufferSizeDropDown->setBounds (lx, y, w, h);
  58193. y += dh;
  58194. }
  58195. if (showUIButton != 0)
  58196. {
  58197. showUIButton->setVisible (showAdvancedSettingsButton == 0
  58198. || ! showAdvancedSettingsButton->isVisible());
  58199. showUIButton->changeWidthToFitText (h);
  58200. showUIButton->setTopLeftPosition (lx, y);
  58201. }
  58202. }
  58203. void comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  58204. {
  58205. if (comboBoxThatHasChanged == 0)
  58206. return;
  58207. AudioDeviceManager::AudioDeviceSetup config;
  58208. setup.manager->getAudioDeviceSetup (config);
  58209. String error;
  58210. if (comboBoxThatHasChanged == outputDeviceDropDown
  58211. || comboBoxThatHasChanged == inputDeviceDropDown)
  58212. {
  58213. if (outputDeviceDropDown != 0)
  58214. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58215. : outputDeviceDropDown->getText();
  58216. if (inputDeviceDropDown != 0)
  58217. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58218. : inputDeviceDropDown->getText();
  58219. if (! type->hasSeparateInputsAndOutputs())
  58220. config.inputDeviceName = config.outputDeviceName;
  58221. if (comboBoxThatHasChanged == inputDeviceDropDown)
  58222. config.useDefaultInputChannels = true;
  58223. else
  58224. config.useDefaultOutputChannels = true;
  58225. error = setup.manager->setAudioDeviceSetup (config, true);
  58226. showCorrectDeviceName (inputDeviceDropDown, true);
  58227. showCorrectDeviceName (outputDeviceDropDown, false);
  58228. updateControlPanelButton();
  58229. resized();
  58230. }
  58231. else if (comboBoxThatHasChanged == sampleRateDropDown)
  58232. {
  58233. if (sampleRateDropDown->getSelectedId() > 0)
  58234. {
  58235. config.sampleRate = sampleRateDropDown->getSelectedId();
  58236. error = setup.manager->setAudioDeviceSetup (config, true);
  58237. }
  58238. }
  58239. else if (comboBoxThatHasChanged == bufferSizeDropDown)
  58240. {
  58241. if (bufferSizeDropDown->getSelectedId() > 0)
  58242. {
  58243. config.bufferSize = bufferSizeDropDown->getSelectedId();
  58244. error = setup.manager->setAudioDeviceSetup (config, true);
  58245. }
  58246. }
  58247. if (error.isNotEmpty())
  58248. {
  58249. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  58250. "Error when trying to open audio device!",
  58251. error);
  58252. }
  58253. }
  58254. void buttonClicked (Button* button)
  58255. {
  58256. if (button == showAdvancedSettingsButton)
  58257. {
  58258. showAdvancedSettingsButton->setVisible (false);
  58259. resized();
  58260. }
  58261. else if (button == showUIButton)
  58262. {
  58263. AudioIODevice* const device = setup.manager->getCurrentAudioDevice();
  58264. if (device != 0 && device->showControlPanel())
  58265. {
  58266. setup.manager->closeAudioDevice();
  58267. setup.manager->restartLastAudioDevice();
  58268. getTopLevelComponent()->toFront (true);
  58269. }
  58270. }
  58271. else if (button == testButton && testButton != 0)
  58272. {
  58273. setup.manager->playTestSound();
  58274. }
  58275. }
  58276. void updateControlPanelButton()
  58277. {
  58278. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58279. showUIButton = 0;
  58280. if (currentDevice != 0 && currentDevice->hasControlPanel())
  58281. {
  58282. addAndMakeVisible (showUIButton = new TextButton (TRANS ("show this device's control panel"),
  58283. TRANS ("opens the device's own control panel")));
  58284. showUIButton->addButtonListener (this);
  58285. }
  58286. resized();
  58287. }
  58288. void changeListenerCallback (void*)
  58289. {
  58290. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58291. if (setup.maxNumOutputChannels > 0 || ! type->hasSeparateInputsAndOutputs())
  58292. {
  58293. if (outputDeviceDropDown == 0)
  58294. {
  58295. outputDeviceDropDown = new ComboBox (String::empty);
  58296. outputDeviceDropDown->addListener (this);
  58297. addAndMakeVisible (outputDeviceDropDown);
  58298. outputDeviceLabel = new Label (String::empty,
  58299. type->hasSeparateInputsAndOutputs() ? TRANS ("output:")
  58300. : TRANS ("device:"));
  58301. outputDeviceLabel->attachToComponent (outputDeviceDropDown, true);
  58302. if (setup.maxNumOutputChannels > 0)
  58303. {
  58304. addAndMakeVisible (testButton = new TextButton (TRANS ("Test")));
  58305. testButton->addButtonListener (this);
  58306. }
  58307. }
  58308. addNamesToDeviceBox (*outputDeviceDropDown, false);
  58309. }
  58310. if (setup.maxNumInputChannels > 0 && type->hasSeparateInputsAndOutputs())
  58311. {
  58312. if (inputDeviceDropDown == 0)
  58313. {
  58314. inputDeviceDropDown = new ComboBox (String::empty);
  58315. inputDeviceDropDown->addListener (this);
  58316. addAndMakeVisible (inputDeviceDropDown);
  58317. inputDeviceLabel = new Label (String::empty, TRANS ("input:"));
  58318. inputDeviceLabel->attachToComponent (inputDeviceDropDown, true);
  58319. addAndMakeVisible (inputLevelMeter
  58320. = new SimpleDeviceManagerInputLevelMeter (setup.manager));
  58321. }
  58322. addNamesToDeviceBox (*inputDeviceDropDown, true);
  58323. }
  58324. updateControlPanelButton();
  58325. showCorrectDeviceName (inputDeviceDropDown, true);
  58326. showCorrectDeviceName (outputDeviceDropDown, false);
  58327. if (currentDevice != 0)
  58328. {
  58329. if (setup.maxNumOutputChannels > 0
  58330. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  58331. {
  58332. if (outputChanList == 0)
  58333. {
  58334. addAndMakeVisible (outputChanList
  58335. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  58336. TRANS ("(no audio output channels found)")));
  58337. outputChanLabel = new Label (String::empty, TRANS ("active output channels:"));
  58338. outputChanLabel->attachToComponent (outputChanList, true);
  58339. }
  58340. outputChanList->refresh();
  58341. }
  58342. else
  58343. {
  58344. outputChanLabel = 0;
  58345. outputChanList = 0;
  58346. }
  58347. if (setup.maxNumInputChannels > 0
  58348. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  58349. {
  58350. if (inputChanList == 0)
  58351. {
  58352. addAndMakeVisible (inputChanList
  58353. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  58354. TRANS ("(no audio input channels found)")));
  58355. inputChanLabel = new Label (String::empty, TRANS ("active input channels:"));
  58356. inputChanLabel->attachToComponent (inputChanList, true);
  58357. }
  58358. inputChanList->refresh();
  58359. }
  58360. else
  58361. {
  58362. inputChanLabel = 0;
  58363. inputChanList = 0;
  58364. }
  58365. // sample rate..
  58366. {
  58367. if (sampleRateDropDown == 0)
  58368. {
  58369. addAndMakeVisible (sampleRateDropDown = new ComboBox (String::empty));
  58370. sampleRateDropDown->addListener (this);
  58371. sampleRateLabel = new Label (String::empty, TRANS ("sample rate:"));
  58372. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  58373. }
  58374. else
  58375. {
  58376. sampleRateDropDown->clear();
  58377. sampleRateDropDown->removeListener (this);
  58378. }
  58379. const int numRates = currentDevice->getNumSampleRates();
  58380. for (int i = 0; i < numRates; ++i)
  58381. {
  58382. const int rate = roundToInt (currentDevice->getSampleRate (i));
  58383. sampleRateDropDown->addItem (String (rate) + " Hz", rate);
  58384. }
  58385. sampleRateDropDown->setSelectedId (roundToInt (currentDevice->getCurrentSampleRate()), true);
  58386. sampleRateDropDown->addListener (this);
  58387. }
  58388. // buffer size
  58389. {
  58390. if (bufferSizeDropDown == 0)
  58391. {
  58392. addAndMakeVisible (bufferSizeDropDown = new ComboBox (String::empty));
  58393. bufferSizeDropDown->addListener (this);
  58394. bufferSizeLabel = new Label (String::empty, TRANS ("audio buffer size:"));
  58395. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  58396. }
  58397. else
  58398. {
  58399. bufferSizeDropDown->clear();
  58400. }
  58401. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  58402. double currentRate = currentDevice->getCurrentSampleRate();
  58403. if (currentRate == 0)
  58404. currentRate = 48000.0;
  58405. for (int i = 0; i < numBufferSizes; ++i)
  58406. {
  58407. const int bs = currentDevice->getBufferSizeSamples (i);
  58408. bufferSizeDropDown->addItem (String (bs)
  58409. + " samples ("
  58410. + String (bs * 1000.0 / currentRate, 1)
  58411. + " ms)",
  58412. bs);
  58413. }
  58414. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  58415. }
  58416. }
  58417. else
  58418. {
  58419. jassert (setup.manager->getCurrentAudioDevice() == 0); // not the correct device type!
  58420. sampleRateLabel = 0;
  58421. bufferSizeLabel = 0;
  58422. sampleRateDropDown = 0;
  58423. bufferSizeDropDown = 0;
  58424. if (outputDeviceDropDown != 0)
  58425. outputDeviceDropDown->setSelectedId (-1, true);
  58426. if (inputDeviceDropDown != 0)
  58427. inputDeviceDropDown->setSelectedId (-1, true);
  58428. }
  58429. resized();
  58430. setSize (getWidth(), getLowestY() + 4);
  58431. }
  58432. private:
  58433. AudioIODeviceType* const type;
  58434. const AudioIODeviceType::DeviceSetupDetails setup;
  58435. ScopedPointer<ComboBox> outputDeviceDropDown, inputDeviceDropDown, sampleRateDropDown, bufferSizeDropDown;
  58436. ScopedPointer<Label> outputDeviceLabel, inputDeviceLabel, sampleRateLabel, bufferSizeLabel, inputChanLabel, outputChanLabel;
  58437. ScopedPointer<TextButton> testButton;
  58438. ScopedPointer<Component> inputLevelMeter;
  58439. ScopedPointer<TextButton> showUIButton, showAdvancedSettingsButton;
  58440. void showCorrectDeviceName (ComboBox* const box, const bool isInput)
  58441. {
  58442. if (box != 0)
  58443. {
  58444. AudioIODevice* const currentDevice = dynamic_cast <AudioIODevice*> (setup.manager->getCurrentAudioDevice());
  58445. const int index = type->getIndexOfDevice (currentDevice, isInput);
  58446. box->setSelectedId (index + 1, true);
  58447. if (testButton != 0 && ! isInput)
  58448. testButton->setEnabled (index >= 0);
  58449. }
  58450. }
  58451. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  58452. {
  58453. const StringArray devs (type->getDeviceNames (isInputs));
  58454. combo.clear (true);
  58455. for (int i = 0; i < devs.size(); ++i)
  58456. combo.addItem (devs[i], i + 1);
  58457. combo.addItem (TRANS("<< none >>"), -1);
  58458. combo.setSelectedId (-1, true);
  58459. }
  58460. int getLowestY() const
  58461. {
  58462. int y = 0;
  58463. for (int i = getNumChildComponents(); --i >= 0;)
  58464. y = jmax (y, getChildComponent (i)->getBottom());
  58465. return y;
  58466. }
  58467. public:
  58468. class ChannelSelectorListBox : public ListBox,
  58469. public ListBoxModel
  58470. {
  58471. public:
  58472. enum BoxType
  58473. {
  58474. audioInputType,
  58475. audioOutputType
  58476. };
  58477. ChannelSelectorListBox (const AudioIODeviceType::DeviceSetupDetails& setup_,
  58478. const BoxType type_,
  58479. const String& noItemsMessage_)
  58480. : ListBox (String::empty, 0),
  58481. setup (setup_),
  58482. type (type_),
  58483. noItemsMessage (noItemsMessage_)
  58484. {
  58485. refresh();
  58486. setModel (this);
  58487. setOutlineThickness (1);
  58488. }
  58489. ~ChannelSelectorListBox()
  58490. {
  58491. }
  58492. void refresh()
  58493. {
  58494. items.clear();
  58495. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58496. if (currentDevice != 0)
  58497. {
  58498. if (type == audioInputType)
  58499. items = currentDevice->getInputChannelNames();
  58500. else if (type == audioOutputType)
  58501. items = currentDevice->getOutputChannelNames();
  58502. if (setup.useStereoPairs)
  58503. {
  58504. StringArray pairs;
  58505. for (int i = 0; i < items.size(); i += 2)
  58506. {
  58507. const String name (items[i]);
  58508. const String name2 (items[i + 1]);
  58509. String commonBit;
  58510. for (int j = 0; j < name.length(); ++j)
  58511. if (name.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  58512. commonBit = name.substring (0, j);
  58513. // Make sure we only split the name at a space, because otherwise, things
  58514. // like "input 11" + "input 12" would become "input 11 + 2"
  58515. while (commonBit.isNotEmpty() && ! CharacterFunctions::isWhitespace (commonBit.getLastCharacter()))
  58516. commonBit = commonBit.dropLastCharacters (1);
  58517. pairs.add (name.trim() + " + " + name2.substring (commonBit.length()).trim());
  58518. }
  58519. items = pairs;
  58520. }
  58521. }
  58522. updateContent();
  58523. repaint();
  58524. }
  58525. int getNumRows()
  58526. {
  58527. return items.size();
  58528. }
  58529. void paintListBoxItem (int row,
  58530. Graphics& g,
  58531. int width, int height,
  58532. bool rowIsSelected)
  58533. {
  58534. if (((unsigned int) row) < (unsigned int) items.size())
  58535. {
  58536. if (rowIsSelected)
  58537. g.fillAll (findColour (TextEditor::highlightColourId)
  58538. .withMultipliedAlpha (0.3f));
  58539. const String item (items [row]);
  58540. bool enabled = false;
  58541. AudioDeviceManager::AudioDeviceSetup config;
  58542. setup.manager->getAudioDeviceSetup (config);
  58543. if (setup.useStereoPairs)
  58544. {
  58545. if (type == audioInputType)
  58546. enabled = config.inputChannels [row * 2] || config.inputChannels [row * 2 + 1];
  58547. else if (type == audioOutputType)
  58548. enabled = config.outputChannels [row * 2] || config.outputChannels [row * 2 + 1];
  58549. }
  58550. else
  58551. {
  58552. if (type == audioInputType)
  58553. enabled = config.inputChannels [row];
  58554. else if (type == audioOutputType)
  58555. enabled = config.outputChannels [row];
  58556. }
  58557. const int x = getTickX();
  58558. const float tickW = height * 0.75f;
  58559. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  58560. enabled, true, true, false);
  58561. g.setFont (height * 0.6f);
  58562. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  58563. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  58564. }
  58565. }
  58566. void listBoxItemClicked (int row, const MouseEvent& e)
  58567. {
  58568. selectRow (row);
  58569. if (e.x < getTickX())
  58570. flipEnablement (row);
  58571. }
  58572. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  58573. {
  58574. flipEnablement (row);
  58575. }
  58576. void returnKeyPressed (int row)
  58577. {
  58578. flipEnablement (row);
  58579. }
  58580. void paint (Graphics& g)
  58581. {
  58582. ListBox::paint (g);
  58583. if (items.size() == 0)
  58584. {
  58585. g.setColour (Colours::grey);
  58586. g.setFont (13.0f);
  58587. g.drawText (noItemsMessage,
  58588. 0, 0, getWidth(), getHeight() / 2,
  58589. Justification::centred, true);
  58590. }
  58591. }
  58592. int getBestHeight (int maxHeight)
  58593. {
  58594. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  58595. getNumRows())
  58596. + getOutlineThickness() * 2;
  58597. }
  58598. juce_UseDebuggingNewOperator
  58599. private:
  58600. const AudioIODeviceType::DeviceSetupDetails setup;
  58601. const BoxType type;
  58602. const String noItemsMessage;
  58603. StringArray items;
  58604. void flipEnablement (const int row)
  58605. {
  58606. jassert (type == audioInputType || type == audioOutputType);
  58607. if (((unsigned int) row) < (unsigned int) items.size())
  58608. {
  58609. AudioDeviceManager::AudioDeviceSetup config;
  58610. setup.manager->getAudioDeviceSetup (config);
  58611. if (setup.useStereoPairs)
  58612. {
  58613. BigInteger bits;
  58614. BigInteger& original = (type == audioInputType ? config.inputChannels
  58615. : config.outputChannels);
  58616. int i;
  58617. for (i = 0; i < 256; i += 2)
  58618. bits.setBit (i / 2, original [i] || original [i + 1]);
  58619. if (type == audioInputType)
  58620. {
  58621. config.useDefaultInputChannels = false;
  58622. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  58623. }
  58624. else
  58625. {
  58626. config.useDefaultOutputChannels = false;
  58627. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  58628. }
  58629. for (i = 0; i < 256; ++i)
  58630. original.setBit (i, bits [i / 2]);
  58631. }
  58632. else
  58633. {
  58634. if (type == audioInputType)
  58635. {
  58636. config.useDefaultInputChannels = false;
  58637. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  58638. }
  58639. else
  58640. {
  58641. config.useDefaultOutputChannels = false;
  58642. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  58643. }
  58644. }
  58645. String error (setup.manager->setAudioDeviceSetup (config, true));
  58646. if (! error.isEmpty())
  58647. {
  58648. //xxx
  58649. }
  58650. }
  58651. }
  58652. static void flipBit (BigInteger& chans, int index, int minNumber, int maxNumber)
  58653. {
  58654. const int numActive = chans.countNumberOfSetBits();
  58655. if (chans [index])
  58656. {
  58657. if (numActive > minNumber)
  58658. chans.setBit (index, false);
  58659. }
  58660. else
  58661. {
  58662. if (numActive >= maxNumber)
  58663. {
  58664. const int firstActiveChan = chans.findNextSetBit();
  58665. chans.setBit (index > firstActiveChan
  58666. ? firstActiveChan : chans.getHighestBit(),
  58667. false);
  58668. }
  58669. chans.setBit (index, true);
  58670. }
  58671. }
  58672. int getTickX() const
  58673. {
  58674. return getRowHeight() + 5;
  58675. }
  58676. ChannelSelectorListBox (const ChannelSelectorListBox&);
  58677. ChannelSelectorListBox& operator= (const ChannelSelectorListBox&);
  58678. };
  58679. private:
  58680. ScopedPointer<ChannelSelectorListBox> inputChanList, outputChanList;
  58681. AudioDeviceSettingsPanel (const AudioDeviceSettingsPanel&);
  58682. AudioDeviceSettingsPanel& operator= (const AudioDeviceSettingsPanel&);
  58683. };
  58684. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  58685. const int minInputChannels_,
  58686. const int maxInputChannels_,
  58687. const int minOutputChannels_,
  58688. const int maxOutputChannels_,
  58689. const bool showMidiInputOptions,
  58690. const bool showMidiOutputSelector,
  58691. const bool showChannelsAsStereoPairs_,
  58692. const bool hideAdvancedOptionsWithButton_)
  58693. : deviceManager (deviceManager_),
  58694. deviceTypeDropDown (0),
  58695. deviceTypeDropDownLabel (0),
  58696. minOutputChannels (minOutputChannels_),
  58697. maxOutputChannels (maxOutputChannels_),
  58698. minInputChannels (minInputChannels_),
  58699. maxInputChannels (maxInputChannels_),
  58700. showChannelsAsStereoPairs (showChannelsAsStereoPairs_),
  58701. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButton_)
  58702. {
  58703. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  58704. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  58705. if (deviceManager_.getAvailableDeviceTypes().size() > 1)
  58706. {
  58707. deviceTypeDropDown = new ComboBox (String::empty);
  58708. for (int i = 0; i < deviceManager_.getAvailableDeviceTypes().size(); ++i)
  58709. {
  58710. deviceTypeDropDown
  58711. ->addItem (deviceManager_.getAvailableDeviceTypes().getUnchecked(i)->getTypeName(),
  58712. i + 1);
  58713. }
  58714. addAndMakeVisible (deviceTypeDropDown);
  58715. deviceTypeDropDown->addListener (this);
  58716. deviceTypeDropDownLabel = new Label (String::empty, TRANS ("audio device type:"));
  58717. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  58718. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown, true);
  58719. }
  58720. if (showMidiInputOptions)
  58721. {
  58722. addAndMakeVisible (midiInputsList
  58723. = new MidiInputSelectorComponentListBox (deviceManager,
  58724. TRANS("(no midi inputs available)"),
  58725. 0, 0));
  58726. midiInputsLabel = new Label (String::empty, TRANS ("active midi inputs:"));
  58727. midiInputsLabel->setJustificationType (Justification::topRight);
  58728. midiInputsLabel->attachToComponent (midiInputsList, true);
  58729. }
  58730. else
  58731. {
  58732. midiInputsList = 0;
  58733. midiInputsLabel = 0;
  58734. }
  58735. if (showMidiOutputSelector)
  58736. {
  58737. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  58738. midiOutputSelector->addListener (this);
  58739. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  58740. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  58741. }
  58742. else
  58743. {
  58744. midiOutputSelector = 0;
  58745. midiOutputLabel = 0;
  58746. }
  58747. deviceManager_.addChangeListener (this);
  58748. changeListenerCallback (0);
  58749. }
  58750. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  58751. {
  58752. deviceManager.removeChangeListener (this);
  58753. }
  58754. void AudioDeviceSelectorComponent::resized()
  58755. {
  58756. const int lx = proportionOfWidth (0.35f);
  58757. const int w = proportionOfWidth (0.4f);
  58758. const int h = 24;
  58759. const int space = 6;
  58760. const int dh = h + space;
  58761. int y = 15;
  58762. if (deviceTypeDropDown != 0)
  58763. {
  58764. deviceTypeDropDown->setBounds (lx, y, proportionOfWidth (0.3f), h);
  58765. y += dh + space * 2;
  58766. }
  58767. if (audioDeviceSettingsComp != 0)
  58768. {
  58769. audioDeviceSettingsComp->setBounds (0, y, getWidth(), audioDeviceSettingsComp->getHeight());
  58770. y += audioDeviceSettingsComp->getHeight() + space;
  58771. }
  58772. if (midiInputsList != 0)
  58773. {
  58774. const int bh = midiInputsList->getBestHeight (jmin (h * 8, getHeight() - y - space - h));
  58775. midiInputsList->setBounds (lx, y, w, bh);
  58776. y += bh + space;
  58777. }
  58778. if (midiOutputSelector != 0)
  58779. midiOutputSelector->setBounds (lx, y, w, h);
  58780. }
  58781. void AudioDeviceSelectorComponent::childBoundsChanged (Component* child)
  58782. {
  58783. if (child == audioDeviceSettingsComp)
  58784. resized();
  58785. }
  58786. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  58787. {
  58788. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  58789. if (device != 0 && device->hasControlPanel())
  58790. {
  58791. if (device->showControlPanel())
  58792. deviceManager.restartLastAudioDevice();
  58793. getTopLevelComponent()->toFront (true);
  58794. }
  58795. }
  58796. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  58797. {
  58798. if (comboBoxThatHasChanged == deviceTypeDropDown)
  58799. {
  58800. AudioIODeviceType* const type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1];
  58801. if (type != 0)
  58802. {
  58803. audioDeviceSettingsComp = 0;
  58804. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  58805. changeListenerCallback (0); // needed in case the type hasn't actally changed
  58806. }
  58807. }
  58808. else if (comboBoxThatHasChanged == midiOutputSelector)
  58809. {
  58810. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  58811. }
  58812. }
  58813. void AudioDeviceSelectorComponent::changeListenerCallback (void*)
  58814. {
  58815. if (deviceTypeDropDown != 0)
  58816. {
  58817. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), false);
  58818. }
  58819. if (audioDeviceSettingsComp == 0
  58820. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  58821. {
  58822. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  58823. audioDeviceSettingsComp = 0;
  58824. AudioIODeviceType* const type
  58825. = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == 0
  58826. ? 0 : deviceTypeDropDown->getSelectedId() - 1];
  58827. if (type != 0)
  58828. {
  58829. AudioIODeviceType::DeviceSetupDetails details;
  58830. details.manager = &deviceManager;
  58831. details.minNumInputChannels = minInputChannels;
  58832. details.maxNumInputChannels = maxInputChannels;
  58833. details.minNumOutputChannels = minOutputChannels;
  58834. details.maxNumOutputChannels = maxOutputChannels;
  58835. details.useStereoPairs = showChannelsAsStereoPairs;
  58836. audioDeviceSettingsComp = new AudioDeviceSettingsPanel (type, details, hideAdvancedOptionsWithButton);
  58837. if (audioDeviceSettingsComp != 0)
  58838. {
  58839. addAndMakeVisible (audioDeviceSettingsComp);
  58840. audioDeviceSettingsComp->resized();
  58841. }
  58842. }
  58843. }
  58844. if (midiInputsList != 0)
  58845. {
  58846. midiInputsList->updateContent();
  58847. midiInputsList->repaint();
  58848. }
  58849. if (midiOutputSelector != 0)
  58850. {
  58851. midiOutputSelector->clear();
  58852. const StringArray midiOuts (MidiOutput::getDevices());
  58853. midiOutputSelector->addItem (TRANS("<< none >>"), -1);
  58854. midiOutputSelector->addSeparator();
  58855. for (int i = 0; i < midiOuts.size(); ++i)
  58856. midiOutputSelector->addItem (midiOuts[i], i + 1);
  58857. int current = -1;
  58858. if (deviceManager.getDefaultMidiOutput() != 0)
  58859. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  58860. midiOutputSelector->setSelectedId (current, true);
  58861. }
  58862. resized();
  58863. }
  58864. END_JUCE_NAMESPACE
  58865. /*** End of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  58866. /*** Start of inlined file: juce_BubbleComponent.cpp ***/
  58867. BEGIN_JUCE_NAMESPACE
  58868. BubbleComponent::BubbleComponent()
  58869. : side (0),
  58870. allowablePlacements (above | below | left | right),
  58871. arrowTipX (0.0f),
  58872. arrowTipY (0.0f)
  58873. {
  58874. setInterceptsMouseClicks (false, false);
  58875. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  58876. setComponentEffect (&shadow);
  58877. }
  58878. BubbleComponent::~BubbleComponent()
  58879. {
  58880. }
  58881. void BubbleComponent::paint (Graphics& g)
  58882. {
  58883. int x = content.getX();
  58884. int y = content.getY();
  58885. int w = content.getWidth();
  58886. int h = content.getHeight();
  58887. int cw, ch;
  58888. getContentSize (cw, ch);
  58889. if (side == 3)
  58890. x += w - cw;
  58891. else if (side != 1)
  58892. x += (w - cw) / 2;
  58893. w = cw;
  58894. if (side == 2)
  58895. y += h - ch;
  58896. else if (side != 0)
  58897. y += (h - ch) / 2;
  58898. h = ch;
  58899. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  58900. (float) x, (float) y,
  58901. (float) w, (float) h);
  58902. const int cx = x + (w - cw) / 2;
  58903. const int cy = y + (h - ch) / 2;
  58904. const int indent = 3;
  58905. g.setOrigin (cx + indent, cy + indent);
  58906. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  58907. paintContent (g, cw - indent * 2, ch - indent * 2);
  58908. }
  58909. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  58910. {
  58911. allowablePlacements = newPlacement;
  58912. }
  58913. void BubbleComponent::setPosition (Component* componentToPointTo)
  58914. {
  58915. jassert (componentToPointTo->isValidComponent());
  58916. Point<int> pos;
  58917. if (getParentComponent() != 0)
  58918. pos = componentToPointTo->relativePositionToOtherComponent (getParentComponent(), pos);
  58919. else
  58920. pos = componentToPointTo->relativePositionToGlobal (pos);
  58921. setPosition (Rectangle<int> (pos.getX(), pos.getY(), componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  58922. }
  58923. void BubbleComponent::setPosition (const int arrowTipX_,
  58924. const int arrowTipY_)
  58925. {
  58926. setPosition (Rectangle<int> (arrowTipX_, arrowTipY_, 1, 1));
  58927. }
  58928. void BubbleComponent::setPosition (const Rectangle<int>& rectangleToPointTo)
  58929. {
  58930. Rectangle<int> availableSpace;
  58931. if (getParentComponent() != 0)
  58932. {
  58933. availableSpace.setSize (getParentComponent()->getWidth(),
  58934. getParentComponent()->getHeight());
  58935. }
  58936. else
  58937. {
  58938. availableSpace = getParentMonitorArea();
  58939. }
  58940. int x = 0;
  58941. int y = 0;
  58942. int w = 150;
  58943. int h = 30;
  58944. getContentSize (w, h);
  58945. w += 30;
  58946. h += 30;
  58947. const float edgeIndent = 2.0f;
  58948. const int arrowLength = jmin (10, h / 3, w / 3);
  58949. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  58950. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  58951. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  58952. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  58953. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  58954. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  58955. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  58956. {
  58957. spaceLeft = spaceRight = 0;
  58958. }
  58959. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  58960. && (spaceLeft > w + 20 || spaceRight > w + 20))
  58961. {
  58962. spaceAbove = spaceBelow = 0;
  58963. }
  58964. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  58965. {
  58966. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  58967. arrowTipX = w * 0.5f;
  58968. content.setSize (w, h - arrowLength);
  58969. if (spaceAbove >= spaceBelow)
  58970. {
  58971. // above
  58972. y = rectangleToPointTo.getY() - h;
  58973. content.setPosition (0, 0);
  58974. arrowTipY = h - edgeIndent;
  58975. side = 2;
  58976. }
  58977. else
  58978. {
  58979. // below
  58980. y = rectangleToPointTo.getBottom();
  58981. content.setPosition (0, arrowLength);
  58982. arrowTipY = edgeIndent;
  58983. side = 0;
  58984. }
  58985. }
  58986. else
  58987. {
  58988. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  58989. arrowTipY = h * 0.5f;
  58990. content.setSize (w - arrowLength, h);
  58991. if (spaceLeft > spaceRight)
  58992. {
  58993. // on the left
  58994. x = rectangleToPointTo.getX() - w;
  58995. content.setPosition (0, 0);
  58996. arrowTipX = w - edgeIndent;
  58997. side = 3;
  58998. }
  58999. else
  59000. {
  59001. // on the right
  59002. x = rectangleToPointTo.getRight();
  59003. content.setPosition (arrowLength, 0);
  59004. arrowTipX = edgeIndent;
  59005. side = 1;
  59006. }
  59007. }
  59008. setBounds (x, y, w, h);
  59009. }
  59010. END_JUCE_NAMESPACE
  59011. /*** End of inlined file: juce_BubbleComponent.cpp ***/
  59012. /*** Start of inlined file: juce_BubbleMessageComponent.cpp ***/
  59013. BEGIN_JUCE_NAMESPACE
  59014. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  59015. : fadeOutLength (fadeOutLengthMs),
  59016. deleteAfterUse (false)
  59017. {
  59018. }
  59019. BubbleMessageComponent::~BubbleMessageComponent()
  59020. {
  59021. fadeOutComponent (fadeOutLength);
  59022. }
  59023. void BubbleMessageComponent::showAt (int x, int y,
  59024. const String& text,
  59025. const int numMillisecondsBeforeRemoving,
  59026. const bool removeWhenMouseClicked,
  59027. const bool deleteSelfAfterUse)
  59028. {
  59029. textLayout.clear();
  59030. textLayout.setText (text, Font (14.0f));
  59031. textLayout.layout (256, Justification::centredLeft, true);
  59032. setPosition (x, y);
  59033. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59034. }
  59035. void BubbleMessageComponent::showAt (Component* const component,
  59036. const String& text,
  59037. const int numMillisecondsBeforeRemoving,
  59038. const bool removeWhenMouseClicked,
  59039. const bool deleteSelfAfterUse)
  59040. {
  59041. textLayout.clear();
  59042. textLayout.setText (text, Font (14.0f));
  59043. textLayout.layout (256, Justification::centredLeft, true);
  59044. setPosition (component);
  59045. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59046. }
  59047. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  59048. const bool removeWhenMouseClicked,
  59049. const bool deleteSelfAfterUse)
  59050. {
  59051. setVisible (true);
  59052. deleteAfterUse = deleteSelfAfterUse;
  59053. if (numMillisecondsBeforeRemoving > 0)
  59054. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  59055. else
  59056. expiryTime = 0;
  59057. startTimer (77);
  59058. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  59059. if (! (removeWhenMouseClicked && isShowing()))
  59060. mouseClickCounter += 0xfffff;
  59061. repaint();
  59062. }
  59063. void BubbleMessageComponent::getContentSize (int& w, int& h)
  59064. {
  59065. w = textLayout.getWidth() + 16;
  59066. h = textLayout.getHeight() + 16;
  59067. }
  59068. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  59069. {
  59070. g.setColour (findColour (TooltipWindow::textColourId));
  59071. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  59072. }
  59073. void BubbleMessageComponent::timerCallback()
  59074. {
  59075. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  59076. {
  59077. stopTimer();
  59078. setVisible (false);
  59079. if (deleteAfterUse)
  59080. delete this;
  59081. }
  59082. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  59083. {
  59084. stopTimer();
  59085. fadeOutComponent (fadeOutLength);
  59086. if (deleteAfterUse)
  59087. delete this;
  59088. }
  59089. }
  59090. END_JUCE_NAMESPACE
  59091. /*** End of inlined file: juce_BubbleMessageComponent.cpp ***/
  59092. /*** Start of inlined file: juce_ColourSelector.cpp ***/
  59093. BEGIN_JUCE_NAMESPACE
  59094. class ColourComponentSlider : public Slider
  59095. {
  59096. public:
  59097. ColourComponentSlider (const String& name)
  59098. : Slider (name)
  59099. {
  59100. setRange (0.0, 255.0, 1.0);
  59101. }
  59102. ~ColourComponentSlider()
  59103. {
  59104. }
  59105. const String getTextFromValue (double value)
  59106. {
  59107. return String::toHexString ((int) value).toUpperCase().paddedLeft ('0', 2);
  59108. }
  59109. double getValueFromText (const String& text)
  59110. {
  59111. return (double) text.getHexValue32();
  59112. }
  59113. private:
  59114. ColourComponentSlider (const ColourComponentSlider&);
  59115. ColourComponentSlider& operator= (const ColourComponentSlider&);
  59116. };
  59117. class ColourSpaceMarker : public Component
  59118. {
  59119. public:
  59120. ColourSpaceMarker()
  59121. {
  59122. setInterceptsMouseClicks (false, false);
  59123. }
  59124. ~ColourSpaceMarker()
  59125. {
  59126. }
  59127. void paint (Graphics& g)
  59128. {
  59129. g.setColour (Colour::greyLevel (0.1f));
  59130. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  59131. g.setColour (Colour::greyLevel (0.9f));
  59132. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  59133. }
  59134. private:
  59135. ColourSpaceMarker (const ColourSpaceMarker&);
  59136. ColourSpaceMarker& operator= (const ColourSpaceMarker&);
  59137. };
  59138. class ColourSelector::ColourSpaceView : public Component
  59139. {
  59140. public:
  59141. ColourSpaceView (ColourSelector* owner_,
  59142. float& h_, float& s_, float& v_,
  59143. const int edgeSize)
  59144. : owner (owner_),
  59145. h (h_), s (s_), v (v_),
  59146. lastHue (0.0f),
  59147. edge (edgeSize)
  59148. {
  59149. addAndMakeVisible (marker = new ColourSpaceMarker());
  59150. setMouseCursor (MouseCursor::CrosshairCursor);
  59151. }
  59152. ~ColourSpaceView()
  59153. {
  59154. deleteAllChildren();
  59155. }
  59156. void paint (Graphics& g)
  59157. {
  59158. if (colours.isNull())
  59159. {
  59160. const int width = getWidth() / 2;
  59161. const int height = getHeight() / 2;
  59162. colours = Image (Image::RGB, width, height, false);
  59163. Image::BitmapData pixels (colours, 0, 0, width, height, true);
  59164. for (int y = 0; y < height; ++y)
  59165. {
  59166. const float val = 1.0f - y / (float) height;
  59167. for (int x = 0; x < width; ++x)
  59168. {
  59169. const float sat = x / (float) width;
  59170. pixels.setPixelColour (x, y, Colour (h, sat, val, 1.0f));
  59171. }
  59172. }
  59173. }
  59174. g.setOpacity (1.0f);
  59175. g.drawImage (colours, edge, edge, getWidth() - edge * 2, getHeight() - edge * 2,
  59176. 0, 0, colours.getWidth(), colours.getHeight());
  59177. }
  59178. void mouseDown (const MouseEvent& e)
  59179. {
  59180. mouseDrag (e);
  59181. }
  59182. void mouseDrag (const MouseEvent& e)
  59183. {
  59184. const float sat = (e.x - edge) / (float) (getWidth() - edge * 2);
  59185. const float val = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  59186. owner->setSV (sat, val);
  59187. }
  59188. void updateIfNeeded()
  59189. {
  59190. if (lastHue != h)
  59191. {
  59192. lastHue = h;
  59193. colours = Image();
  59194. repaint();
  59195. }
  59196. updateMarker();
  59197. }
  59198. void resized()
  59199. {
  59200. colours = Image();
  59201. updateMarker();
  59202. }
  59203. private:
  59204. ColourSelector* const owner;
  59205. float& h;
  59206. float& s;
  59207. float& v;
  59208. float lastHue;
  59209. ColourSpaceMarker* marker;
  59210. const int edge;
  59211. Image colours;
  59212. void updateMarker() const
  59213. {
  59214. marker->setBounds (roundToInt ((getWidth() - edge * 2) * s),
  59215. roundToInt ((getHeight() - edge * 2) * (1.0f - v)),
  59216. edge * 2, edge * 2);
  59217. }
  59218. ColourSpaceView (const ColourSpaceView&);
  59219. ColourSpaceView& operator= (const ColourSpaceView&);
  59220. };
  59221. class HueSelectorMarker : public Component
  59222. {
  59223. public:
  59224. HueSelectorMarker()
  59225. {
  59226. setInterceptsMouseClicks (false, false);
  59227. }
  59228. ~HueSelectorMarker()
  59229. {
  59230. }
  59231. void paint (Graphics& g)
  59232. {
  59233. Path p;
  59234. p.addTriangle (1.0f, 1.0f,
  59235. getWidth() * 0.3f, getHeight() * 0.5f,
  59236. 1.0f, getHeight() - 1.0f);
  59237. p.addTriangle (getWidth() - 1.0f, 1.0f,
  59238. getWidth() * 0.7f, getHeight() * 0.5f,
  59239. getWidth() - 1.0f, getHeight() - 1.0f);
  59240. g.setColour (Colours::white.withAlpha (0.75f));
  59241. g.fillPath (p);
  59242. g.setColour (Colours::black.withAlpha (0.75f));
  59243. g.strokePath (p, PathStrokeType (1.2f));
  59244. }
  59245. private:
  59246. HueSelectorMarker (const HueSelectorMarker&);
  59247. HueSelectorMarker& operator= (const HueSelectorMarker&);
  59248. };
  59249. class ColourSelector::HueSelectorComp : public Component
  59250. {
  59251. public:
  59252. HueSelectorComp (ColourSelector* owner_,
  59253. float& h_, float& s_, float& v_,
  59254. const int edgeSize)
  59255. : owner (owner_),
  59256. h (h_), s (s_), v (v_),
  59257. lastHue (0.0f),
  59258. edge (edgeSize)
  59259. {
  59260. addAndMakeVisible (marker = new HueSelectorMarker());
  59261. }
  59262. ~HueSelectorComp()
  59263. {
  59264. deleteAllChildren();
  59265. }
  59266. void paint (Graphics& g)
  59267. {
  59268. const float yScale = 1.0f / (getHeight() - edge * 2);
  59269. const Rectangle<int> clip (g.getClipBounds());
  59270. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  59271. {
  59272. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  59273. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  59274. }
  59275. }
  59276. void resized()
  59277. {
  59278. marker->setBounds (0, roundToInt ((getHeight() - edge * 2) * h),
  59279. getWidth(), edge * 2);
  59280. }
  59281. void mouseDown (const MouseEvent& e)
  59282. {
  59283. mouseDrag (e);
  59284. }
  59285. void mouseDrag (const MouseEvent& e)
  59286. {
  59287. const float hue = (e.y - edge) / (float) (getHeight() - edge * 2);
  59288. owner->setHue (hue);
  59289. }
  59290. void updateIfNeeded()
  59291. {
  59292. resized();
  59293. }
  59294. private:
  59295. ColourSelector* const owner;
  59296. float& h;
  59297. float& s;
  59298. float& v;
  59299. float lastHue;
  59300. HueSelectorMarker* marker;
  59301. const int edge;
  59302. HueSelectorComp (const HueSelectorComp&);
  59303. HueSelectorComp& operator= (const HueSelectorComp&);
  59304. };
  59305. class ColourSelector::SwatchComponent : public Component
  59306. {
  59307. public:
  59308. SwatchComponent (ColourSelector* owner_, int index_)
  59309. : owner (owner_),
  59310. index (index_)
  59311. {
  59312. }
  59313. ~SwatchComponent()
  59314. {
  59315. }
  59316. void paint (Graphics& g)
  59317. {
  59318. const Colour colour (owner->getSwatchColour (index));
  59319. g.fillCheckerBoard (0, 0, getWidth(), getHeight(),
  59320. 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. flags (flags_),
  59355. topSpace (0),
  59356. edgeGap (edgeGap_)
  59357. {
  59358. // not much point having a selector with no components in it!
  59359. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  59360. updateHSV();
  59361. if ((flags & showSliders) != 0)
  59362. {
  59363. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  59364. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  59365. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  59366. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  59367. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  59368. for (int i = 4; --i >= 0;)
  59369. sliders[i]->addListener (this);
  59370. }
  59371. else
  59372. {
  59373. zeromem (sliders, sizeof (sliders));
  59374. }
  59375. if ((flags & showColourspace) != 0)
  59376. {
  59377. addAndMakeVisible (colourSpace = new ColourSpaceView (this, h, s, v, gapAroundColourSpaceComponent));
  59378. addAndMakeVisible (hueSelector = new HueSelectorComp (this, h, s, v, gapAroundColourSpaceComponent));
  59379. }
  59380. else
  59381. {
  59382. colourSpace = 0;
  59383. hueSelector = 0;
  59384. }
  59385. update();
  59386. }
  59387. ColourSelector::~ColourSelector()
  59388. {
  59389. dispatchPendingMessages();
  59390. swatchComponents.clear();
  59391. deleteAllChildren();
  59392. }
  59393. const Colour ColourSelector::getCurrentColour() const
  59394. {
  59395. return ((flags & showAlphaChannel) != 0) ? colour
  59396. : colour.withAlpha ((uint8) 0xff);
  59397. }
  59398. void ColourSelector::setCurrentColour (const Colour& c)
  59399. {
  59400. if (c != colour)
  59401. {
  59402. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  59403. updateHSV();
  59404. update();
  59405. }
  59406. }
  59407. void ColourSelector::setHue (float newH)
  59408. {
  59409. newH = jlimit (0.0f, 1.0f, newH);
  59410. if (h != newH)
  59411. {
  59412. h = newH;
  59413. colour = Colour (h, s, v, colour.getFloatAlpha());
  59414. update();
  59415. }
  59416. }
  59417. void ColourSelector::setSV (float newS, float newV)
  59418. {
  59419. newS = jlimit (0.0f, 1.0f, newS);
  59420. newV = jlimit (0.0f, 1.0f, newV);
  59421. if (s != newS || v != newV)
  59422. {
  59423. s = newS;
  59424. v = newV;
  59425. colour = Colour (h, s, v, colour.getFloatAlpha());
  59426. update();
  59427. }
  59428. }
  59429. void ColourSelector::updateHSV()
  59430. {
  59431. colour.getHSB (h, s, v);
  59432. }
  59433. void ColourSelector::update()
  59434. {
  59435. if (sliders[0] != 0)
  59436. {
  59437. sliders[0]->setValue ((int) colour.getRed());
  59438. sliders[1]->setValue ((int) colour.getGreen());
  59439. sliders[2]->setValue ((int) colour.getBlue());
  59440. sliders[3]->setValue ((int) colour.getAlpha());
  59441. }
  59442. if (colourSpace != 0)
  59443. {
  59444. colourSpace->updateIfNeeded();
  59445. hueSelector->updateIfNeeded();
  59446. }
  59447. if ((flags & showColourAtTop) != 0)
  59448. repaint (0, edgeGap, getWidth(), topSpace - edgeGap);
  59449. sendChangeMessage (this);
  59450. }
  59451. void ColourSelector::paint (Graphics& g)
  59452. {
  59453. g.fillAll (findColour (backgroundColourId));
  59454. if ((flags & showColourAtTop) != 0)
  59455. {
  59456. const Colour currentColour (getCurrentColour());
  59457. g.fillCheckerBoard (edgeGap, edgeGap, getWidth() - edgeGap - edgeGap, topSpace - edgeGap - edgeGap,
  59458. 10, 10,
  59459. Colour (0xffdddddd).overlaidWith (currentColour),
  59460. Colour (0xffffffff).overlaidWith (currentColour));
  59461. g.setColour (Colours::white.overlaidWith (currentColour).contrasting());
  59462. g.setFont (14.0f, true);
  59463. g.drawText (currentColour.toDisplayString ((flags & showAlphaChannel) != 0),
  59464. 0, edgeGap, getWidth(), topSpace - edgeGap * 2,
  59465. Justification::centred, false);
  59466. }
  59467. if ((flags & showSliders) != 0)
  59468. {
  59469. g.setColour (findColour (labelTextColourId));
  59470. g.setFont (11.0f);
  59471. for (int i = 4; --i >= 0;)
  59472. {
  59473. if (sliders[i]->isVisible())
  59474. g.drawText (sliders[i]->getName() + ":",
  59475. 0, sliders[i]->getY(),
  59476. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  59477. Justification::centredRight, false);
  59478. }
  59479. }
  59480. }
  59481. void ColourSelector::resized()
  59482. {
  59483. const int swatchesPerRow = 8;
  59484. const int swatchHeight = 22;
  59485. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  59486. const int numSwatches = getNumSwatches();
  59487. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  59488. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  59489. topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  59490. int y = topSpace;
  59491. if ((flags & showColourspace) != 0)
  59492. {
  59493. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  59494. colourSpace->setBounds (edgeGap, y,
  59495. getWidth() - hueWidth - edgeGap - 4,
  59496. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  59497. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  59498. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  59499. colourSpace->getHeight());
  59500. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  59501. }
  59502. if ((flags & showSliders) != 0)
  59503. {
  59504. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  59505. for (int i = 0; i < numSliders; ++i)
  59506. {
  59507. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  59508. proportionOfWidth (0.72f), sliderHeight - 2);
  59509. y += sliderHeight;
  59510. }
  59511. }
  59512. if (numSwatches > 0)
  59513. {
  59514. const int startX = 8;
  59515. const int xGap = 4;
  59516. const int yGap = 4;
  59517. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  59518. y += edgeGap;
  59519. if (swatchComponents.size() != numSwatches)
  59520. {
  59521. swatchComponents.clear();
  59522. for (int i = 0; i < numSwatches; ++i)
  59523. {
  59524. SwatchComponent* const sc = new SwatchComponent (this, i);
  59525. swatchComponents.add (sc);
  59526. addAndMakeVisible (sc);
  59527. }
  59528. }
  59529. int x = startX;
  59530. for (int i = 0; i < swatchComponents.size(); ++i)
  59531. {
  59532. SwatchComponent* const sc = swatchComponents.getUnchecked(i);
  59533. sc->setBounds (x + xGap / 2,
  59534. y + yGap / 2,
  59535. swatchWidth - xGap,
  59536. swatchHeight - yGap);
  59537. if (((i + 1) % swatchesPerRow) == 0)
  59538. {
  59539. x = startX;
  59540. y += swatchHeight;
  59541. }
  59542. else
  59543. {
  59544. x += swatchWidth;
  59545. }
  59546. }
  59547. }
  59548. }
  59549. void ColourSelector::sliderValueChanged (Slider*)
  59550. {
  59551. if (sliders[0] != 0)
  59552. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  59553. (uint8) sliders[1]->getValue(),
  59554. (uint8) sliders[2]->getValue(),
  59555. (uint8) sliders[3]->getValue()));
  59556. }
  59557. int ColourSelector::getNumSwatches() const
  59558. {
  59559. return 0;
  59560. }
  59561. const Colour ColourSelector::getSwatchColour (const int) const
  59562. {
  59563. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  59564. return Colours::black;
  59565. }
  59566. void ColourSelector::setSwatchColour (const int, const Colour&) const
  59567. {
  59568. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  59569. }
  59570. END_JUCE_NAMESPACE
  59571. /*** End of inlined file: juce_ColourSelector.cpp ***/
  59572. /*** Start of inlined file: juce_DropShadower.cpp ***/
  59573. BEGIN_JUCE_NAMESPACE
  59574. class ShadowWindow : public Component
  59575. {
  59576. Component* owner;
  59577. Image shadowImageSections [12];
  59578. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  59579. public:
  59580. ShadowWindow (Component* const owner_,
  59581. const int type_,
  59582. const Image shadowImageSections_ [12])
  59583. : owner (owner_),
  59584. type (type_)
  59585. {
  59586. for (int i = 0; i < numElementsInArray (shadowImageSections); ++i)
  59587. shadowImageSections [i] = shadowImageSections_ [i];
  59588. setInterceptsMouseClicks (false, false);
  59589. if (owner_->isOnDesktop())
  59590. {
  59591. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  59592. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  59593. | ComponentPeer::windowIsTemporary
  59594. | ComponentPeer::windowIgnoresKeyPresses);
  59595. }
  59596. else if (owner_->getParentComponent() != 0)
  59597. {
  59598. owner_->getParentComponent()->addChildComponent (this);
  59599. }
  59600. }
  59601. ~ShadowWindow()
  59602. {
  59603. }
  59604. void paint (Graphics& g)
  59605. {
  59606. const Image& topLeft = shadowImageSections [type * 3];
  59607. const Image& bottomRight = shadowImageSections [type * 3 + 1];
  59608. const Image& filler = shadowImageSections [type * 3 + 2];
  59609. g.setOpacity (1.0f);
  59610. if (type < 2)
  59611. {
  59612. int imH = jmin (topLeft.getHeight(), getHeight() / 2);
  59613. g.drawImage (topLeft,
  59614. 0, 0, topLeft.getWidth(), imH,
  59615. 0, 0, topLeft.getWidth(), imH);
  59616. imH = jmin (bottomRight.getHeight(), getHeight() - getHeight() / 2);
  59617. g.drawImage (bottomRight,
  59618. 0, getHeight() - imH, bottomRight.getWidth(), imH,
  59619. 0, bottomRight.getHeight() - imH, bottomRight.getWidth(), imH);
  59620. g.setTiledImageFill (filler, 0, 0, 1.0f);
  59621. g.fillRect (0, topLeft.getHeight(), getWidth(), getHeight() - (topLeft.getHeight() + bottomRight.getHeight()));
  59622. }
  59623. else
  59624. {
  59625. int imW = jmin (topLeft.getWidth(), getWidth() / 2);
  59626. g.drawImage (topLeft,
  59627. 0, 0, imW, topLeft.getHeight(),
  59628. 0, 0, imW, topLeft.getHeight());
  59629. imW = jmin (bottomRight.getWidth(), getWidth() - getWidth() / 2);
  59630. g.drawImage (bottomRight,
  59631. getWidth() - imW, 0, imW, bottomRight.getHeight(),
  59632. bottomRight.getWidth() - imW, 0, imW, bottomRight.getHeight());
  59633. g.setTiledImageFill (filler, 0, 0, 1.0f);
  59634. g.fillRect (topLeft.getWidth(), 0, getWidth() - (topLeft.getWidth() + bottomRight.getWidth()), getHeight());
  59635. }
  59636. }
  59637. void resized()
  59638. {
  59639. repaint(); // (needed for correct repainting)
  59640. }
  59641. private:
  59642. ShadowWindow (const ShadowWindow&);
  59643. ShadowWindow& operator= (const ShadowWindow&);
  59644. };
  59645. DropShadower::DropShadower (const float alpha_,
  59646. const int xOffset_,
  59647. const int yOffset_,
  59648. const float blurRadius_)
  59649. : owner (0),
  59650. numShadows (0),
  59651. shadowEdge (jmax (xOffset_, yOffset_) + (int) blurRadius_),
  59652. xOffset (xOffset_),
  59653. yOffset (yOffset_),
  59654. alpha (alpha_),
  59655. blurRadius (blurRadius_),
  59656. inDestructor (false),
  59657. reentrant (false)
  59658. {
  59659. }
  59660. DropShadower::~DropShadower()
  59661. {
  59662. if (owner != 0)
  59663. owner->removeComponentListener (this);
  59664. inDestructor = true;
  59665. deleteShadowWindows();
  59666. }
  59667. void DropShadower::deleteShadowWindows()
  59668. {
  59669. if (numShadows > 0)
  59670. {
  59671. int i;
  59672. for (i = numShadows; --i >= 0;)
  59673. delete shadowWindows[i];
  59674. numShadows = 0;
  59675. }
  59676. }
  59677. void DropShadower::setOwner (Component* componentToFollow)
  59678. {
  59679. if (componentToFollow != owner)
  59680. {
  59681. if (owner != 0)
  59682. owner->removeComponentListener (this);
  59683. // (the component can't be null)
  59684. jassert (componentToFollow != 0);
  59685. owner = componentToFollow;
  59686. jassert (owner != 0);
  59687. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  59688. owner->addComponentListener (this);
  59689. updateShadows();
  59690. }
  59691. }
  59692. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  59693. {
  59694. updateShadows();
  59695. }
  59696. void DropShadower::componentBroughtToFront (Component&)
  59697. {
  59698. bringShadowWindowsToFront();
  59699. }
  59700. void DropShadower::componentChildrenChanged (Component&)
  59701. {
  59702. }
  59703. void DropShadower::componentParentHierarchyChanged (Component&)
  59704. {
  59705. deleteShadowWindows();
  59706. updateShadows();
  59707. }
  59708. void DropShadower::componentVisibilityChanged (Component&)
  59709. {
  59710. updateShadows();
  59711. }
  59712. void DropShadower::updateShadows()
  59713. {
  59714. if (reentrant || inDestructor || (owner == 0))
  59715. return;
  59716. reentrant = true;
  59717. ComponentPeer* const nw = owner->getPeer();
  59718. const bool isOwnerVisible = owner->isVisible()
  59719. && (nw == 0 || ! nw->isMinimised());
  59720. const bool createShadowWindows = numShadows == 0
  59721. && owner->getWidth() > 0
  59722. && owner->getHeight() > 0
  59723. && isOwnerVisible
  59724. && (Desktop::canUseSemiTransparentWindows()
  59725. || owner->getParentComponent() != 0);
  59726. if (createShadowWindows)
  59727. {
  59728. // keep a cached version of the image to save doing the gaussian too often
  59729. String imageId;
  59730. imageId << shadowEdge << ',' << xOffset << ',' << yOffset << ',' << alpha;
  59731. const int hash = imageId.hashCode();
  59732. Image bigIm (ImageCache::getFromHashCode (hash));
  59733. if (bigIm.isNull())
  59734. {
  59735. bigIm = Image (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true, Image::NativeImage);
  59736. Graphics bigG (bigIm);
  59737. bigG.setColour (Colours::black.withAlpha (alpha));
  59738. bigG.fillRect (shadowEdge + xOffset,
  59739. shadowEdge + yOffset,
  59740. bigIm.getWidth() - (shadowEdge * 2),
  59741. bigIm.getHeight() - (shadowEdge * 2));
  59742. ImageConvolutionKernel blurKernel (roundToInt (blurRadius * 2.0f));
  59743. blurKernel.createGaussianBlur (blurRadius);
  59744. blurKernel.applyToImage (bigIm, bigIm,
  59745. Rectangle<int> (xOffset, yOffset,
  59746. bigIm.getWidth(), bigIm.getHeight()));
  59747. ImageCache::addImageToCache (bigIm, hash);
  59748. }
  59749. const int iw = bigIm.getWidth();
  59750. const int ih = bigIm.getHeight();
  59751. const int shadowEdge2 = shadowEdge * 2;
  59752. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  59753. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  59754. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  59755. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  59756. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  59757. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  59758. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  59759. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  59760. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  59761. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  59762. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  59763. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  59764. for (int i = 0; i < 4; ++i)
  59765. {
  59766. shadowWindows[numShadows] = new ShadowWindow (owner, i, shadowImageSections);
  59767. ++numShadows;
  59768. }
  59769. }
  59770. if (numShadows > 0)
  59771. {
  59772. for (int i = numShadows; --i >= 0;)
  59773. {
  59774. shadowWindows[i]->setAlwaysOnTop (owner->isAlwaysOnTop());
  59775. shadowWindows[i]->setVisible (isOwnerVisible);
  59776. }
  59777. const int x = owner->getX();
  59778. const int y = owner->getY() - shadowEdge;
  59779. const int w = owner->getWidth();
  59780. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  59781. shadowWindows[0]->setBounds (x - shadowEdge,
  59782. y,
  59783. shadowEdge,
  59784. h);
  59785. shadowWindows[1]->setBounds (x + w,
  59786. y,
  59787. shadowEdge,
  59788. h);
  59789. shadowWindows[2]->setBounds (x,
  59790. y,
  59791. w,
  59792. shadowEdge);
  59793. shadowWindows[3]->setBounds (x,
  59794. owner->getBottom(),
  59795. w,
  59796. shadowEdge);
  59797. }
  59798. reentrant = false;
  59799. if (createShadowWindows)
  59800. bringShadowWindowsToFront();
  59801. }
  59802. void DropShadower::setShadowImage (const Image& src, const int num, const int w, const int h,
  59803. const int sx, const int sy)
  59804. {
  59805. shadowImageSections[num] = Image (Image::ARGB, w, h, true, Image::NativeImage);
  59806. Graphics g (shadowImageSections[num]);
  59807. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  59808. }
  59809. void DropShadower::bringShadowWindowsToFront()
  59810. {
  59811. if (! (inDestructor || reentrant))
  59812. {
  59813. updateShadows();
  59814. reentrant = true;
  59815. for (int i = numShadows; --i >= 0;)
  59816. shadowWindows[i]->toBehind (owner);
  59817. reentrant = false;
  59818. }
  59819. }
  59820. END_JUCE_NAMESPACE
  59821. /*** End of inlined file: juce_DropShadower.cpp ***/
  59822. /*** Start of inlined file: juce_MagnifierComponent.cpp ***/
  59823. BEGIN_JUCE_NAMESPACE
  59824. class MagnifyingPeer : public ComponentPeer
  59825. {
  59826. public:
  59827. MagnifyingPeer (Component* const component_,
  59828. MagnifierComponent* const magnifierComp_)
  59829. : ComponentPeer (component_, 0),
  59830. magnifierComp (magnifierComp_)
  59831. {
  59832. }
  59833. ~MagnifyingPeer()
  59834. {
  59835. }
  59836. void* getNativeHandle() const { return 0; }
  59837. void setVisible (bool) {}
  59838. void setTitle (const String&) {}
  59839. void setPosition (int, int) {}
  59840. void setSize (int, int) {}
  59841. void setBounds (int, int, int, int, bool) {}
  59842. void setMinimised (bool) {}
  59843. bool isMinimised() const { return false; }
  59844. void setFullScreen (bool) {}
  59845. bool isFullScreen() const { return false; }
  59846. const BorderSize getFrameSize() const { return BorderSize (0); }
  59847. bool setAlwaysOnTop (bool) { return true; }
  59848. void toFront (bool) {}
  59849. void toBehind (ComponentPeer*) {}
  59850. void setIcon (const Image&) {}
  59851. bool isFocused() const
  59852. {
  59853. return magnifierComp->hasKeyboardFocus (true);
  59854. }
  59855. void grabFocus()
  59856. {
  59857. ComponentPeer* peer = magnifierComp->getPeer();
  59858. if (peer != 0)
  59859. peer->grabFocus();
  59860. }
  59861. void textInputRequired (const Point<int>& position)
  59862. {
  59863. ComponentPeer* peer = magnifierComp->getPeer();
  59864. if (peer != 0)
  59865. peer->textInputRequired (position);
  59866. }
  59867. const Rectangle<int> getBounds() const
  59868. {
  59869. return Rectangle<int> (magnifierComp->getScreenX(), magnifierComp->getScreenY(),
  59870. component->getWidth(), component->getHeight());
  59871. }
  59872. const Point<int> getScreenPosition() const
  59873. {
  59874. return magnifierComp->getScreenPosition();
  59875. }
  59876. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  59877. {
  59878. const double zoom = magnifierComp->getScaleFactor();
  59879. return magnifierComp->relativePositionToGlobal (Point<int> (roundToInt (relativePosition.getX() * zoom),
  59880. roundToInt (relativePosition.getY() * zoom)));
  59881. }
  59882. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  59883. {
  59884. const Point<int> p (magnifierComp->globalPositionToRelative (screenPosition));
  59885. const double zoom = magnifierComp->getScaleFactor();
  59886. return Point<int> (roundToInt (p.getX() / zoom),
  59887. roundToInt (p.getY() / zoom));
  59888. }
  59889. bool contains (const Point<int>& position, bool) const
  59890. {
  59891. return ((unsigned int) position.getX()) < (unsigned int) magnifierComp->getWidth()
  59892. && ((unsigned int) position.getY()) < (unsigned int) magnifierComp->getHeight();
  59893. }
  59894. void repaint (const Rectangle<int>& area)
  59895. {
  59896. const double zoom = magnifierComp->getScaleFactor();
  59897. magnifierComp->repaint ((int) (area.getX() * zoom),
  59898. (int) (area.getY() * zoom),
  59899. roundToInt (area.getWidth() * zoom) + 1,
  59900. roundToInt (area.getHeight() * zoom) + 1);
  59901. }
  59902. void performAnyPendingRepaintsNow()
  59903. {
  59904. }
  59905. juce_UseDebuggingNewOperator
  59906. private:
  59907. MagnifierComponent* const magnifierComp;
  59908. MagnifyingPeer (const MagnifyingPeer&);
  59909. MagnifyingPeer& operator= (const MagnifyingPeer&);
  59910. };
  59911. class PeerHolderComp : public Component
  59912. {
  59913. public:
  59914. PeerHolderComp (MagnifierComponent* const magnifierComp_)
  59915. : magnifierComp (magnifierComp_)
  59916. {
  59917. setVisible (true);
  59918. }
  59919. ~PeerHolderComp()
  59920. {
  59921. }
  59922. ComponentPeer* createNewPeer (int, void*)
  59923. {
  59924. return new MagnifyingPeer (this, magnifierComp);
  59925. }
  59926. void childBoundsChanged (Component* c)
  59927. {
  59928. if (c != 0)
  59929. {
  59930. setSize (c->getWidth(), c->getHeight());
  59931. magnifierComp->childBoundsChanged (this);
  59932. }
  59933. }
  59934. void mouseWheelMove (const MouseEvent& e, float ix, float iy)
  59935. {
  59936. // unhandled mouse wheel moves can be referred upwards to the parent comp..
  59937. Component* const p = magnifierComp->getParentComponent();
  59938. if (p != 0)
  59939. p->mouseWheelMove (e.getEventRelativeTo (p), ix, iy);
  59940. }
  59941. private:
  59942. MagnifierComponent* const magnifierComp;
  59943. PeerHolderComp (const PeerHolderComp&);
  59944. PeerHolderComp& operator= (const PeerHolderComp&);
  59945. };
  59946. MagnifierComponent::MagnifierComponent (Component* const content_,
  59947. const bool deleteContentCompWhenNoLongerNeeded)
  59948. : content (content_),
  59949. scaleFactor (0.0),
  59950. peer (0),
  59951. deleteContent (deleteContentCompWhenNoLongerNeeded),
  59952. quality (Graphics::lowResamplingQuality),
  59953. mouseSource (0, true)
  59954. {
  59955. holderComp = new PeerHolderComp (this);
  59956. setScaleFactor (1.0);
  59957. }
  59958. MagnifierComponent::~MagnifierComponent()
  59959. {
  59960. delete holderComp;
  59961. if (deleteContent)
  59962. delete content;
  59963. }
  59964. void MagnifierComponent::setScaleFactor (double newScaleFactor)
  59965. {
  59966. jassert (newScaleFactor > 0.0); // hmm - unlikely to work well with a negative scale factor
  59967. newScaleFactor = jlimit (1.0 / 8.0, 1000.0, newScaleFactor);
  59968. if (scaleFactor != newScaleFactor)
  59969. {
  59970. scaleFactor = newScaleFactor;
  59971. if (scaleFactor == 1.0)
  59972. {
  59973. holderComp->removeFromDesktop();
  59974. peer = 0;
  59975. addChildComponent (content);
  59976. childBoundsChanged (content);
  59977. }
  59978. else
  59979. {
  59980. holderComp->addAndMakeVisible (content);
  59981. holderComp->childBoundsChanged (content);
  59982. childBoundsChanged (holderComp);
  59983. holderComp->addToDesktop (0);
  59984. peer = holderComp->getPeer();
  59985. }
  59986. repaint();
  59987. }
  59988. }
  59989. void MagnifierComponent::setResamplingQuality (Graphics::ResamplingQuality newQuality)
  59990. {
  59991. quality = newQuality;
  59992. }
  59993. void MagnifierComponent::paint (Graphics& g)
  59994. {
  59995. const int w = holderComp->getWidth();
  59996. const int h = holderComp->getHeight();
  59997. if (w == 0 || h == 0)
  59998. return;
  59999. const Rectangle<int> r (g.getClipBounds());
  60000. const int srcX = (int) (r.getX() / scaleFactor);
  60001. const int srcY = (int) (r.getY() / scaleFactor);
  60002. int srcW = roundToInt (r.getRight() / scaleFactor) - srcX;
  60003. int srcH = roundToInt (r.getBottom() / scaleFactor) - srcY;
  60004. if (scaleFactor >= 1.0)
  60005. {
  60006. ++srcW;
  60007. ++srcH;
  60008. }
  60009. Image temp (Image::ARGB, jmax (w, srcX + srcW), jmax (h, srcY + srcH), false);
  60010. temp.clear (Rectangle<int> (srcX, srcY, srcW, srcH));
  60011. {
  60012. Graphics g2 (temp);
  60013. g2.reduceClipRegion (srcX, srcY, srcW, srcH);
  60014. holderComp->paintEntireComponent (g2);
  60015. }
  60016. g.setImageResamplingQuality (quality);
  60017. g.drawImageTransformed (temp, temp.getBounds(),
  60018. AffineTransform::scale ((float) scaleFactor, (float) scaleFactor),
  60019. false);
  60020. }
  60021. void MagnifierComponent::childBoundsChanged (Component* c)
  60022. {
  60023. if (c != 0)
  60024. setSize (roundToInt (c->getWidth() * scaleFactor),
  60025. roundToInt (c->getHeight() * scaleFactor));
  60026. }
  60027. void MagnifierComponent::passOnMouseEventToPeer (const MouseEvent& e)
  60028. {
  60029. if (peer != 0)
  60030. mouseSource.handleEvent (peer, Point<int> (scaleInt (e.x), scaleInt (e.y)),
  60031. e.eventTime.toMilliseconds(), ModifierKeys::getCurrentModifiers());
  60032. }
  60033. void MagnifierComponent::mouseDown (const MouseEvent& e)
  60034. {
  60035. passOnMouseEventToPeer (e);
  60036. }
  60037. void MagnifierComponent::mouseUp (const MouseEvent& e)
  60038. {
  60039. passOnMouseEventToPeer (e);
  60040. }
  60041. void MagnifierComponent::mouseDrag (const MouseEvent& e)
  60042. {
  60043. passOnMouseEventToPeer (e);
  60044. }
  60045. void MagnifierComponent::mouseMove (const MouseEvent& e)
  60046. {
  60047. passOnMouseEventToPeer (e);
  60048. }
  60049. void MagnifierComponent::mouseEnter (const MouseEvent& e)
  60050. {
  60051. passOnMouseEventToPeer (e);
  60052. }
  60053. void MagnifierComponent::mouseExit (const MouseEvent& e)
  60054. {
  60055. passOnMouseEventToPeer (e);
  60056. }
  60057. void MagnifierComponent::mouseWheelMove (const MouseEvent& e, float ix, float iy)
  60058. {
  60059. if (peer != 0)
  60060. peer->handleMouseWheel (e.source.getIndex(),
  60061. Point<int> (scaleInt (e.x), scaleInt (e.y)), e.eventTime.toMilliseconds(),
  60062. ix * 256.0f, iy * 256.0f);
  60063. else
  60064. Component::mouseWheelMove (e, ix, iy);
  60065. }
  60066. int MagnifierComponent::scaleInt (const int n) const
  60067. {
  60068. return roundToInt (n / scaleFactor);
  60069. }
  60070. END_JUCE_NAMESPACE
  60071. /*** End of inlined file: juce_MagnifierComponent.cpp ***/
  60072. /*** Start of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60073. BEGIN_JUCE_NAMESPACE
  60074. class MidiKeyboardUpDownButton : public Button
  60075. {
  60076. public:
  60077. MidiKeyboardUpDownButton (MidiKeyboardComponent* const owner_,
  60078. const int delta_)
  60079. : Button (String::empty),
  60080. owner (owner_),
  60081. delta (delta_)
  60082. {
  60083. setOpaque (true);
  60084. }
  60085. ~MidiKeyboardUpDownButton()
  60086. {
  60087. }
  60088. void clicked()
  60089. {
  60090. int note = owner->getLowestVisibleKey();
  60091. if (delta < 0)
  60092. note = (note - 1) / 12;
  60093. else
  60094. note = note / 12 + 1;
  60095. owner->setLowestVisibleKey (note * 12);
  60096. }
  60097. void paintButton (Graphics& g,
  60098. bool isMouseOverButton,
  60099. bool isButtonDown)
  60100. {
  60101. owner->drawUpDownButton (g, getWidth(), getHeight(),
  60102. isMouseOverButton, isButtonDown,
  60103. delta > 0);
  60104. }
  60105. private:
  60106. MidiKeyboardComponent* const owner;
  60107. const int delta;
  60108. MidiKeyboardUpDownButton (const MidiKeyboardUpDownButton&);
  60109. MidiKeyboardUpDownButton& operator= (const MidiKeyboardUpDownButton&);
  60110. };
  60111. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  60112. const Orientation orientation_)
  60113. : state (state_),
  60114. xOffset (0),
  60115. blackNoteLength (1),
  60116. keyWidth (16.0f),
  60117. orientation (orientation_),
  60118. midiChannel (1),
  60119. midiInChannelMask (0xffff),
  60120. velocity (1.0f),
  60121. noteUnderMouse (-1),
  60122. mouseDownNote (-1),
  60123. rangeStart (0),
  60124. rangeEnd (127),
  60125. firstKey (12 * 4),
  60126. canScroll (true),
  60127. mouseDragging (false),
  60128. useMousePositionForVelocity (true),
  60129. keyMappingOctave (6),
  60130. octaveNumForMiddleC (3)
  60131. {
  60132. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (this, -1));
  60133. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (this, 1));
  60134. // initialise with a default set of querty key-mappings..
  60135. const char* const keymap = "awsedftgyhujkolp;";
  60136. for (int i = String (keymap).length(); --i >= 0;)
  60137. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  60138. setOpaque (true);
  60139. setWantsKeyboardFocus (true);
  60140. state.addListener (this);
  60141. }
  60142. MidiKeyboardComponent::~MidiKeyboardComponent()
  60143. {
  60144. state.removeListener (this);
  60145. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  60146. deleteAllChildren();
  60147. }
  60148. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  60149. {
  60150. keyWidth = widthInPixels;
  60151. resized();
  60152. }
  60153. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  60154. {
  60155. if (orientation != newOrientation)
  60156. {
  60157. orientation = newOrientation;
  60158. resized();
  60159. }
  60160. }
  60161. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  60162. const int highestNote)
  60163. {
  60164. jassert (lowestNote >= 0 && lowestNote <= 127);
  60165. jassert (highestNote >= 0 && highestNote <= 127);
  60166. jassert (lowestNote <= highestNote);
  60167. if (rangeStart != lowestNote || rangeEnd != highestNote)
  60168. {
  60169. rangeStart = jlimit (0, 127, lowestNote);
  60170. rangeEnd = jlimit (0, 127, highestNote);
  60171. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  60172. resized();
  60173. }
  60174. }
  60175. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  60176. {
  60177. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  60178. if (noteNumber != firstKey)
  60179. {
  60180. firstKey = noteNumber;
  60181. sendChangeMessage (this);
  60182. resized();
  60183. }
  60184. }
  60185. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  60186. {
  60187. if (canScroll != canScroll_)
  60188. {
  60189. canScroll = canScroll_;
  60190. resized();
  60191. }
  60192. }
  60193. void MidiKeyboardComponent::colourChanged()
  60194. {
  60195. repaint();
  60196. }
  60197. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  60198. {
  60199. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  60200. if (midiChannel != midiChannelNumber)
  60201. {
  60202. resetAnyKeysInUse();
  60203. midiChannel = jlimit (1, 16, midiChannelNumber);
  60204. }
  60205. }
  60206. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  60207. {
  60208. midiInChannelMask = midiChannelMask;
  60209. triggerAsyncUpdate();
  60210. }
  60211. void MidiKeyboardComponent::setVelocity (const float velocity_, const bool useMousePositionForVelocity_)
  60212. {
  60213. velocity = jlimit (0.0f, 1.0f, velocity_);
  60214. useMousePositionForVelocity = useMousePositionForVelocity_;
  60215. }
  60216. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth_, int& x, int& w) const
  60217. {
  60218. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  60219. static const float blackNoteWidth = 0.7f;
  60220. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  60221. 1.0f, 2 - blackNoteWidth * 0.4f,
  60222. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  60223. 4.0f, 5 - blackNoteWidth * 0.5f,
  60224. 5.0f, 6 - blackNoteWidth * 0.3f,
  60225. 6.0f };
  60226. static const float widths[] = { 1.0f, blackNoteWidth,
  60227. 1.0f, blackNoteWidth,
  60228. 1.0f, 1.0f, blackNoteWidth,
  60229. 1.0f, blackNoteWidth,
  60230. 1.0f, blackNoteWidth,
  60231. 1.0f };
  60232. const int octave = midiNoteNumber / 12;
  60233. const int note = midiNoteNumber % 12;
  60234. x = roundToInt (octave * 7.0f * keyWidth_ + notePos [note] * keyWidth_);
  60235. w = roundToInt (widths [note] * keyWidth_);
  60236. }
  60237. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  60238. {
  60239. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  60240. int rx, rw;
  60241. getKeyPosition (rangeStart, keyWidth, rx, rw);
  60242. x -= xOffset + rx;
  60243. }
  60244. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  60245. {
  60246. int x, y;
  60247. getKeyPos (midiNoteNumber, x, y);
  60248. return x;
  60249. }
  60250. const uint8 MidiKeyboardComponent::whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  60251. const uint8 MidiKeyboardComponent::blackNotes[] = { 1, 3, 6, 8, 10 };
  60252. int MidiKeyboardComponent::xyToNote (const Point<int>& pos, float& mousePositionVelocity)
  60253. {
  60254. if (! reallyContains (pos.getX(), pos.getY(), false))
  60255. return -1;
  60256. Point<int> p (pos);
  60257. if (orientation != horizontalKeyboard)
  60258. {
  60259. p = Point<int> (p.getY(), p.getX());
  60260. if (orientation == verticalKeyboardFacingLeft)
  60261. p = Point<int> (p.getX(), getWidth() - p.getY());
  60262. else
  60263. p = Point<int> (getHeight() - p.getX(), p.getY());
  60264. }
  60265. return remappedXYToNote (p + Point<int> (xOffset, 0), mousePositionVelocity);
  60266. }
  60267. int MidiKeyboardComponent::remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const
  60268. {
  60269. if (pos.getY() < blackNoteLength)
  60270. {
  60271. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60272. {
  60273. for (int i = 0; i < 5; ++i)
  60274. {
  60275. const int note = octaveStart + blackNotes [i];
  60276. if (note >= rangeStart && note <= rangeEnd)
  60277. {
  60278. int kx, kw;
  60279. getKeyPos (note, kx, kw);
  60280. kx += xOffset;
  60281. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60282. {
  60283. mousePositionVelocity = pos.getY() / (float) blackNoteLength;
  60284. return note;
  60285. }
  60286. }
  60287. }
  60288. }
  60289. }
  60290. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60291. {
  60292. for (int i = 0; i < 7; ++i)
  60293. {
  60294. const int note = octaveStart + whiteNotes [i];
  60295. if (note >= rangeStart && note <= rangeEnd)
  60296. {
  60297. int kx, kw;
  60298. getKeyPos (note, kx, kw);
  60299. kx += xOffset;
  60300. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60301. {
  60302. const int whiteNoteLength = (orientation == horizontalKeyboard) ? getHeight() : getWidth();
  60303. mousePositionVelocity = pos.getY() / (float) whiteNoteLength;
  60304. return note;
  60305. }
  60306. }
  60307. }
  60308. }
  60309. mousePositionVelocity = 0;
  60310. return -1;
  60311. }
  60312. void MidiKeyboardComponent::repaintNote (const int noteNum)
  60313. {
  60314. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60315. {
  60316. int x, w;
  60317. getKeyPos (noteNum, x, w);
  60318. if (orientation == horizontalKeyboard)
  60319. repaint (x, 0, w, getHeight());
  60320. else if (orientation == verticalKeyboardFacingLeft)
  60321. repaint (0, x, getWidth(), w);
  60322. else if (orientation == verticalKeyboardFacingRight)
  60323. repaint (0, getHeight() - x - w, getWidth(), w);
  60324. }
  60325. }
  60326. void MidiKeyboardComponent::paint (Graphics& g)
  60327. {
  60328. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  60329. const Colour lineColour (findColour (keySeparatorLineColourId));
  60330. const Colour textColour (findColour (textLabelColourId));
  60331. int x, w, octave;
  60332. for (octave = 0; octave < 128; octave += 12)
  60333. {
  60334. for (int white = 0; white < 7; ++white)
  60335. {
  60336. const int noteNum = octave + whiteNotes [white];
  60337. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60338. {
  60339. getKeyPos (noteNum, x, w);
  60340. if (orientation == horizontalKeyboard)
  60341. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  60342. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60343. noteUnderMouse == noteNum,
  60344. lineColour, textColour);
  60345. else if (orientation == verticalKeyboardFacingLeft)
  60346. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  60347. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60348. noteUnderMouse == noteNum,
  60349. lineColour, textColour);
  60350. else if (orientation == verticalKeyboardFacingRight)
  60351. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  60352. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60353. noteUnderMouse == noteNum,
  60354. lineColour, textColour);
  60355. }
  60356. }
  60357. }
  60358. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  60359. if (orientation == verticalKeyboardFacingLeft)
  60360. {
  60361. x1 = getWidth() - 1.0f;
  60362. x2 = getWidth() - 5.0f;
  60363. }
  60364. else if (orientation == verticalKeyboardFacingRight)
  60365. x2 = 5.0f;
  60366. else
  60367. y2 = 5.0f;
  60368. g.setGradientFill (ColourGradient (Colours::black.withAlpha (0.3f), x1, y1,
  60369. Colours::transparentBlack, x2, y2, false));
  60370. getKeyPos (rangeEnd, x, w);
  60371. x += w;
  60372. if (orientation == verticalKeyboardFacingLeft)
  60373. g.fillRect (getWidth() - 5, 0, 5, x);
  60374. else if (orientation == verticalKeyboardFacingRight)
  60375. g.fillRect (0, 0, 5, x);
  60376. else
  60377. g.fillRect (0, 0, x, 5);
  60378. g.setColour (lineColour);
  60379. if (orientation == verticalKeyboardFacingLeft)
  60380. g.fillRect (0, 0, 1, x);
  60381. else if (orientation == verticalKeyboardFacingRight)
  60382. g.fillRect (getWidth() - 1, 0, 1, x);
  60383. else
  60384. g.fillRect (0, getHeight() - 1, x, 1);
  60385. const Colour blackNoteColour (findColour (blackNoteColourId));
  60386. for (octave = 0; octave < 128; octave += 12)
  60387. {
  60388. for (int black = 0; black < 5; ++black)
  60389. {
  60390. const int noteNum = octave + blackNotes [black];
  60391. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60392. {
  60393. getKeyPos (noteNum, x, w);
  60394. if (orientation == horizontalKeyboard)
  60395. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  60396. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60397. noteUnderMouse == noteNum,
  60398. blackNoteColour);
  60399. else if (orientation == verticalKeyboardFacingLeft)
  60400. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  60401. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60402. noteUnderMouse == noteNum,
  60403. blackNoteColour);
  60404. else if (orientation == verticalKeyboardFacingRight)
  60405. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  60406. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60407. noteUnderMouse == noteNum,
  60408. blackNoteColour);
  60409. }
  60410. }
  60411. }
  60412. }
  60413. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  60414. Graphics& g, int x, int y, int w, int h,
  60415. bool isDown, bool isOver,
  60416. const Colour& lineColour,
  60417. const Colour& textColour)
  60418. {
  60419. Colour c (Colours::transparentWhite);
  60420. if (isDown)
  60421. c = findColour (keyDownOverlayColourId);
  60422. if (isOver)
  60423. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60424. g.setColour (c);
  60425. g.fillRect (x, y, w, h);
  60426. const String text (getWhiteNoteText (midiNoteNumber));
  60427. if (! text.isEmpty())
  60428. {
  60429. g.setColour (textColour);
  60430. Font f (jmin (12.0f, keyWidth * 0.9f));
  60431. f.setHorizontalScale (0.8f);
  60432. g.setFont (f);
  60433. Justification justification (Justification::centredBottom);
  60434. if (orientation == verticalKeyboardFacingLeft)
  60435. justification = Justification::centredLeft;
  60436. else if (orientation == verticalKeyboardFacingRight)
  60437. justification = Justification::centredRight;
  60438. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  60439. }
  60440. g.setColour (lineColour);
  60441. if (orientation == horizontalKeyboard)
  60442. g.fillRect (x, y, 1, h);
  60443. else if (orientation == verticalKeyboardFacingLeft)
  60444. g.fillRect (x, y, w, 1);
  60445. else if (orientation == verticalKeyboardFacingRight)
  60446. g.fillRect (x, y + h - 1, w, 1);
  60447. if (midiNoteNumber == rangeEnd)
  60448. {
  60449. if (orientation == horizontalKeyboard)
  60450. g.fillRect (x + w, y, 1, h);
  60451. else if (orientation == verticalKeyboardFacingLeft)
  60452. g.fillRect (x, y + h, w, 1);
  60453. else if (orientation == verticalKeyboardFacingRight)
  60454. g.fillRect (x, y - 1, w, 1);
  60455. }
  60456. }
  60457. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  60458. Graphics& g, int x, int y, int w, int h,
  60459. bool isDown, bool isOver,
  60460. const Colour& noteFillColour)
  60461. {
  60462. Colour c (noteFillColour);
  60463. if (isDown)
  60464. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  60465. if (isOver)
  60466. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60467. g.setColour (c);
  60468. g.fillRect (x, y, w, h);
  60469. if (isDown)
  60470. {
  60471. g.setColour (noteFillColour);
  60472. g.drawRect (x, y, w, h);
  60473. }
  60474. else
  60475. {
  60476. const int xIndent = jmax (1, jmin (w, h) / 8);
  60477. g.setColour (c.brighter());
  60478. if (orientation == horizontalKeyboard)
  60479. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  60480. else if (orientation == verticalKeyboardFacingLeft)
  60481. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  60482. else if (orientation == verticalKeyboardFacingRight)
  60483. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  60484. }
  60485. }
  60486. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_)
  60487. {
  60488. octaveNumForMiddleC = octaveNumForMiddleC_;
  60489. repaint();
  60490. }
  60491. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  60492. {
  60493. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  60494. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  60495. return String::empty;
  60496. }
  60497. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  60498. const bool isMouseOver_,
  60499. const bool isButtonDown,
  60500. const bool movesOctavesUp)
  60501. {
  60502. g.fillAll (findColour (upDownButtonBackgroundColourId));
  60503. float angle;
  60504. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  60505. angle = movesOctavesUp ? 0.0f : 0.5f;
  60506. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  60507. angle = movesOctavesUp ? 0.25f : 0.75f;
  60508. else
  60509. angle = movesOctavesUp ? 0.75f : 0.25f;
  60510. Path path;
  60511. path.lineTo (0.0f, 1.0f);
  60512. path.lineTo (1.0f, 0.5f);
  60513. path.closeSubPath();
  60514. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  60515. g.setColour (findColour (upDownButtonArrowColourId)
  60516. .withAlpha (isButtonDown ? 1.0f : (isMouseOver_ ? 0.6f : 0.4f)));
  60517. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  60518. w - 2.0f,
  60519. h - 2.0f,
  60520. true));
  60521. }
  60522. void MidiKeyboardComponent::resized()
  60523. {
  60524. int w = getWidth();
  60525. int h = getHeight();
  60526. if (w > 0 && h > 0)
  60527. {
  60528. if (orientation != horizontalKeyboard)
  60529. swapVariables (w, h);
  60530. blackNoteLength = roundToInt (h * 0.7f);
  60531. int kx2, kw2;
  60532. getKeyPos (rangeEnd, kx2, kw2);
  60533. kx2 += kw2;
  60534. if (firstKey != rangeStart)
  60535. {
  60536. int kx1, kw1;
  60537. getKeyPos (rangeStart, kx1, kw1);
  60538. if (kx2 - kx1 <= w)
  60539. {
  60540. firstKey = rangeStart;
  60541. sendChangeMessage (this);
  60542. repaint();
  60543. }
  60544. }
  60545. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  60546. scrollDown->setVisible (showScrollButtons);
  60547. scrollUp->setVisible (showScrollButtons);
  60548. xOffset = 0;
  60549. if (showScrollButtons)
  60550. {
  60551. const int scrollButtonW = jmin (12, w / 2);
  60552. if (orientation == horizontalKeyboard)
  60553. {
  60554. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  60555. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  60556. }
  60557. else if (orientation == verticalKeyboardFacingLeft)
  60558. {
  60559. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  60560. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  60561. }
  60562. else if (orientation == verticalKeyboardFacingRight)
  60563. {
  60564. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  60565. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  60566. }
  60567. int endOfLastKey, kw;
  60568. getKeyPos (rangeEnd, endOfLastKey, kw);
  60569. endOfLastKey += kw;
  60570. float mousePositionVelocity;
  60571. const int spaceAvailable = w - scrollButtonW * 2;
  60572. const int lastStartKey = remappedXYToNote (Point<int> (endOfLastKey - spaceAvailable, 0), mousePositionVelocity) + 1;
  60573. if (lastStartKey >= 0 && firstKey > lastStartKey)
  60574. {
  60575. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  60576. sendChangeMessage (this);
  60577. }
  60578. int newOffset = 0;
  60579. getKeyPos (firstKey, newOffset, kw);
  60580. xOffset = newOffset - scrollButtonW;
  60581. }
  60582. else
  60583. {
  60584. firstKey = rangeStart;
  60585. }
  60586. timerCallback();
  60587. repaint();
  60588. }
  60589. }
  60590. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  60591. {
  60592. triggerAsyncUpdate();
  60593. }
  60594. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  60595. {
  60596. triggerAsyncUpdate();
  60597. }
  60598. void MidiKeyboardComponent::handleAsyncUpdate()
  60599. {
  60600. for (int i = rangeStart; i <= rangeEnd; ++i)
  60601. {
  60602. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  60603. {
  60604. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  60605. repaintNote (i);
  60606. }
  60607. }
  60608. }
  60609. void MidiKeyboardComponent::resetAnyKeysInUse()
  60610. {
  60611. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  60612. {
  60613. state.allNotesOff (midiChannel);
  60614. keysPressed.clear();
  60615. mouseDownNote = -1;
  60616. }
  60617. }
  60618. void MidiKeyboardComponent::updateNoteUnderMouse (const Point<int>& pos)
  60619. {
  60620. float mousePositionVelocity = 0.0f;
  60621. const int newNote = (mouseDragging || isMouseOver())
  60622. ? xyToNote (pos, mousePositionVelocity) : -1;
  60623. if (noteUnderMouse != newNote)
  60624. {
  60625. if (mouseDownNote >= 0)
  60626. {
  60627. state.noteOff (midiChannel, mouseDownNote);
  60628. mouseDownNote = -1;
  60629. }
  60630. if (mouseDragging && newNote >= 0)
  60631. {
  60632. if (! useMousePositionForVelocity)
  60633. mousePositionVelocity = 1.0f;
  60634. state.noteOn (midiChannel, newNote, mousePositionVelocity * velocity);
  60635. mouseDownNote = newNote;
  60636. }
  60637. repaintNote (noteUnderMouse);
  60638. noteUnderMouse = newNote;
  60639. repaintNote (noteUnderMouse);
  60640. }
  60641. else if (mouseDownNote >= 0 && ! mouseDragging)
  60642. {
  60643. state.noteOff (midiChannel, mouseDownNote);
  60644. mouseDownNote = -1;
  60645. }
  60646. }
  60647. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  60648. {
  60649. updateNoteUnderMouse (e.getPosition());
  60650. stopTimer();
  60651. }
  60652. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  60653. {
  60654. float mousePositionVelocity;
  60655. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  60656. if (newNote >= 0)
  60657. mouseDraggedToKey (newNote, e);
  60658. updateNoteUnderMouse (e.getPosition());
  60659. }
  60660. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  60661. {
  60662. return true;
  60663. }
  60664. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  60665. {
  60666. }
  60667. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  60668. {
  60669. float mousePositionVelocity;
  60670. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  60671. mouseDragging = false;
  60672. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  60673. {
  60674. repaintNote (noteUnderMouse);
  60675. noteUnderMouse = -1;
  60676. mouseDragging = true;
  60677. updateNoteUnderMouse (e.getPosition());
  60678. startTimer (500);
  60679. }
  60680. }
  60681. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  60682. {
  60683. mouseDragging = false;
  60684. updateNoteUnderMouse (e.getPosition());
  60685. stopTimer();
  60686. }
  60687. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  60688. {
  60689. updateNoteUnderMouse (e.getPosition());
  60690. }
  60691. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  60692. {
  60693. updateNoteUnderMouse (e.getPosition());
  60694. }
  60695. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  60696. {
  60697. setLowestVisibleKey (getLowestVisibleKey() + roundToInt ((ix != 0 ? ix : iy) * 5.0f));
  60698. }
  60699. void MidiKeyboardComponent::timerCallback()
  60700. {
  60701. updateNoteUnderMouse (getMouseXYRelative());
  60702. }
  60703. void MidiKeyboardComponent::clearKeyMappings()
  60704. {
  60705. resetAnyKeysInUse();
  60706. keyPressNotes.clear();
  60707. keyPresses.clear();
  60708. }
  60709. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  60710. const int midiNoteOffsetFromC)
  60711. {
  60712. removeKeyPressForNote (midiNoteOffsetFromC);
  60713. keyPressNotes.add (midiNoteOffsetFromC);
  60714. keyPresses.add (key);
  60715. }
  60716. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  60717. {
  60718. for (int i = keyPressNotes.size(); --i >= 0;)
  60719. {
  60720. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  60721. {
  60722. keyPressNotes.remove (i);
  60723. keyPresses.remove (i);
  60724. }
  60725. }
  60726. }
  60727. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  60728. {
  60729. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  60730. keyMappingOctave = newOctaveNumber;
  60731. }
  60732. bool MidiKeyboardComponent::keyStateChanged (const bool /*isKeyDown*/)
  60733. {
  60734. bool keyPressUsed = false;
  60735. for (int i = keyPresses.size(); --i >= 0;)
  60736. {
  60737. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  60738. if (keyPresses.getReference(i).isCurrentlyDown())
  60739. {
  60740. if (! keysPressed [note])
  60741. {
  60742. keysPressed.setBit (note);
  60743. state.noteOn (midiChannel, note, velocity);
  60744. keyPressUsed = true;
  60745. }
  60746. }
  60747. else
  60748. {
  60749. if (keysPressed [note])
  60750. {
  60751. keysPressed.clearBit (note);
  60752. state.noteOff (midiChannel, note);
  60753. keyPressUsed = true;
  60754. }
  60755. }
  60756. }
  60757. return keyPressUsed;
  60758. }
  60759. void MidiKeyboardComponent::focusLost (FocusChangeType)
  60760. {
  60761. resetAnyKeysInUse();
  60762. }
  60763. END_JUCE_NAMESPACE
  60764. /*** End of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60765. /*** Start of inlined file: juce_OpenGLComponent.cpp ***/
  60766. #if JUCE_OPENGL
  60767. BEGIN_JUCE_NAMESPACE
  60768. extern void juce_glViewport (const int w, const int h);
  60769. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  60770. const int alphaBits_,
  60771. const int depthBufferBits_,
  60772. const int stencilBufferBits_)
  60773. : redBits (bitsPerRGBComponent),
  60774. greenBits (bitsPerRGBComponent),
  60775. blueBits (bitsPerRGBComponent),
  60776. alphaBits (alphaBits_),
  60777. depthBufferBits (depthBufferBits_),
  60778. stencilBufferBits (stencilBufferBits_),
  60779. accumulationBufferRedBits (0),
  60780. accumulationBufferGreenBits (0),
  60781. accumulationBufferBlueBits (0),
  60782. accumulationBufferAlphaBits (0),
  60783. fullSceneAntiAliasingNumSamples (0)
  60784. {
  60785. }
  60786. OpenGLPixelFormat::OpenGLPixelFormat (const OpenGLPixelFormat& other)
  60787. : redBits (other.redBits),
  60788. greenBits (other.greenBits),
  60789. blueBits (other.blueBits),
  60790. alphaBits (other.alphaBits),
  60791. depthBufferBits (other.depthBufferBits),
  60792. stencilBufferBits (other.stencilBufferBits),
  60793. accumulationBufferRedBits (other.accumulationBufferRedBits),
  60794. accumulationBufferGreenBits (other.accumulationBufferGreenBits),
  60795. accumulationBufferBlueBits (other.accumulationBufferBlueBits),
  60796. accumulationBufferAlphaBits (other.accumulationBufferAlphaBits),
  60797. fullSceneAntiAliasingNumSamples (other.fullSceneAntiAliasingNumSamples)
  60798. {
  60799. }
  60800. OpenGLPixelFormat& OpenGLPixelFormat::operator= (const OpenGLPixelFormat& other)
  60801. {
  60802. redBits = other.redBits;
  60803. greenBits = other.greenBits;
  60804. blueBits = other.blueBits;
  60805. alphaBits = other.alphaBits;
  60806. depthBufferBits = other.depthBufferBits;
  60807. stencilBufferBits = other.stencilBufferBits;
  60808. accumulationBufferRedBits = other.accumulationBufferRedBits;
  60809. accumulationBufferGreenBits = other.accumulationBufferGreenBits;
  60810. accumulationBufferBlueBits = other.accumulationBufferBlueBits;
  60811. accumulationBufferAlphaBits = other.accumulationBufferAlphaBits;
  60812. fullSceneAntiAliasingNumSamples = other.fullSceneAntiAliasingNumSamples;
  60813. return *this;
  60814. }
  60815. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const
  60816. {
  60817. return redBits == other.redBits
  60818. && greenBits == other.greenBits
  60819. && blueBits == other.blueBits
  60820. && alphaBits == other.alphaBits
  60821. && depthBufferBits == other.depthBufferBits
  60822. && stencilBufferBits == other.stencilBufferBits
  60823. && accumulationBufferRedBits == other.accumulationBufferRedBits
  60824. && accumulationBufferGreenBits == other.accumulationBufferGreenBits
  60825. && accumulationBufferBlueBits == other.accumulationBufferBlueBits
  60826. && accumulationBufferAlphaBits == other.accumulationBufferAlphaBits
  60827. && fullSceneAntiAliasingNumSamples == other.fullSceneAntiAliasingNumSamples;
  60828. }
  60829. static Array<OpenGLContext*> knownContexts;
  60830. OpenGLContext::OpenGLContext() throw()
  60831. {
  60832. knownContexts.add (this);
  60833. }
  60834. OpenGLContext::~OpenGLContext()
  60835. {
  60836. knownContexts.removeValue (this);
  60837. }
  60838. OpenGLContext* OpenGLContext::getCurrentContext()
  60839. {
  60840. for (int i = knownContexts.size(); --i >= 0;)
  60841. {
  60842. OpenGLContext* const oglc = knownContexts.getUnchecked(i);
  60843. if (oglc->isActive())
  60844. return oglc;
  60845. }
  60846. return 0;
  60847. }
  60848. class OpenGLComponent::OpenGLComponentWatcher : public ComponentMovementWatcher
  60849. {
  60850. public:
  60851. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  60852. : ComponentMovementWatcher (owner_),
  60853. owner (owner_),
  60854. wasShowing (false)
  60855. {
  60856. }
  60857. ~OpenGLComponentWatcher() {}
  60858. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  60859. {
  60860. owner->updateContextPosition();
  60861. }
  60862. void componentPeerChanged()
  60863. {
  60864. const ScopedLock sl (owner->getContextLock());
  60865. owner->deleteContext();
  60866. }
  60867. void componentVisibilityChanged (Component&)
  60868. {
  60869. const bool isShowingNow = owner->isShowing();
  60870. if (wasShowing != isShowingNow)
  60871. {
  60872. wasShowing = isShowingNow;
  60873. if (! isShowingNow)
  60874. {
  60875. const ScopedLock sl (owner->getContextLock());
  60876. owner->deleteContext();
  60877. }
  60878. }
  60879. }
  60880. juce_UseDebuggingNewOperator
  60881. private:
  60882. OpenGLComponent* const owner;
  60883. bool wasShowing;
  60884. };
  60885. OpenGLComponent::OpenGLComponent (const OpenGLType type_)
  60886. : type (type_),
  60887. contextToShareListsWith (0),
  60888. needToUpdateViewport (true)
  60889. {
  60890. setOpaque (true);
  60891. componentWatcher = new OpenGLComponentWatcher (this);
  60892. }
  60893. OpenGLComponent::~OpenGLComponent()
  60894. {
  60895. deleteContext();
  60896. componentWatcher = 0;
  60897. }
  60898. void OpenGLComponent::deleteContext()
  60899. {
  60900. const ScopedLock sl (contextLock);
  60901. context = 0;
  60902. }
  60903. void OpenGLComponent::updateContextPosition()
  60904. {
  60905. needToUpdateViewport = true;
  60906. if (getWidth() > 0 && getHeight() > 0)
  60907. {
  60908. Component* const topComp = getTopLevelComponent();
  60909. if (topComp->getPeer() != 0)
  60910. {
  60911. const ScopedLock sl (contextLock);
  60912. if (context != 0)
  60913. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  60914. getScreenY() - topComp->getScreenY(),
  60915. getWidth(),
  60916. getHeight(),
  60917. topComp->getHeight());
  60918. }
  60919. }
  60920. }
  60921. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  60922. {
  60923. OpenGLPixelFormat pf;
  60924. const ScopedLock sl (contextLock);
  60925. if (context != 0)
  60926. pf = context->getPixelFormat();
  60927. return pf;
  60928. }
  60929. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  60930. {
  60931. if (! (preferredPixelFormat == formatToUse))
  60932. {
  60933. const ScopedLock sl (contextLock);
  60934. deleteContext();
  60935. preferredPixelFormat = formatToUse;
  60936. }
  60937. }
  60938. void OpenGLComponent::shareWith (OpenGLContext* c)
  60939. {
  60940. if (contextToShareListsWith != c)
  60941. {
  60942. const ScopedLock sl (contextLock);
  60943. deleteContext();
  60944. contextToShareListsWith = c;
  60945. }
  60946. }
  60947. bool OpenGLComponent::makeCurrentContextActive()
  60948. {
  60949. if (context == 0)
  60950. {
  60951. const ScopedLock sl (contextLock);
  60952. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  60953. {
  60954. context = createContext();
  60955. if (context != 0)
  60956. {
  60957. updateContextPosition();
  60958. if (context->makeActive())
  60959. newOpenGLContextCreated();
  60960. }
  60961. }
  60962. }
  60963. return context != 0 && context->makeActive();
  60964. }
  60965. void OpenGLComponent::makeCurrentContextInactive()
  60966. {
  60967. if (context != 0)
  60968. context->makeInactive();
  60969. }
  60970. bool OpenGLComponent::isActiveContext() const throw()
  60971. {
  60972. return context != 0 && context->isActive();
  60973. }
  60974. void OpenGLComponent::swapBuffers()
  60975. {
  60976. if (context != 0)
  60977. context->swapBuffers();
  60978. }
  60979. void OpenGLComponent::paint (Graphics&)
  60980. {
  60981. if (renderAndSwapBuffers())
  60982. {
  60983. ComponentPeer* const peer = getPeer();
  60984. if (peer != 0)
  60985. {
  60986. const Point<int> topLeft (getScreenPosition() - peer->getScreenPosition());
  60987. peer->addMaskedRegion (topLeft.getX(), topLeft.getY(), getWidth(), getHeight());
  60988. }
  60989. }
  60990. }
  60991. bool OpenGLComponent::renderAndSwapBuffers()
  60992. {
  60993. const ScopedLock sl (contextLock);
  60994. if (! makeCurrentContextActive())
  60995. return false;
  60996. if (needToUpdateViewport)
  60997. {
  60998. needToUpdateViewport = false;
  60999. juce_glViewport (getWidth(), getHeight());
  61000. }
  61001. renderOpenGL();
  61002. swapBuffers();
  61003. return true;
  61004. }
  61005. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  61006. {
  61007. Component::internalRepaint (x, y, w, h);
  61008. if (context != 0)
  61009. context->repaint();
  61010. }
  61011. END_JUCE_NAMESPACE
  61012. #endif
  61013. /*** End of inlined file: juce_OpenGLComponent.cpp ***/
  61014. /*** Start of inlined file: juce_PreferencesPanel.cpp ***/
  61015. BEGIN_JUCE_NAMESPACE
  61016. PreferencesPanel::PreferencesPanel()
  61017. : buttonSize (70)
  61018. {
  61019. }
  61020. PreferencesPanel::~PreferencesPanel()
  61021. {
  61022. currentPage = 0;
  61023. deleteAllChildren();
  61024. }
  61025. void PreferencesPanel::addSettingsPage (const String& title,
  61026. const Drawable* icon,
  61027. const Drawable* overIcon,
  61028. const Drawable* downIcon)
  61029. {
  61030. DrawableButton* button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  61031. button->setImages (icon, overIcon, downIcon);
  61032. button->setRadioGroupId (1);
  61033. button->addButtonListener (this);
  61034. button->setClickingTogglesState (true);
  61035. button->setWantsKeyboardFocus (false);
  61036. addAndMakeVisible (button);
  61037. resized();
  61038. if (currentPage == 0)
  61039. setCurrentPage (title);
  61040. }
  61041. void PreferencesPanel::addSettingsPage (const String& title,
  61042. const void* imageData,
  61043. const int imageDataSize)
  61044. {
  61045. DrawableImage icon, iconOver, iconDown;
  61046. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61047. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61048. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  61049. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61050. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  61051. addSettingsPage (title, &icon, &iconOver, &iconDown);
  61052. }
  61053. class PrefsDialogWindow : public DialogWindow
  61054. {
  61055. public:
  61056. PrefsDialogWindow (const String& dialogtitle,
  61057. const Colour& backgroundColour)
  61058. : DialogWindow (dialogtitle, backgroundColour, true)
  61059. {
  61060. }
  61061. ~PrefsDialogWindow()
  61062. {
  61063. }
  61064. void closeButtonPressed()
  61065. {
  61066. exitModalState (0);
  61067. }
  61068. private:
  61069. PrefsDialogWindow (const PrefsDialogWindow&);
  61070. PrefsDialogWindow& operator= (const PrefsDialogWindow&);
  61071. };
  61072. void PreferencesPanel::showInDialogBox (const String& dialogtitle,
  61073. int dialogWidth,
  61074. int dialogHeight,
  61075. const Colour& backgroundColour)
  61076. {
  61077. setSize (dialogWidth, dialogHeight);
  61078. PrefsDialogWindow dw (dialogtitle, backgroundColour);
  61079. dw.setContentComponent (this, true, true);
  61080. dw.centreAroundComponent (0, dw.getWidth(), dw.getHeight());
  61081. dw.runModalLoop();
  61082. dw.setContentComponent (0, false, false);
  61083. }
  61084. void PreferencesPanel::resized()
  61085. {
  61086. int x = 0;
  61087. for (int i = 0; i < getNumChildComponents(); ++i)
  61088. {
  61089. Component* c = getChildComponent (i);
  61090. if (dynamic_cast <DrawableButton*> (c) == 0)
  61091. {
  61092. c->setBounds (0, buttonSize + 5, getWidth(), getHeight() - buttonSize - 5);
  61093. }
  61094. else
  61095. {
  61096. c->setBounds (x, 0, buttonSize, buttonSize);
  61097. x += buttonSize;
  61098. }
  61099. }
  61100. }
  61101. void PreferencesPanel::paint (Graphics& g)
  61102. {
  61103. g.setColour (Colours::grey);
  61104. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  61105. }
  61106. void PreferencesPanel::setCurrentPage (const String& pageName)
  61107. {
  61108. if (currentPageName != pageName)
  61109. {
  61110. currentPageName = pageName;
  61111. currentPage = 0;
  61112. currentPage = createComponentForPage (pageName);
  61113. if (currentPage != 0)
  61114. {
  61115. addAndMakeVisible (currentPage);
  61116. currentPage->toBack();
  61117. resized();
  61118. }
  61119. for (int i = 0; i < getNumChildComponents(); ++i)
  61120. {
  61121. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  61122. if (db != 0 && db->getName() == pageName)
  61123. {
  61124. db->setToggleState (true, false);
  61125. break;
  61126. }
  61127. }
  61128. }
  61129. }
  61130. void PreferencesPanel::buttonClicked (Button*)
  61131. {
  61132. for (int i = 0; i < getNumChildComponents(); ++i)
  61133. {
  61134. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  61135. if (db != 0 && db->getToggleState())
  61136. {
  61137. setCurrentPage (db->getName());
  61138. break;
  61139. }
  61140. }
  61141. }
  61142. END_JUCE_NAMESPACE
  61143. /*** End of inlined file: juce_PreferencesPanel.cpp ***/
  61144. /*** Start of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61145. #if JUCE_WINDOWS || JUCE_LINUX
  61146. BEGIN_JUCE_NAMESPACE
  61147. SystemTrayIconComponent::SystemTrayIconComponent()
  61148. {
  61149. addToDesktop (0);
  61150. }
  61151. SystemTrayIconComponent::~SystemTrayIconComponent()
  61152. {
  61153. }
  61154. END_JUCE_NAMESPACE
  61155. #endif
  61156. /*** End of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61157. /*** Start of inlined file: juce_AlertWindow.cpp ***/
  61158. BEGIN_JUCE_NAMESPACE
  61159. class AlertWindowTextEditor : public TextEditor
  61160. {
  61161. public:
  61162. AlertWindowTextEditor (const String& name, const bool isPasswordBox)
  61163. : TextEditor (name, isPasswordBox ? getDefaultPasswordChar() : 0)
  61164. {
  61165. setSelectAllWhenFocused (true);
  61166. }
  61167. ~AlertWindowTextEditor()
  61168. {
  61169. }
  61170. void returnPressed()
  61171. {
  61172. // pass these up the component hierarchy to be trigger the buttons
  61173. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, '\n'));
  61174. }
  61175. void escapePressed()
  61176. {
  61177. // pass these up the component hierarchy to be trigger the buttons
  61178. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  61179. }
  61180. private:
  61181. AlertWindowTextEditor (const AlertWindowTextEditor&);
  61182. AlertWindowTextEditor& operator= (const AlertWindowTextEditor&);
  61183. static juce_wchar getDefaultPasswordChar() throw()
  61184. {
  61185. #if JUCE_LINUX
  61186. return 0x2022;
  61187. #else
  61188. return 0x25cf;
  61189. #endif
  61190. }
  61191. };
  61192. AlertWindow::AlertWindow (const String& title,
  61193. const String& message,
  61194. AlertIconType iconType,
  61195. Component* associatedComponent_)
  61196. : TopLevelWindow (title, true),
  61197. alertIconType (iconType),
  61198. associatedComponent (associatedComponent_)
  61199. {
  61200. if (message.isEmpty())
  61201. text = " "; // to force an update if the message is empty
  61202. setMessage (message);
  61203. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  61204. {
  61205. Component* const c = Desktop::getInstance().getComponent (i);
  61206. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  61207. {
  61208. setAlwaysOnTop (true);
  61209. break;
  61210. }
  61211. }
  61212. if (JUCEApplication::getInstance() == 0)
  61213. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  61214. lookAndFeelChanged();
  61215. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  61216. }
  61217. AlertWindow::~AlertWindow()
  61218. {
  61219. for (int i = customComps.size(); --i >= 0;)
  61220. removeChildComponent ((Component*) customComps[i]);
  61221. deleteAllChildren();
  61222. }
  61223. void AlertWindow::userTriedToCloseWindow()
  61224. {
  61225. exitModalState (0);
  61226. }
  61227. void AlertWindow::setMessage (const String& message)
  61228. {
  61229. const String newMessage (message.substring (0, 2048));
  61230. if (text != newMessage)
  61231. {
  61232. text = newMessage;
  61233. font.setHeight (15.0f);
  61234. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  61235. textLayout.setText (getName() + "\n\n", titleFont);
  61236. textLayout.appendText (text, font);
  61237. updateLayout (true);
  61238. repaint();
  61239. }
  61240. }
  61241. void AlertWindow::buttonClicked (Button* button)
  61242. {
  61243. for (int i = 0; i < buttons.size(); i++)
  61244. {
  61245. TextButton* const c = (TextButton*) buttons[i];
  61246. if (button->getName() == c->getName())
  61247. {
  61248. if (c->getParentComponent() != 0)
  61249. c->getParentComponent()->exitModalState (c->getCommandID());
  61250. break;
  61251. }
  61252. }
  61253. }
  61254. void AlertWindow::addButton (const String& name,
  61255. const int returnValue,
  61256. const KeyPress& shortcutKey1,
  61257. const KeyPress& shortcutKey2)
  61258. {
  61259. TextButton* const b = new TextButton (name, String::empty);
  61260. b->setWantsKeyboardFocus (true);
  61261. b->setMouseClickGrabsKeyboardFocus (false);
  61262. b->setCommandToTrigger (0, returnValue, false);
  61263. b->addShortcut (shortcutKey1);
  61264. b->addShortcut (shortcutKey2);
  61265. b->addButtonListener (this);
  61266. b->changeWidthToFitText (getLookAndFeel().getAlertWindowButtonHeight());
  61267. addAndMakeVisible (b, 0);
  61268. buttons.add (b);
  61269. updateLayout (false);
  61270. }
  61271. int AlertWindow::getNumButtons() const
  61272. {
  61273. return buttons.size();
  61274. }
  61275. void AlertWindow::triggerButtonClick (const String& buttonName)
  61276. {
  61277. for (int i = buttons.size(); --i >= 0;)
  61278. {
  61279. TextButton* const b = (TextButton*) buttons[i];
  61280. if (buttonName == b->getName())
  61281. {
  61282. b->triggerClick();
  61283. break;
  61284. }
  61285. }
  61286. }
  61287. void AlertWindow::addTextEditor (const String& name,
  61288. const String& initialContents,
  61289. const String& onScreenLabel,
  61290. const bool isPasswordBox)
  61291. {
  61292. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  61293. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  61294. tc->setFont (font);
  61295. tc->setText (initialContents);
  61296. tc->setCaretPosition (initialContents.length());
  61297. addAndMakeVisible (tc);
  61298. textBoxes.add (tc);
  61299. allComps.add (tc);
  61300. textboxNames.add (onScreenLabel);
  61301. updateLayout (false);
  61302. }
  61303. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  61304. {
  61305. for (int i = textBoxes.size(); --i >= 0;)
  61306. if (((TextEditor*)textBoxes[i])->getName() == nameOfTextEditor)
  61307. return ((TextEditor*)textBoxes[i])->getText();
  61308. return String::empty;
  61309. }
  61310. void AlertWindow::addComboBox (const String& name,
  61311. const StringArray& items,
  61312. const String& onScreenLabel)
  61313. {
  61314. ComboBox* const cb = new ComboBox (name);
  61315. for (int i = 0; i < items.size(); ++i)
  61316. cb->addItem (items[i], i + 1);
  61317. addAndMakeVisible (cb);
  61318. cb->setSelectedItemIndex (0);
  61319. comboBoxes.add (cb);
  61320. allComps.add (cb);
  61321. comboBoxNames.add (onScreenLabel);
  61322. updateLayout (false);
  61323. }
  61324. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  61325. {
  61326. for (int i = comboBoxes.size(); --i >= 0;)
  61327. if (((ComboBox*) comboBoxes[i])->getName() == nameOfList)
  61328. return (ComboBox*) comboBoxes[i];
  61329. return 0;
  61330. }
  61331. class AlertTextComp : public TextEditor
  61332. {
  61333. public:
  61334. AlertTextComp (const String& message,
  61335. const Font& font)
  61336. {
  61337. setReadOnly (true);
  61338. setMultiLine (true, true);
  61339. setCaretVisible (false);
  61340. setScrollbarsShown (true);
  61341. lookAndFeelChanged();
  61342. setWantsKeyboardFocus (false);
  61343. setFont (font);
  61344. setText (message, false);
  61345. bestWidth = 2 * (int) std::sqrt (font.getHeight() * font.getStringWidth (message));
  61346. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  61347. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  61348. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  61349. }
  61350. ~AlertTextComp()
  61351. {
  61352. }
  61353. int getPreferredWidth() const throw() { return bestWidth; }
  61354. void updateLayout (const int width)
  61355. {
  61356. TextLayout text;
  61357. text.appendText (getText(), getFont());
  61358. text.layout (width - 8, Justification::topLeft, true);
  61359. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  61360. }
  61361. private:
  61362. int bestWidth;
  61363. AlertTextComp (const AlertTextComp&);
  61364. AlertTextComp& operator= (const AlertTextComp&);
  61365. };
  61366. void AlertWindow::addTextBlock (const String& textBlock)
  61367. {
  61368. AlertTextComp* const c = new AlertTextComp (textBlock, font);
  61369. textBlocks.add (c);
  61370. allComps.add (c);
  61371. addAndMakeVisible (c);
  61372. updateLayout (false);
  61373. }
  61374. void AlertWindow::addProgressBarComponent (double& progressValue)
  61375. {
  61376. ProgressBar* const pb = new ProgressBar (progressValue);
  61377. progressBars.add (pb);
  61378. allComps.add (pb);
  61379. addAndMakeVisible (pb);
  61380. updateLayout (false);
  61381. }
  61382. void AlertWindow::addCustomComponent (Component* const component)
  61383. {
  61384. customComps.add (component);
  61385. allComps.add (component);
  61386. addAndMakeVisible (component);
  61387. updateLayout (false);
  61388. }
  61389. int AlertWindow::getNumCustomComponents() const
  61390. {
  61391. return customComps.size();
  61392. }
  61393. Component* AlertWindow::getCustomComponent (const int index) const
  61394. {
  61395. return (Component*) customComps [index];
  61396. }
  61397. Component* AlertWindow::removeCustomComponent (const int index)
  61398. {
  61399. Component* const c = getCustomComponent (index);
  61400. if (c != 0)
  61401. {
  61402. customComps.removeValue (c);
  61403. allComps.removeValue (c);
  61404. removeChildComponent (c);
  61405. updateLayout (false);
  61406. }
  61407. return c;
  61408. }
  61409. void AlertWindow::paint (Graphics& g)
  61410. {
  61411. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  61412. g.setColour (findColour (textColourId));
  61413. g.setFont (getLookAndFeel().getAlertWindowFont());
  61414. int i;
  61415. for (i = textBoxes.size(); --i >= 0;)
  61416. {
  61417. const TextEditor* const te = (TextEditor*) textBoxes[i];
  61418. g.drawFittedText (textboxNames[i],
  61419. te->getX(), te->getY() - 14,
  61420. te->getWidth(), 14,
  61421. Justification::centredLeft, 1);
  61422. }
  61423. for (i = comboBoxNames.size(); --i >= 0;)
  61424. {
  61425. const ComboBox* const cb = (ComboBox*) comboBoxes[i];
  61426. g.drawFittedText (comboBoxNames[i],
  61427. cb->getX(), cb->getY() - 14,
  61428. cb->getWidth(), 14,
  61429. Justification::centredLeft, 1);
  61430. }
  61431. for (i = customComps.size(); --i >= 0;)
  61432. {
  61433. const Component* const c = (Component*) customComps[i];
  61434. g.drawFittedText (c->getName(),
  61435. c->getX(), c->getY() - 14,
  61436. c->getWidth(), 14,
  61437. Justification::centredLeft, 1);
  61438. }
  61439. }
  61440. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  61441. {
  61442. const int titleH = 24;
  61443. const int iconWidth = 80;
  61444. const int wid = jmax (font.getStringWidth (text),
  61445. font.getStringWidth (getName()));
  61446. const int sw = (int) std::sqrt (font.getHeight() * wid);
  61447. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  61448. const int edgeGap = 10;
  61449. const int labelHeight = 18;
  61450. int iconSpace;
  61451. if (alertIconType == NoIcon)
  61452. {
  61453. textLayout.layout (w, Justification::horizontallyCentred, true);
  61454. iconSpace = 0;
  61455. }
  61456. else
  61457. {
  61458. textLayout.layout (w, Justification::left, true);
  61459. iconSpace = iconWidth;
  61460. }
  61461. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  61462. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61463. const int textLayoutH = textLayout.getHeight();
  61464. const int textBottom = 16 + titleH + textLayoutH;
  61465. int h = textBottom;
  61466. int buttonW = 40;
  61467. int i;
  61468. for (i = 0; i < buttons.size(); ++i)
  61469. buttonW += 16 + ((const TextButton*) buttons[i])->getWidth();
  61470. w = jmax (buttonW, w);
  61471. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  61472. if (buttons.size() > 0)
  61473. h += 20 + ((TextButton*) buttons[0])->getHeight();
  61474. for (i = customComps.size(); --i >= 0;)
  61475. {
  61476. Component* c = (Component*) customComps[i];
  61477. w = jmax (w, (c->getWidth() * 100) / 80);
  61478. h += 10 + c->getHeight();
  61479. if (c->getName().isNotEmpty())
  61480. h += labelHeight;
  61481. }
  61482. for (i = textBlocks.size(); --i >= 0;)
  61483. {
  61484. const AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  61485. w = jmax (w, ac->getPreferredWidth());
  61486. }
  61487. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61488. for (i = textBlocks.size(); --i >= 0;)
  61489. {
  61490. AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  61491. ac->updateLayout ((int) (w * 0.8f));
  61492. h += ac->getHeight() + 10;
  61493. }
  61494. h = jmin (getParentHeight() - 50, h);
  61495. if (onlyIncreaseSize)
  61496. {
  61497. w = jmax (w, getWidth());
  61498. h = jmax (h, getHeight());
  61499. }
  61500. if (! isVisible())
  61501. {
  61502. centreAroundComponent (associatedComponent, w, h);
  61503. }
  61504. else
  61505. {
  61506. const int cx = getX() + getWidth() / 2;
  61507. const int cy = getY() + getHeight() / 2;
  61508. setBounds (cx - w / 2,
  61509. cy - h / 2,
  61510. w, h);
  61511. }
  61512. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  61513. const int spacer = 16;
  61514. int totalWidth = -spacer;
  61515. for (i = buttons.size(); --i >= 0;)
  61516. totalWidth += ((TextButton*) buttons[i])->getWidth() + spacer;
  61517. int x = (w - totalWidth) / 2;
  61518. int y = (int) (getHeight() * 0.95f);
  61519. for (i = 0; i < buttons.size(); ++i)
  61520. {
  61521. TextButton* const c = (TextButton*) buttons[i];
  61522. int ny = proportionOfHeight (0.95f) - c->getHeight();
  61523. c->setTopLeftPosition (x, ny);
  61524. if (ny < y)
  61525. y = ny;
  61526. x += c->getWidth() + spacer;
  61527. c->toFront (false);
  61528. }
  61529. y = textBottom;
  61530. for (i = 0; i < allComps.size(); ++i)
  61531. {
  61532. Component* const c = (Component*) allComps[i];
  61533. h = 22;
  61534. const int comboIndex = comboBoxes.indexOf (c);
  61535. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  61536. y += labelHeight;
  61537. const int tbIndex = textBoxes.indexOf (c);
  61538. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  61539. y += labelHeight;
  61540. if (customComps.contains (c))
  61541. {
  61542. if (c->getName().isNotEmpty())
  61543. y += labelHeight;
  61544. c->setTopLeftPosition (proportionOfWidth (0.1f), y);
  61545. h = c->getHeight();
  61546. }
  61547. else if (textBlocks.contains (c))
  61548. {
  61549. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  61550. h = c->getHeight();
  61551. }
  61552. else
  61553. {
  61554. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  61555. }
  61556. y += h + 10;
  61557. }
  61558. setWantsKeyboardFocus (getNumChildComponents() == 0);
  61559. }
  61560. bool AlertWindow::containsAnyExtraComponents() const
  61561. {
  61562. return textBoxes.size()
  61563. + comboBoxes.size()
  61564. + progressBars.size()
  61565. + customComps.size() > 0;
  61566. }
  61567. void AlertWindow::mouseDown (const MouseEvent&)
  61568. {
  61569. dragger.startDraggingComponent (this, &constrainer);
  61570. }
  61571. void AlertWindow::mouseDrag (const MouseEvent& e)
  61572. {
  61573. dragger.dragComponent (this, e);
  61574. }
  61575. bool AlertWindow::keyPressed (const KeyPress& key)
  61576. {
  61577. for (int i = buttons.size(); --i >= 0;)
  61578. {
  61579. TextButton* const b = (TextButton*) buttons[i];
  61580. if (b->isRegisteredForShortcut (key))
  61581. {
  61582. b->triggerClick();
  61583. return true;
  61584. }
  61585. }
  61586. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  61587. {
  61588. exitModalState (0);
  61589. return true;
  61590. }
  61591. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  61592. {
  61593. ((TextButton*) buttons.getFirst())->triggerClick();
  61594. return true;
  61595. }
  61596. return false;
  61597. }
  61598. void AlertWindow::lookAndFeelChanged()
  61599. {
  61600. const int newFlags = getLookAndFeel().getAlertBoxWindowFlags();
  61601. setUsingNativeTitleBar ((newFlags & ComponentPeer::windowHasTitleBar) != 0);
  61602. setDropShadowEnabled (isOpaque() && (newFlags & ComponentPeer::windowHasDropShadow) != 0);
  61603. }
  61604. int AlertWindow::getDesktopWindowStyleFlags() const
  61605. {
  61606. return getLookAndFeel().getAlertBoxWindowFlags();
  61607. }
  61608. struct AlertWindowInfo
  61609. {
  61610. String title, message, button1, button2, button3;
  61611. AlertWindow::AlertIconType iconType;
  61612. int numButtons;
  61613. Component::SafePointer<Component> associatedComponent;
  61614. int run() const
  61615. {
  61616. return (int) (pointer_sized_int)
  61617. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  61618. }
  61619. private:
  61620. int show() const
  61621. {
  61622. LookAndFeel& lf = associatedComponent != 0 ? associatedComponent->getLookAndFeel()
  61623. : LookAndFeel::getDefaultLookAndFeel();
  61624. ScopedPointer <Component> alertBox (lf.createAlertWindow (title, message, button1, button2, button3,
  61625. iconType, numButtons, associatedComponent));
  61626. jassert (alertBox != 0); // you have to return one of these!
  61627. return alertBox->runModalLoop();
  61628. }
  61629. static void* showCallback (void* userData)
  61630. {
  61631. return (void*) (pointer_sized_int) ((const AlertWindowInfo*) userData)->show();
  61632. }
  61633. };
  61634. void AlertWindow::showMessageBox (AlertIconType iconType,
  61635. const String& title,
  61636. const String& message,
  61637. const String& buttonText,
  61638. Component* associatedComponent)
  61639. {
  61640. AlertWindowInfo info;
  61641. info.title = title;
  61642. info.message = message;
  61643. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  61644. info.iconType = iconType;
  61645. info.numButtons = 1;
  61646. info.associatedComponent = associatedComponent;
  61647. info.run();
  61648. }
  61649. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  61650. const String& title,
  61651. const String& message,
  61652. const String& button1Text,
  61653. const String& button2Text,
  61654. Component* associatedComponent)
  61655. {
  61656. AlertWindowInfo info;
  61657. info.title = title;
  61658. info.message = message;
  61659. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  61660. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  61661. info.iconType = iconType;
  61662. info.numButtons = 2;
  61663. info.associatedComponent = associatedComponent;
  61664. return info.run() != 0;
  61665. }
  61666. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  61667. const String& title,
  61668. const String& message,
  61669. const String& button1Text,
  61670. const String& button2Text,
  61671. const String& button3Text,
  61672. Component* associatedComponent)
  61673. {
  61674. AlertWindowInfo info;
  61675. info.title = title;
  61676. info.message = message;
  61677. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  61678. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  61679. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  61680. info.iconType = iconType;
  61681. info.numButtons = 3;
  61682. info.associatedComponent = associatedComponent;
  61683. return info.run();
  61684. }
  61685. END_JUCE_NAMESPACE
  61686. /*** End of inlined file: juce_AlertWindow.cpp ***/
  61687. /*** Start of inlined file: juce_CallOutBox.cpp ***/
  61688. BEGIN_JUCE_NAMESPACE
  61689. CallOutBox::CallOutBox (Component& contentComponent,
  61690. Component& componentToPointTo,
  61691. Component* const parentComponent)
  61692. : borderSpace (20), arrowSize (16.0f), content (contentComponent)
  61693. {
  61694. addAndMakeVisible (&content);
  61695. if (parentComponent != 0)
  61696. {
  61697. updatePosition (parentComponent->getLocalBounds(),
  61698. componentToPointTo.getLocalBounds()
  61699. + componentToPointTo.relativePositionToOtherComponent (parentComponent, Point<int>()));
  61700. parentComponent->addAndMakeVisible (this);
  61701. }
  61702. else
  61703. {
  61704. updatePosition (componentToPointTo.getScreenBounds(),
  61705. componentToPointTo.getParentMonitorArea());
  61706. addToDesktop (ComponentPeer::windowIsTemporary);
  61707. }
  61708. }
  61709. CallOutBox::~CallOutBox()
  61710. {
  61711. }
  61712. void CallOutBox::setArrowSize (const float newSize)
  61713. {
  61714. arrowSize = newSize;
  61715. borderSpace = jmax (20, (int) arrowSize);
  61716. refreshPath();
  61717. }
  61718. void CallOutBox::paint (Graphics& g)
  61719. {
  61720. if (background.isNull())
  61721. {
  61722. background = Image (Image::ARGB, getWidth(), getHeight(), true);
  61723. Graphics g (background);
  61724. getLookAndFeel().drawCallOutBoxBackground (*this, g, outline);
  61725. }
  61726. g.setColour (Colours::black);
  61727. g.drawImageAt (background, 0, 0);
  61728. }
  61729. void CallOutBox::resized()
  61730. {
  61731. content.setTopLeftPosition (borderSpace, borderSpace);
  61732. refreshPath();
  61733. }
  61734. void CallOutBox::moved()
  61735. {
  61736. refreshPath();
  61737. }
  61738. void CallOutBox::childBoundsChanged (Component*)
  61739. {
  61740. updatePosition (targetArea, availableArea);
  61741. }
  61742. bool CallOutBox::hitTest (int x, int y)
  61743. {
  61744. return outline.contains ((float) x, (float) y);
  61745. }
  61746. enum { callOutBoxDismissCommandId = 0x4f83a04b };
  61747. void CallOutBox::inputAttemptWhenModal()
  61748. {
  61749. const Point<int> mousePos (getMouseXYRelative() + getBounds().getPosition());
  61750. if (targetArea.contains (mousePos))
  61751. {
  61752. // if you click on the area that originally popped-up the callout, you expect it
  61753. // to get rid of the box, but deleting the box here allows the click to pass through and
  61754. // probably re-trigger it, so we need to dismiss the box asynchronously to consume the click..
  61755. postCommandMessage (callOutBoxDismissCommandId);
  61756. }
  61757. else
  61758. {
  61759. exitModalState (0);
  61760. setVisible (false);
  61761. }
  61762. }
  61763. void CallOutBox::handleCommandMessage (int commandId)
  61764. {
  61765. Component::handleCommandMessage (commandId);
  61766. if (commandId == callOutBoxDismissCommandId)
  61767. {
  61768. exitModalState (0);
  61769. setVisible (false);
  61770. }
  61771. }
  61772. bool CallOutBox::keyPressed (const KeyPress& key)
  61773. {
  61774. if (key.isKeyCode (KeyPress::escapeKey))
  61775. {
  61776. inputAttemptWhenModal();
  61777. return true;
  61778. }
  61779. return false;
  61780. }
  61781. void CallOutBox::updatePosition (const Rectangle<int>& newAreaToPointTo, const Rectangle<int>& newAreaToFitIn)
  61782. {
  61783. targetArea = newAreaToPointTo;
  61784. availableArea = newAreaToFitIn;
  61785. Rectangle<int> bounds (0, 0,
  61786. content.getWidth() + borderSpace * 2,
  61787. content.getHeight() + borderSpace * 2);
  61788. const int hw = bounds.getWidth() / 2;
  61789. const int hh = bounds.getHeight() / 2;
  61790. const float hwReduced = (float) (hw - borderSpace * 3);
  61791. const float hhReduced = (float) (hh - borderSpace * 3);
  61792. const float arrowIndent = borderSpace - arrowSize;
  61793. Point<float> targets[4] = { Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getBottom()),
  61794. Point<float> ((float) targetArea.getRight(), (float) targetArea.getCentreY()),
  61795. Point<float> ((float) targetArea.getX(), (float) targetArea.getCentreY()),
  61796. Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getY()) };
  61797. Line<float> lines[4] = { Line<float> (targets[0].translated (-hwReduced, hh - arrowIndent), targets[0].translated (hwReduced, hh - arrowIndent)),
  61798. Line<float> (targets[1].translated (hw - arrowIndent, -hhReduced), targets[1].translated (hw - arrowIndent, hhReduced)),
  61799. Line<float> (targets[2].translated (-(hw - arrowIndent), -hhReduced), targets[2].translated (-(hw - arrowIndent), hhReduced)),
  61800. Line<float> (targets[3].translated (-hwReduced, -(hh - arrowIndent)), targets[3].translated (hwReduced, -(hh - arrowIndent))) };
  61801. const Rectangle<float> centrePointArea (newAreaToFitIn.reduced (hw, hh).toFloat());
  61802. float nearest = 1.0e9f;
  61803. for (int i = 0; i < 4; ++i)
  61804. {
  61805. Line<float> constrainedLine (centrePointArea.getConstrainedPoint (lines[i].getStart()),
  61806. centrePointArea.getConstrainedPoint (lines[i].getEnd()));
  61807. const Point<float> centre (constrainedLine.findNearestPointTo (centrePointArea.getCentre()));
  61808. float distanceFromCentre = centre.getDistanceFrom (centrePointArea.getCentre());
  61809. if (! (centrePointArea.contains (lines[i].getStart()) || centrePointArea.contains (lines[i].getEnd())))
  61810. distanceFromCentre *= 2.0f;
  61811. if (distanceFromCentre < nearest)
  61812. {
  61813. nearest = distanceFromCentre;
  61814. targetPoint = targets[i];
  61815. bounds.setPosition ((int) (centre.getX() - hw),
  61816. (int) (centre.getY() - hh));
  61817. }
  61818. }
  61819. setBounds (bounds);
  61820. }
  61821. void CallOutBox::refreshPath()
  61822. {
  61823. repaint();
  61824. background = Image();
  61825. outline.clear();
  61826. const float gap = 4.5f;
  61827. const float cornerSize = 9.0f;
  61828. const float cornerSize2 = 2.0f * cornerSize;
  61829. const float arrowBaseWidth = arrowSize * 0.7f;
  61830. const float left = content.getX() - gap, top = content.getY() - gap, right = content.getRight() + gap, bottom = content.getBottom() + gap;
  61831. const float targetX = targetPoint.getX() - getX(), targetY = targetPoint.getY() - getY();
  61832. outline.startNewSubPath (left + cornerSize, top);
  61833. if (targetY <= top)
  61834. {
  61835. outline.lineTo (targetX - arrowBaseWidth, top);
  61836. outline.lineTo (targetX, targetY);
  61837. outline.lineTo (targetX + arrowBaseWidth, top);
  61838. }
  61839. outline.lineTo (right - cornerSize, top);
  61840. outline.addArc (right - cornerSize2, top, cornerSize2, cornerSize2, 0, float_Pi * 0.5f);
  61841. if (targetX >= right)
  61842. {
  61843. outline.lineTo (right, targetY - arrowBaseWidth);
  61844. outline.lineTo (targetX, targetY);
  61845. outline.lineTo (right, targetY + arrowBaseWidth);
  61846. }
  61847. outline.lineTo (right, bottom - cornerSize);
  61848. outline.addArc (right - cornerSize2, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi * 0.5f, float_Pi);
  61849. if (targetY >= bottom)
  61850. {
  61851. outline.lineTo (targetX + arrowBaseWidth, bottom);
  61852. outline.lineTo (targetX, targetY);
  61853. outline.lineTo (targetX - arrowBaseWidth, bottom);
  61854. }
  61855. outline.lineTo (left + cornerSize, bottom);
  61856. outline.addArc (left, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi, float_Pi * 1.5f);
  61857. if (targetX <= left)
  61858. {
  61859. outline.lineTo (left, targetY + arrowBaseWidth);
  61860. outline.lineTo (targetX, targetY);
  61861. outline.lineTo (left, targetY - arrowBaseWidth);
  61862. }
  61863. outline.lineTo (left, top + cornerSize);
  61864. outline.addArc (left, top, cornerSize2, cornerSize2, float_Pi * 1.5f, float_Pi * 2.0f - 0.05f);
  61865. outline.closeSubPath();
  61866. }
  61867. END_JUCE_NAMESPACE
  61868. /*** End of inlined file: juce_CallOutBox.cpp ***/
  61869. /*** Start of inlined file: juce_ComponentPeer.cpp ***/
  61870. BEGIN_JUCE_NAMESPACE
  61871. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  61872. static Array <ComponentPeer*> heavyweightPeers;
  61873. ComponentPeer::ComponentPeer (Component* const component_, const int styleFlags_)
  61874. : component (component_),
  61875. styleFlags (styleFlags_),
  61876. lastPaintTime (0),
  61877. constrainer (0),
  61878. lastDragAndDropCompUnderMouse (0),
  61879. fakeMouseMessageSent (false),
  61880. isWindowMinimised (false)
  61881. {
  61882. heavyweightPeers.add (this);
  61883. }
  61884. ComponentPeer::~ComponentPeer()
  61885. {
  61886. heavyweightPeers.removeValue (this);
  61887. Desktop::getInstance().triggerFocusCallback();
  61888. }
  61889. int ComponentPeer::getNumPeers() throw()
  61890. {
  61891. return heavyweightPeers.size();
  61892. }
  61893. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  61894. {
  61895. return heavyweightPeers [index];
  61896. }
  61897. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  61898. {
  61899. for (int i = heavyweightPeers.size(); --i >= 0;)
  61900. {
  61901. ComponentPeer* const peer = heavyweightPeers.getUnchecked(i);
  61902. if (peer->getComponent() == component)
  61903. return peer;
  61904. }
  61905. return 0;
  61906. }
  61907. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  61908. {
  61909. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  61910. }
  61911. void ComponentPeer::updateCurrentModifiers() throw()
  61912. {
  61913. ModifierKeys::updateCurrentModifiers();
  61914. }
  61915. void ComponentPeer::handleMouseEvent (const int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, const int64 time)
  61916. {
  61917. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  61918. jassert (mouse != 0); // not enough sources!
  61919. mouse->handleEvent (this, positionWithinPeer, time, newMods);
  61920. }
  61921. void ComponentPeer::handleMouseWheel (const int touchIndex, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  61922. {
  61923. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  61924. jassert (mouse != 0); // not enough sources!
  61925. mouse->handleWheel (this, positionWithinPeer, time, x, y);
  61926. }
  61927. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  61928. {
  61929. Graphics g (&contextToPaintTo);
  61930. #if JUCE_ENABLE_REPAINT_DEBUGGING
  61931. g.saveState();
  61932. #endif
  61933. JUCE_TRY
  61934. {
  61935. component->paintEntireComponent (g);
  61936. }
  61937. JUCE_CATCH_EXCEPTION
  61938. #if JUCE_ENABLE_REPAINT_DEBUGGING
  61939. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  61940. // clearly when things are being repainted.
  61941. {
  61942. g.restoreState();
  61943. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  61944. (uint8) Random::getSystemRandom().nextInt (255),
  61945. (uint8) Random::getSystemRandom().nextInt (255),
  61946. (uint8) 0x50));
  61947. }
  61948. #endif
  61949. }
  61950. bool ComponentPeer::handleKeyPress (const int keyCode,
  61951. const juce_wchar textCharacter)
  61952. {
  61953. updateCurrentModifiers();
  61954. Component* target = Component::getCurrentlyFocusedComponent() != 0
  61955. ? Component::getCurrentlyFocusedComponent()
  61956. : component;
  61957. if (target->isCurrentlyBlockedByAnotherModalComponent())
  61958. {
  61959. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  61960. if (currentModalComp != 0)
  61961. target = currentModalComp;
  61962. }
  61963. const KeyPress keyInfo (keyCode,
  61964. ModifierKeys::getCurrentModifiers().getRawFlags()
  61965. & ModifierKeys::allKeyboardModifiers,
  61966. textCharacter);
  61967. bool keyWasUsed = false;
  61968. while (target != 0)
  61969. {
  61970. const Component::SafePointer<Component> deletionChecker (target);
  61971. if (target->keyListeners_ != 0)
  61972. {
  61973. for (int i = target->keyListeners_->size(); --i >= 0;)
  61974. {
  61975. keyWasUsed = target->keyListeners_->getUnchecked(i)->keyPressed (keyInfo, target);
  61976. if (keyWasUsed || deletionChecker == 0)
  61977. return keyWasUsed;
  61978. i = jmin (i, target->keyListeners_->size());
  61979. }
  61980. }
  61981. keyWasUsed = target->keyPressed (keyInfo);
  61982. if (keyWasUsed || deletionChecker == 0)
  61983. break;
  61984. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  61985. {
  61986. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  61987. currentlyFocused->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  61988. keyWasUsed = (currentlyFocused != Component::getCurrentlyFocusedComponent());
  61989. break;
  61990. }
  61991. target = target->parentComponent_;
  61992. }
  61993. return keyWasUsed;
  61994. }
  61995. bool ComponentPeer::handleKeyUpOrDown (const bool isKeyDown)
  61996. {
  61997. updateCurrentModifiers();
  61998. Component* target = Component::getCurrentlyFocusedComponent() != 0
  61999. ? Component::getCurrentlyFocusedComponent()
  62000. : component;
  62001. if (target->isCurrentlyBlockedByAnotherModalComponent())
  62002. {
  62003. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  62004. if (currentModalComp != 0)
  62005. target = currentModalComp;
  62006. }
  62007. bool keyWasUsed = false;
  62008. while (target != 0)
  62009. {
  62010. const Component::SafePointer<Component> deletionChecker (target);
  62011. keyWasUsed = target->keyStateChanged (isKeyDown);
  62012. if (keyWasUsed || deletionChecker == 0)
  62013. break;
  62014. if (target->keyListeners_ != 0)
  62015. {
  62016. for (int i = target->keyListeners_->size(); --i >= 0;)
  62017. {
  62018. keyWasUsed = target->keyListeners_->getUnchecked(i)->keyStateChanged (isKeyDown, target);
  62019. if (keyWasUsed || deletionChecker == 0)
  62020. return keyWasUsed;
  62021. i = jmin (i, target->keyListeners_->size());
  62022. }
  62023. }
  62024. target = target->parentComponent_;
  62025. }
  62026. return keyWasUsed;
  62027. }
  62028. void ComponentPeer::handleModifierKeysChange()
  62029. {
  62030. updateCurrentModifiers();
  62031. Component* target = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  62032. if (target == 0)
  62033. target = Component::getCurrentlyFocusedComponent();
  62034. if (target == 0)
  62035. target = component;
  62036. if (target != 0)
  62037. target->internalModifierKeysChanged();
  62038. }
  62039. TextInputTarget* ComponentPeer::findCurrentTextInputTarget()
  62040. {
  62041. Component* const c = Component::getCurrentlyFocusedComponent();
  62042. if (component->isParentOf (c))
  62043. {
  62044. TextInputTarget* const ti = dynamic_cast <TextInputTarget*> (c);
  62045. if (ti != 0 && ti->isTextInputActive())
  62046. return ti;
  62047. }
  62048. return 0;
  62049. }
  62050. void ComponentPeer::handleBroughtToFront()
  62051. {
  62052. updateCurrentModifiers();
  62053. if (component != 0)
  62054. component->internalBroughtToFront();
  62055. }
  62056. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  62057. {
  62058. constrainer = newConstrainer;
  62059. }
  62060. void ComponentPeer::handleMovedOrResized()
  62061. {
  62062. jassert (component->isValidComponent());
  62063. updateCurrentModifiers();
  62064. const bool nowMinimised = isMinimised();
  62065. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  62066. {
  62067. const Component::SafePointer<Component> deletionChecker (component);
  62068. const Rectangle<int> newBounds (getBounds());
  62069. const bool wasMoved = (component->getPosition() != newBounds.getPosition());
  62070. const bool wasResized = (component->getWidth() != newBounds.getWidth() || component->getHeight() != newBounds.getHeight());
  62071. if (wasMoved || wasResized)
  62072. {
  62073. component->bounds_ = newBounds;
  62074. if (wasResized)
  62075. component->repaint();
  62076. component->sendMovedResizedMessages (wasMoved, wasResized);
  62077. if (deletionChecker == 0)
  62078. return;
  62079. }
  62080. }
  62081. if (isWindowMinimised != nowMinimised)
  62082. {
  62083. isWindowMinimised = nowMinimised;
  62084. component->minimisationStateChanged (nowMinimised);
  62085. component->sendVisibilityChangeMessage();
  62086. }
  62087. if (! isFullScreen())
  62088. lastNonFullscreenBounds = component->getBounds();
  62089. }
  62090. void ComponentPeer::handleFocusGain()
  62091. {
  62092. updateCurrentModifiers();
  62093. if (component->isParentOf (lastFocusedComponent))
  62094. {
  62095. Component::currentlyFocusedComponent = lastFocusedComponent;
  62096. Desktop::getInstance().triggerFocusCallback();
  62097. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  62098. }
  62099. else
  62100. {
  62101. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  62102. component->grabKeyboardFocus();
  62103. else
  62104. Component::bringModalComponentToFront();
  62105. }
  62106. }
  62107. void ComponentPeer::handleFocusLoss()
  62108. {
  62109. updateCurrentModifiers();
  62110. if (component->hasKeyboardFocus (true))
  62111. {
  62112. lastFocusedComponent = Component::currentlyFocusedComponent;
  62113. if (lastFocusedComponent != 0)
  62114. {
  62115. Component::currentlyFocusedComponent = 0;
  62116. Desktop::getInstance().triggerFocusCallback();
  62117. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  62118. }
  62119. }
  62120. }
  62121. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  62122. {
  62123. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  62124. ? static_cast <Component*> (lastFocusedComponent)
  62125. : component;
  62126. }
  62127. void ComponentPeer::handleScreenSizeChange()
  62128. {
  62129. updateCurrentModifiers();
  62130. component->parentSizeChanged();
  62131. handleMovedOrResized();
  62132. }
  62133. void ComponentPeer::setNonFullScreenBounds (const Rectangle<int>& newBounds) throw()
  62134. {
  62135. lastNonFullscreenBounds = newBounds;
  62136. }
  62137. const Rectangle<int>& ComponentPeer::getNonFullScreenBounds() const throw()
  62138. {
  62139. return lastNonFullscreenBounds;
  62140. }
  62141. static FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  62142. const StringArray& files,
  62143. FileDragAndDropTarget* const lastOne)
  62144. {
  62145. while (c != 0)
  62146. {
  62147. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  62148. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  62149. return t;
  62150. c = c->getParentComponent();
  62151. }
  62152. return 0;
  62153. }
  62154. void ComponentPeer::handleFileDragMove (const StringArray& files, const Point<int>& position)
  62155. {
  62156. updateCurrentModifiers();
  62157. FileDragAndDropTarget* lastTarget
  62158. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62159. FileDragAndDropTarget* newTarget = 0;
  62160. Component* const compUnderMouse = component->getComponentAt (position);
  62161. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  62162. {
  62163. lastDragAndDropCompUnderMouse = compUnderMouse;
  62164. newTarget = findDragAndDropTarget (compUnderMouse, files, lastTarget);
  62165. if (newTarget != lastTarget)
  62166. {
  62167. if (lastTarget != 0)
  62168. lastTarget->fileDragExit (files);
  62169. dragAndDropTargetComponent = 0;
  62170. if (newTarget != 0)
  62171. {
  62172. dragAndDropTargetComponent = dynamic_cast <Component*> (newTarget);
  62173. const Point<int> pos (component->relativePositionToOtherComponent (dragAndDropTargetComponent, position));
  62174. newTarget->fileDragEnter (files, pos.getX(), pos.getY());
  62175. }
  62176. }
  62177. }
  62178. else
  62179. {
  62180. newTarget = lastTarget;
  62181. }
  62182. if (newTarget != 0)
  62183. {
  62184. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  62185. const Point<int> pos (component->relativePositionToOtherComponent (targetComp, position));
  62186. newTarget->fileDragMove (files, pos.getX(), pos.getY());
  62187. }
  62188. }
  62189. void ComponentPeer::handleFileDragExit (const StringArray& files)
  62190. {
  62191. handleFileDragMove (files, Point<int> (-1, -1));
  62192. jassert (dragAndDropTargetComponent == 0);
  62193. lastDragAndDropCompUnderMouse = 0;
  62194. }
  62195. void ComponentPeer::handleFileDragDrop (const StringArray& files, const Point<int>& position)
  62196. {
  62197. handleFileDragMove (files, position);
  62198. if (dragAndDropTargetComponent != 0)
  62199. {
  62200. FileDragAndDropTarget* const target
  62201. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62202. dragAndDropTargetComponent = 0;
  62203. lastDragAndDropCompUnderMouse = 0;
  62204. if (target != 0)
  62205. {
  62206. Component* const targetComp = dynamic_cast <Component*> (target);
  62207. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  62208. {
  62209. targetComp->internalModalInputAttempt();
  62210. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  62211. return;
  62212. }
  62213. const Point<int> pos (component->relativePositionToOtherComponent (targetComp, position));
  62214. target->filesDropped (files, pos.getX(), pos.getY());
  62215. }
  62216. }
  62217. }
  62218. void ComponentPeer::handleUserClosingWindow()
  62219. {
  62220. updateCurrentModifiers();
  62221. component->userTriedToCloseWindow();
  62222. }
  62223. void ComponentPeer::bringModalComponentToFront()
  62224. {
  62225. Component::bringModalComponentToFront();
  62226. }
  62227. void ComponentPeer::clearMaskedRegion()
  62228. {
  62229. maskedRegion.clear();
  62230. }
  62231. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h)
  62232. {
  62233. maskedRegion.add (x, y, w, h);
  62234. }
  62235. const StringArray ComponentPeer::getAvailableRenderingEngines() throw()
  62236. {
  62237. StringArray s;
  62238. s.add ("Software Renderer");
  62239. return s;
  62240. }
  62241. int ComponentPeer::getCurrentRenderingEngine() throw()
  62242. {
  62243. return 0;
  62244. }
  62245. void ComponentPeer::setCurrentRenderingEngine (int /*index*/) throw()
  62246. {
  62247. }
  62248. END_JUCE_NAMESPACE
  62249. /*** End of inlined file: juce_ComponentPeer.cpp ***/
  62250. /*** Start of inlined file: juce_DialogWindow.cpp ***/
  62251. BEGIN_JUCE_NAMESPACE
  62252. DialogWindow::DialogWindow (const String& name,
  62253. const Colour& backgroundColour_,
  62254. const bool escapeKeyTriggersCloseButton_,
  62255. const bool addToDesktop_)
  62256. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  62257. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  62258. {
  62259. }
  62260. DialogWindow::~DialogWindow()
  62261. {
  62262. }
  62263. void DialogWindow::resized()
  62264. {
  62265. DocumentWindow::resized();
  62266. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  62267. if (escapeKeyTriggersCloseButton
  62268. && getCloseButton() != 0
  62269. && ! getCloseButton()->isRegisteredForShortcut (esc))
  62270. {
  62271. getCloseButton()->addShortcut (esc);
  62272. }
  62273. }
  62274. class TempDialogWindow : public DialogWindow
  62275. {
  62276. public:
  62277. TempDialogWindow (const String& title, const Colour& colour, const bool escapeCloses)
  62278. : DialogWindow (title, colour, escapeCloses, true)
  62279. {
  62280. if (JUCEApplication::getInstance() == 0)
  62281. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  62282. }
  62283. ~TempDialogWindow()
  62284. {
  62285. }
  62286. void closeButtonPressed()
  62287. {
  62288. setVisible (false);
  62289. }
  62290. private:
  62291. TempDialogWindow (const TempDialogWindow&);
  62292. TempDialogWindow& operator= (const TempDialogWindow&);
  62293. };
  62294. int DialogWindow::showModalDialog (const String& dialogTitle,
  62295. Component* contentComponent,
  62296. Component* componentToCentreAround,
  62297. const Colour& colour,
  62298. const bool escapeKeyTriggersCloseButton,
  62299. const bool shouldBeResizable,
  62300. const bool useBottomRightCornerResizer)
  62301. {
  62302. TempDialogWindow dw (dialogTitle, colour, escapeKeyTriggersCloseButton);
  62303. dw.setContentComponent (contentComponent, true, true);
  62304. dw.centreAroundComponent (componentToCentreAround, dw.getWidth(), dw.getHeight());
  62305. dw.setResizable (shouldBeResizable, useBottomRightCornerResizer);
  62306. const int result = dw.runModalLoop();
  62307. dw.setContentComponent (0, false);
  62308. return result;
  62309. }
  62310. END_JUCE_NAMESPACE
  62311. /*** End of inlined file: juce_DialogWindow.cpp ***/
  62312. /*** Start of inlined file: juce_DocumentWindow.cpp ***/
  62313. BEGIN_JUCE_NAMESPACE
  62314. class DocumentWindow::ButtonListenerProxy : public ButtonListener
  62315. {
  62316. public:
  62317. ButtonListenerProxy (DocumentWindow& owner_)
  62318. : owner (owner_)
  62319. {
  62320. }
  62321. void buttonClicked (Button* button)
  62322. {
  62323. if (button == owner.getMinimiseButton())
  62324. owner.minimiseButtonPressed();
  62325. else if (button == owner.getMaximiseButton())
  62326. owner.maximiseButtonPressed();
  62327. else if (button == owner.getCloseButton())
  62328. owner.closeButtonPressed();
  62329. }
  62330. juce_UseDebuggingNewOperator
  62331. private:
  62332. DocumentWindow& owner;
  62333. ButtonListenerProxy (const ButtonListenerProxy&);
  62334. ButtonListenerProxy& operator= (const ButtonListenerProxy&);
  62335. };
  62336. DocumentWindow::DocumentWindow (const String& title,
  62337. const Colour& backgroundColour,
  62338. const int requiredButtons_,
  62339. const bool addToDesktop_)
  62340. : ResizableWindow (title, backgroundColour, addToDesktop_),
  62341. titleBarHeight (26),
  62342. menuBarHeight (24),
  62343. requiredButtons (requiredButtons_),
  62344. #if JUCE_MAC
  62345. positionTitleBarButtonsOnLeft (true),
  62346. #else
  62347. positionTitleBarButtonsOnLeft (false),
  62348. #endif
  62349. drawTitleTextCentred (true),
  62350. menuBarModel (0)
  62351. {
  62352. setResizeLimits (128, 128, 32768, 32768);
  62353. lookAndFeelChanged();
  62354. }
  62355. DocumentWindow::~DocumentWindow()
  62356. {
  62357. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  62358. titleBarButtons[i] = 0;
  62359. menuBar = 0;
  62360. }
  62361. void DocumentWindow::repaintTitleBar()
  62362. {
  62363. repaint (getTitleBarArea());
  62364. }
  62365. void DocumentWindow::setName (const String& newName)
  62366. {
  62367. if (newName != getName())
  62368. {
  62369. Component::setName (newName);
  62370. repaintTitleBar();
  62371. }
  62372. }
  62373. void DocumentWindow::setIcon (const Image& imageToUse)
  62374. {
  62375. titleBarIcon = imageToUse;
  62376. repaintTitleBar();
  62377. }
  62378. void DocumentWindow::setTitleBarHeight (const int newHeight)
  62379. {
  62380. titleBarHeight = newHeight;
  62381. resized();
  62382. repaintTitleBar();
  62383. }
  62384. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  62385. const bool positionTitleBarButtonsOnLeft_)
  62386. {
  62387. requiredButtons = requiredButtons_;
  62388. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  62389. lookAndFeelChanged();
  62390. }
  62391. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  62392. {
  62393. drawTitleTextCentred = textShouldBeCentred;
  62394. repaintTitleBar();
  62395. }
  62396. void DocumentWindow::setMenuBar (MenuBarModel* menuBarModel_,
  62397. const int menuBarHeight_)
  62398. {
  62399. if (menuBarModel != menuBarModel_)
  62400. {
  62401. menuBar = 0;
  62402. menuBarModel = menuBarModel_;
  62403. menuBarHeight = (menuBarHeight_ > 0) ? menuBarHeight_
  62404. : getLookAndFeel().getDefaultMenuBarHeight();
  62405. if (menuBarModel != 0)
  62406. {
  62407. // (call the Component method directly to avoid the assertion in ResizableWindow)
  62408. Component::addAndMakeVisible (menuBar = new MenuBarComponent (menuBarModel));
  62409. menuBar->setEnabled (isActiveWindow());
  62410. }
  62411. resized();
  62412. }
  62413. }
  62414. void DocumentWindow::closeButtonPressed()
  62415. {
  62416. /* If you've got a close button, you have to override this method to get
  62417. rid of your window!
  62418. If the window is just a pop-up, you should override this method and make
  62419. it delete the window in whatever way is appropriate for your app. E.g. you
  62420. might just want to call "delete this".
  62421. If your app is centred around this window such that the whole app should quit when
  62422. the window is closed, then you will probably want to use this method as an opportunity
  62423. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  62424. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  62425. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  62426. or closing it via the taskbar icon on Windows).
  62427. */
  62428. jassertfalse;
  62429. }
  62430. void DocumentWindow::minimiseButtonPressed()
  62431. {
  62432. setMinimised (true);
  62433. }
  62434. void DocumentWindow::maximiseButtonPressed()
  62435. {
  62436. setFullScreen (! isFullScreen());
  62437. }
  62438. void DocumentWindow::paint (Graphics& g)
  62439. {
  62440. ResizableWindow::paint (g);
  62441. if (resizableBorder == 0)
  62442. {
  62443. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  62444. const BorderSize border (getBorderThickness());
  62445. g.fillRect (0, 0, getWidth(), border.getTop());
  62446. g.fillRect (0, border.getTop(), border.getLeft(), getHeight() - border.getTopAndBottom());
  62447. g.fillRect (getWidth() - border.getRight(), border.getTop(), border.getRight(), getHeight() - border.getTopAndBottom());
  62448. g.fillRect (0, getHeight() - border.getBottom(), getWidth(), border.getBottom());
  62449. }
  62450. const Rectangle<int> titleBarArea (getTitleBarArea());
  62451. g.setOrigin (titleBarArea.getX(), titleBarArea.getY());
  62452. g.reduceClipRegion (0, 0, titleBarArea.getWidth(), titleBarArea.getHeight());
  62453. int titleSpaceX1 = 6;
  62454. int titleSpaceX2 = titleBarArea.getWidth() - 6;
  62455. for (int i = 0; i < 3; ++i)
  62456. {
  62457. if (titleBarButtons[i] != 0)
  62458. {
  62459. if (positionTitleBarButtonsOnLeft)
  62460. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  62461. else
  62462. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  62463. }
  62464. }
  62465. getLookAndFeel().drawDocumentWindowTitleBar (*this, g,
  62466. titleBarArea.getWidth(),
  62467. titleBarArea.getHeight(),
  62468. titleSpaceX1,
  62469. jmax (1, titleSpaceX2 - titleSpaceX1),
  62470. titleBarIcon.isValid() ? &titleBarIcon : 0,
  62471. ! drawTitleTextCentred);
  62472. }
  62473. void DocumentWindow::resized()
  62474. {
  62475. ResizableWindow::resized();
  62476. if (titleBarButtons[1] != 0)
  62477. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  62478. const Rectangle<int> titleBarArea (getTitleBarArea());
  62479. getLookAndFeel()
  62480. .positionDocumentWindowButtons (*this,
  62481. titleBarArea.getX(), titleBarArea.getY(),
  62482. titleBarArea.getWidth(), titleBarArea.getHeight(),
  62483. titleBarButtons[0],
  62484. titleBarButtons[1],
  62485. titleBarButtons[2],
  62486. positionTitleBarButtonsOnLeft);
  62487. if (menuBar != 0)
  62488. menuBar->setBounds (titleBarArea.getX(), titleBarArea.getBottom(),
  62489. titleBarArea.getWidth(), menuBarHeight);
  62490. }
  62491. const BorderSize DocumentWindow::getBorderThickness()
  62492. {
  62493. return BorderSize ((isFullScreen() || isUsingNativeTitleBar())
  62494. ? 0 : (resizableBorder != 0 ? 4 : 1));
  62495. }
  62496. const BorderSize DocumentWindow::getContentComponentBorder()
  62497. {
  62498. BorderSize border (getBorderThickness());
  62499. border.setTop (border.getTop()
  62500. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  62501. + (menuBar != 0 ? menuBarHeight : 0));
  62502. return border;
  62503. }
  62504. int DocumentWindow::getTitleBarHeight() const
  62505. {
  62506. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  62507. }
  62508. const Rectangle<int> DocumentWindow::getTitleBarArea()
  62509. {
  62510. const BorderSize border (getBorderThickness());
  62511. return Rectangle<int> (border.getLeft(), border.getTop(),
  62512. getWidth() - border.getLeftAndRight(),
  62513. getTitleBarHeight());
  62514. }
  62515. Button* DocumentWindow::getCloseButton() const throw()
  62516. {
  62517. return titleBarButtons[2];
  62518. }
  62519. Button* DocumentWindow::getMinimiseButton() const throw()
  62520. {
  62521. return titleBarButtons[0];
  62522. }
  62523. Button* DocumentWindow::getMaximiseButton() const throw()
  62524. {
  62525. return titleBarButtons[1];
  62526. }
  62527. int DocumentWindow::getDesktopWindowStyleFlags() const
  62528. {
  62529. int styleFlags = ResizableWindow::getDesktopWindowStyleFlags();
  62530. if ((requiredButtons & minimiseButton) != 0)
  62531. styleFlags |= ComponentPeer::windowHasMinimiseButton;
  62532. if ((requiredButtons & maximiseButton) != 0)
  62533. styleFlags |= ComponentPeer::windowHasMaximiseButton;
  62534. if ((requiredButtons & closeButton) != 0)
  62535. styleFlags |= ComponentPeer::windowHasCloseButton;
  62536. return styleFlags;
  62537. }
  62538. void DocumentWindow::lookAndFeelChanged()
  62539. {
  62540. int i;
  62541. for (i = numElementsInArray (titleBarButtons); --i >= 0;)
  62542. titleBarButtons[i] = 0;
  62543. if (! isUsingNativeTitleBar())
  62544. {
  62545. titleBarButtons[0] = ((requiredButtons & minimiseButton) != 0)
  62546. ? getLookAndFeel().createDocumentWindowButton (minimiseButton) : 0;
  62547. titleBarButtons[1] = ((requiredButtons & maximiseButton) != 0)
  62548. ? getLookAndFeel().createDocumentWindowButton (maximiseButton) : 0;
  62549. titleBarButtons[2] = ((requiredButtons & closeButton) != 0)
  62550. ? getLookAndFeel().createDocumentWindowButton (closeButton) : 0;
  62551. for (i = 0; i < 3; ++i)
  62552. {
  62553. if (titleBarButtons[i] != 0)
  62554. {
  62555. if (buttonListener == 0)
  62556. buttonListener = new ButtonListenerProxy (*this);
  62557. titleBarButtons[i]->addButtonListener (buttonListener);
  62558. titleBarButtons[i]->setWantsKeyboardFocus (false);
  62559. // (call the Component method directly to avoid the assertion in ResizableWindow)
  62560. Component::addAndMakeVisible (titleBarButtons[i]);
  62561. }
  62562. }
  62563. if (getCloseButton() != 0)
  62564. {
  62565. #if JUCE_MAC
  62566. getCloseButton()->addShortcut (KeyPress ('w', ModifierKeys::commandModifier, 0));
  62567. #else
  62568. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  62569. #endif
  62570. }
  62571. }
  62572. activeWindowStatusChanged();
  62573. ResizableWindow::lookAndFeelChanged();
  62574. }
  62575. void DocumentWindow::parentHierarchyChanged()
  62576. {
  62577. lookAndFeelChanged();
  62578. }
  62579. void DocumentWindow::activeWindowStatusChanged()
  62580. {
  62581. ResizableWindow::activeWindowStatusChanged();
  62582. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  62583. if (titleBarButtons[i] != 0)
  62584. titleBarButtons[i]->setEnabled (isActiveWindow());
  62585. if (menuBar != 0)
  62586. menuBar->setEnabled (isActiveWindow());
  62587. }
  62588. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  62589. {
  62590. if (getTitleBarArea().contains (e.x, e.y)
  62591. && getMaximiseButton() != 0)
  62592. {
  62593. getMaximiseButton()->triggerClick();
  62594. }
  62595. }
  62596. void DocumentWindow::userTriedToCloseWindow()
  62597. {
  62598. closeButtonPressed();
  62599. }
  62600. END_JUCE_NAMESPACE
  62601. /*** End of inlined file: juce_DocumentWindow.cpp ***/
  62602. /*** Start of inlined file: juce_ResizableWindow.cpp ***/
  62603. BEGIN_JUCE_NAMESPACE
  62604. ResizableWindow::ResizableWindow (const String& name,
  62605. const bool addToDesktop_)
  62606. : TopLevelWindow (name, addToDesktop_),
  62607. resizeToFitContent (false),
  62608. fullscreen (false),
  62609. lastNonFullScreenPos (50, 50, 256, 256),
  62610. constrainer (0)
  62611. #if JUCE_DEBUG
  62612. , hasBeenResized (false)
  62613. #endif
  62614. {
  62615. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  62616. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  62617. if (addToDesktop_)
  62618. Component::addToDesktop (getDesktopWindowStyleFlags());
  62619. }
  62620. ResizableWindow::ResizableWindow (const String& name,
  62621. const Colour& backgroundColour_,
  62622. const bool addToDesktop_)
  62623. : TopLevelWindow (name, addToDesktop_),
  62624. resizeToFitContent (false),
  62625. fullscreen (false),
  62626. lastNonFullScreenPos (50, 50, 256, 256),
  62627. constrainer (0)
  62628. #if JUCE_DEBUG
  62629. , hasBeenResized (false)
  62630. #endif
  62631. {
  62632. setBackgroundColour (backgroundColour_);
  62633. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  62634. if (addToDesktop_)
  62635. Component::addToDesktop (getDesktopWindowStyleFlags());
  62636. }
  62637. ResizableWindow::~ResizableWindow()
  62638. {
  62639. resizableCorner = 0;
  62640. resizableBorder = 0;
  62641. contentComponent = 0;
  62642. // have you been adding your own components directly to this window..? tut tut tut.
  62643. // Read the instructions for using a ResizableWindow!
  62644. jassert (getNumChildComponents() == 0);
  62645. }
  62646. int ResizableWindow::getDesktopWindowStyleFlags() const
  62647. {
  62648. int styleFlags = TopLevelWindow::getDesktopWindowStyleFlags();
  62649. if (isResizable() && (styleFlags & ComponentPeer::windowHasTitleBar) != 0)
  62650. styleFlags |= ComponentPeer::windowIsResizable;
  62651. return styleFlags;
  62652. }
  62653. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  62654. const bool deleteOldOne,
  62655. const bool resizeToFit)
  62656. {
  62657. resizeToFitContent = resizeToFit;
  62658. if (newContentComponent != static_cast <Component*> (contentComponent))
  62659. {
  62660. if (! deleteOldOne)
  62661. removeChildComponent (contentComponent.release());
  62662. contentComponent = newContentComponent;
  62663. Component::addAndMakeVisible (contentComponent);
  62664. }
  62665. if (resizeToFit)
  62666. childBoundsChanged (contentComponent);
  62667. resized(); // must always be called to position the new content comp
  62668. }
  62669. void ResizableWindow::setContentComponentSize (int width, int height)
  62670. {
  62671. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  62672. const BorderSize border (getContentComponentBorder());
  62673. setSize (width + border.getLeftAndRight(),
  62674. height + border.getTopAndBottom());
  62675. }
  62676. const BorderSize ResizableWindow::getBorderThickness()
  62677. {
  62678. return BorderSize (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  62679. }
  62680. const BorderSize ResizableWindow::getContentComponentBorder()
  62681. {
  62682. return getBorderThickness();
  62683. }
  62684. void ResizableWindow::moved()
  62685. {
  62686. updateLastPos();
  62687. }
  62688. void ResizableWindow::visibilityChanged()
  62689. {
  62690. TopLevelWindow::visibilityChanged();
  62691. updateLastPos();
  62692. }
  62693. void ResizableWindow::resized()
  62694. {
  62695. if (resizableBorder != 0)
  62696. {
  62697. resizableBorder->setVisible (! isFullScreen());
  62698. resizableBorder->setBorderThickness (getBorderThickness());
  62699. resizableBorder->setSize (getWidth(), getHeight());
  62700. resizableBorder->toBack();
  62701. }
  62702. if (resizableCorner != 0)
  62703. {
  62704. resizableCorner->setVisible (! isFullScreen());
  62705. const int resizerSize = 18;
  62706. resizableCorner->setBounds (getWidth() - resizerSize,
  62707. getHeight() - resizerSize,
  62708. resizerSize, resizerSize);
  62709. }
  62710. if (contentComponent != 0)
  62711. contentComponent->setBoundsInset (getContentComponentBorder());
  62712. updateLastPos();
  62713. #if JUCE_DEBUG
  62714. hasBeenResized = true;
  62715. #endif
  62716. }
  62717. void ResizableWindow::childBoundsChanged (Component* child)
  62718. {
  62719. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  62720. {
  62721. // not going to look very good if this component has a zero size..
  62722. jassert (child->getWidth() > 0);
  62723. jassert (child->getHeight() > 0);
  62724. const BorderSize borders (getContentComponentBorder());
  62725. setSize (child->getWidth() + borders.getLeftAndRight(),
  62726. child->getHeight() + borders.getTopAndBottom());
  62727. }
  62728. }
  62729. void ResizableWindow::activeWindowStatusChanged()
  62730. {
  62731. const BorderSize borders (getContentComponentBorder());
  62732. repaint (0, 0, getWidth(), borders.getTop());
  62733. repaint (0, borders.getTop(), borders.getLeft(), getHeight() - borders.getBottom() - borders.getTop());
  62734. repaint (0, getHeight() - borders.getBottom(), getWidth(), borders.getBottom());
  62735. repaint (getWidth() - borders.getRight(), borders.getTop(), borders.getRight(), getHeight() - borders.getBottom() - borders.getTop());
  62736. }
  62737. void ResizableWindow::setResizable (const bool shouldBeResizable,
  62738. const bool useBottomRightCornerResizer)
  62739. {
  62740. if (shouldBeResizable)
  62741. {
  62742. if (useBottomRightCornerResizer)
  62743. {
  62744. resizableBorder = 0;
  62745. if (resizableCorner == 0)
  62746. {
  62747. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  62748. resizableCorner->setAlwaysOnTop (true);
  62749. }
  62750. }
  62751. else
  62752. {
  62753. resizableCorner = 0;
  62754. if (resizableBorder == 0)
  62755. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  62756. }
  62757. }
  62758. else
  62759. {
  62760. resizableCorner = 0;
  62761. resizableBorder = 0;
  62762. }
  62763. if (isUsingNativeTitleBar())
  62764. recreateDesktopWindow();
  62765. childBoundsChanged (contentComponent);
  62766. resized();
  62767. }
  62768. bool ResizableWindow::isResizable() const throw()
  62769. {
  62770. return resizableCorner != 0
  62771. || resizableBorder != 0;
  62772. }
  62773. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  62774. const int newMinimumHeight,
  62775. const int newMaximumWidth,
  62776. const int newMaximumHeight) throw()
  62777. {
  62778. // if you've set up a custom constrainer then these settings won't have any effect..
  62779. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  62780. if (constrainer == 0)
  62781. setConstrainer (&defaultConstrainer);
  62782. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  62783. newMaximumWidth, newMaximumHeight);
  62784. setBoundsConstrained (getBounds());
  62785. }
  62786. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  62787. {
  62788. if (constrainer != newConstrainer)
  62789. {
  62790. constrainer = newConstrainer;
  62791. const bool useBottomRightCornerResizer = resizableCorner != 0;
  62792. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  62793. resizableCorner = 0;
  62794. resizableBorder = 0;
  62795. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  62796. ComponentPeer* const peer = getPeer();
  62797. if (peer != 0)
  62798. peer->setConstrainer (newConstrainer);
  62799. }
  62800. }
  62801. void ResizableWindow::setBoundsConstrained (const Rectangle<int>& bounds)
  62802. {
  62803. if (constrainer != 0)
  62804. constrainer->setBoundsForComponent (this, bounds, false, false, false, false);
  62805. else
  62806. setBounds (bounds);
  62807. }
  62808. void ResizableWindow::paint (Graphics& g)
  62809. {
  62810. getLookAndFeel().fillResizableWindowBackground (g, getWidth(), getHeight(),
  62811. getBorderThickness(), *this);
  62812. if (! isFullScreen())
  62813. {
  62814. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  62815. getBorderThickness(), *this);
  62816. }
  62817. #if JUCE_DEBUG
  62818. /* If this fails, then you've probably written a subclass with a resized()
  62819. callback but forgotten to make it call its parent class's resized() method.
  62820. It's important when you override methods like resized(), moved(),
  62821. etc., that you make sure the base class methods also get called.
  62822. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  62823. because your content should all be inside the content component - and it's the
  62824. content component's resized() method that you should be using to do your
  62825. layout.
  62826. */
  62827. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  62828. #endif
  62829. }
  62830. void ResizableWindow::lookAndFeelChanged()
  62831. {
  62832. resized();
  62833. if (isOnDesktop())
  62834. {
  62835. Component::addToDesktop (getDesktopWindowStyleFlags());
  62836. ComponentPeer* const peer = getPeer();
  62837. if (peer != 0)
  62838. peer->setConstrainer (constrainer);
  62839. }
  62840. }
  62841. const Colour ResizableWindow::getBackgroundColour() const throw()
  62842. {
  62843. return findColour (backgroundColourId, false);
  62844. }
  62845. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  62846. {
  62847. Colour backgroundColour (newColour);
  62848. if (! Desktop::canUseSemiTransparentWindows())
  62849. backgroundColour = newColour.withAlpha (1.0f);
  62850. setColour (backgroundColourId, backgroundColour);
  62851. setOpaque (backgroundColour.isOpaque());
  62852. repaint();
  62853. }
  62854. bool ResizableWindow::isFullScreen() const
  62855. {
  62856. if (isOnDesktop())
  62857. {
  62858. ComponentPeer* const peer = getPeer();
  62859. return peer != 0 && peer->isFullScreen();
  62860. }
  62861. return fullscreen;
  62862. }
  62863. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  62864. {
  62865. if (shouldBeFullScreen != isFullScreen())
  62866. {
  62867. updateLastPos();
  62868. fullscreen = shouldBeFullScreen;
  62869. if (isOnDesktop())
  62870. {
  62871. ComponentPeer* const peer = getPeer();
  62872. if (peer != 0)
  62873. {
  62874. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  62875. const Rectangle<int> lastPos (lastNonFullScreenPos);
  62876. peer->setFullScreen (shouldBeFullScreen);
  62877. if (! shouldBeFullScreen)
  62878. setBounds (lastPos);
  62879. }
  62880. else
  62881. {
  62882. jassertfalse;
  62883. }
  62884. }
  62885. else
  62886. {
  62887. if (shouldBeFullScreen)
  62888. setBounds (0, 0, getParentWidth(), getParentHeight());
  62889. else
  62890. setBounds (lastNonFullScreenPos);
  62891. }
  62892. resized();
  62893. }
  62894. }
  62895. bool ResizableWindow::isMinimised() const
  62896. {
  62897. ComponentPeer* const peer = getPeer();
  62898. return (peer != 0) && peer->isMinimised();
  62899. }
  62900. void ResizableWindow::setMinimised (const bool shouldMinimise)
  62901. {
  62902. if (shouldMinimise != isMinimised())
  62903. {
  62904. ComponentPeer* const peer = getPeer();
  62905. if (peer != 0)
  62906. {
  62907. updateLastPos();
  62908. peer->setMinimised (shouldMinimise);
  62909. }
  62910. else
  62911. {
  62912. jassertfalse;
  62913. }
  62914. }
  62915. }
  62916. void ResizableWindow::updateLastPos()
  62917. {
  62918. if (isShowing() && ! (isFullScreen() || isMinimised()))
  62919. {
  62920. lastNonFullScreenPos = getBounds();
  62921. }
  62922. }
  62923. void ResizableWindow::parentSizeChanged()
  62924. {
  62925. if (isFullScreen() && getParentComponent() != 0)
  62926. {
  62927. setBounds (0, 0, getParentWidth(), getParentHeight());
  62928. }
  62929. }
  62930. const String ResizableWindow::getWindowStateAsString()
  62931. {
  62932. updateLastPos();
  62933. return (isFullScreen() ? "fs " : "") + lastNonFullScreenPos.toString();
  62934. }
  62935. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  62936. {
  62937. StringArray tokens;
  62938. tokens.addTokens (s, false);
  62939. tokens.removeEmptyStrings();
  62940. tokens.trim();
  62941. const bool fs = tokens[0].startsWithIgnoreCase ("fs");
  62942. const int firstCoord = fs ? 1 : 0;
  62943. if (tokens.size() != firstCoord + 4)
  62944. return false;
  62945. Rectangle<int> newPos (tokens[firstCoord].getIntValue(),
  62946. tokens[firstCoord + 1].getIntValue(),
  62947. tokens[firstCoord + 2].getIntValue(),
  62948. tokens[firstCoord + 3].getIntValue());
  62949. if (newPos.isEmpty())
  62950. return false;
  62951. const Rectangle<int> screen (Desktop::getInstance().getMonitorAreaContaining (newPos.getCentre()));
  62952. ComponentPeer* const peer = isOnDesktop() ? getPeer() : 0;
  62953. if (peer != 0)
  62954. peer->getFrameSize().addTo (newPos);
  62955. if (! screen.contains (newPos))
  62956. {
  62957. newPos.setSize (jmin (newPos.getWidth(), screen.getWidth()),
  62958. jmin (newPos.getHeight(), screen.getHeight()));
  62959. newPos.setPosition (jlimit (screen.getX(), screen.getRight() - newPos.getWidth(), newPos.getX()),
  62960. jlimit (screen.getY(), screen.getBottom() - newPos.getHeight(), newPos.getY()));
  62961. }
  62962. if (peer != 0)
  62963. {
  62964. peer->getFrameSize().subtractFrom (newPos);
  62965. peer->setNonFullScreenBounds (newPos);
  62966. }
  62967. lastNonFullScreenPos = newPos;
  62968. setFullScreen (fs);
  62969. if (! fs)
  62970. setBoundsConstrained (newPos);
  62971. return true;
  62972. }
  62973. void ResizableWindow::mouseDown (const MouseEvent&)
  62974. {
  62975. if (! isFullScreen())
  62976. dragger.startDraggingComponent (this, constrainer);
  62977. }
  62978. void ResizableWindow::mouseDrag (const MouseEvent& e)
  62979. {
  62980. if (! isFullScreen())
  62981. dragger.dragComponent (this, e);
  62982. }
  62983. #if JUCE_DEBUG
  62984. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  62985. {
  62986. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  62987. manages its child components automatically, and if you add your own it'll cause
  62988. trouble. Instead, use setContentComponent() to give it a component which
  62989. will be automatically resized and kept in the right place - then you can add
  62990. subcomponents to the content comp. See the notes for the ResizableWindow class
  62991. for more info.
  62992. If you really know what you're doing and want to avoid this assertion, just call
  62993. Component::addChildComponent directly.
  62994. */
  62995. jassertfalse;
  62996. Component::addChildComponent (child, zOrder);
  62997. }
  62998. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  62999. {
  63000. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63001. manages its child components automatically, and if you add your own it'll cause
  63002. trouble. Instead, use setContentComponent() to give it a component which
  63003. will be automatically resized and kept in the right place - then you can add
  63004. subcomponents to the content comp. See the notes for the ResizableWindow class
  63005. for more info.
  63006. If you really know what you're doing and want to avoid this assertion, just call
  63007. Component::addAndMakeVisible directly.
  63008. */
  63009. jassertfalse;
  63010. Component::addAndMakeVisible (child, zOrder);
  63011. }
  63012. #endif
  63013. END_JUCE_NAMESPACE
  63014. /*** End of inlined file: juce_ResizableWindow.cpp ***/
  63015. /*** Start of inlined file: juce_SplashScreen.cpp ***/
  63016. BEGIN_JUCE_NAMESPACE
  63017. SplashScreen::SplashScreen()
  63018. {
  63019. setOpaque (true);
  63020. }
  63021. SplashScreen::~SplashScreen()
  63022. {
  63023. }
  63024. void SplashScreen::show (const String& title,
  63025. const Image& backgroundImage_,
  63026. const int minimumTimeToDisplayFor,
  63027. const bool useDropShadow,
  63028. const bool removeOnMouseClick)
  63029. {
  63030. backgroundImage = backgroundImage_;
  63031. jassert (backgroundImage_.isValid());
  63032. if (backgroundImage_.isValid())
  63033. {
  63034. setOpaque (! backgroundImage_.hasAlphaChannel());
  63035. show (title,
  63036. backgroundImage_.getWidth(),
  63037. backgroundImage_.getHeight(),
  63038. minimumTimeToDisplayFor,
  63039. useDropShadow,
  63040. removeOnMouseClick);
  63041. }
  63042. }
  63043. void SplashScreen::show (const String& title,
  63044. const int width,
  63045. const int height,
  63046. const int minimumTimeToDisplayFor,
  63047. const bool useDropShadow,
  63048. const bool removeOnMouseClick)
  63049. {
  63050. setName (title);
  63051. setAlwaysOnTop (true);
  63052. setVisible (true);
  63053. centreWithSize (width, height);
  63054. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  63055. toFront (false);
  63056. MessageManager::getInstance()->runDispatchLoopUntil (300);
  63057. repaint();
  63058. originalClickCounter = removeOnMouseClick
  63059. ? Desktop::getMouseButtonClickCounter()
  63060. : std::numeric_limits<int>::max();
  63061. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  63062. startTimer (50);
  63063. }
  63064. void SplashScreen::paint (Graphics& g)
  63065. {
  63066. g.setOpacity (1.0f);
  63067. g.drawImage (backgroundImage,
  63068. 0, 0, getWidth(), getHeight(),
  63069. 0, 0, backgroundImage.getWidth(), backgroundImage.getHeight());
  63070. }
  63071. void SplashScreen::timerCallback()
  63072. {
  63073. if (Time::getCurrentTime() > earliestTimeToDelete
  63074. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  63075. {
  63076. delete this;
  63077. }
  63078. }
  63079. END_JUCE_NAMESPACE
  63080. /*** End of inlined file: juce_SplashScreen.cpp ***/
  63081. /*** Start of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63082. BEGIN_JUCE_NAMESPACE
  63083. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  63084. const bool hasProgressBar,
  63085. const bool hasCancelButton,
  63086. const int timeOutMsWhenCancelling_,
  63087. const String& cancelButtonText)
  63088. : Thread ("Juce Progress Window"),
  63089. progress (0.0),
  63090. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  63091. {
  63092. alertWindow = LookAndFeel::getDefaultLookAndFeel()
  63093. .createAlertWindow (title, String::empty, cancelButtonText,
  63094. String::empty, String::empty,
  63095. AlertWindow::NoIcon, hasCancelButton ? 1 : 0, 0);
  63096. if (hasProgressBar)
  63097. alertWindow->addProgressBarComponent (progress);
  63098. }
  63099. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  63100. {
  63101. stopThread (timeOutMsWhenCancelling);
  63102. }
  63103. bool ThreadWithProgressWindow::runThread (const int priority)
  63104. {
  63105. startThread (priority);
  63106. startTimer (100);
  63107. {
  63108. const ScopedLock sl (messageLock);
  63109. alertWindow->setMessage (message);
  63110. }
  63111. const bool finishedNaturally = alertWindow->runModalLoop() != 0;
  63112. stopThread (timeOutMsWhenCancelling);
  63113. alertWindow->setVisible (false);
  63114. return finishedNaturally;
  63115. }
  63116. void ThreadWithProgressWindow::setProgress (const double newProgress)
  63117. {
  63118. progress = newProgress;
  63119. }
  63120. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  63121. {
  63122. const ScopedLock sl (messageLock);
  63123. message = newStatusMessage;
  63124. }
  63125. void ThreadWithProgressWindow::timerCallback()
  63126. {
  63127. if (! isThreadRunning())
  63128. {
  63129. // thread has finished normally..
  63130. alertWindow->exitModalState (1);
  63131. alertWindow->setVisible (false);
  63132. }
  63133. else
  63134. {
  63135. const ScopedLock sl (messageLock);
  63136. alertWindow->setMessage (message);
  63137. }
  63138. }
  63139. END_JUCE_NAMESPACE
  63140. /*** End of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63141. /*** Start of inlined file: juce_TooltipWindow.cpp ***/
  63142. BEGIN_JUCE_NAMESPACE
  63143. TooltipWindow::TooltipWindow (Component* const parentComponent,
  63144. const int millisecondsBeforeTipAppears_)
  63145. : Component ("tooltip"),
  63146. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  63147. mouseClicks (0),
  63148. lastHideTime (0),
  63149. lastComponentUnderMouse (0),
  63150. changedCompsSinceShown (true)
  63151. {
  63152. if (Desktop::getInstance().getMainMouseSource().canHover())
  63153. startTimer (123);
  63154. setAlwaysOnTop (true);
  63155. setOpaque (true);
  63156. if (parentComponent != 0)
  63157. parentComponent->addChildComponent (this);
  63158. }
  63159. TooltipWindow::~TooltipWindow()
  63160. {
  63161. hide();
  63162. }
  63163. void TooltipWindow::setMillisecondsBeforeTipAppears (const int newTimeMs) throw()
  63164. {
  63165. millisecondsBeforeTipAppears = newTimeMs;
  63166. }
  63167. void TooltipWindow::paint (Graphics& g)
  63168. {
  63169. getLookAndFeel().drawTooltip (g, tipShowing, getWidth(), getHeight());
  63170. }
  63171. void TooltipWindow::mouseEnter (const MouseEvent&)
  63172. {
  63173. hide();
  63174. }
  63175. void TooltipWindow::showFor (const String& tip)
  63176. {
  63177. jassert (tip.isNotEmpty());
  63178. tipShowing = tip;
  63179. Point<int> mousePos (Desktop::getMousePosition());
  63180. if (getParentComponent() != 0)
  63181. mousePos = getParentComponent()->globalPositionToRelative (mousePos);
  63182. int x, y, w, h;
  63183. getLookAndFeel().getTooltipSize (tip, w, h);
  63184. if (mousePos.getX() > getParentWidth() / 2)
  63185. x = mousePos.getX() - (w + 12);
  63186. else
  63187. x = mousePos.getX() + 24;
  63188. if (mousePos.getY() > getParentHeight() / 2)
  63189. y = mousePos.getY() - (h + 6);
  63190. else
  63191. y = mousePos.getY() + 6;
  63192. setBounds (x, y, w, h);
  63193. setVisible (true);
  63194. if (getParentComponent() == 0)
  63195. {
  63196. addToDesktop (ComponentPeer::windowHasDropShadow
  63197. | ComponentPeer::windowIsTemporary
  63198. | ComponentPeer::windowIgnoresKeyPresses);
  63199. }
  63200. toFront (false);
  63201. }
  63202. const String TooltipWindow::getTipFor (Component* const c)
  63203. {
  63204. if (c != 0
  63205. && Process::isForegroundProcess()
  63206. && ! Component::isMouseButtonDownAnywhere())
  63207. {
  63208. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  63209. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  63210. return ttc->getTooltip();
  63211. }
  63212. return String::empty;
  63213. }
  63214. void TooltipWindow::hide()
  63215. {
  63216. tipShowing = String::empty;
  63217. removeFromDesktop();
  63218. setVisible (false);
  63219. }
  63220. void TooltipWindow::timerCallback()
  63221. {
  63222. const unsigned int now = Time::getApproximateMillisecondCounter();
  63223. Component* const newComp = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  63224. const String newTip (getTipFor (newComp));
  63225. const bool tipChanged = (newTip != lastTipUnderMouse || newComp != lastComponentUnderMouse);
  63226. lastComponentUnderMouse = newComp;
  63227. lastTipUnderMouse = newTip;
  63228. const int clickCount = Desktop::getInstance().getMouseButtonClickCounter();
  63229. const bool mouseWasClicked = clickCount > mouseClicks;
  63230. mouseClicks = clickCount;
  63231. const Point<int> mousePos (Desktop::getMousePosition());
  63232. const bool mouseMovedQuickly = mousePos.getDistanceFrom (lastMousePos) > 12;
  63233. lastMousePos = mousePos;
  63234. if (tipChanged || mouseWasClicked || mouseMovedQuickly)
  63235. lastCompChangeTime = now;
  63236. if (isVisible() || now < lastHideTime + 500)
  63237. {
  63238. // if a tip is currently visible (or has just disappeared), update to a new one
  63239. // immediately if needed..
  63240. if (newComp == 0 || mouseWasClicked || newTip.isEmpty())
  63241. {
  63242. if (isVisible())
  63243. {
  63244. lastHideTime = now;
  63245. hide();
  63246. }
  63247. }
  63248. else if (tipChanged)
  63249. {
  63250. showFor (newTip);
  63251. }
  63252. }
  63253. else
  63254. {
  63255. // if there isn't currently a tip, but one is needed, only let it
  63256. // appear after a timeout..
  63257. if (newTip.isNotEmpty()
  63258. && newTip != tipShowing
  63259. && now > lastCompChangeTime + millisecondsBeforeTipAppears)
  63260. {
  63261. showFor (newTip);
  63262. }
  63263. }
  63264. }
  63265. END_JUCE_NAMESPACE
  63266. /*** End of inlined file: juce_TooltipWindow.cpp ***/
  63267. /*** Start of inlined file: juce_TopLevelWindow.cpp ***/
  63268. BEGIN_JUCE_NAMESPACE
  63269. /** Keeps track of the active top level window.
  63270. */
  63271. class TopLevelWindowManager : public Timer,
  63272. public DeletedAtShutdown
  63273. {
  63274. public:
  63275. TopLevelWindowManager()
  63276. : currentActive (0)
  63277. {
  63278. }
  63279. ~TopLevelWindowManager()
  63280. {
  63281. clearSingletonInstance();
  63282. }
  63283. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  63284. void timerCallback()
  63285. {
  63286. startTimer (jmin (1731, getTimerInterval() * 2));
  63287. TopLevelWindow* active = 0;
  63288. if (Process::isForegroundProcess())
  63289. {
  63290. active = currentActive;
  63291. Component* const c = Component::getCurrentlyFocusedComponent();
  63292. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  63293. if (tlw == 0 && c != 0)
  63294. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  63295. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  63296. if (tlw != 0)
  63297. active = tlw;
  63298. }
  63299. if (active != currentActive)
  63300. {
  63301. currentActive = active;
  63302. for (int i = windows.size(); --i >= 0;)
  63303. {
  63304. TopLevelWindow* const tlw = windows.getUnchecked (i);
  63305. tlw->setWindowActive (isWindowActive (tlw));
  63306. i = jmin (i, windows.size() - 1);
  63307. }
  63308. Desktop::getInstance().triggerFocusCallback();
  63309. }
  63310. }
  63311. bool addWindow (TopLevelWindow* const w)
  63312. {
  63313. windows.add (w);
  63314. startTimer (10);
  63315. return isWindowActive (w);
  63316. }
  63317. void removeWindow (TopLevelWindow* const w)
  63318. {
  63319. startTimer (10);
  63320. if (currentActive == w)
  63321. currentActive = 0;
  63322. windows.removeValue (w);
  63323. if (windows.size() == 0)
  63324. deleteInstance();
  63325. }
  63326. Array <TopLevelWindow*> windows;
  63327. private:
  63328. TopLevelWindow* currentActive;
  63329. bool isWindowActive (TopLevelWindow* const tlw) const
  63330. {
  63331. return (tlw == currentActive
  63332. || tlw->isParentOf (currentActive)
  63333. || tlw->hasKeyboardFocus (true))
  63334. && tlw->isShowing();
  63335. }
  63336. TopLevelWindowManager (const TopLevelWindowManager&);
  63337. TopLevelWindowManager& operator= (const TopLevelWindowManager&);
  63338. };
  63339. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  63340. void juce_CheckCurrentlyFocusedTopLevelWindow()
  63341. {
  63342. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  63343. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  63344. }
  63345. TopLevelWindow::TopLevelWindow (const String& name,
  63346. const bool addToDesktop_)
  63347. : Component (name),
  63348. useDropShadow (true),
  63349. useNativeTitleBar (false),
  63350. windowIsActive_ (false)
  63351. {
  63352. setOpaque (true);
  63353. if (addToDesktop_)
  63354. Component::addToDesktop (getDesktopWindowStyleFlags());
  63355. else
  63356. setDropShadowEnabled (true);
  63357. setWantsKeyboardFocus (true);
  63358. setBroughtToFrontOnMouseClick (true);
  63359. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  63360. }
  63361. TopLevelWindow::~TopLevelWindow()
  63362. {
  63363. shadower = 0;
  63364. TopLevelWindowManager::getInstance()->removeWindow (this);
  63365. }
  63366. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  63367. {
  63368. if (hasKeyboardFocus (true))
  63369. TopLevelWindowManager::getInstance()->timerCallback();
  63370. else
  63371. TopLevelWindowManager::getInstance()->startTimer (10);
  63372. }
  63373. void TopLevelWindow::setWindowActive (const bool isNowActive)
  63374. {
  63375. if (windowIsActive_ != isNowActive)
  63376. {
  63377. windowIsActive_ = isNowActive;
  63378. activeWindowStatusChanged();
  63379. }
  63380. }
  63381. void TopLevelWindow::activeWindowStatusChanged()
  63382. {
  63383. }
  63384. void TopLevelWindow::parentHierarchyChanged()
  63385. {
  63386. setDropShadowEnabled (useDropShadow);
  63387. }
  63388. void TopLevelWindow::visibilityChanged()
  63389. {
  63390. if (isShowing())
  63391. toFront (true);
  63392. }
  63393. int TopLevelWindow::getDesktopWindowStyleFlags() const
  63394. {
  63395. int styleFlags = ComponentPeer::windowAppearsOnTaskbar;
  63396. if (useDropShadow)
  63397. styleFlags |= ComponentPeer::windowHasDropShadow;
  63398. if (useNativeTitleBar)
  63399. styleFlags |= ComponentPeer::windowHasTitleBar;
  63400. return styleFlags;
  63401. }
  63402. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  63403. {
  63404. useDropShadow = useShadow;
  63405. if (isOnDesktop())
  63406. {
  63407. shadower = 0;
  63408. Component::addToDesktop (getDesktopWindowStyleFlags());
  63409. }
  63410. else
  63411. {
  63412. if (useShadow && isOpaque())
  63413. {
  63414. if (shadower == 0)
  63415. {
  63416. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  63417. if (shadower != 0)
  63418. shadower->setOwner (this);
  63419. }
  63420. }
  63421. else
  63422. {
  63423. shadower = 0;
  63424. }
  63425. }
  63426. }
  63427. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  63428. {
  63429. if (useNativeTitleBar != useNativeTitleBar_)
  63430. {
  63431. useNativeTitleBar = useNativeTitleBar_;
  63432. recreateDesktopWindow();
  63433. sendLookAndFeelChange();
  63434. }
  63435. }
  63436. void TopLevelWindow::recreateDesktopWindow()
  63437. {
  63438. if (isOnDesktop())
  63439. {
  63440. Component::addToDesktop (getDesktopWindowStyleFlags());
  63441. toFront (true);
  63442. }
  63443. }
  63444. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  63445. {
  63446. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  63447. because this class needs to make sure its layout corresponds with settings like whether
  63448. it's got a native title bar or not.
  63449. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  63450. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  63451. method, then add or remove whatever flags are necessary from this value before returning it.
  63452. */
  63453. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  63454. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  63455. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  63456. if (windowStyleFlags != getDesktopWindowStyleFlags())
  63457. sendLookAndFeelChange();
  63458. }
  63459. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  63460. {
  63461. if (c == 0)
  63462. c = TopLevelWindow::getActiveTopLevelWindow();
  63463. if (c == 0)
  63464. {
  63465. centreWithSize (width, height);
  63466. }
  63467. else
  63468. {
  63469. Point<int> p (c->relativePositionToGlobal (Point<int> ((c->getWidth() - width) / 2,
  63470. (c->getHeight() - height) / 2)));
  63471. Rectangle<int> parentArea (c->getParentMonitorArea());
  63472. if (getParentComponent() != 0)
  63473. {
  63474. p = getParentComponent()->globalPositionToRelative (p);
  63475. parentArea.setBounds (0, 0, getParentWidth(), getParentHeight());
  63476. }
  63477. parentArea.reduce (12, 12);
  63478. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), p.getX()),
  63479. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), p.getY()),
  63480. width, height);
  63481. }
  63482. }
  63483. int TopLevelWindow::getNumTopLevelWindows() throw()
  63484. {
  63485. return TopLevelWindowManager::getInstance()->windows.size();
  63486. }
  63487. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  63488. {
  63489. return static_cast <TopLevelWindow*> (TopLevelWindowManager::getInstance()->windows [index]);
  63490. }
  63491. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  63492. {
  63493. TopLevelWindow* best = 0;
  63494. int bestNumTWLParents = -1;
  63495. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  63496. {
  63497. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  63498. if (tlw->isActiveWindow())
  63499. {
  63500. int numTWLParents = 0;
  63501. const Component* c = tlw->getParentComponent();
  63502. while (c != 0)
  63503. {
  63504. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  63505. ++numTWLParents;
  63506. c = c->getParentComponent();
  63507. }
  63508. if (bestNumTWLParents < numTWLParents)
  63509. {
  63510. best = tlw;
  63511. bestNumTWLParents = numTWLParents;
  63512. }
  63513. }
  63514. }
  63515. return best;
  63516. }
  63517. END_JUCE_NAMESPACE
  63518. /*** End of inlined file: juce_TopLevelWindow.cpp ***/
  63519. #endif
  63520. #if JUCE_BUILD_MISC // (put these in misc to balance the file sizes and avoid problems in iphone build)
  63521. /*** Start of inlined file: juce_Colour.cpp ***/
  63522. BEGIN_JUCE_NAMESPACE
  63523. namespace ColourHelpers
  63524. {
  63525. static uint8 floatAlphaToInt (const float alpha) throw()
  63526. {
  63527. return (uint8) jlimit (0, 0xff, roundToInt (alpha * 255.0f));
  63528. }
  63529. static void convertHSBtoRGB (float h, float s, float v,
  63530. uint8& r, uint8& g, uint8& b) throw()
  63531. {
  63532. v = jlimit (0.0f, 1.0f, v);
  63533. v *= 255.0f;
  63534. const uint8 intV = (uint8) roundToInt (v);
  63535. if (s <= 0)
  63536. {
  63537. r = intV;
  63538. g = intV;
  63539. b = intV;
  63540. }
  63541. else
  63542. {
  63543. s = jmin (1.0f, s);
  63544. h = jlimit (0.0f, 1.0f, h);
  63545. h = (h - std::floor (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  63546. const float f = h - std::floor (h);
  63547. const uint8 x = (uint8) roundToInt (v * (1.0f - s));
  63548. const float y = v * (1.0f - s * f);
  63549. const float z = v * (1.0f - (s * (1.0f - f)));
  63550. if (h < 1.0f)
  63551. {
  63552. r = intV;
  63553. g = (uint8) roundToInt (z);
  63554. b = x;
  63555. }
  63556. else if (h < 2.0f)
  63557. {
  63558. r = (uint8) roundToInt (y);
  63559. g = intV;
  63560. b = x;
  63561. }
  63562. else if (h < 3.0f)
  63563. {
  63564. r = x;
  63565. g = intV;
  63566. b = (uint8) roundToInt (z);
  63567. }
  63568. else if (h < 4.0f)
  63569. {
  63570. r = x;
  63571. g = (uint8) roundToInt (y);
  63572. b = intV;
  63573. }
  63574. else if (h < 5.0f)
  63575. {
  63576. r = (uint8) roundToInt (z);
  63577. g = x;
  63578. b = intV;
  63579. }
  63580. else if (h < 6.0f)
  63581. {
  63582. r = intV;
  63583. g = x;
  63584. b = (uint8) roundToInt (y);
  63585. }
  63586. else
  63587. {
  63588. r = 0;
  63589. g = 0;
  63590. b = 0;
  63591. }
  63592. }
  63593. }
  63594. }
  63595. Colour::Colour() throw()
  63596. : argb (0)
  63597. {
  63598. }
  63599. Colour::Colour (const Colour& other) throw()
  63600. : argb (other.argb)
  63601. {
  63602. }
  63603. Colour& Colour::operator= (const Colour& other) throw()
  63604. {
  63605. argb = other.argb;
  63606. return *this;
  63607. }
  63608. bool Colour::operator== (const Colour& other) const throw()
  63609. {
  63610. return argb.getARGB() == other.argb.getARGB();
  63611. }
  63612. bool Colour::operator!= (const Colour& other) const throw()
  63613. {
  63614. return argb.getARGB() != other.argb.getARGB();
  63615. }
  63616. Colour::Colour (const uint32 argb_) throw()
  63617. : argb (argb_)
  63618. {
  63619. }
  63620. Colour::Colour (const uint8 red,
  63621. const uint8 green,
  63622. const uint8 blue) throw()
  63623. {
  63624. argb.setARGB (0xff, red, green, blue);
  63625. }
  63626. const Colour Colour::fromRGB (const uint8 red,
  63627. const uint8 green,
  63628. const uint8 blue) throw()
  63629. {
  63630. return Colour (red, green, blue);
  63631. }
  63632. Colour::Colour (const uint8 red,
  63633. const uint8 green,
  63634. const uint8 blue,
  63635. const uint8 alpha) throw()
  63636. {
  63637. argb.setARGB (alpha, red, green, blue);
  63638. }
  63639. const Colour Colour::fromRGBA (const uint8 red,
  63640. const uint8 green,
  63641. const uint8 blue,
  63642. const uint8 alpha) throw()
  63643. {
  63644. return Colour (red, green, blue, alpha);
  63645. }
  63646. Colour::Colour (const uint8 red,
  63647. const uint8 green,
  63648. const uint8 blue,
  63649. const float alpha) throw()
  63650. {
  63651. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), red, green, blue);
  63652. }
  63653. const Colour Colour::fromRGBAFloat (const uint8 red,
  63654. const uint8 green,
  63655. const uint8 blue,
  63656. const float alpha) throw()
  63657. {
  63658. return Colour (red, green, blue, alpha);
  63659. }
  63660. Colour::Colour (const float hue,
  63661. const float saturation,
  63662. const float brightness,
  63663. const float alpha) throw()
  63664. {
  63665. uint8 r = getRed(), g = getGreen(), b = getBlue();
  63666. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  63667. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), r, g, b);
  63668. }
  63669. const Colour Colour::fromHSV (const float hue,
  63670. const float saturation,
  63671. const float brightness,
  63672. const float alpha) throw()
  63673. {
  63674. return Colour (hue, saturation, brightness, alpha);
  63675. }
  63676. Colour::Colour (const float hue,
  63677. const float saturation,
  63678. const float brightness,
  63679. const uint8 alpha) throw()
  63680. {
  63681. uint8 r = getRed(), g = getGreen(), b = getBlue();
  63682. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  63683. argb.setARGB (alpha, r, g, b);
  63684. }
  63685. Colour::~Colour() throw()
  63686. {
  63687. }
  63688. const PixelARGB Colour::getPixelARGB() const throw()
  63689. {
  63690. PixelARGB p (argb);
  63691. p.premultiply();
  63692. return p;
  63693. }
  63694. uint32 Colour::getARGB() const throw()
  63695. {
  63696. return argb.getARGB();
  63697. }
  63698. bool Colour::isTransparent() const throw()
  63699. {
  63700. return getAlpha() == 0;
  63701. }
  63702. bool Colour::isOpaque() const throw()
  63703. {
  63704. return getAlpha() == 0xff;
  63705. }
  63706. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  63707. {
  63708. PixelARGB newCol (argb);
  63709. newCol.setAlpha (newAlpha);
  63710. return Colour (newCol.getARGB());
  63711. }
  63712. const Colour Colour::withAlpha (const float newAlpha) const throw()
  63713. {
  63714. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  63715. PixelARGB newCol (argb);
  63716. newCol.setAlpha (ColourHelpers::floatAlphaToInt (newAlpha));
  63717. return Colour (newCol.getARGB());
  63718. }
  63719. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  63720. {
  63721. jassert (alphaMultiplier >= 0);
  63722. PixelARGB newCol (argb);
  63723. newCol.setAlpha ((uint8) jmin (0xff, roundToInt (alphaMultiplier * newCol.getAlpha())));
  63724. return Colour (newCol.getARGB());
  63725. }
  63726. const Colour Colour::overlaidWith (const Colour& src) const throw()
  63727. {
  63728. const int destAlpha = getAlpha();
  63729. if (destAlpha > 0)
  63730. {
  63731. const int invA = 0xff - (int) src.getAlpha();
  63732. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  63733. if (resA > 0)
  63734. {
  63735. const int da = (invA * destAlpha) / resA;
  63736. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  63737. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  63738. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  63739. (uint8) resA);
  63740. }
  63741. return *this;
  63742. }
  63743. else
  63744. {
  63745. return src;
  63746. }
  63747. }
  63748. const Colour Colour::interpolatedWith (const Colour& other, float proportionOfOther) const throw()
  63749. {
  63750. if (proportionOfOther <= 0)
  63751. return *this;
  63752. if (proportionOfOther >= 1.0f)
  63753. return other;
  63754. PixelARGB c1 (getPixelARGB());
  63755. const PixelARGB c2 (other.getPixelARGB());
  63756. c1.tween (c2, roundToInt (proportionOfOther * 255.0f));
  63757. c1.unpremultiply();
  63758. return Colour (c1.getARGB());
  63759. }
  63760. float Colour::getFloatRed() const throw()
  63761. {
  63762. return getRed() / 255.0f;
  63763. }
  63764. float Colour::getFloatGreen() const throw()
  63765. {
  63766. return getGreen() / 255.0f;
  63767. }
  63768. float Colour::getFloatBlue() const throw()
  63769. {
  63770. return getBlue() / 255.0f;
  63771. }
  63772. float Colour::getFloatAlpha() const throw()
  63773. {
  63774. return getAlpha() / 255.0f;
  63775. }
  63776. void Colour::getHSB (float& h, float& s, float& v) const throw()
  63777. {
  63778. const int r = getRed();
  63779. const int g = getGreen();
  63780. const int b = getBlue();
  63781. const int hi = jmax (r, g, b);
  63782. const int lo = jmin (r, g, b);
  63783. if (hi != 0)
  63784. {
  63785. s = (hi - lo) / (float) hi;
  63786. if (s != 0)
  63787. {
  63788. const float invDiff = 1.0f / (hi - lo);
  63789. const float red = (hi - r) * invDiff;
  63790. const float green = (hi - g) * invDiff;
  63791. const float blue = (hi - b) * invDiff;
  63792. if (r == hi)
  63793. h = blue - green;
  63794. else if (g == hi)
  63795. h = 2.0f + red - blue;
  63796. else
  63797. h = 4.0f + green - red;
  63798. h *= 1.0f / 6.0f;
  63799. if (h < 0)
  63800. ++h;
  63801. }
  63802. else
  63803. {
  63804. h = 0;
  63805. }
  63806. }
  63807. else
  63808. {
  63809. s = 0;
  63810. h = 0;
  63811. }
  63812. v = hi / 255.0f;
  63813. }
  63814. float Colour::getHue() const throw()
  63815. {
  63816. float h, s, b;
  63817. getHSB (h, s, b);
  63818. return h;
  63819. }
  63820. const Colour Colour::withHue (const float hue) const throw()
  63821. {
  63822. float h, s, b;
  63823. getHSB (h, s, b);
  63824. return Colour (hue, s, b, getAlpha());
  63825. }
  63826. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  63827. {
  63828. float h, s, b;
  63829. getHSB (h, s, b);
  63830. h += amountToRotate;
  63831. h -= std::floor (h);
  63832. return Colour (h, s, b, getAlpha());
  63833. }
  63834. float Colour::getSaturation() const throw()
  63835. {
  63836. float h, s, b;
  63837. getHSB (h, s, b);
  63838. return s;
  63839. }
  63840. const Colour Colour::withSaturation (const float saturation) const throw()
  63841. {
  63842. float h, s, b;
  63843. getHSB (h, s, b);
  63844. return Colour (h, saturation, b, getAlpha());
  63845. }
  63846. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  63847. {
  63848. float h, s, b;
  63849. getHSB (h, s, b);
  63850. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  63851. }
  63852. float Colour::getBrightness() const throw()
  63853. {
  63854. float h, s, b;
  63855. getHSB (h, s, b);
  63856. return b;
  63857. }
  63858. const Colour Colour::withBrightness (const float brightness) const throw()
  63859. {
  63860. float h, s, b;
  63861. getHSB (h, s, b);
  63862. return Colour (h, s, brightness, getAlpha());
  63863. }
  63864. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  63865. {
  63866. float h, s, b;
  63867. getHSB (h, s, b);
  63868. b *= amount;
  63869. if (b > 1.0f)
  63870. b = 1.0f;
  63871. return Colour (h, s, b, getAlpha());
  63872. }
  63873. const Colour Colour::brighter (float amount) const throw()
  63874. {
  63875. amount = 1.0f / (1.0f + amount);
  63876. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  63877. (uint8) (255 - (amount * (255 - getGreen()))),
  63878. (uint8) (255 - (amount * (255 - getBlue()))),
  63879. getAlpha());
  63880. }
  63881. const Colour Colour::darker (float amount) const throw()
  63882. {
  63883. amount = 1.0f / (1.0f + amount);
  63884. return Colour ((uint8) (amount * getRed()),
  63885. (uint8) (amount * getGreen()),
  63886. (uint8) (amount * getBlue()),
  63887. getAlpha());
  63888. }
  63889. const Colour Colour::greyLevel (const float brightness) throw()
  63890. {
  63891. const uint8 level
  63892. = (uint8) jlimit (0x00, 0xff, roundToInt (brightness * 255.0f));
  63893. return Colour (level, level, level);
  63894. }
  63895. const Colour Colour::contrasting (const float amount) const throw()
  63896. {
  63897. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  63898. ? Colours::black
  63899. : Colours::white).withAlpha (amount));
  63900. }
  63901. const Colour Colour::contrasting (const Colour& colour1,
  63902. const Colour& colour2) throw()
  63903. {
  63904. const float b1 = colour1.getBrightness();
  63905. const float b2 = colour2.getBrightness();
  63906. float best = 0.0f;
  63907. float bestDist = 0.0f;
  63908. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  63909. {
  63910. const float d1 = std::abs (i - b1);
  63911. const float d2 = std::abs (i - b2);
  63912. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  63913. if (dist > bestDist)
  63914. {
  63915. best = i;
  63916. bestDist = dist;
  63917. }
  63918. }
  63919. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  63920. .withBrightness (best);
  63921. }
  63922. const String Colour::toString() const
  63923. {
  63924. return String::toHexString ((int) argb.getARGB());
  63925. }
  63926. const Colour Colour::fromString (const String& encodedColourString)
  63927. {
  63928. return Colour ((uint32) encodedColourString.getHexValue32());
  63929. }
  63930. const String Colour::toDisplayString (const bool includeAlphaValue) const
  63931. {
  63932. return String::toHexString ((int) (argb.getARGB() & (includeAlphaValue ? 0xffffffff : 0xffffff)))
  63933. .paddedLeft ('0', includeAlphaValue ? 8 : 6)
  63934. .toUpperCase();
  63935. }
  63936. END_JUCE_NAMESPACE
  63937. /*** End of inlined file: juce_Colour.cpp ***/
  63938. /*** Start of inlined file: juce_ColourGradient.cpp ***/
  63939. BEGIN_JUCE_NAMESPACE
  63940. ColourGradient::ColourGradient() throw()
  63941. {
  63942. #if JUCE_DEBUG
  63943. point1.setX (987654.0f);
  63944. #endif
  63945. }
  63946. ColourGradient::ColourGradient (const Colour& colour1, const float x1_, const float y1_,
  63947. const Colour& colour2, const float x2_, const float y2_,
  63948. const bool isRadial_)
  63949. : point1 (x1_, y1_),
  63950. point2 (x2_, y2_),
  63951. isRadial (isRadial_)
  63952. {
  63953. colours.add (ColourPoint (0.0, colour1));
  63954. colours.add (ColourPoint (1.0, colour2));
  63955. }
  63956. ColourGradient::~ColourGradient()
  63957. {
  63958. }
  63959. bool ColourGradient::operator== (const ColourGradient& other) const throw()
  63960. {
  63961. return point1 == other.point1 && point2 == other.point2
  63962. && isRadial == other.isRadial
  63963. && colours == other.colours;
  63964. }
  63965. bool ColourGradient::operator!= (const ColourGradient& other) const throw()
  63966. {
  63967. return ! operator== (other);
  63968. }
  63969. void ColourGradient::clearColours()
  63970. {
  63971. colours.clear();
  63972. }
  63973. int ColourGradient::addColour (const double proportionAlongGradient, const Colour& colour)
  63974. {
  63975. // must be within the two end-points
  63976. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  63977. const double pos = jlimit (0.0, 1.0, proportionAlongGradient);
  63978. int i;
  63979. for (i = 0; i < colours.size(); ++i)
  63980. if (colours.getReference(i).position > pos)
  63981. break;
  63982. colours.insert (i, ColourPoint (pos, colour));
  63983. return i;
  63984. }
  63985. void ColourGradient::removeColour (int index)
  63986. {
  63987. jassert (index > 0 && index < colours.size() - 1);
  63988. colours.remove (index);
  63989. }
  63990. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  63991. {
  63992. for (int i = 0; i < colours.size(); ++i)
  63993. {
  63994. Colour& c = colours.getReference(i).colour;
  63995. c = c.withMultipliedAlpha (multiplier);
  63996. }
  63997. }
  63998. int ColourGradient::getNumColours() const throw()
  63999. {
  64000. return colours.size();
  64001. }
  64002. double ColourGradient::getColourPosition (const int index) const throw()
  64003. {
  64004. if (((unsigned int) index) < (unsigned int) colours.size())
  64005. return colours.getReference (index).position;
  64006. return 0;
  64007. }
  64008. const Colour ColourGradient::getColour (const int index) const throw()
  64009. {
  64010. if (((unsigned int) index) < (unsigned int) colours.size())
  64011. return colours.getReference (index).colour;
  64012. return Colour();
  64013. }
  64014. void ColourGradient::setColour (int index, const Colour& newColour) throw()
  64015. {
  64016. if (((unsigned int) index) < (unsigned int) colours.size())
  64017. colours.getReference (index).colour = newColour;
  64018. }
  64019. const Colour ColourGradient::getColourAtPosition (const double position) const throw()
  64020. {
  64021. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  64022. if (position <= 0 || colours.size() <= 1)
  64023. return colours.getReference(0).colour;
  64024. int i = colours.size() - 1;
  64025. while (position < colours.getReference(i).position)
  64026. --i;
  64027. const ColourPoint& p1 = colours.getReference (i);
  64028. if (i >= colours.size() - 1)
  64029. return p1.colour;
  64030. const ColourPoint& p2 = colours.getReference (i + 1);
  64031. return p1.colour.interpolatedWith (p2.colour, (float) ((position - p1.position) / (p2.position - p1.position)));
  64032. }
  64033. int ColourGradient::createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& lookupTable) const
  64034. {
  64035. #if JUCE_DEBUG
  64036. // trying to use the object without setting its co-ordinates? Have a careful read of
  64037. // the comments for the constructors.
  64038. jassert (point1.getX() != 987654.0f);
  64039. #endif
  64040. const int numEntries = jlimit (1, jmax (1, (colours.size() - 1) << 8),
  64041. 3 * (int) point1.transformedBy (transform)
  64042. .getDistanceFrom (point2.transformedBy (transform)));
  64043. lookupTable.malloc (numEntries);
  64044. if (colours.size() >= 2)
  64045. {
  64046. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  64047. PixelARGB pix1 (colours.getReference (0).colour.getPixelARGB());
  64048. int index = 0;
  64049. for (int j = 1; j < colours.size(); ++j)
  64050. {
  64051. const ColourPoint& p = colours.getReference (j);
  64052. const int numToDo = roundToInt (p.position * (numEntries - 1)) - index;
  64053. const PixelARGB pix2 (p.colour.getPixelARGB());
  64054. for (int i = 0; i < numToDo; ++i)
  64055. {
  64056. jassert (index >= 0 && index < numEntries);
  64057. lookupTable[index] = pix1;
  64058. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  64059. ++index;
  64060. }
  64061. pix1 = pix2;
  64062. }
  64063. while (index < numEntries)
  64064. lookupTable [index++] = pix1;
  64065. }
  64066. else
  64067. {
  64068. jassertfalse; // no colours specified!
  64069. }
  64070. return numEntries;
  64071. }
  64072. bool ColourGradient::isOpaque() const throw()
  64073. {
  64074. for (int i = 0; i < colours.size(); ++i)
  64075. if (! colours.getReference(i).colour.isOpaque())
  64076. return false;
  64077. return true;
  64078. }
  64079. bool ColourGradient::isInvisible() const throw()
  64080. {
  64081. for (int i = 0; i < colours.size(); ++i)
  64082. if (! colours.getReference(i).colour.isTransparent())
  64083. return false;
  64084. return true;
  64085. }
  64086. END_JUCE_NAMESPACE
  64087. /*** End of inlined file: juce_ColourGradient.cpp ***/
  64088. /*** Start of inlined file: juce_Colours.cpp ***/
  64089. BEGIN_JUCE_NAMESPACE
  64090. const Colour Colours::transparentBlack (0);
  64091. const Colour Colours::transparentWhite (0x00ffffff);
  64092. const Colour Colours::aliceblue (0xfff0f8ff);
  64093. const Colour Colours::antiquewhite (0xfffaebd7);
  64094. const Colour Colours::aqua (0xff00ffff);
  64095. const Colour Colours::aquamarine (0xff7fffd4);
  64096. const Colour Colours::azure (0xfff0ffff);
  64097. const Colour Colours::beige (0xfff5f5dc);
  64098. const Colour Colours::bisque (0xffffe4c4);
  64099. const Colour Colours::black (0xff000000);
  64100. const Colour Colours::blanchedalmond (0xffffebcd);
  64101. const Colour Colours::blue (0xff0000ff);
  64102. const Colour Colours::blueviolet (0xff8a2be2);
  64103. const Colour Colours::brown (0xffa52a2a);
  64104. const Colour Colours::burlywood (0xffdeb887);
  64105. const Colour Colours::cadetblue (0xff5f9ea0);
  64106. const Colour Colours::chartreuse (0xff7fff00);
  64107. const Colour Colours::chocolate (0xffd2691e);
  64108. const Colour Colours::coral (0xffff7f50);
  64109. const Colour Colours::cornflowerblue (0xff6495ed);
  64110. const Colour Colours::cornsilk (0xfffff8dc);
  64111. const Colour Colours::crimson (0xffdc143c);
  64112. const Colour Colours::cyan (0xff00ffff);
  64113. const Colour Colours::darkblue (0xff00008b);
  64114. const Colour Colours::darkcyan (0xff008b8b);
  64115. const Colour Colours::darkgoldenrod (0xffb8860b);
  64116. const Colour Colours::darkgrey (0xff555555);
  64117. const Colour Colours::darkgreen (0xff006400);
  64118. const Colour Colours::darkkhaki (0xffbdb76b);
  64119. const Colour Colours::darkmagenta (0xff8b008b);
  64120. const Colour Colours::darkolivegreen (0xff556b2f);
  64121. const Colour Colours::darkorange (0xffff8c00);
  64122. const Colour Colours::darkorchid (0xff9932cc);
  64123. const Colour Colours::darkred (0xff8b0000);
  64124. const Colour Colours::darksalmon (0xffe9967a);
  64125. const Colour Colours::darkseagreen (0xff8fbc8f);
  64126. const Colour Colours::darkslateblue (0xff483d8b);
  64127. const Colour Colours::darkslategrey (0xff2f4f4f);
  64128. const Colour Colours::darkturquoise (0xff00ced1);
  64129. const Colour Colours::darkviolet (0xff9400d3);
  64130. const Colour Colours::deeppink (0xffff1493);
  64131. const Colour Colours::deepskyblue (0xff00bfff);
  64132. const Colour Colours::dimgrey (0xff696969);
  64133. const Colour Colours::dodgerblue (0xff1e90ff);
  64134. const Colour Colours::firebrick (0xffb22222);
  64135. const Colour Colours::floralwhite (0xfffffaf0);
  64136. const Colour Colours::forestgreen (0xff228b22);
  64137. const Colour Colours::fuchsia (0xffff00ff);
  64138. const Colour Colours::gainsboro (0xffdcdcdc);
  64139. const Colour Colours::gold (0xffffd700);
  64140. const Colour Colours::goldenrod (0xffdaa520);
  64141. const Colour Colours::grey (0xff808080);
  64142. const Colour Colours::green (0xff008000);
  64143. const Colour Colours::greenyellow (0xffadff2f);
  64144. const Colour Colours::honeydew (0xfff0fff0);
  64145. const Colour Colours::hotpink (0xffff69b4);
  64146. const Colour Colours::indianred (0xffcd5c5c);
  64147. const Colour Colours::indigo (0xff4b0082);
  64148. const Colour Colours::ivory (0xfffffff0);
  64149. const Colour Colours::khaki (0xfff0e68c);
  64150. const Colour Colours::lavender (0xffe6e6fa);
  64151. const Colour Colours::lavenderblush (0xfffff0f5);
  64152. const Colour Colours::lemonchiffon (0xfffffacd);
  64153. const Colour Colours::lightblue (0xffadd8e6);
  64154. const Colour Colours::lightcoral (0xfff08080);
  64155. const Colour Colours::lightcyan (0xffe0ffff);
  64156. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  64157. const Colour Colours::lightgreen (0xff90ee90);
  64158. const Colour Colours::lightgrey (0xffd3d3d3);
  64159. const Colour Colours::lightpink (0xffffb6c1);
  64160. const Colour Colours::lightsalmon (0xffffa07a);
  64161. const Colour Colours::lightseagreen (0xff20b2aa);
  64162. const Colour Colours::lightskyblue (0xff87cefa);
  64163. const Colour Colours::lightslategrey (0xff778899);
  64164. const Colour Colours::lightsteelblue (0xffb0c4de);
  64165. const Colour Colours::lightyellow (0xffffffe0);
  64166. const Colour Colours::lime (0xff00ff00);
  64167. const Colour Colours::limegreen (0xff32cd32);
  64168. const Colour Colours::linen (0xfffaf0e6);
  64169. const Colour Colours::magenta (0xffff00ff);
  64170. const Colour Colours::maroon (0xff800000);
  64171. const Colour Colours::mediumaquamarine (0xff66cdaa);
  64172. const Colour Colours::mediumblue (0xff0000cd);
  64173. const Colour Colours::mediumorchid (0xffba55d3);
  64174. const Colour Colours::mediumpurple (0xff9370db);
  64175. const Colour Colours::mediumseagreen (0xff3cb371);
  64176. const Colour Colours::mediumslateblue (0xff7b68ee);
  64177. const Colour Colours::mediumspringgreen (0xff00fa9a);
  64178. const Colour Colours::mediumturquoise (0xff48d1cc);
  64179. const Colour Colours::mediumvioletred (0xffc71585);
  64180. const Colour Colours::midnightblue (0xff191970);
  64181. const Colour Colours::mintcream (0xfff5fffa);
  64182. const Colour Colours::mistyrose (0xffffe4e1);
  64183. const Colour Colours::navajowhite (0xffffdead);
  64184. const Colour Colours::navy (0xff000080);
  64185. const Colour Colours::oldlace (0xfffdf5e6);
  64186. const Colour Colours::olive (0xff808000);
  64187. const Colour Colours::olivedrab (0xff6b8e23);
  64188. const Colour Colours::orange (0xffffa500);
  64189. const Colour Colours::orangered (0xffff4500);
  64190. const Colour Colours::orchid (0xffda70d6);
  64191. const Colour Colours::palegoldenrod (0xffeee8aa);
  64192. const Colour Colours::palegreen (0xff98fb98);
  64193. const Colour Colours::paleturquoise (0xffafeeee);
  64194. const Colour Colours::palevioletred (0xffdb7093);
  64195. const Colour Colours::papayawhip (0xffffefd5);
  64196. const Colour Colours::peachpuff (0xffffdab9);
  64197. const Colour Colours::peru (0xffcd853f);
  64198. const Colour Colours::pink (0xffffc0cb);
  64199. const Colour Colours::plum (0xffdda0dd);
  64200. const Colour Colours::powderblue (0xffb0e0e6);
  64201. const Colour Colours::purple (0xff800080);
  64202. const Colour Colours::red (0xffff0000);
  64203. const Colour Colours::rosybrown (0xffbc8f8f);
  64204. const Colour Colours::royalblue (0xff4169e1);
  64205. const Colour Colours::saddlebrown (0xff8b4513);
  64206. const Colour Colours::salmon (0xfffa8072);
  64207. const Colour Colours::sandybrown (0xfff4a460);
  64208. const Colour Colours::seagreen (0xff2e8b57);
  64209. const Colour Colours::seashell (0xfffff5ee);
  64210. const Colour Colours::sienna (0xffa0522d);
  64211. const Colour Colours::silver (0xffc0c0c0);
  64212. const Colour Colours::skyblue (0xff87ceeb);
  64213. const Colour Colours::slateblue (0xff6a5acd);
  64214. const Colour Colours::slategrey (0xff708090);
  64215. const Colour Colours::snow (0xfffffafa);
  64216. const Colour Colours::springgreen (0xff00ff7f);
  64217. const Colour Colours::steelblue (0xff4682b4);
  64218. const Colour Colours::tan (0xffd2b48c);
  64219. const Colour Colours::teal (0xff008080);
  64220. const Colour Colours::thistle (0xffd8bfd8);
  64221. const Colour Colours::tomato (0xffff6347);
  64222. const Colour Colours::turquoise (0xff40e0d0);
  64223. const Colour Colours::violet (0xffee82ee);
  64224. const Colour Colours::wheat (0xfff5deb3);
  64225. const Colour Colours::white (0xffffffff);
  64226. const Colour Colours::whitesmoke (0xfff5f5f5);
  64227. const Colour Colours::yellow (0xffffff00);
  64228. const Colour Colours::yellowgreen (0xff9acd32);
  64229. const Colour Colours::findColourForName (const String& colourName,
  64230. const Colour& defaultColour)
  64231. {
  64232. static const int presets[] =
  64233. {
  64234. // (first value is the string's hashcode, second is ARGB)
  64235. 0x05978fff, 0xff000000, /* black */
  64236. 0x06bdcc29, 0xffffffff, /* white */
  64237. 0x002e305a, 0xff0000ff, /* blue */
  64238. 0x00308adf, 0xff808080, /* grey */
  64239. 0x05e0cf03, 0xff008000, /* green */
  64240. 0x0001b891, 0xffff0000, /* red */
  64241. 0xd43c6474, 0xffffff00, /* yellow */
  64242. 0x620886da, 0xfff0f8ff, /* aliceblue */
  64243. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  64244. 0x002dcebc, 0xff00ffff, /* aqua */
  64245. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  64246. 0x0590228f, 0xfff0ffff, /* azure */
  64247. 0x05947fe4, 0xfff5f5dc, /* beige */
  64248. 0xad388e35, 0xffffe4c4, /* bisque */
  64249. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  64250. 0x39129959, 0xff8a2be2, /* blueviolet */
  64251. 0x059a8136, 0xffa52a2a, /* brown */
  64252. 0x89cea8f9, 0xffdeb887, /* burlywood */
  64253. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  64254. 0x6b748956, 0xff7fff00, /* chartreuse */
  64255. 0x2903623c, 0xffd2691e, /* chocolate */
  64256. 0x05a74431, 0xffff7f50, /* coral */
  64257. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  64258. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  64259. 0x3d8c4edf, 0xffdc143c, /* crimson */
  64260. 0x002ed323, 0xff00ffff, /* cyan */
  64261. 0x67cc74d0, 0xff00008b, /* darkblue */
  64262. 0x67cd1799, 0xff008b8b, /* darkcyan */
  64263. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  64264. 0x67cecf55, 0xff555555, /* darkgrey */
  64265. 0x920b194d, 0xff006400, /* darkgreen */
  64266. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  64267. 0x5c293873, 0xff8b008b, /* darkmagenta */
  64268. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  64269. 0xbcfd2524, 0xffff8c00, /* darkorange */
  64270. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  64271. 0x55ee0d5b, 0xff8b0000, /* darkred */
  64272. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  64273. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  64274. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  64275. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  64276. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  64277. 0xc8769375, 0xff9400d3, /* darkviolet */
  64278. 0x25832862, 0xffff1493, /* deeppink */
  64279. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  64280. 0x634c8b67, 0xff696969, /* dimgrey */
  64281. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  64282. 0xef19e3cb, 0xffb22222, /* firebrick */
  64283. 0xb852b195, 0xfffffaf0, /* floralwhite */
  64284. 0xd086fd06, 0xff228b22, /* forestgreen */
  64285. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  64286. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  64287. 0x00308060, 0xffffd700, /* gold */
  64288. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  64289. 0xbab8a537, 0xffadff2f, /* greenyellow */
  64290. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  64291. 0x41892743, 0xffff69b4, /* hotpink */
  64292. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  64293. 0xb969fed2, 0xff4b0082, /* indigo */
  64294. 0x05fef6a9, 0xfffffff0, /* ivory */
  64295. 0x06149302, 0xfff0e68c, /* khaki */
  64296. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  64297. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  64298. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  64299. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  64300. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  64301. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  64302. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  64303. 0xf40157ad, 0xff90ee90, /* lightgreen */
  64304. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  64305. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  64306. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  64307. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  64308. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  64309. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  64310. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  64311. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  64312. 0x0032afd5, 0xff00ff00, /* lime */
  64313. 0x607bbc4e, 0xff32cd32, /* limegreen */
  64314. 0x06234efa, 0xfffaf0e6, /* linen */
  64315. 0x316858a9, 0xffff00ff, /* magenta */
  64316. 0xbf8ca470, 0xff800000, /* maroon */
  64317. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  64318. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  64319. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  64320. 0x07556b71, 0xff9370db, /* mediumpurple */
  64321. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  64322. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  64323. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  64324. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  64325. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  64326. 0x168eb32a, 0xff191970, /* midnightblue */
  64327. 0x4306b960, 0xfff5fffa, /* mintcream */
  64328. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  64329. 0xe97218a6, 0xffffdead, /* navajowhite */
  64330. 0x00337bb6, 0xff000080, /* navy */
  64331. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  64332. 0x064ee1db, 0xff808000, /* olive */
  64333. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  64334. 0xc3de262e, 0xffffa500, /* orange */
  64335. 0x58bebba3, 0xffff4500, /* orangered */
  64336. 0xc3def8a3, 0xffda70d6, /* orchid */
  64337. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  64338. 0x3d9dd619, 0xff98fb98, /* palegreen */
  64339. 0x74022737, 0xffafeeee, /* paleturquoise */
  64340. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  64341. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  64342. 0x93e1b776, 0xffffdab9, /* peachpuff */
  64343. 0x003472f8, 0xffcd853f, /* peru */
  64344. 0x00348176, 0xffffc0cb, /* pink */
  64345. 0x00348d94, 0xffdda0dd, /* plum */
  64346. 0xd036be93, 0xffb0e0e6, /* powderblue */
  64347. 0xc5c507bc, 0xff800080, /* purple */
  64348. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  64349. 0xbd9413e1, 0xff4169e1, /* royalblue */
  64350. 0xf456044f, 0xff8b4513, /* saddlebrown */
  64351. 0xc9c6f66e, 0xfffa8072, /* salmon */
  64352. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  64353. 0x34636c14, 0xff2e8b57, /* seagreen */
  64354. 0x3507fb41, 0xfffff5ee, /* seashell */
  64355. 0xca348772, 0xffa0522d, /* sienna */
  64356. 0xca37d30d, 0xffc0c0c0, /* silver */
  64357. 0x80da74fb, 0xff87ceeb, /* skyblue */
  64358. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  64359. 0x44ab37f8, 0xff708090, /* slategrey */
  64360. 0x0035f183, 0xfffffafa, /* snow */
  64361. 0xd5440d16, 0xff00ff7f, /* springgreen */
  64362. 0x3e1524a5, 0xff4682b4, /* steelblue */
  64363. 0x0001bfa1, 0xffd2b48c, /* tan */
  64364. 0x0036425c, 0xff008080, /* teal */
  64365. 0xafc8858f, 0xffd8bfd8, /* thistle */
  64366. 0xcc41600a, 0xffff6347, /* tomato */
  64367. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  64368. 0xcf57947f, 0xffee82ee, /* violet */
  64369. 0x06bdbae7, 0xfff5deb3, /* wheat */
  64370. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  64371. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  64372. };
  64373. const int hash = colourName.trim().toLowerCase().hashCode();
  64374. for (int i = 0; i < numElementsInArray (presets); i += 2)
  64375. if (presets [i] == hash)
  64376. return Colour (presets [i + 1]);
  64377. return defaultColour;
  64378. }
  64379. END_JUCE_NAMESPACE
  64380. /*** End of inlined file: juce_Colours.cpp ***/
  64381. /*** Start of inlined file: juce_EdgeTable.cpp ***/
  64382. BEGIN_JUCE_NAMESPACE
  64383. const int juce_edgeTableDefaultEdgesPerLine = 32;
  64384. EdgeTable::EdgeTable (const Rectangle<int>& bounds_,
  64385. const Path& path, const AffineTransform& transform)
  64386. : bounds (bounds_),
  64387. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  64388. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  64389. needToCheckEmptinesss (true)
  64390. {
  64391. table.malloc ((bounds.getHeight() + 1) * lineStrideElements);
  64392. int* t = table;
  64393. for (int i = bounds.getHeight(); --i >= 0;)
  64394. {
  64395. *t = 0;
  64396. t += lineStrideElements;
  64397. }
  64398. const int topLimit = bounds.getY() << 8;
  64399. const int heightLimit = bounds.getHeight() << 8;
  64400. const int leftLimit = bounds.getX() << 8;
  64401. const int rightLimit = bounds.getRight() << 8;
  64402. PathFlatteningIterator iter (path, transform);
  64403. while (iter.next())
  64404. {
  64405. int y1 = roundToInt (iter.y1 * 256.0f);
  64406. int y2 = roundToInt (iter.y2 * 256.0f);
  64407. if (y1 != y2)
  64408. {
  64409. y1 -= topLimit;
  64410. y2 -= topLimit;
  64411. const int startY = y1;
  64412. int direction = -1;
  64413. if (y1 > y2)
  64414. {
  64415. swapVariables (y1, y2);
  64416. direction = 1;
  64417. }
  64418. if (y1 < 0)
  64419. y1 = 0;
  64420. if (y2 > heightLimit)
  64421. y2 = heightLimit;
  64422. if (y1 < y2)
  64423. {
  64424. const double startX = 256.0f * iter.x1;
  64425. const double multiplier = (iter.x2 - iter.x1) / (iter.y2 - iter.y1);
  64426. const int stepSize = jlimit (1, 256, 256 / (1 + (int) std::abs (multiplier)));
  64427. do
  64428. {
  64429. const int step = jmin (stepSize, y2 - y1, 256 - (y1 & 255));
  64430. int x = roundToInt (startX + multiplier * ((y1 + (step >> 1)) - startY));
  64431. if (x < leftLimit)
  64432. x = leftLimit;
  64433. else if (x >= rightLimit)
  64434. x = rightLimit - 1;
  64435. addEdgePoint (x, y1 >> 8, direction * step);
  64436. y1 += step;
  64437. }
  64438. while (y1 < y2);
  64439. }
  64440. }
  64441. }
  64442. sanitiseLevels (path.isUsingNonZeroWinding());
  64443. }
  64444. EdgeTable::EdgeTable (const Rectangle<int>& rectangleToAdd)
  64445. : bounds (rectangleToAdd),
  64446. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  64447. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  64448. needToCheckEmptinesss (true)
  64449. {
  64450. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  64451. table[0] = 0;
  64452. const int x1 = rectangleToAdd.getX() << 8;
  64453. const int x2 = rectangleToAdd.getRight() << 8;
  64454. int* t = table;
  64455. for (int i = rectangleToAdd.getHeight(); --i >= 0;)
  64456. {
  64457. t[0] = 2;
  64458. t[1] = x1;
  64459. t[2] = 255;
  64460. t[3] = x2;
  64461. t[4] = 0;
  64462. t += lineStrideElements;
  64463. }
  64464. }
  64465. EdgeTable::EdgeTable (const RectangleList& rectanglesToAdd)
  64466. : bounds (rectanglesToAdd.getBounds()),
  64467. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  64468. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  64469. needToCheckEmptinesss (true)
  64470. {
  64471. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  64472. int* t = table;
  64473. for (int i = bounds.getHeight(); --i >= 0;)
  64474. {
  64475. *t = 0;
  64476. t += lineStrideElements;
  64477. }
  64478. for (RectangleList::Iterator iter (rectanglesToAdd); iter.next();)
  64479. {
  64480. const Rectangle<int>* const r = iter.getRectangle();
  64481. const int x1 = r->getX() << 8;
  64482. const int x2 = r->getRight() << 8;
  64483. int y = r->getY() - bounds.getY();
  64484. for (int j = r->getHeight(); --j >= 0;)
  64485. {
  64486. addEdgePoint (x1, y, 255);
  64487. addEdgePoint (x2, y, -255);
  64488. ++y;
  64489. }
  64490. }
  64491. sanitiseLevels (true);
  64492. }
  64493. EdgeTable::EdgeTable (const Rectangle<float>& rectangleToAdd)
  64494. : bounds (Rectangle<int> ((int) std::floor (rectangleToAdd.getX()),
  64495. roundToInt (rectangleToAdd.getY() * 256.0f) >> 8,
  64496. 2 + (int) rectangleToAdd.getWidth(),
  64497. 2 + (int) rectangleToAdd.getHeight())),
  64498. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  64499. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  64500. needToCheckEmptinesss (true)
  64501. {
  64502. jassert (! rectangleToAdd.isEmpty());
  64503. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  64504. table[0] = 0;
  64505. const int x1 = roundToInt (rectangleToAdd.getX() * 256.0f);
  64506. const int x2 = roundToInt (rectangleToAdd.getRight() * 256.0f);
  64507. int y1 = roundToInt (rectangleToAdd.getY() * 256.0f) - (bounds.getY() << 8);
  64508. jassert (y1 < 256);
  64509. int y2 = roundToInt (rectangleToAdd.getBottom() * 256.0f) - (bounds.getY() << 8);
  64510. if (x2 <= x1 || y2 <= y1)
  64511. {
  64512. bounds.setHeight (0);
  64513. return;
  64514. }
  64515. int lineY = 0;
  64516. int* t = table;
  64517. if ((y1 >> 8) == (y2 >> 8))
  64518. {
  64519. t[0] = 2;
  64520. t[1] = x1;
  64521. t[2] = y2 - y1;
  64522. t[3] = x2;
  64523. t[4] = 0;
  64524. ++lineY;
  64525. t += lineStrideElements;
  64526. }
  64527. else
  64528. {
  64529. t[0] = 2;
  64530. t[1] = x1;
  64531. t[2] = 255 - (y1 & 255);
  64532. t[3] = x2;
  64533. t[4] = 0;
  64534. ++lineY;
  64535. t += lineStrideElements;
  64536. while (lineY < (y2 >> 8))
  64537. {
  64538. t[0] = 2;
  64539. t[1] = x1;
  64540. t[2] = 255;
  64541. t[3] = x2;
  64542. t[4] = 0;
  64543. ++lineY;
  64544. t += lineStrideElements;
  64545. }
  64546. jassert (lineY < bounds.getHeight());
  64547. t[0] = 2;
  64548. t[1] = x1;
  64549. t[2] = y2 & 255;
  64550. t[3] = x2;
  64551. t[4] = 0;
  64552. ++lineY;
  64553. t += lineStrideElements;
  64554. }
  64555. while (lineY < bounds.getHeight())
  64556. {
  64557. t[0] = 0;
  64558. t += lineStrideElements;
  64559. ++lineY;
  64560. }
  64561. }
  64562. EdgeTable::EdgeTable (const EdgeTable& other)
  64563. {
  64564. operator= (other);
  64565. }
  64566. EdgeTable& EdgeTable::operator= (const EdgeTable& other)
  64567. {
  64568. bounds = other.bounds;
  64569. maxEdgesPerLine = other.maxEdgesPerLine;
  64570. lineStrideElements = other.lineStrideElements;
  64571. needToCheckEmptinesss = other.needToCheckEmptinesss;
  64572. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  64573. copyEdgeTableData (table, lineStrideElements, other.table, lineStrideElements, bounds.getHeight());
  64574. return *this;
  64575. }
  64576. EdgeTable::~EdgeTable()
  64577. {
  64578. }
  64579. void EdgeTable::copyEdgeTableData (int* dest, const int destLineStride, const int* src, const int srcLineStride, int numLines) throw()
  64580. {
  64581. while (--numLines >= 0)
  64582. {
  64583. memcpy (dest, src, (src[0] * 2 + 1) * sizeof (int));
  64584. src += srcLineStride;
  64585. dest += destLineStride;
  64586. }
  64587. }
  64588. void EdgeTable::sanitiseLevels (const bool useNonZeroWinding) throw()
  64589. {
  64590. // Convert the table from relative windings to absolute levels..
  64591. int* lineStart = table;
  64592. for (int i = bounds.getHeight(); --i >= 0;)
  64593. {
  64594. int* line = lineStart;
  64595. lineStart += lineStrideElements;
  64596. int num = *line;
  64597. if (num == 0)
  64598. continue;
  64599. int level = 0;
  64600. if (useNonZeroWinding)
  64601. {
  64602. while (--num > 0)
  64603. {
  64604. line += 2;
  64605. level += *line;
  64606. int corrected = abs (level);
  64607. if (corrected >> 8)
  64608. corrected = 255;
  64609. *line = corrected;
  64610. }
  64611. }
  64612. else
  64613. {
  64614. while (--num > 0)
  64615. {
  64616. line += 2;
  64617. level += *line;
  64618. int corrected = abs (level);
  64619. if (corrected >> 8)
  64620. {
  64621. corrected &= 511;
  64622. if (corrected >> 8)
  64623. corrected = 511 - corrected;
  64624. }
  64625. *line = corrected;
  64626. }
  64627. }
  64628. line[2] = 0; // force the last level to 0, just in case something went wrong in creating the table
  64629. }
  64630. }
  64631. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine) throw()
  64632. {
  64633. if (newNumEdgesPerLine != maxEdgesPerLine)
  64634. {
  64635. maxEdgesPerLine = newNumEdgesPerLine;
  64636. jassert (bounds.getHeight() > 0);
  64637. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  64638. HeapBlock <int> newTable (bounds.getHeight() * newLineStrideElements);
  64639. copyEdgeTableData (newTable, newLineStrideElements, table, lineStrideElements, bounds.getHeight());
  64640. table.swapWith (newTable);
  64641. lineStrideElements = newLineStrideElements;
  64642. }
  64643. }
  64644. void EdgeTable::optimiseTable() throw()
  64645. {
  64646. int maxLineElements = 0;
  64647. for (int i = bounds.getHeight(); --i >= 0;)
  64648. maxLineElements = jmax (maxLineElements, table [i * lineStrideElements]);
  64649. remapTableForNumEdges (maxLineElements);
  64650. }
  64651. void EdgeTable::addEdgePoint (const int x, const int y, const int winding) throw()
  64652. {
  64653. jassert (y >= 0 && y < bounds.getHeight());
  64654. int* line = table + lineStrideElements * y;
  64655. const int numPoints = line[0];
  64656. int n = numPoints << 1;
  64657. if (n > 0)
  64658. {
  64659. while (n > 0)
  64660. {
  64661. const int cx = line [n - 1];
  64662. if (cx <= x)
  64663. {
  64664. if (cx == x)
  64665. {
  64666. line [n] += winding;
  64667. return;
  64668. }
  64669. break;
  64670. }
  64671. n -= 2;
  64672. }
  64673. if (numPoints >= maxEdgesPerLine)
  64674. {
  64675. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  64676. jassert (numPoints < maxEdgesPerLine);
  64677. line = table + lineStrideElements * y;
  64678. }
  64679. memmove (line + (n + 3), line + (n + 1), sizeof (int) * ((numPoints << 1) - n));
  64680. }
  64681. line [n + 1] = x;
  64682. line [n + 2] = winding;
  64683. line[0]++;
  64684. }
  64685. void EdgeTable::translate (float dx, const int dy) throw()
  64686. {
  64687. bounds.translate ((int) std::floor (dx), dy);
  64688. int* lineStart = table;
  64689. const int intDx = (int) (dx * 256.0f);
  64690. for (int i = bounds.getHeight(); --i >= 0;)
  64691. {
  64692. int* line = lineStart;
  64693. lineStart += lineStrideElements;
  64694. int num = *line++;
  64695. while (--num >= 0)
  64696. {
  64697. *line += intDx;
  64698. line += 2;
  64699. }
  64700. }
  64701. }
  64702. void EdgeTable::intersectWithEdgeTableLine (const int y, const int* otherLine) throw()
  64703. {
  64704. jassert (y >= 0 && y < bounds.getHeight());
  64705. int* dest = table + lineStrideElements * y;
  64706. if (dest[0] == 0)
  64707. return;
  64708. int otherNumPoints = *otherLine;
  64709. if (otherNumPoints == 0)
  64710. {
  64711. *dest = 0;
  64712. return;
  64713. }
  64714. const int right = bounds.getRight() << 8;
  64715. // optimise for the common case where our line lies entirely within a
  64716. // single pair of points, as happens when clipping to a simple rect.
  64717. if (otherNumPoints == 2 && otherLine[2] >= 255)
  64718. {
  64719. clipEdgeTableLineToRange (dest, otherLine[1], jmin (right, otherLine[3]));
  64720. return;
  64721. }
  64722. ++otherLine;
  64723. const size_t lineSizeBytes = (dest[0] * 2 + 1) * sizeof (int);
  64724. int* temp = (int*) alloca (lineSizeBytes);
  64725. memcpy (temp, dest, lineSizeBytes);
  64726. const int* src1 = temp;
  64727. int srcNum1 = *src1++;
  64728. int x1 = *src1++;
  64729. const int* src2 = otherLine;
  64730. int srcNum2 = otherNumPoints;
  64731. int x2 = *src2++;
  64732. int destIndex = 0, destTotal = 0;
  64733. int level1 = 0, level2 = 0;
  64734. int lastX = std::numeric_limits<int>::min(), lastLevel = 0;
  64735. while (srcNum1 > 0 && srcNum2 > 0)
  64736. {
  64737. int nextX;
  64738. if (x1 < x2)
  64739. {
  64740. nextX = x1;
  64741. level1 = *src1++;
  64742. x1 = *src1++;
  64743. --srcNum1;
  64744. }
  64745. else if (x1 == x2)
  64746. {
  64747. nextX = x1;
  64748. level1 = *src1++;
  64749. level2 = *src2++;
  64750. x1 = *src1++;
  64751. x2 = *src2++;
  64752. --srcNum1;
  64753. --srcNum2;
  64754. }
  64755. else
  64756. {
  64757. nextX = x2;
  64758. level2 = *src2++;
  64759. x2 = *src2++;
  64760. --srcNum2;
  64761. }
  64762. if (nextX > lastX)
  64763. {
  64764. if (nextX >= right)
  64765. break;
  64766. lastX = nextX;
  64767. const int nextLevel = (level1 * (level2 + 1)) >> 8;
  64768. jassert (((unsigned int) nextLevel) < (unsigned int) 256);
  64769. if (nextLevel != lastLevel)
  64770. {
  64771. if (destTotal >= maxEdgesPerLine)
  64772. {
  64773. dest[0] = destTotal;
  64774. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  64775. dest = table + lineStrideElements * y;
  64776. }
  64777. ++destTotal;
  64778. lastLevel = nextLevel;
  64779. dest[++destIndex] = nextX;
  64780. dest[++destIndex] = nextLevel;
  64781. }
  64782. }
  64783. }
  64784. if (lastLevel > 0)
  64785. {
  64786. if (destTotal >= maxEdgesPerLine)
  64787. {
  64788. dest[0] = destTotal;
  64789. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  64790. dest = table + lineStrideElements * y;
  64791. }
  64792. ++destTotal;
  64793. dest[++destIndex] = right;
  64794. dest[++destIndex] = 0;
  64795. }
  64796. dest[0] = destTotal;
  64797. #if JUCE_DEBUG
  64798. int last = std::numeric_limits<int>::min();
  64799. for (int i = 0; i < dest[0]; ++i)
  64800. {
  64801. jassert (dest[i * 2 + 1] > last);
  64802. last = dest[i * 2 + 1];
  64803. }
  64804. jassert (dest [dest[0] * 2] == 0);
  64805. #endif
  64806. }
  64807. void EdgeTable::clipEdgeTableLineToRange (int* dest, const int x1, const int x2) throw()
  64808. {
  64809. int* lastItem = dest + (dest[0] * 2 - 1);
  64810. if (x2 < lastItem[0])
  64811. {
  64812. if (x2 <= dest[1])
  64813. {
  64814. dest[0] = 0;
  64815. return;
  64816. }
  64817. while (x2 < lastItem[-2])
  64818. {
  64819. --(dest[0]);
  64820. lastItem -= 2;
  64821. }
  64822. lastItem[0] = x2;
  64823. lastItem[1] = 0;
  64824. }
  64825. if (x1 > dest[1])
  64826. {
  64827. while (lastItem[0] > x1)
  64828. lastItem -= 2;
  64829. const int itemsRemoved = (int) (lastItem - (dest + 1)) / 2;
  64830. if (itemsRemoved > 0)
  64831. {
  64832. dest[0] -= itemsRemoved;
  64833. memmove (dest + 1, lastItem, dest[0] * (sizeof (int) * 2));
  64834. }
  64835. dest[1] = x1;
  64836. }
  64837. }
  64838. void EdgeTable::clipToRectangle (const Rectangle<int>& r) throw()
  64839. {
  64840. const Rectangle<int> clipped (r.getIntersection (bounds));
  64841. if (clipped.isEmpty())
  64842. {
  64843. needToCheckEmptinesss = false;
  64844. bounds.setHeight (0);
  64845. }
  64846. else
  64847. {
  64848. const int top = clipped.getY() - bounds.getY();
  64849. const int bottom = clipped.getBottom() - bounds.getY();
  64850. if (bottom < bounds.getHeight())
  64851. bounds.setHeight (bottom);
  64852. if (clipped.getRight() < bounds.getRight())
  64853. bounds.setRight (clipped.getRight());
  64854. for (int i = top; --i >= 0;)
  64855. table [lineStrideElements * i] = 0;
  64856. if (clipped.getX() > bounds.getX())
  64857. {
  64858. const int x1 = clipped.getX() << 8;
  64859. const int x2 = jmin (bounds.getRight(), clipped.getRight()) << 8;
  64860. int* line = table + lineStrideElements * top;
  64861. for (int i = bottom - top; --i >= 0;)
  64862. {
  64863. if (line[0] != 0)
  64864. clipEdgeTableLineToRange (line, x1, x2);
  64865. line += lineStrideElements;
  64866. }
  64867. }
  64868. needToCheckEmptinesss = true;
  64869. }
  64870. }
  64871. void EdgeTable::excludeRectangle (const Rectangle<int>& r) throw()
  64872. {
  64873. const Rectangle<int> clipped (r.getIntersection (bounds));
  64874. if (! clipped.isEmpty())
  64875. {
  64876. const int top = clipped.getY() - bounds.getY();
  64877. const int bottom = clipped.getBottom() - bounds.getY();
  64878. //XXX optimise here by shortening the table if it fills top or bottom
  64879. const int rectLine[] = { 4, std::numeric_limits<int>::min(), 255,
  64880. clipped.getX() << 8, 0,
  64881. clipped.getRight() << 8, 255,
  64882. std::numeric_limits<int>::max(), 0 };
  64883. for (int i = top; i < bottom; ++i)
  64884. intersectWithEdgeTableLine (i, rectLine);
  64885. needToCheckEmptinesss = true;
  64886. }
  64887. }
  64888. void EdgeTable::clipToEdgeTable (const EdgeTable& other)
  64889. {
  64890. const Rectangle<int> clipped (other.bounds.getIntersection (bounds));
  64891. if (clipped.isEmpty())
  64892. {
  64893. needToCheckEmptinesss = false;
  64894. bounds.setHeight (0);
  64895. }
  64896. else
  64897. {
  64898. const int top = clipped.getY() - bounds.getY();
  64899. const int bottom = clipped.getBottom() - bounds.getY();
  64900. if (bottom < bounds.getHeight())
  64901. bounds.setHeight (bottom);
  64902. if (clipped.getRight() < bounds.getRight())
  64903. bounds.setRight (clipped.getRight());
  64904. int i = 0;
  64905. for (i = top; --i >= 0;)
  64906. table [lineStrideElements * i] = 0;
  64907. const int* otherLine = other.table + other.lineStrideElements * (clipped.getY() - other.bounds.getY());
  64908. for (i = top; i < bottom; ++i)
  64909. {
  64910. intersectWithEdgeTableLine (i, otherLine);
  64911. otherLine += other.lineStrideElements;
  64912. }
  64913. needToCheckEmptinesss = true;
  64914. }
  64915. }
  64916. void EdgeTable::clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels) throw()
  64917. {
  64918. y -= bounds.getY();
  64919. if (y < 0 || y >= bounds.getHeight())
  64920. return;
  64921. needToCheckEmptinesss = true;
  64922. if (numPixels <= 0)
  64923. {
  64924. table [lineStrideElements * y] = 0;
  64925. return;
  64926. }
  64927. int* tempLine = (int*) alloca ((numPixels * 2 + 4) * sizeof (int));
  64928. int destIndex = 0, lastLevel = 0;
  64929. while (--numPixels >= 0)
  64930. {
  64931. const int alpha = *mask;
  64932. mask += maskStride;
  64933. if (alpha != lastLevel)
  64934. {
  64935. tempLine[++destIndex] = (x << 8);
  64936. tempLine[++destIndex] = alpha;
  64937. lastLevel = alpha;
  64938. }
  64939. ++x;
  64940. }
  64941. if (lastLevel > 0)
  64942. {
  64943. tempLine[++destIndex] = (x << 8);
  64944. tempLine[++destIndex] = 0;
  64945. }
  64946. tempLine[0] = destIndex >> 1;
  64947. intersectWithEdgeTableLine (y, tempLine);
  64948. }
  64949. bool EdgeTable::isEmpty() throw()
  64950. {
  64951. if (needToCheckEmptinesss)
  64952. {
  64953. needToCheckEmptinesss = false;
  64954. int* t = table;
  64955. for (int i = bounds.getHeight(); --i >= 0;)
  64956. {
  64957. if (t[0] > 1)
  64958. return false;
  64959. t += lineStrideElements;
  64960. }
  64961. bounds.setHeight (0);
  64962. }
  64963. return bounds.getHeight() == 0;
  64964. }
  64965. END_JUCE_NAMESPACE
  64966. /*** End of inlined file: juce_EdgeTable.cpp ***/
  64967. /*** Start of inlined file: juce_FillType.cpp ***/
  64968. BEGIN_JUCE_NAMESPACE
  64969. FillType::FillType() throw()
  64970. : colour (0xff000000), image (0)
  64971. {
  64972. }
  64973. FillType::FillType (const Colour& colour_) throw()
  64974. : colour (colour_), image (0)
  64975. {
  64976. }
  64977. FillType::FillType (const ColourGradient& gradient_)
  64978. : colour (0xff000000), gradient (new ColourGradient (gradient_)), image (0)
  64979. {
  64980. }
  64981. FillType::FillType (const Image& image_, const AffineTransform& transform_) throw()
  64982. : colour (0xff000000), image (image_), transform (transform_)
  64983. {
  64984. }
  64985. FillType::FillType (const FillType& other)
  64986. : colour (other.colour),
  64987. gradient (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0),
  64988. image (other.image), transform (other.transform)
  64989. {
  64990. }
  64991. FillType& FillType::operator= (const FillType& other)
  64992. {
  64993. if (this != &other)
  64994. {
  64995. colour = other.colour;
  64996. gradient = (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0);
  64997. image = other.image;
  64998. transform = other.transform;
  64999. }
  65000. return *this;
  65001. }
  65002. FillType::~FillType() throw()
  65003. {
  65004. }
  65005. bool FillType::operator== (const FillType& other) const
  65006. {
  65007. return colour == other.colour && image == other.image
  65008. && (gradient == other.gradient
  65009. || (gradient != 0 && other.gradient != 0 && *gradient == *other.gradient));
  65010. }
  65011. bool FillType::operator!= (const FillType& other) const
  65012. {
  65013. return ! operator== (other);
  65014. }
  65015. void FillType::setColour (const Colour& newColour) throw()
  65016. {
  65017. gradient = 0;
  65018. image = Image();
  65019. colour = newColour;
  65020. }
  65021. void FillType::setGradient (const ColourGradient& newGradient)
  65022. {
  65023. if (gradient != 0)
  65024. {
  65025. *gradient = newGradient;
  65026. }
  65027. else
  65028. {
  65029. image = Image();
  65030. gradient = new ColourGradient (newGradient);
  65031. colour = Colours::black;
  65032. }
  65033. }
  65034. void FillType::setTiledImage (const Image& image_, const AffineTransform& transform_) throw()
  65035. {
  65036. gradient = 0;
  65037. image = image_;
  65038. transform = transform_;
  65039. colour = Colours::black;
  65040. }
  65041. void FillType::setOpacity (const float newOpacity) throw()
  65042. {
  65043. colour = colour.withAlpha (newOpacity);
  65044. }
  65045. bool FillType::isInvisible() const throw()
  65046. {
  65047. return colour.isTransparent() || (gradient != 0 && gradient->isInvisible());
  65048. }
  65049. END_JUCE_NAMESPACE
  65050. /*** End of inlined file: juce_FillType.cpp ***/
  65051. /*** Start of inlined file: juce_Graphics.cpp ***/
  65052. BEGIN_JUCE_NAMESPACE
  65053. template <typename Type>
  65054. static bool areCoordsSensibleNumbers (Type x, Type y, Type w, Type h)
  65055. {
  65056. const int maxVal = 0x3fffffff;
  65057. return (int) x >= -maxVal && (int) x <= maxVal
  65058. && (int) y >= -maxVal && (int) y <= maxVal
  65059. && (int) w >= -maxVal && (int) w <= maxVal
  65060. && (int) h >= -maxVal && (int) h <= maxVal;
  65061. }
  65062. LowLevelGraphicsContext::LowLevelGraphicsContext()
  65063. {
  65064. }
  65065. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  65066. {
  65067. }
  65068. Graphics::Graphics (const Image& imageToDrawOnto)
  65069. : context (imageToDrawOnto.createLowLevelContext()),
  65070. contextToDelete (context),
  65071. saveStatePending (false)
  65072. {
  65073. }
  65074. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  65075. : context (internalContext),
  65076. saveStatePending (false)
  65077. {
  65078. }
  65079. Graphics::~Graphics()
  65080. {
  65081. }
  65082. void Graphics::resetToDefaultState()
  65083. {
  65084. saveStateIfPending();
  65085. context->setFill (FillType());
  65086. context->setFont (Font());
  65087. context->setInterpolationQuality (Graphics::mediumResamplingQuality);
  65088. }
  65089. bool Graphics::isVectorDevice() const
  65090. {
  65091. return context->isVectorDevice();
  65092. }
  65093. bool Graphics::reduceClipRegion (const int x, const int y, const int w, const int h)
  65094. {
  65095. saveStateIfPending();
  65096. return context->clipToRectangle (Rectangle<int> (x, y, w, h));
  65097. }
  65098. bool Graphics::reduceClipRegion (const RectangleList& clipRegion)
  65099. {
  65100. saveStateIfPending();
  65101. return context->clipToRectangleList (clipRegion);
  65102. }
  65103. bool Graphics::reduceClipRegion (const Path& path, const AffineTransform& transform)
  65104. {
  65105. saveStateIfPending();
  65106. context->clipToPath (path, transform);
  65107. return ! context->isClipEmpty();
  65108. }
  65109. bool Graphics::reduceClipRegion (const Image& image, const Rectangle<int>& sourceClipRegion, const AffineTransform& transform)
  65110. {
  65111. saveStateIfPending();
  65112. context->clipToImageAlpha (image, sourceClipRegion, transform);
  65113. return ! context->isClipEmpty();
  65114. }
  65115. void Graphics::excludeClipRegion (const Rectangle<int>& rectangleToExclude)
  65116. {
  65117. saveStateIfPending();
  65118. context->excludeClipRectangle (rectangleToExclude);
  65119. }
  65120. bool Graphics::isClipEmpty() const
  65121. {
  65122. return context->isClipEmpty();
  65123. }
  65124. const Rectangle<int> Graphics::getClipBounds() const
  65125. {
  65126. return context->getClipBounds();
  65127. }
  65128. void Graphics::saveState()
  65129. {
  65130. saveStateIfPending();
  65131. saveStatePending = true;
  65132. }
  65133. void Graphics::restoreState()
  65134. {
  65135. if (saveStatePending)
  65136. saveStatePending = false;
  65137. else
  65138. context->restoreState();
  65139. }
  65140. void Graphics::saveStateIfPending()
  65141. {
  65142. if (saveStatePending)
  65143. {
  65144. saveStatePending = false;
  65145. context->saveState();
  65146. }
  65147. }
  65148. void Graphics::setOrigin (const int newOriginX, const int newOriginY)
  65149. {
  65150. saveStateIfPending();
  65151. context->setOrigin (newOriginX, newOriginY);
  65152. }
  65153. bool Graphics::clipRegionIntersects (const Rectangle<int>& area) const
  65154. {
  65155. return context->clipRegionIntersects (area);
  65156. }
  65157. void Graphics::setColour (const Colour& newColour)
  65158. {
  65159. saveStateIfPending();
  65160. context->setFill (newColour);
  65161. }
  65162. void Graphics::setOpacity (const float newOpacity)
  65163. {
  65164. saveStateIfPending();
  65165. context->setOpacity (newOpacity);
  65166. }
  65167. void Graphics::setGradientFill (const ColourGradient& gradient)
  65168. {
  65169. setFillType (gradient);
  65170. }
  65171. void Graphics::setTiledImageFill (const Image& imageToUse, const int anchorX, const int anchorY, const float opacity)
  65172. {
  65173. saveStateIfPending();
  65174. context->setFill (FillType (imageToUse, AffineTransform::translation ((float) anchorX, (float) anchorY)));
  65175. context->setOpacity (opacity);
  65176. }
  65177. void Graphics::setFillType (const FillType& newFill)
  65178. {
  65179. saveStateIfPending();
  65180. context->setFill (newFill);
  65181. }
  65182. void Graphics::setFont (const Font& newFont)
  65183. {
  65184. saveStateIfPending();
  65185. context->setFont (newFont);
  65186. }
  65187. void Graphics::setFont (const float newFontHeight, const int newFontStyleFlags)
  65188. {
  65189. saveStateIfPending();
  65190. Font f (context->getFont());
  65191. f.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0);
  65192. context->setFont (f);
  65193. }
  65194. const Font Graphics::getCurrentFont() const
  65195. {
  65196. return context->getFont();
  65197. }
  65198. void Graphics::drawSingleLineText (const String& text, const int startX, const int baselineY) const
  65199. {
  65200. if (text.isNotEmpty()
  65201. && startX < context->getClipBounds().getRight())
  65202. {
  65203. GlyphArrangement arr;
  65204. arr.addLineOfText (context->getFont(), text, (float) startX, (float) baselineY);
  65205. arr.draw (*this);
  65206. }
  65207. }
  65208. void Graphics::drawTextAsPath (const String& text, const AffineTransform& transform) const
  65209. {
  65210. if (text.isNotEmpty())
  65211. {
  65212. GlyphArrangement arr;
  65213. arr.addLineOfText (context->getFont(), text, 0.0f, 0.0f);
  65214. arr.draw (*this, transform);
  65215. }
  65216. }
  65217. void Graphics::drawMultiLineText (const String& text, const int startX, const int baselineY, const int maximumLineWidth) const
  65218. {
  65219. if (text.isNotEmpty()
  65220. && startX < context->getClipBounds().getRight())
  65221. {
  65222. GlyphArrangement arr;
  65223. arr.addJustifiedText (context->getFont(), text,
  65224. (float) startX, (float) baselineY, (float) maximumLineWidth,
  65225. Justification::left);
  65226. arr.draw (*this);
  65227. }
  65228. }
  65229. void Graphics::drawText (const String& text,
  65230. const int x, const int y, const int width, const int height,
  65231. const Justification& justificationType,
  65232. const bool useEllipsesIfTooBig) const
  65233. {
  65234. if (text.isNotEmpty() && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  65235. {
  65236. GlyphArrangement arr;
  65237. arr.addCurtailedLineOfText (context->getFont(), text,
  65238. 0.0f, 0.0f, (float) width,
  65239. useEllipsesIfTooBig);
  65240. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  65241. (float) x, (float) y, (float) width, (float) height,
  65242. justificationType);
  65243. arr.draw (*this);
  65244. }
  65245. }
  65246. void Graphics::drawFittedText (const String& text,
  65247. const int x, const int y, const int width, const int height,
  65248. const Justification& justification,
  65249. const int maximumNumberOfLines,
  65250. const float minimumHorizontalScale) const
  65251. {
  65252. if (text.isNotEmpty()
  65253. && width > 0 && height > 0
  65254. && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  65255. {
  65256. GlyphArrangement arr;
  65257. arr.addFittedText (context->getFont(), text,
  65258. (float) x, (float) y, (float) width, (float) height,
  65259. justification,
  65260. maximumNumberOfLines,
  65261. minimumHorizontalScale);
  65262. arr.draw (*this);
  65263. }
  65264. }
  65265. void Graphics::fillRect (int x, int y, int width, int height) const
  65266. {
  65267. // passing in a silly number can cause maths problems in rendering!
  65268. jassert (areCoordsSensibleNumbers (x, y, width, height));
  65269. context->fillRect (Rectangle<int> (x, y, width, height), false);
  65270. }
  65271. void Graphics::fillRect (const Rectangle<int>& r) const
  65272. {
  65273. context->fillRect (r, false);
  65274. }
  65275. void Graphics::fillRect (const float x, const float y, const float width, const float height) const
  65276. {
  65277. // passing in a silly number can cause maths problems in rendering!
  65278. jassert (areCoordsSensibleNumbers (x, y, width, height));
  65279. Path p;
  65280. p.addRectangle (x, y, width, height);
  65281. fillPath (p);
  65282. }
  65283. void Graphics::setPixel (int x, int y) const
  65284. {
  65285. context->fillRect (Rectangle<int> (x, y, 1, 1), false);
  65286. }
  65287. void Graphics::fillAll() const
  65288. {
  65289. fillRect (context->getClipBounds());
  65290. }
  65291. void Graphics::fillAll (const Colour& colourToUse) const
  65292. {
  65293. if (! colourToUse.isTransparent())
  65294. {
  65295. const Rectangle<int> clip (context->getClipBounds());
  65296. context->saveState();
  65297. context->setFill (colourToUse);
  65298. context->fillRect (clip, false);
  65299. context->restoreState();
  65300. }
  65301. }
  65302. void Graphics::fillPath (const Path& path, const AffineTransform& transform) const
  65303. {
  65304. if ((! context->isClipEmpty()) && ! path.isEmpty())
  65305. context->fillPath (path, transform);
  65306. }
  65307. void Graphics::strokePath (const Path& path,
  65308. const PathStrokeType& strokeType,
  65309. const AffineTransform& transform) const
  65310. {
  65311. Path stroke;
  65312. strokeType.createStrokedPath (stroke, path, transform);
  65313. fillPath (stroke);
  65314. }
  65315. void Graphics::drawRect (const int x, const int y, const int width, const int height,
  65316. const int lineThickness) const
  65317. {
  65318. // passing in a silly number can cause maths problems in rendering!
  65319. jassert (areCoordsSensibleNumbers (x, y, width, height));
  65320. context->fillRect (Rectangle<int> (x, y, width, lineThickness), false);
  65321. context->fillRect (Rectangle<int> (x, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  65322. context->fillRect (Rectangle<int> (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  65323. context->fillRect (Rectangle<int> (x, y + height - lineThickness, width, lineThickness), false);
  65324. }
  65325. void Graphics::drawRect (const float x, const float y, const float width, const float height, const float lineThickness) const
  65326. {
  65327. // passing in a silly number can cause maths problems in rendering!
  65328. jassert (areCoordsSensibleNumbers (x, y, width, height));
  65329. Path p;
  65330. p.addRectangle (x, y, width, lineThickness);
  65331. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  65332. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  65333. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  65334. fillPath (p);
  65335. }
  65336. void Graphics::drawRect (const Rectangle<int>& r, const int lineThickness) const
  65337. {
  65338. drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight(), lineThickness);
  65339. }
  65340. void Graphics::drawBevel (const int x, const int y, const int width, const int height,
  65341. const int bevelThickness, const Colour& topLeftColour, const Colour& bottomRightColour,
  65342. const bool useGradient, const bool sharpEdgeOnOutside) const
  65343. {
  65344. // passing in a silly number can cause maths problems in rendering!
  65345. jassert (areCoordsSensibleNumbers (x, y, width, height));
  65346. if (clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  65347. {
  65348. context->saveState();
  65349. const float oldOpacity = 1.0f;//xxx state->colour.getFloatAlpha();
  65350. const float ramp = oldOpacity / bevelThickness;
  65351. for (int i = bevelThickness; --i >= 0;)
  65352. {
  65353. const float op = useGradient ? ramp * (sharpEdgeOnOutside ? bevelThickness - i : i)
  65354. : oldOpacity;
  65355. context->setFill (topLeftColour.withMultipliedAlpha (op));
  65356. context->fillRect (Rectangle<int> (x + i, y + i, width - i * 2, 1), false);
  65357. context->setFill (topLeftColour.withMultipliedAlpha (op * 0.75f));
  65358. context->fillRect (Rectangle<int> (x + i, y + i + 1, 1, height - i * 2 - 2), false);
  65359. context->setFill (bottomRightColour.withMultipliedAlpha (op));
  65360. context->fillRect (Rectangle<int> (x + i, y + height - i - 1, width - i * 2, 1), false);
  65361. context->setFill (bottomRightColour.withMultipliedAlpha (op * 0.75f));
  65362. context->fillRect (Rectangle<int> (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2), false);
  65363. }
  65364. context->restoreState();
  65365. }
  65366. }
  65367. void Graphics::fillEllipse (const float x, const float y, const float width, const float height) const
  65368. {
  65369. // passing in a silly number can cause maths problems in rendering!
  65370. jassert (areCoordsSensibleNumbers (x, y, width, height));
  65371. Path p;
  65372. p.addEllipse (x, y, width, height);
  65373. fillPath (p);
  65374. }
  65375. void Graphics::drawEllipse (const float x, const float y, const float width, const float height,
  65376. const float lineThickness) const
  65377. {
  65378. // passing in a silly number can cause maths problems in rendering!
  65379. jassert (areCoordsSensibleNumbers (x, y, width, height));
  65380. Path p;
  65381. p.addEllipse (x, y, width, height);
  65382. strokePath (p, PathStrokeType (lineThickness));
  65383. }
  65384. void Graphics::fillRoundedRectangle (const float x, const float y, const float width, const float height, const float cornerSize) const
  65385. {
  65386. // passing in a silly number can cause maths problems in rendering!
  65387. jassert (areCoordsSensibleNumbers (x, y, width, height));
  65388. Path p;
  65389. p.addRoundedRectangle (x, y, width, height, cornerSize);
  65390. fillPath (p);
  65391. }
  65392. void Graphics::fillRoundedRectangle (const Rectangle<float>& r, const float cornerSize) const
  65393. {
  65394. fillRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize);
  65395. }
  65396. void Graphics::drawRoundedRectangle (const float x, const float y, const float width, const float height,
  65397. const float cornerSize, const float lineThickness) const
  65398. {
  65399. // passing in a silly number can cause maths problems in rendering!
  65400. jassert (areCoordsSensibleNumbers (x, y, width, height));
  65401. Path p;
  65402. p.addRoundedRectangle (x, y, width, height, cornerSize);
  65403. strokePath (p, PathStrokeType (lineThickness));
  65404. }
  65405. void Graphics::drawRoundedRectangle (const Rectangle<float>& r, const float cornerSize, const float lineThickness) const
  65406. {
  65407. drawRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize, lineThickness);
  65408. }
  65409. void Graphics::drawArrow (const Line<float>& line, const float lineThickness, const float arrowheadWidth, const float arrowheadLength) const
  65410. {
  65411. Path p;
  65412. p.addArrow (line, lineThickness, arrowheadWidth, arrowheadLength);
  65413. fillPath (p);
  65414. }
  65415. void Graphics::fillCheckerBoard (int x, int y, int width, int height,
  65416. const int checkWidth, const int checkHeight,
  65417. const Colour& colour1, const Colour& colour2) const
  65418. {
  65419. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  65420. if (checkWidth > 0 && checkHeight > 0)
  65421. {
  65422. context->saveState();
  65423. if (colour1 == colour2)
  65424. {
  65425. context->setFill (colour1);
  65426. context->fillRect (Rectangle<int> (x, y, width, height), false);
  65427. }
  65428. else
  65429. {
  65430. const Rectangle<int> clip (context->getClipBounds());
  65431. const int right = jmin (x + width, clip.getRight());
  65432. const int bottom = jmin (y + height, clip.getBottom());
  65433. int cy = 0;
  65434. while (y < bottom)
  65435. {
  65436. int cx = cy;
  65437. for (int xx = x; xx < right; xx += checkWidth)
  65438. {
  65439. context->setFill (((cx++ & 1) == 0) ? colour1 : colour2);
  65440. context->fillRect (Rectangle<int> (xx, y, jmin (checkWidth, right - xx), jmin (checkHeight, bottom - y)),
  65441. false);
  65442. }
  65443. ++cy;
  65444. y += checkHeight;
  65445. }
  65446. }
  65447. context->restoreState();
  65448. }
  65449. }
  65450. void Graphics::drawVerticalLine (const int x, float top, float bottom) const
  65451. {
  65452. context->drawVerticalLine (x, top, bottom);
  65453. }
  65454. void Graphics::drawHorizontalLine (const int y, float left, float right) const
  65455. {
  65456. context->drawHorizontalLine (y, left, right);
  65457. }
  65458. void Graphics::drawLine (float x1, float y1, float x2, float y2) const
  65459. {
  65460. context->drawLine (Line<float> (x1, y1, x2, y2));
  65461. }
  65462. void Graphics::drawLine (const float startX, const float startY,
  65463. const float endX, const float endY,
  65464. const float lineThickness) const
  65465. {
  65466. drawLine (Line<float> (startX, startY, endX, endY),lineThickness);
  65467. }
  65468. void Graphics::drawLine (const Line<float>& line) const
  65469. {
  65470. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY());
  65471. }
  65472. void Graphics::drawLine (const Line<float>& line, const float lineThickness) const
  65473. {
  65474. Path p;
  65475. p.addLineSegment (line, lineThickness);
  65476. fillPath (p);
  65477. }
  65478. void Graphics::drawDashedLine (const float startX, const float startY,
  65479. const float endX, const float endY,
  65480. const float* const dashLengths,
  65481. const int numDashLengths,
  65482. const float lineThickness) const
  65483. {
  65484. const double dx = endX - startX;
  65485. const double dy = endY - startY;
  65486. const double totalLen = juce_hypot (dx, dy);
  65487. if (totalLen >= 0.5)
  65488. {
  65489. const double onePixAlpha = 1.0 / totalLen;
  65490. double alpha = 0.0;
  65491. float x = startX;
  65492. float y = startY;
  65493. int n = 0;
  65494. while (alpha < 1.0f)
  65495. {
  65496. alpha = jmin (1.0, alpha + dashLengths[n++] * onePixAlpha);
  65497. n = n % numDashLengths;
  65498. const float oldX = x;
  65499. const float oldY = y;
  65500. x = (float) (startX + dx * alpha);
  65501. y = (float) (startY + dy * alpha);
  65502. if ((n & 1) != 0)
  65503. {
  65504. if (lineThickness != 1.0f)
  65505. drawLine (oldX, oldY, x, y, lineThickness);
  65506. else
  65507. drawLine (oldX, oldY, x, y);
  65508. }
  65509. }
  65510. }
  65511. }
  65512. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality)
  65513. {
  65514. saveStateIfPending();
  65515. context->setInterpolationQuality (newQuality);
  65516. }
  65517. void Graphics::drawImageAt (const Image& imageToDraw,
  65518. const int topLeftX, const int topLeftY,
  65519. const bool fillAlphaChannelWithCurrentBrush) const
  65520. {
  65521. const int imageW = imageToDraw.getWidth();
  65522. const int imageH = imageToDraw.getHeight();
  65523. drawImage (imageToDraw,
  65524. topLeftX, topLeftY, imageW, imageH,
  65525. 0, 0, imageW, imageH,
  65526. fillAlphaChannelWithCurrentBrush);
  65527. }
  65528. void Graphics::drawImageWithin (const Image& imageToDraw,
  65529. const int destX, const int destY,
  65530. const int destW, const int destH,
  65531. const RectanglePlacement& placementWithinTarget,
  65532. const bool fillAlphaChannelWithCurrentBrush) const
  65533. {
  65534. // passing in a silly number can cause maths problems in rendering!
  65535. jassert (areCoordsSensibleNumbers (destX, destY, destW, destH));
  65536. if (imageToDraw.isValid())
  65537. {
  65538. const int imageW = imageToDraw.getWidth();
  65539. const int imageH = imageToDraw.getHeight();
  65540. if (imageW > 0 && imageH > 0)
  65541. {
  65542. double newX = 0.0, newY = 0.0;
  65543. double newW = imageW;
  65544. double newH = imageH;
  65545. placementWithinTarget.applyTo (newX, newY, newW, newH,
  65546. destX, destY, destW, destH);
  65547. if (newW > 0 && newH > 0)
  65548. {
  65549. drawImage (imageToDraw,
  65550. roundToInt (newX), roundToInt (newY),
  65551. roundToInt (newW), roundToInt (newH),
  65552. 0, 0, imageW, imageH,
  65553. fillAlphaChannelWithCurrentBrush);
  65554. }
  65555. }
  65556. }
  65557. }
  65558. void Graphics::drawImage (const Image& imageToDraw,
  65559. int dx, int dy, int dw, int dh,
  65560. int sx, int sy, int sw, int sh,
  65561. const bool fillAlphaChannelWithCurrentBrush) const
  65562. {
  65563. // passing in a silly number can cause maths problems in rendering!
  65564. jassert (areCoordsSensibleNumbers (dx, dy, dw, dh));
  65565. jassert (areCoordsSensibleNumbers (sx, sy, sw, sh));
  65566. if (imageToDraw.isValid() && context->clipRegionIntersects (Rectangle<int> (dx, dy, dw, dh)))
  65567. {
  65568. drawImageTransformed (imageToDraw, Rectangle<int> (sx, sy, sw, sh),
  65569. AffineTransform::scale (dw / (float) sw, dh / (float) sh)
  65570. .translated ((float) dx, (float) dy),
  65571. fillAlphaChannelWithCurrentBrush);
  65572. }
  65573. }
  65574. void Graphics::drawImageTransformed (const Image& imageToDraw,
  65575. const Rectangle<int>& imageSubRegion,
  65576. const AffineTransform& transform,
  65577. const bool fillAlphaChannelWithCurrentBrush) const
  65578. {
  65579. if (imageToDraw.isValid() && ! context->isClipEmpty())
  65580. {
  65581. const Rectangle<int> srcClip (imageSubRegion.getIntersection (imageToDraw.getBounds()));
  65582. if (fillAlphaChannelWithCurrentBrush)
  65583. {
  65584. context->saveState();
  65585. context->clipToImageAlpha (imageToDraw, srcClip, transform);
  65586. fillAll();
  65587. context->restoreState();
  65588. }
  65589. else
  65590. {
  65591. context->drawImage (imageToDraw, srcClip, transform, false);
  65592. }
  65593. }
  65594. }
  65595. END_JUCE_NAMESPACE
  65596. /*** End of inlined file: juce_Graphics.cpp ***/
  65597. /*** Start of inlined file: juce_Justification.cpp ***/
  65598. BEGIN_JUCE_NAMESPACE
  65599. Justification::Justification (const Justification& other) throw()
  65600. : flags (other.flags)
  65601. {
  65602. }
  65603. Justification& Justification::operator= (const Justification& other) throw()
  65604. {
  65605. flags = other.flags;
  65606. return *this;
  65607. }
  65608. int Justification::getOnlyVerticalFlags() const throw()
  65609. {
  65610. return flags & (top | bottom | verticallyCentred);
  65611. }
  65612. int Justification::getOnlyHorizontalFlags() const throw()
  65613. {
  65614. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  65615. }
  65616. void Justification::applyToRectangle (int& x, int& y,
  65617. const int w, const int h,
  65618. const int spaceX, const int spaceY,
  65619. const int spaceW, const int spaceH) const throw()
  65620. {
  65621. if ((flags & horizontallyCentred) != 0)
  65622. x = spaceX + ((spaceW - w) >> 1);
  65623. else if ((flags & right) != 0)
  65624. x = spaceX + spaceW - w;
  65625. else
  65626. x = spaceX;
  65627. if ((flags & verticallyCentred) != 0)
  65628. y = spaceY + ((spaceH - h) >> 1);
  65629. else if ((flags & bottom) != 0)
  65630. y = spaceY + spaceH - h;
  65631. else
  65632. y = spaceY;
  65633. }
  65634. END_JUCE_NAMESPACE
  65635. /*** End of inlined file: juce_Justification.cpp ***/
  65636. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  65637. BEGIN_JUCE_NAMESPACE
  65638. // this will throw an assertion if you try to draw something that's not
  65639. // possible in postscript
  65640. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  65641. #if JUCE_DEBUG && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  65642. #define notPossibleInPostscriptAssert jassertfalse
  65643. #else
  65644. #define notPossibleInPostscriptAssert
  65645. #endif
  65646. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  65647. const String& documentTitle,
  65648. const int totalWidth_,
  65649. const int totalHeight_)
  65650. : out (resultingPostScript),
  65651. totalWidth (totalWidth_),
  65652. totalHeight (totalHeight_),
  65653. needToClip (true)
  65654. {
  65655. stateStack.add (new SavedState());
  65656. stateStack.getLast()->clip = Rectangle<int> (0, 0, totalWidth_, totalHeight_);
  65657. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  65658. out << "%!PS-Adobe-3.0 EPSF-3.0"
  65659. "\n%%BoundingBox: 0 0 600 824"
  65660. "\n%%Pages: 0"
  65661. "\n%%Creator: Raw Material Software JUCE"
  65662. "\n%%Title: " << documentTitle <<
  65663. "\n%%CreationDate: none"
  65664. "\n%%LanguageLevel: 2"
  65665. "\n%%EndComments"
  65666. "\n%%BeginProlog"
  65667. "\n%%BeginResource: JRes"
  65668. "\n/bd {bind def} bind def"
  65669. "\n/c {setrgbcolor} bd"
  65670. "\n/m {moveto} bd"
  65671. "\n/l {lineto} bd"
  65672. "\n/rl {rlineto} bd"
  65673. "\n/ct {curveto} bd"
  65674. "\n/cp {closepath} bd"
  65675. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  65676. "\n/doclip {initclip newpath} bd"
  65677. "\n/endclip {clip newpath} bd"
  65678. "\n%%EndResource"
  65679. "\n%%EndProlog"
  65680. "\n%%BeginSetup"
  65681. "\n%%EndSetup"
  65682. "\n%%Page: 1 1"
  65683. "\n%%BeginPageSetup"
  65684. "\n%%EndPageSetup\n\n"
  65685. << "40 800 translate\n"
  65686. << scale << ' ' << scale << " scale\n\n";
  65687. }
  65688. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  65689. {
  65690. }
  65691. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  65692. {
  65693. return true;
  65694. }
  65695. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  65696. {
  65697. if (x != 0 || y != 0)
  65698. {
  65699. stateStack.getLast()->xOffset += x;
  65700. stateStack.getLast()->yOffset += y;
  65701. needToClip = true;
  65702. }
  65703. }
  65704. bool LowLevelGraphicsPostScriptRenderer::clipToRectangle (const Rectangle<int>& r)
  65705. {
  65706. needToClip = true;
  65707. return stateStack.getLast()->clip.clipTo (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  65708. }
  65709. bool LowLevelGraphicsPostScriptRenderer::clipToRectangleList (const RectangleList& clipRegion)
  65710. {
  65711. needToClip = true;
  65712. return stateStack.getLast()->clip.clipTo (clipRegion);
  65713. }
  65714. void LowLevelGraphicsPostScriptRenderer::excludeClipRectangle (const Rectangle<int>& r)
  65715. {
  65716. needToClip = true;
  65717. stateStack.getLast()->clip.subtract (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  65718. }
  65719. void LowLevelGraphicsPostScriptRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  65720. {
  65721. writeClip();
  65722. Path p (path);
  65723. p.applyTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  65724. writePath (p);
  65725. out << "clip\n";
  65726. }
  65727. void LowLevelGraphicsPostScriptRenderer::clipToImageAlpha (const Image& /*sourceImage*/, const Rectangle<int>& /*srcClip*/, const AffineTransform& /*transform*/)
  65728. {
  65729. needToClip = true;
  65730. jassertfalse; // xxx
  65731. }
  65732. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (const Rectangle<int>& r)
  65733. {
  65734. return stateStack.getLast()->clip.intersectsRectangle (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  65735. }
  65736. const Rectangle<int> LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  65737. {
  65738. return stateStack.getLast()->clip.getBounds().translated (-stateStack.getLast()->xOffset,
  65739. -stateStack.getLast()->yOffset);
  65740. }
  65741. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  65742. {
  65743. return stateStack.getLast()->clip.isEmpty();
  65744. }
  65745. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState()
  65746. : xOffset (0),
  65747. yOffset (0)
  65748. {
  65749. }
  65750. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  65751. {
  65752. }
  65753. void LowLevelGraphicsPostScriptRenderer::saveState()
  65754. {
  65755. stateStack.add (new SavedState (*stateStack.getLast()));
  65756. }
  65757. void LowLevelGraphicsPostScriptRenderer::restoreState()
  65758. {
  65759. jassert (stateStack.size() > 0);
  65760. if (stateStack.size() > 0)
  65761. stateStack.removeLast();
  65762. }
  65763. void LowLevelGraphicsPostScriptRenderer::writeClip()
  65764. {
  65765. if (needToClip)
  65766. {
  65767. needToClip = false;
  65768. out << "doclip ";
  65769. int itemsOnLine = 0;
  65770. for (RectangleList::Iterator i (stateStack.getLast()->clip); i.next();)
  65771. {
  65772. if (++itemsOnLine == 6)
  65773. {
  65774. itemsOnLine = 0;
  65775. out << '\n';
  65776. }
  65777. const Rectangle<int>& r = *i.getRectangle();
  65778. out << r.getX() << ' ' << -r.getY() << ' '
  65779. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  65780. }
  65781. out << "endclip\n";
  65782. }
  65783. }
  65784. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  65785. {
  65786. Colour c (Colours::white.overlaidWith (colour));
  65787. if (lastColour != c)
  65788. {
  65789. lastColour = c;
  65790. out << String (c.getFloatRed(), 3) << ' '
  65791. << String (c.getFloatGreen(), 3) << ' '
  65792. << String (c.getFloatBlue(), 3) << " c\n";
  65793. }
  65794. }
  65795. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  65796. {
  65797. out << String (x, 2) << ' '
  65798. << String (-y, 2) << ' ';
  65799. }
  65800. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  65801. {
  65802. out << "newpath ";
  65803. float lastX = 0.0f;
  65804. float lastY = 0.0f;
  65805. int itemsOnLine = 0;
  65806. Path::Iterator i (path);
  65807. while (i.next())
  65808. {
  65809. if (++itemsOnLine == 4)
  65810. {
  65811. itemsOnLine = 0;
  65812. out << '\n';
  65813. }
  65814. switch (i.elementType)
  65815. {
  65816. case Path::Iterator::startNewSubPath:
  65817. writeXY (i.x1, i.y1);
  65818. lastX = i.x1;
  65819. lastY = i.y1;
  65820. out << "m ";
  65821. break;
  65822. case Path::Iterator::lineTo:
  65823. writeXY (i.x1, i.y1);
  65824. lastX = i.x1;
  65825. lastY = i.y1;
  65826. out << "l ";
  65827. break;
  65828. case Path::Iterator::quadraticTo:
  65829. {
  65830. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  65831. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  65832. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  65833. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  65834. writeXY (cp1x, cp1y);
  65835. writeXY (cp2x, cp2y);
  65836. writeXY (i.x2, i.y2);
  65837. out << "ct ";
  65838. lastX = i.x2;
  65839. lastY = i.y2;
  65840. }
  65841. break;
  65842. case Path::Iterator::cubicTo:
  65843. writeXY (i.x1, i.y1);
  65844. writeXY (i.x2, i.y2);
  65845. writeXY (i.x3, i.y3);
  65846. out << "ct ";
  65847. lastX = i.x3;
  65848. lastY = i.y3;
  65849. break;
  65850. case Path::Iterator::closePath:
  65851. out << "cp ";
  65852. break;
  65853. default:
  65854. jassertfalse;
  65855. break;
  65856. }
  65857. }
  65858. out << '\n';
  65859. }
  65860. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  65861. {
  65862. out << "[ "
  65863. << trans.mat00 << ' '
  65864. << trans.mat10 << ' '
  65865. << trans.mat01 << ' '
  65866. << trans.mat11 << ' '
  65867. << trans.mat02 << ' '
  65868. << trans.mat12 << " ] concat ";
  65869. }
  65870. void LowLevelGraphicsPostScriptRenderer::setFill (const FillType& fillType)
  65871. {
  65872. stateStack.getLast()->fillType = fillType;
  65873. }
  65874. void LowLevelGraphicsPostScriptRenderer::setOpacity (float /*opacity*/)
  65875. {
  65876. }
  65877. void LowLevelGraphicsPostScriptRenderer::setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  65878. {
  65879. }
  65880. void LowLevelGraphicsPostScriptRenderer::fillRect (const Rectangle<int>& r, const bool /*replaceExistingContents*/)
  65881. {
  65882. if (stateStack.getLast()->fillType.isColour())
  65883. {
  65884. writeClip();
  65885. writeColour (stateStack.getLast()->fillType.colour);
  65886. Rectangle<int> r2 (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  65887. out << r2.getX() << ' ' << -r2.getBottom() << ' ' << r2.getWidth() << ' ' << r2.getHeight() << " rectfill\n";
  65888. }
  65889. else
  65890. {
  65891. Path p;
  65892. p.addRectangle (r);
  65893. fillPath (p, AffineTransform::identity);
  65894. }
  65895. }
  65896. void LowLevelGraphicsPostScriptRenderer::fillPath (const Path& path, const AffineTransform& t)
  65897. {
  65898. if (stateStack.getLast()->fillType.isColour())
  65899. {
  65900. writeClip();
  65901. Path p (path);
  65902. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset,
  65903. (float) stateStack.getLast()->yOffset));
  65904. writePath (p);
  65905. writeColour (stateStack.getLast()->fillType.colour);
  65906. out << "fill\n";
  65907. }
  65908. else if (stateStack.getLast()->fillType.isGradient())
  65909. {
  65910. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  65911. // postscript can't do semi-transparent ones.
  65912. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  65913. writeClip();
  65914. out << "gsave ";
  65915. {
  65916. Path p (path);
  65917. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  65918. writePath (p);
  65919. out << "clip\n";
  65920. }
  65921. const Rectangle<int> bounds (stateStack.getLast()->clip.getBounds());
  65922. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  65923. // time-being, this just fills it with the average colour..
  65924. writeColour (stateStack.getLast()->fillType.gradient->getColourAtPosition (0.5f));
  65925. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  65926. out << "grestore\n";
  65927. }
  65928. }
  65929. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  65930. const int sx, const int sy,
  65931. const int maxW, const int maxH) const
  65932. {
  65933. out << "{<\n";
  65934. const int w = jmin (maxW, im.getWidth());
  65935. const int h = jmin (maxH, im.getHeight());
  65936. int charsOnLine = 0;
  65937. const Image::BitmapData srcData (im, 0, 0, w, h);
  65938. Colour pixel;
  65939. for (int y = h; --y >= 0;)
  65940. {
  65941. for (int x = 0; x < w; ++x)
  65942. {
  65943. const uint8* pixelData = srcData.getPixelPointer (x, y);
  65944. if (x >= sx && y >= sy)
  65945. {
  65946. if (im.isARGB())
  65947. {
  65948. PixelARGB p (*(const PixelARGB*) pixelData);
  65949. p.unpremultiply();
  65950. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  65951. }
  65952. else if (im.isRGB())
  65953. {
  65954. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  65955. }
  65956. else
  65957. {
  65958. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  65959. }
  65960. }
  65961. else
  65962. {
  65963. pixel = Colours::transparentWhite;
  65964. }
  65965. const uint8 pixelValues[3] = { pixel.getRed(), pixel.getGreen(), pixel.getBlue() };
  65966. out << String::toHexString (pixelValues, 3, 0);
  65967. charsOnLine += 3;
  65968. if (charsOnLine > 100)
  65969. {
  65970. out << '\n';
  65971. charsOnLine = 0;
  65972. }
  65973. }
  65974. }
  65975. out << "\n>}\n";
  65976. }
  65977. void LowLevelGraphicsPostScriptRenderer::drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  65978. const AffineTransform& transform, const bool /*fillEntireClipAsTiles*/)
  65979. {
  65980. const int w = jmin (sourceImage.getWidth(), srcClip.getRight());
  65981. const int h = jmin (sourceImage.getHeight(), srcClip.getBottom());
  65982. writeClip();
  65983. out << "gsave ";
  65984. writeTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset)
  65985. .scaled (1.0f, -1.0f));
  65986. RectangleList imageClip;
  65987. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  65988. imageClip.clipTo (srcClip);
  65989. out << "newpath ";
  65990. int itemsOnLine = 0;
  65991. for (RectangleList::Iterator i (imageClip); i.next();)
  65992. {
  65993. if (++itemsOnLine == 6)
  65994. {
  65995. out << '\n';
  65996. itemsOnLine = 0;
  65997. }
  65998. const Rectangle<int>& r = *i.getRectangle();
  65999. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  66000. }
  66001. out << " clip newpath\n";
  66002. out << w << ' ' << h << " scale\n";
  66003. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  66004. writeImage (sourceImage, srcClip.getX(), srcClip.getY(), srcClip.getWidth(), srcClip.getHeight());
  66005. out << "false 3 colorimage grestore\n";
  66006. needToClip = true;
  66007. }
  66008. void LowLevelGraphicsPostScriptRenderer::drawLine (const Line <float>& line)
  66009. {
  66010. Path p;
  66011. p.addLineSegment (line, 1.0f);
  66012. fillPath (p, AffineTransform::identity);
  66013. }
  66014. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, float top, float bottom)
  66015. {
  66016. drawLine (Line<float> ((float) x, top, (float) x, bottom));
  66017. }
  66018. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, float left, float right)
  66019. {
  66020. drawLine (Line<float> (left, (float) y, right, (float) y));
  66021. }
  66022. void LowLevelGraphicsPostScriptRenderer::setFont (const Font& newFont)
  66023. {
  66024. stateStack.getLast()->font = newFont;
  66025. }
  66026. const Font LowLevelGraphicsPostScriptRenderer::getFont()
  66027. {
  66028. return stateStack.getLast()->font;
  66029. }
  66030. void LowLevelGraphicsPostScriptRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  66031. {
  66032. Path p;
  66033. Font& font = stateStack.getLast()->font;
  66034. font.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  66035. fillPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight()).followedBy (transform));
  66036. }
  66037. END_JUCE_NAMESPACE
  66038. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  66039. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  66040. BEGIN_JUCE_NAMESPACE
  66041. #if (JUCE_WINDOWS || JUCE_LINUX) && ! JUCE_64BIT
  66042. #define JUCE_USE_SSE_INSTRUCTIONS 1
  66043. #endif
  66044. #if JUCE_MSVC
  66045. #pragma warning (push)
  66046. #pragma warning (disable: 4127) // "expression is constant" warning
  66047. #if JUCE_DEBUG
  66048. #pragma optimize ("t", on) // optimise just this file, to avoid sluggish graphics when debugging
  66049. #pragma warning (disable: 4714) // warning about forcedinline methods not being inlined
  66050. #endif
  66051. #endif
  66052. namespace SoftwareRendererClasses
  66053. {
  66054. template <class PixelType, bool replaceExisting = false>
  66055. class SolidColourEdgeTableRenderer
  66056. {
  66057. public:
  66058. SolidColourEdgeTableRenderer (const Image::BitmapData& data_, const PixelARGB& colour)
  66059. : data (data_),
  66060. sourceColour (colour)
  66061. {
  66062. if (sizeof (PixelType) == 3)
  66063. {
  66064. areRGBComponentsEqual = sourceColour.getRed() == sourceColour.getGreen()
  66065. && sourceColour.getGreen() == sourceColour.getBlue();
  66066. filler[0].set (sourceColour);
  66067. filler[1].set (sourceColour);
  66068. filler[2].set (sourceColour);
  66069. filler[3].set (sourceColour);
  66070. }
  66071. }
  66072. forcedinline void setEdgeTableYPos (const int y) throw()
  66073. {
  66074. linePixels = (PixelType*) data.getLinePointer (y);
  66075. }
  66076. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  66077. {
  66078. if (replaceExisting)
  66079. linePixels[x].set (sourceColour);
  66080. else
  66081. linePixels[x].blend (sourceColour, alphaLevel);
  66082. }
  66083. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  66084. {
  66085. if (replaceExisting)
  66086. linePixels[x].set (sourceColour);
  66087. else
  66088. linePixels[x].blend (sourceColour);
  66089. }
  66090. forcedinline void handleEdgeTableLine (const int x, const int width, const int alphaLevel) const throw()
  66091. {
  66092. PixelARGB p (sourceColour);
  66093. p.multiplyAlpha (alphaLevel);
  66094. PixelType* dest = linePixels + x;
  66095. if (replaceExisting || p.getAlpha() >= 0xff)
  66096. replaceLine (dest, p, width);
  66097. else
  66098. blendLine (dest, p, width);
  66099. }
  66100. forcedinline void handleEdgeTableLineFull (const int x, const int width) const throw()
  66101. {
  66102. PixelType* dest = linePixels + x;
  66103. if (replaceExisting || sourceColour.getAlpha() >= 0xff)
  66104. replaceLine (dest, sourceColour, width);
  66105. else
  66106. blendLine (dest, sourceColour, width);
  66107. }
  66108. private:
  66109. const Image::BitmapData& data;
  66110. PixelType* linePixels;
  66111. PixelARGB sourceColour;
  66112. PixelRGB filler [4];
  66113. bool areRGBComponentsEqual;
  66114. inline void blendLine (PixelType* dest, const PixelARGB& colour, int width) const throw()
  66115. {
  66116. do
  66117. {
  66118. dest->blend (colour);
  66119. ++dest;
  66120. } while (--width > 0);
  66121. }
  66122. forcedinline void replaceLine (PixelRGB* dest, const PixelARGB& colour, int width) const throw()
  66123. {
  66124. if (areRGBComponentsEqual) // if all the component values are the same, we can cheat..
  66125. {
  66126. memset (dest, colour.getRed(), width * 3);
  66127. }
  66128. else
  66129. {
  66130. if (width >> 5)
  66131. {
  66132. const int* const intFiller = (const int*) filler;
  66133. while (width > 8 && (((pointer_sized_int) dest) & 7) != 0)
  66134. {
  66135. dest->set (colour);
  66136. ++dest;
  66137. --width;
  66138. }
  66139. while (width > 4)
  66140. {
  66141. ((int*) dest) [0] = intFiller[0];
  66142. ((int*) dest) [1] = intFiller[1];
  66143. ((int*) dest) [2] = intFiller[2];
  66144. dest = (PixelRGB*) (((uint8*) dest) + 12);
  66145. width -= 4;
  66146. }
  66147. }
  66148. while (--width >= 0)
  66149. {
  66150. dest->set (colour);
  66151. ++dest;
  66152. }
  66153. }
  66154. }
  66155. forcedinline void replaceLine (PixelAlpha* const dest, const PixelARGB& colour, int const width) const throw()
  66156. {
  66157. memset (dest, colour.getAlpha(), width);
  66158. }
  66159. forcedinline void replaceLine (PixelARGB* dest, const PixelARGB& colour, int width) const throw()
  66160. {
  66161. do
  66162. {
  66163. dest->set (colour);
  66164. ++dest;
  66165. } while (--width > 0);
  66166. }
  66167. SolidColourEdgeTableRenderer (const SolidColourEdgeTableRenderer&);
  66168. SolidColourEdgeTableRenderer& operator= (const SolidColourEdgeTableRenderer&);
  66169. };
  66170. class LinearGradientPixelGenerator
  66171. {
  66172. public:
  66173. LinearGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform, const PixelARGB* const lookupTable_, const int numEntries_)
  66174. : lookupTable (lookupTable_), numEntries (numEntries_)
  66175. {
  66176. jassert (numEntries_ >= 0);
  66177. Point<float> p1 (gradient.point1);
  66178. Point<float> p2 (gradient.point2);
  66179. if (! transform.isIdentity())
  66180. {
  66181. const Line<float> l (p2, p1);
  66182. Point<float> p3 = l.getPointAlongLine (0.0f, 100.0f);
  66183. p1.applyTransform (transform);
  66184. p2.applyTransform (transform);
  66185. p3.applyTransform (transform);
  66186. p2 = Line<float> (p2, p3).findNearestPointTo (p1);
  66187. }
  66188. vertical = std::abs (p1.getX() - p2.getX()) < 0.001f;
  66189. horizontal = std::abs (p1.getY() - p2.getY()) < 0.001f;
  66190. if (vertical)
  66191. {
  66192. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getY() - p1.getY()));
  66193. start = roundToInt (p1.getY() * scale);
  66194. }
  66195. else if (horizontal)
  66196. {
  66197. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getX() - p1.getX()));
  66198. start = roundToInt (p1.getX() * scale);
  66199. }
  66200. else
  66201. {
  66202. grad = (p2.getY() - p1.getY()) / (double) (p1.getX() - p2.getX());
  66203. yTerm = p1.getY() - p1.getX() / grad;
  66204. scale = roundToInt ((numEntries << (int) numScaleBits) / (yTerm * grad - (p2.getY() * grad - p2.getX())));
  66205. grad *= scale;
  66206. }
  66207. }
  66208. forcedinline void setY (const int y) throw()
  66209. {
  66210. if (vertical)
  66211. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> (int) numScaleBits)];
  66212. else if (! horizontal)
  66213. start = roundToInt ((y - yTerm) * grad);
  66214. }
  66215. inline const PixelARGB getPixel (const int x) const throw()
  66216. {
  66217. return vertical ? linePix
  66218. : lookupTable [jlimit (0, numEntries, (x * scale - start) >> (int) numScaleBits)];
  66219. }
  66220. private:
  66221. const PixelARGB* const lookupTable;
  66222. const int numEntries;
  66223. PixelARGB linePix;
  66224. int start, scale;
  66225. double grad, yTerm;
  66226. bool vertical, horizontal;
  66227. enum { numScaleBits = 12 };
  66228. LinearGradientPixelGenerator (const LinearGradientPixelGenerator&);
  66229. LinearGradientPixelGenerator& operator= (const LinearGradientPixelGenerator&);
  66230. };
  66231. class RadialGradientPixelGenerator
  66232. {
  66233. public:
  66234. RadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform&,
  66235. const PixelARGB* const lookupTable_, const int numEntries_)
  66236. : lookupTable (lookupTable_),
  66237. numEntries (numEntries_),
  66238. gx1 (gradient.point1.getX()),
  66239. gy1 (gradient.point1.getY())
  66240. {
  66241. jassert (numEntries_ >= 0);
  66242. const Point<float> diff (gradient.point1 - gradient.point2);
  66243. maxDist = diff.getX() * diff.getX() + diff.getY() * diff.getY();
  66244. invScale = numEntries / std::sqrt (maxDist);
  66245. jassert (roundToInt (std::sqrt (maxDist) * invScale) <= numEntries);
  66246. }
  66247. forcedinline void setY (const int y) throw()
  66248. {
  66249. dy = y - gy1;
  66250. dy *= dy;
  66251. }
  66252. inline const PixelARGB getPixel (const int px) const throw()
  66253. {
  66254. double x = px - gx1;
  66255. x *= x;
  66256. x += dy;
  66257. return lookupTable [x >= maxDist ? numEntries : roundToInt (std::sqrt (x) * invScale)];
  66258. }
  66259. protected:
  66260. const PixelARGB* const lookupTable;
  66261. const int numEntries;
  66262. const double gx1, gy1;
  66263. double maxDist, invScale, dy;
  66264. RadialGradientPixelGenerator (const RadialGradientPixelGenerator&);
  66265. RadialGradientPixelGenerator& operator= (const RadialGradientPixelGenerator&);
  66266. };
  66267. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  66268. {
  66269. public:
  66270. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform,
  66271. const PixelARGB* const lookupTable_, const int numEntries_)
  66272. : RadialGradientPixelGenerator (gradient, transform, lookupTable_, numEntries_),
  66273. inverseTransform (transform.inverted())
  66274. {
  66275. tM10 = inverseTransform.mat10;
  66276. tM00 = inverseTransform.mat00;
  66277. }
  66278. forcedinline void setY (const int y) throw()
  66279. {
  66280. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  66281. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  66282. }
  66283. inline const PixelARGB getPixel (const int px) const throw()
  66284. {
  66285. double x = px;
  66286. const double y = tM10 * x + lineYM11;
  66287. x = tM00 * x + lineYM01;
  66288. x *= x;
  66289. x += y * y;
  66290. if (x >= maxDist)
  66291. return lookupTable [numEntries];
  66292. else
  66293. return lookupTable [jmin (numEntries, roundToInt (std::sqrt (x) * invScale))];
  66294. }
  66295. private:
  66296. double tM10, tM00, lineYM01, lineYM11;
  66297. const AffineTransform inverseTransform;
  66298. TransformedRadialGradientPixelGenerator (const TransformedRadialGradientPixelGenerator&);
  66299. TransformedRadialGradientPixelGenerator& operator= (const TransformedRadialGradientPixelGenerator&);
  66300. };
  66301. template <class PixelType, class GradientType>
  66302. class GradientEdgeTableRenderer : public GradientType
  66303. {
  66304. public:
  66305. GradientEdgeTableRenderer (const Image::BitmapData& destData_, const ColourGradient& gradient, const AffineTransform& transform,
  66306. const PixelARGB* const lookupTable_, const int numEntries_)
  66307. : GradientType (gradient, transform, lookupTable_, numEntries_ - 1),
  66308. destData (destData_)
  66309. {
  66310. }
  66311. forcedinline void setEdgeTableYPos (const int y) throw()
  66312. {
  66313. linePixels = (PixelType*) destData.getLinePointer (y);
  66314. GradientType::setY (y);
  66315. }
  66316. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  66317. {
  66318. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  66319. }
  66320. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  66321. {
  66322. linePixels[x].blend (GradientType::getPixel (x));
  66323. }
  66324. void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  66325. {
  66326. PixelType* dest = linePixels + x;
  66327. if (alphaLevel < 0xff)
  66328. {
  66329. do
  66330. {
  66331. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  66332. } while (--width > 0);
  66333. }
  66334. else
  66335. {
  66336. do
  66337. {
  66338. (dest++)->blend (GradientType::getPixel (x++));
  66339. } while (--width > 0);
  66340. }
  66341. }
  66342. void handleEdgeTableLineFull (int x, int width) const throw()
  66343. {
  66344. PixelType* dest = linePixels + x;
  66345. do
  66346. {
  66347. (dest++)->blend (GradientType::getPixel (x++));
  66348. } while (--width > 0);
  66349. }
  66350. private:
  66351. const Image::BitmapData& destData;
  66352. PixelType* linePixels;
  66353. GradientEdgeTableRenderer (const GradientEdgeTableRenderer&);
  66354. GradientEdgeTableRenderer& operator= (const GradientEdgeTableRenderer&);
  66355. };
  66356. static forcedinline int safeModulo (int n, const int divisor) throw()
  66357. {
  66358. jassert (divisor > 0);
  66359. n %= divisor;
  66360. return (n < 0) ? (n + divisor) : n;
  66361. }
  66362. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  66363. class ImageFillEdgeTableRenderer
  66364. {
  66365. public:
  66366. ImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  66367. const Image::BitmapData& srcData_,
  66368. const int extraAlpha_,
  66369. const int x, const int y)
  66370. : destData (destData_),
  66371. srcData (srcData_),
  66372. extraAlpha (extraAlpha_ + 1),
  66373. xOffset (repeatPattern ? safeModulo (x, srcData_.width) - srcData_.width : x),
  66374. yOffset (repeatPattern ? safeModulo (y, srcData_.height) - srcData_.height : y)
  66375. {
  66376. }
  66377. forcedinline void setEdgeTableYPos (int y) throw()
  66378. {
  66379. linePixels = (DestPixelType*) destData.getLinePointer (y);
  66380. y -= yOffset;
  66381. if (repeatPattern)
  66382. {
  66383. jassert (y >= 0);
  66384. y %= srcData.height;
  66385. }
  66386. sourceLineStart = (SrcPixelType*) srcData.getLinePointer (y);
  66387. }
  66388. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) const throw()
  66389. {
  66390. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  66391. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], alphaLevel);
  66392. }
  66393. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  66394. {
  66395. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], extraAlpha);
  66396. }
  66397. void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  66398. {
  66399. DestPixelType* dest = linePixels + x;
  66400. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  66401. x -= xOffset;
  66402. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  66403. if (alphaLevel < 0xfe)
  66404. {
  66405. do
  66406. {
  66407. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], alphaLevel);
  66408. } while (--width > 0);
  66409. }
  66410. else
  66411. {
  66412. if (repeatPattern)
  66413. {
  66414. do
  66415. {
  66416. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  66417. } while (--width > 0);
  66418. }
  66419. else
  66420. {
  66421. copyRow (dest, sourceLineStart + x, width);
  66422. }
  66423. }
  66424. }
  66425. void handleEdgeTableLineFull (int x, int width) const throw()
  66426. {
  66427. DestPixelType* dest = linePixels + x;
  66428. x -= xOffset;
  66429. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  66430. if (extraAlpha < 0xfe)
  66431. {
  66432. do
  66433. {
  66434. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], extraAlpha);
  66435. } while (--width > 0);
  66436. }
  66437. else
  66438. {
  66439. if (repeatPattern)
  66440. {
  66441. do
  66442. {
  66443. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  66444. } while (--width > 0);
  66445. }
  66446. else
  66447. {
  66448. copyRow (dest, sourceLineStart + x, width);
  66449. }
  66450. }
  66451. }
  66452. void clipEdgeTableLine (EdgeTable& et, int x, int y, int width)
  66453. {
  66454. jassert (x - xOffset >= 0 && x + width - xOffset <= srcData.width);
  66455. SrcPixelType* s = (SrcPixelType*) srcData.getLinePointer (y - yOffset);
  66456. uint8* mask = (uint8*) (s + x - xOffset);
  66457. if (sizeof (SrcPixelType) == sizeof (PixelARGB))
  66458. mask += PixelARGB::indexA;
  66459. et.clipLineToMask (x, y, mask, sizeof (SrcPixelType), width);
  66460. }
  66461. private:
  66462. const Image::BitmapData& destData;
  66463. const Image::BitmapData& srcData;
  66464. const int extraAlpha, xOffset, yOffset;
  66465. DestPixelType* linePixels;
  66466. SrcPixelType* sourceLineStart;
  66467. template <class PixelType1, class PixelType2>
  66468. forcedinline static void copyRow (PixelType1* dest, PixelType2* src, int width) throw()
  66469. {
  66470. do
  66471. {
  66472. dest++ ->blend (*src++);
  66473. } while (--width > 0);
  66474. }
  66475. forcedinline static void copyRow (PixelRGB* dest, PixelRGB* src, int width) throw()
  66476. {
  66477. memcpy (dest, src, width * sizeof (PixelRGB));
  66478. }
  66479. ImageFillEdgeTableRenderer (const ImageFillEdgeTableRenderer&);
  66480. ImageFillEdgeTableRenderer& operator= (const ImageFillEdgeTableRenderer&);
  66481. };
  66482. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  66483. class TransformedImageFillEdgeTableRenderer
  66484. {
  66485. public:
  66486. TransformedImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  66487. const Image::BitmapData& srcData_,
  66488. const AffineTransform& transform,
  66489. const int extraAlpha_,
  66490. const bool betterQuality_)
  66491. : interpolator (transform),
  66492. destData (destData_),
  66493. srcData (srcData_),
  66494. extraAlpha (extraAlpha_ + 1),
  66495. betterQuality (betterQuality_),
  66496. pixelOffset (betterQuality_ ? 0.5f : 0.0f),
  66497. pixelOffsetInt (betterQuality_ ? -128 : 0),
  66498. maxX (srcData_.width - 1),
  66499. maxY (srcData_.height - 1),
  66500. scratchSize (2048)
  66501. {
  66502. scratchBuffer.malloc (scratchSize);
  66503. }
  66504. ~TransformedImageFillEdgeTableRenderer()
  66505. {
  66506. }
  66507. forcedinline void setEdgeTableYPos (const int newY) throw()
  66508. {
  66509. y = newY;
  66510. linePixels = (DestPixelType*) destData.getLinePointer (newY);
  66511. }
  66512. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) throw()
  66513. {
  66514. alphaLevel *= extraAlpha;
  66515. alphaLevel >>= 8;
  66516. SrcPixelType p;
  66517. generate (&p, x, 1);
  66518. linePixels[x].blend (p, alphaLevel);
  66519. }
  66520. forcedinline void handleEdgeTablePixelFull (const int x) throw()
  66521. {
  66522. SrcPixelType p;
  66523. generate (&p, x, 1);
  66524. linePixels[x].blend (p, extraAlpha);
  66525. }
  66526. void handleEdgeTableLine (const int x, int width, int alphaLevel) throw()
  66527. {
  66528. if (width > scratchSize)
  66529. {
  66530. scratchSize = width;
  66531. scratchBuffer.malloc (scratchSize);
  66532. }
  66533. SrcPixelType* span = scratchBuffer;
  66534. generate (span, x, width);
  66535. DestPixelType* dest = linePixels + x;
  66536. alphaLevel *= extraAlpha;
  66537. alphaLevel >>= 8;
  66538. if (alphaLevel < 0xfe)
  66539. {
  66540. do
  66541. {
  66542. dest++ ->blend (*span++, alphaLevel);
  66543. } while (--width > 0);
  66544. }
  66545. else
  66546. {
  66547. do
  66548. {
  66549. dest++ ->blend (*span++);
  66550. } while (--width > 0);
  66551. }
  66552. }
  66553. forcedinline void handleEdgeTableLineFull (const int x, int width) throw()
  66554. {
  66555. handleEdgeTableLine (x, width, 255);
  66556. }
  66557. void clipEdgeTableLine (EdgeTable& et, int x, int y_, int width)
  66558. {
  66559. if (width > scratchSize)
  66560. {
  66561. scratchSize = width;
  66562. scratchBuffer.malloc (scratchSize);
  66563. }
  66564. y = y_;
  66565. generate (scratchBuffer, x, width);
  66566. et.clipLineToMask (x, y_,
  66567. reinterpret_cast<uint8*> (scratchBuffer.getData()) + SrcPixelType::indexA,
  66568. sizeof (SrcPixelType), width);
  66569. }
  66570. private:
  66571. void generate (PixelARGB* dest, const int x, int numPixels) throw()
  66572. {
  66573. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  66574. do
  66575. {
  66576. int hiResX, hiResY;
  66577. this->interpolator.next (hiResX, hiResY);
  66578. hiResX += pixelOffsetInt;
  66579. hiResY += pixelOffsetInt;
  66580. int loResX = hiResX >> 8;
  66581. int loResY = hiResY >> 8;
  66582. if (repeatPattern)
  66583. {
  66584. loResX = safeModulo (loResX, srcData.width);
  66585. loResY = safeModulo (loResY, srcData.height);
  66586. }
  66587. if (betterQuality
  66588. && ((unsigned int) loResX) < (unsigned int) maxX
  66589. && ((unsigned int) loResY) < (unsigned int) maxY)
  66590. {
  66591. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  66592. hiResX &= 255;
  66593. hiResY &= 255;
  66594. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  66595. uint32 weight = (256 - hiResX) * (256 - hiResY);
  66596. c[0] += weight * src[0];
  66597. c[1] += weight * src[1];
  66598. c[2] += weight * src[2];
  66599. c[3] += weight * src[3];
  66600. weight = hiResX * (256 - hiResY);
  66601. c[0] += weight * src[4];
  66602. c[1] += weight * src[5];
  66603. c[2] += weight * src[6];
  66604. c[3] += weight * src[7];
  66605. src += this->srcData.lineStride;
  66606. weight = (256 - hiResX) * hiResY;
  66607. c[0] += weight * src[0];
  66608. c[1] += weight * src[1];
  66609. c[2] += weight * src[2];
  66610. c[3] += weight * src[3];
  66611. weight = hiResX * hiResY;
  66612. c[0] += weight * src[4];
  66613. c[1] += weight * src[5];
  66614. c[2] += weight * src[6];
  66615. c[3] += weight * src[7];
  66616. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  66617. (uint8) (c[PixelARGB::indexR] >> 16),
  66618. (uint8) (c[PixelARGB::indexG] >> 16),
  66619. (uint8) (c[PixelARGB::indexB] >> 16));
  66620. }
  66621. else
  66622. {
  66623. if (! repeatPattern)
  66624. {
  66625. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  66626. if (loResX < 0) loResX = 0;
  66627. if (loResY < 0) loResY = 0;
  66628. if (loResX > maxX) loResX = maxX;
  66629. if (loResY > maxY) loResY = maxY;
  66630. }
  66631. dest->set (*(const PixelARGB*) this->srcData.getPixelPointer (loResX, loResY));
  66632. }
  66633. ++dest;
  66634. } while (--numPixels > 0);
  66635. }
  66636. void generate (PixelRGB* dest, const int x, int numPixels) throw()
  66637. {
  66638. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  66639. do
  66640. {
  66641. int hiResX, hiResY;
  66642. this->interpolator.next (hiResX, hiResY);
  66643. hiResX += pixelOffsetInt;
  66644. hiResY += pixelOffsetInt;
  66645. int loResX = hiResX >> 8;
  66646. int loResY = hiResY >> 8;
  66647. if (repeatPattern)
  66648. {
  66649. loResX = safeModulo (loResX, srcData.width);
  66650. loResY = safeModulo (loResY, srcData.height);
  66651. }
  66652. if (betterQuality
  66653. && ((unsigned int) loResX) < (unsigned int) maxX
  66654. && ((unsigned int) loResY) < (unsigned int) maxY)
  66655. {
  66656. uint32 c[3] = { 256 * 128, 256 * 128, 256 * 128 };
  66657. hiResX &= 255;
  66658. hiResY &= 255;
  66659. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  66660. unsigned int weight = (256 - hiResX) * (256 - hiResY);
  66661. c[0] += weight * src[0];
  66662. c[1] += weight * src[1];
  66663. c[2] += weight * src[2];
  66664. weight = hiResX * (256 - hiResY);
  66665. c[0] += weight * src[3];
  66666. c[1] += weight * src[4];
  66667. c[2] += weight * src[5];
  66668. src += this->srcData.lineStride;
  66669. weight = (256 - hiResX) * hiResY;
  66670. c[0] += weight * src[0];
  66671. c[1] += weight * src[1];
  66672. c[2] += weight * src[2];
  66673. weight = hiResX * hiResY;
  66674. c[0] += weight * src[3];
  66675. c[1] += weight * src[4];
  66676. c[2] += weight * src[5];
  66677. dest->setARGB ((uint8) 255,
  66678. (uint8) (c[PixelRGB::indexR] >> 16),
  66679. (uint8) (c[PixelRGB::indexG] >> 16),
  66680. (uint8) (c[PixelRGB::indexB] >> 16));
  66681. }
  66682. else
  66683. {
  66684. if (! repeatPattern)
  66685. {
  66686. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  66687. if (loResX < 0) loResX = 0;
  66688. if (loResY < 0) loResY = 0;
  66689. if (loResX > maxX) loResX = maxX;
  66690. if (loResY > maxY) loResY = maxY;
  66691. }
  66692. dest->set (*(const PixelRGB*) this->srcData.getPixelPointer (loResX, loResY));
  66693. }
  66694. ++dest;
  66695. } while (--numPixels > 0);
  66696. }
  66697. void generate (PixelAlpha* dest, const int x, int numPixels) throw()
  66698. {
  66699. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  66700. do
  66701. {
  66702. int hiResX, hiResY;
  66703. this->interpolator.next (hiResX, hiResY);
  66704. hiResX += pixelOffsetInt;
  66705. hiResY += pixelOffsetInt;
  66706. int loResX = hiResX >> 8;
  66707. int loResY = hiResY >> 8;
  66708. if (repeatPattern)
  66709. {
  66710. loResX = safeModulo (loResX, srcData.width);
  66711. loResY = safeModulo (loResY, srcData.height);
  66712. }
  66713. if (betterQuality
  66714. && ((unsigned int) loResX) < (unsigned int) maxX
  66715. && ((unsigned int) loResY) < (unsigned int) maxY)
  66716. {
  66717. hiResX &= 255;
  66718. hiResY &= 255;
  66719. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  66720. uint32 c = 256 * 128;
  66721. c += src[0] * ((256 - hiResX) * (256 - hiResY));
  66722. c += src[1] * (hiResX * (256 - hiResY));
  66723. src += this->srcData.lineStride;
  66724. c += src[0] * ((256 - hiResX) * hiResY);
  66725. c += src[1] * (hiResX * hiResY);
  66726. *((uint8*) dest) = (uint8) c;
  66727. }
  66728. else
  66729. {
  66730. if (! repeatPattern)
  66731. {
  66732. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  66733. if (loResX < 0) loResX = 0;
  66734. if (loResY < 0) loResY = 0;
  66735. if (loResX > maxX) loResX = maxX;
  66736. if (loResY > maxY) loResY = maxY;
  66737. }
  66738. *((uint8*) dest) = *(this->srcData.getPixelPointer (loResX, loResY));
  66739. }
  66740. ++dest;
  66741. } while (--numPixels > 0);
  66742. }
  66743. class TransformedImageSpanInterpolator
  66744. {
  66745. public:
  66746. TransformedImageSpanInterpolator (const AffineTransform& transform) throw()
  66747. : inverseTransform (transform.inverted())
  66748. {}
  66749. void setStartOfLine (float x, float y, const int numPixels) throw()
  66750. {
  66751. float x1 = x, y1 = y;
  66752. x += numPixels;
  66753. inverseTransform.transformPoints (x1, y1, x, y);
  66754. xBresenham.set ((int) (x1 * 256.0f), (int) (x * 256.0f), numPixels);
  66755. yBresenham.set ((int) (y1 * 256.0f), (int) (y * 256.0f), numPixels);
  66756. }
  66757. void next (int& x, int& y) throw()
  66758. {
  66759. x = xBresenham.n;
  66760. xBresenham.stepToNext();
  66761. y = yBresenham.n;
  66762. yBresenham.stepToNext();
  66763. }
  66764. private:
  66765. class BresenhamInterpolator
  66766. {
  66767. public:
  66768. BresenhamInterpolator() throw() {}
  66769. void set (const int n1, const int n2, const int numSteps_) throw()
  66770. {
  66771. numSteps = jmax (1, numSteps_);
  66772. step = (n2 - n1) / numSteps;
  66773. remainder = modulo = (n2 - n1) % numSteps;
  66774. n = n1;
  66775. if (modulo <= 0)
  66776. {
  66777. modulo += numSteps;
  66778. remainder += numSteps;
  66779. --step;
  66780. }
  66781. modulo -= numSteps;
  66782. }
  66783. forcedinline void stepToNext() throw()
  66784. {
  66785. modulo += remainder;
  66786. n += step;
  66787. if (modulo > 0)
  66788. {
  66789. modulo -= numSteps;
  66790. ++n;
  66791. }
  66792. }
  66793. int n;
  66794. private:
  66795. int numSteps, step, modulo, remainder;
  66796. };
  66797. const AffineTransform inverseTransform;
  66798. BresenhamInterpolator xBresenham, yBresenham;
  66799. TransformedImageSpanInterpolator (const TransformedImageSpanInterpolator&);
  66800. TransformedImageSpanInterpolator& operator= (const TransformedImageSpanInterpolator&);
  66801. };
  66802. TransformedImageSpanInterpolator interpolator;
  66803. const Image::BitmapData& destData;
  66804. const Image::BitmapData& srcData;
  66805. const int extraAlpha;
  66806. const bool betterQuality;
  66807. const float pixelOffset;
  66808. const int pixelOffsetInt, maxX, maxY;
  66809. int y;
  66810. DestPixelType* linePixels;
  66811. HeapBlock <SrcPixelType> scratchBuffer;
  66812. int scratchSize;
  66813. TransformedImageFillEdgeTableRenderer (const TransformedImageFillEdgeTableRenderer&);
  66814. TransformedImageFillEdgeTableRenderer& operator= (const TransformedImageFillEdgeTableRenderer&);
  66815. };
  66816. class ClipRegionBase : public ReferenceCountedObject
  66817. {
  66818. public:
  66819. ClipRegionBase() {}
  66820. virtual ~ClipRegionBase() {}
  66821. typedef ReferenceCountedObjectPtr<ClipRegionBase> Ptr;
  66822. virtual const Ptr clone() const = 0;
  66823. virtual const Ptr applyClipTo (const Ptr& target) const = 0;
  66824. virtual const Ptr clipToRectangle (const Rectangle<int>& r) = 0;
  66825. virtual const Ptr clipToRectangleList (const RectangleList& r) = 0;
  66826. virtual const Ptr excludeClipRectangle (const Rectangle<int>& r) = 0;
  66827. virtual const Ptr clipToPath (const Path& p, const AffineTransform& transform) = 0;
  66828. virtual const Ptr clipToEdgeTable (const EdgeTable& et) = 0;
  66829. virtual const Ptr clipToImageAlpha (const Image& image, const Rectangle<int>& srcClip, const AffineTransform& t, const bool betterQuality) = 0;
  66830. virtual bool clipRegionIntersects (const Rectangle<int>& r) const = 0;
  66831. virtual const Rectangle<int> getClipBounds() const = 0;
  66832. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const = 0;
  66833. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const = 0;
  66834. virtual void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const = 0;
  66835. virtual void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const = 0;
  66836. virtual void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& t, bool betterQuality, bool tiledFill) const = 0;
  66837. virtual void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const = 0;
  66838. protected:
  66839. template <class Iterator>
  66840. static void renderImageTransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData,
  66841. const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill)
  66842. {
  66843. switch (destData.pixelFormat)
  66844. {
  66845. case Image::ARGB:
  66846. switch (srcData.pixelFormat)
  66847. {
  66848. case Image::ARGB:
  66849. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66850. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66851. break;
  66852. case Image::RGB:
  66853. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66854. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66855. break;
  66856. default:
  66857. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66858. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66859. break;
  66860. }
  66861. break;
  66862. case Image::RGB:
  66863. switch (srcData.pixelFormat)
  66864. {
  66865. case Image::ARGB:
  66866. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66867. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66868. break;
  66869. case Image::RGB:
  66870. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66871. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66872. break;
  66873. default:
  66874. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66875. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66876. break;
  66877. }
  66878. break;
  66879. default:
  66880. switch (srcData.pixelFormat)
  66881. {
  66882. case Image::ARGB:
  66883. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66884. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66885. break;
  66886. case Image::RGB:
  66887. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66888. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66889. break;
  66890. default:
  66891. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66892. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  66893. break;
  66894. }
  66895. break;
  66896. }
  66897. }
  66898. template <class Iterator>
  66899. static void renderImageUntransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill)
  66900. {
  66901. switch (destData.pixelFormat)
  66902. {
  66903. case Image::ARGB:
  66904. switch (srcData.pixelFormat)
  66905. {
  66906. case Image::ARGB:
  66907. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66908. else { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66909. break;
  66910. case Image::RGB:
  66911. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66912. else { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66913. break;
  66914. default:
  66915. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66916. else { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66917. break;
  66918. }
  66919. break;
  66920. case Image::RGB:
  66921. switch (srcData.pixelFormat)
  66922. {
  66923. case Image::ARGB:
  66924. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66925. else { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66926. break;
  66927. case Image::RGB:
  66928. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66929. else { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66930. break;
  66931. default:
  66932. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66933. else { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66934. break;
  66935. }
  66936. break;
  66937. default:
  66938. switch (srcData.pixelFormat)
  66939. {
  66940. case Image::ARGB:
  66941. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66942. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66943. break;
  66944. case Image::RGB:
  66945. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66946. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66947. break;
  66948. default:
  66949. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66950. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  66951. break;
  66952. }
  66953. break;
  66954. }
  66955. }
  66956. template <class Iterator, class DestPixelType>
  66957. static void renderSolidFill (Iterator& iter, const Image::BitmapData& destData, const PixelARGB& fillColour, const bool replaceContents, DestPixelType*)
  66958. {
  66959. jassert (destData.pixelStride == sizeof (DestPixelType));
  66960. if (replaceContents)
  66961. {
  66962. SolidColourEdgeTableRenderer <DestPixelType, true> r (destData, fillColour);
  66963. iter.iterate (r);
  66964. }
  66965. else
  66966. {
  66967. SolidColourEdgeTableRenderer <DestPixelType, false> r (destData, fillColour);
  66968. iter.iterate (r);
  66969. }
  66970. }
  66971. template <class Iterator, class DestPixelType>
  66972. static void renderGradient (Iterator& iter, const Image::BitmapData& destData, const ColourGradient& g, const AffineTransform& transform,
  66973. const PixelARGB* const lookupTable, const int numLookupEntries, const bool isIdentity, DestPixelType*)
  66974. {
  66975. jassert (destData.pixelStride == sizeof (DestPixelType));
  66976. if (g.isRadial)
  66977. {
  66978. if (isIdentity)
  66979. {
  66980. GradientEdgeTableRenderer <DestPixelType, RadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  66981. iter.iterate (renderer);
  66982. }
  66983. else
  66984. {
  66985. GradientEdgeTableRenderer <DestPixelType, TransformedRadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  66986. iter.iterate (renderer);
  66987. }
  66988. }
  66989. else
  66990. {
  66991. GradientEdgeTableRenderer <DestPixelType, LinearGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  66992. iter.iterate (renderer);
  66993. }
  66994. }
  66995. };
  66996. class ClipRegion_EdgeTable : public ClipRegionBase
  66997. {
  66998. public:
  66999. ClipRegion_EdgeTable (const EdgeTable& e) : edgeTable (e) {}
  67000. ClipRegion_EdgeTable (const Rectangle<int>& r) : edgeTable (r) {}
  67001. ClipRegion_EdgeTable (const Rectangle<float>& r) : edgeTable (r) {}
  67002. ClipRegion_EdgeTable (const RectangleList& r) : edgeTable (r) {}
  67003. ClipRegion_EdgeTable (const Rectangle<int>& bounds, const Path& p, const AffineTransform& t) : edgeTable (bounds, p, t) {}
  67004. ClipRegion_EdgeTable (const ClipRegion_EdgeTable& other) : edgeTable (other.edgeTable) {}
  67005. ~ClipRegion_EdgeTable() {}
  67006. const Ptr clone() const
  67007. {
  67008. return new ClipRegion_EdgeTable (*this);
  67009. }
  67010. const Ptr applyClipTo (const Ptr& target) const
  67011. {
  67012. return target->clipToEdgeTable (edgeTable);
  67013. }
  67014. const Ptr clipToRectangle (const Rectangle<int>& r)
  67015. {
  67016. edgeTable.clipToRectangle (r);
  67017. return edgeTable.isEmpty() ? 0 : this;
  67018. }
  67019. const Ptr clipToRectangleList (const RectangleList& r)
  67020. {
  67021. RectangleList inverse (edgeTable.getMaximumBounds());
  67022. if (inverse.subtract (r))
  67023. for (RectangleList::Iterator iter (inverse); iter.next();)
  67024. edgeTable.excludeRectangle (*iter.getRectangle());
  67025. return edgeTable.isEmpty() ? 0 : this;
  67026. }
  67027. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  67028. {
  67029. edgeTable.excludeRectangle (r);
  67030. return edgeTable.isEmpty() ? 0 : this;
  67031. }
  67032. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  67033. {
  67034. EdgeTable et (edgeTable.getMaximumBounds(), p, transform);
  67035. edgeTable.clipToEdgeTable (et);
  67036. return edgeTable.isEmpty() ? 0 : this;
  67037. }
  67038. const Ptr clipToEdgeTable (const EdgeTable& et)
  67039. {
  67040. edgeTable.clipToEdgeTable (et);
  67041. return edgeTable.isEmpty() ? 0 : this;
  67042. }
  67043. const Ptr clipToImageAlpha (const Image& image, const Rectangle<int>& srcClip, const AffineTransform& transform, const bool betterQuality)
  67044. {
  67045. const Image::BitmapData srcData (image, srcClip.getX(), srcClip.getY(), srcClip.getWidth(), srcClip.getHeight());
  67046. if (transform.isOnlyTranslation())
  67047. {
  67048. // If our translation doesn't involve any distortion, just use a simple blit..
  67049. const int tx = (int) (transform.getTranslationX() * 256.0f);
  67050. const int ty = (int) (transform.getTranslationY() * 256.0f);
  67051. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  67052. {
  67053. const int imageX = ((tx + 128) >> 8);
  67054. const int imageY = ((ty + 128) >> 8);
  67055. if (image.getFormat() == Image::ARGB)
  67056. straightClipImage (srcData, imageX, imageY, (PixelARGB*) 0);
  67057. else
  67058. straightClipImage (srcData, imageX, imageY, (PixelAlpha*) 0);
  67059. return edgeTable.isEmpty() ? 0 : this;
  67060. }
  67061. }
  67062. if (transform.isSingularity())
  67063. return 0;
  67064. {
  67065. Path p;
  67066. p.addRectangle (0, 0, (float) srcData.width, (float) srcData.height);
  67067. EdgeTable et2 (edgeTable.getMaximumBounds(), p, transform);
  67068. edgeTable.clipToEdgeTable (et2);
  67069. }
  67070. if (! edgeTable.isEmpty())
  67071. {
  67072. if (image.getFormat() == Image::ARGB)
  67073. transformedClipImage (srcData, transform, betterQuality, (PixelARGB*) 0);
  67074. else
  67075. transformedClipImage (srcData, transform, betterQuality, (PixelAlpha*) 0);
  67076. }
  67077. return edgeTable.isEmpty() ? 0 : this;
  67078. }
  67079. bool clipRegionIntersects (const Rectangle<int>& r) const
  67080. {
  67081. return edgeTable.getMaximumBounds().intersects (r);
  67082. }
  67083. const Rectangle<int> getClipBounds() const
  67084. {
  67085. return edgeTable.getMaximumBounds();
  67086. }
  67087. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  67088. {
  67089. const Rectangle<int> totalClip (edgeTable.getMaximumBounds());
  67090. const Rectangle<int> clipped (totalClip.getIntersection (area));
  67091. if (! clipped.isEmpty())
  67092. {
  67093. ClipRegion_EdgeTable et (clipped);
  67094. et.edgeTable.clipToEdgeTable (edgeTable);
  67095. et.fillAllWithColour (destData, colour, replaceContents);
  67096. }
  67097. }
  67098. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  67099. {
  67100. const Rectangle<float> totalClip (edgeTable.getMaximumBounds().toFloat());
  67101. const Rectangle<float> clipped (totalClip.getIntersection (area));
  67102. if (! clipped.isEmpty())
  67103. {
  67104. ClipRegion_EdgeTable et (clipped);
  67105. et.edgeTable.clipToEdgeTable (edgeTable);
  67106. et.fillAllWithColour (destData, colour, false);
  67107. }
  67108. }
  67109. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  67110. {
  67111. switch (destData.pixelFormat)
  67112. {
  67113. case Image::ARGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelARGB*) 0); break;
  67114. case Image::RGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelRGB*) 0); break;
  67115. default: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  67116. }
  67117. }
  67118. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  67119. {
  67120. HeapBlock <PixelARGB> lookupTable;
  67121. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  67122. jassert (numLookupEntries > 0);
  67123. switch (destData.pixelFormat)
  67124. {
  67125. case Image::ARGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  67126. case Image::RGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  67127. default: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  67128. }
  67129. }
  67130. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  67131. {
  67132. renderImageTransformedInternal (edgeTable, destData, srcData, alpha, transform, betterQuality, tiledFill);
  67133. }
  67134. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  67135. {
  67136. renderImageUntransformedInternal (edgeTable, destData, srcData, alpha, x, y, tiledFill);
  67137. }
  67138. EdgeTable edgeTable;
  67139. private:
  67140. template <class SrcPixelType>
  67141. void transformedClipImage (const Image::BitmapData& srcData, const AffineTransform& transform, const bool betterQuality, const SrcPixelType*)
  67142. {
  67143. TransformedImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, transform, 255, betterQuality);
  67144. for (int y = 0; y < edgeTable.getMaximumBounds().getHeight(); ++y)
  67145. renderer.clipEdgeTableLine (edgeTable, edgeTable.getMaximumBounds().getX(), y + edgeTable.getMaximumBounds().getY(),
  67146. edgeTable.getMaximumBounds().getWidth());
  67147. }
  67148. template <class SrcPixelType>
  67149. void straightClipImage (const Image::BitmapData& srcData, int imageX, int imageY, const SrcPixelType*)
  67150. {
  67151. Rectangle<int> r (imageX, imageY, srcData.width, srcData.height);
  67152. edgeTable.clipToRectangle (r);
  67153. ImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, 255, imageX, imageY);
  67154. for (int y = 0; y < r.getHeight(); ++y)
  67155. renderer.clipEdgeTableLine (edgeTable, r.getX(), y + r.getY(), r.getWidth());
  67156. }
  67157. ClipRegion_EdgeTable& operator= (const ClipRegion_EdgeTable&);
  67158. };
  67159. class ClipRegion_RectangleList : public ClipRegionBase
  67160. {
  67161. public:
  67162. ClipRegion_RectangleList (const Rectangle<int>& r) : clip (r) {}
  67163. ClipRegion_RectangleList (const RectangleList& r) : clip (r) {}
  67164. ClipRegion_RectangleList (const ClipRegion_RectangleList& other) : clip (other.clip) {}
  67165. ~ClipRegion_RectangleList() {}
  67166. const Ptr clone() const
  67167. {
  67168. return new ClipRegion_RectangleList (*this);
  67169. }
  67170. const Ptr applyClipTo (const Ptr& target) const
  67171. {
  67172. return target->clipToRectangleList (clip);
  67173. }
  67174. const Ptr clipToRectangle (const Rectangle<int>& r)
  67175. {
  67176. clip.clipTo (r);
  67177. return clip.isEmpty() ? 0 : this;
  67178. }
  67179. const Ptr clipToRectangleList (const RectangleList& r)
  67180. {
  67181. clip.clipTo (r);
  67182. return clip.isEmpty() ? 0 : this;
  67183. }
  67184. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  67185. {
  67186. clip.subtract (r);
  67187. return clip.isEmpty() ? 0 : this;
  67188. }
  67189. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  67190. {
  67191. return Ptr (new ClipRegion_EdgeTable (clip))->clipToPath (p, transform);
  67192. }
  67193. const Ptr clipToEdgeTable (const EdgeTable& et)
  67194. {
  67195. return Ptr (new ClipRegion_EdgeTable (clip))->clipToEdgeTable (et);
  67196. }
  67197. const Ptr clipToImageAlpha (const Image& image, const Rectangle<int>& srcClip, const AffineTransform& transform, const bool betterQuality)
  67198. {
  67199. return Ptr (new ClipRegion_EdgeTable (clip))->clipToImageAlpha (image, srcClip, transform, betterQuality);
  67200. }
  67201. bool clipRegionIntersects (const Rectangle<int>& r) const
  67202. {
  67203. return clip.intersects (r);
  67204. }
  67205. const Rectangle<int> getClipBounds() const
  67206. {
  67207. return clip.getBounds();
  67208. }
  67209. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  67210. {
  67211. SubRectangleIterator iter (clip, area);
  67212. switch (destData.pixelFormat)
  67213. {
  67214. case Image::ARGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelARGB*) 0); break;
  67215. case Image::RGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelRGB*) 0); break;
  67216. default: renderSolidFill (iter, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  67217. }
  67218. }
  67219. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  67220. {
  67221. SubRectangleIteratorFloat iter (clip, area);
  67222. switch (destData.pixelFormat)
  67223. {
  67224. case Image::ARGB: renderSolidFill (iter, destData, colour, false, (PixelARGB*) 0); break;
  67225. case Image::RGB: renderSolidFill (iter, destData, colour, false, (PixelRGB*) 0); break;
  67226. default: renderSolidFill (iter, destData, colour, false, (PixelAlpha*) 0); break;
  67227. }
  67228. }
  67229. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  67230. {
  67231. switch (destData.pixelFormat)
  67232. {
  67233. case Image::ARGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelARGB*) 0); break;
  67234. case Image::RGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelRGB*) 0); break;
  67235. default: renderSolidFill (*this, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  67236. }
  67237. }
  67238. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  67239. {
  67240. HeapBlock <PixelARGB> lookupTable;
  67241. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  67242. jassert (numLookupEntries > 0);
  67243. switch (destData.pixelFormat)
  67244. {
  67245. case Image::ARGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  67246. case Image::RGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  67247. default: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  67248. }
  67249. }
  67250. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  67251. {
  67252. renderImageTransformedInternal (*this, destData, srcData, alpha, transform, betterQuality, tiledFill);
  67253. }
  67254. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  67255. {
  67256. renderImageUntransformedInternal (*this, destData, srcData, alpha, x, y, tiledFill);
  67257. }
  67258. RectangleList clip;
  67259. template <class Renderer>
  67260. void iterate (Renderer& r) const throw()
  67261. {
  67262. RectangleList::Iterator iter (clip);
  67263. while (iter.next())
  67264. {
  67265. const Rectangle<int> rect (*iter.getRectangle());
  67266. const int x = rect.getX();
  67267. const int w = rect.getWidth();
  67268. jassert (w > 0);
  67269. const int bottom = rect.getBottom();
  67270. for (int y = rect.getY(); y < bottom; ++y)
  67271. {
  67272. r.setEdgeTableYPos (y);
  67273. r.handleEdgeTableLineFull (x, w);
  67274. }
  67275. }
  67276. }
  67277. private:
  67278. class SubRectangleIterator
  67279. {
  67280. public:
  67281. SubRectangleIterator (const RectangleList& clip_, const Rectangle<int>& area_)
  67282. : clip (clip_), area (area_)
  67283. {
  67284. }
  67285. template <class Renderer>
  67286. void iterate (Renderer& r) const throw()
  67287. {
  67288. RectangleList::Iterator iter (clip);
  67289. while (iter.next())
  67290. {
  67291. const Rectangle<int> rect (iter.getRectangle()->getIntersection (area));
  67292. if (! rect.isEmpty())
  67293. {
  67294. const int x = rect.getX();
  67295. const int w = rect.getWidth();
  67296. const int bottom = rect.getBottom();
  67297. for (int y = rect.getY(); y < bottom; ++y)
  67298. {
  67299. r.setEdgeTableYPos (y);
  67300. r.handleEdgeTableLineFull (x, w);
  67301. }
  67302. }
  67303. }
  67304. }
  67305. private:
  67306. const RectangleList& clip;
  67307. const Rectangle<int> area;
  67308. SubRectangleIterator (const SubRectangleIterator&);
  67309. SubRectangleIterator& operator= (const SubRectangleIterator&);
  67310. };
  67311. class SubRectangleIteratorFloat
  67312. {
  67313. public:
  67314. SubRectangleIteratorFloat (const RectangleList& clip_, const Rectangle<float>& area_)
  67315. : clip (clip_), area (area_)
  67316. {
  67317. }
  67318. template <class Renderer>
  67319. void iterate (Renderer& r) const throw()
  67320. {
  67321. int left = roundToInt (area.getX() * 256.0f);
  67322. int top = roundToInt (area.getY() * 256.0f);
  67323. int right = roundToInt (area.getRight() * 256.0f);
  67324. int bottom = roundToInt (area.getBottom() * 256.0f);
  67325. int totalTop, totalLeft, totalBottom, totalRight;
  67326. int topAlpha, leftAlpha, bottomAlpha, rightAlpha;
  67327. if ((top >> 8) == (bottom >> 8))
  67328. {
  67329. topAlpha = bottom - top;
  67330. bottomAlpha = 0;
  67331. totalTop = top >> 8;
  67332. totalBottom = bottom = top = totalTop + 1;
  67333. }
  67334. else
  67335. {
  67336. if ((top & 255) == 0)
  67337. {
  67338. topAlpha = 0;
  67339. top = totalTop = (top >> 8);
  67340. }
  67341. else
  67342. {
  67343. topAlpha = 255 - (top & 255);
  67344. totalTop = (top >> 8);
  67345. top = totalTop + 1;
  67346. }
  67347. bottomAlpha = bottom & 255;
  67348. bottom >>= 8;
  67349. totalBottom = bottom + (bottomAlpha != 0 ? 1 : 0);
  67350. }
  67351. if ((left >> 8) == (right >> 8))
  67352. {
  67353. leftAlpha = right - left;
  67354. rightAlpha = 0;
  67355. totalLeft = (left >> 8);
  67356. totalRight = right = left = totalLeft + 1;
  67357. }
  67358. else
  67359. {
  67360. if ((left & 255) == 0)
  67361. {
  67362. leftAlpha = 0;
  67363. left = totalLeft = (left >> 8);
  67364. }
  67365. else
  67366. {
  67367. leftAlpha = 255 - (left & 255);
  67368. totalLeft = (left >> 8);
  67369. left = totalLeft + 1;
  67370. }
  67371. rightAlpha = right & 255;
  67372. right >>= 8;
  67373. totalRight = right + (rightAlpha != 0 ? 1 : 0);
  67374. }
  67375. RectangleList::Iterator iter (clip);
  67376. while (iter.next())
  67377. {
  67378. const int clipLeft = iter.getRectangle()->getX();
  67379. const int clipRight = iter.getRectangle()->getRight();
  67380. const int clipTop = iter.getRectangle()->getY();
  67381. const int clipBottom = iter.getRectangle()->getBottom();
  67382. if (totalBottom > clipTop && totalTop < clipBottom && totalRight > clipLeft && totalLeft < clipRight)
  67383. {
  67384. if (right - left == 1 && leftAlpha + rightAlpha == 0) // special case for 1-pix vertical lines
  67385. {
  67386. if (topAlpha != 0 && totalTop >= clipTop)
  67387. {
  67388. r.setEdgeTableYPos (totalTop);
  67389. r.handleEdgeTablePixel (left, topAlpha);
  67390. }
  67391. const int endY = jmin (bottom, clipBottom);
  67392. for (int y = jmax (clipTop, top); y < endY; ++y)
  67393. {
  67394. r.setEdgeTableYPos (y);
  67395. r.handleEdgeTablePixelFull (left);
  67396. }
  67397. if (bottomAlpha != 0 && bottom < clipBottom)
  67398. {
  67399. r.setEdgeTableYPos (bottom);
  67400. r.handleEdgeTablePixel (left, bottomAlpha);
  67401. }
  67402. }
  67403. else
  67404. {
  67405. const int clippedLeft = jmax (left, clipLeft);
  67406. const int clippedWidth = jmin (right, clipRight) - clippedLeft;
  67407. const bool doLeftAlpha = leftAlpha != 0 && totalLeft >= clipLeft;
  67408. const bool doRightAlpha = rightAlpha != 0 && right < clipRight;
  67409. if (topAlpha != 0 && totalTop >= clipTop)
  67410. {
  67411. r.setEdgeTableYPos (totalTop);
  67412. if (doLeftAlpha)
  67413. r.handleEdgeTablePixel (totalLeft, (leftAlpha * topAlpha) >> 8);
  67414. if (clippedWidth > 0)
  67415. r.handleEdgeTableLine (clippedLeft, clippedWidth, topAlpha);
  67416. if (doRightAlpha)
  67417. r.handleEdgeTablePixel (right, (rightAlpha * topAlpha) >> 8);
  67418. }
  67419. const int endY = jmin (bottom, clipBottom);
  67420. for (int y = jmax (clipTop, top); y < endY; ++y)
  67421. {
  67422. r.setEdgeTableYPos (y);
  67423. if (doLeftAlpha)
  67424. r.handleEdgeTablePixel (totalLeft, leftAlpha);
  67425. if (clippedWidth > 0)
  67426. r.handleEdgeTableLineFull (clippedLeft, clippedWidth);
  67427. if (doRightAlpha)
  67428. r.handleEdgeTablePixel (right, rightAlpha);
  67429. }
  67430. if (bottomAlpha != 0 && bottom < clipBottom)
  67431. {
  67432. r.setEdgeTableYPos (bottom);
  67433. if (doLeftAlpha)
  67434. r.handleEdgeTablePixel (totalLeft, (leftAlpha * bottomAlpha) >> 8);
  67435. if (clippedWidth > 0)
  67436. r.handleEdgeTableLine (clippedLeft, clippedWidth, bottomAlpha);
  67437. if (doRightAlpha)
  67438. r.handleEdgeTablePixel (right, (rightAlpha * bottomAlpha) >> 8);
  67439. }
  67440. }
  67441. }
  67442. }
  67443. }
  67444. private:
  67445. const RectangleList& clip;
  67446. const Rectangle<float>& area;
  67447. SubRectangleIteratorFloat (const SubRectangleIteratorFloat&);
  67448. SubRectangleIteratorFloat& operator= (const SubRectangleIteratorFloat&);
  67449. };
  67450. ClipRegion_RectangleList& operator= (const ClipRegion_RectangleList&);
  67451. };
  67452. }
  67453. class LowLevelGraphicsSoftwareRenderer::SavedState
  67454. {
  67455. public:
  67456. SavedState (const Rectangle<int>& clip_, const int xOffset_, const int yOffset_)
  67457. : clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  67458. xOffset (xOffset_), yOffset (yOffset_), interpolationQuality (Graphics::mediumResamplingQuality)
  67459. {
  67460. }
  67461. SavedState (const RectangleList& clip_, const int xOffset_, const int yOffset_)
  67462. : clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  67463. xOffset (xOffset_), yOffset (yOffset_), interpolationQuality (Graphics::mediumResamplingQuality)
  67464. {
  67465. }
  67466. SavedState (const SavedState& other)
  67467. : clip (other.clip), xOffset (other.xOffset), yOffset (other.yOffset), font (other.font),
  67468. fillType (other.fillType), interpolationQuality (other.interpolationQuality)
  67469. {
  67470. }
  67471. ~SavedState()
  67472. {
  67473. }
  67474. void setOrigin (const int x, const int y) throw()
  67475. {
  67476. xOffset += x;
  67477. yOffset += y;
  67478. }
  67479. bool clipToRectangle (const Rectangle<int>& r)
  67480. {
  67481. if (clip != 0)
  67482. {
  67483. cloneClipIfMultiplyReferenced();
  67484. clip = clip->clipToRectangle (r.translated (xOffset, yOffset));
  67485. }
  67486. return clip != 0;
  67487. }
  67488. bool clipToRectangleList (const RectangleList& r)
  67489. {
  67490. if (clip != 0)
  67491. {
  67492. cloneClipIfMultiplyReferenced();
  67493. RectangleList offsetList (r);
  67494. offsetList.offsetAll (xOffset, yOffset);
  67495. clip = clip->clipToRectangleList (offsetList);
  67496. }
  67497. return clip != 0;
  67498. }
  67499. bool excludeClipRectangle (const Rectangle<int>& r)
  67500. {
  67501. if (clip != 0)
  67502. {
  67503. cloneClipIfMultiplyReferenced();
  67504. clip = clip->excludeClipRectangle (r.translated (xOffset, yOffset));
  67505. }
  67506. return clip != 0;
  67507. }
  67508. void clipToPath (const Path& p, const AffineTransform& transform)
  67509. {
  67510. if (clip != 0)
  67511. {
  67512. cloneClipIfMultiplyReferenced();
  67513. clip = clip->clipToPath (p, transform.translated ((float) xOffset, (float) yOffset));
  67514. }
  67515. }
  67516. void clipToImageAlpha (const Image& image, const Rectangle<int>& srcClip, const AffineTransform& t)
  67517. {
  67518. if (clip != 0)
  67519. {
  67520. if (image.hasAlphaChannel())
  67521. {
  67522. cloneClipIfMultiplyReferenced();
  67523. clip = clip->clipToImageAlpha (image, srcClip, t.translated ((float) xOffset, (float) yOffset),
  67524. interpolationQuality != Graphics::lowResamplingQuality);
  67525. }
  67526. else
  67527. {
  67528. Path p;
  67529. p.addRectangle (srcClip);
  67530. clipToPath (p, t);
  67531. }
  67532. }
  67533. }
  67534. bool clipRegionIntersects (const Rectangle<int>& r) const
  67535. {
  67536. return clip != 0 && clip->clipRegionIntersects (r.translated (xOffset, yOffset));
  67537. }
  67538. const Rectangle<int> getClipBounds() const
  67539. {
  67540. return clip == 0 ? Rectangle<int>() : clip->getClipBounds().translated (-xOffset, -yOffset);
  67541. }
  67542. void fillRect (Image& image, const Rectangle<int>& r, const bool replaceContents)
  67543. {
  67544. if (clip != 0)
  67545. {
  67546. if (fillType.isColour())
  67547. {
  67548. Image::BitmapData destData (image, 0, 0, image.getWidth(), image.getHeight(), true);
  67549. clip->fillRectWithColour (destData, r.translated (xOffset, yOffset), fillType.colour.getPixelARGB(), replaceContents);
  67550. }
  67551. else
  67552. {
  67553. const Rectangle<int> totalClip (clip->getClipBounds());
  67554. const Rectangle<int> clipped (totalClip.getIntersection (r.translated (xOffset, yOffset)));
  67555. if (! clipped.isEmpty())
  67556. fillShape (image, new SoftwareRendererClasses::ClipRegion_RectangleList (clipped), false);
  67557. }
  67558. }
  67559. }
  67560. void fillRect (Image& image, const Rectangle<float>& r)
  67561. {
  67562. if (clip != 0)
  67563. {
  67564. if (fillType.isColour())
  67565. {
  67566. Image::BitmapData destData (image, 0, 0, image.getWidth(), image.getHeight(), true);
  67567. clip->fillRectWithColour (destData, r.translated ((float) xOffset, (float) yOffset), fillType.colour.getPixelARGB());
  67568. }
  67569. else
  67570. {
  67571. const Rectangle<float> totalClip (clip->getClipBounds().toFloat());
  67572. const Rectangle<float> clipped (totalClip.getIntersection (r.translated ((float) xOffset, (float) yOffset)));
  67573. if (! clipped.isEmpty())
  67574. fillShape (image, new SoftwareRendererClasses::ClipRegion_EdgeTable (clipped), false);
  67575. }
  67576. }
  67577. }
  67578. void fillPath (Image& image, const Path& path, const AffineTransform& transform)
  67579. {
  67580. if (clip != 0)
  67581. fillShape (image, new SoftwareRendererClasses::ClipRegion_EdgeTable (clip->getClipBounds(), path, transform.translated ((float) xOffset, (float) yOffset)), false);
  67582. }
  67583. void fillEdgeTable (Image& image, const EdgeTable& edgeTable, const float x, const int y)
  67584. {
  67585. if (clip != 0)
  67586. {
  67587. SoftwareRendererClasses::ClipRegion_EdgeTable* edgeTableClip = new SoftwareRendererClasses::ClipRegion_EdgeTable (edgeTable);
  67588. SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill (edgeTableClip);
  67589. edgeTableClip->edgeTable.translate (x + xOffset, y + yOffset);
  67590. fillShape (image, shapeToFill, false);
  67591. }
  67592. }
  67593. void fillShape (Image& image, SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill, const bool replaceContents)
  67594. {
  67595. jassert (clip != 0);
  67596. shapeToFill = clip->applyClipTo (shapeToFill);
  67597. if (shapeToFill != 0)
  67598. {
  67599. Image::BitmapData destData (image, 0, 0, image.getWidth(), image.getHeight(), true);
  67600. if (fillType.isGradient())
  67601. {
  67602. jassert (! replaceContents); // that option is just for solid colours
  67603. ColourGradient g2 (*(fillType.gradient));
  67604. g2.multiplyOpacity (fillType.getOpacity());
  67605. g2.point1.addXY (-0.5f, -0.5f);
  67606. g2.point2.addXY (-0.5f, -0.5f);
  67607. AffineTransform transform (fillType.transform.translated ((float) xOffset, (float) yOffset));
  67608. const bool isIdentity = transform.isOnlyTranslation();
  67609. if (isIdentity)
  67610. {
  67611. // If our translation doesn't involve any distortion, we can speed it up..
  67612. g2.point1.applyTransform (transform);
  67613. g2.point2.applyTransform (transform);
  67614. transform = AffineTransform::identity;
  67615. }
  67616. shapeToFill->fillAllWithGradient (destData, g2, transform, isIdentity);
  67617. }
  67618. else if (fillType.isTiledImage())
  67619. {
  67620. renderImage (image, fillType.image, fillType.image.getBounds(), fillType.transform, shapeToFill);
  67621. }
  67622. else
  67623. {
  67624. shapeToFill->fillAllWithColour (destData, fillType.colour.getPixelARGB(), replaceContents);
  67625. }
  67626. }
  67627. }
  67628. void renderImage (Image& destImage, const Image& sourceImage, const Rectangle<int>& srcClip,
  67629. const AffineTransform& t, const SoftwareRendererClasses::ClipRegionBase* const tiledFillClipRegion)
  67630. {
  67631. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  67632. const Image::BitmapData destData (destImage, 0, 0, destImage.getWidth(), destImage.getHeight(), true);
  67633. const Image::BitmapData srcData (sourceImage, srcClip.getX(), srcClip.getY(), srcClip.getWidth(), srcClip.getHeight());
  67634. const int alpha = fillType.colour.getAlpha();
  67635. const bool betterQuality = (interpolationQuality != Graphics::lowResamplingQuality);
  67636. if (transform.isOnlyTranslation())
  67637. {
  67638. // If our translation doesn't involve any distortion, just use a simple blit..
  67639. int tx = (int) (transform.getTranslationX() * 256.0f);
  67640. int ty = (int) (transform.getTranslationY() * 256.0f);
  67641. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  67642. {
  67643. tx = ((tx + 128) >> 8);
  67644. ty = ((ty + 128) >> 8);
  67645. if (tiledFillClipRegion != 0)
  67646. {
  67647. tiledFillClipRegion->renderImageUntransformed (destData, srcData, alpha, tx, ty, true);
  67648. }
  67649. else
  67650. {
  67651. SoftwareRendererClasses::ClipRegionBase::Ptr c (new SoftwareRendererClasses::ClipRegion_EdgeTable (Rectangle<int> (tx, ty, srcClip.getWidth(), srcClip.getHeight()).getIntersection (destImage.getBounds())));
  67652. c = clip->applyClipTo (c);
  67653. if (c != 0)
  67654. c->renderImageUntransformed (destData, srcData, alpha, tx, ty, false);
  67655. }
  67656. return;
  67657. }
  67658. }
  67659. if (transform.isSingularity())
  67660. return;
  67661. if (tiledFillClipRegion != 0)
  67662. {
  67663. tiledFillClipRegion->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, true);
  67664. }
  67665. else
  67666. {
  67667. Path p;
  67668. p.addRectangle (srcClip);
  67669. SoftwareRendererClasses::ClipRegionBase::Ptr c (clip->clone());
  67670. c = c->clipToPath (p, transform);
  67671. if (c != 0)
  67672. c->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, false);
  67673. }
  67674. }
  67675. SoftwareRendererClasses::ClipRegionBase::Ptr clip;
  67676. int xOffset, yOffset;
  67677. Font font;
  67678. FillType fillType;
  67679. Graphics::ResamplingQuality interpolationQuality;
  67680. private:
  67681. void cloneClipIfMultiplyReferenced()
  67682. {
  67683. if (clip->getReferenceCount() > 1)
  67684. clip = clip->clone();
  67685. }
  67686. SavedState& operator= (const SavedState&);
  67687. };
  67688. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_)
  67689. : image (image_)
  67690. {
  67691. currentState = new SavedState (image_.getBounds(), 0, 0);
  67692. }
  67693. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_, const int xOffset, const int yOffset,
  67694. const RectangleList& initialClip)
  67695. : image (image_)
  67696. {
  67697. currentState = new SavedState (initialClip, xOffset, yOffset);
  67698. }
  67699. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  67700. {
  67701. }
  67702. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  67703. {
  67704. return false;
  67705. }
  67706. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  67707. {
  67708. currentState->setOrigin (x, y);
  67709. }
  67710. bool LowLevelGraphicsSoftwareRenderer::clipToRectangle (const Rectangle<int>& r)
  67711. {
  67712. return currentState->clipToRectangle (r);
  67713. }
  67714. bool LowLevelGraphicsSoftwareRenderer::clipToRectangleList (const RectangleList& clipRegion)
  67715. {
  67716. return currentState->clipToRectangleList (clipRegion);
  67717. }
  67718. void LowLevelGraphicsSoftwareRenderer::excludeClipRectangle (const Rectangle<int>& r)
  67719. {
  67720. currentState->excludeClipRectangle (r);
  67721. }
  67722. void LowLevelGraphicsSoftwareRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  67723. {
  67724. currentState->clipToPath (path, transform);
  67725. }
  67726. void LowLevelGraphicsSoftwareRenderer::clipToImageAlpha (const Image& sourceImage, const Rectangle<int>& srcClip, const AffineTransform& transform)
  67727. {
  67728. currentState->clipToImageAlpha (sourceImage, srcClip, transform);
  67729. }
  67730. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (const Rectangle<int>& r)
  67731. {
  67732. return currentState->clipRegionIntersects (r);
  67733. }
  67734. const Rectangle<int> LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  67735. {
  67736. return currentState->getClipBounds();
  67737. }
  67738. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  67739. {
  67740. return currentState->clip == 0;
  67741. }
  67742. void LowLevelGraphicsSoftwareRenderer::saveState()
  67743. {
  67744. stateStack.add (new SavedState (*currentState));
  67745. }
  67746. void LowLevelGraphicsSoftwareRenderer::restoreState()
  67747. {
  67748. SavedState* const top = stateStack.getLast();
  67749. if (top != 0)
  67750. {
  67751. currentState = top;
  67752. stateStack.removeLast (1, false);
  67753. }
  67754. else
  67755. {
  67756. jassertfalse; // trying to pop with an empty stack!
  67757. }
  67758. }
  67759. void LowLevelGraphicsSoftwareRenderer::setFill (const FillType& fillType)
  67760. {
  67761. currentState->fillType = fillType;
  67762. }
  67763. void LowLevelGraphicsSoftwareRenderer::setOpacity (float newOpacity)
  67764. {
  67765. currentState->fillType.setOpacity (newOpacity);
  67766. }
  67767. void LowLevelGraphicsSoftwareRenderer::setInterpolationQuality (Graphics::ResamplingQuality quality)
  67768. {
  67769. currentState->interpolationQuality = quality;
  67770. }
  67771. void LowLevelGraphicsSoftwareRenderer::fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  67772. {
  67773. currentState->fillRect (image, r, replaceExistingContents);
  67774. }
  67775. void LowLevelGraphicsSoftwareRenderer::fillPath (const Path& path, const AffineTransform& transform)
  67776. {
  67777. currentState->fillPath (image, path, transform);
  67778. }
  67779. void LowLevelGraphicsSoftwareRenderer::drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  67780. const AffineTransform& transform, const bool fillEntireClipAsTiles)
  67781. {
  67782. jassert (sourceImage.getBounds().contains (srcClip));
  67783. currentState->renderImage (image, sourceImage, srcClip, transform,
  67784. fillEntireClipAsTiles ? currentState->clip : 0);
  67785. }
  67786. void LowLevelGraphicsSoftwareRenderer::drawLine (const Line <float>& line)
  67787. {
  67788. Path p;
  67789. p.addLineSegment (line, 1.0f);
  67790. fillPath (p, AffineTransform::identity);
  67791. }
  67792. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, float top, float bottom)
  67793. {
  67794. if (bottom > top)
  67795. currentState->fillRect (image, Rectangle<float> ((float) x, top, 1.0f, bottom - top));
  67796. }
  67797. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, float left, float right)
  67798. {
  67799. if (right > left)
  67800. currentState->fillRect (image, Rectangle<float> (left, (float) y, right - left, 1.0f));
  67801. }
  67802. class LowLevelGraphicsSoftwareRenderer::CachedGlyph
  67803. {
  67804. public:
  67805. CachedGlyph() : glyph (0), lastAccessCount (0) {}
  67806. ~CachedGlyph() {}
  67807. void draw (SavedState& state, Image& image, const float x, const float y) const
  67808. {
  67809. if (edgeTable != 0)
  67810. state.fillEdgeTable (image, *edgeTable, x, roundToInt (y));
  67811. }
  67812. void generate (const Font& newFont, const int glyphNumber)
  67813. {
  67814. font = newFont;
  67815. glyph = glyphNumber;
  67816. edgeTable = 0;
  67817. Path glyphPath;
  67818. font.getTypeface()->getOutlineForGlyph (glyphNumber, glyphPath);
  67819. if (! glyphPath.isEmpty())
  67820. {
  67821. const float fontHeight = font.getHeight();
  67822. const AffineTransform transform (AffineTransform::scale (fontHeight * font.getHorizontalScale(), fontHeight)
  67823. .translated (0.0f, -0.5f));
  67824. edgeTable = new EdgeTable (glyphPath.getBoundsTransformed (transform).getSmallestIntegerContainer().expanded (1, 0),
  67825. glyphPath, transform);
  67826. }
  67827. }
  67828. int glyph, lastAccessCount;
  67829. Font font;
  67830. juce_UseDebuggingNewOperator
  67831. private:
  67832. ScopedPointer <EdgeTable> edgeTable;
  67833. CachedGlyph (const CachedGlyph&);
  67834. CachedGlyph& operator= (const CachedGlyph&);
  67835. };
  67836. class LowLevelGraphicsSoftwareRenderer::GlyphCache : private DeletedAtShutdown
  67837. {
  67838. public:
  67839. GlyphCache()
  67840. : accessCounter (0), hits (0), misses (0)
  67841. {
  67842. for (int i = 120; --i >= 0;)
  67843. glyphs.add (new CachedGlyph());
  67844. }
  67845. ~GlyphCache()
  67846. {
  67847. clearSingletonInstance();
  67848. }
  67849. juce_DeclareSingleton_SingleThreaded_Minimal (GlyphCache);
  67850. void drawGlyph (SavedState& state, Image& image, const Font& font, const int glyphNumber, float x, float y)
  67851. {
  67852. ++accessCounter;
  67853. int oldestCounter = std::numeric_limits<int>::max();
  67854. CachedGlyph* oldest = 0;
  67855. for (int i = glyphs.size(); --i >= 0;)
  67856. {
  67857. CachedGlyph* const glyph = glyphs.getUnchecked (i);
  67858. if (glyph->glyph == glyphNumber && glyph->font == font)
  67859. {
  67860. ++hits;
  67861. glyph->lastAccessCount = accessCounter;
  67862. glyph->draw (state, image, x, y);
  67863. return;
  67864. }
  67865. if (glyph->lastAccessCount <= oldestCounter)
  67866. {
  67867. oldestCounter = glyph->lastAccessCount;
  67868. oldest = glyph;
  67869. }
  67870. }
  67871. if (hits + ++misses > (glyphs.size() << 4))
  67872. {
  67873. if (misses * 2 > hits)
  67874. {
  67875. for (int i = 32; --i >= 0;)
  67876. glyphs.add (new CachedGlyph());
  67877. }
  67878. hits = misses = 0;
  67879. oldest = glyphs.getLast();
  67880. }
  67881. jassert (oldest != 0);
  67882. oldest->lastAccessCount = accessCounter;
  67883. oldest->generate (font, glyphNumber);
  67884. oldest->draw (state, image, x, y);
  67885. }
  67886. juce_UseDebuggingNewOperator
  67887. private:
  67888. friend class OwnedArray <CachedGlyph>;
  67889. OwnedArray <CachedGlyph> glyphs;
  67890. int accessCounter, hits, misses;
  67891. GlyphCache (const GlyphCache&);
  67892. GlyphCache& operator= (const GlyphCache&);
  67893. };
  67894. juce_ImplementSingleton_SingleThreaded (LowLevelGraphicsSoftwareRenderer::GlyphCache);
  67895. void LowLevelGraphicsSoftwareRenderer::setFont (const Font& newFont)
  67896. {
  67897. currentState->font = newFont;
  67898. }
  67899. const Font LowLevelGraphicsSoftwareRenderer::getFont()
  67900. {
  67901. return currentState->font;
  67902. }
  67903. void LowLevelGraphicsSoftwareRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  67904. {
  67905. Font& f = currentState->font;
  67906. if (transform.isOnlyTranslation())
  67907. {
  67908. GlyphCache::getInstance()->drawGlyph (*currentState, image, f, glyphNumber,
  67909. transform.getTranslationX(),
  67910. transform.getTranslationY());
  67911. }
  67912. else
  67913. {
  67914. Path p;
  67915. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  67916. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight()).followedBy (transform));
  67917. }
  67918. }
  67919. #if JUCE_MSVC
  67920. #pragma warning (pop)
  67921. #if JUCE_DEBUG
  67922. #pragma optimize ("", on) // resets optimisations to the project defaults
  67923. #endif
  67924. #endif
  67925. END_JUCE_NAMESPACE
  67926. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  67927. /*** Start of inlined file: juce_RectanglePlacement.cpp ***/
  67928. BEGIN_JUCE_NAMESPACE
  67929. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  67930. : flags (other.flags)
  67931. {
  67932. }
  67933. RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  67934. {
  67935. flags = other.flags;
  67936. return *this;
  67937. }
  67938. void RectanglePlacement::applyTo (double& x, double& y,
  67939. double& w, double& h,
  67940. const double dx, const double dy,
  67941. const double dw, const double dh) const throw()
  67942. {
  67943. if (w == 0 || h == 0)
  67944. return;
  67945. if ((flags & stretchToFit) != 0)
  67946. {
  67947. x = dx;
  67948. y = dy;
  67949. w = dw;
  67950. h = dh;
  67951. }
  67952. else
  67953. {
  67954. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  67955. : jmin (dw / w, dh / h);
  67956. if ((flags & onlyReduceInSize) != 0)
  67957. scale = jmin (scale, 1.0);
  67958. if ((flags & onlyIncreaseInSize) != 0)
  67959. scale = jmax (scale, 1.0);
  67960. w *= scale;
  67961. h *= scale;
  67962. if ((flags & xLeft) != 0)
  67963. x = dx;
  67964. else if ((flags & xRight) != 0)
  67965. x = dx + dw - w;
  67966. else
  67967. x = dx + (dw - w) * 0.5;
  67968. if ((flags & yTop) != 0)
  67969. y = dy;
  67970. else if ((flags & yBottom) != 0)
  67971. y = dy + dh - h;
  67972. else
  67973. y = dy + (dh - h) * 0.5;
  67974. }
  67975. }
  67976. const AffineTransform RectanglePlacement::getTransformToFit (float x, float y,
  67977. float w, float h,
  67978. const float dx, const float dy,
  67979. const float dw, const float dh) const throw()
  67980. {
  67981. if (w == 0 || h == 0)
  67982. return AffineTransform::identity;
  67983. const float scaleX = dw / w;
  67984. const float scaleY = dh / h;
  67985. if ((flags & stretchToFit) != 0)
  67986. return AffineTransform::translation (-x, -y)
  67987. .scaled (scaleX, scaleY)
  67988. .translated (dx, dy);
  67989. float scale = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  67990. : jmin (scaleX, scaleY);
  67991. if ((flags & onlyReduceInSize) != 0)
  67992. scale = jmin (scale, 1.0f);
  67993. if ((flags & onlyIncreaseInSize) != 0)
  67994. scale = jmax (scale, 1.0f);
  67995. w *= scale;
  67996. h *= scale;
  67997. float newX = dx;
  67998. if ((flags & xRight) != 0)
  67999. newX += dw - w; // right
  68000. else if ((flags & xLeft) == 0)
  68001. newX += (dw - w) / 2.0f; // centre
  68002. float newY = dy;
  68003. if ((flags & yBottom) != 0)
  68004. newY += dh - h; // bottom
  68005. else if ((flags & yTop) == 0)
  68006. newY += (dh - h) / 2.0f; // centre
  68007. return AffineTransform::translation (-x, -y)
  68008. .scaled (scale, scale)
  68009. .translated (newX, newY);
  68010. }
  68011. END_JUCE_NAMESPACE
  68012. /*** End of inlined file: juce_RectanglePlacement.cpp ***/
  68013. /*** Start of inlined file: juce_Drawable.cpp ***/
  68014. BEGIN_JUCE_NAMESPACE
  68015. Drawable::RenderingContext::RenderingContext (Graphics& g_,
  68016. const AffineTransform& transform_,
  68017. const float opacity_) throw()
  68018. : g (g_),
  68019. transform (transform_),
  68020. opacity (opacity_)
  68021. {
  68022. }
  68023. Drawable::Drawable()
  68024. : parent (0)
  68025. {
  68026. }
  68027. Drawable::~Drawable()
  68028. {
  68029. }
  68030. void Drawable::draw (Graphics& g, const float opacity, const AffineTransform& transform) const
  68031. {
  68032. render (RenderingContext (g, transform, opacity));
  68033. }
  68034. void Drawable::drawAt (Graphics& g, const float x, const float y, const float opacity) const
  68035. {
  68036. draw (g, opacity, AffineTransform::translation (x, y));
  68037. }
  68038. void Drawable::drawWithin (Graphics& g,
  68039. const int destX,
  68040. const int destY,
  68041. const int destW,
  68042. const int destH,
  68043. const RectanglePlacement& placement,
  68044. const float opacity) const
  68045. {
  68046. if (destW > 0 && destH > 0)
  68047. {
  68048. Rectangle<float> bounds (getBounds());
  68049. draw (g, opacity,
  68050. placement.getTransformToFit (bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(),
  68051. (float) destX, (float) destY,
  68052. (float) destW, (float) destH));
  68053. }
  68054. }
  68055. Drawable* Drawable::createFromImageData (const void* data, const size_t numBytes)
  68056. {
  68057. Drawable* result = 0;
  68058. Image image (ImageFileFormat::loadFrom (data, (int) numBytes));
  68059. if (image.isValid())
  68060. {
  68061. DrawableImage* const di = new DrawableImage();
  68062. di->setImage (image);
  68063. result = di;
  68064. }
  68065. else
  68066. {
  68067. const String asString (String::createStringFromData (data, (int) numBytes));
  68068. XmlDocument doc (asString);
  68069. ScopedPointer <XmlElement> outer (doc.getDocumentElement (true));
  68070. if (outer != 0 && outer->hasTagName ("svg"))
  68071. {
  68072. ScopedPointer <XmlElement> svg (doc.getDocumentElement());
  68073. if (svg != 0)
  68074. result = Drawable::createFromSVG (*svg);
  68075. }
  68076. }
  68077. return result;
  68078. }
  68079. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  68080. {
  68081. MemoryBlock mb;
  68082. dataSource.readIntoMemoryBlock (mb);
  68083. return createFromImageData (mb.getData(), mb.getSize());
  68084. }
  68085. Drawable* Drawable::createFromImageFile (const File& file)
  68086. {
  68087. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  68088. return fin != 0 ? createFromImageDataStream (*fin) : 0;
  68089. }
  68090. Drawable* Drawable::createFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  68091. {
  68092. return createChildFromValueTree (0, tree, imageProvider);
  68093. }
  68094. Drawable* Drawable::createChildFromValueTree (DrawableComposite* parent, const ValueTree& tree, ImageProvider* imageProvider)
  68095. {
  68096. const Identifier type (tree.getType());
  68097. Drawable* d = 0;
  68098. if (type == DrawablePath::valueTreeType)
  68099. d = new DrawablePath();
  68100. else if (type == DrawableComposite::valueTreeType)
  68101. d = new DrawableComposite();
  68102. else if (type == DrawableImage::valueTreeType)
  68103. d = new DrawableImage();
  68104. else if (type == DrawableText::valueTreeType)
  68105. d = new DrawableText();
  68106. if (d != 0)
  68107. {
  68108. d->parent = parent;
  68109. d->refreshFromValueTree (tree, imageProvider);
  68110. }
  68111. return d;
  68112. }
  68113. const Identifier Drawable::ValueTreeWrapperBase::idProperty ("id");
  68114. const Identifier Drawable::ValueTreeWrapperBase::type ("type");
  68115. const Identifier Drawable::ValueTreeWrapperBase::gradientPoint1 ("point1");
  68116. const Identifier Drawable::ValueTreeWrapperBase::gradientPoint2 ("point2");
  68117. const Identifier Drawable::ValueTreeWrapperBase::colour ("colour");
  68118. const Identifier Drawable::ValueTreeWrapperBase::radial ("radial");
  68119. const Identifier Drawable::ValueTreeWrapperBase::colours ("colours");
  68120. const Identifier Drawable::ValueTreeWrapperBase::imageId ("imageId");
  68121. const Identifier Drawable::ValueTreeWrapperBase::imageOpacity ("imageOpacity");
  68122. Drawable::ValueTreeWrapperBase::ValueTreeWrapperBase (const ValueTree& state_)
  68123. : state (state_)
  68124. {
  68125. }
  68126. Drawable::ValueTreeWrapperBase::~ValueTreeWrapperBase()
  68127. {
  68128. }
  68129. const String Drawable::ValueTreeWrapperBase::getID() const
  68130. {
  68131. return state [idProperty];
  68132. }
  68133. void Drawable::ValueTreeWrapperBase::setID (const String& newID, UndoManager* const undoManager)
  68134. {
  68135. if (newID.isEmpty())
  68136. state.removeProperty (idProperty, undoManager);
  68137. else
  68138. state.setProperty (idProperty, newID, undoManager);
  68139. }
  68140. const FillType Drawable::ValueTreeWrapperBase::readFillType (const ValueTree& v, RelativePoint* const gp1, RelativePoint* const gp2,
  68141. RelativeCoordinate::NamedCoordinateFinder* const nameFinder, ImageProvider* imageProvider)
  68142. {
  68143. const String newType (v[type].toString());
  68144. if (newType == "solid")
  68145. {
  68146. const String colourString (v [colour].toString());
  68147. return FillType (Colour (colourString.isEmpty() ? (uint32) 0xff000000
  68148. : (uint32) colourString.getHexValue32()));
  68149. }
  68150. else if (newType == "gradient")
  68151. {
  68152. RelativePoint p1 (v [gradientPoint1]), p2 (v [gradientPoint2]);
  68153. ColourGradient g;
  68154. if (gp1 != 0)
  68155. *gp1 = p1;
  68156. if (gp2 != 0)
  68157. *gp2 = p2;
  68158. g.point1 = p1.resolve (nameFinder);
  68159. g.point2 = p2.resolve (nameFinder);
  68160. g.isRadial = v[radial];
  68161. StringArray colourSteps;
  68162. colourSteps.addTokens (v[colours].toString(), false);
  68163. for (int i = 0; i < colourSteps.size() / 2; ++i)
  68164. g.addColour (colourSteps[i * 2].getDoubleValue(),
  68165. Colour ((uint32) colourSteps[i * 2 + 1].getHexValue32()));
  68166. return FillType (g);
  68167. }
  68168. else if (newType == "image")
  68169. {
  68170. Image im;
  68171. if (imageProvider != 0)
  68172. im = imageProvider->getImageForIdentifier (v[imageId]);
  68173. FillType f (im, AffineTransform::identity);
  68174. f.setOpacity ((float) v.getProperty (imageOpacity, 1.0f));
  68175. return f;
  68176. }
  68177. jassertfalse;
  68178. return FillType();
  68179. }
  68180. void Drawable::ValueTreeWrapperBase::writeFillType (ValueTree& v, const FillType& fillType,
  68181. const RelativePoint* const gp1, const RelativePoint* const gp2,
  68182. ImageProvider* imageProvider, UndoManager* const undoManager)
  68183. {
  68184. if (fillType.isColour())
  68185. {
  68186. v.setProperty (type, "solid", undoManager);
  68187. v.setProperty (colour, String::toHexString ((int) fillType.colour.getARGB()), undoManager);
  68188. }
  68189. else if (fillType.isGradient())
  68190. {
  68191. v.setProperty (type, "gradient", undoManager);
  68192. v.setProperty (gradientPoint1, gp1 != 0 ? gp1->toString() : fillType.gradient->point1.toString(), undoManager);
  68193. v.setProperty (gradientPoint2, gp2 != 0 ? gp2->toString() : fillType.gradient->point2.toString(), undoManager);
  68194. v.setProperty (radial, fillType.gradient->isRadial, undoManager);
  68195. String s;
  68196. for (int i = 0; i < fillType.gradient->getNumColours(); ++i)
  68197. s << ' ' << fillType.gradient->getColourPosition (i)
  68198. << ' ' << String::toHexString ((int) fillType.gradient->getColour(i).getARGB());
  68199. v.setProperty (colours, s.trimStart(), undoManager);
  68200. }
  68201. else if (fillType.isTiledImage())
  68202. {
  68203. v.setProperty (type, "image", undoManager);
  68204. if (imageProvider != 0)
  68205. v.setProperty (imageId, imageProvider->getIdentifierForImage (fillType.image), undoManager);
  68206. if (fillType.getOpacity() < 1.0f)
  68207. v.setProperty (imageOpacity, fillType.getOpacity(), undoManager);
  68208. else
  68209. v.removeProperty (imageOpacity, undoManager);
  68210. }
  68211. else
  68212. {
  68213. jassertfalse;
  68214. }
  68215. }
  68216. END_JUCE_NAMESPACE
  68217. /*** End of inlined file: juce_Drawable.cpp ***/
  68218. /*** Start of inlined file: juce_DrawableComposite.cpp ***/
  68219. BEGIN_JUCE_NAMESPACE
  68220. DrawableComposite::DrawableComposite()
  68221. : bounds (Point<float>(), Point<float> (100.0f, 0.0f), Point<float> (0.0f, 100.0f))
  68222. {
  68223. setContentArea (RelativeRectangle (RelativeCoordinate (0.0, true),
  68224. RelativeCoordinate (100.0, true),
  68225. RelativeCoordinate (0.0, false),
  68226. RelativeCoordinate (100.0, false)));
  68227. }
  68228. DrawableComposite::DrawableComposite (const DrawableComposite& other)
  68229. {
  68230. bounds = other.bounds;
  68231. for (int i = 0; i < other.drawables.size(); ++i)
  68232. drawables.add (other.drawables.getUnchecked(i)->createCopy());
  68233. markersX.addCopiesOf (other.markersX);
  68234. markersY.addCopiesOf (other.markersY);
  68235. }
  68236. DrawableComposite::~DrawableComposite()
  68237. {
  68238. }
  68239. void DrawableComposite::insertDrawable (Drawable* drawable, const int index)
  68240. {
  68241. if (drawable != 0)
  68242. {
  68243. jassert (! drawables.contains (drawable)); // trying to add a drawable that's already in here!
  68244. jassert (drawable->parent == 0); // A drawable can only live inside one parent at a time!
  68245. drawables.insert (index, drawable);
  68246. drawable->parent = this;
  68247. }
  68248. }
  68249. void DrawableComposite::insertDrawable (const Drawable& drawable, const int index)
  68250. {
  68251. insertDrawable (drawable.createCopy(), index);
  68252. }
  68253. void DrawableComposite::removeDrawable (const int index, const bool deleteDrawable)
  68254. {
  68255. drawables.remove (index, deleteDrawable);
  68256. }
  68257. Drawable* DrawableComposite::getDrawableWithName (const String& name) const throw()
  68258. {
  68259. for (int i = drawables.size(); --i >= 0;)
  68260. if (drawables.getUnchecked(i)->getName() == name)
  68261. return drawables.getUnchecked(i);
  68262. return 0;
  68263. }
  68264. void DrawableComposite::bringToFront (const int index)
  68265. {
  68266. if (index >= 0 && index < drawables.size() - 1)
  68267. drawables.move (index, -1);
  68268. }
  68269. void DrawableComposite::setBoundingBox (const RelativeParallelogram& newBoundingBox)
  68270. {
  68271. bounds = newBoundingBox;
  68272. }
  68273. DrawableComposite::Marker::Marker (const DrawableComposite::Marker& other)
  68274. : name (other.name), position (other.position)
  68275. {
  68276. }
  68277. DrawableComposite::Marker::Marker (const String& name_, const RelativeCoordinate& position_)
  68278. : name (name_), position (position_)
  68279. {
  68280. }
  68281. bool DrawableComposite::Marker::operator!= (const DrawableComposite::Marker& other) const throw()
  68282. {
  68283. return name != other.name || position != other.position;
  68284. }
  68285. const char* const DrawableComposite::contentLeftMarkerName ("left");
  68286. const char* const DrawableComposite::contentRightMarkerName ("right");
  68287. const char* const DrawableComposite::contentTopMarkerName ("top");
  68288. const char* const DrawableComposite::contentBottomMarkerName ("bottom");
  68289. const RelativeRectangle DrawableComposite::getContentArea() const
  68290. {
  68291. jassert (markersX.size() >= 2 && getMarker (true, 0)->name == contentLeftMarkerName && getMarker (true, 1)->name == contentRightMarkerName);
  68292. jassert (markersY.size() >= 2 && getMarker (false, 0)->name == contentTopMarkerName && getMarker (false, 1)->name == contentBottomMarkerName);
  68293. return RelativeRectangle (markersX.getUnchecked(0)->position, markersX.getUnchecked(1)->position,
  68294. markersY.getUnchecked(0)->position, markersY.getUnchecked(1)->position);
  68295. }
  68296. void DrawableComposite::setContentArea (const RelativeRectangle& newArea)
  68297. {
  68298. setMarker (contentLeftMarkerName, true, newArea.left);
  68299. setMarker (contentRightMarkerName, true, newArea.right);
  68300. setMarker (contentTopMarkerName, false, newArea.top);
  68301. setMarker (contentBottomMarkerName, false, newArea.bottom);
  68302. }
  68303. void DrawableComposite::resetBoundingBoxToContentArea()
  68304. {
  68305. const RelativeRectangle content (getContentArea());
  68306. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  68307. RelativePoint (content.right, content.top),
  68308. RelativePoint (content.left, content.bottom)));
  68309. }
  68310. void DrawableComposite::resetContentAreaAndBoundingBoxToFitChildren()
  68311. {
  68312. const Rectangle<float> bounds (getUntransformedBounds (false));
  68313. setContentArea (RelativeRectangle (RelativeCoordinate (bounds.getX(), true),
  68314. RelativeCoordinate (bounds.getRight(), true),
  68315. RelativeCoordinate (bounds.getY(), false),
  68316. RelativeCoordinate (bounds.getBottom(), false)));
  68317. resetBoundingBoxToContentArea();
  68318. }
  68319. int DrawableComposite::getNumMarkers (const bool xAxis) const throw()
  68320. {
  68321. return (xAxis ? markersX : markersY).size();
  68322. }
  68323. const DrawableComposite::Marker* DrawableComposite::getMarker (const bool xAxis, const int index) const throw()
  68324. {
  68325. return (xAxis ? markersX : markersY) [index];
  68326. }
  68327. void DrawableComposite::setMarker (const String& name, const bool xAxis, const RelativeCoordinate& position)
  68328. {
  68329. OwnedArray <Marker>& markers = (xAxis ? markersX : markersY);
  68330. for (int i = 0; i < markers.size(); ++i)
  68331. {
  68332. Marker* const m = markers.getUnchecked(i);
  68333. if (m->name == name)
  68334. {
  68335. if (m->position != position)
  68336. {
  68337. m->position = position;
  68338. invalidatePoints();
  68339. }
  68340. return;
  68341. }
  68342. }
  68343. (xAxis ? markersX : markersY).add (new Marker (name, position));
  68344. invalidatePoints();
  68345. }
  68346. void DrawableComposite::removeMarker (const bool xAxis, const int index)
  68347. {
  68348. jassert (index >= 2);
  68349. if (index >= 2)
  68350. (xAxis ? markersX : markersY).remove (index);
  68351. }
  68352. const AffineTransform DrawableComposite::calculateTransform() const
  68353. {
  68354. Point<float> resolved[3];
  68355. bounds.resolveThreePoints (resolved, parent);
  68356. const Rectangle<float> content (getContentArea().resolve (parent));
  68357. return AffineTransform::fromTargetPoints (content.getX(), content.getY(), resolved[0].getX(), resolved[0].getY(),
  68358. content.getRight(), content.getY(), resolved[1].getX(), resolved[1].getY(),
  68359. content.getX(), content.getBottom(), resolved[2].getX(), resolved[2].getY());
  68360. }
  68361. void DrawableComposite::render (const Drawable::RenderingContext& context) const
  68362. {
  68363. if (drawables.size() > 0 && context.opacity > 0)
  68364. {
  68365. if (context.opacity >= 1.0f || drawables.size() == 1)
  68366. {
  68367. Drawable::RenderingContext contextCopy (context);
  68368. contextCopy.transform = calculateTransform().followedBy (context.transform);
  68369. for (int i = 0; i < drawables.size(); ++i)
  68370. drawables.getUnchecked(i)->render (contextCopy);
  68371. }
  68372. else
  68373. {
  68374. // To correctly render a whole composite layer with an overall transparency,
  68375. // we need to render everything opaquely into a temp buffer, then blend that
  68376. // with the target opacity...
  68377. const Rectangle<int> clipBounds (context.g.getClipBounds());
  68378. Image tempImage (Image::ARGB, clipBounds.getWidth(), clipBounds.getHeight(), true);
  68379. {
  68380. Graphics tempG (tempImage);
  68381. tempG.setOrigin (-clipBounds.getX(), -clipBounds.getY());
  68382. Drawable::RenderingContext tempContext (tempG, context.transform, 1.0f);
  68383. render (tempContext);
  68384. }
  68385. context.g.setOpacity (context.opacity);
  68386. context.g.drawImageAt (tempImage, clipBounds.getX(), clipBounds.getY());
  68387. }
  68388. }
  68389. }
  68390. const RelativeCoordinate DrawableComposite::findNamedCoordinate (const String& objectName, const String& edge) const
  68391. {
  68392. if (objectName == RelativeCoordinate::Strings::parent)
  68393. {
  68394. if (edge == RelativeCoordinate::Strings::right)
  68395. {
  68396. jassertfalse; // a Drawable doesn't have a fixed right-hand edge - use a marker instead if you need a point of reference.
  68397. return RelativeCoordinate (100.0, true);
  68398. }
  68399. if (edge == RelativeCoordinate::Strings::bottom)
  68400. {
  68401. jassertfalse; // a Drawable doesn't have a fixed bottom edge - use a marker instead if you need a point of reference.
  68402. return RelativeCoordinate (100.0, false);
  68403. }
  68404. }
  68405. int i;
  68406. for (i = 0; i < markersX.size(); ++i)
  68407. {
  68408. Marker* const m = markersX.getUnchecked(i);
  68409. if (m->name == objectName)
  68410. return m->position;
  68411. }
  68412. for (i = 0; i < markersY.size(); ++i)
  68413. {
  68414. Marker* const m = markersY.getUnchecked(i);
  68415. if (m->name == objectName)
  68416. return m->position;
  68417. }
  68418. return RelativeCoordinate();
  68419. }
  68420. const Rectangle<float> DrawableComposite::getUntransformedBounds (const bool includeMarkers) const
  68421. {
  68422. Rectangle<float> bounds;
  68423. int i;
  68424. for (i = 0; i < drawables.size(); ++i)
  68425. bounds = bounds.getUnion (drawables.getUnchecked(i)->getBounds());
  68426. if (includeMarkers)
  68427. {
  68428. if (markersX.size() > 0)
  68429. {
  68430. float minX = std::numeric_limits<float>::max();
  68431. float maxX = std::numeric_limits<float>::min();
  68432. for (i = markersX.size(); --i >= 0;)
  68433. {
  68434. const Marker* m = markersX.getUnchecked(i);
  68435. const float pos = (float) m->position.resolve (parent);
  68436. minX = jmin (minX, pos);
  68437. maxX = jmax (maxX, pos);
  68438. }
  68439. if (minX <= maxX)
  68440. {
  68441. if (bounds.getHeight() > 0)
  68442. {
  68443. minX = jmin (minX, bounds.getX());
  68444. maxX = jmax (maxX, bounds.getRight());
  68445. }
  68446. bounds.setLeft (minX);
  68447. bounds.setWidth (maxX - minX);
  68448. }
  68449. }
  68450. if (markersY.size() > 0)
  68451. {
  68452. float minY = std::numeric_limits<float>::max();
  68453. float maxY = std::numeric_limits<float>::min();
  68454. for (i = markersY.size(); --i >= 0;)
  68455. {
  68456. const Marker* m = markersY.getUnchecked(i);
  68457. const float pos = (float) m->position.resolve (parent);
  68458. minY = jmin (minY, pos);
  68459. maxY = jmax (maxY, pos);
  68460. }
  68461. if (minY <= maxY)
  68462. {
  68463. if (bounds.getHeight() > 0)
  68464. {
  68465. minY = jmin (minY, bounds.getY());
  68466. maxY = jmax (maxY, bounds.getBottom());
  68467. }
  68468. bounds.setTop (minY);
  68469. bounds.setHeight (maxY - minY);
  68470. }
  68471. }
  68472. }
  68473. return bounds;
  68474. }
  68475. const Rectangle<float> DrawableComposite::getBounds() const
  68476. {
  68477. return getUntransformedBounds (true).transformed (calculateTransform());
  68478. }
  68479. bool DrawableComposite::hitTest (float x, float y) const
  68480. {
  68481. calculateTransform().inverted().transformPoint (x, y);
  68482. for (int i = 0; i < drawables.size(); ++i)
  68483. if (drawables.getUnchecked(i)->hitTest (x, y))
  68484. return true;
  68485. return false;
  68486. }
  68487. Drawable* DrawableComposite::createCopy() const
  68488. {
  68489. return new DrawableComposite (*this);
  68490. }
  68491. void DrawableComposite::invalidatePoints()
  68492. {
  68493. for (int i = 0; i < drawables.size(); ++i)
  68494. drawables.getUnchecked(i)->invalidatePoints();
  68495. }
  68496. const Identifier DrawableComposite::valueTreeType ("Group");
  68497. const Identifier DrawableComposite::ValueTreeWrapper::topLeft ("topLeft");
  68498. const Identifier DrawableComposite::ValueTreeWrapper::topRight ("topRight");
  68499. const Identifier DrawableComposite::ValueTreeWrapper::bottomLeft ("bottomLeft");
  68500. const Identifier DrawableComposite::ValueTreeWrapper::childGroupTag ("Drawables");
  68501. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagX ("MarkersX");
  68502. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagY ("MarkersY");
  68503. const Identifier DrawableComposite::ValueTreeWrapper::markerTag ("Marker");
  68504. const Identifier DrawableComposite::ValueTreeWrapper::nameProperty ("name");
  68505. const Identifier DrawableComposite::ValueTreeWrapper::posProperty ("position");
  68506. DrawableComposite::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  68507. : ValueTreeWrapperBase (state_)
  68508. {
  68509. jassert (state.hasType (valueTreeType));
  68510. }
  68511. ValueTree DrawableComposite::ValueTreeWrapper::getChildList() const
  68512. {
  68513. return state.getChildWithName (childGroupTag);
  68514. }
  68515. ValueTree DrawableComposite::ValueTreeWrapper::getChildListCreating (UndoManager* undoManager)
  68516. {
  68517. return state.getOrCreateChildWithName (childGroupTag, undoManager);
  68518. }
  68519. int DrawableComposite::ValueTreeWrapper::getNumDrawables() const
  68520. {
  68521. return getChildList().getNumChildren();
  68522. }
  68523. ValueTree DrawableComposite::ValueTreeWrapper::getDrawableState (int index) const
  68524. {
  68525. return getChildList().getChild (index);
  68526. }
  68527. ValueTree DrawableComposite::ValueTreeWrapper::getDrawableWithId (const String& objectId, bool recursive) const
  68528. {
  68529. if (getID() == objectId)
  68530. return state;
  68531. if (! recursive)
  68532. {
  68533. return getChildList().getChildWithProperty (idProperty, objectId);
  68534. }
  68535. else
  68536. {
  68537. const ValueTree childList (getChildList());
  68538. for (int i = getNumDrawables(); --i >= 0;)
  68539. {
  68540. const ValueTree& child = childList.getChild (i);
  68541. if (child [Drawable::ValueTreeWrapperBase::idProperty] == objectId)
  68542. return child;
  68543. if (child.hasType (DrawableComposite::valueTreeType))
  68544. {
  68545. ValueTree v (DrawableComposite::ValueTreeWrapper (child).getDrawableWithId (objectId, true));
  68546. if (v.isValid())
  68547. return v;
  68548. }
  68549. }
  68550. return ValueTree::invalid;
  68551. }
  68552. }
  68553. int DrawableComposite::ValueTreeWrapper::indexOfDrawable (const ValueTree& item) const
  68554. {
  68555. return getChildList().indexOf (item);
  68556. }
  68557. void DrawableComposite::ValueTreeWrapper::addDrawable (const ValueTree& newDrawableState, int index, UndoManager* undoManager)
  68558. {
  68559. getChildListCreating (undoManager).addChild (newDrawableState, index, undoManager);
  68560. }
  68561. void DrawableComposite::ValueTreeWrapper::moveDrawableOrder (int currentIndex, int newIndex, UndoManager* undoManager)
  68562. {
  68563. getChildListCreating (undoManager).moveChild (currentIndex, newIndex, undoManager);
  68564. }
  68565. void DrawableComposite::ValueTreeWrapper::removeDrawable (const ValueTree& child, UndoManager* undoManager)
  68566. {
  68567. getChildList().removeChild (child, undoManager);
  68568. }
  68569. const RelativeParallelogram DrawableComposite::ValueTreeWrapper::getBoundingBox() const
  68570. {
  68571. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  68572. state.getProperty (topRight, "100, 0"),
  68573. state.getProperty (bottomLeft, "0, 100"));
  68574. }
  68575. void DrawableComposite::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  68576. {
  68577. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  68578. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  68579. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  68580. }
  68581. void DrawableComposite::ValueTreeWrapper::resetBoundingBoxToContentArea (UndoManager* undoManager)
  68582. {
  68583. const RelativeRectangle content (getContentArea());
  68584. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  68585. RelativePoint (content.right, content.top),
  68586. RelativePoint (content.left, content.bottom)), undoManager);
  68587. }
  68588. const RelativeRectangle DrawableComposite::ValueTreeWrapper::getContentArea() const
  68589. {
  68590. return RelativeRectangle (getMarker (true, getMarkerState (true, 0)).position,
  68591. getMarker (true, getMarkerState (true, 1)).position,
  68592. getMarker (false, getMarkerState (false, 0)).position,
  68593. getMarker (false, getMarkerState (false, 1)).position);
  68594. }
  68595. void DrawableComposite::ValueTreeWrapper::setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager)
  68596. {
  68597. setMarker (true, Marker (contentLeftMarkerName, newArea.left), undoManager);
  68598. setMarker (true, Marker (contentRightMarkerName, newArea.right), undoManager);
  68599. setMarker (false, Marker (contentTopMarkerName, newArea.top), undoManager);
  68600. setMarker (false, Marker (contentBottomMarkerName, newArea.bottom), undoManager);
  68601. }
  68602. ValueTree DrawableComposite::ValueTreeWrapper::getMarkerList (bool xAxis) const
  68603. {
  68604. return state.getChildWithName (xAxis ? markerGroupTagX : markerGroupTagY);
  68605. }
  68606. ValueTree DrawableComposite::ValueTreeWrapper::getMarkerListCreating (bool xAxis, UndoManager* undoManager)
  68607. {
  68608. return state.getOrCreateChildWithName (xAxis ? markerGroupTagX : markerGroupTagY, undoManager);
  68609. }
  68610. int DrawableComposite::ValueTreeWrapper::getNumMarkers (bool xAxis) const
  68611. {
  68612. return getMarkerList (xAxis).getNumChildren();
  68613. }
  68614. const ValueTree DrawableComposite::ValueTreeWrapper::getMarkerState (bool xAxis, int index) const
  68615. {
  68616. return getMarkerList (xAxis).getChild (index);
  68617. }
  68618. const ValueTree DrawableComposite::ValueTreeWrapper::getMarkerState (bool xAxis, const String& name) const
  68619. {
  68620. return getMarkerList (xAxis).getChildWithProperty (nameProperty, name);
  68621. }
  68622. bool DrawableComposite::ValueTreeWrapper::containsMarker (bool xAxis, const ValueTree& state) const
  68623. {
  68624. return state.isAChildOf (getMarkerList (xAxis));
  68625. }
  68626. const DrawableComposite::Marker DrawableComposite::ValueTreeWrapper::getMarker (bool xAxis, const ValueTree& state) const
  68627. {
  68628. jassert (containsMarker (xAxis, state));
  68629. return Marker (state [nameProperty], RelativeCoordinate (state [posProperty].toString(), xAxis));
  68630. }
  68631. void DrawableComposite::ValueTreeWrapper::setMarker (bool xAxis, const Marker& m, UndoManager* undoManager)
  68632. {
  68633. ValueTree markerList (getMarkerListCreating (xAxis, undoManager));
  68634. ValueTree marker (markerList.getChildWithProperty (nameProperty, m.name));
  68635. if (marker.isValid())
  68636. {
  68637. marker.setProperty (posProperty, m.position.toString(), undoManager);
  68638. }
  68639. else
  68640. {
  68641. marker = ValueTree (markerTag);
  68642. marker.setProperty (nameProperty, m.name, 0);
  68643. marker.setProperty (posProperty, m.position.toString(), 0);
  68644. markerList.addChild (marker, -1, undoManager);
  68645. }
  68646. }
  68647. void DrawableComposite::ValueTreeWrapper::removeMarker (bool xAxis, const ValueTree& state, UndoManager* undoManager)
  68648. {
  68649. if (state [nameProperty].toString() != contentLeftMarkerName
  68650. && state [nameProperty].toString() != contentRightMarkerName
  68651. && state [nameProperty].toString() != contentTopMarkerName
  68652. && state [nameProperty].toString() != contentBottomMarkerName)
  68653. return getMarkerList (xAxis).removeChild (state, undoManager);
  68654. }
  68655. const Rectangle<float> DrawableComposite::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  68656. {
  68657. const ValueTreeWrapper wrapper (tree);
  68658. setName (wrapper.getID());
  68659. Rectangle<float> damage;
  68660. bool redrawAll = false;
  68661. const RelativeParallelogram newBounds (wrapper.getBoundingBox());
  68662. if (bounds != newBounds)
  68663. {
  68664. redrawAll = true;
  68665. damage = getBounds();
  68666. bounds = newBounds;
  68667. }
  68668. const int numMarkersX = wrapper.getNumMarkers (true);
  68669. const int numMarkersY = wrapper.getNumMarkers (false);
  68670. // Remove deleted markers...
  68671. if (markersX.size() > numMarkersX || markersY.size() > numMarkersY)
  68672. {
  68673. if (! redrawAll)
  68674. {
  68675. redrawAll = true;
  68676. damage = getBounds();
  68677. }
  68678. markersX.removeRange (jmax (2, numMarkersX), markersX.size());
  68679. markersY.removeRange (jmax (2, numMarkersY), markersY.size());
  68680. }
  68681. // Update markers and add new ones..
  68682. int i;
  68683. for (i = 0; i < numMarkersX; ++i)
  68684. {
  68685. const Marker newMarker (wrapper.getMarker (true, wrapper.getMarkerState (true, i)));
  68686. Marker* m = markersX[i];
  68687. if (m == 0 || newMarker != *m)
  68688. {
  68689. if (! redrawAll)
  68690. {
  68691. redrawAll = true;
  68692. damage = getBounds();
  68693. }
  68694. if (m == 0)
  68695. markersX.add (new Marker (newMarker));
  68696. else
  68697. *m = newMarker;
  68698. }
  68699. }
  68700. for (i = 0; i < numMarkersY; ++i)
  68701. {
  68702. const Marker newMarker (wrapper.getMarker (false, wrapper.getMarkerState (false, i)));
  68703. Marker* m = markersY[i];
  68704. if (m == 0 || newMarker != *m)
  68705. {
  68706. if (! redrawAll)
  68707. {
  68708. redrawAll = true;
  68709. damage = getBounds();
  68710. }
  68711. if (m == 0)
  68712. markersY.add (new Marker (newMarker));
  68713. else
  68714. *m = newMarker;
  68715. }
  68716. }
  68717. // Remove deleted drawables..
  68718. for (i = drawables.size(); --i >= wrapper.getNumDrawables();)
  68719. {
  68720. Drawable* const d = drawables.getUnchecked(i);
  68721. if (! redrawAll)
  68722. damage = damage.getUnion (d->getBounds());
  68723. d->parent = 0;
  68724. drawables.remove (i);
  68725. }
  68726. // Update drawables and add new ones..
  68727. for (i = 0; i < wrapper.getNumDrawables(); ++i)
  68728. {
  68729. const ValueTree newDrawable (wrapper.getDrawableState (i));
  68730. Drawable* d = drawables[i];
  68731. if (d != 0)
  68732. {
  68733. if (newDrawable.hasType (d->getValueTreeType()))
  68734. {
  68735. const Rectangle<float> area (d->refreshFromValueTree (newDrawable, imageProvider));
  68736. if (! redrawAll)
  68737. damage = damage.getUnion (area);
  68738. }
  68739. else
  68740. {
  68741. if (! redrawAll)
  68742. damage = damage.getUnion (d->getBounds());
  68743. d = createChildFromValueTree (this, newDrawable, imageProvider);
  68744. drawables.set (i, d);
  68745. if (! redrawAll)
  68746. damage = damage.getUnion (d->getBounds());
  68747. }
  68748. }
  68749. else
  68750. {
  68751. d = createChildFromValueTree (this, newDrawable, imageProvider);
  68752. drawables.set (i, d);
  68753. if (! redrawAll)
  68754. damage = damage.getUnion (d->getBounds());
  68755. }
  68756. }
  68757. if (redrawAll)
  68758. damage = damage.getUnion (getBounds());
  68759. else if (! damage.isEmpty())
  68760. damage = damage.transformed (calculateTransform());
  68761. return damage;
  68762. }
  68763. const ValueTree DrawableComposite::createValueTree (ImageProvider* imageProvider) const
  68764. {
  68765. ValueTree tree (valueTreeType);
  68766. ValueTreeWrapper v (tree);
  68767. v.setID (getName(), 0);
  68768. v.setBoundingBox (bounds, 0);
  68769. int i;
  68770. for (i = 0; i < drawables.size(); ++i)
  68771. v.addDrawable (drawables.getUnchecked(i)->createValueTree (imageProvider), -1, 0);
  68772. for (i = 0; i < markersX.size(); ++i)
  68773. v.setMarker (true, *markersX.getUnchecked(i), 0);
  68774. for (i = 0; i < markersY.size(); ++i)
  68775. v.setMarker (false, *markersY.getUnchecked(i), 0);
  68776. return tree;
  68777. }
  68778. END_JUCE_NAMESPACE
  68779. /*** End of inlined file: juce_DrawableComposite.cpp ***/
  68780. /*** Start of inlined file: juce_DrawableImage.cpp ***/
  68781. BEGIN_JUCE_NAMESPACE
  68782. DrawableImage::DrawableImage()
  68783. : image (0),
  68784. opacity (1.0f),
  68785. overlayColour (0x00000000)
  68786. {
  68787. bounds.topRight = RelativePoint (Point<float> (1.0f, 0.0f));
  68788. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, 1.0f));
  68789. }
  68790. DrawableImage::DrawableImage (const DrawableImage& other)
  68791. : image (other.image),
  68792. opacity (other.opacity),
  68793. overlayColour (other.overlayColour),
  68794. bounds (other.bounds)
  68795. {
  68796. }
  68797. DrawableImage::~DrawableImage()
  68798. {
  68799. }
  68800. void DrawableImage::setImage (const Image& imageToUse)
  68801. {
  68802. image = imageToUse;
  68803. if (image.isValid())
  68804. {
  68805. bounds.topLeft = RelativePoint (Point<float> (0.0f, 0.0f));
  68806. bounds.topRight = RelativePoint (Point<float> ((float) image.getWidth(), 0.0f));
  68807. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, (float) image.getHeight()));
  68808. }
  68809. }
  68810. void DrawableImage::setOpacity (const float newOpacity)
  68811. {
  68812. opacity = newOpacity;
  68813. }
  68814. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  68815. {
  68816. overlayColour = newOverlayColour;
  68817. }
  68818. void DrawableImage::setBoundingBox (const RelativeParallelogram& newBounds)
  68819. {
  68820. bounds = newBounds;
  68821. }
  68822. const AffineTransform DrawableImage::calculateTransform() const
  68823. {
  68824. if (image.isNull())
  68825. return AffineTransform::identity;
  68826. Point<float> resolved[3];
  68827. bounds.resolveThreePoints (resolved, parent);
  68828. const Point<float> tr (resolved[0] + (resolved[1] - resolved[0]) / (float) image.getWidth());
  68829. const Point<float> bl (resolved[0] + (resolved[2] - resolved[0]) / (float) image.getHeight());
  68830. return AffineTransform::fromTargetPoints (resolved[0].getX(), resolved[0].getY(),
  68831. tr.getX(), tr.getY(),
  68832. bl.getX(), bl.getY());
  68833. }
  68834. void DrawableImage::render (const Drawable::RenderingContext& context) const
  68835. {
  68836. if (image.isValid())
  68837. {
  68838. const AffineTransform t (calculateTransform().followedBy (context.transform));
  68839. if (opacity > 0.0f && ! overlayColour.isOpaque())
  68840. {
  68841. context.g.setOpacity (context.opacity * opacity);
  68842. context.g.drawImageTransformed (image, image.getBounds(), t, false);
  68843. }
  68844. if (! overlayColour.isTransparent())
  68845. {
  68846. context.g.setColour (overlayColour.withMultipliedAlpha (context.opacity));
  68847. context.g.drawImageTransformed (image, image.getBounds(), t, true);
  68848. }
  68849. }
  68850. }
  68851. const Rectangle<float> DrawableImage::getBounds() const
  68852. {
  68853. if (image.isNull())
  68854. return Rectangle<float>();
  68855. return bounds.getBounds (parent);
  68856. }
  68857. bool DrawableImage::hitTest (float x, float y) const
  68858. {
  68859. if (image.isNull())
  68860. return false;
  68861. calculateTransform().inverted().transformPoint (x, y);
  68862. const int ix = roundToInt (x);
  68863. const int iy = roundToInt (y);
  68864. return ix >= 0
  68865. && iy >= 0
  68866. && ix < image.getWidth()
  68867. && iy < image.getHeight()
  68868. && image.getPixelAt (ix, iy).getAlpha() >= 127;
  68869. }
  68870. Drawable* DrawableImage::createCopy() const
  68871. {
  68872. return new DrawableImage (*this);
  68873. }
  68874. void DrawableImage::invalidatePoints()
  68875. {
  68876. }
  68877. const Identifier DrawableImage::valueTreeType ("Image");
  68878. const Identifier DrawableImage::ValueTreeWrapper::opacity ("opacity");
  68879. const Identifier DrawableImage::ValueTreeWrapper::overlay ("overlay");
  68880. const Identifier DrawableImage::ValueTreeWrapper::image ("image");
  68881. const Identifier DrawableImage::ValueTreeWrapper::topLeft ("topLeft");
  68882. const Identifier DrawableImage::ValueTreeWrapper::topRight ("topRight");
  68883. const Identifier DrawableImage::ValueTreeWrapper::bottomLeft ("bottomLeft");
  68884. DrawableImage::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  68885. : ValueTreeWrapperBase (state_)
  68886. {
  68887. jassert (state.hasType (valueTreeType));
  68888. }
  68889. const var DrawableImage::ValueTreeWrapper::getImageIdentifier() const
  68890. {
  68891. return state [image];
  68892. }
  68893. Value DrawableImage::ValueTreeWrapper::getImageIdentifierValue (UndoManager* undoManager)
  68894. {
  68895. return state.getPropertyAsValue (image, undoManager);
  68896. }
  68897. void DrawableImage::ValueTreeWrapper::setImageIdentifier (const var& newIdentifier, UndoManager* undoManager)
  68898. {
  68899. state.setProperty (image, newIdentifier, undoManager);
  68900. }
  68901. float DrawableImage::ValueTreeWrapper::getOpacity() const
  68902. {
  68903. return (float) state.getProperty (opacity, 1.0);
  68904. }
  68905. Value DrawableImage::ValueTreeWrapper::getOpacityValue (UndoManager* undoManager)
  68906. {
  68907. if (! state.hasProperty (opacity))
  68908. state.setProperty (opacity, 1.0, undoManager);
  68909. return state.getPropertyAsValue (opacity, undoManager);
  68910. }
  68911. void DrawableImage::ValueTreeWrapper::setOpacity (float newOpacity, UndoManager* undoManager)
  68912. {
  68913. state.setProperty (opacity, newOpacity, undoManager);
  68914. }
  68915. const Colour DrawableImage::ValueTreeWrapper::getOverlayColour() const
  68916. {
  68917. return Colour (state [overlay].toString().getHexValue32());
  68918. }
  68919. void DrawableImage::ValueTreeWrapper::setOverlayColour (const Colour& newColour, UndoManager* undoManager)
  68920. {
  68921. if (newColour.isTransparent())
  68922. state.removeProperty (overlay, undoManager);
  68923. else
  68924. state.setProperty (overlay, String::toHexString ((int) newColour.getARGB()), undoManager);
  68925. }
  68926. Value DrawableImage::ValueTreeWrapper::getOverlayColourValue (UndoManager* undoManager)
  68927. {
  68928. return state.getPropertyAsValue (overlay, undoManager);
  68929. }
  68930. const RelativeParallelogram DrawableImage::ValueTreeWrapper::getBoundingBox() const
  68931. {
  68932. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  68933. state.getProperty (topRight, "100, 0"),
  68934. state.getProperty (bottomLeft, "0, 100"));
  68935. }
  68936. void DrawableImage::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  68937. {
  68938. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  68939. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  68940. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  68941. }
  68942. const Rectangle<float> DrawableImage::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  68943. {
  68944. const ValueTreeWrapper controller (tree);
  68945. setName (controller.getID());
  68946. const float newOpacity = controller.getOpacity();
  68947. const Colour newOverlayColour (controller.getOverlayColour());
  68948. Image newImage;
  68949. const var imageIdentifier (controller.getImageIdentifier());
  68950. jassert (imageProvider != 0 || imageIdentifier.isVoid()); // if you're using images, you need to provide something that can load and save them!
  68951. if (imageProvider != 0)
  68952. newImage = imageProvider->getImageForIdentifier (imageIdentifier);
  68953. const RelativeParallelogram newBounds (controller.getBoundingBox());
  68954. if (newOpacity != opacity || overlayColour != newOverlayColour || image != newImage || bounds != newBounds)
  68955. {
  68956. const Rectangle<float> damage (getBounds());
  68957. opacity = newOpacity;
  68958. overlayColour = newOverlayColour;
  68959. bounds = newBounds;
  68960. image = newImage;
  68961. return damage.getUnion (getBounds());
  68962. }
  68963. return Rectangle<float>();
  68964. }
  68965. const ValueTree DrawableImage::createValueTree (ImageProvider* imageProvider) const
  68966. {
  68967. ValueTree tree (valueTreeType);
  68968. ValueTreeWrapper v (tree);
  68969. v.setID (getName(), 0);
  68970. v.setOpacity (opacity, 0);
  68971. v.setOverlayColour (overlayColour, 0);
  68972. v.setBoundingBox (bounds, 0);
  68973. if (image.isValid())
  68974. {
  68975. jassert (imageProvider != 0); // if you're using images, you need to provide something that can load and save them!
  68976. if (imageProvider != 0)
  68977. v.setImageIdentifier (imageProvider->getIdentifierForImage (image), 0);
  68978. }
  68979. return tree;
  68980. }
  68981. END_JUCE_NAMESPACE
  68982. /*** End of inlined file: juce_DrawableImage.cpp ***/
  68983. /*** Start of inlined file: juce_DrawablePath.cpp ***/
  68984. BEGIN_JUCE_NAMESPACE
  68985. DrawablePath::DrawablePath()
  68986. : mainFill (Colours::black),
  68987. strokeFill (Colours::black),
  68988. strokeType (0.0f),
  68989. pathNeedsUpdating (true),
  68990. strokeNeedsUpdating (true)
  68991. {
  68992. }
  68993. DrawablePath::DrawablePath (const DrawablePath& other)
  68994. : mainFill (other.mainFill),
  68995. strokeFill (other.strokeFill),
  68996. strokeType (other.strokeType),
  68997. pathNeedsUpdating (true),
  68998. strokeNeedsUpdating (true)
  68999. {
  69000. if (other.relativePath != 0)
  69001. relativePath = new RelativePointPath (*other.relativePath);
  69002. else
  69003. path = other.path;
  69004. }
  69005. DrawablePath::~DrawablePath()
  69006. {
  69007. }
  69008. void DrawablePath::setPath (const Path& newPath)
  69009. {
  69010. path = newPath;
  69011. strokeNeedsUpdating = true;
  69012. }
  69013. void DrawablePath::setFill (const FillType& newFill)
  69014. {
  69015. mainFill = newFill;
  69016. }
  69017. void DrawablePath::setStrokeFill (const FillType& newFill)
  69018. {
  69019. strokeFill = newFill;
  69020. }
  69021. void DrawablePath::setStrokeType (const PathStrokeType& newStrokeType)
  69022. {
  69023. strokeType = newStrokeType;
  69024. strokeNeedsUpdating = true;
  69025. }
  69026. void DrawablePath::setStrokeThickness (const float newThickness)
  69027. {
  69028. setStrokeType (PathStrokeType (newThickness, strokeType.getJointStyle(), strokeType.getEndStyle()));
  69029. }
  69030. void DrawablePath::updatePath() const
  69031. {
  69032. if (pathNeedsUpdating)
  69033. {
  69034. pathNeedsUpdating = false;
  69035. if (relativePath != 0)
  69036. {
  69037. path.clear();
  69038. relativePath->createPath (path, parent);
  69039. strokeNeedsUpdating = true;
  69040. }
  69041. }
  69042. }
  69043. void DrawablePath::updateStroke() const
  69044. {
  69045. if (strokeNeedsUpdating)
  69046. {
  69047. strokeNeedsUpdating = false;
  69048. updatePath();
  69049. stroke.clear();
  69050. strokeType.createStrokedPath (stroke, path, AffineTransform::identity, 4.0f);
  69051. }
  69052. }
  69053. const Path& DrawablePath::getPath() const
  69054. {
  69055. updatePath();
  69056. return path;
  69057. }
  69058. const Path& DrawablePath::getStrokePath() const
  69059. {
  69060. updateStroke();
  69061. return stroke;
  69062. }
  69063. bool DrawablePath::isStrokeVisible() const throw()
  69064. {
  69065. return strokeType.getStrokeThickness() > 0.0f && ! strokeFill.isInvisible();
  69066. }
  69067. void DrawablePath::invalidatePoints()
  69068. {
  69069. pathNeedsUpdating = true;
  69070. strokeNeedsUpdating = true;
  69071. }
  69072. void DrawablePath::render (const Drawable::RenderingContext& context) const
  69073. {
  69074. {
  69075. FillType f (mainFill);
  69076. if (f.isGradient())
  69077. f.gradient->multiplyOpacity (context.opacity);
  69078. f.transform = f.transform.followedBy (context.transform);
  69079. context.g.setFillType (f);
  69080. context.g.fillPath (getPath(), context.transform);
  69081. }
  69082. if (isStrokeVisible())
  69083. {
  69084. FillType f (strokeFill);
  69085. if (f.isGradient())
  69086. f.gradient->multiplyOpacity (context.opacity);
  69087. f.transform = f.transform.followedBy (context.transform);
  69088. context.g.setFillType (f);
  69089. context.g.fillPath (getStrokePath(), context.transform);
  69090. }
  69091. }
  69092. const Rectangle<float> DrawablePath::getBounds() const
  69093. {
  69094. if (isStrokeVisible())
  69095. return getStrokePath().getBounds();
  69096. else
  69097. return getPath().getBounds();
  69098. }
  69099. bool DrawablePath::hitTest (float x, float y) const
  69100. {
  69101. return getPath().contains (x, y)
  69102. || (isStrokeVisible() && getStrokePath().contains (x, y));
  69103. }
  69104. Drawable* DrawablePath::createCopy() const
  69105. {
  69106. return new DrawablePath (*this);
  69107. }
  69108. const Identifier DrawablePath::valueTreeType ("Path");
  69109. const Identifier DrawablePath::ValueTreeWrapper::fill ("Fill");
  69110. const Identifier DrawablePath::ValueTreeWrapper::stroke ("Stroke");
  69111. const Identifier DrawablePath::ValueTreeWrapper::path ("Path");
  69112. const Identifier DrawablePath::ValueTreeWrapper::jointStyle ("jointStyle");
  69113. const Identifier DrawablePath::ValueTreeWrapper::capStyle ("capStyle");
  69114. const Identifier DrawablePath::ValueTreeWrapper::strokeWidth ("strokeWidth");
  69115. const Identifier DrawablePath::ValueTreeWrapper::nonZeroWinding ("nonZeroWinding");
  69116. const Identifier DrawablePath::ValueTreeWrapper::point1 ("p1");
  69117. const Identifier DrawablePath::ValueTreeWrapper::point2 ("p2");
  69118. const Identifier DrawablePath::ValueTreeWrapper::point3 ("p3");
  69119. DrawablePath::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  69120. : ValueTreeWrapperBase (state_)
  69121. {
  69122. jassert (state.hasType (valueTreeType));
  69123. }
  69124. ValueTree DrawablePath::ValueTreeWrapper::getPathState()
  69125. {
  69126. return state.getOrCreateChildWithName (path, 0);
  69127. }
  69128. ValueTree DrawablePath::ValueTreeWrapper::getMainFillState()
  69129. {
  69130. ValueTree v (state.getChildWithName (fill));
  69131. if (v.isValid())
  69132. return v;
  69133. setMainFill (Colours::black, 0, 0, 0, 0);
  69134. return getMainFillState();
  69135. }
  69136. ValueTree DrawablePath::ValueTreeWrapper::getStrokeFillState()
  69137. {
  69138. ValueTree v (state.getChildWithName (stroke));
  69139. if (v.isValid())
  69140. return v;
  69141. setStrokeFill (Colours::black, 0, 0, 0, 0);
  69142. return getStrokeFillState();
  69143. }
  69144. const FillType DrawablePath::ValueTreeWrapper::getMainFill (RelativeCoordinate::NamedCoordinateFinder* nameFinder,
  69145. ImageProvider* imageProvider) const
  69146. {
  69147. return readFillType (state.getChildWithName (fill), 0, 0, nameFinder, imageProvider);
  69148. }
  69149. void DrawablePath::ValueTreeWrapper::setMainFill (const FillType& newFill, const RelativePoint* gp1,
  69150. const RelativePoint* gp2, ImageProvider* imageProvider, UndoManager* undoManager)
  69151. {
  69152. ValueTree v (state.getOrCreateChildWithName (fill, undoManager));
  69153. writeFillType (v, newFill, gp1, gp2, imageProvider, undoManager);
  69154. }
  69155. const FillType DrawablePath::ValueTreeWrapper::getStrokeFill (RelativeCoordinate::NamedCoordinateFinder* nameFinder,
  69156. ImageProvider* imageProvider) const
  69157. {
  69158. return readFillType (state.getChildWithName (stroke), 0, 0, nameFinder, imageProvider);
  69159. }
  69160. void DrawablePath::ValueTreeWrapper::setStrokeFill (const FillType& newFill, const RelativePoint* gp1,
  69161. const RelativePoint* gp2, ImageProvider* imageProvider, UndoManager* undoManager)
  69162. {
  69163. ValueTree v (state.getOrCreateChildWithName (stroke, undoManager));
  69164. writeFillType (v, newFill, gp1, gp2, imageProvider, undoManager);
  69165. }
  69166. const PathStrokeType DrawablePath::ValueTreeWrapper::getStrokeType() const
  69167. {
  69168. const String jointStyleString (state [jointStyle].toString());
  69169. const String capStyleString (state [capStyle].toString());
  69170. return PathStrokeType (state [strokeWidth],
  69171. jointStyleString == "curved" ? PathStrokeType::curved
  69172. : (jointStyleString == "bevel" ? PathStrokeType::beveled
  69173. : PathStrokeType::mitered),
  69174. capStyleString == "square" ? PathStrokeType::square
  69175. : (capStyleString == "round" ? PathStrokeType::rounded
  69176. : PathStrokeType::butt));
  69177. }
  69178. void DrawablePath::ValueTreeWrapper::setStrokeType (const PathStrokeType& newStrokeType, UndoManager* undoManager)
  69179. {
  69180. state.setProperty (strokeWidth, (double) newStrokeType.getStrokeThickness(), undoManager);
  69181. state.setProperty (jointStyle, newStrokeType.getJointStyle() == PathStrokeType::mitered
  69182. ? "miter" : (newStrokeType.getJointStyle() == PathStrokeType::curved ? "curved" : "bevel"), undoManager);
  69183. state.setProperty (capStyle, newStrokeType.getEndStyle() == PathStrokeType::butt
  69184. ? "butt" : (newStrokeType.getEndStyle() == PathStrokeType::square ? "square" : "round"), undoManager);
  69185. }
  69186. bool DrawablePath::ValueTreeWrapper::usesNonZeroWinding() const
  69187. {
  69188. return state [nonZeroWinding];
  69189. }
  69190. void DrawablePath::ValueTreeWrapper::setUsesNonZeroWinding (bool b, UndoManager* undoManager)
  69191. {
  69192. state.setProperty (nonZeroWinding, b, undoManager);
  69193. }
  69194. const Identifier DrawablePath::ValueTreeWrapper::Element::startSubPathElement ("Move");
  69195. const Identifier DrawablePath::ValueTreeWrapper::Element::closeSubPathElement ("Close");
  69196. const Identifier DrawablePath::ValueTreeWrapper::Element::lineToElement ("Line");
  69197. const Identifier DrawablePath::ValueTreeWrapper::Element::quadraticToElement ("Quad");
  69198. const Identifier DrawablePath::ValueTreeWrapper::Element::cubicToElement ("Cubic");
  69199. DrawablePath::ValueTreeWrapper::Element::Element (const ValueTree& state_)
  69200. : state (state_)
  69201. {
  69202. }
  69203. DrawablePath::ValueTreeWrapper::Element::~Element()
  69204. {
  69205. }
  69206. DrawablePath::ValueTreeWrapper DrawablePath::ValueTreeWrapper::Element::getParent() const
  69207. {
  69208. return ValueTreeWrapper (state.getParent().getParent());
  69209. }
  69210. int DrawablePath::ValueTreeWrapper::Element::getNumControlPoints() const throw()
  69211. {
  69212. const Identifier i (state.getType());
  69213. if (i == startSubPathElement || i == lineToElement) return 1;
  69214. if (i == quadraticToElement) return 2;
  69215. if (i == cubicToElement) return 3;
  69216. return 0;
  69217. }
  69218. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getControlPoint (const int index) const
  69219. {
  69220. jassert (index >= 0 && index < getNumControlPoints());
  69221. return RelativePoint (state [index == 0 ? point1 : (index == 1 ? point2 : point3)].toString());
  69222. }
  69223. Value DrawablePath::ValueTreeWrapper::Element::getControlPointValue (int index, UndoManager* undoManager) const
  69224. {
  69225. jassert (index >= 0 && index < getNumControlPoints());
  69226. return state.getPropertyAsValue (index == 0 ? point1 : (index == 1 ? point2 : point3), undoManager);
  69227. }
  69228. void DrawablePath::ValueTreeWrapper::Element::setControlPoint (const int index, const RelativePoint& point, UndoManager* undoManager)
  69229. {
  69230. jassert (index >= 0 && index < getNumControlPoints());
  69231. return state.setProperty (index == 0 ? point1 : (index == 1 ? point2 : point3), point.toString(), undoManager);
  69232. }
  69233. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getEndPoint() const
  69234. {
  69235. const Identifier i (state.getType());
  69236. if (i == startSubPathElement || i == lineToElement) return getControlPoint (0);
  69237. if (i == quadraticToElement) return getControlPoint (1);
  69238. if (i == cubicToElement) return getControlPoint (2);
  69239. return RelativePoint();
  69240. }
  69241. const Rectangle<float> DrawablePath::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  69242. {
  69243. Rectangle<float> damageRect;
  69244. ValueTreeWrapper v (tree);
  69245. setName (v.getID());
  69246. bool needsRedraw = false;
  69247. const FillType newFill (v.getMainFill (parent, imageProvider));
  69248. if (mainFill != newFill)
  69249. {
  69250. needsRedraw = true;
  69251. mainFill = newFill;
  69252. }
  69253. const FillType newStrokeFill (v.getStrokeFill (parent, imageProvider));
  69254. if (strokeFill != newStrokeFill)
  69255. {
  69256. needsRedraw = true;
  69257. strokeFill = newStrokeFill;
  69258. }
  69259. const PathStrokeType newStroke (v.getStrokeType());
  69260. ScopedPointer<RelativePointPath> newRelativePath (new RelativePointPath (tree));
  69261. Path newPath;
  69262. newRelativePath->createPath (newPath, parent);
  69263. if (! newRelativePath->containsAnyDynamicPoints())
  69264. newRelativePath = 0;
  69265. if (strokeType != newStroke || path != newPath)
  69266. {
  69267. damageRect = getBounds();
  69268. path.swapWithPath (newPath);
  69269. strokeNeedsUpdating = true;
  69270. strokeType = newStroke;
  69271. needsRedraw = true;
  69272. }
  69273. relativePath = newRelativePath.release();
  69274. if (needsRedraw)
  69275. damageRect = damageRect.getUnion (getBounds());
  69276. return damageRect;
  69277. }
  69278. const ValueTree DrawablePath::createValueTree (ImageProvider* imageProvider) const
  69279. {
  69280. ValueTree tree (valueTreeType);
  69281. ValueTreeWrapper v (tree);
  69282. v.setID (getName(), 0);
  69283. v.setMainFill (mainFill, 0, 0, imageProvider, 0);
  69284. v.setStrokeFill (strokeFill, 0, 0, imageProvider, 0);
  69285. v.setStrokeType (strokeType, 0);
  69286. if (relativePath != 0)
  69287. {
  69288. relativePath->writeTo (tree, 0);
  69289. }
  69290. else
  69291. {
  69292. RelativePointPath rp (path);
  69293. rp.writeTo (tree, 0);
  69294. }
  69295. return tree;
  69296. }
  69297. END_JUCE_NAMESPACE
  69298. /*** End of inlined file: juce_DrawablePath.cpp ***/
  69299. /*** Start of inlined file: juce_DrawableText.cpp ***/
  69300. BEGIN_JUCE_NAMESPACE
  69301. DrawableText::DrawableText()
  69302. : colour (Colours::black),
  69303. justification (Justification::centredLeft)
  69304. {
  69305. setFont (Font (15.0f), true);
  69306. }
  69307. DrawableText::DrawableText (const DrawableText& other)
  69308. : text (other.text),
  69309. font (other.font),
  69310. colour (other.colour),
  69311. justification (other.justification),
  69312. bounds (other.bounds),
  69313. fontSizeControlPoint (other.fontSizeControlPoint)
  69314. {
  69315. }
  69316. DrawableText::~DrawableText()
  69317. {
  69318. }
  69319. void DrawableText::setText (const String& newText)
  69320. {
  69321. text = newText;
  69322. }
  69323. void DrawableText::setColour (const Colour& newColour)
  69324. {
  69325. colour = newColour;
  69326. }
  69327. void DrawableText::setFont (const Font& newFont, bool applySizeAndScale)
  69328. {
  69329. font = newFont;
  69330. if (applySizeAndScale)
  69331. {
  69332. Point<float> corners[3];
  69333. bounds.resolveThreePoints (corners, parent);
  69334. setFontSizeControlPoint (RelativePoint (RelativeParallelogram::getPointForInternalCoord (corners,
  69335. Point<float> (font.getHorizontalScale() * font.getHeight(), font.getHeight()))));
  69336. }
  69337. }
  69338. void DrawableText::setJustification (const Justification& newJustification)
  69339. {
  69340. justification = newJustification;
  69341. }
  69342. void DrawableText::setBoundingBox (const RelativeParallelogram& newBounds)
  69343. {
  69344. bounds = newBounds;
  69345. }
  69346. void DrawableText::setFontSizeControlPoint (const RelativePoint& newPoint)
  69347. {
  69348. fontSizeControlPoint = newPoint;
  69349. }
  69350. void DrawableText::render (const Drawable::RenderingContext& context) const
  69351. {
  69352. Point<float> points[3];
  69353. bounds.resolveThreePoints (points, parent);
  69354. const float w = Line<float> (points[0], points[1]).getLength();
  69355. const float h = Line<float> (points[0], points[2]).getLength();
  69356. const Point<float> fontCoords (bounds.getInternalCoordForPoint (points, fontSizeControlPoint.resolve (parent)));
  69357. const float fontHeight = jlimit (1.0f, h, fontCoords.getY());
  69358. const float fontWidth = jlimit (0.01f, w, fontCoords.getX());
  69359. Font f (font);
  69360. f.setHeight (fontHeight);
  69361. f.setHorizontalScale (fontWidth / fontHeight);
  69362. context.g.setColour (colour.withMultipliedAlpha (context.opacity));
  69363. GlyphArrangement ga;
  69364. ga.addFittedText (f, text, 0, 0, w, h, justification, 0x100000);
  69365. ga.draw (context.g,
  69366. AffineTransform::fromTargetPoints (0, 0, points[0].getX(), points[0].getY(),
  69367. w, 0, points[1].getX(), points[1].getY(),
  69368. 0, h, points[2].getX(), points[2].getY())
  69369. .followedBy (context.transform));
  69370. }
  69371. const Rectangle<float> DrawableText::getBounds() const
  69372. {
  69373. return bounds.getBounds (parent);
  69374. }
  69375. bool DrawableText::hitTest (float x, float y) const
  69376. {
  69377. Path p;
  69378. bounds.getPath (p, parent);
  69379. return p.contains (x, y);
  69380. }
  69381. Drawable* DrawableText::createCopy() const
  69382. {
  69383. return new DrawableText (*this);
  69384. }
  69385. void DrawableText::invalidatePoints()
  69386. {
  69387. }
  69388. const Identifier DrawableText::valueTreeType ("Text");
  69389. const Identifier DrawableText::ValueTreeWrapper::text ("text");
  69390. const Identifier DrawableText::ValueTreeWrapper::colour ("colour");
  69391. const Identifier DrawableText::ValueTreeWrapper::font ("font");
  69392. const Identifier DrawableText::ValueTreeWrapper::justification ("justification");
  69393. const Identifier DrawableText::ValueTreeWrapper::topLeft ("topLeft");
  69394. const Identifier DrawableText::ValueTreeWrapper::topRight ("topRight");
  69395. const Identifier DrawableText::ValueTreeWrapper::bottomLeft ("bottomLeft");
  69396. const Identifier DrawableText::ValueTreeWrapper::fontSizeAnchor ("fontSizeAnchor");
  69397. DrawableText::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  69398. : ValueTreeWrapperBase (state_)
  69399. {
  69400. jassert (state.hasType (valueTreeType));
  69401. }
  69402. const String DrawableText::ValueTreeWrapper::getText() const
  69403. {
  69404. return state [text].toString();
  69405. }
  69406. void DrawableText::ValueTreeWrapper::setText (const String& newText, UndoManager* undoManager)
  69407. {
  69408. state.setProperty (text, newText, undoManager);
  69409. }
  69410. Value DrawableText::ValueTreeWrapper::getTextValue (UndoManager* undoManager)
  69411. {
  69412. return state.getPropertyAsValue (text, undoManager);
  69413. }
  69414. const Colour DrawableText::ValueTreeWrapper::getColour() const
  69415. {
  69416. return Colour::fromString (state [colour].toString());
  69417. }
  69418. void DrawableText::ValueTreeWrapper::setColour (const Colour& newColour, UndoManager* undoManager)
  69419. {
  69420. state.setProperty (colour, newColour.toString(), undoManager);
  69421. }
  69422. const Justification DrawableText::ValueTreeWrapper::getJustification() const
  69423. {
  69424. return Justification ((int) state [justification]);
  69425. }
  69426. void DrawableText::ValueTreeWrapper::setJustification (const Justification& newJustification, UndoManager* undoManager)
  69427. {
  69428. state.setProperty (justification, newJustification.getFlags(), undoManager);
  69429. }
  69430. const Font DrawableText::ValueTreeWrapper::getFont() const
  69431. {
  69432. return Font::fromString (state [font]);
  69433. }
  69434. void DrawableText::ValueTreeWrapper::setFont (const Font& newFont, UndoManager* undoManager)
  69435. {
  69436. state.setProperty (font, newFont.toString(), undoManager);
  69437. }
  69438. Value DrawableText::ValueTreeWrapper::getFontValue (UndoManager* undoManager)
  69439. {
  69440. return state.getPropertyAsValue (font, undoManager);
  69441. }
  69442. const RelativeParallelogram DrawableText::ValueTreeWrapper::getBoundingBox() const
  69443. {
  69444. return RelativeParallelogram (state [topLeft].toString(), state [topRight].toString(), state [bottomLeft].toString());
  69445. }
  69446. void DrawableText::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  69447. {
  69448. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  69449. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  69450. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  69451. }
  69452. const RelativePoint DrawableText::ValueTreeWrapper::getFontSizeControlPoint() const
  69453. {
  69454. return state [fontSizeAnchor].toString();
  69455. }
  69456. void DrawableText::ValueTreeWrapper::setFontSizeControlPoint (const RelativePoint& p, UndoManager* undoManager)
  69457. {
  69458. state.setProperty (fontSizeAnchor, p.toString(), undoManager);
  69459. }
  69460. const Rectangle<float> DrawableText::refreshFromValueTree (const ValueTree& tree, ImageProvider*)
  69461. {
  69462. ValueTreeWrapper v (tree);
  69463. setName (v.getID());
  69464. const RelativeParallelogram newBounds (v.getBoundingBox());
  69465. const RelativePoint newFontPoint (v.getFontSizeControlPoint());
  69466. const Colour newColour (v.getColour());
  69467. const Justification newJustification (v.getJustification());
  69468. const String newText (v.getText());
  69469. const Font newFont (v.getFont());
  69470. if (text != newText || font != newFont || justification != newJustification
  69471. || colour != newColour || bounds != newBounds || newFontPoint != fontSizeControlPoint)
  69472. {
  69473. const Rectangle<float> damage (getBounds());
  69474. setBoundingBox (newBounds);
  69475. setFontSizeControlPoint (newFontPoint);
  69476. setColour (newColour);
  69477. setFont (newFont, false);
  69478. setJustification (newJustification);
  69479. setText (newText);
  69480. return damage.getUnion (getBounds());
  69481. }
  69482. return Rectangle<float>();
  69483. }
  69484. const ValueTree DrawableText::createValueTree (ImageProvider*) const
  69485. {
  69486. ValueTree tree (valueTreeType);
  69487. ValueTreeWrapper v (tree);
  69488. v.setID (getName(), 0);
  69489. v.setText (text, 0);
  69490. v.setFont (font, 0);
  69491. v.setJustification (justification, 0);
  69492. v.setColour (colour, 0);
  69493. v.setBoundingBox (bounds, 0);
  69494. v.setFontSizeControlPoint (fontSizeControlPoint, 0);
  69495. return tree;
  69496. }
  69497. END_JUCE_NAMESPACE
  69498. /*** End of inlined file: juce_DrawableText.cpp ***/
  69499. /*** Start of inlined file: juce_SVGParser.cpp ***/
  69500. BEGIN_JUCE_NAMESPACE
  69501. class SVGState
  69502. {
  69503. public:
  69504. SVGState (const XmlElement* const topLevel)
  69505. : topLevelXml (topLevel),
  69506. elementX (0), elementY (0),
  69507. width (512), height (512),
  69508. viewBoxW (0), viewBoxH (0)
  69509. {
  69510. }
  69511. ~SVGState()
  69512. {
  69513. }
  69514. Drawable* parseSVGElement (const XmlElement& xml)
  69515. {
  69516. if (! xml.hasTagName ("svg"))
  69517. return 0;
  69518. DrawableComposite* const drawable = new DrawableComposite();
  69519. drawable->setName (xml.getStringAttribute ("id"));
  69520. SVGState newState (*this);
  69521. if (xml.hasAttribute ("transform"))
  69522. newState.addTransform (xml);
  69523. newState.elementX = getCoordLength (xml.getStringAttribute ("x", String (newState.elementX)), viewBoxW);
  69524. newState.elementY = getCoordLength (xml.getStringAttribute ("y", String (newState.elementY)), viewBoxH);
  69525. newState.width = getCoordLength (xml.getStringAttribute ("width", String (newState.width)), viewBoxW);
  69526. newState.height = getCoordLength (xml.getStringAttribute ("height", String (newState.height)), viewBoxH);
  69527. if (xml.hasAttribute ("viewBox"))
  69528. {
  69529. const String viewParams (xml.getStringAttribute ("viewBox"));
  69530. int i = 0;
  69531. float vx, vy, vw, vh;
  69532. if (parseCoords (viewParams, vx, vy, i, true)
  69533. && parseCoords (viewParams, vw, vh, i, true)
  69534. && vw > 0
  69535. && vh > 0)
  69536. {
  69537. newState.viewBoxW = vw;
  69538. newState.viewBoxH = vh;
  69539. int placementFlags = 0;
  69540. const String aspect (xml.getStringAttribute ("preserveAspectRatio"));
  69541. if (aspect.containsIgnoreCase ("none"))
  69542. {
  69543. placementFlags = RectanglePlacement::stretchToFit;
  69544. }
  69545. else
  69546. {
  69547. if (aspect.containsIgnoreCase ("slice"))
  69548. placementFlags |= RectanglePlacement::fillDestination;
  69549. if (aspect.containsIgnoreCase ("xMin"))
  69550. placementFlags |= RectanglePlacement::xLeft;
  69551. else if (aspect.containsIgnoreCase ("xMax"))
  69552. placementFlags |= RectanglePlacement::xRight;
  69553. else
  69554. placementFlags |= RectanglePlacement::xMid;
  69555. if (aspect.containsIgnoreCase ("yMin"))
  69556. placementFlags |= RectanglePlacement::yTop;
  69557. else if (aspect.containsIgnoreCase ("yMax"))
  69558. placementFlags |= RectanglePlacement::yBottom;
  69559. else
  69560. placementFlags |= RectanglePlacement::yMid;
  69561. }
  69562. const RectanglePlacement placement (placementFlags);
  69563. newState.transform
  69564. = placement.getTransformToFit (vx, vy, vw, vh,
  69565. 0.0f, 0.0f, newState.width, newState.height)
  69566. .followedBy (newState.transform);
  69567. }
  69568. }
  69569. else
  69570. {
  69571. if (viewBoxW == 0)
  69572. newState.viewBoxW = newState.width;
  69573. if (viewBoxH == 0)
  69574. newState.viewBoxH = newState.height;
  69575. }
  69576. newState.parseSubElements (xml, drawable);
  69577. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  69578. return drawable;
  69579. }
  69580. private:
  69581. const XmlElement* const topLevelXml;
  69582. float elementX, elementY, width, height, viewBoxW, viewBoxH;
  69583. AffineTransform transform;
  69584. String cssStyleText;
  69585. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  69586. {
  69587. forEachXmlChildElement (xml, e)
  69588. {
  69589. Drawable* d = 0;
  69590. if (e->hasTagName ("g")) d = parseGroupElement (*e);
  69591. else if (e->hasTagName ("svg")) d = parseSVGElement (*e);
  69592. else if (e->hasTagName ("path")) d = parsePath (*e);
  69593. else if (e->hasTagName ("rect")) d = parseRect (*e);
  69594. else if (e->hasTagName ("circle")) d = parseCircle (*e);
  69595. else if (e->hasTagName ("ellipse")) d = parseEllipse (*e);
  69596. else if (e->hasTagName ("line")) d = parseLine (*e);
  69597. else if (e->hasTagName ("polyline")) d = parsePolygon (*e, true);
  69598. else if (e->hasTagName ("polygon")) d = parsePolygon (*e, false);
  69599. else if (e->hasTagName ("text")) d = parseText (*e);
  69600. else if (e->hasTagName ("switch")) d = parseSwitch (*e);
  69601. else if (e->hasTagName ("style")) parseCSSStyle (*e);
  69602. parentDrawable->insertDrawable (d);
  69603. }
  69604. }
  69605. DrawableComposite* parseSwitch (const XmlElement& xml)
  69606. {
  69607. const XmlElement* const group = xml.getChildByName ("g");
  69608. if (group != 0)
  69609. return parseGroupElement (*group);
  69610. return 0;
  69611. }
  69612. DrawableComposite* parseGroupElement (const XmlElement& xml)
  69613. {
  69614. DrawableComposite* const drawable = new DrawableComposite();
  69615. drawable->setName (xml.getStringAttribute ("id"));
  69616. if (xml.hasAttribute ("transform"))
  69617. {
  69618. SVGState newState (*this);
  69619. newState.addTransform (xml);
  69620. newState.parseSubElements (xml, drawable);
  69621. }
  69622. else
  69623. {
  69624. parseSubElements (xml, drawable);
  69625. }
  69626. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  69627. return drawable;
  69628. }
  69629. Drawable* parsePath (const XmlElement& xml) const
  69630. {
  69631. const String d (xml.getStringAttribute ("d").trimStart());
  69632. Path path;
  69633. if (getStyleAttribute (&xml, "fill-rule").trim().equalsIgnoreCase ("evenodd"))
  69634. path.setUsingNonZeroWinding (false);
  69635. int index = 0;
  69636. float lastX = 0, lastY = 0;
  69637. float lastX2 = 0, lastY2 = 0;
  69638. juce_wchar lastCommandChar = 0;
  69639. bool isRelative = true;
  69640. bool carryOn = true;
  69641. const String validCommandChars ("MmLlHhVvCcSsQqTtAaZz");
  69642. while (d[index] != 0)
  69643. {
  69644. float x, y, x2, y2, x3, y3;
  69645. if (validCommandChars.containsChar (d[index]))
  69646. {
  69647. lastCommandChar = d [index++];
  69648. isRelative = (lastCommandChar >= 'a' && lastCommandChar <= 'z');
  69649. }
  69650. switch (lastCommandChar)
  69651. {
  69652. case 'M':
  69653. case 'm':
  69654. case 'L':
  69655. case 'l':
  69656. if (parseCoords (d, x, y, index, false))
  69657. {
  69658. if (isRelative)
  69659. {
  69660. x += lastX;
  69661. y += lastY;
  69662. }
  69663. if (lastCommandChar == 'M' || lastCommandChar == 'm')
  69664. {
  69665. path.startNewSubPath (x, y);
  69666. lastCommandChar = 'l';
  69667. }
  69668. else
  69669. path.lineTo (x, y);
  69670. lastX2 = lastX;
  69671. lastY2 = lastY;
  69672. lastX = x;
  69673. lastY = y;
  69674. }
  69675. else
  69676. {
  69677. ++index;
  69678. }
  69679. break;
  69680. case 'H':
  69681. case 'h':
  69682. if (parseCoord (d, x, index, false, true))
  69683. {
  69684. if (isRelative)
  69685. x += lastX;
  69686. path.lineTo (x, lastY);
  69687. lastX2 = lastX;
  69688. lastX = x;
  69689. }
  69690. else
  69691. {
  69692. ++index;
  69693. }
  69694. break;
  69695. case 'V':
  69696. case 'v':
  69697. if (parseCoord (d, y, index, false, false))
  69698. {
  69699. if (isRelative)
  69700. y += lastY;
  69701. path.lineTo (lastX, y);
  69702. lastY2 = lastY;
  69703. lastY = y;
  69704. }
  69705. else
  69706. {
  69707. ++index;
  69708. }
  69709. break;
  69710. case 'C':
  69711. case 'c':
  69712. if (parseCoords (d, x, y, index, false)
  69713. && parseCoords (d, x2, y2, index, false)
  69714. && parseCoords (d, x3, y3, index, false))
  69715. {
  69716. if (isRelative)
  69717. {
  69718. x += lastX;
  69719. y += lastY;
  69720. x2 += lastX;
  69721. y2 += lastY;
  69722. x3 += lastX;
  69723. y3 += lastY;
  69724. }
  69725. path.cubicTo (x, y, x2, y2, x3, y3);
  69726. lastX2 = x2;
  69727. lastY2 = y2;
  69728. lastX = x3;
  69729. lastY = y3;
  69730. }
  69731. else
  69732. {
  69733. ++index;
  69734. }
  69735. break;
  69736. case 'S':
  69737. case 's':
  69738. if (parseCoords (d, x, y, index, false)
  69739. && parseCoords (d, x3, y3, index, false))
  69740. {
  69741. if (isRelative)
  69742. {
  69743. x += lastX;
  69744. y += lastY;
  69745. x3 += lastX;
  69746. y3 += lastY;
  69747. }
  69748. x2 = lastX + (lastX - lastX2);
  69749. y2 = lastY + (lastY - lastY2);
  69750. path.cubicTo (x2, y2, x, y, x3, y3);
  69751. lastX2 = x;
  69752. lastY2 = y;
  69753. lastX = x3;
  69754. lastY = y3;
  69755. }
  69756. else
  69757. {
  69758. ++index;
  69759. }
  69760. break;
  69761. case 'Q':
  69762. case 'q':
  69763. if (parseCoords (d, x, y, index, false)
  69764. && parseCoords (d, x2, y2, index, false))
  69765. {
  69766. if (isRelative)
  69767. {
  69768. x += lastX;
  69769. y += lastY;
  69770. x2 += lastX;
  69771. y2 += lastY;
  69772. }
  69773. path.quadraticTo (x, y, x2, y2);
  69774. lastX2 = x;
  69775. lastY2 = y;
  69776. lastX = x2;
  69777. lastY = y2;
  69778. }
  69779. else
  69780. {
  69781. ++index;
  69782. }
  69783. break;
  69784. case 'T':
  69785. case 't':
  69786. if (parseCoords (d, x, y, index, false))
  69787. {
  69788. if (isRelative)
  69789. {
  69790. x += lastX;
  69791. y += lastY;
  69792. }
  69793. x2 = lastX + (lastX - lastX2);
  69794. y2 = lastY + (lastY - lastY2);
  69795. path.quadraticTo (x2, y2, x, y);
  69796. lastX2 = x2;
  69797. lastY2 = y2;
  69798. lastX = x;
  69799. lastY = y;
  69800. }
  69801. else
  69802. {
  69803. ++index;
  69804. }
  69805. break;
  69806. case 'A':
  69807. case 'a':
  69808. if (parseCoords (d, x, y, index, false))
  69809. {
  69810. String num;
  69811. if (parseNextNumber (d, num, index, false))
  69812. {
  69813. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  69814. if (parseNextNumber (d, num, index, false))
  69815. {
  69816. const bool largeArc = num.getIntValue() != 0;
  69817. if (parseNextNumber (d, num, index, false))
  69818. {
  69819. const bool sweep = num.getIntValue() != 0;
  69820. if (parseCoords (d, x2, y2, index, false))
  69821. {
  69822. if (isRelative)
  69823. {
  69824. x2 += lastX;
  69825. y2 += lastY;
  69826. }
  69827. if (lastX != x2 || lastY != y2)
  69828. {
  69829. double centreX, centreY, startAngle, deltaAngle;
  69830. double rx = x, ry = y;
  69831. endpointToCentreParameters (lastX, lastY, x2, y2,
  69832. angle, largeArc, sweep,
  69833. rx, ry, centreX, centreY,
  69834. startAngle, deltaAngle);
  69835. path.addCentredArc ((float) centreX, (float) centreY,
  69836. (float) rx, (float) ry,
  69837. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  69838. false);
  69839. path.lineTo (x2, y2);
  69840. }
  69841. lastX2 = lastX;
  69842. lastY2 = lastY;
  69843. lastX = x2;
  69844. lastY = y2;
  69845. }
  69846. }
  69847. }
  69848. }
  69849. }
  69850. else
  69851. {
  69852. ++index;
  69853. }
  69854. break;
  69855. case 'Z':
  69856. case 'z':
  69857. path.closeSubPath();
  69858. while (CharacterFunctions::isWhitespace (d [index]))
  69859. ++index;
  69860. break;
  69861. default:
  69862. carryOn = false;
  69863. break;
  69864. }
  69865. if (! carryOn)
  69866. break;
  69867. }
  69868. return parseShape (xml, path);
  69869. }
  69870. Drawable* parseRect (const XmlElement& xml) const
  69871. {
  69872. Path rect;
  69873. const bool hasRX = xml.hasAttribute ("rx");
  69874. const bool hasRY = xml.hasAttribute ("ry");
  69875. if (hasRX || hasRY)
  69876. {
  69877. float rx = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  69878. float ry = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  69879. if (! hasRX)
  69880. rx = ry;
  69881. else if (! hasRY)
  69882. ry = rx;
  69883. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  69884. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  69885. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  69886. getCoordLength (xml.getStringAttribute ("height"), viewBoxH),
  69887. rx, ry);
  69888. }
  69889. else
  69890. {
  69891. rect.addRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  69892. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  69893. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  69894. getCoordLength (xml.getStringAttribute ("height"), viewBoxH));
  69895. }
  69896. return parseShape (xml, rect);
  69897. }
  69898. Drawable* parseCircle (const XmlElement& xml) const
  69899. {
  69900. Path circle;
  69901. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  69902. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  69903. const float radius = getCoordLength (xml.getStringAttribute ("r"), viewBoxW);
  69904. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  69905. return parseShape (xml, circle);
  69906. }
  69907. Drawable* parseEllipse (const XmlElement& xml) const
  69908. {
  69909. Path ellipse;
  69910. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  69911. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  69912. const float radiusX = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  69913. const float radiusY = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  69914. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  69915. return parseShape (xml, ellipse);
  69916. }
  69917. Drawable* parseLine (const XmlElement& xml) const
  69918. {
  69919. Path line;
  69920. const float x1 = getCoordLength (xml.getStringAttribute ("x1"), viewBoxW);
  69921. const float y1 = getCoordLength (xml.getStringAttribute ("y1"), viewBoxH);
  69922. const float x2 = getCoordLength (xml.getStringAttribute ("x2"), viewBoxW);
  69923. const float y2 = getCoordLength (xml.getStringAttribute ("y2"), viewBoxH);
  69924. line.startNewSubPath (x1, y1);
  69925. line.lineTo (x2, y2);
  69926. return parseShape (xml, line);
  69927. }
  69928. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  69929. {
  69930. const String points (xml.getStringAttribute ("points"));
  69931. Path path;
  69932. int index = 0;
  69933. float x, y;
  69934. if (parseCoords (points, x, y, index, true))
  69935. {
  69936. float firstX = x;
  69937. float firstY = y;
  69938. float lastX = 0, lastY = 0;
  69939. path.startNewSubPath (x, y);
  69940. while (parseCoords (points, x, y, index, true))
  69941. {
  69942. lastX = x;
  69943. lastY = y;
  69944. path.lineTo (x, y);
  69945. }
  69946. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  69947. path.closeSubPath();
  69948. }
  69949. return parseShape (xml, path);
  69950. }
  69951. Drawable* parseShape (const XmlElement& xml, Path& path,
  69952. const bool shouldParseTransform = true) const
  69953. {
  69954. if (shouldParseTransform && xml.hasAttribute ("transform"))
  69955. {
  69956. SVGState newState (*this);
  69957. newState.addTransform (xml);
  69958. return newState.parseShape (xml, path, false);
  69959. }
  69960. DrawablePath* dp = new DrawablePath();
  69961. dp->setName (xml.getStringAttribute ("id"));
  69962. dp->setFill (Colours::transparentBlack);
  69963. path.applyTransform (transform);
  69964. dp->setPath (path);
  69965. Path::Iterator iter (path);
  69966. bool containsClosedSubPath = false;
  69967. while (iter.next())
  69968. {
  69969. if (iter.elementType == Path::Iterator::closePath)
  69970. {
  69971. containsClosedSubPath = true;
  69972. break;
  69973. }
  69974. }
  69975. dp->setFill (getPathFillType (path,
  69976. getStyleAttribute (&xml, "fill"),
  69977. getStyleAttribute (&xml, "fill-opacity"),
  69978. getStyleAttribute (&xml, "opacity"),
  69979. containsClosedSubPath ? Colours::black
  69980. : Colours::transparentBlack));
  69981. const String strokeType (getStyleAttribute (&xml, "stroke"));
  69982. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase ("none"))
  69983. {
  69984. dp->setStrokeFill (getPathFillType (path, strokeType,
  69985. getStyleAttribute (&xml, "stroke-opacity"),
  69986. getStyleAttribute (&xml, "opacity"),
  69987. Colours::transparentBlack));
  69988. dp->setStrokeType (getStrokeFor (&xml));
  69989. }
  69990. return dp;
  69991. }
  69992. const XmlElement* findLinkedElement (const XmlElement* e) const
  69993. {
  69994. const String id (e->getStringAttribute ("xlink:href"));
  69995. if (! id.startsWithChar ('#'))
  69996. return 0;
  69997. return findElementForId (topLevelXml, id.substring (1));
  69998. }
  69999. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  70000. {
  70001. if (fillXml == 0)
  70002. return;
  70003. forEachXmlChildElementWithTagName (*fillXml, e, "stop")
  70004. {
  70005. int index = 0;
  70006. Colour col (parseColour (getStyleAttribute (e, "stop-color"), index, Colours::black));
  70007. const String opacity (getStyleAttribute (e, "stop-opacity", "1"));
  70008. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  70009. double offset = e->getDoubleAttribute ("offset");
  70010. if (e->getStringAttribute ("offset").containsChar ('%'))
  70011. offset *= 0.01;
  70012. cg.addColour (jlimit (0.0, 1.0, offset), col);
  70013. }
  70014. }
  70015. const FillType getPathFillType (const Path& path,
  70016. const String& fill,
  70017. const String& fillOpacity,
  70018. const String& overallOpacity,
  70019. const Colour& defaultColour) const
  70020. {
  70021. float opacity = 1.0f;
  70022. if (overallOpacity.isNotEmpty())
  70023. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  70024. if (fillOpacity.isNotEmpty())
  70025. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  70026. if (fill.startsWithIgnoreCase ("url"))
  70027. {
  70028. const String id (fill.fromFirstOccurrenceOf ("#", false, false)
  70029. .upToLastOccurrenceOf (")", false, false).trim());
  70030. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  70031. if (fillXml != 0
  70032. && (fillXml->hasTagName ("linearGradient")
  70033. || fillXml->hasTagName ("radialGradient")))
  70034. {
  70035. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  70036. ColourGradient gradient;
  70037. addGradientStopsIn (gradient, inheritedFrom);
  70038. addGradientStopsIn (gradient, fillXml);
  70039. if (gradient.getNumColours() > 0)
  70040. {
  70041. gradient.addColour (0.0, gradient.getColour (0));
  70042. gradient.addColour (1.0, gradient.getColour (gradient.getNumColours() - 1));
  70043. }
  70044. else
  70045. {
  70046. gradient.addColour (0.0, Colours::black);
  70047. gradient.addColour (1.0, Colours::black);
  70048. }
  70049. if (overallOpacity.isNotEmpty())
  70050. gradient.multiplyOpacity (overallOpacity.getFloatValue());
  70051. jassert (gradient.getNumColours() > 0);
  70052. gradient.isRadial = fillXml->hasTagName ("radialGradient");
  70053. float gradientWidth = viewBoxW;
  70054. float gradientHeight = viewBoxH;
  70055. float dx = 0.0f;
  70056. float dy = 0.0f;
  70057. const bool userSpace = fillXml->getStringAttribute ("gradientUnits").equalsIgnoreCase ("userSpaceOnUse");
  70058. if (! userSpace)
  70059. {
  70060. const Rectangle<float> bounds (path.getBounds());
  70061. dx = bounds.getX();
  70062. dy = bounds.getY();
  70063. gradientWidth = bounds.getWidth();
  70064. gradientHeight = bounds.getHeight();
  70065. }
  70066. if (gradient.isRadial)
  70067. {
  70068. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("cx", "50%"), gradientWidth),
  70069. dy + getCoordLength (fillXml->getStringAttribute ("cy", "50%"), gradientHeight));
  70070. const float radius = getCoordLength (fillXml->getStringAttribute ("r", "50%"), gradientWidth);
  70071. gradient.point2 = gradient.point1 + Point<float> (radius, 0.0f);
  70072. //xxx (the fx, fy focal point isn't handled properly here..)
  70073. }
  70074. else
  70075. {
  70076. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x1", "0%"), gradientWidth),
  70077. dy + getCoordLength (fillXml->getStringAttribute ("y1", "0%"), gradientHeight));
  70078. gradient.point2.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x2", "100%"), gradientWidth),
  70079. dy + getCoordLength (fillXml->getStringAttribute ("y2", "0%"), gradientHeight));
  70080. if (gradient.point1 == gradient.point2)
  70081. return Colour (gradient.getColour (gradient.getNumColours() - 1));
  70082. }
  70083. FillType type (gradient);
  70084. type.transform = parseTransform (fillXml->getStringAttribute ("gradientTransform"))
  70085. .followedBy (transform);
  70086. return type;
  70087. }
  70088. }
  70089. if (fill.equalsIgnoreCase ("none"))
  70090. return Colours::transparentBlack;
  70091. int i = 0;
  70092. const Colour colour (parseColour (fill, i, defaultColour));
  70093. return colour.withMultipliedAlpha (opacity);
  70094. }
  70095. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  70096. {
  70097. const String strokeWidth (getStyleAttribute (xml, "stroke-width"));
  70098. const String cap (getStyleAttribute (xml, "stroke-linecap"));
  70099. const String join (getStyleAttribute (xml, "stroke-linejoin"));
  70100. //const String mitreLimit (getStyleAttribute (xml, "stroke-miterlimit"));
  70101. //const String dashArray (getStyleAttribute (xml, "stroke-dasharray"));
  70102. //const String dashOffset (getStyleAttribute (xml, "stroke-dashoffset"));
  70103. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  70104. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  70105. if (join.equalsIgnoreCase ("round"))
  70106. joinStyle = PathStrokeType::curved;
  70107. else if (join.equalsIgnoreCase ("bevel"))
  70108. joinStyle = PathStrokeType::beveled;
  70109. if (cap.equalsIgnoreCase ("round"))
  70110. capStyle = PathStrokeType::rounded;
  70111. else if (cap.equalsIgnoreCase ("square"))
  70112. capStyle = PathStrokeType::square;
  70113. float ox = 0.0f, oy = 0.0f;
  70114. float x = getCoordLength (strokeWidth, viewBoxW), y = 0.0f;
  70115. transform.transformPoints (ox, oy, x, y);
  70116. return PathStrokeType (strokeWidth.isNotEmpty() ? juce_hypotf (x - ox, y - oy) : 1.0f,
  70117. joinStyle, capStyle);
  70118. }
  70119. Drawable* parseText (const XmlElement& xml)
  70120. {
  70121. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  70122. getCoordList (xCoords, getInheritedAttribute (&xml, "x"), true, true);
  70123. getCoordList (yCoords, getInheritedAttribute (&xml, "y"), true, false);
  70124. getCoordList (dxCoords, getInheritedAttribute (&xml, "dx"), true, true);
  70125. getCoordList (dyCoords, getInheritedAttribute (&xml, "dy"), true, false);
  70126. //xxx not done text yet!
  70127. forEachXmlChildElement (xml, e)
  70128. {
  70129. if (e->isTextElement())
  70130. {
  70131. const String text (e->getText());
  70132. Path path;
  70133. Drawable* s = parseShape (*e, path);
  70134. delete s;
  70135. }
  70136. else if (e->hasTagName ("tspan"))
  70137. {
  70138. Drawable* s = parseText (*e);
  70139. delete s;
  70140. }
  70141. }
  70142. return 0;
  70143. }
  70144. void addTransform (const XmlElement& xml)
  70145. {
  70146. transform = parseTransform (xml.getStringAttribute ("transform"))
  70147. .followedBy (transform);
  70148. }
  70149. bool parseCoord (const String& s, float& value, int& index,
  70150. const bool allowUnits, const bool isX) const
  70151. {
  70152. String number;
  70153. if (! parseNextNumber (s, number, index, allowUnits))
  70154. {
  70155. value = 0;
  70156. return false;
  70157. }
  70158. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  70159. return true;
  70160. }
  70161. bool parseCoords (const String& s, float& x, float& y,
  70162. int& index, const bool allowUnits) const
  70163. {
  70164. return parseCoord (s, x, index, allowUnits, true)
  70165. && parseCoord (s, y, index, allowUnits, false);
  70166. }
  70167. float getCoordLength (const String& s, const float sizeForProportions) const
  70168. {
  70169. float n = s.getFloatValue();
  70170. const int len = s.length();
  70171. if (len > 2)
  70172. {
  70173. const float dpi = 96.0f;
  70174. const juce_wchar n1 = s [len - 2];
  70175. const juce_wchar n2 = s [len - 1];
  70176. if (n1 == 'i' && n2 == 'n')
  70177. n *= dpi;
  70178. else if (n1 == 'm' && n2 == 'm')
  70179. n *= dpi / 25.4f;
  70180. else if (n1 == 'c' && n2 == 'm')
  70181. n *= dpi / 2.54f;
  70182. else if (n1 == 'p' && n2 == 'c')
  70183. n *= 15.0f;
  70184. else if (n2 == '%')
  70185. n *= 0.01f * sizeForProportions;
  70186. }
  70187. return n;
  70188. }
  70189. void getCoordList (Array <float>& coords, const String& list,
  70190. const bool allowUnits, const bool isX) const
  70191. {
  70192. int index = 0;
  70193. float value;
  70194. while (parseCoord (list, value, index, allowUnits, isX))
  70195. coords.add (value);
  70196. }
  70197. void parseCSSStyle (const XmlElement& xml)
  70198. {
  70199. cssStyleText = xml.getAllSubText() + "\n" + cssStyleText;
  70200. }
  70201. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  70202. const String& defaultValue = String::empty) const
  70203. {
  70204. if (xml->hasAttribute (attributeName))
  70205. return xml->getStringAttribute (attributeName, defaultValue);
  70206. const String styleAtt (xml->getStringAttribute ("style"));
  70207. if (styleAtt.isNotEmpty())
  70208. {
  70209. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  70210. if (value.isNotEmpty())
  70211. return value;
  70212. }
  70213. else if (xml->hasAttribute ("class"))
  70214. {
  70215. const String className ("." + xml->getStringAttribute ("class"));
  70216. int index = cssStyleText.indexOfIgnoreCase (className + " ");
  70217. if (index < 0)
  70218. index = cssStyleText.indexOfIgnoreCase (className + "{");
  70219. if (index >= 0)
  70220. {
  70221. const int openBracket = cssStyleText.indexOfChar (index, '{');
  70222. if (openBracket > index)
  70223. {
  70224. const int closeBracket = cssStyleText.indexOfChar (openBracket, '}');
  70225. if (closeBracket > openBracket)
  70226. {
  70227. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  70228. if (value.isNotEmpty())
  70229. return value;
  70230. }
  70231. }
  70232. }
  70233. }
  70234. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  70235. if (xml != 0)
  70236. return getStyleAttribute (xml, attributeName, defaultValue);
  70237. return defaultValue;
  70238. }
  70239. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  70240. {
  70241. if (xml->hasAttribute (attributeName))
  70242. return xml->getStringAttribute (attributeName);
  70243. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  70244. if (xml != 0)
  70245. return getInheritedAttribute (xml, attributeName);
  70246. return String::empty;
  70247. }
  70248. static bool isIdentifierChar (const juce_wchar c)
  70249. {
  70250. return CharacterFunctions::isLetter (c) || c == '-';
  70251. }
  70252. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  70253. {
  70254. int i = 0;
  70255. for (;;)
  70256. {
  70257. i = list.indexOf (i, attributeName);
  70258. if (i < 0)
  70259. break;
  70260. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  70261. && ! isIdentifierChar (list [i + attributeName.length()]))
  70262. {
  70263. i = list.indexOfChar (i, ':');
  70264. if (i < 0)
  70265. break;
  70266. int end = list.indexOfChar (i, ';');
  70267. if (end < 0)
  70268. end = 0x7ffff;
  70269. return list.substring (i + 1, end).trim();
  70270. }
  70271. ++i;
  70272. }
  70273. return defaultValue;
  70274. }
  70275. static bool parseNextNumber (const String& source, String& value, int& index, const bool allowUnits)
  70276. {
  70277. const juce_wchar* const s = source;
  70278. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  70279. ++index;
  70280. int start = index;
  70281. if (CharacterFunctions::isDigit (s[index]) || s[index] == '.' || s[index] == '-')
  70282. ++index;
  70283. while (CharacterFunctions::isDigit (s[index]) || s[index] == '.')
  70284. ++index;
  70285. if ((s[index] == 'e' || s[index] == 'E')
  70286. && (CharacterFunctions::isDigit (s[index + 1])
  70287. || s[index + 1] == '-'
  70288. || s[index + 1] == '+'))
  70289. {
  70290. index += 2;
  70291. while (CharacterFunctions::isDigit (s[index]))
  70292. ++index;
  70293. }
  70294. if (allowUnits)
  70295. {
  70296. while (CharacterFunctions::isLetter (s[index]))
  70297. ++index;
  70298. }
  70299. if (index == start)
  70300. return false;
  70301. value = String (s + start, index - start);
  70302. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  70303. ++index;
  70304. return true;
  70305. }
  70306. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  70307. {
  70308. if (s [index] == '#')
  70309. {
  70310. uint32 hex [6];
  70311. zeromem (hex, sizeof (hex));
  70312. int numChars = 0;
  70313. for (int i = 6; --i >= 0;)
  70314. {
  70315. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  70316. if (hexValue >= 0)
  70317. hex [numChars++] = hexValue;
  70318. else
  70319. break;
  70320. }
  70321. if (numChars <= 3)
  70322. return Colour ((uint8) (hex [0] * 0x11),
  70323. (uint8) (hex [1] * 0x11),
  70324. (uint8) (hex [2] * 0x11));
  70325. else
  70326. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  70327. (uint8) ((hex [2] << 4) + hex [3]),
  70328. (uint8) ((hex [4] << 4) + hex [5]));
  70329. }
  70330. else if (s [index] == 'r'
  70331. && s [index + 1] == 'g'
  70332. && s [index + 2] == 'b')
  70333. {
  70334. const int openBracket = s.indexOfChar (index, '(');
  70335. const int closeBracket = s.indexOfChar (openBracket, ')');
  70336. if (openBracket >= 3 && closeBracket > openBracket)
  70337. {
  70338. index = closeBracket;
  70339. StringArray tokens;
  70340. tokens.addTokens (s.substring (openBracket + 1, closeBracket), ",", "");
  70341. tokens.trim();
  70342. tokens.removeEmptyStrings();
  70343. if (tokens[0].containsChar ('%'))
  70344. return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
  70345. (uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
  70346. (uint8) roundToInt (2.55 * tokens[2].getDoubleValue()));
  70347. else
  70348. return Colour ((uint8) tokens[0].getIntValue(),
  70349. (uint8) tokens[1].getIntValue(),
  70350. (uint8) tokens[2].getIntValue());
  70351. }
  70352. }
  70353. return Colours::findColourForName (s, defaultColour);
  70354. }
  70355. static const AffineTransform parseTransform (String t)
  70356. {
  70357. AffineTransform result;
  70358. while (t.isNotEmpty())
  70359. {
  70360. StringArray tokens;
  70361. tokens.addTokens (t.fromFirstOccurrenceOf ("(", false, false)
  70362. .upToFirstOccurrenceOf (")", false, false),
  70363. ", ", String::empty);
  70364. tokens.removeEmptyStrings (true);
  70365. float numbers [6];
  70366. for (int i = 0; i < 6; ++i)
  70367. numbers[i] = tokens[i].getFloatValue();
  70368. AffineTransform trans;
  70369. if (t.startsWithIgnoreCase ("matrix"))
  70370. {
  70371. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  70372. numbers[1], numbers[3], numbers[5]);
  70373. }
  70374. else if (t.startsWithIgnoreCase ("translate"))
  70375. {
  70376. jassert (tokens.size() == 2);
  70377. trans = AffineTransform::translation (numbers[0], numbers[1]);
  70378. }
  70379. else if (t.startsWithIgnoreCase ("scale"))
  70380. {
  70381. if (tokens.size() == 1)
  70382. trans = AffineTransform::scale (numbers[0], numbers[0]);
  70383. else
  70384. trans = AffineTransform::scale (numbers[0], numbers[1]);
  70385. }
  70386. else if (t.startsWithIgnoreCase ("rotate"))
  70387. {
  70388. if (tokens.size() != 3)
  70389. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi));
  70390. else
  70391. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi),
  70392. numbers[1], numbers[2]);
  70393. }
  70394. else if (t.startsWithIgnoreCase ("skewX"))
  70395. {
  70396. trans = AffineTransform (1.0f, std::tan (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  70397. 0.0f, 1.0f, 0.0f);
  70398. }
  70399. else if (t.startsWithIgnoreCase ("skewY"))
  70400. {
  70401. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  70402. std::tan (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  70403. }
  70404. result = trans.followedBy (result);
  70405. t = t.fromFirstOccurrenceOf (")", false, false).trimStart();
  70406. }
  70407. return result;
  70408. }
  70409. static void endpointToCentreParameters (const double x1, const double y1,
  70410. const double x2, const double y2,
  70411. const double angle,
  70412. const bool largeArc, const bool sweep,
  70413. double& rx, double& ry,
  70414. double& centreX, double& centreY,
  70415. double& startAngle, double& deltaAngle)
  70416. {
  70417. const double midX = (x1 - x2) * 0.5;
  70418. const double midY = (y1 - y2) * 0.5;
  70419. const double cosAngle = cos (angle);
  70420. const double sinAngle = sin (angle);
  70421. const double xp = cosAngle * midX + sinAngle * midY;
  70422. const double yp = cosAngle * midY - sinAngle * midX;
  70423. const double xp2 = xp * xp;
  70424. const double yp2 = yp * yp;
  70425. double rx2 = rx * rx;
  70426. double ry2 = ry * ry;
  70427. const double s = (xp2 / rx2) + (yp2 / ry2);
  70428. double c;
  70429. if (s <= 1.0)
  70430. {
  70431. c = std::sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  70432. / (( rx2 * yp2) + (ry2 * xp2))));
  70433. if (largeArc == sweep)
  70434. c = -c;
  70435. }
  70436. else
  70437. {
  70438. const double s2 = std::sqrt (s);
  70439. rx *= s2;
  70440. ry *= s2;
  70441. rx2 = rx * rx;
  70442. ry2 = ry * ry;
  70443. c = 0;
  70444. }
  70445. const double cpx = ((rx * yp) / ry) * c;
  70446. const double cpy = ((-ry * xp) / rx) * c;
  70447. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  70448. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  70449. const double ux = (xp - cpx) / rx;
  70450. const double uy = (yp - cpy) / ry;
  70451. const double vx = (-xp - cpx) / rx;
  70452. const double vy = (-yp - cpy) / ry;
  70453. const double length = juce_hypot (ux, uy);
  70454. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  70455. if (uy < 0)
  70456. startAngle = -startAngle;
  70457. startAngle += double_Pi * 0.5;
  70458. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  70459. / (length * juce_hypot (vx, vy))));
  70460. if ((ux * vy) - (uy * vx) < 0)
  70461. deltaAngle = -deltaAngle;
  70462. if (sweep)
  70463. {
  70464. if (deltaAngle < 0)
  70465. deltaAngle += double_Pi * 2.0;
  70466. }
  70467. else
  70468. {
  70469. if (deltaAngle > 0)
  70470. deltaAngle -= double_Pi * 2.0;
  70471. }
  70472. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  70473. }
  70474. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  70475. {
  70476. forEachXmlChildElement (*parent, e)
  70477. {
  70478. if (e->compareAttribute ("id", id))
  70479. return e;
  70480. const XmlElement* const found = findElementForId (e, id);
  70481. if (found != 0)
  70482. return found;
  70483. }
  70484. return 0;
  70485. }
  70486. SVGState& operator= (const SVGState&);
  70487. };
  70488. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  70489. {
  70490. SVGState state (&svgDocument);
  70491. return state.parseSVGElement (svgDocument);
  70492. }
  70493. END_JUCE_NAMESPACE
  70494. /*** End of inlined file: juce_SVGParser.cpp ***/
  70495. /*** Start of inlined file: juce_DropShadowEffect.cpp ***/
  70496. BEGIN_JUCE_NAMESPACE
  70497. #if JUCE_MSVC && JUCE_DEBUG
  70498. #pragma optimize ("t", on)
  70499. #endif
  70500. DropShadowEffect::DropShadowEffect()
  70501. : offsetX (0),
  70502. offsetY (0),
  70503. radius (4),
  70504. opacity (0.6f)
  70505. {
  70506. }
  70507. DropShadowEffect::~DropShadowEffect()
  70508. {
  70509. }
  70510. void DropShadowEffect::setShadowProperties (const float newRadius,
  70511. const float newOpacity,
  70512. const int newShadowOffsetX,
  70513. const int newShadowOffsetY)
  70514. {
  70515. radius = jmax (1.1f, newRadius);
  70516. offsetX = newShadowOffsetX;
  70517. offsetY = newShadowOffsetY;
  70518. opacity = newOpacity;
  70519. }
  70520. void DropShadowEffect::applyEffect (Image& image, Graphics& g)
  70521. {
  70522. const int w = image.getWidth();
  70523. const int h = image.getHeight();
  70524. Image shadowImage (Image::SingleChannel, w, h, false);
  70525. const Image::BitmapData srcData (image, 0, 0, w, h);
  70526. const Image::BitmapData destData (shadowImage, 0, 0, w, h, true);
  70527. const int filter = roundToInt (63.0f / radius);
  70528. const int radiusMinus1 = roundToInt ((radius - 1.0f) * 63.0f);
  70529. for (int x = w; --x >= 0;)
  70530. {
  70531. int shadowAlpha = 0;
  70532. const PixelARGB* src = ((const PixelARGB*) srcData.data) + x;
  70533. uint8* shadowPix = destData.data + x;
  70534. for (int y = h; --y >= 0;)
  70535. {
  70536. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  70537. *shadowPix = (uint8) shadowAlpha;
  70538. src = (const PixelARGB*) (((const uint8*) src) + srcData.lineStride);
  70539. shadowPix += destData.lineStride;
  70540. }
  70541. }
  70542. for (int y = h; --y >= 0;)
  70543. {
  70544. int shadowAlpha = 0;
  70545. uint8* shadowPix = destData.getLinePointer (y);
  70546. for (int x = w; --x >= 0;)
  70547. {
  70548. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  70549. *shadowPix++ = (uint8) shadowAlpha;
  70550. }
  70551. }
  70552. g.setColour (Colours::black.withAlpha (opacity));
  70553. g.drawImageAt (shadowImage, offsetX, offsetY, true);
  70554. g.setOpacity (1.0f);
  70555. g.drawImageAt (image, 0, 0);
  70556. }
  70557. #if JUCE_MSVC && JUCE_DEBUG
  70558. #pragma optimize ("", on) // resets optimisations to the project defaults
  70559. #endif
  70560. END_JUCE_NAMESPACE
  70561. /*** End of inlined file: juce_DropShadowEffect.cpp ***/
  70562. /*** Start of inlined file: juce_GlowEffect.cpp ***/
  70563. BEGIN_JUCE_NAMESPACE
  70564. GlowEffect::GlowEffect()
  70565. : radius (2.0f),
  70566. colour (Colours::white)
  70567. {
  70568. }
  70569. GlowEffect::~GlowEffect()
  70570. {
  70571. }
  70572. void GlowEffect::setGlowProperties (const float newRadius,
  70573. const Colour& newColour)
  70574. {
  70575. radius = newRadius;
  70576. colour = newColour;
  70577. }
  70578. void GlowEffect::applyEffect (Image& image, Graphics& g)
  70579. {
  70580. Image temp (image.getFormat(), image.getWidth(), image.getHeight(), true);
  70581. ImageConvolutionKernel blurKernel (roundToInt (radius * 2.0f));
  70582. blurKernel.createGaussianBlur (radius);
  70583. blurKernel.rescaleAllValues (radius);
  70584. blurKernel.applyToImage (temp, image, image.getBounds());
  70585. g.setColour (colour);
  70586. g.drawImageAt (temp, 0, 0, true);
  70587. g.setOpacity (1.0f);
  70588. g.drawImageAt (image, 0, 0, false);
  70589. }
  70590. END_JUCE_NAMESPACE
  70591. /*** End of inlined file: juce_GlowEffect.cpp ***/
  70592. /*** Start of inlined file: juce_ReduceOpacityEffect.cpp ***/
  70593. BEGIN_JUCE_NAMESPACE
  70594. ReduceOpacityEffect::ReduceOpacityEffect (const float opacity_)
  70595. : opacity (opacity_)
  70596. {
  70597. }
  70598. ReduceOpacityEffect::~ReduceOpacityEffect()
  70599. {
  70600. }
  70601. void ReduceOpacityEffect::setOpacity (const float newOpacity)
  70602. {
  70603. opacity = jlimit (0.0f, 1.0f, newOpacity);
  70604. }
  70605. void ReduceOpacityEffect::applyEffect (Image& image, Graphics& g)
  70606. {
  70607. g.setOpacity (opacity);
  70608. g.drawImageAt (image, 0, 0);
  70609. }
  70610. END_JUCE_NAMESPACE
  70611. /*** End of inlined file: juce_ReduceOpacityEffect.cpp ***/
  70612. /*** Start of inlined file: juce_Font.cpp ***/
  70613. BEGIN_JUCE_NAMESPACE
  70614. namespace FontValues
  70615. {
  70616. static float limitFontHeight (const float height) throw()
  70617. {
  70618. return jlimit (0.1f, 10000.0f, height);
  70619. }
  70620. static const float defaultFontHeight = 14.0f;
  70621. static String fallbackFont;
  70622. }
  70623. Font::SharedFontInternal::SharedFontInternal (const String& typefaceName_, const float height_, const float horizontalScale_,
  70624. const float kerning_, const float ascent_, const int styleFlags_,
  70625. Typeface* const typeface_) throw()
  70626. : typefaceName (typefaceName_),
  70627. height (height_),
  70628. horizontalScale (horizontalScale_),
  70629. kerning (kerning_),
  70630. ascent (ascent_),
  70631. styleFlags (styleFlags_),
  70632. typeface (typeface_)
  70633. {
  70634. }
  70635. Font::SharedFontInternal::SharedFontInternal (const SharedFontInternal& other) throw()
  70636. : typefaceName (other.typefaceName),
  70637. height (other.height),
  70638. horizontalScale (other.horizontalScale),
  70639. kerning (other.kerning),
  70640. ascent (other.ascent),
  70641. styleFlags (other.styleFlags),
  70642. typeface (other.typeface)
  70643. {
  70644. }
  70645. Font::Font() throw()
  70646. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::defaultFontHeight,
  70647. 1.0f, 0, 0, Font::plain, 0))
  70648. {
  70649. }
  70650. Font::Font (const float fontHeight, const int styleFlags_) throw()
  70651. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::limitFontHeight (fontHeight),
  70652. 1.0f, 0, 0, styleFlags_, 0))
  70653. {
  70654. }
  70655. Font::Font (const String& typefaceName_,
  70656. const float fontHeight,
  70657. const int styleFlags_) throw()
  70658. : font (new SharedFontInternal (typefaceName_, FontValues::limitFontHeight (fontHeight),
  70659. 1.0f, 0, 0, styleFlags_, 0))
  70660. {
  70661. }
  70662. Font::Font (const Font& other) throw()
  70663. : font (other.font)
  70664. {
  70665. }
  70666. Font& Font::operator= (const Font& other) throw()
  70667. {
  70668. font = other.font;
  70669. return *this;
  70670. }
  70671. Font::~Font() throw()
  70672. {
  70673. }
  70674. Font::Font (const Typeface::Ptr& typeface) throw()
  70675. : font (new SharedFontInternal (typeface->getName(), FontValues::defaultFontHeight,
  70676. 1.0f, 0, 0, Font::plain, typeface))
  70677. {
  70678. }
  70679. bool Font::operator== (const Font& other) const throw()
  70680. {
  70681. return font == other.font
  70682. || (font->height == other.font->height
  70683. && font->styleFlags == other.font->styleFlags
  70684. && font->horizontalScale == other.font->horizontalScale
  70685. && font->kerning == other.font->kerning
  70686. && font->typefaceName == other.font->typefaceName);
  70687. }
  70688. bool Font::operator!= (const Font& other) const throw()
  70689. {
  70690. return ! operator== (other);
  70691. }
  70692. void Font::dupeInternalIfShared() throw()
  70693. {
  70694. if (font->getReferenceCount() > 1)
  70695. font = new SharedFontInternal (*font);
  70696. }
  70697. const String Font::getDefaultSansSerifFontName() throw()
  70698. {
  70699. static const String name ("<Sans-Serif>");
  70700. return name;
  70701. }
  70702. const String Font::getDefaultSerifFontName() throw()
  70703. {
  70704. static const String name ("<Serif>");
  70705. return name;
  70706. }
  70707. const String Font::getDefaultMonospacedFontName() throw()
  70708. {
  70709. static const String name ("<Monospaced>");
  70710. return name;
  70711. }
  70712. void Font::setTypefaceName (const String& faceName) throw()
  70713. {
  70714. if (faceName != font->typefaceName)
  70715. {
  70716. dupeInternalIfShared();
  70717. font->typefaceName = faceName;
  70718. font->typeface = 0;
  70719. font->ascent = 0;
  70720. }
  70721. }
  70722. const String Font::getFallbackFontName() throw()
  70723. {
  70724. return FontValues::fallbackFont;
  70725. }
  70726. void Font::setFallbackFontName (const String& name) throw()
  70727. {
  70728. FontValues::fallbackFont = name;
  70729. }
  70730. void Font::setHeight (float newHeight) throw()
  70731. {
  70732. newHeight = FontValues::limitFontHeight (newHeight);
  70733. if (font->height != newHeight)
  70734. {
  70735. dupeInternalIfShared();
  70736. font->height = newHeight;
  70737. }
  70738. }
  70739. void Font::setHeightWithoutChangingWidth (float newHeight) throw()
  70740. {
  70741. newHeight = FontValues::limitFontHeight (newHeight);
  70742. if (font->height != newHeight)
  70743. {
  70744. dupeInternalIfShared();
  70745. font->horizontalScale *= (font->height / newHeight);
  70746. font->height = newHeight;
  70747. }
  70748. }
  70749. void Font::setStyleFlags (const int newFlags) throw()
  70750. {
  70751. if (font->styleFlags != newFlags)
  70752. {
  70753. dupeInternalIfShared();
  70754. font->styleFlags = newFlags;
  70755. font->typeface = 0;
  70756. font->ascent = 0;
  70757. }
  70758. }
  70759. void Font::setSizeAndStyle (float newHeight,
  70760. const int newStyleFlags,
  70761. const float newHorizontalScale,
  70762. const float newKerningAmount) throw()
  70763. {
  70764. newHeight = FontValues::limitFontHeight (newHeight);
  70765. if (font->height != newHeight
  70766. || font->horizontalScale != newHorizontalScale
  70767. || font->kerning != newKerningAmount)
  70768. {
  70769. dupeInternalIfShared();
  70770. font->height = newHeight;
  70771. font->horizontalScale = newHorizontalScale;
  70772. font->kerning = newKerningAmount;
  70773. }
  70774. setStyleFlags (newStyleFlags);
  70775. }
  70776. void Font::setHorizontalScale (const float scaleFactor) throw()
  70777. {
  70778. dupeInternalIfShared();
  70779. font->horizontalScale = scaleFactor;
  70780. }
  70781. void Font::setExtraKerningFactor (const float extraKerning) throw()
  70782. {
  70783. dupeInternalIfShared();
  70784. font->kerning = extraKerning;
  70785. }
  70786. void Font::setBold (const bool shouldBeBold) throw()
  70787. {
  70788. setStyleFlags (shouldBeBold ? (font->styleFlags | bold)
  70789. : (font->styleFlags & ~bold));
  70790. }
  70791. bool Font::isBold() const throw()
  70792. {
  70793. return (font->styleFlags & bold) != 0;
  70794. }
  70795. void Font::setItalic (const bool shouldBeItalic) throw()
  70796. {
  70797. setStyleFlags (shouldBeItalic ? (font->styleFlags | italic)
  70798. : (font->styleFlags & ~italic));
  70799. }
  70800. bool Font::isItalic() const throw()
  70801. {
  70802. return (font->styleFlags & italic) != 0;
  70803. }
  70804. void Font::setUnderline (const bool shouldBeUnderlined) throw()
  70805. {
  70806. setStyleFlags (shouldBeUnderlined ? (font->styleFlags | underlined)
  70807. : (font->styleFlags & ~underlined));
  70808. }
  70809. bool Font::isUnderlined() const throw()
  70810. {
  70811. return (font->styleFlags & underlined) != 0;
  70812. }
  70813. float Font::getAscent() const throw()
  70814. {
  70815. if (font->ascent == 0)
  70816. font->ascent = getTypeface()->getAscent();
  70817. return font->height * font->ascent;
  70818. }
  70819. float Font::getDescent() const throw()
  70820. {
  70821. return font->height - getAscent();
  70822. }
  70823. int Font::getStringWidth (const String& text) const throw()
  70824. {
  70825. return roundToInt (getStringWidthFloat (text));
  70826. }
  70827. float Font::getStringWidthFloat (const String& text) const throw()
  70828. {
  70829. float w = getTypeface()->getStringWidth (text);
  70830. if (font->kerning != 0)
  70831. w += font->kerning * text.length();
  70832. return w * font->height * font->horizontalScale;
  70833. }
  70834. void Font::getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const throw()
  70835. {
  70836. getTypeface()->getGlyphPositions (text, glyphs, xOffsets);
  70837. const float scale = font->height * font->horizontalScale;
  70838. const int num = xOffsets.size();
  70839. if (num > 0)
  70840. {
  70841. float* const x = &(xOffsets.getReference(0));
  70842. if (font->kerning != 0)
  70843. {
  70844. for (int i = 0; i < num; ++i)
  70845. x[i] = (x[i] + i * font->kerning) * scale;
  70846. }
  70847. else
  70848. {
  70849. for (int i = 0; i < num; ++i)
  70850. x[i] *= scale;
  70851. }
  70852. }
  70853. }
  70854. void Font::findFonts (Array<Font>& destArray) throw()
  70855. {
  70856. const StringArray names (findAllTypefaceNames());
  70857. for (int i = 0; i < names.size(); ++i)
  70858. destArray.add (Font (names[i], FontValues::defaultFontHeight, Font::plain));
  70859. }
  70860. const String Font::toString() const
  70861. {
  70862. String s (getTypefaceName());
  70863. if (s == getDefaultSansSerifFontName())
  70864. s = String::empty;
  70865. else
  70866. s += "; ";
  70867. s += String (getHeight(), 1);
  70868. if (isBold())
  70869. s += " bold";
  70870. if (isItalic())
  70871. s += " italic";
  70872. return s;
  70873. }
  70874. const Font Font::fromString (const String& fontDescription)
  70875. {
  70876. String name;
  70877. const int separator = fontDescription.indexOfChar (';');
  70878. if (separator > 0)
  70879. name = fontDescription.substring (0, separator).trim();
  70880. if (name.isEmpty())
  70881. name = getDefaultSansSerifFontName();
  70882. String sizeAndStyle (fontDescription.substring (separator + 1));
  70883. float height = sizeAndStyle.getFloatValue();
  70884. if (height <= 0)
  70885. height = 10.0f;
  70886. int flags = Font::plain;
  70887. if (sizeAndStyle.containsIgnoreCase ("bold"))
  70888. flags |= Font::bold;
  70889. if (sizeAndStyle.containsIgnoreCase ("italic"))
  70890. flags |= Font::italic;
  70891. return Font (name, height, flags);
  70892. }
  70893. class TypefaceCache : public DeletedAtShutdown
  70894. {
  70895. public:
  70896. TypefaceCache (int numToCache = 10) throw()
  70897. : counter (1)
  70898. {
  70899. while (--numToCache >= 0)
  70900. faces.add (new CachedFace());
  70901. }
  70902. ~TypefaceCache()
  70903. {
  70904. clearSingletonInstance();
  70905. }
  70906. juce_DeclareSingleton_SingleThreaded_Minimal (TypefaceCache)
  70907. const Typeface::Ptr findTypefaceFor (const Font& font) throw()
  70908. {
  70909. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  70910. const String faceName (font.getTypefaceName());
  70911. int i;
  70912. for (i = faces.size(); --i >= 0;)
  70913. {
  70914. CachedFace* const face = faces.getUnchecked(i);
  70915. if (face->flags == flags
  70916. && face->typefaceName == faceName)
  70917. {
  70918. face->lastUsageCount = ++counter;
  70919. return face->typeFace;
  70920. }
  70921. }
  70922. int replaceIndex = 0;
  70923. int bestLastUsageCount = std::numeric_limits<int>::max();
  70924. for (i = faces.size(); --i >= 0;)
  70925. {
  70926. const int lu = faces.getUnchecked(i)->lastUsageCount;
  70927. if (bestLastUsageCount > lu)
  70928. {
  70929. bestLastUsageCount = lu;
  70930. replaceIndex = i;
  70931. }
  70932. }
  70933. CachedFace* const face = faces.getUnchecked (replaceIndex);
  70934. face->typefaceName = faceName;
  70935. face->flags = flags;
  70936. face->lastUsageCount = ++counter;
  70937. face->typeFace = LookAndFeel::getDefaultLookAndFeel().getTypefaceForFont (font);
  70938. jassert (face->typeFace != 0); // the look and feel must return a typeface!
  70939. return face->typeFace;
  70940. }
  70941. juce_UseDebuggingNewOperator
  70942. private:
  70943. struct CachedFace
  70944. {
  70945. CachedFace() throw()
  70946. : lastUsageCount (0), flags (-1)
  70947. {
  70948. }
  70949. String typefaceName;
  70950. int lastUsageCount;
  70951. int flags;
  70952. Typeface::Ptr typeFace;
  70953. };
  70954. int counter;
  70955. OwnedArray <CachedFace> faces;
  70956. TypefaceCache (const TypefaceCache&);
  70957. TypefaceCache& operator= (const TypefaceCache&);
  70958. };
  70959. juce_ImplementSingleton_SingleThreaded (TypefaceCache)
  70960. Typeface* Font::getTypeface() const throw()
  70961. {
  70962. if (font->typeface == 0)
  70963. font->typeface = TypefaceCache::getInstance()->findTypefaceFor (*this);
  70964. return font->typeface;
  70965. }
  70966. END_JUCE_NAMESPACE
  70967. /*** End of inlined file: juce_Font.cpp ***/
  70968. /*** Start of inlined file: juce_GlyphArrangement.cpp ***/
  70969. BEGIN_JUCE_NAMESPACE
  70970. PositionedGlyph::PositionedGlyph (const float x_, const float y_, const float w_, const Font& font_,
  70971. const juce_wchar character_, const int glyph_)
  70972. : x (x_),
  70973. y (y_),
  70974. w (w_),
  70975. font (font_),
  70976. character (character_),
  70977. glyph (glyph_)
  70978. {
  70979. }
  70980. PositionedGlyph::PositionedGlyph (const PositionedGlyph& other)
  70981. : x (other.x),
  70982. y (other.y),
  70983. w (other.w),
  70984. font (other.font),
  70985. character (other.character),
  70986. glyph (other.glyph)
  70987. {
  70988. }
  70989. void PositionedGlyph::draw (const Graphics& g) const
  70990. {
  70991. if (! isWhitespace())
  70992. {
  70993. g.getInternalContext()->setFont (font);
  70994. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y));
  70995. }
  70996. }
  70997. void PositionedGlyph::draw (const Graphics& g,
  70998. const AffineTransform& transform) const
  70999. {
  71000. if (! isWhitespace())
  71001. {
  71002. g.getInternalContext()->setFont (font);
  71003. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y)
  71004. .followedBy (transform));
  71005. }
  71006. }
  71007. void PositionedGlyph::createPath (Path& path) const
  71008. {
  71009. if (! isWhitespace())
  71010. {
  71011. Typeface* const t = font.getTypeface();
  71012. if (t != 0)
  71013. {
  71014. Path p;
  71015. t->getOutlineForGlyph (glyph, p);
  71016. path.addPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight())
  71017. .translated (x, y));
  71018. }
  71019. }
  71020. }
  71021. bool PositionedGlyph::hitTest (float px, float py) const
  71022. {
  71023. if (getBounds().contains (px, py) && ! isWhitespace())
  71024. {
  71025. Typeface* const t = font.getTypeface();
  71026. if (t != 0)
  71027. {
  71028. Path p;
  71029. t->getOutlineForGlyph (glyph, p);
  71030. AffineTransform::translation (-x, -y)
  71031. .scaled (1.0f / (font.getHeight() * font.getHorizontalScale()), 1.0f / font.getHeight())
  71032. .transformPoint (px, py);
  71033. return p.contains (px, py);
  71034. }
  71035. }
  71036. return false;
  71037. }
  71038. void PositionedGlyph::moveBy (const float deltaX,
  71039. const float deltaY)
  71040. {
  71041. x += deltaX;
  71042. y += deltaY;
  71043. }
  71044. GlyphArrangement::GlyphArrangement()
  71045. {
  71046. glyphs.ensureStorageAllocated (128);
  71047. }
  71048. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other)
  71049. {
  71050. addGlyphArrangement (other);
  71051. }
  71052. GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other)
  71053. {
  71054. if (this != &other)
  71055. {
  71056. clear();
  71057. addGlyphArrangement (other);
  71058. }
  71059. return *this;
  71060. }
  71061. GlyphArrangement::~GlyphArrangement()
  71062. {
  71063. }
  71064. void GlyphArrangement::clear()
  71065. {
  71066. glyphs.clear();
  71067. }
  71068. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const
  71069. {
  71070. jassert (((unsigned int) index) < (unsigned int) glyphs.size());
  71071. return *glyphs [index];
  71072. }
  71073. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other)
  71074. {
  71075. glyphs.ensureStorageAllocated (glyphs.size() + other.glyphs.size());
  71076. glyphs.addCopiesOf (other.glyphs);
  71077. }
  71078. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num)
  71079. {
  71080. glyphs.removeRange (startIndex, num < 0 ? glyphs.size() : num);
  71081. }
  71082. void GlyphArrangement::addLineOfText (const Font& font,
  71083. const String& text,
  71084. const float xOffset,
  71085. const float yOffset)
  71086. {
  71087. addCurtailedLineOfText (font, text,
  71088. xOffset, yOffset,
  71089. 1.0e10f, false);
  71090. }
  71091. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  71092. const String& text,
  71093. float xOffset,
  71094. const float yOffset,
  71095. const float maxWidthPixels,
  71096. const bool useEllipsis)
  71097. {
  71098. if (text.isNotEmpty())
  71099. {
  71100. Array <int> newGlyphs;
  71101. Array <float> xOffsets;
  71102. font.getGlyphPositions (text, newGlyphs, xOffsets);
  71103. const int textLen = newGlyphs.size();
  71104. const juce_wchar* const unicodeText = text;
  71105. for (int i = 0; i < textLen; ++i)
  71106. {
  71107. const float thisX = xOffsets.getUnchecked (i);
  71108. const float nextX = xOffsets.getUnchecked (i + 1);
  71109. if (nextX > maxWidthPixels + 1.0f)
  71110. {
  71111. // curtail the string if it's too wide..
  71112. if (useEllipsis && textLen > 3 && glyphs.size() >= 3)
  71113. insertEllipsis (font, xOffset + maxWidthPixels, 0, glyphs.size());
  71114. break;
  71115. }
  71116. else
  71117. {
  71118. glyphs.add (new PositionedGlyph (xOffset + thisX, yOffset, nextX - thisX,
  71119. font, unicodeText[i], newGlyphs.getUnchecked(i)));
  71120. }
  71121. }
  71122. }
  71123. }
  71124. int GlyphArrangement::insertEllipsis (const Font& font, const float maxXPos,
  71125. const int startIndex, int endIndex)
  71126. {
  71127. int numDeleted = 0;
  71128. if (glyphs.size() > 0)
  71129. {
  71130. Array<int> dotGlyphs;
  71131. Array<float> dotXs;
  71132. font.getGlyphPositions ("..", dotGlyphs, dotXs);
  71133. const float dx = dotXs[1];
  71134. float xOffset = 0.0f, yOffset = 0.0f;
  71135. while (endIndex > startIndex)
  71136. {
  71137. const PositionedGlyph* pg = glyphs.getUnchecked (--endIndex);
  71138. xOffset = pg->x;
  71139. yOffset = pg->y;
  71140. glyphs.remove (endIndex);
  71141. ++numDeleted;
  71142. if (xOffset + dx * 3 <= maxXPos)
  71143. break;
  71144. }
  71145. for (int i = 3; --i >= 0;)
  71146. {
  71147. glyphs.insert (endIndex++, new PositionedGlyph (xOffset, yOffset, dx,
  71148. font, '.', dotGlyphs.getFirst()));
  71149. --numDeleted;
  71150. xOffset += dx;
  71151. if (xOffset > maxXPos)
  71152. break;
  71153. }
  71154. }
  71155. return numDeleted;
  71156. }
  71157. void GlyphArrangement::addJustifiedText (const Font& font,
  71158. const String& text,
  71159. float x, float y,
  71160. const float maxLineWidth,
  71161. const Justification& horizontalLayout)
  71162. {
  71163. int lineStartIndex = glyphs.size();
  71164. addLineOfText (font, text, x, y);
  71165. const float originalY = y;
  71166. while (lineStartIndex < glyphs.size())
  71167. {
  71168. int i = lineStartIndex;
  71169. if (glyphs.getUnchecked(i)->getCharacter() != '\n'
  71170. && glyphs.getUnchecked(i)->getCharacter() != '\r')
  71171. ++i;
  71172. const float lineMaxX = glyphs.getUnchecked (lineStartIndex)->getLeft() + maxLineWidth;
  71173. int lastWordBreakIndex = -1;
  71174. while (i < glyphs.size())
  71175. {
  71176. const PositionedGlyph* pg = glyphs.getUnchecked (i);
  71177. const juce_wchar c = pg->getCharacter();
  71178. if (c == '\r' || c == '\n')
  71179. {
  71180. ++i;
  71181. if (c == '\r' && i < glyphs.size()
  71182. && glyphs.getUnchecked(i)->getCharacter() == '\n')
  71183. ++i;
  71184. break;
  71185. }
  71186. else if (pg->isWhitespace())
  71187. {
  71188. lastWordBreakIndex = i + 1;
  71189. }
  71190. else if (pg->getRight() - 0.0001f >= lineMaxX)
  71191. {
  71192. if (lastWordBreakIndex >= 0)
  71193. i = lastWordBreakIndex;
  71194. break;
  71195. }
  71196. ++i;
  71197. }
  71198. const float currentLineStartX = glyphs.getUnchecked (lineStartIndex)->getLeft();
  71199. float currentLineEndX = currentLineStartX;
  71200. for (int j = i; --j >= lineStartIndex;)
  71201. {
  71202. if (! glyphs.getUnchecked (j)->isWhitespace())
  71203. {
  71204. currentLineEndX = glyphs.getUnchecked (j)->getRight();
  71205. break;
  71206. }
  71207. }
  71208. float deltaX = 0.0f;
  71209. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  71210. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  71211. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  71212. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  71213. else if (horizontalLayout.testFlags (Justification::right))
  71214. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  71215. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  71216. x + deltaX - currentLineStartX, y - originalY);
  71217. lineStartIndex = i;
  71218. y += font.getHeight();
  71219. }
  71220. }
  71221. void GlyphArrangement::addFittedText (const Font& f,
  71222. const String& text,
  71223. const float x, const float y,
  71224. const float width, const float height,
  71225. const Justification& layout,
  71226. int maximumLines,
  71227. const float minimumHorizontalScale)
  71228. {
  71229. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  71230. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  71231. if (text.containsAnyOf ("\r\n"))
  71232. {
  71233. GlyphArrangement ga;
  71234. ga.addJustifiedText (f, text, x, y, width, layout);
  71235. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  71236. float dy = y - bb.getY();
  71237. if (layout.testFlags (Justification::verticallyCentred))
  71238. dy += (height - bb.getHeight()) * 0.5f;
  71239. else if (layout.testFlags (Justification::bottom))
  71240. dy += height - bb.getHeight();
  71241. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  71242. glyphs.ensureStorageAllocated (glyphs.size() + ga.glyphs.size());
  71243. for (int i = 0; i < ga.glyphs.size(); ++i)
  71244. glyphs.add (ga.glyphs.getUnchecked (i));
  71245. ga.glyphs.clear (false);
  71246. return;
  71247. }
  71248. int startIndex = glyphs.size();
  71249. addLineOfText (f, text.trim(), x, y);
  71250. if (glyphs.size() > startIndex)
  71251. {
  71252. float lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  71253. - glyphs.getUnchecked (startIndex)->getLeft();
  71254. if (lineWidth <= 0)
  71255. return;
  71256. if (lineWidth * minimumHorizontalScale < width)
  71257. {
  71258. if (lineWidth > width)
  71259. stretchRangeOfGlyphs (startIndex, glyphs.size() - startIndex,
  71260. width / lineWidth);
  71261. justifyGlyphs (startIndex, glyphs.size() - startIndex,
  71262. x, y, width, height, layout);
  71263. }
  71264. else if (maximumLines <= 1)
  71265. {
  71266. fitLineIntoSpace (startIndex, glyphs.size() - startIndex,
  71267. x, y, width, height, f, layout, minimumHorizontalScale);
  71268. }
  71269. else
  71270. {
  71271. Font font (f);
  71272. String txt (text.trim());
  71273. const int length = txt.length();
  71274. const int originalStartIndex = startIndex;
  71275. int numLines = 1;
  71276. if (length <= 12 && ! txt.containsAnyOf (" -\t\r\n"))
  71277. maximumLines = 1;
  71278. maximumLines = jmin (maximumLines, length);
  71279. while (numLines < maximumLines)
  71280. {
  71281. ++numLines;
  71282. const float newFontHeight = height / (float) numLines;
  71283. if (newFontHeight < font.getHeight())
  71284. {
  71285. font.setHeight (jmax (8.0f, newFontHeight));
  71286. removeRangeOfGlyphs (startIndex, -1);
  71287. addLineOfText (font, txt, x, y);
  71288. lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  71289. - glyphs.getUnchecked (startIndex)->getLeft();
  71290. }
  71291. if (numLines > lineWidth / width || newFontHeight < 8.0f)
  71292. break;
  71293. }
  71294. if (numLines < 1)
  71295. numLines = 1;
  71296. float lineY = y;
  71297. float widthPerLine = lineWidth / numLines;
  71298. int lastLineStartIndex = 0;
  71299. for (int line = 0; line < numLines; ++line)
  71300. {
  71301. int i = startIndex;
  71302. lastLineStartIndex = i;
  71303. float lineStartX = glyphs.getUnchecked (startIndex)->getLeft();
  71304. if (line == numLines - 1)
  71305. {
  71306. widthPerLine = width;
  71307. i = glyphs.size();
  71308. }
  71309. else
  71310. {
  71311. while (i < glyphs.size())
  71312. {
  71313. lineWidth = (glyphs.getUnchecked (i)->getRight() - lineStartX);
  71314. if (lineWidth > widthPerLine)
  71315. {
  71316. // got to a point where the line's too long, so skip forward to find a
  71317. // good place to break it..
  71318. const int searchStartIndex = i;
  71319. while (i < glyphs.size())
  71320. {
  71321. if ((glyphs.getUnchecked (i)->getRight() - lineStartX) * minimumHorizontalScale < width)
  71322. {
  71323. if (glyphs.getUnchecked (i)->isWhitespace()
  71324. || glyphs.getUnchecked (i)->getCharacter() == '-')
  71325. {
  71326. ++i;
  71327. break;
  71328. }
  71329. }
  71330. else
  71331. {
  71332. // can't find a suitable break, so try looking backwards..
  71333. i = searchStartIndex;
  71334. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  71335. {
  71336. if (glyphs.getUnchecked (i - back)->isWhitespace()
  71337. || glyphs.getUnchecked (i - back)->getCharacter() == '-')
  71338. {
  71339. i -= back - 1;
  71340. break;
  71341. }
  71342. }
  71343. break;
  71344. }
  71345. ++i;
  71346. }
  71347. break;
  71348. }
  71349. ++i;
  71350. }
  71351. int wsStart = i;
  71352. while (wsStart > 0 && glyphs.getUnchecked (wsStart - 1)->isWhitespace())
  71353. --wsStart;
  71354. int wsEnd = i;
  71355. while (wsEnd < glyphs.size() && glyphs.getUnchecked (wsEnd)->isWhitespace())
  71356. ++wsEnd;
  71357. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  71358. i = jmax (wsStart, startIndex + 1);
  71359. }
  71360. i -= fitLineIntoSpace (startIndex, i - startIndex,
  71361. x, lineY, width, font.getHeight(), font,
  71362. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  71363. minimumHorizontalScale);
  71364. startIndex = i;
  71365. lineY += font.getHeight();
  71366. if (startIndex >= glyphs.size())
  71367. break;
  71368. }
  71369. justifyGlyphs (originalStartIndex, glyphs.size() - originalStartIndex,
  71370. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  71371. }
  71372. }
  71373. }
  71374. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  71375. const float dx, const float dy)
  71376. {
  71377. jassert (startIndex >= 0);
  71378. if (dx != 0.0f || dy != 0.0f)
  71379. {
  71380. if (num < 0 || startIndex + num > glyphs.size())
  71381. num = glyphs.size() - startIndex;
  71382. while (--num >= 0)
  71383. glyphs.getUnchecked (startIndex++)->moveBy (dx, dy);
  71384. }
  71385. }
  71386. int GlyphArrangement::fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  71387. const Justification& justification, float minimumHorizontalScale)
  71388. {
  71389. int numDeleted = 0;
  71390. const float lineStartX = glyphs.getUnchecked (start)->getLeft();
  71391. float lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX;
  71392. if (lineWidth > w)
  71393. {
  71394. if (minimumHorizontalScale < 1.0f)
  71395. {
  71396. stretchRangeOfGlyphs (start, numGlyphs, jmax (minimumHorizontalScale, w / lineWidth));
  71397. lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX - 0.5f;
  71398. }
  71399. if (lineWidth > w)
  71400. {
  71401. numDeleted = insertEllipsis (font, lineStartX + w, start, start + numGlyphs);
  71402. numGlyphs -= numDeleted;
  71403. }
  71404. }
  71405. justifyGlyphs (start, numGlyphs, x, y, w, h, justification);
  71406. return numDeleted;
  71407. }
  71408. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  71409. const float horizontalScaleFactor)
  71410. {
  71411. jassert (startIndex >= 0);
  71412. if (num < 0 || startIndex + num > glyphs.size())
  71413. num = glyphs.size() - startIndex;
  71414. if (num > 0)
  71415. {
  71416. const float xAnchor = glyphs.getUnchecked (startIndex)->getLeft();
  71417. while (--num >= 0)
  71418. {
  71419. PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  71420. pg->x = xAnchor + (pg->x - xAnchor) * horizontalScaleFactor;
  71421. pg->font.setHorizontalScale (pg->font.getHorizontalScale() * horizontalScaleFactor);
  71422. pg->w *= horizontalScaleFactor;
  71423. }
  71424. }
  71425. }
  71426. const Rectangle<float> GlyphArrangement::getBoundingBox (int startIndex, int num, const bool includeWhitespace) const
  71427. {
  71428. jassert (startIndex >= 0);
  71429. if (num < 0 || startIndex + num > glyphs.size())
  71430. num = glyphs.size() - startIndex;
  71431. Rectangle<float> result;
  71432. while (--num >= 0)
  71433. {
  71434. const PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  71435. if (includeWhitespace || ! pg->isWhitespace())
  71436. result = result.getUnion (pg->getBounds());
  71437. }
  71438. return result;
  71439. }
  71440. void GlyphArrangement::justifyGlyphs (const int startIndex, const int num,
  71441. const float x, const float y, const float width, const float height,
  71442. const Justification& justification)
  71443. {
  71444. jassert (num >= 0 && startIndex >= 0);
  71445. if (glyphs.size() > 0 && num > 0)
  71446. {
  71447. const Rectangle<float> bb (getBoundingBox (startIndex, num, ! justification.testFlags (Justification::horizontallyJustified
  71448. | Justification::horizontallyCentred)));
  71449. float deltaX = 0.0f;
  71450. if (justification.testFlags (Justification::horizontallyJustified))
  71451. deltaX = x - bb.getX();
  71452. else if (justification.testFlags (Justification::horizontallyCentred))
  71453. deltaX = x + (width - bb.getWidth()) * 0.5f - bb.getX();
  71454. else if (justification.testFlags (Justification::right))
  71455. deltaX = (x + width) - bb.getRight();
  71456. else
  71457. deltaX = x - bb.getX();
  71458. float deltaY = 0.0f;
  71459. if (justification.testFlags (Justification::top))
  71460. deltaY = y - bb.getY();
  71461. else if (justification.testFlags (Justification::bottom))
  71462. deltaY = (y + height) - bb.getBottom();
  71463. else
  71464. deltaY = y + (height - bb.getHeight()) * 0.5f - bb.getY();
  71465. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  71466. if (justification.testFlags (Justification::horizontallyJustified))
  71467. {
  71468. int lineStart = 0;
  71469. float baseY = glyphs.getUnchecked (startIndex)->getBaselineY();
  71470. int i;
  71471. for (i = 0; i < num; ++i)
  71472. {
  71473. const float glyphY = glyphs.getUnchecked (startIndex + i)->getBaselineY();
  71474. if (glyphY != baseY)
  71475. {
  71476. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  71477. lineStart = i;
  71478. baseY = glyphY;
  71479. }
  71480. }
  71481. if (i > lineStart)
  71482. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  71483. }
  71484. }
  71485. }
  71486. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth)
  71487. {
  71488. if (start + num < glyphs.size()
  71489. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\r'
  71490. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\n')
  71491. {
  71492. int numSpaces = 0;
  71493. int spacesAtEnd = 0;
  71494. for (int i = 0; i < num; ++i)
  71495. {
  71496. if (glyphs.getUnchecked (start + i)->isWhitespace())
  71497. {
  71498. ++spacesAtEnd;
  71499. ++numSpaces;
  71500. }
  71501. else
  71502. {
  71503. spacesAtEnd = 0;
  71504. }
  71505. }
  71506. numSpaces -= spacesAtEnd;
  71507. if (numSpaces > 0)
  71508. {
  71509. const float startX = glyphs.getUnchecked (start)->getLeft();
  71510. const float endX = glyphs.getUnchecked (start + num - 1 - spacesAtEnd)->getRight();
  71511. const float extraPaddingBetweenWords
  71512. = (targetWidth - (endX - startX)) / (float) numSpaces;
  71513. float deltaX = 0.0f;
  71514. for (int i = 0; i < num; ++i)
  71515. {
  71516. glyphs.getUnchecked (start + i)->moveBy (deltaX, 0.0f);
  71517. if (glyphs.getUnchecked (start + i)->isWhitespace())
  71518. deltaX += extraPaddingBetweenWords;
  71519. }
  71520. }
  71521. }
  71522. }
  71523. void GlyphArrangement::draw (const Graphics& g) const
  71524. {
  71525. for (int i = 0; i < glyphs.size(); ++i)
  71526. {
  71527. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  71528. if (pg->font.isUnderlined())
  71529. {
  71530. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  71531. float nextX = pg->x + pg->w;
  71532. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  71533. nextX = glyphs.getUnchecked (i + 1)->x;
  71534. g.fillRect (pg->x, pg->y + lineThickness * 2.0f,
  71535. nextX - pg->x, lineThickness);
  71536. }
  71537. pg->draw (g);
  71538. }
  71539. }
  71540. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const
  71541. {
  71542. for (int i = 0; i < glyphs.size(); ++i)
  71543. {
  71544. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  71545. if (pg->font.isUnderlined())
  71546. {
  71547. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  71548. float nextX = pg->x + pg->w;
  71549. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  71550. nextX = glyphs.getUnchecked (i + 1)->x;
  71551. Path p;
  71552. p.addLineSegment (Line<float> (pg->x, pg->y + lineThickness * 2.0f,
  71553. nextX, pg->y + lineThickness * 2.0f),
  71554. lineThickness);
  71555. g.fillPath (p, transform);
  71556. }
  71557. pg->draw (g, transform);
  71558. }
  71559. }
  71560. void GlyphArrangement::createPath (Path& path) const
  71561. {
  71562. for (int i = 0; i < glyphs.size(); ++i)
  71563. glyphs.getUnchecked (i)->createPath (path);
  71564. }
  71565. int GlyphArrangement::findGlyphIndexAt (float x, float y) const
  71566. {
  71567. for (int i = 0; i < glyphs.size(); ++i)
  71568. if (glyphs.getUnchecked (i)->hitTest (x, y))
  71569. return i;
  71570. return -1;
  71571. }
  71572. END_JUCE_NAMESPACE
  71573. /*** End of inlined file: juce_GlyphArrangement.cpp ***/
  71574. /*** Start of inlined file: juce_TextLayout.cpp ***/
  71575. BEGIN_JUCE_NAMESPACE
  71576. class TextLayout::Token
  71577. {
  71578. public:
  71579. String text;
  71580. Font font;
  71581. int x, y, w, h;
  71582. int line, lineHeight;
  71583. bool isWhitespace, isNewLine;
  71584. Token (const String& t,
  71585. const Font& f,
  71586. const bool isWhitespace_)
  71587. : text (t),
  71588. font (f),
  71589. x(0),
  71590. y(0),
  71591. isWhitespace (isWhitespace_)
  71592. {
  71593. w = font.getStringWidth (t);
  71594. h = roundToInt (f.getHeight());
  71595. isNewLine = t.containsChar ('\n') || t.containsChar ('\r');
  71596. }
  71597. Token (const Token& other)
  71598. : text (other.text),
  71599. font (other.font),
  71600. x (other.x),
  71601. y (other.y),
  71602. w (other.w),
  71603. h (other.h),
  71604. line (other.line),
  71605. lineHeight (other.lineHeight),
  71606. isWhitespace (other.isWhitespace),
  71607. isNewLine (other.isNewLine)
  71608. {
  71609. }
  71610. ~Token()
  71611. {
  71612. }
  71613. void draw (Graphics& g,
  71614. const int xOffset,
  71615. const int yOffset)
  71616. {
  71617. if (! isWhitespace)
  71618. {
  71619. g.setFont (font);
  71620. g.drawSingleLineText (text.trimEnd(),
  71621. xOffset + x,
  71622. yOffset + y + (lineHeight - h)
  71623. + roundToInt (font.getAscent()));
  71624. }
  71625. }
  71626. juce_UseDebuggingNewOperator
  71627. };
  71628. TextLayout::TextLayout()
  71629. : totalLines (0)
  71630. {
  71631. tokens.ensureStorageAllocated (64);
  71632. }
  71633. TextLayout::TextLayout (const String& text, const Font& font)
  71634. : totalLines (0)
  71635. {
  71636. tokens.ensureStorageAllocated (64);
  71637. appendText (text, font);
  71638. }
  71639. TextLayout::TextLayout (const TextLayout& other)
  71640. : totalLines (0)
  71641. {
  71642. *this = other;
  71643. }
  71644. TextLayout& TextLayout::operator= (const TextLayout& other)
  71645. {
  71646. if (this != &other)
  71647. {
  71648. clear();
  71649. totalLines = other.totalLines;
  71650. tokens.addCopiesOf (other.tokens);
  71651. }
  71652. return *this;
  71653. }
  71654. TextLayout::~TextLayout()
  71655. {
  71656. clear();
  71657. }
  71658. void TextLayout::clear()
  71659. {
  71660. tokens.clear();
  71661. totalLines = 0;
  71662. }
  71663. void TextLayout::appendText (const String& text, const Font& font)
  71664. {
  71665. const juce_wchar* t = text;
  71666. String currentString;
  71667. int lastCharType = 0;
  71668. for (;;)
  71669. {
  71670. const juce_wchar c = *t++;
  71671. if (c == 0)
  71672. break;
  71673. int charType;
  71674. if (c == '\r' || c == '\n')
  71675. {
  71676. charType = 0;
  71677. }
  71678. else if (CharacterFunctions::isWhitespace (c))
  71679. {
  71680. charType = 2;
  71681. }
  71682. else
  71683. {
  71684. charType = 1;
  71685. }
  71686. if (charType == 0 || charType != lastCharType)
  71687. {
  71688. if (currentString.isNotEmpty())
  71689. {
  71690. tokens.add (new Token (currentString, font,
  71691. lastCharType == 2 || lastCharType == 0));
  71692. }
  71693. currentString = String::charToString (c);
  71694. if (c == '\r' && *t == '\n')
  71695. currentString += *t++;
  71696. }
  71697. else
  71698. {
  71699. currentString += c;
  71700. }
  71701. lastCharType = charType;
  71702. }
  71703. if (currentString.isNotEmpty())
  71704. tokens.add (new Token (currentString, font, lastCharType == 2));
  71705. }
  71706. void TextLayout::setText (const String& text, const Font& font)
  71707. {
  71708. clear();
  71709. appendText (text, font);
  71710. }
  71711. void TextLayout::layout (int maxWidth,
  71712. const Justification& justification,
  71713. const bool attemptToBalanceLineLengths)
  71714. {
  71715. if (attemptToBalanceLineLengths)
  71716. {
  71717. const int originalW = maxWidth;
  71718. int bestWidth = maxWidth;
  71719. float bestLineProportion = 0.0f;
  71720. while (maxWidth > originalW / 2)
  71721. {
  71722. layout (maxWidth, justification, false);
  71723. if (getNumLines() <= 1)
  71724. return;
  71725. const int lastLineW = getLineWidth (getNumLines() - 1);
  71726. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  71727. const float prop = lastLineW / (float) lastButOneLineW;
  71728. if (prop > 0.9f)
  71729. return;
  71730. if (prop > bestLineProportion)
  71731. {
  71732. bestLineProportion = prop;
  71733. bestWidth = maxWidth;
  71734. }
  71735. maxWidth -= 10;
  71736. }
  71737. layout (bestWidth, justification, false);
  71738. }
  71739. else
  71740. {
  71741. int x = 0;
  71742. int y = 0;
  71743. int h = 0;
  71744. totalLines = 0;
  71745. int i;
  71746. for (i = 0; i < tokens.size(); ++i)
  71747. {
  71748. Token* const t = tokens.getUnchecked(i);
  71749. t->x = x;
  71750. t->y = y;
  71751. t->line = totalLines;
  71752. x += t->w;
  71753. h = jmax (h, t->h);
  71754. const Token* nextTok = tokens [i + 1];
  71755. if (nextTok == 0)
  71756. break;
  71757. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  71758. {
  71759. // finished a line, so go back and update the heights of the things on it
  71760. for (int j = i; j >= 0; --j)
  71761. {
  71762. Token* const tok = tokens.getUnchecked(j);
  71763. if (tok->line == totalLines)
  71764. tok->lineHeight = h;
  71765. else
  71766. break;
  71767. }
  71768. x = 0;
  71769. y += h;
  71770. h = 0;
  71771. ++totalLines;
  71772. }
  71773. }
  71774. // finished a line, so go back and update the heights of the things on it
  71775. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  71776. {
  71777. Token* const t = tokens.getUnchecked(j);
  71778. if (t->line == totalLines)
  71779. t->lineHeight = h;
  71780. else
  71781. break;
  71782. }
  71783. ++totalLines;
  71784. if (! justification.testFlags (Justification::left))
  71785. {
  71786. int totalW = getWidth();
  71787. for (i = totalLines; --i >= 0;)
  71788. {
  71789. const int lineW = getLineWidth (i);
  71790. int dx = 0;
  71791. if (justification.testFlags (Justification::horizontallyCentred))
  71792. dx = (totalW - lineW) / 2;
  71793. else if (justification.testFlags (Justification::right))
  71794. dx = totalW - lineW;
  71795. for (int j = tokens.size(); --j >= 0;)
  71796. {
  71797. Token* const t = tokens.getUnchecked(j);
  71798. if (t->line == i)
  71799. t->x += dx;
  71800. }
  71801. }
  71802. }
  71803. }
  71804. }
  71805. int TextLayout::getLineWidth (const int lineNumber) const
  71806. {
  71807. int maxW = 0;
  71808. for (int i = tokens.size(); --i >= 0;)
  71809. {
  71810. const Token* const t = tokens.getUnchecked(i);
  71811. if (t->line == lineNumber && ! t->isWhitespace)
  71812. maxW = jmax (maxW, t->x + t->w);
  71813. }
  71814. return maxW;
  71815. }
  71816. int TextLayout::getWidth() const
  71817. {
  71818. int maxW = 0;
  71819. for (int i = tokens.size(); --i >= 0;)
  71820. {
  71821. const Token* const t = tokens.getUnchecked(i);
  71822. if (! t->isWhitespace)
  71823. maxW = jmax (maxW, t->x + t->w);
  71824. }
  71825. return maxW;
  71826. }
  71827. int TextLayout::getHeight() const
  71828. {
  71829. int maxH = 0;
  71830. for (int i = tokens.size(); --i >= 0;)
  71831. {
  71832. const Token* const t = tokens.getUnchecked(i);
  71833. if (! t->isWhitespace)
  71834. maxH = jmax (maxH, t->y + t->h);
  71835. }
  71836. return maxH;
  71837. }
  71838. void TextLayout::draw (Graphics& g,
  71839. const int xOffset,
  71840. const int yOffset) const
  71841. {
  71842. for (int i = tokens.size(); --i >= 0;)
  71843. tokens.getUnchecked(i)->draw (g, xOffset, yOffset);
  71844. }
  71845. void TextLayout::drawWithin (Graphics& g,
  71846. int x, int y, int w, int h,
  71847. const Justification& justification) const
  71848. {
  71849. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  71850. x, y, w, h);
  71851. draw (g, x, y);
  71852. }
  71853. END_JUCE_NAMESPACE
  71854. /*** End of inlined file: juce_TextLayout.cpp ***/
  71855. /*** Start of inlined file: juce_Typeface.cpp ***/
  71856. BEGIN_JUCE_NAMESPACE
  71857. Typeface::Typeface (const String& name_) throw()
  71858. : name (name_)
  71859. {
  71860. }
  71861. Typeface::~Typeface()
  71862. {
  71863. }
  71864. class CustomTypeface::GlyphInfo
  71865. {
  71866. public:
  71867. GlyphInfo (const juce_wchar character_, const Path& path_, const float width_) throw()
  71868. : character (character_), path (path_), width (width_)
  71869. {
  71870. }
  71871. ~GlyphInfo() throw()
  71872. {
  71873. }
  71874. struct KerningPair
  71875. {
  71876. juce_wchar character2;
  71877. float kerningAmount;
  71878. };
  71879. void addKerningPair (const juce_wchar subsequentCharacter,
  71880. const float extraKerningAmount) throw()
  71881. {
  71882. KerningPair kp;
  71883. kp.character2 = subsequentCharacter;
  71884. kp.kerningAmount = extraKerningAmount;
  71885. kerningPairs.add (kp);
  71886. }
  71887. float getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  71888. {
  71889. if (subsequentCharacter != 0)
  71890. {
  71891. for (int i = kerningPairs.size(); --i >= 0;)
  71892. if (kerningPairs.getReference(i).character2 == subsequentCharacter)
  71893. return width + kerningPairs.getReference(i).kerningAmount;
  71894. }
  71895. return width;
  71896. }
  71897. const juce_wchar character;
  71898. const Path path;
  71899. float width;
  71900. Array <KerningPair> kerningPairs;
  71901. juce_UseDebuggingNewOperator
  71902. private:
  71903. GlyphInfo (const GlyphInfo&);
  71904. GlyphInfo& operator= (const GlyphInfo&);
  71905. };
  71906. CustomTypeface::CustomTypeface()
  71907. : Typeface (String::empty)
  71908. {
  71909. clear();
  71910. }
  71911. CustomTypeface::CustomTypeface (InputStream& serialisedTypefaceStream)
  71912. : Typeface (String::empty)
  71913. {
  71914. clear();
  71915. GZIPDecompressorInputStream gzin (&serialisedTypefaceStream, false);
  71916. BufferedInputStream in (&gzin, 32768, false);
  71917. name = in.readString();
  71918. isBold = in.readBool();
  71919. isItalic = in.readBool();
  71920. ascent = in.readFloat();
  71921. defaultCharacter = (juce_wchar) in.readShort();
  71922. int i, numChars = in.readInt();
  71923. for (i = 0; i < numChars; ++i)
  71924. {
  71925. const juce_wchar c = (juce_wchar) in.readShort();
  71926. const float width = in.readFloat();
  71927. Path p;
  71928. p.loadPathFromStream (in);
  71929. addGlyph (c, p, width);
  71930. }
  71931. const int numKerningPairs = in.readInt();
  71932. for (i = 0; i < numKerningPairs; ++i)
  71933. {
  71934. const juce_wchar char1 = (juce_wchar) in.readShort();
  71935. const juce_wchar char2 = (juce_wchar) in.readShort();
  71936. addKerningPair (char1, char2, in.readFloat());
  71937. }
  71938. }
  71939. CustomTypeface::~CustomTypeface()
  71940. {
  71941. }
  71942. void CustomTypeface::clear()
  71943. {
  71944. defaultCharacter = 0;
  71945. ascent = 1.0f;
  71946. isBold = isItalic = false;
  71947. zeromem (lookupTable, sizeof (lookupTable));
  71948. glyphs.clear();
  71949. }
  71950. void CustomTypeface::setCharacteristics (const String& name_, const float ascent_, const bool isBold_,
  71951. const bool isItalic_, const juce_wchar defaultCharacter_) throw()
  71952. {
  71953. name = name_;
  71954. defaultCharacter = defaultCharacter_;
  71955. ascent = ascent_;
  71956. isBold = isBold_;
  71957. isItalic = isItalic_;
  71958. }
  71959. void CustomTypeface::addGlyph (const juce_wchar character, const Path& path, const float width) throw()
  71960. {
  71961. // Check that you're not trying to add the same character twice..
  71962. jassert (findGlyph (character, false) == 0);
  71963. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable))
  71964. lookupTable [character] = (short) glyphs.size();
  71965. glyphs.add (new GlyphInfo (character, path, width));
  71966. }
  71967. void CustomTypeface::addKerningPair (const juce_wchar char1, const juce_wchar char2, const float extraAmount) throw()
  71968. {
  71969. if (extraAmount != 0)
  71970. {
  71971. GlyphInfo* const g = findGlyph (char1, true);
  71972. jassert (g != 0); // can only add kerning pairs for characters that exist!
  71973. if (g != 0)
  71974. g->addKerningPair (char2, extraAmount);
  71975. }
  71976. }
  71977. CustomTypeface::GlyphInfo* CustomTypeface::findGlyph (const juce_wchar character, const bool loadIfNeeded) throw()
  71978. {
  71979. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable) && lookupTable [character] > 0)
  71980. return glyphs [(int) lookupTable [(int) character]];
  71981. for (int i = 0; i < glyphs.size(); ++i)
  71982. {
  71983. GlyphInfo* const g = glyphs.getUnchecked(i);
  71984. if (g->character == character)
  71985. return g;
  71986. }
  71987. if (loadIfNeeded && loadGlyphIfPossible (character))
  71988. return findGlyph (character, false);
  71989. return 0;
  71990. }
  71991. CustomTypeface::GlyphInfo* CustomTypeface::findGlyphSubstituting (const juce_wchar character) throw()
  71992. {
  71993. GlyphInfo* glyph = findGlyph (character, true);
  71994. if (glyph == 0)
  71995. {
  71996. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  71997. glyph = findGlyph (L' ', true);
  71998. if (glyph == 0)
  71999. {
  72000. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  72001. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  72002. if (fallbackTypeface != 0 && fallbackTypeface != this)
  72003. {
  72004. //xxx
  72005. }
  72006. if (glyph == 0)
  72007. glyph = findGlyph (defaultCharacter, true);
  72008. }
  72009. }
  72010. return glyph;
  72011. }
  72012. bool CustomTypeface::loadGlyphIfPossible (const juce_wchar /*characterNeeded*/)
  72013. {
  72014. return false;
  72015. }
  72016. void CustomTypeface::addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw()
  72017. {
  72018. setCharacteristics (name, typefaceToCopy.getAscent(), isBold, isItalic, defaultCharacter);
  72019. for (int i = 0; i < numCharacters; ++i)
  72020. {
  72021. const juce_wchar c = (juce_wchar) (characterStartIndex + i);
  72022. Array <int> glyphIndexes;
  72023. Array <float> offsets;
  72024. typefaceToCopy.getGlyphPositions (String::charToString (c), glyphIndexes, offsets);
  72025. const int glyphIndex = glyphIndexes.getFirst();
  72026. if (glyphIndex >= 0 && glyphIndexes.size() > 0)
  72027. {
  72028. const float glyphWidth = offsets[1];
  72029. Path p;
  72030. typefaceToCopy.getOutlineForGlyph (glyphIndex, p);
  72031. addGlyph (c, p, glyphWidth);
  72032. for (int j = glyphs.size() - 1; --j >= 0;)
  72033. {
  72034. const juce_wchar char2 = glyphs.getUnchecked (j)->character;
  72035. glyphIndexes.clearQuick();
  72036. offsets.clearQuick();
  72037. typefaceToCopy.getGlyphPositions (String::charToString (c) + String::charToString (char2), glyphIndexes, offsets);
  72038. if (offsets.size() > 1)
  72039. addKerningPair (c, char2, offsets[1] - glyphWidth);
  72040. }
  72041. }
  72042. }
  72043. }
  72044. bool CustomTypeface::writeToStream (OutputStream& outputStream)
  72045. {
  72046. GZIPCompressorOutputStream out (&outputStream);
  72047. out.writeString (name);
  72048. out.writeBool (isBold);
  72049. out.writeBool (isItalic);
  72050. out.writeFloat (ascent);
  72051. out.writeShort ((short) (unsigned short) defaultCharacter);
  72052. out.writeInt (glyphs.size());
  72053. int i, numKerningPairs = 0;
  72054. for (i = 0; i < glyphs.size(); ++i)
  72055. {
  72056. const GlyphInfo* const g = glyphs.getUnchecked (i);
  72057. out.writeShort ((short) (unsigned short) g->character);
  72058. out.writeFloat (g->width);
  72059. g->path.writePathToStream (out);
  72060. numKerningPairs += g->kerningPairs.size();
  72061. }
  72062. out.writeInt (numKerningPairs);
  72063. for (i = 0; i < glyphs.size(); ++i)
  72064. {
  72065. const GlyphInfo* const g = glyphs.getUnchecked (i);
  72066. for (int j = 0; j < g->kerningPairs.size(); ++j)
  72067. {
  72068. const GlyphInfo::KerningPair& p = g->kerningPairs.getReference (j);
  72069. out.writeShort ((short) (unsigned short) g->character);
  72070. out.writeShort ((short) (unsigned short) p.character2);
  72071. out.writeFloat (p.kerningAmount);
  72072. }
  72073. }
  72074. return true;
  72075. }
  72076. float CustomTypeface::getAscent() const
  72077. {
  72078. return ascent;
  72079. }
  72080. float CustomTypeface::getDescent() const
  72081. {
  72082. return 1.0f - ascent;
  72083. }
  72084. float CustomTypeface::getStringWidth (const String& text)
  72085. {
  72086. float x = 0;
  72087. const juce_wchar* t = text;
  72088. while (*t != 0)
  72089. {
  72090. const GlyphInfo* const glyph = findGlyphSubstituting (*t++);
  72091. if (glyph != 0)
  72092. x += glyph->getHorizontalSpacing (*t);
  72093. }
  72094. return x;
  72095. }
  72096. void CustomTypeface::getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array<float>& xOffsets)
  72097. {
  72098. xOffsets.add (0);
  72099. float x = 0;
  72100. const juce_wchar* t = text;
  72101. while (*t != 0)
  72102. {
  72103. const juce_wchar c = *t++;
  72104. const GlyphInfo* const glyph = findGlyphSubstituting (c);
  72105. if (glyph != 0)
  72106. {
  72107. x += glyph->getHorizontalSpacing (*t);
  72108. resultGlyphs.add ((int) glyph->character);
  72109. xOffsets.add (x);
  72110. }
  72111. }
  72112. }
  72113. bool CustomTypeface::getOutlineForGlyph (int glyphNumber, Path& path)
  72114. {
  72115. const GlyphInfo* const glyph = findGlyphSubstituting ((juce_wchar) glyphNumber);
  72116. if (glyph != 0)
  72117. {
  72118. path = glyph->path;
  72119. return true;
  72120. }
  72121. return false;
  72122. }
  72123. END_JUCE_NAMESPACE
  72124. /*** End of inlined file: juce_Typeface.cpp ***/
  72125. /*** Start of inlined file: juce_AffineTransform.cpp ***/
  72126. BEGIN_JUCE_NAMESPACE
  72127. AffineTransform::AffineTransform() throw()
  72128. : mat00 (1.0f),
  72129. mat01 (0),
  72130. mat02 (0),
  72131. mat10 (0),
  72132. mat11 (1.0f),
  72133. mat12 (0)
  72134. {
  72135. }
  72136. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  72137. : mat00 (other.mat00),
  72138. mat01 (other.mat01),
  72139. mat02 (other.mat02),
  72140. mat10 (other.mat10),
  72141. mat11 (other.mat11),
  72142. mat12 (other.mat12)
  72143. {
  72144. }
  72145. AffineTransform::AffineTransform (const float mat00_,
  72146. const float mat01_,
  72147. const float mat02_,
  72148. const float mat10_,
  72149. const float mat11_,
  72150. const float mat12_) throw()
  72151. : mat00 (mat00_),
  72152. mat01 (mat01_),
  72153. mat02 (mat02_),
  72154. mat10 (mat10_),
  72155. mat11 (mat11_),
  72156. mat12 (mat12_)
  72157. {
  72158. }
  72159. AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  72160. {
  72161. mat00 = other.mat00;
  72162. mat01 = other.mat01;
  72163. mat02 = other.mat02;
  72164. mat10 = other.mat10;
  72165. mat11 = other.mat11;
  72166. mat12 = other.mat12;
  72167. return *this;
  72168. }
  72169. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  72170. {
  72171. return mat00 == other.mat00
  72172. && mat01 == other.mat01
  72173. && mat02 == other.mat02
  72174. && mat10 == other.mat10
  72175. && mat11 == other.mat11
  72176. && mat12 == other.mat12;
  72177. }
  72178. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  72179. {
  72180. return ! operator== (other);
  72181. }
  72182. bool AffineTransform::isIdentity() const throw()
  72183. {
  72184. return (mat01 == 0)
  72185. && (mat02 == 0)
  72186. && (mat10 == 0)
  72187. && (mat12 == 0)
  72188. && (mat00 == 1.0f)
  72189. && (mat11 == 1.0f);
  72190. }
  72191. const AffineTransform AffineTransform::identity;
  72192. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  72193. {
  72194. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  72195. other.mat00 * mat01 + other.mat01 * mat11,
  72196. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  72197. other.mat10 * mat00 + other.mat11 * mat10,
  72198. other.mat10 * mat01 + other.mat11 * mat11,
  72199. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  72200. }
  72201. const AffineTransform AffineTransform::followedBy (const float omat00,
  72202. const float omat01,
  72203. const float omat02,
  72204. const float omat10,
  72205. const float omat11,
  72206. const float omat12) const throw()
  72207. {
  72208. return AffineTransform (omat00 * mat00 + omat01 * mat10,
  72209. omat00 * mat01 + omat01 * mat11,
  72210. omat00 * mat02 + omat01 * mat12 + omat02,
  72211. omat10 * mat00 + omat11 * mat10,
  72212. omat10 * mat01 + omat11 * mat11,
  72213. omat10 * mat02 + omat11 * mat12 + omat12);
  72214. }
  72215. const AffineTransform AffineTransform::translated (const float dx,
  72216. const float dy) const throw()
  72217. {
  72218. return AffineTransform (mat00, mat01, mat02 + dx,
  72219. mat10, mat11, mat12 + dy);
  72220. }
  72221. const AffineTransform AffineTransform::translation (const float dx,
  72222. const float dy) throw()
  72223. {
  72224. return AffineTransform (1.0f, 0, dx,
  72225. 0, 1.0f, dy);
  72226. }
  72227. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  72228. {
  72229. const float cosRad = std::cos (rad);
  72230. const float sinRad = std::sin (rad);
  72231. return followedBy (cosRad, -sinRad, 0,
  72232. sinRad, cosRad, 0);
  72233. }
  72234. const AffineTransform AffineTransform::rotation (const float rad) throw()
  72235. {
  72236. const float cosRad = std::cos (rad);
  72237. const float sinRad = std::sin (rad);
  72238. return AffineTransform (cosRad, -sinRad, 0,
  72239. sinRad, cosRad, 0);
  72240. }
  72241. const AffineTransform AffineTransform::rotated (const float angle,
  72242. const float pivotX,
  72243. const float pivotY) const throw()
  72244. {
  72245. return translated (-pivotX, -pivotY)
  72246. .rotated (angle)
  72247. .translated (pivotX, pivotY);
  72248. }
  72249. const AffineTransform AffineTransform::rotation (const float angle,
  72250. const float pivotX,
  72251. const float pivotY) throw()
  72252. {
  72253. return translation (-pivotX, -pivotY)
  72254. .rotated (angle)
  72255. .translated (pivotX, pivotY);
  72256. }
  72257. const AffineTransform AffineTransform::scaled (const float factorX,
  72258. const float factorY) const throw()
  72259. {
  72260. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02,
  72261. factorY * mat10, factorY * mat11, factorY * mat12);
  72262. }
  72263. const AffineTransform AffineTransform::scale (const float factorX,
  72264. const float factorY) throw()
  72265. {
  72266. return AffineTransform (factorX, 0, 0,
  72267. 0, factorY, 0);
  72268. }
  72269. const AffineTransform AffineTransform::sheared (const float shearX,
  72270. const float shearY) const throw()
  72271. {
  72272. return followedBy (1.0f, shearX, 0,
  72273. shearY, 1.0f, 0);
  72274. }
  72275. const AffineTransform AffineTransform::inverted() const throw()
  72276. {
  72277. double determinant = (mat00 * mat11 - mat10 * mat01);
  72278. if (determinant != 0.0)
  72279. {
  72280. determinant = 1.0 / determinant;
  72281. const float dst00 = (float) (mat11 * determinant);
  72282. const float dst10 = (float) (-mat10 * determinant);
  72283. const float dst01 = (float) (-mat01 * determinant);
  72284. const float dst11 = (float) (mat00 * determinant);
  72285. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  72286. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  72287. }
  72288. else
  72289. {
  72290. // singularity..
  72291. return *this;
  72292. }
  72293. }
  72294. bool AffineTransform::isSingularity() const throw()
  72295. {
  72296. return (mat00 * mat11 - mat10 * mat01) == 0.0;
  72297. }
  72298. const AffineTransform AffineTransform::fromTargetPoints (const float x00, const float y00,
  72299. const float x10, const float y10,
  72300. const float x01, const float y01) throw()
  72301. {
  72302. return AffineTransform (x10 - x00, x01 - x00, x00,
  72303. y10 - y00, y01 - y00, y00);
  72304. }
  72305. const AffineTransform AffineTransform::fromTargetPoints (const float sx1, const float sy1, const float tx1, const float ty1,
  72306. const float sx2, const float sy2, const float tx2, const float ty2,
  72307. const float sx3, const float sy3, const float tx3, const float ty3) throw()
  72308. {
  72309. return fromTargetPoints (sx1, sy1, sx2, sy2, sx3, sy3)
  72310. .inverted()
  72311. .followedBy (fromTargetPoints (tx1, ty1, tx2, ty2, tx3, ty3));
  72312. }
  72313. bool AffineTransform::isOnlyTranslation() const throw()
  72314. {
  72315. return (mat01 == 0)
  72316. && (mat10 == 0)
  72317. && (mat00 == 1.0f)
  72318. && (mat11 == 1.0f);
  72319. }
  72320. END_JUCE_NAMESPACE
  72321. /*** End of inlined file: juce_AffineTransform.cpp ***/
  72322. /*** Start of inlined file: juce_BorderSize.cpp ***/
  72323. BEGIN_JUCE_NAMESPACE
  72324. BorderSize::BorderSize() throw()
  72325. : top (0),
  72326. left (0),
  72327. bottom (0),
  72328. right (0)
  72329. {
  72330. }
  72331. BorderSize::BorderSize (const BorderSize& other) throw()
  72332. : top (other.top),
  72333. left (other.left),
  72334. bottom (other.bottom),
  72335. right (other.right)
  72336. {
  72337. }
  72338. BorderSize::BorderSize (const int topGap,
  72339. const int leftGap,
  72340. const int bottomGap,
  72341. const int rightGap) throw()
  72342. : top (topGap),
  72343. left (leftGap),
  72344. bottom (bottomGap),
  72345. right (rightGap)
  72346. {
  72347. }
  72348. BorderSize::BorderSize (const int allGaps) throw()
  72349. : top (allGaps),
  72350. left (allGaps),
  72351. bottom (allGaps),
  72352. right (allGaps)
  72353. {
  72354. }
  72355. BorderSize::~BorderSize() throw()
  72356. {
  72357. }
  72358. void BorderSize::setTop (const int newTopGap) throw()
  72359. {
  72360. top = newTopGap;
  72361. }
  72362. void BorderSize::setLeft (const int newLeftGap) throw()
  72363. {
  72364. left = newLeftGap;
  72365. }
  72366. void BorderSize::setBottom (const int newBottomGap) throw()
  72367. {
  72368. bottom = newBottomGap;
  72369. }
  72370. void BorderSize::setRight (const int newRightGap) throw()
  72371. {
  72372. right = newRightGap;
  72373. }
  72374. const Rectangle<int> BorderSize::subtractedFrom (const Rectangle<int>& r) const throw()
  72375. {
  72376. return Rectangle<int> (r.getX() + left,
  72377. r.getY() + top,
  72378. r.getWidth() - (left + right),
  72379. r.getHeight() - (top + bottom));
  72380. }
  72381. void BorderSize::subtractFrom (Rectangle<int>& r) const throw()
  72382. {
  72383. r.setBounds (r.getX() + left,
  72384. r.getY() + top,
  72385. r.getWidth() - (left + right),
  72386. r.getHeight() - (top + bottom));
  72387. }
  72388. const Rectangle<int> BorderSize::addedTo (const Rectangle<int>& r) const throw()
  72389. {
  72390. return Rectangle<int> (r.getX() - left,
  72391. r.getY() - top,
  72392. r.getWidth() + (left + right),
  72393. r.getHeight() + (top + bottom));
  72394. }
  72395. void BorderSize::addTo (Rectangle<int>& r) const throw()
  72396. {
  72397. r.setBounds (r.getX() - left,
  72398. r.getY() - top,
  72399. r.getWidth() + (left + right),
  72400. r.getHeight() + (top + bottom));
  72401. }
  72402. bool BorderSize::operator== (const BorderSize& other) const throw()
  72403. {
  72404. return top == other.top
  72405. && left == other.left
  72406. && bottom == other.bottom
  72407. && right == other.right;
  72408. }
  72409. bool BorderSize::operator!= (const BorderSize& other) const throw()
  72410. {
  72411. return ! operator== (other);
  72412. }
  72413. END_JUCE_NAMESPACE
  72414. /*** End of inlined file: juce_BorderSize.cpp ***/
  72415. /*** Start of inlined file: juce_Path.cpp ***/
  72416. BEGIN_JUCE_NAMESPACE
  72417. // tests that some co-ords aren't NaNs
  72418. #define CHECK_COORDS_ARE_VALID(x, y) \
  72419. jassert (x == x && y == y);
  72420. namespace PathHelpers
  72421. {
  72422. static const float ellipseAngularIncrement = 0.05f;
  72423. static const String nextToken (const juce_wchar*& t)
  72424. {
  72425. while (CharacterFunctions::isWhitespace (*t))
  72426. ++t;
  72427. const juce_wchar* const start = t;
  72428. while (*t != 0 && ! CharacterFunctions::isWhitespace (*t))
  72429. ++t;
  72430. return String (start, (int) (t - start));
  72431. }
  72432. }
  72433. const float Path::lineMarker = 100001.0f;
  72434. const float Path::moveMarker = 100002.0f;
  72435. const float Path::quadMarker = 100003.0f;
  72436. const float Path::cubicMarker = 100004.0f;
  72437. const float Path::closeSubPathMarker = 100005.0f;
  72438. Path::Path()
  72439. : numElements (0),
  72440. pathXMin (0),
  72441. pathXMax (0),
  72442. pathYMin (0),
  72443. pathYMax (0),
  72444. useNonZeroWinding (true)
  72445. {
  72446. }
  72447. Path::~Path()
  72448. {
  72449. }
  72450. Path::Path (const Path& other)
  72451. : numElements (other.numElements),
  72452. pathXMin (other.pathXMin),
  72453. pathXMax (other.pathXMax),
  72454. pathYMin (other.pathYMin),
  72455. pathYMax (other.pathYMax),
  72456. useNonZeroWinding (other.useNonZeroWinding)
  72457. {
  72458. if (numElements > 0)
  72459. {
  72460. data.setAllocatedSize ((int) numElements);
  72461. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  72462. }
  72463. }
  72464. Path& Path::operator= (const Path& other)
  72465. {
  72466. if (this != &other)
  72467. {
  72468. data.ensureAllocatedSize ((int) other.numElements);
  72469. numElements = other.numElements;
  72470. pathXMin = other.pathXMin;
  72471. pathXMax = other.pathXMax;
  72472. pathYMin = other.pathYMin;
  72473. pathYMax = other.pathYMax;
  72474. useNonZeroWinding = other.useNonZeroWinding;
  72475. if (numElements > 0)
  72476. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  72477. }
  72478. return *this;
  72479. }
  72480. bool Path::operator== (const Path& other) const throw()
  72481. {
  72482. return ! operator!= (other);
  72483. }
  72484. bool Path::operator!= (const Path& other) const throw()
  72485. {
  72486. if (numElements != other.numElements || useNonZeroWinding != other.useNonZeroWinding)
  72487. return true;
  72488. for (size_t i = 0; i < numElements; ++i)
  72489. if (data.elements[i] != other.data.elements[i])
  72490. return true;
  72491. return false;
  72492. }
  72493. void Path::clear() throw()
  72494. {
  72495. numElements = 0;
  72496. pathXMin = 0;
  72497. pathYMin = 0;
  72498. pathYMax = 0;
  72499. pathXMax = 0;
  72500. }
  72501. void Path::swapWithPath (Path& other) throw()
  72502. {
  72503. data.swapWith (other.data);
  72504. swapVariables <size_t> (numElements, other.numElements);
  72505. swapVariables <float> (pathXMin, other.pathXMin);
  72506. swapVariables <float> (pathXMax, other.pathXMax);
  72507. swapVariables <float> (pathYMin, other.pathYMin);
  72508. swapVariables <float> (pathYMax, other.pathYMax);
  72509. swapVariables <bool> (useNonZeroWinding, other.useNonZeroWinding);
  72510. }
  72511. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  72512. {
  72513. useNonZeroWinding = isNonZero;
  72514. }
  72515. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  72516. const bool preserveProportions) throw()
  72517. {
  72518. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  72519. }
  72520. bool Path::isEmpty() const throw()
  72521. {
  72522. size_t i = 0;
  72523. while (i < numElements)
  72524. {
  72525. const float type = data.elements [i++];
  72526. if (type == moveMarker)
  72527. {
  72528. i += 2;
  72529. }
  72530. else if (type == lineMarker
  72531. || type == quadMarker
  72532. || type == cubicMarker)
  72533. {
  72534. return false;
  72535. }
  72536. }
  72537. return true;
  72538. }
  72539. const Rectangle<float> Path::getBounds() const throw()
  72540. {
  72541. return Rectangle<float> (pathXMin, pathYMin,
  72542. pathXMax - pathXMin,
  72543. pathYMax - pathYMin);
  72544. }
  72545. const Rectangle<float> Path::getBoundsTransformed (const AffineTransform& transform) const throw()
  72546. {
  72547. return getBounds().transformed (transform);
  72548. }
  72549. void Path::startNewSubPath (const float x, const float y)
  72550. {
  72551. CHECK_COORDS_ARE_VALID (x, y);
  72552. if (numElements == 0)
  72553. {
  72554. pathXMin = pathXMax = x;
  72555. pathYMin = pathYMax = y;
  72556. }
  72557. else
  72558. {
  72559. pathXMin = jmin (pathXMin, x);
  72560. pathXMax = jmax (pathXMax, x);
  72561. pathYMin = jmin (pathYMin, y);
  72562. pathYMax = jmax (pathYMax, y);
  72563. }
  72564. data.ensureAllocatedSize ((int) numElements + 3);
  72565. data.elements [numElements++] = moveMarker;
  72566. data.elements [numElements++] = x;
  72567. data.elements [numElements++] = y;
  72568. }
  72569. void Path::startNewSubPath (const Point<float>& start)
  72570. {
  72571. startNewSubPath (start.getX(), start.getY());
  72572. }
  72573. void Path::lineTo (const float x, const float y)
  72574. {
  72575. CHECK_COORDS_ARE_VALID (x, y);
  72576. if (numElements == 0)
  72577. startNewSubPath (0, 0);
  72578. data.ensureAllocatedSize ((int) numElements + 3);
  72579. data.elements [numElements++] = lineMarker;
  72580. data.elements [numElements++] = x;
  72581. data.elements [numElements++] = y;
  72582. pathXMin = jmin (pathXMin, x);
  72583. pathXMax = jmax (pathXMax, x);
  72584. pathYMin = jmin (pathYMin, y);
  72585. pathYMax = jmax (pathYMax, y);
  72586. }
  72587. void Path::lineTo (const Point<float>& end)
  72588. {
  72589. lineTo (end.getX(), end.getY());
  72590. }
  72591. void Path::quadraticTo (const float x1, const float y1,
  72592. const float x2, const float y2)
  72593. {
  72594. CHECK_COORDS_ARE_VALID (x1, y1);
  72595. CHECK_COORDS_ARE_VALID (x2, y2);
  72596. if (numElements == 0)
  72597. startNewSubPath (0, 0);
  72598. data.ensureAllocatedSize ((int) numElements + 5);
  72599. data.elements [numElements++] = quadMarker;
  72600. data.elements [numElements++] = x1;
  72601. data.elements [numElements++] = y1;
  72602. data.elements [numElements++] = x2;
  72603. data.elements [numElements++] = y2;
  72604. pathXMin = jmin (pathXMin, x1, x2);
  72605. pathXMax = jmax (pathXMax, x1, x2);
  72606. pathYMin = jmin (pathYMin, y1, y2);
  72607. pathYMax = jmax (pathYMax, y1, y2);
  72608. }
  72609. void Path::quadraticTo (const Point<float>& controlPoint,
  72610. const Point<float>& endPoint)
  72611. {
  72612. quadraticTo (controlPoint.getX(), controlPoint.getY(),
  72613. endPoint.getX(), endPoint.getY());
  72614. }
  72615. void Path::cubicTo (const float x1, const float y1,
  72616. const float x2, const float y2,
  72617. const float x3, const float y3)
  72618. {
  72619. CHECK_COORDS_ARE_VALID (x1, y1);
  72620. CHECK_COORDS_ARE_VALID (x2, y2);
  72621. CHECK_COORDS_ARE_VALID (x3, y3);
  72622. if (numElements == 0)
  72623. startNewSubPath (0, 0);
  72624. data.ensureAllocatedSize ((int) numElements + 7);
  72625. data.elements [numElements++] = cubicMarker;
  72626. data.elements [numElements++] = x1;
  72627. data.elements [numElements++] = y1;
  72628. data.elements [numElements++] = x2;
  72629. data.elements [numElements++] = y2;
  72630. data.elements [numElements++] = x3;
  72631. data.elements [numElements++] = y3;
  72632. pathXMin = jmin (pathXMin, x1, x2, x3);
  72633. pathXMax = jmax (pathXMax, x1, x2, x3);
  72634. pathYMin = jmin (pathYMin, y1, y2, y3);
  72635. pathYMax = jmax (pathYMax, y1, y2, y3);
  72636. }
  72637. void Path::cubicTo (const Point<float>& controlPoint1,
  72638. const Point<float>& controlPoint2,
  72639. const Point<float>& endPoint)
  72640. {
  72641. cubicTo (controlPoint1.getX(), controlPoint1.getY(),
  72642. controlPoint2.getX(), controlPoint2.getY(),
  72643. endPoint.getX(), endPoint.getY());
  72644. }
  72645. void Path::closeSubPath()
  72646. {
  72647. if (numElements > 0
  72648. && data.elements [numElements - 1] != closeSubPathMarker)
  72649. {
  72650. data.ensureAllocatedSize ((int) numElements + 1);
  72651. data.elements [numElements++] = closeSubPathMarker;
  72652. }
  72653. }
  72654. const Point<float> Path::getCurrentPosition() const
  72655. {
  72656. size_t i = numElements - 1;
  72657. if (i > 0 && data.elements[i] == closeSubPathMarker)
  72658. {
  72659. while (i >= 0)
  72660. {
  72661. if (data.elements[i] == moveMarker)
  72662. {
  72663. i += 2;
  72664. break;
  72665. }
  72666. --i;
  72667. }
  72668. }
  72669. if (i > 0)
  72670. return Point<float> (data.elements [i - 1], data.elements [i]);
  72671. return Point<float>();
  72672. }
  72673. void Path::addRectangle (const float x, const float y,
  72674. const float w, const float h)
  72675. {
  72676. float x1 = x, y1 = y, x2 = x + w, y2 = y + h;
  72677. if (w < 0)
  72678. swapVariables (x1, x2);
  72679. if (h < 0)
  72680. swapVariables (y1, y2);
  72681. data.ensureAllocatedSize ((int) numElements + 13);
  72682. if (numElements == 0)
  72683. {
  72684. pathXMin = x1;
  72685. pathXMax = x2;
  72686. pathYMin = y1;
  72687. pathYMax = y2;
  72688. }
  72689. else
  72690. {
  72691. pathXMin = jmin (pathXMin, x1);
  72692. pathXMax = jmax (pathXMax, x2);
  72693. pathYMin = jmin (pathYMin, y1);
  72694. pathYMax = jmax (pathYMax, y2);
  72695. }
  72696. data.elements [numElements++] = moveMarker;
  72697. data.elements [numElements++] = x1;
  72698. data.elements [numElements++] = y2;
  72699. data.elements [numElements++] = lineMarker;
  72700. data.elements [numElements++] = x1;
  72701. data.elements [numElements++] = y1;
  72702. data.elements [numElements++] = lineMarker;
  72703. data.elements [numElements++] = x2;
  72704. data.elements [numElements++] = y1;
  72705. data.elements [numElements++] = lineMarker;
  72706. data.elements [numElements++] = x2;
  72707. data.elements [numElements++] = y2;
  72708. data.elements [numElements++] = closeSubPathMarker;
  72709. }
  72710. void Path::addRectangle (const Rectangle<int>& rectangle)
  72711. {
  72712. addRectangle ((float) rectangle.getX(), (float) rectangle.getY(),
  72713. (float) rectangle.getWidth(), (float) rectangle.getHeight());
  72714. }
  72715. void Path::addRoundedRectangle (const float x, const float y,
  72716. const float w, const float h,
  72717. float csx,
  72718. float csy)
  72719. {
  72720. csx = jmin (csx, w * 0.5f);
  72721. csy = jmin (csy, h * 0.5f);
  72722. const float cs45x = csx * 0.45f;
  72723. const float cs45y = csy * 0.45f;
  72724. const float x2 = x + w;
  72725. const float y2 = y + h;
  72726. startNewSubPath (x + csx, y);
  72727. lineTo (x2 - csx, y);
  72728. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  72729. lineTo (x2, y2 - csy);
  72730. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  72731. lineTo (x + csx, y2);
  72732. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  72733. lineTo (x, y + csy);
  72734. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  72735. closeSubPath();
  72736. }
  72737. void Path::addRoundedRectangle (const float x, const float y,
  72738. const float w, const float h,
  72739. float cs)
  72740. {
  72741. addRoundedRectangle (x, y, w, h, cs, cs);
  72742. }
  72743. void Path::addTriangle (const float x1, const float y1,
  72744. const float x2, const float y2,
  72745. const float x3, const float y3)
  72746. {
  72747. startNewSubPath (x1, y1);
  72748. lineTo (x2, y2);
  72749. lineTo (x3, y3);
  72750. closeSubPath();
  72751. }
  72752. void Path::addQuadrilateral (const float x1, const float y1,
  72753. const float x2, const float y2,
  72754. const float x3, const float y3,
  72755. const float x4, const float y4)
  72756. {
  72757. startNewSubPath (x1, y1);
  72758. lineTo (x2, y2);
  72759. lineTo (x3, y3);
  72760. lineTo (x4, y4);
  72761. closeSubPath();
  72762. }
  72763. void Path::addEllipse (const float x, const float y,
  72764. const float w, const float h)
  72765. {
  72766. const float hw = w * 0.5f;
  72767. const float hw55 = hw * 0.55f;
  72768. const float hh = h * 0.5f;
  72769. const float hh45 = hh * 0.55f;
  72770. const float cx = x + hw;
  72771. const float cy = y + hh;
  72772. startNewSubPath (cx, cy - hh);
  72773. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh45, cx + hw, cy);
  72774. cubicTo (cx + hw, cy + hh45, cx + hw55, cy + hh, cx, cy + hh);
  72775. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh45, cx - hw, cy);
  72776. cubicTo (cx - hw, cy - hh45, cx - hw55, cy - hh, cx, cy - hh);
  72777. closeSubPath();
  72778. }
  72779. void Path::addArc (const float x, const float y,
  72780. const float w, const float h,
  72781. const float fromRadians,
  72782. const float toRadians,
  72783. const bool startAsNewSubPath)
  72784. {
  72785. const float radiusX = w / 2.0f;
  72786. const float radiusY = h / 2.0f;
  72787. addCentredArc (x + radiusX,
  72788. y + radiusY,
  72789. radiusX, radiusY,
  72790. 0.0f,
  72791. fromRadians, toRadians,
  72792. startAsNewSubPath);
  72793. }
  72794. void Path::addCentredArc (const float centreX, const float centreY,
  72795. const float radiusX, const float radiusY,
  72796. const float rotationOfEllipse,
  72797. const float fromRadians,
  72798. const float toRadians,
  72799. const bool startAsNewSubPath)
  72800. {
  72801. if (radiusX > 0.0f && radiusY > 0.0f)
  72802. {
  72803. const Point<float> centre (centreX, centreY);
  72804. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  72805. float angle = fromRadians;
  72806. if (startAsNewSubPath)
  72807. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  72808. if (fromRadians < toRadians)
  72809. {
  72810. if (startAsNewSubPath)
  72811. angle += PathHelpers::ellipseAngularIncrement;
  72812. while (angle < toRadians)
  72813. {
  72814. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  72815. angle += PathHelpers::ellipseAngularIncrement;
  72816. }
  72817. }
  72818. else
  72819. {
  72820. if (startAsNewSubPath)
  72821. angle -= PathHelpers::ellipseAngularIncrement;
  72822. while (angle > toRadians)
  72823. {
  72824. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  72825. angle -= PathHelpers::ellipseAngularIncrement;
  72826. }
  72827. }
  72828. lineTo (centre.getPointOnCircumference (radiusX, radiusY, toRadians).transformedBy (rotation));
  72829. }
  72830. }
  72831. void Path::addPieSegment (const float x, const float y,
  72832. const float width, const float height,
  72833. const float fromRadians,
  72834. const float toRadians,
  72835. const float innerCircleProportionalSize)
  72836. {
  72837. float radiusX = width * 0.5f;
  72838. float radiusY = height * 0.5f;
  72839. const Point<float> centre (x + radiusX, y + radiusY);
  72840. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, fromRadians));
  72841. addArc (x, y, width, height, fromRadians, toRadians);
  72842. if (std::abs (fromRadians - toRadians) > float_Pi * 1.999f)
  72843. {
  72844. closeSubPath();
  72845. if (innerCircleProportionalSize > 0)
  72846. {
  72847. radiusX *= innerCircleProportionalSize;
  72848. radiusY *= innerCircleProportionalSize;
  72849. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, toRadians));
  72850. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  72851. }
  72852. }
  72853. else
  72854. {
  72855. if (innerCircleProportionalSize > 0)
  72856. {
  72857. radiusX *= innerCircleProportionalSize;
  72858. radiusY *= innerCircleProportionalSize;
  72859. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  72860. }
  72861. else
  72862. {
  72863. lineTo (centre);
  72864. }
  72865. }
  72866. closeSubPath();
  72867. }
  72868. void Path::addLineSegment (const Line<float>& line, float lineThickness)
  72869. {
  72870. const Line<float> reversed (line.reversed());
  72871. lineThickness *= 0.5f;
  72872. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  72873. lineTo (line.getPointAlongLine (0, -lineThickness));
  72874. lineTo (reversed.getPointAlongLine (0, lineThickness));
  72875. lineTo (reversed.getPointAlongLine (0, -lineThickness));
  72876. closeSubPath();
  72877. }
  72878. void Path::addArrow (const Line<float>& line, float lineThickness,
  72879. float arrowheadWidth, float arrowheadLength)
  72880. {
  72881. const Line<float> reversed (line.reversed());
  72882. lineThickness *= 0.5f;
  72883. arrowheadWidth *= 0.5f;
  72884. arrowheadLength = jmin (arrowheadLength, 0.8f * line.getLength());
  72885. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  72886. lineTo (line.getPointAlongLine (0, -lineThickness));
  72887. lineTo (reversed.getPointAlongLine (arrowheadLength, lineThickness));
  72888. lineTo (reversed.getPointAlongLine (arrowheadLength, arrowheadWidth));
  72889. lineTo (line.getEnd());
  72890. lineTo (reversed.getPointAlongLine (arrowheadLength, -arrowheadWidth));
  72891. lineTo (reversed.getPointAlongLine (arrowheadLength, -lineThickness));
  72892. closeSubPath();
  72893. }
  72894. void Path::addPolygon (const Point<float>& centre, const int numberOfSides,
  72895. const float radius, const float startAngle)
  72896. {
  72897. jassert (numberOfSides > 1); // this would be silly.
  72898. if (numberOfSides > 1)
  72899. {
  72900. const float angleBetweenPoints = float_Pi * 2.0f / numberOfSides;
  72901. for (int i = 0; i < numberOfSides; ++i)
  72902. {
  72903. const float angle = startAngle + i * angleBetweenPoints;
  72904. const Point<float> p (centre.getPointOnCircumference (radius, angle));
  72905. if (i == 0)
  72906. startNewSubPath (p);
  72907. else
  72908. lineTo (p);
  72909. }
  72910. closeSubPath();
  72911. }
  72912. }
  72913. void Path::addStar (const Point<float>& centre, const int numberOfPoints,
  72914. const float innerRadius, const float outerRadius, const float startAngle)
  72915. {
  72916. jassert (numberOfPoints > 1); // this would be silly.
  72917. if (numberOfPoints > 1)
  72918. {
  72919. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  72920. for (int i = 0; i < numberOfPoints; ++i)
  72921. {
  72922. const float angle = startAngle + i * angleBetweenPoints;
  72923. const Point<float> p (centre.getPointOnCircumference (outerRadius, angle));
  72924. if (i == 0)
  72925. startNewSubPath (p);
  72926. else
  72927. lineTo (p);
  72928. lineTo (centre.getPointOnCircumference (innerRadius, angle + angleBetweenPoints * 0.5f));
  72929. }
  72930. closeSubPath();
  72931. }
  72932. }
  72933. void Path::addBubble (float x, float y,
  72934. float w, float h,
  72935. float cs,
  72936. float tipX,
  72937. float tipY,
  72938. int whichSide,
  72939. float arrowPos,
  72940. float arrowWidth)
  72941. {
  72942. if (w > 1.0f && h > 1.0f)
  72943. {
  72944. cs = jmin (cs, w * 0.5f, h * 0.5f);
  72945. const float cs2 = 2.0f * cs;
  72946. startNewSubPath (x + cs, y);
  72947. if (whichSide == 0)
  72948. {
  72949. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  72950. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  72951. lineTo (arrowX1, y);
  72952. lineTo (tipX, tipY);
  72953. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  72954. }
  72955. lineTo (x + w - cs, y);
  72956. if (cs > 0.0f)
  72957. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  72958. if (whichSide == 3)
  72959. {
  72960. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  72961. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  72962. lineTo (x + w, arrowY1);
  72963. lineTo (tipX, tipY);
  72964. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  72965. }
  72966. lineTo (x + w, y + h - cs);
  72967. if (cs > 0.0f)
  72968. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  72969. if (whichSide == 2)
  72970. {
  72971. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  72972. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  72973. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  72974. lineTo (tipX, tipY);
  72975. lineTo (arrowX1, y + h);
  72976. }
  72977. lineTo (x + cs, y + h);
  72978. if (cs > 0.0f)
  72979. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  72980. if (whichSide == 1)
  72981. {
  72982. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  72983. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  72984. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  72985. lineTo (tipX, tipY);
  72986. lineTo (x, arrowY1);
  72987. }
  72988. lineTo (x, y + cs);
  72989. if (cs > 0.0f)
  72990. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - PathHelpers::ellipseAngularIncrement);
  72991. closeSubPath();
  72992. }
  72993. }
  72994. void Path::addPath (const Path& other)
  72995. {
  72996. size_t i = 0;
  72997. while (i < other.numElements)
  72998. {
  72999. const float type = other.data.elements [i++];
  73000. if (type == moveMarker)
  73001. {
  73002. startNewSubPath (other.data.elements [i],
  73003. other.data.elements [i + 1]);
  73004. i += 2;
  73005. }
  73006. else if (type == lineMarker)
  73007. {
  73008. lineTo (other.data.elements [i],
  73009. other.data.elements [i + 1]);
  73010. i += 2;
  73011. }
  73012. else if (type == quadMarker)
  73013. {
  73014. quadraticTo (other.data.elements [i],
  73015. other.data.elements [i + 1],
  73016. other.data.elements [i + 2],
  73017. other.data.elements [i + 3]);
  73018. i += 4;
  73019. }
  73020. else if (type == cubicMarker)
  73021. {
  73022. cubicTo (other.data.elements [i],
  73023. other.data.elements [i + 1],
  73024. other.data.elements [i + 2],
  73025. other.data.elements [i + 3],
  73026. other.data.elements [i + 4],
  73027. other.data.elements [i + 5]);
  73028. i += 6;
  73029. }
  73030. else if (type == closeSubPathMarker)
  73031. {
  73032. closeSubPath();
  73033. }
  73034. else
  73035. {
  73036. // something's gone wrong with the element list!
  73037. jassertfalse;
  73038. }
  73039. }
  73040. }
  73041. void Path::addPath (const Path& other,
  73042. const AffineTransform& transformToApply)
  73043. {
  73044. size_t i = 0;
  73045. while (i < other.numElements)
  73046. {
  73047. const float type = other.data.elements [i++];
  73048. if (type == closeSubPathMarker)
  73049. {
  73050. closeSubPath();
  73051. }
  73052. else
  73053. {
  73054. float x = other.data.elements [i++];
  73055. float y = other.data.elements [i++];
  73056. transformToApply.transformPoint (x, y);
  73057. if (type == moveMarker)
  73058. {
  73059. startNewSubPath (x, y);
  73060. }
  73061. else if (type == lineMarker)
  73062. {
  73063. lineTo (x, y);
  73064. }
  73065. else if (type == quadMarker)
  73066. {
  73067. float x2 = other.data.elements [i++];
  73068. float y2 = other.data.elements [i++];
  73069. transformToApply.transformPoint (x2, y2);
  73070. quadraticTo (x, y, x2, y2);
  73071. }
  73072. else if (type == cubicMarker)
  73073. {
  73074. float x2 = other.data.elements [i++];
  73075. float y2 = other.data.elements [i++];
  73076. float x3 = other.data.elements [i++];
  73077. float y3 = other.data.elements [i++];
  73078. transformToApply.transformPoints (x2, y2, x3, y3);
  73079. cubicTo (x, y, x2, y2, x3, y3);
  73080. }
  73081. else
  73082. {
  73083. // something's gone wrong with the element list!
  73084. jassertfalse;
  73085. }
  73086. }
  73087. }
  73088. }
  73089. void Path::applyTransform (const AffineTransform& transform) throw()
  73090. {
  73091. size_t i = 0;
  73092. pathYMin = pathXMin = 0;
  73093. pathYMax = pathXMax = 0;
  73094. bool setMaxMin = false;
  73095. while (i < numElements)
  73096. {
  73097. const float type = data.elements [i++];
  73098. if (type == moveMarker)
  73099. {
  73100. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  73101. if (setMaxMin)
  73102. {
  73103. pathXMin = jmin (pathXMin, data.elements [i]);
  73104. pathXMax = jmax (pathXMax, data.elements [i]);
  73105. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  73106. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  73107. }
  73108. else
  73109. {
  73110. pathXMin = pathXMax = data.elements [i];
  73111. pathYMin = pathYMax = data.elements [i + 1];
  73112. setMaxMin = true;
  73113. }
  73114. i += 2;
  73115. }
  73116. else if (type == lineMarker)
  73117. {
  73118. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  73119. pathXMin = jmin (pathXMin, data.elements [i]);
  73120. pathXMax = jmax (pathXMax, data.elements [i]);
  73121. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  73122. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  73123. i += 2;
  73124. }
  73125. else if (type == quadMarker)
  73126. {
  73127. transform.transformPoints (data.elements [i], data.elements [i + 1],
  73128. data.elements [i + 2], data.elements [i + 3]);
  73129. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2]);
  73130. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2]);
  73131. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3]);
  73132. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3]);
  73133. i += 4;
  73134. }
  73135. else if (type == cubicMarker)
  73136. {
  73137. transform.transformPoints (data.elements [i], data.elements [i + 1],
  73138. data.elements [i + 2], data.elements [i + 3],
  73139. data.elements [i + 4], data.elements [i + 5]);
  73140. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  73141. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  73142. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  73143. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  73144. i += 6;
  73145. }
  73146. }
  73147. }
  73148. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  73149. const float w, const float h,
  73150. const bool preserveProportions,
  73151. const Justification& justification) const
  73152. {
  73153. Rectangle<float> bounds (getBounds());
  73154. if (preserveProportions)
  73155. {
  73156. if (w <= 0 || h <= 0 || bounds.isEmpty())
  73157. return AffineTransform::identity;
  73158. float newW, newH;
  73159. const float srcRatio = bounds.getHeight() / bounds.getWidth();
  73160. if (srcRatio > h / w)
  73161. {
  73162. newW = h / srcRatio;
  73163. newH = h;
  73164. }
  73165. else
  73166. {
  73167. newW = w;
  73168. newH = w * srcRatio;
  73169. }
  73170. float newXCentre = x;
  73171. float newYCentre = y;
  73172. if (justification.testFlags (Justification::left))
  73173. newXCentre += newW * 0.5f;
  73174. else if (justification.testFlags (Justification::right))
  73175. newXCentre += w - newW * 0.5f;
  73176. else
  73177. newXCentre += w * 0.5f;
  73178. if (justification.testFlags (Justification::top))
  73179. newYCentre += newH * 0.5f;
  73180. else if (justification.testFlags (Justification::bottom))
  73181. newYCentre += h - newH * 0.5f;
  73182. else
  73183. newYCentre += h * 0.5f;
  73184. return AffineTransform::translation (bounds.getWidth() * -0.5f - bounds.getX(),
  73185. bounds.getHeight() * -0.5f - bounds.getY())
  73186. .scaled (newW / bounds.getWidth(), newH / bounds.getHeight())
  73187. .translated (newXCentre, newYCentre);
  73188. }
  73189. else
  73190. {
  73191. return AffineTransform::translation (-bounds.getX(), -bounds.getY())
  73192. .scaled (w / bounds.getWidth(), h / bounds.getHeight())
  73193. .translated (x, y);
  73194. }
  73195. }
  73196. bool Path::contains (const float x, const float y, const float tolerence) const
  73197. {
  73198. if (x <= pathXMin || x >= pathXMax
  73199. || y <= pathYMin || y >= pathYMax)
  73200. return false;
  73201. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  73202. int positiveCrossings = 0;
  73203. int negativeCrossings = 0;
  73204. while (i.next())
  73205. {
  73206. if ((i.y1 <= y && i.y2 > y) || (i.y2 <= y && i.y1 > y))
  73207. {
  73208. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  73209. if (intersectX <= x)
  73210. {
  73211. if (i.y1 < i.y2)
  73212. ++positiveCrossings;
  73213. else
  73214. ++negativeCrossings;
  73215. }
  73216. }
  73217. }
  73218. return useNonZeroWinding ? (negativeCrossings != positiveCrossings)
  73219. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  73220. }
  73221. bool Path::contains (const Point<float>& point, const float tolerence) const
  73222. {
  73223. return contains (point.getX(), point.getY(), tolerence);
  73224. }
  73225. bool Path::intersectsLine (const Line<float>& line, const float tolerence)
  73226. {
  73227. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  73228. Point<float> intersection;
  73229. while (i.next())
  73230. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  73231. return true;
  73232. return false;
  73233. }
  73234. const Line<float> Path::getClippedLine (const Line<float>& line, const bool keepSectionOutsidePath) const
  73235. {
  73236. Line<float> result (line);
  73237. const bool startInside = contains (line.getStart());
  73238. const bool endInside = contains (line.getEnd());
  73239. if (startInside == endInside)
  73240. {
  73241. if (keepSectionOutsidePath == startInside)
  73242. result = Line<float>();
  73243. }
  73244. else
  73245. {
  73246. PathFlatteningIterator i (*this, AffineTransform::identity);
  73247. Point<float> intersection;
  73248. while (i.next())
  73249. {
  73250. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  73251. {
  73252. if ((startInside && keepSectionOutsidePath) || (endInside && ! keepSectionOutsidePath))
  73253. result.setStart (intersection);
  73254. else
  73255. result.setEnd (intersection);
  73256. }
  73257. }
  73258. }
  73259. return result;
  73260. }
  73261. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const
  73262. {
  73263. if (cornerRadius <= 0.01f)
  73264. return *this;
  73265. size_t indexOfPathStart = 0, indexOfPathStartThis = 0;
  73266. size_t n = 0;
  73267. bool lastWasLine = false, firstWasLine = false;
  73268. Path p;
  73269. while (n < numElements)
  73270. {
  73271. const float type = data.elements [n++];
  73272. if (type == moveMarker)
  73273. {
  73274. indexOfPathStart = p.numElements;
  73275. indexOfPathStartThis = n - 1;
  73276. const float x = data.elements [n++];
  73277. const float y = data.elements [n++];
  73278. p.startNewSubPath (x, y);
  73279. lastWasLine = false;
  73280. firstWasLine = (data.elements [n] == lineMarker);
  73281. }
  73282. else if (type == lineMarker || type == closeSubPathMarker)
  73283. {
  73284. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  73285. if (type == lineMarker)
  73286. {
  73287. endX = data.elements [n++];
  73288. endY = data.elements [n++];
  73289. if (n > 8)
  73290. {
  73291. startX = data.elements [n - 8];
  73292. startY = data.elements [n - 7];
  73293. joinX = data.elements [n - 5];
  73294. joinY = data.elements [n - 4];
  73295. }
  73296. }
  73297. else
  73298. {
  73299. endX = data.elements [indexOfPathStartThis + 1];
  73300. endY = data.elements [indexOfPathStartThis + 2];
  73301. if (n > 6)
  73302. {
  73303. startX = data.elements [n - 6];
  73304. startY = data.elements [n - 5];
  73305. joinX = data.elements [n - 3];
  73306. joinY = data.elements [n - 2];
  73307. }
  73308. }
  73309. if (lastWasLine)
  73310. {
  73311. const double len1 = juce_hypot (startX - joinX,
  73312. startY - joinY);
  73313. if (len1 > 0)
  73314. {
  73315. const double propNeeded = jmin (0.5, cornerRadius / len1);
  73316. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  73317. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  73318. }
  73319. const double len2 = juce_hypot (endX - joinX,
  73320. endY - joinY);
  73321. if (len2 > 0)
  73322. {
  73323. const double propNeeded = jmin (0.5, cornerRadius / len2);
  73324. p.quadraticTo (joinX, joinY,
  73325. (float) (joinX + (endX - joinX) * propNeeded),
  73326. (float) (joinY + (endY - joinY) * propNeeded));
  73327. }
  73328. p.lineTo (endX, endY);
  73329. }
  73330. else if (type == lineMarker)
  73331. {
  73332. p.lineTo (endX, endY);
  73333. lastWasLine = true;
  73334. }
  73335. if (type == closeSubPathMarker)
  73336. {
  73337. if (firstWasLine)
  73338. {
  73339. startX = data.elements [n - 3];
  73340. startY = data.elements [n - 2];
  73341. joinX = endX;
  73342. joinY = endY;
  73343. endX = data.elements [indexOfPathStartThis + 4];
  73344. endY = data.elements [indexOfPathStartThis + 5];
  73345. const double len1 = juce_hypot (startX - joinX,
  73346. startY - joinY);
  73347. if (len1 > 0)
  73348. {
  73349. const double propNeeded = jmin (0.5, cornerRadius / len1);
  73350. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  73351. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  73352. }
  73353. const double len2 = juce_hypot (endX - joinX,
  73354. endY - joinY);
  73355. if (len2 > 0)
  73356. {
  73357. const double propNeeded = jmin (0.5, cornerRadius / len2);
  73358. endX = (float) (joinX + (endX - joinX) * propNeeded);
  73359. endY = (float) (joinY + (endY - joinY) * propNeeded);
  73360. p.quadraticTo (joinX, joinY, endX, endY);
  73361. p.data.elements [indexOfPathStart + 1] = endX;
  73362. p.data.elements [indexOfPathStart + 2] = endY;
  73363. }
  73364. }
  73365. p.closeSubPath();
  73366. }
  73367. }
  73368. else if (type == quadMarker)
  73369. {
  73370. lastWasLine = false;
  73371. const float x1 = data.elements [n++];
  73372. const float y1 = data.elements [n++];
  73373. const float x2 = data.elements [n++];
  73374. const float y2 = data.elements [n++];
  73375. p.quadraticTo (x1, y1, x2, y2);
  73376. }
  73377. else if (type == cubicMarker)
  73378. {
  73379. lastWasLine = false;
  73380. const float x1 = data.elements [n++];
  73381. const float y1 = data.elements [n++];
  73382. const float x2 = data.elements [n++];
  73383. const float y2 = data.elements [n++];
  73384. const float x3 = data.elements [n++];
  73385. const float y3 = data.elements [n++];
  73386. p.cubicTo (x1, y1, x2, y2, x3, y3);
  73387. }
  73388. }
  73389. return p;
  73390. }
  73391. void Path::loadPathFromStream (InputStream& source)
  73392. {
  73393. while (! source.isExhausted())
  73394. {
  73395. switch (source.readByte())
  73396. {
  73397. case 'm':
  73398. {
  73399. const float x = source.readFloat();
  73400. const float y = source.readFloat();
  73401. startNewSubPath (x, y);
  73402. break;
  73403. }
  73404. case 'l':
  73405. {
  73406. const float x = source.readFloat();
  73407. const float y = source.readFloat();
  73408. lineTo (x, y);
  73409. break;
  73410. }
  73411. case 'q':
  73412. {
  73413. const float x1 = source.readFloat();
  73414. const float y1 = source.readFloat();
  73415. const float x2 = source.readFloat();
  73416. const float y2 = source.readFloat();
  73417. quadraticTo (x1, y1, x2, y2);
  73418. break;
  73419. }
  73420. case 'b':
  73421. {
  73422. const float x1 = source.readFloat();
  73423. const float y1 = source.readFloat();
  73424. const float x2 = source.readFloat();
  73425. const float y2 = source.readFloat();
  73426. const float x3 = source.readFloat();
  73427. const float y3 = source.readFloat();
  73428. cubicTo (x1, y1, x2, y2, x3, y3);
  73429. break;
  73430. }
  73431. case 'c':
  73432. closeSubPath();
  73433. break;
  73434. case 'n':
  73435. useNonZeroWinding = true;
  73436. break;
  73437. case 'z':
  73438. useNonZeroWinding = false;
  73439. break;
  73440. case 'e':
  73441. return; // end of path marker
  73442. default:
  73443. jassertfalse; // illegal char in the stream
  73444. break;
  73445. }
  73446. }
  73447. }
  73448. void Path::loadPathFromData (const void* const pathData, const int numberOfBytes)
  73449. {
  73450. MemoryInputStream in (pathData, numberOfBytes, false);
  73451. loadPathFromStream (in);
  73452. }
  73453. void Path::writePathToStream (OutputStream& dest) const
  73454. {
  73455. dest.writeByte (useNonZeroWinding ? 'n' : 'z');
  73456. size_t i = 0;
  73457. while (i < numElements)
  73458. {
  73459. const float type = data.elements [i++];
  73460. if (type == moveMarker)
  73461. {
  73462. dest.writeByte ('m');
  73463. dest.writeFloat (data.elements [i++]);
  73464. dest.writeFloat (data.elements [i++]);
  73465. }
  73466. else if (type == lineMarker)
  73467. {
  73468. dest.writeByte ('l');
  73469. dest.writeFloat (data.elements [i++]);
  73470. dest.writeFloat (data.elements [i++]);
  73471. }
  73472. else if (type == quadMarker)
  73473. {
  73474. dest.writeByte ('q');
  73475. dest.writeFloat (data.elements [i++]);
  73476. dest.writeFloat (data.elements [i++]);
  73477. dest.writeFloat (data.elements [i++]);
  73478. dest.writeFloat (data.elements [i++]);
  73479. }
  73480. else if (type == cubicMarker)
  73481. {
  73482. dest.writeByte ('b');
  73483. dest.writeFloat (data.elements [i++]);
  73484. dest.writeFloat (data.elements [i++]);
  73485. dest.writeFloat (data.elements [i++]);
  73486. dest.writeFloat (data.elements [i++]);
  73487. dest.writeFloat (data.elements [i++]);
  73488. dest.writeFloat (data.elements [i++]);
  73489. }
  73490. else if (type == closeSubPathMarker)
  73491. {
  73492. dest.writeByte ('c');
  73493. }
  73494. }
  73495. dest.writeByte ('e'); // marks the end-of-path
  73496. }
  73497. const String Path::toString() const
  73498. {
  73499. MemoryOutputStream s (2048, 2048);
  73500. if (! useNonZeroWinding)
  73501. s << 'a';
  73502. size_t i = 0;
  73503. float lastMarker = 0.0f;
  73504. while (i < numElements)
  73505. {
  73506. const float marker = data.elements [i++];
  73507. char markerChar = 0;
  73508. int numCoords = 0;
  73509. if (marker == moveMarker)
  73510. {
  73511. markerChar = 'm';
  73512. numCoords = 2;
  73513. }
  73514. else if (marker == lineMarker)
  73515. {
  73516. markerChar = 'l';
  73517. numCoords = 2;
  73518. }
  73519. else if (marker == quadMarker)
  73520. {
  73521. markerChar = 'q';
  73522. numCoords = 4;
  73523. }
  73524. else if (marker == cubicMarker)
  73525. {
  73526. markerChar = 'c';
  73527. numCoords = 6;
  73528. }
  73529. else
  73530. {
  73531. jassert (marker == closeSubPathMarker);
  73532. markerChar = 'z';
  73533. }
  73534. if (marker != lastMarker)
  73535. {
  73536. if (s.getDataSize() != 0)
  73537. s << ' ';
  73538. s << markerChar;
  73539. lastMarker = marker;
  73540. }
  73541. while (--numCoords >= 0 && i < numElements)
  73542. {
  73543. String coord (data.elements [i++], 3);
  73544. while (coord.endsWithChar ('0') && coord != "0")
  73545. coord = coord.dropLastCharacters (1);
  73546. if (coord.endsWithChar ('.'))
  73547. coord = coord.dropLastCharacters (1);
  73548. if (s.getDataSize() != 0)
  73549. s << ' ';
  73550. s << coord;
  73551. }
  73552. }
  73553. return s.toUTF8();
  73554. }
  73555. void Path::restoreFromString (const String& stringVersion)
  73556. {
  73557. clear();
  73558. setUsingNonZeroWinding (true);
  73559. const juce_wchar* t = stringVersion;
  73560. juce_wchar marker = 'm';
  73561. int numValues = 2;
  73562. float values [6];
  73563. for (;;)
  73564. {
  73565. const String token (PathHelpers::nextToken (t));
  73566. const juce_wchar firstChar = token[0];
  73567. int startNum = 0;
  73568. if (firstChar == 0)
  73569. break;
  73570. if (firstChar == 'm' || firstChar == 'l')
  73571. {
  73572. marker = firstChar;
  73573. numValues = 2;
  73574. }
  73575. else if (firstChar == 'q')
  73576. {
  73577. marker = firstChar;
  73578. numValues = 4;
  73579. }
  73580. else if (firstChar == 'c')
  73581. {
  73582. marker = firstChar;
  73583. numValues = 6;
  73584. }
  73585. else if (firstChar == 'z')
  73586. {
  73587. marker = firstChar;
  73588. numValues = 0;
  73589. }
  73590. else if (firstChar == 'a')
  73591. {
  73592. setUsingNonZeroWinding (false);
  73593. continue;
  73594. }
  73595. else
  73596. {
  73597. ++startNum;
  73598. values [0] = token.getFloatValue();
  73599. }
  73600. for (int i = startNum; i < numValues; ++i)
  73601. values [i] = PathHelpers::nextToken (t).getFloatValue();
  73602. switch (marker)
  73603. {
  73604. case 'm':
  73605. startNewSubPath (values[0], values[1]);
  73606. break;
  73607. case 'l':
  73608. lineTo (values[0], values[1]);
  73609. break;
  73610. case 'q':
  73611. quadraticTo (values[0], values[1],
  73612. values[2], values[3]);
  73613. break;
  73614. case 'c':
  73615. cubicTo (values[0], values[1],
  73616. values[2], values[3],
  73617. values[4], values[5]);
  73618. break;
  73619. case 'z':
  73620. closeSubPath();
  73621. break;
  73622. default:
  73623. jassertfalse; // illegal string format?
  73624. break;
  73625. }
  73626. }
  73627. }
  73628. Path::Iterator::Iterator (const Path& path_)
  73629. : path (path_),
  73630. index (0)
  73631. {
  73632. }
  73633. Path::Iterator::~Iterator()
  73634. {
  73635. }
  73636. bool Path::Iterator::next()
  73637. {
  73638. const float* const elements = path.data.elements;
  73639. if (index < path.numElements)
  73640. {
  73641. const float type = elements [index++];
  73642. if (type == moveMarker)
  73643. {
  73644. elementType = startNewSubPath;
  73645. x1 = elements [index++];
  73646. y1 = elements [index++];
  73647. }
  73648. else if (type == lineMarker)
  73649. {
  73650. elementType = lineTo;
  73651. x1 = elements [index++];
  73652. y1 = elements [index++];
  73653. }
  73654. else if (type == quadMarker)
  73655. {
  73656. elementType = quadraticTo;
  73657. x1 = elements [index++];
  73658. y1 = elements [index++];
  73659. x2 = elements [index++];
  73660. y2 = elements [index++];
  73661. }
  73662. else if (type == cubicMarker)
  73663. {
  73664. elementType = cubicTo;
  73665. x1 = elements [index++];
  73666. y1 = elements [index++];
  73667. x2 = elements [index++];
  73668. y2 = elements [index++];
  73669. x3 = elements [index++];
  73670. y3 = elements [index++];
  73671. }
  73672. else if (type == closeSubPathMarker)
  73673. {
  73674. elementType = closePath;
  73675. }
  73676. return true;
  73677. }
  73678. return false;
  73679. }
  73680. END_JUCE_NAMESPACE
  73681. /*** End of inlined file: juce_Path.cpp ***/
  73682. /*** Start of inlined file: juce_PathIterator.cpp ***/
  73683. BEGIN_JUCE_NAMESPACE
  73684. #if JUCE_MSVC && JUCE_DEBUG
  73685. #pragma optimize ("t", on)
  73686. #endif
  73687. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  73688. const AffineTransform& transform_,
  73689. float tolerence_)
  73690. : x2 (0),
  73691. y2 (0),
  73692. closesSubPath (false),
  73693. subPathIndex (-1),
  73694. path (path_),
  73695. transform (transform_),
  73696. points (path_.data.elements),
  73697. tolerence (tolerence_ * tolerence_),
  73698. subPathCloseX (0),
  73699. subPathCloseY (0),
  73700. isIdentityTransform (transform_.isIdentity()),
  73701. stackBase (32),
  73702. index (0),
  73703. stackSize (32)
  73704. {
  73705. stackPos = stackBase;
  73706. }
  73707. PathFlatteningIterator::~PathFlatteningIterator()
  73708. {
  73709. }
  73710. bool PathFlatteningIterator::next()
  73711. {
  73712. x1 = x2;
  73713. y1 = y2;
  73714. float x3 = 0;
  73715. float y3 = 0;
  73716. float x4 = 0;
  73717. float y4 = 0;
  73718. float type;
  73719. for (;;)
  73720. {
  73721. if (stackPos == stackBase)
  73722. {
  73723. if (index >= path.numElements)
  73724. {
  73725. return false;
  73726. }
  73727. else
  73728. {
  73729. type = points [index++];
  73730. if (type != Path::closeSubPathMarker)
  73731. {
  73732. x2 = points [index++];
  73733. y2 = points [index++];
  73734. if (type == Path::quadMarker)
  73735. {
  73736. x3 = points [index++];
  73737. y3 = points [index++];
  73738. if (! isIdentityTransform)
  73739. transform.transformPoints (x2, y2, x3, y3);
  73740. }
  73741. else if (type == Path::cubicMarker)
  73742. {
  73743. x3 = points [index++];
  73744. y3 = points [index++];
  73745. x4 = points [index++];
  73746. y4 = points [index++];
  73747. if (! isIdentityTransform)
  73748. transform.transformPoints (x2, y2, x3, y3, x4, y4);
  73749. }
  73750. else
  73751. {
  73752. if (! isIdentityTransform)
  73753. transform.transformPoint (x2, y2);
  73754. }
  73755. }
  73756. }
  73757. }
  73758. else
  73759. {
  73760. type = *--stackPos;
  73761. if (type != Path::closeSubPathMarker)
  73762. {
  73763. x2 = *--stackPos;
  73764. y2 = *--stackPos;
  73765. if (type == Path::quadMarker)
  73766. {
  73767. x3 = *--stackPos;
  73768. y3 = *--stackPos;
  73769. }
  73770. else if (type == Path::cubicMarker)
  73771. {
  73772. x3 = *--stackPos;
  73773. y3 = *--stackPos;
  73774. x4 = *--stackPos;
  73775. y4 = *--stackPos;
  73776. }
  73777. }
  73778. }
  73779. if (type == Path::lineMarker)
  73780. {
  73781. ++subPathIndex;
  73782. closesSubPath = (stackPos == stackBase)
  73783. && (index < path.numElements)
  73784. && (points [index] == Path::closeSubPathMarker)
  73785. && x2 == subPathCloseX
  73786. && y2 == subPathCloseY;
  73787. return true;
  73788. }
  73789. else if (type == Path::quadMarker)
  73790. {
  73791. const size_t offset = (size_t) (stackPos - stackBase);
  73792. if (offset >= stackSize - 10)
  73793. {
  73794. stackSize <<= 1;
  73795. stackBase.realloc (stackSize);
  73796. stackPos = stackBase + offset;
  73797. }
  73798. const float dx1 = x1 - x2;
  73799. const float dy1 = y1 - y2;
  73800. const float dx2 = x2 - x3;
  73801. const float dy2 = y2 - y3;
  73802. const float m1x = (x1 + x2) * 0.5f;
  73803. const float m1y = (y1 + y2) * 0.5f;
  73804. const float m2x = (x2 + x3) * 0.5f;
  73805. const float m2y = (y2 + y3) * 0.5f;
  73806. const float m3x = (m1x + m2x) * 0.5f;
  73807. const float m3y = (m1y + m2y) * 0.5f;
  73808. if (dx1*dx1 + dy1*dy1 + dx2*dx2 + dy2*dy2 > tolerence)
  73809. {
  73810. *stackPos++ = y3;
  73811. *stackPos++ = x3;
  73812. *stackPos++ = m2y;
  73813. *stackPos++ = m2x;
  73814. *stackPos++ = Path::quadMarker;
  73815. *stackPos++ = m3y;
  73816. *stackPos++ = m3x;
  73817. *stackPos++ = m1y;
  73818. *stackPos++ = m1x;
  73819. *stackPos++ = Path::quadMarker;
  73820. }
  73821. else
  73822. {
  73823. *stackPos++ = y3;
  73824. *stackPos++ = x3;
  73825. *stackPos++ = Path::lineMarker;
  73826. *stackPos++ = m3y;
  73827. *stackPos++ = m3x;
  73828. *stackPos++ = Path::lineMarker;
  73829. }
  73830. jassert (stackPos < stackBase + stackSize);
  73831. }
  73832. else if (type == Path::cubicMarker)
  73833. {
  73834. const size_t offset = (size_t) (stackPos - stackBase);
  73835. if (offset >= stackSize - 16)
  73836. {
  73837. stackSize <<= 1;
  73838. stackBase.realloc (stackSize);
  73839. stackPos = stackBase + offset;
  73840. }
  73841. const float dx1 = x1 - x2;
  73842. const float dy1 = y1 - y2;
  73843. const float dx2 = x2 - x3;
  73844. const float dy2 = y2 - y3;
  73845. const float dx3 = x3 - x4;
  73846. const float dy3 = y3 - y4;
  73847. const float m1x = (x1 + x2) * 0.5f;
  73848. const float m1y = (y1 + y2) * 0.5f;
  73849. const float m2x = (x3 + x2) * 0.5f;
  73850. const float m2y = (y3 + y2) * 0.5f;
  73851. const float m3x = (x3 + x4) * 0.5f;
  73852. const float m3y = (y3 + y4) * 0.5f;
  73853. const float m4x = (m1x + m2x) * 0.5f;
  73854. const float m4y = (m1y + m2y) * 0.5f;
  73855. const float m5x = (m3x + m2x) * 0.5f;
  73856. const float m5y = (m3y + m2y) * 0.5f;
  73857. if (dx1*dx1 + dy1*dy1 + dx2*dx2
  73858. + dy2*dy2 + dx3*dx3 + dy3*dy3 > tolerence)
  73859. {
  73860. *stackPos++ = y4;
  73861. *stackPos++ = x4;
  73862. *stackPos++ = m3y;
  73863. *stackPos++ = m3x;
  73864. *stackPos++ = m5y;
  73865. *stackPos++ = m5x;
  73866. *stackPos++ = Path::cubicMarker;
  73867. *stackPos++ = (m4y + m5y) * 0.5f;
  73868. *stackPos++ = (m4x + m5x) * 0.5f;
  73869. *stackPos++ = m4y;
  73870. *stackPos++ = m4x;
  73871. *stackPos++ = m1y;
  73872. *stackPos++ = m1x;
  73873. *stackPos++ = Path::cubicMarker;
  73874. }
  73875. else
  73876. {
  73877. *stackPos++ = y4;
  73878. *stackPos++ = x4;
  73879. *stackPos++ = Path::lineMarker;
  73880. *stackPos++ = m5y;
  73881. *stackPos++ = m5x;
  73882. *stackPos++ = Path::lineMarker;
  73883. *stackPos++ = m4y;
  73884. *stackPos++ = m4x;
  73885. *stackPos++ = Path::lineMarker;
  73886. }
  73887. }
  73888. else if (type == Path::closeSubPathMarker)
  73889. {
  73890. if (x2 != subPathCloseX || y2 != subPathCloseY)
  73891. {
  73892. x1 = x2;
  73893. y1 = y2;
  73894. x2 = subPathCloseX;
  73895. y2 = subPathCloseY;
  73896. closesSubPath = true;
  73897. return true;
  73898. }
  73899. }
  73900. else
  73901. {
  73902. jassert (type == Path::moveMarker);
  73903. subPathIndex = -1;
  73904. subPathCloseX = x1 = x2;
  73905. subPathCloseY = y1 = y2;
  73906. }
  73907. }
  73908. }
  73909. #if JUCE_MSVC && JUCE_DEBUG
  73910. #pragma optimize ("", on) // resets optimisations to the project defaults
  73911. #endif
  73912. END_JUCE_NAMESPACE
  73913. /*** End of inlined file: juce_PathIterator.cpp ***/
  73914. /*** Start of inlined file: juce_PathStrokeType.cpp ***/
  73915. BEGIN_JUCE_NAMESPACE
  73916. PathStrokeType::PathStrokeType (const float strokeThickness,
  73917. const JointStyle jointStyle_,
  73918. const EndCapStyle endStyle_) throw()
  73919. : thickness (strokeThickness),
  73920. jointStyle (jointStyle_),
  73921. endStyle (endStyle_)
  73922. {
  73923. }
  73924. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  73925. : thickness (other.thickness),
  73926. jointStyle (other.jointStyle),
  73927. endStyle (other.endStyle)
  73928. {
  73929. }
  73930. PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  73931. {
  73932. thickness = other.thickness;
  73933. jointStyle = other.jointStyle;
  73934. endStyle = other.endStyle;
  73935. return *this;
  73936. }
  73937. PathStrokeType::~PathStrokeType() throw()
  73938. {
  73939. }
  73940. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  73941. {
  73942. return thickness == other.thickness
  73943. && jointStyle == other.jointStyle
  73944. && endStyle == other.endStyle;
  73945. }
  73946. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  73947. {
  73948. return ! operator== (other);
  73949. }
  73950. namespace PathStrokeHelpers
  73951. {
  73952. static bool lineIntersection (const float x1, const float y1,
  73953. const float x2, const float y2,
  73954. const float x3, const float y3,
  73955. const float x4, const float y4,
  73956. float& intersectionX,
  73957. float& intersectionY,
  73958. float& distanceBeyondLine1EndSquared) throw()
  73959. {
  73960. if (x2 != x3 || y2 != y3)
  73961. {
  73962. const float dx1 = x2 - x1;
  73963. const float dy1 = y2 - y1;
  73964. const float dx2 = x4 - x3;
  73965. const float dy2 = y4 - y3;
  73966. const float divisor = dx1 * dy2 - dx2 * dy1;
  73967. if (divisor == 0)
  73968. {
  73969. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  73970. {
  73971. if (dy1 == 0 && dy2 != 0)
  73972. {
  73973. const float along = (y1 - y3) / dy2;
  73974. intersectionX = x3 + along * dx2;
  73975. intersectionY = y1;
  73976. distanceBeyondLine1EndSquared = intersectionX - x2;
  73977. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  73978. if ((x2 > x1) == (intersectionX < x2))
  73979. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  73980. return along >= 0 && along <= 1.0f;
  73981. }
  73982. else if (dy2 == 0 && dy1 != 0)
  73983. {
  73984. const float along = (y3 - y1) / dy1;
  73985. intersectionX = x1 + along * dx1;
  73986. intersectionY = y3;
  73987. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  73988. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  73989. if (along < 1.0f)
  73990. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  73991. return along >= 0 && along <= 1.0f;
  73992. }
  73993. else if (dx1 == 0 && dx2 != 0)
  73994. {
  73995. const float along = (x1 - x3) / dx2;
  73996. intersectionX = x1;
  73997. intersectionY = y3 + along * dy2;
  73998. distanceBeyondLine1EndSquared = intersectionY - y2;
  73999. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  74000. if ((y2 > y1) == (intersectionY < y2))
  74001. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  74002. return along >= 0 && along <= 1.0f;
  74003. }
  74004. else if (dx2 == 0 && dx1 != 0)
  74005. {
  74006. const float along = (x3 - x1) / dx1;
  74007. intersectionX = x3;
  74008. intersectionY = y1 + along * dy1;
  74009. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  74010. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  74011. if (along < 1.0f)
  74012. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  74013. return along >= 0 && along <= 1.0f;
  74014. }
  74015. }
  74016. intersectionX = 0.5f * (x2 + x3);
  74017. intersectionY = 0.5f * (y2 + y3);
  74018. distanceBeyondLine1EndSquared = 0.0f;
  74019. return false;
  74020. }
  74021. else
  74022. {
  74023. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  74024. intersectionX = x1 + along1 * dx1;
  74025. intersectionY = y1 + along1 * dy1;
  74026. if (along1 >= 0 && along1 <= 1.0f)
  74027. {
  74028. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  74029. if (along2 >= 0 && along2 <= divisor)
  74030. {
  74031. distanceBeyondLine1EndSquared = 0.0f;
  74032. return true;
  74033. }
  74034. }
  74035. distanceBeyondLine1EndSquared = along1 - 1.0f;
  74036. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  74037. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  74038. if (along1 < 1.0f)
  74039. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  74040. return false;
  74041. }
  74042. }
  74043. intersectionX = x2;
  74044. intersectionY = y2;
  74045. distanceBeyondLine1EndSquared = 0.0f;
  74046. return true;
  74047. }
  74048. static void addEdgeAndJoint (Path& destPath,
  74049. const PathStrokeType::JointStyle style,
  74050. const float maxMiterExtensionSquared, const float width,
  74051. const float x1, const float y1,
  74052. const float x2, const float y2,
  74053. const float x3, const float y3,
  74054. const float x4, const float y4,
  74055. const float midX, const float midY)
  74056. {
  74057. if (style == PathStrokeType::beveled
  74058. || (x3 == x4 && y3 == y4)
  74059. || (x1 == x2 && y1 == y2))
  74060. {
  74061. destPath.lineTo (x2, y2);
  74062. destPath.lineTo (x3, y3);
  74063. }
  74064. else
  74065. {
  74066. float jx, jy, distanceBeyondLine1EndSquared;
  74067. // if they intersect, use this point..
  74068. if (lineIntersection (x1, y1, x2, y2,
  74069. x3, y3, x4, y4,
  74070. jx, jy, distanceBeyondLine1EndSquared))
  74071. {
  74072. destPath.lineTo (jx, jy);
  74073. }
  74074. else
  74075. {
  74076. if (style == PathStrokeType::mitered)
  74077. {
  74078. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  74079. && distanceBeyondLine1EndSquared > 0.0f)
  74080. {
  74081. destPath.lineTo (jx, jy);
  74082. }
  74083. else
  74084. {
  74085. // the end sticks out too far, so just use a blunt joint
  74086. destPath.lineTo (x2, y2);
  74087. destPath.lineTo (x3, y3);
  74088. }
  74089. }
  74090. else
  74091. {
  74092. // curved joints
  74093. float angle1 = std::atan2 (x2 - midX, y2 - midY);
  74094. float angle2 = std::atan2 (x3 - midX, y3 - midY);
  74095. const float angleIncrement = 0.1f;
  74096. destPath.lineTo (x2, y2);
  74097. if (std::abs (angle1 - angle2) > angleIncrement)
  74098. {
  74099. if (angle2 > angle1 + float_Pi
  74100. || (angle2 < angle1 && angle2 >= angle1 - float_Pi))
  74101. {
  74102. if (angle2 > angle1)
  74103. angle2 -= float_Pi * 2.0f;
  74104. jassert (angle1 <= angle2 + float_Pi);
  74105. angle1 -= angleIncrement;
  74106. while (angle1 > angle2)
  74107. {
  74108. destPath.lineTo (midX + width * std::sin (angle1),
  74109. midY + width * std::cos (angle1));
  74110. angle1 -= angleIncrement;
  74111. }
  74112. }
  74113. else
  74114. {
  74115. if (angle1 > angle2)
  74116. angle1 -= float_Pi * 2.0f;
  74117. jassert (angle1 >= angle2 - float_Pi);
  74118. angle1 += angleIncrement;
  74119. while (angle1 < angle2)
  74120. {
  74121. destPath.lineTo (midX + width * std::sin (angle1),
  74122. midY + width * std::cos (angle1));
  74123. angle1 += angleIncrement;
  74124. }
  74125. }
  74126. }
  74127. destPath.lineTo (x3, y3);
  74128. }
  74129. }
  74130. }
  74131. }
  74132. static void addLineEnd (Path& destPath,
  74133. const PathStrokeType::EndCapStyle style,
  74134. const float x1, const float y1,
  74135. const float x2, const float y2,
  74136. const float width)
  74137. {
  74138. if (style == PathStrokeType::butt)
  74139. {
  74140. destPath.lineTo (x2, y2);
  74141. }
  74142. else
  74143. {
  74144. float offx1, offy1, offx2, offy2;
  74145. float dx = x2 - x1;
  74146. float dy = y2 - y1;
  74147. const float len = juce_hypotf (dx, dy);
  74148. if (len == 0)
  74149. {
  74150. offx1 = offx2 = x1;
  74151. offy1 = offy2 = y1;
  74152. }
  74153. else
  74154. {
  74155. const float offset = width / len;
  74156. dx *= offset;
  74157. dy *= offset;
  74158. offx1 = x1 + dy;
  74159. offy1 = y1 - dx;
  74160. offx2 = x2 + dy;
  74161. offy2 = y2 - dx;
  74162. }
  74163. if (style == PathStrokeType::square)
  74164. {
  74165. // sqaure ends
  74166. destPath.lineTo (offx1, offy1);
  74167. destPath.lineTo (offx2, offy2);
  74168. destPath.lineTo (x2, y2);
  74169. }
  74170. else
  74171. {
  74172. // rounded ends
  74173. const float midx = (offx1 + offx2) * 0.5f;
  74174. const float midy = (offy1 + offy2) * 0.5f;
  74175. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  74176. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  74177. midx, midy);
  74178. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  74179. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  74180. x2, y2);
  74181. }
  74182. }
  74183. }
  74184. struct Arrowhead
  74185. {
  74186. float startWidth, startLength;
  74187. float endWidth, endLength;
  74188. };
  74189. static void addArrowhead (Path& destPath,
  74190. const float x1, const float y1,
  74191. const float x2, const float y2,
  74192. const float tipX, const float tipY,
  74193. const float width,
  74194. const float arrowheadWidth)
  74195. {
  74196. Line<float> line (x1, y1, x2, y2);
  74197. destPath.lineTo (line.getPointAlongLine (-(arrowheadWidth / 2.0f - width), 0));
  74198. destPath.lineTo (tipX, tipY);
  74199. destPath.lineTo (line.getPointAlongLine (arrowheadWidth - (arrowheadWidth / 2.0f - width), 0));
  74200. destPath.lineTo (x2, y2);
  74201. }
  74202. struct LineSection
  74203. {
  74204. float x1, y1, x2, y2; // original line
  74205. float lx1, ly1, lx2, ly2; // the left-hand stroke
  74206. float rx1, ry1, rx2, ry2; // the right-hand stroke
  74207. };
  74208. static void shortenSubPath (Array<LineSection>& subPath, float amountAtStart, float amountAtEnd)
  74209. {
  74210. while (amountAtEnd > 0 && subPath.size() > 0)
  74211. {
  74212. LineSection& l = subPath.getReference (subPath.size() - 1);
  74213. float dx = l.rx2 - l.rx1;
  74214. float dy = l.ry2 - l.ry1;
  74215. const float len = juce_hypotf (dx, dy);
  74216. if (len <= amountAtEnd && subPath.size() > 1)
  74217. {
  74218. LineSection& prev = subPath.getReference (subPath.size() - 2);
  74219. prev.x2 = l.x2;
  74220. prev.y2 = l.y2;
  74221. subPath.removeLast();
  74222. amountAtEnd -= len;
  74223. }
  74224. else
  74225. {
  74226. const float prop = jmin (0.9999f, amountAtEnd / len);
  74227. dx *= prop;
  74228. dy *= prop;
  74229. l.rx1 += dx;
  74230. l.ry1 += dy;
  74231. l.lx2 += dx;
  74232. l.ly2 += dy;
  74233. break;
  74234. }
  74235. }
  74236. while (amountAtStart > 0 && subPath.size() > 0)
  74237. {
  74238. LineSection& l = subPath.getReference (0);
  74239. float dx = l.rx2 - l.rx1;
  74240. float dy = l.ry2 - l.ry1;
  74241. const float len = juce_hypotf (dx, dy);
  74242. if (len <= amountAtStart && subPath.size() > 1)
  74243. {
  74244. LineSection& next = subPath.getReference (1);
  74245. next.x1 = l.x1;
  74246. next.y1 = l.y1;
  74247. subPath.remove (0);
  74248. amountAtStart -= len;
  74249. }
  74250. else
  74251. {
  74252. const float prop = jmin (0.9999f, amountAtStart / len);
  74253. dx *= prop;
  74254. dy *= prop;
  74255. l.rx2 -= dx;
  74256. l.ry2 -= dy;
  74257. l.lx1 -= dx;
  74258. l.ly1 -= dy;
  74259. break;
  74260. }
  74261. }
  74262. }
  74263. static void addSubPath (Path& destPath, Array<LineSection>& subPath,
  74264. const bool isClosed, const float width, const float maxMiterExtensionSquared,
  74265. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle,
  74266. const Arrowhead* const arrowhead)
  74267. {
  74268. jassert (subPath.size() > 0);
  74269. if (arrowhead != 0)
  74270. shortenSubPath (subPath, arrowhead->startLength, arrowhead->endLength);
  74271. const LineSection& firstLine = subPath.getReference (0);
  74272. float lastX1 = firstLine.lx1;
  74273. float lastY1 = firstLine.ly1;
  74274. float lastX2 = firstLine.lx2;
  74275. float lastY2 = firstLine.ly2;
  74276. if (isClosed)
  74277. {
  74278. destPath.startNewSubPath (lastX1, lastY1);
  74279. }
  74280. else
  74281. {
  74282. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  74283. if (arrowhead != 0)
  74284. addArrowhead (destPath, firstLine.rx2, firstLine.ry2, lastX1, lastY1, firstLine.x1, firstLine.y1,
  74285. width, arrowhead->startWidth);
  74286. else
  74287. addLineEnd (destPath, endStyle, firstLine.rx2, firstLine.ry2, lastX1, lastY1, width);
  74288. }
  74289. int i;
  74290. for (i = 1; i < subPath.size(); ++i)
  74291. {
  74292. const LineSection& l = subPath.getReference (i);
  74293. addEdgeAndJoint (destPath, jointStyle,
  74294. maxMiterExtensionSquared, width,
  74295. lastX1, lastY1, lastX2, lastY2,
  74296. l.lx1, l.ly1, l.lx2, l.ly2,
  74297. l.x1, l.y1);
  74298. lastX1 = l.lx1;
  74299. lastY1 = l.ly1;
  74300. lastX2 = l.lx2;
  74301. lastY2 = l.ly2;
  74302. }
  74303. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  74304. if (isClosed)
  74305. {
  74306. const LineSection& l = subPath.getReference (0);
  74307. addEdgeAndJoint (destPath, jointStyle,
  74308. maxMiterExtensionSquared, width,
  74309. lastX1, lastY1, lastX2, lastY2,
  74310. l.lx1, l.ly1, l.lx2, l.ly2,
  74311. l.x1, l.y1);
  74312. destPath.closeSubPath();
  74313. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  74314. }
  74315. else
  74316. {
  74317. destPath.lineTo (lastX2, lastY2);
  74318. if (arrowhead != 0)
  74319. addArrowhead (destPath, lastX2, lastY2, lastLine.rx1, lastLine.ry1, lastLine.x2, lastLine.y2,
  74320. width, arrowhead->endWidth);
  74321. else
  74322. addLineEnd (destPath, endStyle, lastX2, lastY2, lastLine.rx1, lastLine.ry1, width);
  74323. }
  74324. lastX1 = lastLine.rx1;
  74325. lastY1 = lastLine.ry1;
  74326. lastX2 = lastLine.rx2;
  74327. lastY2 = lastLine.ry2;
  74328. for (i = subPath.size() - 1; --i >= 0;)
  74329. {
  74330. const LineSection& l = subPath.getReference (i);
  74331. addEdgeAndJoint (destPath, jointStyle,
  74332. maxMiterExtensionSquared, width,
  74333. lastX1, lastY1, lastX2, lastY2,
  74334. l.rx1, l.ry1, l.rx2, l.ry2,
  74335. l.x2, l.y2);
  74336. lastX1 = l.rx1;
  74337. lastY1 = l.ry1;
  74338. lastX2 = l.rx2;
  74339. lastY2 = l.ry2;
  74340. }
  74341. if (isClosed)
  74342. {
  74343. addEdgeAndJoint (destPath, jointStyle,
  74344. maxMiterExtensionSquared, width,
  74345. lastX1, lastY1, lastX2, lastY2,
  74346. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  74347. lastLine.x2, lastLine.y2);
  74348. }
  74349. else
  74350. {
  74351. // do the last line
  74352. destPath.lineTo (lastX2, lastY2);
  74353. }
  74354. destPath.closeSubPath();
  74355. }
  74356. static void createStroke (const float thickness, const PathStrokeType::JointStyle jointStyle,
  74357. const PathStrokeType::EndCapStyle endStyle,
  74358. Path& destPath, const Path& source,
  74359. const AffineTransform& transform,
  74360. const float extraAccuracy, const Arrowhead* const arrowhead)
  74361. {
  74362. if (thickness <= 0)
  74363. {
  74364. destPath.clear();
  74365. return;
  74366. }
  74367. const Path* sourcePath = &source;
  74368. Path temp;
  74369. if (sourcePath == &destPath)
  74370. {
  74371. destPath.swapWithPath (temp);
  74372. sourcePath = &temp;
  74373. }
  74374. else
  74375. {
  74376. destPath.clear();
  74377. }
  74378. destPath.setUsingNonZeroWinding (true);
  74379. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  74380. const float width = 0.5f * thickness;
  74381. // Iterate the path, creating a list of the
  74382. // left/right-hand lines along either side of it...
  74383. PathFlatteningIterator it (*sourcePath, transform, 9.0f / extraAccuracy);
  74384. Array <LineSection> subPath;
  74385. subPath.ensureStorageAllocated (512);
  74386. LineSection l;
  74387. l.x1 = 0;
  74388. l.y1 = 0;
  74389. const float minSegmentLength = 2.0f / (extraAccuracy * extraAccuracy);
  74390. while (it.next())
  74391. {
  74392. if (it.subPathIndex == 0)
  74393. {
  74394. if (subPath.size() > 0)
  74395. {
  74396. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  74397. subPath.clearQuick();
  74398. }
  74399. l.x1 = it.x1;
  74400. l.y1 = it.y1;
  74401. }
  74402. l.x2 = it.x2;
  74403. l.y2 = it.y2;
  74404. float dx = l.x2 - l.x1;
  74405. float dy = l.y2 - l.y1;
  74406. const float hypotSquared = dx*dx + dy*dy;
  74407. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  74408. {
  74409. const float len = std::sqrt (hypotSquared);
  74410. if (len == 0)
  74411. {
  74412. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  74413. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  74414. }
  74415. else
  74416. {
  74417. const float offset = width / len;
  74418. dx *= offset;
  74419. dy *= offset;
  74420. l.rx2 = l.x1 - dy;
  74421. l.ry2 = l.y1 + dx;
  74422. l.lx1 = l.x1 + dy;
  74423. l.ly1 = l.y1 - dx;
  74424. l.lx2 = l.x2 + dy;
  74425. l.ly2 = l.y2 - dx;
  74426. l.rx1 = l.x2 - dy;
  74427. l.ry1 = l.y2 + dx;
  74428. }
  74429. subPath.add (l);
  74430. if (it.closesSubPath)
  74431. {
  74432. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  74433. subPath.clearQuick();
  74434. }
  74435. else
  74436. {
  74437. l.x1 = it.x2;
  74438. l.y1 = it.y2;
  74439. }
  74440. }
  74441. }
  74442. if (subPath.size() > 0)
  74443. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  74444. }
  74445. }
  74446. void PathStrokeType::createStrokedPath (Path& destPath, const Path& sourcePath,
  74447. const AffineTransform& transform, const float extraAccuracy) const
  74448. {
  74449. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle, destPath, sourcePath,
  74450. transform, extraAccuracy, 0);
  74451. }
  74452. void PathStrokeType::createDashedStroke (Path& destPath,
  74453. const Path& sourcePath,
  74454. const float* dashLengths,
  74455. int numDashLengths,
  74456. const AffineTransform& transform,
  74457. const float extraAccuracy) const
  74458. {
  74459. if (thickness <= 0)
  74460. return;
  74461. // this should really be an even number..
  74462. jassert ((numDashLengths & 1) == 0);
  74463. Path newDestPath;
  74464. PathFlatteningIterator it (sourcePath, transform, 9.0f / extraAccuracy);
  74465. bool first = true;
  74466. int dashNum = 0;
  74467. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  74468. float dx = 0.0f, dy = 0.0f;
  74469. for (;;)
  74470. {
  74471. const bool isSolid = ((dashNum & 1) == 0);
  74472. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  74473. jassert (dashLen > 0); // must be a positive increment!
  74474. if (dashLen <= 0)
  74475. break;
  74476. pos += dashLen;
  74477. while (pos > lineEndPos)
  74478. {
  74479. if (! it.next())
  74480. {
  74481. if (isSolid && ! first)
  74482. newDestPath.lineTo (it.x2, it.y2);
  74483. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  74484. return;
  74485. }
  74486. if (isSolid && ! first)
  74487. newDestPath.lineTo (it.x1, it.y1);
  74488. else
  74489. newDestPath.startNewSubPath (it.x1, it.y1);
  74490. dx = it.x2 - it.x1;
  74491. dy = it.y2 - it.y1;
  74492. lineLen = juce_hypotf (dx, dy);
  74493. lineEndPos += lineLen;
  74494. first = it.closesSubPath;
  74495. }
  74496. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  74497. if (isSolid)
  74498. newDestPath.lineTo (it.x1 + dx * alpha,
  74499. it.y1 + dy * alpha);
  74500. else
  74501. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  74502. it.y1 + dy * alpha);
  74503. }
  74504. }
  74505. void PathStrokeType::createStrokeWithArrowheads (Path& destPath,
  74506. const Path& sourcePath,
  74507. const float arrowheadStartWidth, const float arrowheadStartLength,
  74508. const float arrowheadEndWidth, const float arrowheadEndLength,
  74509. const AffineTransform& transform,
  74510. const float extraAccuracy) const
  74511. {
  74512. PathStrokeHelpers::Arrowhead head;
  74513. head.startWidth = arrowheadStartWidth;
  74514. head.startLength = arrowheadStartLength;
  74515. head.endWidth = arrowheadEndWidth;
  74516. head.endLength = arrowheadEndLength;
  74517. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle,
  74518. destPath, sourcePath, transform, extraAccuracy, &head);
  74519. }
  74520. END_JUCE_NAMESPACE
  74521. /*** End of inlined file: juce_PathStrokeType.cpp ***/
  74522. /*** Start of inlined file: juce_PositionedRectangle.cpp ***/
  74523. BEGIN_JUCE_NAMESPACE
  74524. PositionedRectangle::PositionedRectangle() throw()
  74525. : x (0.0),
  74526. y (0.0),
  74527. w (0.0),
  74528. h (0.0),
  74529. xMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  74530. yMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  74531. wMode (absoluteSize),
  74532. hMode (absoluteSize)
  74533. {
  74534. }
  74535. PositionedRectangle::PositionedRectangle (const PositionedRectangle& other) throw()
  74536. : x (other.x),
  74537. y (other.y),
  74538. w (other.w),
  74539. h (other.h),
  74540. xMode (other.xMode),
  74541. yMode (other.yMode),
  74542. wMode (other.wMode),
  74543. hMode (other.hMode)
  74544. {
  74545. }
  74546. PositionedRectangle& PositionedRectangle::operator= (const PositionedRectangle& other) throw()
  74547. {
  74548. x = other.x;
  74549. y = other.y;
  74550. w = other.w;
  74551. h = other.h;
  74552. xMode = other.xMode;
  74553. yMode = other.yMode;
  74554. wMode = other.wMode;
  74555. hMode = other.hMode;
  74556. return *this;
  74557. }
  74558. PositionedRectangle::~PositionedRectangle() throw()
  74559. {
  74560. }
  74561. bool PositionedRectangle::operator== (const PositionedRectangle& other) const throw()
  74562. {
  74563. return x == other.x
  74564. && y == other.y
  74565. && w == other.w
  74566. && h == other.h
  74567. && xMode == other.xMode
  74568. && yMode == other.yMode
  74569. && wMode == other.wMode
  74570. && hMode == other.hMode;
  74571. }
  74572. bool PositionedRectangle::operator!= (const PositionedRectangle& other) const throw()
  74573. {
  74574. return ! operator== (other);
  74575. }
  74576. PositionedRectangle::PositionedRectangle (const String& stringVersion) throw()
  74577. {
  74578. StringArray tokens;
  74579. tokens.addTokens (stringVersion, false);
  74580. decodePosString (tokens [0], xMode, x);
  74581. decodePosString (tokens [1], yMode, y);
  74582. decodeSizeString (tokens [2], wMode, w);
  74583. decodeSizeString (tokens [3], hMode, h);
  74584. }
  74585. const String PositionedRectangle::toString() const throw()
  74586. {
  74587. String s;
  74588. s.preallocateStorage (12);
  74589. addPosDescription (s, xMode, x);
  74590. s << ' ';
  74591. addPosDescription (s, yMode, y);
  74592. s << ' ';
  74593. addSizeDescription (s, wMode, w);
  74594. s << ' ';
  74595. addSizeDescription (s, hMode, h);
  74596. return s;
  74597. }
  74598. const Rectangle<int> PositionedRectangle::getRectangle (const Rectangle<int>& target) const throw()
  74599. {
  74600. jassert (! target.isEmpty());
  74601. double x_, y_, w_, h_;
  74602. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  74603. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  74604. return Rectangle<int> (roundToInt (x_), roundToInt (y_),
  74605. roundToInt (w_), roundToInt (h_));
  74606. }
  74607. void PositionedRectangle::getRectangleDouble (const Rectangle<int>& target,
  74608. double& x_, double& y_,
  74609. double& w_, double& h_) const throw()
  74610. {
  74611. jassert (! target.isEmpty());
  74612. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  74613. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  74614. }
  74615. void PositionedRectangle::applyToComponent (Component& comp) const throw()
  74616. {
  74617. comp.setBounds (getRectangle (Rectangle<int> (0, 0, comp.getParentWidth(), comp.getParentHeight())));
  74618. }
  74619. void PositionedRectangle::updateFrom (const Rectangle<int>& rectangle,
  74620. const Rectangle<int>& target) throw()
  74621. {
  74622. updatePosAndSize (x, w, rectangle.getX(), rectangle.getWidth(), xMode, wMode, target.getX(), target.getWidth());
  74623. updatePosAndSize (y, h, rectangle.getY(), rectangle.getHeight(), yMode, hMode, target.getY(), target.getHeight());
  74624. }
  74625. void PositionedRectangle::updateFromDouble (const double newX, const double newY,
  74626. const double newW, const double newH,
  74627. const Rectangle<int>& target) throw()
  74628. {
  74629. updatePosAndSize (x, w, newX, newW, xMode, wMode, target.getX(), target.getWidth());
  74630. updatePosAndSize (y, h, newY, newH, yMode, hMode, target.getY(), target.getHeight());
  74631. }
  74632. void PositionedRectangle::updateFromComponent (const Component& comp) throw()
  74633. {
  74634. if (comp.getParentComponent() == 0 && ! comp.isOnDesktop())
  74635. updateFrom (comp.getBounds(), Rectangle<int>());
  74636. else
  74637. updateFrom (comp.getBounds(), Rectangle<int> (0, 0, comp.getParentWidth(), comp.getParentHeight()));
  74638. }
  74639. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointX() const throw()
  74640. {
  74641. return (AnchorPoint) (xMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  74642. }
  74643. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeX() const throw()
  74644. {
  74645. return (PositionMode) (xMode & (absoluteFromParentTopLeft
  74646. | absoluteFromParentBottomRight
  74647. | absoluteFromParentCentre
  74648. | proportionOfParentSize));
  74649. }
  74650. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointY() const throw()
  74651. {
  74652. return (AnchorPoint) (yMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  74653. }
  74654. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeY() const throw()
  74655. {
  74656. return (PositionMode) (yMode & (absoluteFromParentTopLeft
  74657. | absoluteFromParentBottomRight
  74658. | absoluteFromParentCentre
  74659. | proportionOfParentSize));
  74660. }
  74661. PositionedRectangle::SizeMode PositionedRectangle::getWidthMode() const throw()
  74662. {
  74663. return (SizeMode) wMode;
  74664. }
  74665. PositionedRectangle::SizeMode PositionedRectangle::getHeightMode() const throw()
  74666. {
  74667. return (SizeMode) hMode;
  74668. }
  74669. void PositionedRectangle::setModes (const AnchorPoint xAnchor,
  74670. const PositionMode xMode_,
  74671. const AnchorPoint yAnchor,
  74672. const PositionMode yMode_,
  74673. const SizeMode widthMode,
  74674. const SizeMode heightMode,
  74675. const Rectangle<int>& target) throw()
  74676. {
  74677. if (xMode != (xAnchor | xMode_) || wMode != widthMode)
  74678. {
  74679. double tx, tw;
  74680. applyPosAndSize (tx, tw, x, w, xMode, wMode, target.getX(), target.getWidth());
  74681. xMode = (uint8) (xAnchor | xMode_);
  74682. wMode = (uint8) widthMode;
  74683. updatePosAndSize (x, w, tx, tw, xMode, wMode, target.getX(), target.getWidth());
  74684. }
  74685. if (yMode != (yAnchor | yMode_) || hMode != heightMode)
  74686. {
  74687. double ty, th;
  74688. applyPosAndSize (ty, th, y, h, yMode, hMode, target.getY(), target.getHeight());
  74689. yMode = (uint8) (yAnchor | yMode_);
  74690. hMode = (uint8) heightMode;
  74691. updatePosAndSize (y, h, ty, th, yMode, hMode, target.getY(), target.getHeight());
  74692. }
  74693. }
  74694. bool PositionedRectangle::isPositionAbsolute() const throw()
  74695. {
  74696. return xMode == absoluteFromParentTopLeft
  74697. && yMode == absoluteFromParentTopLeft
  74698. && wMode == absoluteSize
  74699. && hMode == absoluteSize;
  74700. }
  74701. void PositionedRectangle::addPosDescription (String& s, const uint8 mode, const double value) const throw()
  74702. {
  74703. if ((mode & proportionOfParentSize) != 0)
  74704. {
  74705. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  74706. }
  74707. else
  74708. {
  74709. s << (roundToInt (value * 100.0) / 100.0);
  74710. if ((mode & absoluteFromParentBottomRight) != 0)
  74711. s << 'R';
  74712. else if ((mode & absoluteFromParentCentre) != 0)
  74713. s << 'C';
  74714. }
  74715. if ((mode & anchorAtRightOrBottom) != 0)
  74716. s << 'r';
  74717. else if ((mode & anchorAtCentre) != 0)
  74718. s << 'c';
  74719. }
  74720. void PositionedRectangle::addSizeDescription (String& s, const uint8 mode, const double value) const throw()
  74721. {
  74722. if (mode == proportionalSize)
  74723. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  74724. else if (mode == parentSizeMinusAbsolute)
  74725. s << (roundToInt (value * 100.0) / 100.0) << 'M';
  74726. else
  74727. s << (roundToInt (value * 100.0) / 100.0);
  74728. }
  74729. void PositionedRectangle::decodePosString (const String& s, uint8& mode, double& value) throw()
  74730. {
  74731. if (s.containsChar ('r'))
  74732. mode = anchorAtRightOrBottom;
  74733. else if (s.containsChar ('c'))
  74734. mode = anchorAtCentre;
  74735. else
  74736. mode = anchorAtLeftOrTop;
  74737. if (s.containsChar ('%'))
  74738. {
  74739. mode |= proportionOfParentSize;
  74740. value = s.removeCharacters ("%rcRC").getDoubleValue() / 100.0;
  74741. }
  74742. else
  74743. {
  74744. if (s.containsChar ('R'))
  74745. mode |= absoluteFromParentBottomRight;
  74746. else if (s.containsChar ('C'))
  74747. mode |= absoluteFromParentCentre;
  74748. else
  74749. mode |= absoluteFromParentTopLeft;
  74750. value = s.removeCharacters ("rcRC").getDoubleValue();
  74751. }
  74752. }
  74753. void PositionedRectangle::decodeSizeString (const String& s, uint8& mode, double& value) throw()
  74754. {
  74755. if (s.containsChar ('%'))
  74756. {
  74757. mode = proportionalSize;
  74758. value = s.upToFirstOccurrenceOf ("%", false, false).getDoubleValue() / 100.0;
  74759. }
  74760. else if (s.containsChar ('M'))
  74761. {
  74762. mode = parentSizeMinusAbsolute;
  74763. value = s.getDoubleValue();
  74764. }
  74765. else
  74766. {
  74767. mode = absoluteSize;
  74768. value = s.getDoubleValue();
  74769. }
  74770. }
  74771. void PositionedRectangle::applyPosAndSize (double& xOut, double& wOut,
  74772. const double x_, const double w_,
  74773. const uint8 xMode_, const uint8 wMode_,
  74774. const int parentPos,
  74775. const int parentSize) const throw()
  74776. {
  74777. if (wMode_ == proportionalSize)
  74778. wOut = roundToInt (w_ * parentSize);
  74779. else if (wMode_ == parentSizeMinusAbsolute)
  74780. wOut = jmax (0, parentSize - roundToInt (w_));
  74781. else
  74782. wOut = roundToInt (w_);
  74783. if ((xMode_ & proportionOfParentSize) != 0)
  74784. xOut = parentPos + x_ * parentSize;
  74785. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  74786. xOut = (parentPos + parentSize) - x_;
  74787. else if ((xMode_ & absoluteFromParentCentre) != 0)
  74788. xOut = x_ + (parentPos + parentSize / 2);
  74789. else
  74790. xOut = x_ + parentPos;
  74791. if ((xMode_ & anchorAtRightOrBottom) != 0)
  74792. xOut -= wOut;
  74793. else if ((xMode_ & anchorAtCentre) != 0)
  74794. xOut -= wOut / 2;
  74795. }
  74796. void PositionedRectangle::updatePosAndSize (double& xOut, double& wOut,
  74797. double x_, const double w_,
  74798. const uint8 xMode_, const uint8 wMode_,
  74799. const int parentPos,
  74800. const int parentSize) const throw()
  74801. {
  74802. if (wMode_ == proportionalSize)
  74803. {
  74804. if (parentSize > 0)
  74805. wOut = w_ / parentSize;
  74806. }
  74807. else if (wMode_ == parentSizeMinusAbsolute)
  74808. wOut = parentSize - w_;
  74809. else
  74810. wOut = w_;
  74811. if ((xMode_ & anchorAtRightOrBottom) != 0)
  74812. x_ += w_;
  74813. else if ((xMode_ & anchorAtCentre) != 0)
  74814. x_ += w_ / 2;
  74815. if ((xMode_ & proportionOfParentSize) != 0)
  74816. {
  74817. if (parentSize > 0)
  74818. xOut = (x_ - parentPos) / parentSize;
  74819. }
  74820. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  74821. xOut = (parentPos + parentSize) - x_;
  74822. else if ((xMode_ & absoluteFromParentCentre) != 0)
  74823. xOut = x_ - (parentPos + parentSize / 2);
  74824. else
  74825. xOut = x_ - parentPos;
  74826. }
  74827. END_JUCE_NAMESPACE
  74828. /*** End of inlined file: juce_PositionedRectangle.cpp ***/
  74829. /*** Start of inlined file: juce_RectangleList.cpp ***/
  74830. BEGIN_JUCE_NAMESPACE
  74831. RectangleList::RectangleList() throw()
  74832. {
  74833. }
  74834. RectangleList::RectangleList (const Rectangle<int>& rect)
  74835. {
  74836. if (! rect.isEmpty())
  74837. rects.add (rect);
  74838. }
  74839. RectangleList::RectangleList (const RectangleList& other)
  74840. : rects (other.rects)
  74841. {
  74842. }
  74843. RectangleList& RectangleList::operator= (const RectangleList& other)
  74844. {
  74845. rects = other.rects;
  74846. return *this;
  74847. }
  74848. RectangleList::~RectangleList()
  74849. {
  74850. }
  74851. void RectangleList::clear()
  74852. {
  74853. rects.clearQuick();
  74854. }
  74855. const Rectangle<int> RectangleList::getRectangle (const int index) const throw()
  74856. {
  74857. if (((unsigned int) index) < (unsigned int) rects.size())
  74858. return rects.getReference (index);
  74859. return Rectangle<int>();
  74860. }
  74861. bool RectangleList::isEmpty() const throw()
  74862. {
  74863. return rects.size() == 0;
  74864. }
  74865. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  74866. : current (0),
  74867. owner (list),
  74868. index (list.rects.size())
  74869. {
  74870. }
  74871. RectangleList::Iterator::~Iterator()
  74872. {
  74873. }
  74874. bool RectangleList::Iterator::next() throw()
  74875. {
  74876. if (--index >= 0)
  74877. {
  74878. current = & (owner.rects.getReference (index));
  74879. return true;
  74880. }
  74881. return false;
  74882. }
  74883. void RectangleList::add (const Rectangle<int>& rect)
  74884. {
  74885. if (! rect.isEmpty())
  74886. {
  74887. if (rects.size() == 0)
  74888. {
  74889. rects.add (rect);
  74890. }
  74891. else
  74892. {
  74893. bool anyOverlaps = false;
  74894. int i;
  74895. for (i = rects.size(); --i >= 0;)
  74896. {
  74897. Rectangle<int>& ourRect = rects.getReference (i);
  74898. if (rect.intersects (ourRect))
  74899. {
  74900. if (rect.contains (ourRect))
  74901. rects.remove (i);
  74902. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  74903. anyOverlaps = true;
  74904. }
  74905. }
  74906. if (anyOverlaps && rects.size() > 0)
  74907. {
  74908. RectangleList r (rect);
  74909. for (i = rects.size(); --i >= 0;)
  74910. {
  74911. const Rectangle<int>& ourRect = rects.getReference (i);
  74912. if (rect.intersects (ourRect))
  74913. {
  74914. r.subtract (ourRect);
  74915. if (r.rects.size() == 0)
  74916. return;
  74917. }
  74918. }
  74919. for (i = r.getNumRectangles(); --i >= 0;)
  74920. rects.add (r.rects.getReference (i));
  74921. }
  74922. else
  74923. {
  74924. rects.add (rect);
  74925. }
  74926. }
  74927. }
  74928. }
  74929. void RectangleList::addWithoutMerging (const Rectangle<int>& rect)
  74930. {
  74931. if (! rect.isEmpty())
  74932. rects.add (rect);
  74933. }
  74934. void RectangleList::add (const int x, const int y, const int w, const int h)
  74935. {
  74936. if (rects.size() == 0)
  74937. {
  74938. if (w > 0 && h > 0)
  74939. rects.add (Rectangle<int> (x, y, w, h));
  74940. }
  74941. else
  74942. {
  74943. add (Rectangle<int> (x, y, w, h));
  74944. }
  74945. }
  74946. void RectangleList::add (const RectangleList& other)
  74947. {
  74948. for (int i = 0; i < other.rects.size(); ++i)
  74949. add (other.rects.getReference (i));
  74950. }
  74951. void RectangleList::subtract (const Rectangle<int>& rect)
  74952. {
  74953. const int originalNumRects = rects.size();
  74954. if (originalNumRects > 0)
  74955. {
  74956. const int x1 = rect.x;
  74957. const int y1 = rect.y;
  74958. const int x2 = x1 + rect.w;
  74959. const int y2 = y1 + rect.h;
  74960. for (int i = getNumRectangles(); --i >= 0;)
  74961. {
  74962. Rectangle<int>& r = rects.getReference (i);
  74963. const int rx1 = r.x;
  74964. const int ry1 = r.y;
  74965. const int rx2 = rx1 + r.w;
  74966. const int ry2 = ry1 + r.h;
  74967. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  74968. {
  74969. if (x1 > rx1 && x1 < rx2)
  74970. {
  74971. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  74972. {
  74973. r.w = x1 - rx1;
  74974. }
  74975. else
  74976. {
  74977. r.x = x1;
  74978. r.w = rx2 - x1;
  74979. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x1 - rx1, ry2 - ry1));
  74980. i += 2;
  74981. }
  74982. }
  74983. else if (x2 > rx1 && x2 < rx2)
  74984. {
  74985. r.x = x2;
  74986. r.w = rx2 - x2;
  74987. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  74988. {
  74989. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x2 - rx1, ry2 - ry1));
  74990. i += 2;
  74991. }
  74992. }
  74993. else if (y1 > ry1 && y1 < ry2)
  74994. {
  74995. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  74996. {
  74997. r.h = y1 - ry1;
  74998. }
  74999. else
  75000. {
  75001. r.y = y1;
  75002. r.h = ry2 - y1;
  75003. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y1 - ry1));
  75004. i += 2;
  75005. }
  75006. }
  75007. else if (y2 > ry1 && y2 < ry2)
  75008. {
  75009. r.y = y2;
  75010. r.h = ry2 - y2;
  75011. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  75012. {
  75013. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y2 - ry1));
  75014. i += 2;
  75015. }
  75016. }
  75017. else
  75018. {
  75019. rects.remove (i);
  75020. }
  75021. }
  75022. }
  75023. }
  75024. }
  75025. bool RectangleList::subtract (const RectangleList& otherList)
  75026. {
  75027. for (int i = otherList.rects.size(); --i >= 0 && rects.size() > 0;)
  75028. subtract (otherList.rects.getReference (i));
  75029. return rects.size() > 0;
  75030. }
  75031. bool RectangleList::clipTo (const Rectangle<int>& rect)
  75032. {
  75033. bool notEmpty = false;
  75034. if (rect.isEmpty())
  75035. {
  75036. clear();
  75037. }
  75038. else
  75039. {
  75040. for (int i = rects.size(); --i >= 0;)
  75041. {
  75042. Rectangle<int>& r = rects.getReference (i);
  75043. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  75044. rects.remove (i);
  75045. else
  75046. notEmpty = true;
  75047. }
  75048. }
  75049. return notEmpty;
  75050. }
  75051. bool RectangleList::clipTo (const RectangleList& other)
  75052. {
  75053. if (rects.size() == 0)
  75054. return false;
  75055. RectangleList result;
  75056. for (int j = 0; j < rects.size(); ++j)
  75057. {
  75058. const Rectangle<int>& rect = rects.getReference (j);
  75059. for (int i = other.rects.size(); --i >= 0;)
  75060. {
  75061. Rectangle<int> r (other.rects.getReference (i));
  75062. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  75063. result.rects.add (r);
  75064. }
  75065. }
  75066. swapWith (result);
  75067. return ! isEmpty();
  75068. }
  75069. bool RectangleList::getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const
  75070. {
  75071. destRegion.clear();
  75072. if (! rect.isEmpty())
  75073. {
  75074. for (int i = rects.size(); --i >= 0;)
  75075. {
  75076. Rectangle<int> r (rects.getReference (i));
  75077. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  75078. destRegion.rects.add (r);
  75079. }
  75080. }
  75081. return destRegion.rects.size() > 0;
  75082. }
  75083. void RectangleList::swapWith (RectangleList& otherList) throw()
  75084. {
  75085. rects.swapWithArray (otherList.rects);
  75086. }
  75087. void RectangleList::consolidate()
  75088. {
  75089. int i;
  75090. for (i = 0; i < getNumRectangles() - 1; ++i)
  75091. {
  75092. Rectangle<int>& r = rects.getReference (i);
  75093. const int rx1 = r.x;
  75094. const int ry1 = r.y;
  75095. const int rx2 = rx1 + r.w;
  75096. const int ry2 = ry1 + r.h;
  75097. for (int j = rects.size(); --j > i;)
  75098. {
  75099. Rectangle<int>& r2 = rects.getReference (j);
  75100. const int jrx1 = r2.x;
  75101. const int jry1 = r2.y;
  75102. const int jrx2 = jrx1 + r2.w;
  75103. const int jry2 = jry1 + r2.h;
  75104. // if the vertical edges of any blocks are touching and their horizontals don't
  75105. // line up, split them horizontally..
  75106. if (jrx1 == rx2 || jrx2 == rx1)
  75107. {
  75108. if (jry1 > ry1 && jry1 < ry2)
  75109. {
  75110. r.h = jry1 - ry1;
  75111. rects.add (Rectangle<int> (rx1, jry1, rx2 - rx1, ry2 - jry1));
  75112. i = -1;
  75113. break;
  75114. }
  75115. if (jry2 > ry1 && jry2 < ry2)
  75116. {
  75117. r.h = jry2 - ry1;
  75118. rects.add (Rectangle<int> (rx1, jry2, rx2 - rx1, ry2 - jry2));
  75119. i = -1;
  75120. break;
  75121. }
  75122. else if (ry1 > jry1 && ry1 < jry2)
  75123. {
  75124. r2.h = ry1 - jry1;
  75125. rects.add (Rectangle<int> (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  75126. i = -1;
  75127. break;
  75128. }
  75129. else if (ry2 > jry1 && ry2 < jry2)
  75130. {
  75131. r2.h = ry2 - jry1;
  75132. rects.add (Rectangle<int> (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  75133. i = -1;
  75134. break;
  75135. }
  75136. }
  75137. }
  75138. }
  75139. for (i = 0; i < rects.size() - 1; ++i)
  75140. {
  75141. Rectangle<int>& r = rects.getReference (i);
  75142. for (int j = rects.size(); --j > i;)
  75143. {
  75144. if (r.enlargeIfAdjacent (rects.getReference (j)))
  75145. {
  75146. rects.remove (j);
  75147. i = -1;
  75148. break;
  75149. }
  75150. }
  75151. }
  75152. }
  75153. bool RectangleList::containsPoint (const int x, const int y) const throw()
  75154. {
  75155. for (int i = getNumRectangles(); --i >= 0;)
  75156. if (rects.getReference (i).contains (x, y))
  75157. return true;
  75158. return false;
  75159. }
  75160. bool RectangleList::containsRectangle (const Rectangle<int>& rectangleToCheck) const
  75161. {
  75162. if (rects.size() > 1)
  75163. {
  75164. RectangleList r (rectangleToCheck);
  75165. for (int i = rects.size(); --i >= 0;)
  75166. {
  75167. r.subtract (rects.getReference (i));
  75168. if (r.rects.size() == 0)
  75169. return true;
  75170. }
  75171. }
  75172. else if (rects.size() > 0)
  75173. {
  75174. return rects.getReference (0).contains (rectangleToCheck);
  75175. }
  75176. return false;
  75177. }
  75178. bool RectangleList::intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw()
  75179. {
  75180. for (int i = rects.size(); --i >= 0;)
  75181. if (rects.getReference (i).intersects (rectangleToCheck))
  75182. return true;
  75183. return false;
  75184. }
  75185. bool RectangleList::intersects (const RectangleList& other) const throw()
  75186. {
  75187. for (int i = rects.size(); --i >= 0;)
  75188. if (other.intersectsRectangle (rects.getReference (i)))
  75189. return true;
  75190. return false;
  75191. }
  75192. const Rectangle<int> RectangleList::getBounds() const throw()
  75193. {
  75194. if (rects.size() <= 1)
  75195. {
  75196. if (rects.size() == 0)
  75197. return Rectangle<int>();
  75198. else
  75199. return rects.getReference (0);
  75200. }
  75201. else
  75202. {
  75203. const Rectangle<int>& r = rects.getReference (0);
  75204. int minX = r.x;
  75205. int minY = r.y;
  75206. int maxX = minX + r.w;
  75207. int maxY = minY + r.h;
  75208. for (int i = rects.size(); --i > 0;)
  75209. {
  75210. const Rectangle<int>& r2 = rects.getReference (i);
  75211. minX = jmin (minX, r2.x);
  75212. minY = jmin (minY, r2.y);
  75213. maxX = jmax (maxX, r2.getRight());
  75214. maxY = jmax (maxY, r2.getBottom());
  75215. }
  75216. return Rectangle<int> (minX, minY, maxX - minX, maxY - minY);
  75217. }
  75218. }
  75219. void RectangleList::offsetAll (const int dx, const int dy) throw()
  75220. {
  75221. for (int i = rects.size(); --i >= 0;)
  75222. {
  75223. Rectangle<int>& r = rects.getReference (i);
  75224. r.x += dx;
  75225. r.y += dy;
  75226. }
  75227. }
  75228. const Path RectangleList::toPath() const
  75229. {
  75230. Path p;
  75231. for (int i = rects.size(); --i >= 0;)
  75232. {
  75233. const Rectangle<int>& r = rects.getReference (i);
  75234. p.addRectangle ((float) r.x,
  75235. (float) r.y,
  75236. (float) r.w,
  75237. (float) r.h);
  75238. }
  75239. return p;
  75240. }
  75241. END_JUCE_NAMESPACE
  75242. /*** End of inlined file: juce_RectangleList.cpp ***/
  75243. /*** Start of inlined file: juce_RelativeCoordinate.cpp ***/
  75244. BEGIN_JUCE_NAMESPACE
  75245. namespace RelativeCoordinateHelpers
  75246. {
  75247. static bool isOrigin (const String& name)
  75248. {
  75249. return name.isEmpty()
  75250. || name == RelativeCoordinate::Strings::parentLeft
  75251. || name == RelativeCoordinate::Strings::parentTop;
  75252. }
  75253. static const String getOriginAnchorName (const bool isHorizontal) throw()
  75254. {
  75255. return isHorizontal ? RelativeCoordinate::Strings::parentLeft
  75256. : RelativeCoordinate::Strings::parentTop;
  75257. }
  75258. static const String getExtentAnchorName (const bool isHorizontal) throw()
  75259. {
  75260. return isHorizontal ? RelativeCoordinate::Strings::parentRight
  75261. : RelativeCoordinate::Strings::parentBottom;
  75262. }
  75263. static const String getObjectName (const String& fullName)
  75264. {
  75265. return fullName.upToFirstOccurrenceOf (".", false, false);
  75266. }
  75267. static const String getEdgeName (const String& fullName)
  75268. {
  75269. return fullName.fromFirstOccurrenceOf (".", false, false);
  75270. }
  75271. static const RelativeCoordinate findCoordinate (const String& name, const RelativeCoordinate::NamedCoordinateFinder* nameFinder)
  75272. {
  75273. return nameFinder != 0 ? nameFinder->findNamedCoordinate (getObjectName (name), getEdgeName (name))
  75274. : RelativeCoordinate();
  75275. }
  75276. struct RecursionException : public std::runtime_error
  75277. {
  75278. RecursionException() : std::runtime_error ("Recursive RelativeCoordinate expression")
  75279. {
  75280. }
  75281. };
  75282. static void skipWhitespace (const juce_wchar* const s, int& i)
  75283. {
  75284. while (CharacterFunctions::isWhitespace (s[i]))
  75285. ++i;
  75286. }
  75287. static void skipComma (const juce_wchar* const s, int& i)
  75288. {
  75289. skipWhitespace (s, i);
  75290. if (s[i] == ',')
  75291. ++i;
  75292. }
  75293. static const String readAnchorName (const juce_wchar* const s, int& i)
  75294. {
  75295. skipWhitespace (s, i);
  75296. if (CharacterFunctions::isLetter (s[i]) || s[i] == '_')
  75297. {
  75298. int start = i;
  75299. while (CharacterFunctions::isLetterOrDigit (s[i]) || s[i] == '_' || s[i] == '.')
  75300. ++i;
  75301. return String (s + start, i - start);
  75302. }
  75303. return String::empty;
  75304. }
  75305. static double readNumber (const juce_wchar* const s, int& i)
  75306. {
  75307. skipWhitespace (s, i);
  75308. int start = i;
  75309. if (CharacterFunctions::isDigit (s[i]) || s[i] == '.' || s[i] == '-')
  75310. ++i;
  75311. while (CharacterFunctions::isDigit (s[i]) || s[i] == '.')
  75312. ++i;
  75313. if ((s[i] == 'e' || s[i] == 'E')
  75314. && (CharacterFunctions::isDigit (s[i + 1])
  75315. || s[i + 1] == '-'
  75316. || s[i + 1] == '+'))
  75317. {
  75318. i += 2;
  75319. while (CharacterFunctions::isDigit (s[i]))
  75320. ++i;
  75321. }
  75322. const double value = String (s + start, i - start).getDoubleValue();
  75323. while (CharacterFunctions::isWhitespace (s[i]) || s[i] == ',')
  75324. ++i;
  75325. return value;
  75326. }
  75327. static const RelativeCoordinate readNextCoordinate (const juce_wchar* const s, int& i, const bool isHorizontal)
  75328. {
  75329. String anchor1 (readAnchorName (s, i));
  75330. double value = 0;
  75331. if (anchor1.isNotEmpty())
  75332. {
  75333. skipWhitespace (s, i);
  75334. if (s[i] == '+')
  75335. value = readNumber (s, ++i);
  75336. else if (s[i] == '-')
  75337. value = -readNumber (s, ++i);
  75338. return RelativeCoordinate (value, anchor1);
  75339. }
  75340. else
  75341. {
  75342. value = readNumber (s, i);
  75343. skipWhitespace (s, i);
  75344. if (s[i] == '%')
  75345. {
  75346. value /= 100.0;
  75347. skipWhitespace (s, ++i);
  75348. String anchor2;
  75349. if (s[i] == '*')
  75350. {
  75351. anchor1 = readAnchorName (s, ++i);
  75352. if (anchor1.isEmpty())
  75353. anchor1 = getOriginAnchorName (isHorizontal);
  75354. skipWhitespace (s, i);
  75355. if (s[i] == '-' && s[i + 1] == '>')
  75356. {
  75357. i += 2;
  75358. anchor2 = readAnchorName (s, i);
  75359. }
  75360. else
  75361. {
  75362. anchor2 = anchor1;
  75363. anchor1 = getOriginAnchorName (isHorizontal);
  75364. }
  75365. }
  75366. else
  75367. {
  75368. anchor1 = getOriginAnchorName (isHorizontal);
  75369. anchor2 = getExtentAnchorName (isHorizontal);
  75370. }
  75371. return RelativeCoordinate (value, anchor1, anchor2);
  75372. }
  75373. return RelativeCoordinate (value, isHorizontal);
  75374. }
  75375. }
  75376. static const String limitedAccuracyString (const double n)
  75377. {
  75378. if (! (n < -0.001 || n > 0.001)) // to detect NaN and inf as well as for rounding
  75379. return "0";
  75380. return String (n, 3).trimCharactersAtEnd ("0").trimCharactersAtEnd (".");
  75381. }
  75382. }
  75383. const String RelativeCoordinate::Strings::parent ("parent");
  75384. const String RelativeCoordinate::Strings::left ("left");
  75385. const String RelativeCoordinate::Strings::right ("right");
  75386. const String RelativeCoordinate::Strings::top ("top");
  75387. const String RelativeCoordinate::Strings::bottom ("bottom");
  75388. const String RelativeCoordinate::Strings::parentLeft ("parent.left");
  75389. const String RelativeCoordinate::Strings::parentTop ("parent.top");
  75390. const String RelativeCoordinate::Strings::parentRight ("parent.right");
  75391. const String RelativeCoordinate::Strings::parentBottom ("parent.bottom");
  75392. RelativeCoordinate::RelativeCoordinate()
  75393. : value (0)
  75394. {
  75395. }
  75396. RelativeCoordinate::RelativeCoordinate (const double absoluteDistanceFromOrigin, const bool horizontal_)
  75397. : anchor1 (RelativeCoordinateHelpers::getOriginAnchorName (horizontal_)),
  75398. value (absoluteDistanceFromOrigin)
  75399. {
  75400. }
  75401. RelativeCoordinate::RelativeCoordinate (const double absoluteDistance, const String& source)
  75402. : anchor1 (source.trim()),
  75403. value (absoluteDistance)
  75404. {
  75405. jassert (anchor1.isNotEmpty());
  75406. }
  75407. RelativeCoordinate::RelativeCoordinate (const double relativeProportion, const String& pos1, const String& pos2)
  75408. : anchor1 (pos1.trim()),
  75409. anchor2 (pos2.trim()),
  75410. value (relativeProportion)
  75411. {
  75412. jassert (anchor1.isNotEmpty());
  75413. jassert (anchor2.isNotEmpty());
  75414. }
  75415. RelativeCoordinate::RelativeCoordinate (const String& s, const bool isHorizontal)
  75416. : value (0)
  75417. {
  75418. int i = 0;
  75419. *this = RelativeCoordinateHelpers::readNextCoordinate (s, i, isHorizontal);
  75420. }
  75421. RelativeCoordinate::~RelativeCoordinate()
  75422. {
  75423. }
  75424. bool RelativeCoordinate::operator== (const RelativeCoordinate& other) const throw()
  75425. {
  75426. return value == other.value && anchor1 == other.anchor1 && anchor2 == other.anchor2;
  75427. }
  75428. bool RelativeCoordinate::operator!= (const RelativeCoordinate& other) const throw()
  75429. {
  75430. return ! operator== (other);
  75431. }
  75432. const RelativeCoordinate RelativeCoordinate::getAnchorCoordinate1() const
  75433. {
  75434. return RelativeCoordinate (0.0, anchor1);
  75435. }
  75436. const RelativeCoordinate RelativeCoordinate::getAnchorCoordinate2() const
  75437. {
  75438. return RelativeCoordinate (0.0, anchor2);
  75439. }
  75440. double RelativeCoordinate::resolveAnchor (const String& anchorName, const NamedCoordinateFinder* nameFinder, int recursionCounter)
  75441. {
  75442. if (RelativeCoordinateHelpers::isOrigin (anchorName))
  75443. return 0.0;
  75444. return RelativeCoordinateHelpers::findCoordinate (anchorName, nameFinder).resolve (nameFinder, recursionCounter + 1);
  75445. }
  75446. double RelativeCoordinate::resolve (const NamedCoordinateFinder* nameFinder, int recursionCounter) const
  75447. {
  75448. if (recursionCounter > 150)
  75449. {
  75450. jassertfalse
  75451. throw RelativeCoordinateHelpers::RecursionException();
  75452. }
  75453. const double pos1 = resolveAnchor (anchor1, nameFinder, recursionCounter);
  75454. return isProportional() ? pos1 + (resolveAnchor (anchor2, nameFinder, recursionCounter) - pos1) * value
  75455. : pos1 + value;
  75456. }
  75457. double RelativeCoordinate::resolve (const NamedCoordinateFinder* nameFinder) const
  75458. {
  75459. try
  75460. {
  75461. return resolve (nameFinder, 0);
  75462. }
  75463. catch (RelativeCoordinateHelpers::RecursionException&)
  75464. {}
  75465. return 0.0;
  75466. }
  75467. bool RelativeCoordinate::isRecursive (const NamedCoordinateFinder* nameFinder) const
  75468. {
  75469. try
  75470. {
  75471. (void) resolve (nameFinder, 0);
  75472. }
  75473. catch (RelativeCoordinateHelpers::RecursionException&)
  75474. {
  75475. return true;
  75476. }
  75477. return false;
  75478. }
  75479. void RelativeCoordinate::moveToAbsolute (double newPos, const NamedCoordinateFinder* nameFinder)
  75480. {
  75481. try
  75482. {
  75483. const double pos1 = resolveAnchor (anchor1, nameFinder, 0);
  75484. if (isProportional())
  75485. {
  75486. const double size = resolveAnchor (anchor2, nameFinder, 0) - pos1;
  75487. if (size != 0)
  75488. value = (newPos - pos1) / size;
  75489. }
  75490. else
  75491. {
  75492. value = newPos - pos1;
  75493. }
  75494. }
  75495. catch (RelativeCoordinateHelpers::RecursionException&)
  75496. {}
  75497. }
  75498. void RelativeCoordinate::toggleProportionality (const NamedCoordinateFinder* nameFinder, bool isHorizontal)
  75499. {
  75500. const double oldValue = resolve (nameFinder);
  75501. anchor1 = RelativeCoordinateHelpers::getOriginAnchorName (isHorizontal);
  75502. anchor2 = isProportional() ? String::empty
  75503. : RelativeCoordinateHelpers::getExtentAnchorName (isHorizontal);
  75504. moveToAbsolute (oldValue, nameFinder);
  75505. }
  75506. bool RelativeCoordinate::references (const String& coordName, const NamedCoordinateFinder* nameFinder) const
  75507. {
  75508. using namespace RelativeCoordinateHelpers;
  75509. if (isOrigin (anchor1) && ! isProportional())
  75510. return isOrigin (coordName);
  75511. return anchor1 == coordName
  75512. || anchor2 == coordName
  75513. || findCoordinate (anchor1, nameFinder).references (coordName, nameFinder)
  75514. || (isProportional() && findCoordinate (anchor2, nameFinder).references (coordName, nameFinder));
  75515. }
  75516. bool RelativeCoordinate::isDynamic() const
  75517. {
  75518. return anchor2.isNotEmpty() || ! RelativeCoordinateHelpers::isOrigin (anchor1);
  75519. }
  75520. const String RelativeCoordinate::toString() const
  75521. {
  75522. using namespace RelativeCoordinateHelpers;
  75523. if (isProportional())
  75524. {
  75525. const String percent (limitedAccuracyString (value * 100.0));
  75526. if (isOrigin (anchor1))
  75527. {
  75528. if (anchor2 == "parent.right" || anchor2 == "parent.bottom")
  75529. return percent + "%";
  75530. else
  75531. return percent + "% * " + anchor2;
  75532. }
  75533. else
  75534. return percent + "% * " + anchor1 + " -> " + anchor2;
  75535. }
  75536. else
  75537. {
  75538. if (isOrigin (anchor1))
  75539. return limitedAccuracyString (value);
  75540. else if (value > 0)
  75541. return anchor1 + " + " + limitedAccuracyString (value);
  75542. else if (value < 0)
  75543. return anchor1 + " - " + limitedAccuracyString (-value);
  75544. else
  75545. return anchor1;
  75546. }
  75547. }
  75548. const double RelativeCoordinate::getEditableNumber() const
  75549. {
  75550. return isProportional() ? value * 100.0 : value;
  75551. }
  75552. void RelativeCoordinate::setEditableNumber (const double newValue)
  75553. {
  75554. value = isProportional() ? newValue / 100.0 : newValue;
  75555. }
  75556. void RelativeCoordinate::changeAnchor1 (const String& newAnchorName, const NamedCoordinateFinder* nameFinder)
  75557. {
  75558. jassert (newAnchorName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_."));
  75559. const double oldValue = resolve (nameFinder);
  75560. anchor1 = newAnchorName;
  75561. moveToAbsolute (oldValue, nameFinder);
  75562. }
  75563. void RelativeCoordinate::changeAnchor2 (const String& newAnchorName, const NamedCoordinateFinder* nameFinder)
  75564. {
  75565. jassert (isProportional());
  75566. jassert (newAnchorName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_."));
  75567. const double oldValue = resolve (nameFinder);
  75568. anchor2 = newAnchorName;
  75569. moveToAbsolute (oldValue, nameFinder);
  75570. }
  75571. void RelativeCoordinate::renameAnchorIfUsed (const String& oldName, const String& newName, const NamedCoordinateFinder* nameFinder)
  75572. {
  75573. using namespace RelativeCoordinateHelpers;
  75574. jassert (oldName.isNotEmpty());
  75575. jassert (newName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  75576. if (newName.isEmpty())
  75577. {
  75578. if (getObjectName (anchor1) == oldName
  75579. || getObjectName (anchor2) == oldName)
  75580. {
  75581. value = resolve (nameFinder);
  75582. anchor1 = String::empty;
  75583. anchor2 = String::empty;
  75584. }
  75585. }
  75586. else
  75587. {
  75588. if (getObjectName (anchor1) == oldName)
  75589. anchor1 = newName + "." + getEdgeName (anchor1);
  75590. if (getObjectName (anchor2) == oldName)
  75591. anchor2 = newName + "." + getEdgeName (anchor2);
  75592. }
  75593. }
  75594. RelativePoint::RelativePoint()
  75595. : x (0, true), y (0, false)
  75596. {
  75597. }
  75598. RelativePoint::RelativePoint (const Point<float>& absolutePoint)
  75599. : x (absolutePoint.getX(), true), y (absolutePoint.getY(), false)
  75600. {
  75601. }
  75602. RelativePoint::RelativePoint (const float x_, const float y_)
  75603. : x (x_, true), y (y_, false)
  75604. {
  75605. }
  75606. RelativePoint::RelativePoint (const RelativeCoordinate& x_, const RelativeCoordinate& y_)
  75607. : x (x_), y (y_)
  75608. {
  75609. }
  75610. RelativePoint::RelativePoint (const String& s)
  75611. {
  75612. int i = 0;
  75613. x = RelativeCoordinateHelpers::readNextCoordinate (s, i, true);
  75614. RelativeCoordinateHelpers::skipComma (s, i);
  75615. y = RelativeCoordinateHelpers::readNextCoordinate (s, i, false);
  75616. }
  75617. bool RelativePoint::operator== (const RelativePoint& other) const throw()
  75618. {
  75619. return x == other.x && y == other.y;
  75620. }
  75621. bool RelativePoint::operator!= (const RelativePoint& other) const throw()
  75622. {
  75623. return ! operator== (other);
  75624. }
  75625. const Point<float> RelativePoint::resolve (const RelativeCoordinate::NamedCoordinateFinder* nameFinder) const
  75626. {
  75627. return Point<float> ((float) x.resolve (nameFinder),
  75628. (float) y.resolve (nameFinder));
  75629. }
  75630. void RelativePoint::moveToAbsolute (const Point<float>& newPos, const RelativeCoordinate::NamedCoordinateFinder* nameFinder)
  75631. {
  75632. x.moveToAbsolute (newPos.getX(), nameFinder);
  75633. y.moveToAbsolute (newPos.getY(), nameFinder);
  75634. }
  75635. const String RelativePoint::toString() const
  75636. {
  75637. return x.toString() + ", " + y.toString();
  75638. }
  75639. void RelativePoint::renameAnchorIfUsed (const String& oldName, const String& newName, const RelativeCoordinate::NamedCoordinateFinder* nameFinder)
  75640. {
  75641. x.renameAnchorIfUsed (oldName, newName, nameFinder);
  75642. y.renameAnchorIfUsed (oldName, newName, nameFinder);
  75643. }
  75644. bool RelativePoint::isDynamic() const
  75645. {
  75646. return x.isDynamic() || y.isDynamic();
  75647. }
  75648. RelativeRectangle::RelativeRectangle()
  75649. {
  75650. }
  75651. RelativeRectangle::RelativeRectangle (const RelativeCoordinate& left_, const RelativeCoordinate& right_,
  75652. const RelativeCoordinate& top_, const RelativeCoordinate& bottom_)
  75653. : left (left_), right (right_), top (top_), bottom (bottom_)
  75654. {
  75655. }
  75656. RelativeRectangle::RelativeRectangle (const Rectangle<float>& rect, const String& componentName)
  75657. : left (rect.getX(), true),
  75658. right (rect.getWidth(), componentName + "." + RelativeCoordinate::Strings::left),
  75659. top (rect.getY(), false),
  75660. bottom (rect.getHeight(), componentName + "." + RelativeCoordinate::Strings::top)
  75661. {
  75662. }
  75663. RelativeRectangle::RelativeRectangle (const String& s)
  75664. {
  75665. int i = 0;
  75666. left = RelativeCoordinateHelpers::readNextCoordinate (s, i, true);
  75667. RelativeCoordinateHelpers::skipComma (s, i);
  75668. top = RelativeCoordinateHelpers::readNextCoordinate (s, i, false);
  75669. RelativeCoordinateHelpers::skipComma (s, i);
  75670. right = RelativeCoordinateHelpers::readNextCoordinate (s, i, true);
  75671. RelativeCoordinateHelpers::skipComma (s, i);
  75672. bottom = RelativeCoordinateHelpers::readNextCoordinate (s, i, false);
  75673. }
  75674. bool RelativeRectangle::operator== (const RelativeRectangle& other) const throw()
  75675. {
  75676. return left == other.left && top == other.top && right == other.right && bottom == other.bottom;
  75677. }
  75678. bool RelativeRectangle::operator!= (const RelativeRectangle& other) const throw()
  75679. {
  75680. return ! operator== (other);
  75681. }
  75682. const Rectangle<float> RelativeRectangle::resolve (const RelativeCoordinate::NamedCoordinateFinder* nameFinder) const
  75683. {
  75684. const double l = left.resolve (nameFinder);
  75685. const double r = right.resolve (nameFinder);
  75686. const double t = top.resolve (nameFinder);
  75687. const double b = bottom.resolve (nameFinder);
  75688. return Rectangle<float> ((float) l, (float) t, (float) (r - l), (float) (b - t));
  75689. }
  75690. void RelativeRectangle::moveToAbsolute (const Rectangle<float>& newPos, const RelativeCoordinate::NamedCoordinateFinder* nameFinder)
  75691. {
  75692. left.moveToAbsolute (newPos.getX(), nameFinder);
  75693. right.moveToAbsolute (newPos.getRight(), nameFinder);
  75694. top.moveToAbsolute (newPos.getY(), nameFinder);
  75695. bottom.moveToAbsolute (newPos.getBottom(), nameFinder);
  75696. }
  75697. const String RelativeRectangle::toString() const
  75698. {
  75699. return left.toString() + ", " + top.toString() + ", " + right.toString() + ", " + bottom.toString();
  75700. }
  75701. void RelativeRectangle::renameAnchorIfUsed (const String& oldName, const String& newName,
  75702. const RelativeCoordinate::NamedCoordinateFinder* nameFinder)
  75703. {
  75704. left.renameAnchorIfUsed (oldName, newName, nameFinder);
  75705. right.renameAnchorIfUsed (oldName, newName, nameFinder);
  75706. top.renameAnchorIfUsed (oldName, newName, nameFinder);
  75707. bottom.renameAnchorIfUsed (oldName, newName, nameFinder);
  75708. }
  75709. RelativePointPath::RelativePointPath()
  75710. : usesNonZeroWinding (true),
  75711. containsDynamicPoints (false)
  75712. {
  75713. }
  75714. RelativePointPath::RelativePointPath (const RelativePointPath& other)
  75715. : usesNonZeroWinding (true),
  75716. containsDynamicPoints (false)
  75717. {
  75718. ValueTree state (DrawablePath::valueTreeType);
  75719. other.writeTo (state, 0);
  75720. parse (state);
  75721. }
  75722. RelativePointPath::RelativePointPath (const ValueTree& drawable)
  75723. : usesNonZeroWinding (true),
  75724. containsDynamicPoints (false)
  75725. {
  75726. parse (drawable);
  75727. }
  75728. RelativePointPath::RelativePointPath (const Path& path)
  75729. {
  75730. usesNonZeroWinding = path.isUsingNonZeroWinding();
  75731. Path::Iterator i (path);
  75732. while (i.next())
  75733. {
  75734. switch (i.elementType)
  75735. {
  75736. case Path::Iterator::startNewSubPath: elements.add (new StartSubPath (RelativePoint (i.x1, i.y1))); break;
  75737. case Path::Iterator::lineTo: elements.add (new LineTo (RelativePoint (i.x1, i.y1))); break;
  75738. case Path::Iterator::quadraticTo: elements.add (new QuadraticTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2))); break;
  75739. case Path::Iterator::cubicTo: elements.add (new CubicTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2), RelativePoint (i.x3, i.y3))); break;
  75740. case Path::Iterator::closePath: elements.add (new CloseSubPath()); break;
  75741. default: jassertfalse; break;
  75742. }
  75743. }
  75744. }
  75745. void RelativePointPath::writeTo (ValueTree state, UndoManager* undoManager) const
  75746. {
  75747. DrawablePath::ValueTreeWrapper wrapper (state);
  75748. wrapper.setUsesNonZeroWinding (usesNonZeroWinding, undoManager);
  75749. ValueTree pathTree (wrapper.getPathState());
  75750. pathTree.removeAllChildren (undoManager);
  75751. for (int i = 0; i < elements.size(); ++i)
  75752. pathTree.addChild (elements.getUnchecked(i)->createTree(), -1, undoManager);
  75753. }
  75754. void RelativePointPath::parse (const ValueTree& state)
  75755. {
  75756. DrawablePath::ValueTreeWrapper wrapper (state);
  75757. usesNonZeroWinding = wrapper.usesNonZeroWinding();
  75758. RelativePoint points[3];
  75759. const ValueTree pathTree (wrapper.getPathState());
  75760. const int num = pathTree.getNumChildren();
  75761. for (int i = 0; i < num; ++i)
  75762. {
  75763. const DrawablePath::ValueTreeWrapper::Element e (pathTree.getChild(i));
  75764. const int numCps = e.getNumControlPoints();
  75765. for (int j = 0; j < numCps; ++j)
  75766. {
  75767. points[j] = e.getControlPoint (j);
  75768. containsDynamicPoints = containsDynamicPoints || points[j].isDynamic();
  75769. }
  75770. const Identifier type (e.getType());
  75771. if (type == DrawablePath::ValueTreeWrapper::Element::startSubPathElement)
  75772. elements.add (new StartSubPath (points[0]));
  75773. else if (type == DrawablePath::ValueTreeWrapper::Element::closeSubPathElement)
  75774. elements.add (new CloseSubPath());
  75775. else if (type == DrawablePath::ValueTreeWrapper::Element::lineToElement)
  75776. elements.add (new LineTo (points[0]));
  75777. else if (type == DrawablePath::ValueTreeWrapper::Element::quadraticToElement)
  75778. elements.add (new QuadraticTo (points[0], points[1]));
  75779. else if (type == DrawablePath::ValueTreeWrapper::Element::cubicToElement)
  75780. elements.add (new CubicTo (points[0], points[1], points[2]));
  75781. else
  75782. jassertfalse;
  75783. }
  75784. }
  75785. RelativePointPath::~RelativePointPath()
  75786. {
  75787. }
  75788. void RelativePointPath::swapWith (RelativePointPath& other) throw()
  75789. {
  75790. elements.swapWithArray (other.elements);
  75791. swapVariables (usesNonZeroWinding, other.usesNonZeroWinding);
  75792. }
  75793. void RelativePointPath::createPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder)
  75794. {
  75795. for (int i = 0; i < elements.size(); ++i)
  75796. elements.getUnchecked(i)->addToPath (path, coordFinder);
  75797. }
  75798. bool RelativePointPath::containsAnyDynamicPoints() const
  75799. {
  75800. return containsDynamicPoints;
  75801. }
  75802. RelativePointPath::ElementBase::ElementBase (const ElementType type_) : type (type_)
  75803. {
  75804. }
  75805. RelativePointPath::StartSubPath::StartSubPath (const RelativePoint& pos)
  75806. : ElementBase (startSubPathElement), startPos (pos)
  75807. {
  75808. }
  75809. const ValueTree RelativePointPath::StartSubPath::createTree() const
  75810. {
  75811. ValueTree v (DrawablePath::ValueTreeWrapper::Element::startSubPathElement);
  75812. v.setProperty (DrawablePath::ValueTreeWrapper::point1, startPos.toString(), 0);
  75813. return v;
  75814. }
  75815. void RelativePointPath::StartSubPath::addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const
  75816. {
  75817. path.startNewSubPath (startPos.resolve (coordFinder));
  75818. }
  75819. RelativePoint* RelativePointPath::StartSubPath::getControlPoints (int& numPoints)
  75820. {
  75821. numPoints = 1;
  75822. return &startPos;
  75823. }
  75824. RelativePointPath::CloseSubPath::CloseSubPath()
  75825. : ElementBase (closeSubPathElement)
  75826. {
  75827. }
  75828. const ValueTree RelativePointPath::CloseSubPath::createTree() const
  75829. {
  75830. return ValueTree (DrawablePath::ValueTreeWrapper::Element::closeSubPathElement);
  75831. }
  75832. void RelativePointPath::CloseSubPath::addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder*) const
  75833. {
  75834. path.closeSubPath();
  75835. }
  75836. RelativePoint* RelativePointPath::CloseSubPath::getControlPoints (int& numPoints)
  75837. {
  75838. numPoints = 0;
  75839. return 0;
  75840. }
  75841. RelativePointPath::LineTo::LineTo (const RelativePoint& endPoint_)
  75842. : ElementBase (lineToElement), endPoint (endPoint_)
  75843. {
  75844. }
  75845. const ValueTree RelativePointPath::LineTo::createTree() const
  75846. {
  75847. ValueTree v (DrawablePath::ValueTreeWrapper::Element::lineToElement);
  75848. v.setProperty (DrawablePath::ValueTreeWrapper::point1, endPoint.toString(), 0);
  75849. return v;
  75850. }
  75851. void RelativePointPath::LineTo::addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const
  75852. {
  75853. path.lineTo (endPoint.resolve (coordFinder));
  75854. }
  75855. RelativePoint* RelativePointPath::LineTo::getControlPoints (int& numPoints)
  75856. {
  75857. numPoints = 1;
  75858. return &endPoint;
  75859. }
  75860. RelativePointPath::QuadraticTo::QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint)
  75861. : ElementBase (quadraticToElement)
  75862. {
  75863. controlPoints[0] = controlPoint;
  75864. controlPoints[1] = endPoint;
  75865. }
  75866. const ValueTree RelativePointPath::QuadraticTo::createTree() const
  75867. {
  75868. ValueTree v (DrawablePath::ValueTreeWrapper::Element::quadraticToElement);
  75869. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  75870. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  75871. return v;
  75872. }
  75873. void RelativePointPath::QuadraticTo::addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const
  75874. {
  75875. path.quadraticTo (controlPoints[0].resolve (coordFinder),
  75876. controlPoints[1].resolve (coordFinder));
  75877. }
  75878. RelativePoint* RelativePointPath::QuadraticTo::getControlPoints (int& numPoints)
  75879. {
  75880. numPoints = 2;
  75881. return controlPoints;
  75882. }
  75883. RelativePointPath::CubicTo::CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint)
  75884. : ElementBase (cubicToElement)
  75885. {
  75886. controlPoints[0] = controlPoint1;
  75887. controlPoints[1] = controlPoint2;
  75888. controlPoints[2] = endPoint;
  75889. }
  75890. const ValueTree RelativePointPath::CubicTo::createTree() const
  75891. {
  75892. ValueTree v (DrawablePath::ValueTreeWrapper::Element::cubicToElement);
  75893. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  75894. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  75895. v.setProperty (DrawablePath::ValueTreeWrapper::point3, controlPoints[2].toString(), 0);
  75896. return v;
  75897. }
  75898. void RelativePointPath::CubicTo::addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const
  75899. {
  75900. path.cubicTo (controlPoints[0].resolve (coordFinder),
  75901. controlPoints[1].resolve (coordFinder),
  75902. controlPoints[2].resolve (coordFinder));
  75903. }
  75904. RelativePoint* RelativePointPath::CubicTo::getControlPoints (int& numPoints)
  75905. {
  75906. numPoints = 3;
  75907. return controlPoints;
  75908. }
  75909. RelativeParallelogram::RelativeParallelogram()
  75910. {
  75911. }
  75912. RelativeParallelogram::RelativeParallelogram (const RelativePoint& topLeft_, const RelativePoint& topRight_, const RelativePoint& bottomLeft_)
  75913. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  75914. {
  75915. }
  75916. RelativeParallelogram::RelativeParallelogram (const String& topLeft_, const String& topRight_, const String& bottomLeft_)
  75917. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  75918. {
  75919. }
  75920. RelativeParallelogram::~RelativeParallelogram()
  75921. {
  75922. }
  75923. void RelativeParallelogram::resolveThreePoints (Point<float>* points, RelativeCoordinate::NamedCoordinateFinder* const coordFinder) const
  75924. {
  75925. points[0] = topLeft.resolve (coordFinder);
  75926. points[1] = topRight.resolve (coordFinder);
  75927. points[2] = bottomLeft.resolve (coordFinder);
  75928. }
  75929. void RelativeParallelogram::resolveFourCorners (Point<float>* points, RelativeCoordinate::NamedCoordinateFinder* const coordFinder) const
  75930. {
  75931. resolveThreePoints (points, coordFinder);
  75932. points[3] = points[1] + (points[2] - points[0]);
  75933. }
  75934. const Rectangle<float> RelativeParallelogram::getBounds (RelativeCoordinate::NamedCoordinateFinder* const coordFinder) const
  75935. {
  75936. Point<float> points[4];
  75937. resolveFourCorners (points, coordFinder);
  75938. return Rectangle<float>::findAreaContainingPoints (points, 4);
  75939. }
  75940. void RelativeParallelogram::getPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* const coordFinder) const
  75941. {
  75942. Point<float> points[4];
  75943. resolveFourCorners (points, coordFinder);
  75944. path.startNewSubPath (points[0]);
  75945. path.lineTo (points[1]);
  75946. path.lineTo (points[3]);
  75947. path.lineTo (points[2]);
  75948. path.closeSubPath();
  75949. }
  75950. const AffineTransform RelativeParallelogram::resetToPerpendicular (RelativeCoordinate::NamedCoordinateFinder* const coordFinder)
  75951. {
  75952. Point<float> corners[3];
  75953. resolveThreePoints (corners, coordFinder);
  75954. const Line<float> top (corners[0], corners[1]);
  75955. const Line<float> left (corners[0], corners[2]);
  75956. const Point<float> newTopRight (corners[0] + Point<float> (top.getLength(), 0.0f));
  75957. const Point<float> newBottomLeft (corners[0] + Point<float> (0.0f, left.getLength()));
  75958. topRight.moveToAbsolute (newTopRight, coordFinder);
  75959. bottomLeft.moveToAbsolute (newBottomLeft, coordFinder);
  75960. return AffineTransform::fromTargetPoints (corners[0].getX(), corners[0].getY(), corners[0].getX(), corners[0].getY(),
  75961. corners[1].getX(), corners[1].getY(), newTopRight.getX(), newTopRight.getY(),
  75962. corners[2].getX(), corners[2].getY(), newBottomLeft.getX(), newBottomLeft.getY());
  75963. }
  75964. bool RelativeParallelogram::operator== (const RelativeParallelogram& other) const throw()
  75965. {
  75966. return topLeft == other.topLeft && topRight == other.topRight && bottomLeft == other.bottomLeft;
  75967. }
  75968. bool RelativeParallelogram::operator!= (const RelativeParallelogram& other) const throw()
  75969. {
  75970. return ! operator== (other);
  75971. }
  75972. const Point<float> RelativeParallelogram::getInternalCoordForPoint (const Point<float>* const corners, Point<float> target) throw()
  75973. {
  75974. const Point<float> tr (corners[1] - corners[0]);
  75975. const Point<float> bl (corners[2] - corners[0]);
  75976. target -= corners[0];
  75977. return Point<float> (Line<float> (Point<float>(), tr).getIntersection (Line<float> (target, target - bl)).getDistanceFromOrigin(),
  75978. Line<float> (Point<float>(), bl).getIntersection (Line<float> (target, target - tr)).getDistanceFromOrigin());
  75979. }
  75980. const Point<float> RelativeParallelogram::getPointForInternalCoord (const Point<float>* const corners, const Point<float>& point) throw()
  75981. {
  75982. return corners[0]
  75983. + Line<float> (Point<float>(), corners[1] - corners[0]).getPointAlongLine (point.getX())
  75984. + Line<float> (Point<float>(), corners[2] - corners[0]).getPointAlongLine (point.getY());
  75985. }
  75986. END_JUCE_NAMESPACE
  75987. /*** End of inlined file: juce_RelativeCoordinate.cpp ***/
  75988. /*** Start of inlined file: juce_Image.cpp ***/
  75989. BEGIN_JUCE_NAMESPACE
  75990. Image::SharedImage::SharedImage (const PixelFormat format_, const int width_, const int height_)
  75991. : format (format_), width (width_), height (height_)
  75992. {
  75993. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  75994. jassert (width > 0 && height > 0); // It's illegal to create a zero-sized image!
  75995. }
  75996. Image::SharedImage::~SharedImage()
  75997. {
  75998. }
  75999. inline uint8* Image::SharedImage::getPixelData (const int x, const int y) const throw()
  76000. {
  76001. return imageData + lineStride * y + pixelStride * x;
  76002. }
  76003. class SoftwareSharedImage : public Image::SharedImage
  76004. {
  76005. public:
  76006. SoftwareSharedImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  76007. : Image::SharedImage (format_, width_, height_)
  76008. {
  76009. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  76010. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  76011. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  76012. imageData = imageDataAllocated;
  76013. }
  76014. ~SoftwareSharedImage()
  76015. {
  76016. }
  76017. Image::ImageType getType() const
  76018. {
  76019. return Image::SoftwareImage;
  76020. }
  76021. LowLevelGraphicsContext* createLowLevelContext()
  76022. {
  76023. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  76024. }
  76025. SharedImage* clone()
  76026. {
  76027. SoftwareSharedImage* s = new SoftwareSharedImage (format, width, height, false);
  76028. memcpy (s->imageData, imageData, lineStride * height);
  76029. return s;
  76030. }
  76031. private:
  76032. HeapBlock<uint8> imageDataAllocated;
  76033. };
  76034. Image::SharedImage* Image::SharedImage::createSoftwareImage (Image::PixelFormat format, int width, int height, bool clearImage)
  76035. {
  76036. return new SoftwareSharedImage (format, width, height, clearImage);
  76037. }
  76038. Image::Image()
  76039. {
  76040. }
  76041. Image::Image (SharedImage* const instance)
  76042. : image (instance)
  76043. {
  76044. }
  76045. Image::Image (const PixelFormat format,
  76046. const int width, const int height,
  76047. const bool clearImage, const ImageType type)
  76048. : image (type == Image::NativeImage ? SharedImage::createNativeImage (format, width, height, clearImage)
  76049. : new SoftwareSharedImage (format, width, height, clearImage))
  76050. {
  76051. }
  76052. Image::Image (const Image& other)
  76053. : image (other.image)
  76054. {
  76055. }
  76056. Image& Image::operator= (const Image& other)
  76057. {
  76058. image = other.image;
  76059. return *this;
  76060. }
  76061. Image::~Image()
  76062. {
  76063. }
  76064. LowLevelGraphicsContext* Image::createLowLevelContext() const
  76065. {
  76066. return image == 0 ? 0 : image->createLowLevelContext();
  76067. }
  76068. void Image::duplicateIfShared()
  76069. {
  76070. if (image != 0 && image->getReferenceCount() > 1)
  76071. image = image->clone();
  76072. }
  76073. const Image Image::rescaled (const int newWidth, const int newHeight, const Graphics::ResamplingQuality quality) const
  76074. {
  76075. if (image == 0 || (image->width == newWidth && image->height == newHeight))
  76076. return *this;
  76077. Image newImage (image->format, newWidth, newHeight, hasAlphaChannel(), image->getType());
  76078. Graphics g (newImage);
  76079. g.setImageResamplingQuality (quality);
  76080. g.drawImage (*this, 0, 0, newWidth, newHeight, 0, 0, image->width, image->height, false);
  76081. return newImage;
  76082. }
  76083. const Image Image::convertedToFormat (PixelFormat newFormat) const
  76084. {
  76085. if (image == 0 || newFormat == image->format)
  76086. return *this;
  76087. Image newImage (newFormat, image->width, image->height, false, image->getType());
  76088. if (newFormat == SingleChannel)
  76089. {
  76090. if (! hasAlphaChannel())
  76091. {
  76092. newImage.clear (getBounds(), Colours::black);
  76093. }
  76094. else
  76095. {
  76096. const BitmapData destData (newImage, 0, 0, image->width, image->height, true);
  76097. const BitmapData srcData (*this, 0, 0, image->width, image->height);
  76098. for (int y = 0; y < image->height; ++y)
  76099. {
  76100. const PixelARGB* src = (const PixelARGB*) srcData.getLinePointer(y);
  76101. uint8* dst = destData.getLinePointer (y);
  76102. for (int x = image->width; --x >= 0;)
  76103. {
  76104. *dst++ = src->getAlpha();
  76105. ++src;
  76106. }
  76107. }
  76108. }
  76109. }
  76110. else
  76111. {
  76112. if (hasAlphaChannel())
  76113. newImage.clear (getBounds());
  76114. Graphics g (newImage);
  76115. g.drawImageAt (*this, 0, 0);
  76116. }
  76117. return newImage;
  76118. }
  76119. const var Image::getTag() const
  76120. {
  76121. return image == 0 ? var::null : image->userTag;
  76122. }
  76123. void Image::setTag (const var& newTag)
  76124. {
  76125. if (image != 0)
  76126. image->userTag = newTag;
  76127. }
  76128. Image::BitmapData::BitmapData (Image& image, const int x, const int y, const int w, const int h, const bool /*makeWritable*/)
  76129. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  76130. pixelFormat (image.getFormat()),
  76131. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  76132. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  76133. width (w),
  76134. height (h)
  76135. {
  76136. jassert (data != 0);
  76137. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  76138. }
  76139. Image::BitmapData::BitmapData (const Image& image, const int x, const int y, const int w, const int h)
  76140. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  76141. pixelFormat (image.getFormat()),
  76142. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  76143. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  76144. width (w),
  76145. height (h)
  76146. {
  76147. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  76148. }
  76149. Image::BitmapData::~BitmapData()
  76150. {
  76151. }
  76152. const Colour Image::BitmapData::getPixelColour (const int x, const int y) const throw()
  76153. {
  76154. jassert (((unsigned int) x) < (unsigned int) width && ((unsigned int) y) < (unsigned int) height);
  76155. const uint8* const pixel = getPixelPointer (x, y);
  76156. switch (pixelFormat)
  76157. {
  76158. case Image::ARGB:
  76159. {
  76160. PixelARGB p (*(const PixelARGB*) pixel);
  76161. p.unpremultiply();
  76162. return Colour (p.getARGB());
  76163. }
  76164. case Image::RGB:
  76165. return Colour (((const PixelRGB*) pixel)->getARGB());
  76166. case Image::SingleChannel:
  76167. return Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixel);
  76168. default:
  76169. jassertfalse;
  76170. break;
  76171. }
  76172. return Colour();
  76173. }
  76174. void Image::BitmapData::setPixelColour (const int x, const int y, const Colour& colour) const throw()
  76175. {
  76176. jassert (((unsigned int) x) < (unsigned int) width && ((unsigned int) y) < (unsigned int) height);
  76177. uint8* const pixel = getPixelPointer (x, y);
  76178. const PixelARGB col (colour.getPixelARGB());
  76179. switch (pixelFormat)
  76180. {
  76181. case Image::ARGB: ((PixelARGB*) pixel)->set (col); break;
  76182. case Image::RGB: ((PixelRGB*) pixel)->set (col); break;
  76183. case Image::SingleChannel: *pixel = col.getAlpha(); break;
  76184. default: jassertfalse; break;
  76185. }
  76186. }
  76187. void Image::setPixelData (int x, int y, int w, int h,
  76188. const uint8* const sourcePixelData, const int sourceLineStride)
  76189. {
  76190. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= getWidth() && y + h <= getHeight());
  76191. if (Rectangle<int>::intersectRectangles (x, y, w, h, 0, 0, getWidth(), getHeight()))
  76192. {
  76193. const BitmapData dest (*this, x, y, w, h, true);
  76194. for (int i = 0; i < h; ++i)
  76195. {
  76196. memcpy (dest.getLinePointer(i),
  76197. sourcePixelData + sourceLineStride * i,
  76198. w * dest.pixelStride);
  76199. }
  76200. }
  76201. }
  76202. void Image::clear (const Rectangle<int>& area, const Colour& colourToClearTo)
  76203. {
  76204. const Rectangle<int> clipped (area.getIntersection (getBounds()));
  76205. if (! clipped.isEmpty())
  76206. {
  76207. const PixelARGB col (colourToClearTo.getPixelARGB());
  76208. const BitmapData destData (*this, clipped.getX(), clipped.getY(), clipped.getWidth(), clipped.getHeight(), true);
  76209. uint8* dest = destData.data;
  76210. int dh = clipped.getHeight();
  76211. while (--dh >= 0)
  76212. {
  76213. uint8* line = dest;
  76214. dest += destData.lineStride;
  76215. if (isARGB())
  76216. {
  76217. for (int x = clipped.getWidth(); --x >= 0;)
  76218. {
  76219. ((PixelARGB*) line)->set (col);
  76220. line += destData.pixelStride;
  76221. }
  76222. }
  76223. else if (isRGB())
  76224. {
  76225. for (int x = clipped.getWidth(); --x >= 0;)
  76226. {
  76227. ((PixelRGB*) line)->set (col);
  76228. line += destData.pixelStride;
  76229. }
  76230. }
  76231. else
  76232. {
  76233. for (int x = clipped.getWidth(); --x >= 0;)
  76234. {
  76235. *line = col.getAlpha();
  76236. line += destData.pixelStride;
  76237. }
  76238. }
  76239. }
  76240. }
  76241. }
  76242. const Colour Image::getPixelAt (const int x, const int y) const
  76243. {
  76244. if (((unsigned int) x) < (unsigned int) getWidth()
  76245. && ((unsigned int) y) < (unsigned int) getHeight())
  76246. {
  76247. const BitmapData srcData (*this, x, y, 1, 1);
  76248. return srcData.getPixelColour (0, 0);
  76249. }
  76250. return Colour();
  76251. }
  76252. void Image::setPixelAt (const int x, const int y, const Colour& colour)
  76253. {
  76254. if (((unsigned int) x) < (unsigned int) getWidth()
  76255. && ((unsigned int) y) < (unsigned int) getHeight())
  76256. {
  76257. const BitmapData destData (*this, x, y, 1, 1, true);
  76258. destData.setPixelColour (0, 0, colour);
  76259. }
  76260. }
  76261. void Image::multiplyAlphaAt (const int x, const int y, const float multiplier)
  76262. {
  76263. if (((unsigned int) x) < (unsigned int) getWidth()
  76264. && ((unsigned int) y) < (unsigned int) getHeight()
  76265. && hasAlphaChannel())
  76266. {
  76267. const BitmapData destData (*this, x, y, 1, 1, true);
  76268. if (isARGB())
  76269. ((PixelARGB*) destData.data)->multiplyAlpha (multiplier);
  76270. else
  76271. *(destData.data) = (uint8) (*(destData.data) * multiplier);
  76272. }
  76273. }
  76274. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  76275. {
  76276. if (hasAlphaChannel())
  76277. {
  76278. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  76279. if (isARGB())
  76280. {
  76281. for (int y = 0; y < destData.height; ++y)
  76282. {
  76283. uint8* p = destData.getLinePointer (y);
  76284. for (int x = 0; x < destData.width; ++x)
  76285. {
  76286. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  76287. p += destData.pixelStride;
  76288. }
  76289. }
  76290. }
  76291. else
  76292. {
  76293. for (int y = 0; y < destData.height; ++y)
  76294. {
  76295. uint8* p = destData.getLinePointer (y);
  76296. for (int x = 0; x < destData.width; ++x)
  76297. {
  76298. *p = (uint8) (*p * amountToMultiplyBy);
  76299. p += destData.pixelStride;
  76300. }
  76301. }
  76302. }
  76303. }
  76304. else
  76305. {
  76306. jassertfalse; // can't do this without an alpha-channel!
  76307. }
  76308. }
  76309. void Image::desaturate()
  76310. {
  76311. if (isARGB() || isRGB())
  76312. {
  76313. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  76314. if (isARGB())
  76315. {
  76316. for (int y = 0; y < destData.height; ++y)
  76317. {
  76318. uint8* p = destData.getLinePointer (y);
  76319. for (int x = 0; x < destData.width; ++x)
  76320. {
  76321. ((PixelARGB*) p)->desaturate();
  76322. p += destData.pixelStride;
  76323. }
  76324. }
  76325. }
  76326. else
  76327. {
  76328. for (int y = 0; y < destData.height; ++y)
  76329. {
  76330. uint8* p = destData.getLinePointer (y);
  76331. for (int x = 0; x < destData.width; ++x)
  76332. {
  76333. ((PixelRGB*) p)->desaturate();
  76334. p += destData.pixelStride;
  76335. }
  76336. }
  76337. }
  76338. }
  76339. }
  76340. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  76341. {
  76342. if (hasAlphaChannel())
  76343. {
  76344. const uint8 threshold = (uint8) jlimit (0, 255, roundToInt (alphaThreshold * 255.0f));
  76345. SparseSet<int> pixelsOnRow;
  76346. const BitmapData srcData (*this, 0, 0, getWidth(), getHeight());
  76347. for (int y = 0; y < srcData.height; ++y)
  76348. {
  76349. pixelsOnRow.clear();
  76350. const uint8* lineData = srcData.getLinePointer (y);
  76351. if (isARGB())
  76352. {
  76353. for (int x = 0; x < srcData.width; ++x)
  76354. {
  76355. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  76356. pixelsOnRow.addRange (Range<int> (x, x + 1));
  76357. lineData += srcData.pixelStride;
  76358. }
  76359. }
  76360. else
  76361. {
  76362. for (int x = 0; x < srcData.width; ++x)
  76363. {
  76364. if (*lineData >= threshold)
  76365. pixelsOnRow.addRange (Range<int> (x, x + 1));
  76366. lineData += srcData.pixelStride;
  76367. }
  76368. }
  76369. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  76370. {
  76371. const Range<int> range (pixelsOnRow.getRange (i));
  76372. result.add (Rectangle<int> (range.getStart(), y, range.getLength(), 1));
  76373. }
  76374. result.consolidate();
  76375. }
  76376. }
  76377. else
  76378. {
  76379. result.add (0, 0, getWidth(), getHeight());
  76380. }
  76381. }
  76382. void Image::moveImageSection (int dx, int dy,
  76383. int sx, int sy,
  76384. int w, int h)
  76385. {
  76386. if (dx < 0)
  76387. {
  76388. w += dx;
  76389. sx -= dx;
  76390. dx = 0;
  76391. }
  76392. if (dy < 0)
  76393. {
  76394. h += dy;
  76395. sy -= dy;
  76396. dy = 0;
  76397. }
  76398. if (sx < 0)
  76399. {
  76400. w += sx;
  76401. dx -= sx;
  76402. sx = 0;
  76403. }
  76404. if (sy < 0)
  76405. {
  76406. h += sy;
  76407. dy -= sy;
  76408. sy = 0;
  76409. }
  76410. const int minX = jmin (dx, sx);
  76411. const int minY = jmin (dy, sy);
  76412. w = jmin (w, getWidth() - jmax (sx, dx));
  76413. h = jmin (h, getHeight() - jmax (sy, dy));
  76414. if (w > 0 && h > 0)
  76415. {
  76416. const int maxX = jmax (dx, sx) + w;
  76417. const int maxY = jmax (dy, sy) + h;
  76418. const BitmapData destData (*this, minX, minY, maxX - minX, maxY - minY, true);
  76419. uint8* dst = destData.getPixelPointer (dx - minX, dy - minY);
  76420. const uint8* src = destData.getPixelPointer (sx - minX, sy - minY);
  76421. const int lineSize = destData.pixelStride * w;
  76422. if (dy > sy)
  76423. {
  76424. while (--h >= 0)
  76425. {
  76426. const int offset = h * destData.lineStride;
  76427. memmove (dst + offset, src + offset, lineSize);
  76428. }
  76429. }
  76430. else if (dst != src)
  76431. {
  76432. while (--h >= 0)
  76433. {
  76434. memmove (dst, src, lineSize);
  76435. dst += destData.lineStride;
  76436. src += destData.lineStride;
  76437. }
  76438. }
  76439. }
  76440. }
  76441. END_JUCE_NAMESPACE
  76442. /*** End of inlined file: juce_Image.cpp ***/
  76443. /*** Start of inlined file: juce_ImageCache.cpp ***/
  76444. BEGIN_JUCE_NAMESPACE
  76445. class ImageCache::Pimpl : public Timer,
  76446. public DeletedAtShutdown
  76447. {
  76448. public:
  76449. Pimpl()
  76450. : cacheTimeout (5000)
  76451. {
  76452. }
  76453. ~Pimpl()
  76454. {
  76455. clearSingletonInstance();
  76456. }
  76457. const Image getFromHashCode (const int64 hashCode)
  76458. {
  76459. const ScopedLock sl (lock);
  76460. for (int i = images.size(); --i >= 0;)
  76461. {
  76462. Item* const item = images.getUnchecked(i);
  76463. if (item->hashCode == hashCode)
  76464. return item->image;
  76465. }
  76466. return Image();
  76467. }
  76468. void addImageToCache (const Image& image, const int64 hashCode)
  76469. {
  76470. if (image.isValid())
  76471. {
  76472. if (! isTimerRunning())
  76473. startTimer (2000);
  76474. Item* const item = new Item();
  76475. item->hashCode = hashCode;
  76476. item->image = image;
  76477. item->lastUseTime = Time::getApproximateMillisecondCounter();
  76478. const ScopedLock sl (lock);
  76479. images.add (item);
  76480. }
  76481. }
  76482. void timerCallback()
  76483. {
  76484. const uint32 now = Time::getApproximateMillisecondCounter();
  76485. const ScopedLock sl (lock);
  76486. for (int i = images.size(); --i >= 0;)
  76487. {
  76488. Item* const item = images.getUnchecked(i);
  76489. if (item->image.getReferenceCount() <= 1)
  76490. {
  76491. if (now > item->lastUseTime + cacheTimeout || now < item->lastUseTime - 1000)
  76492. images.remove (i);
  76493. }
  76494. else
  76495. {
  76496. item->lastUseTime = now; // multiply-referenced, so this image is still in use.
  76497. }
  76498. }
  76499. if (images.size() == 0)
  76500. stopTimer();
  76501. }
  76502. struct Item
  76503. {
  76504. Image image;
  76505. int64 hashCode;
  76506. uint32 lastUseTime;
  76507. };
  76508. int cacheTimeout;
  76509. juce_DeclareSingleton_SingleThreaded_Minimal (ImageCache::Pimpl);
  76510. private:
  76511. OwnedArray<Item> images;
  76512. CriticalSection lock;
  76513. Pimpl (const Pimpl&);
  76514. Pimpl& operator= (const Pimpl&);
  76515. };
  76516. juce_ImplementSingleton_SingleThreaded (ImageCache::Pimpl);
  76517. const Image ImageCache::getFromHashCode (const int64 hashCode)
  76518. {
  76519. if (Pimpl::getInstanceWithoutCreating() != 0)
  76520. return Pimpl::getInstanceWithoutCreating()->getFromHashCode (hashCode);
  76521. return Image();
  76522. }
  76523. void ImageCache::addImageToCache (const Image& image, const int64 hashCode)
  76524. {
  76525. Pimpl::getInstance()->addImageToCache (image, hashCode);
  76526. }
  76527. const Image ImageCache::getFromFile (const File& file)
  76528. {
  76529. const int64 hashCode = file.hashCode64();
  76530. Image image (getFromHashCode (hashCode));
  76531. if (image.isNull())
  76532. {
  76533. image = ImageFileFormat::loadFrom (file);
  76534. addImageToCache (image, hashCode);
  76535. }
  76536. return image;
  76537. }
  76538. const Image ImageCache::getFromMemory (const void* imageData, const int dataSize)
  76539. {
  76540. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  76541. Image image (getFromHashCode (hashCode));
  76542. if (image.isNull())
  76543. {
  76544. image = ImageFileFormat::loadFrom (imageData, dataSize);
  76545. addImageToCache (image, hashCode);
  76546. }
  76547. return image;
  76548. }
  76549. void ImageCache::setCacheTimeout (const int millisecs)
  76550. {
  76551. Pimpl::getInstance()->cacheTimeout = millisecs;
  76552. }
  76553. END_JUCE_NAMESPACE
  76554. /*** End of inlined file: juce_ImageCache.cpp ***/
  76555. /*** Start of inlined file: juce_ImageConvolutionKernel.cpp ***/
  76556. BEGIN_JUCE_NAMESPACE
  76557. ImageConvolutionKernel::ImageConvolutionKernel (const int size_)
  76558. : values (size_ * size_),
  76559. size (size_)
  76560. {
  76561. clear();
  76562. }
  76563. ImageConvolutionKernel::~ImageConvolutionKernel()
  76564. {
  76565. }
  76566. float ImageConvolutionKernel::getKernelValue (const int x, const int y) const throw()
  76567. {
  76568. if (((unsigned int) x) < (unsigned int) size
  76569. && ((unsigned int) y) < (unsigned int) size)
  76570. {
  76571. return values [x + y * size];
  76572. }
  76573. else
  76574. {
  76575. jassertfalse;
  76576. return 0;
  76577. }
  76578. }
  76579. void ImageConvolutionKernel::setKernelValue (const int x, const int y, const float value) throw()
  76580. {
  76581. if (((unsigned int) x) < (unsigned int) size
  76582. && ((unsigned int) y) < (unsigned int) size)
  76583. {
  76584. values [x + y * size] = value;
  76585. }
  76586. else
  76587. {
  76588. jassertfalse;
  76589. }
  76590. }
  76591. void ImageConvolutionKernel::clear()
  76592. {
  76593. for (int i = size * size; --i >= 0;)
  76594. values[i] = 0;
  76595. }
  76596. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum)
  76597. {
  76598. double currentTotal = 0.0;
  76599. for (int i = size * size; --i >= 0;)
  76600. currentTotal += values[i];
  76601. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  76602. }
  76603. void ImageConvolutionKernel::rescaleAllValues (const float multiplier)
  76604. {
  76605. for (int i = size * size; --i >= 0;)
  76606. values[i] *= multiplier;
  76607. }
  76608. void ImageConvolutionKernel::createGaussianBlur (const float radius)
  76609. {
  76610. const double radiusFactor = -1.0 / (radius * radius * 2);
  76611. const int centre = size >> 1;
  76612. for (int y = size; --y >= 0;)
  76613. {
  76614. for (int x = size; --x >= 0;)
  76615. {
  76616. const int cx = x - centre;
  76617. const int cy = y - centre;
  76618. values [x + y * size] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  76619. }
  76620. }
  76621. setOverallSum (1.0f);
  76622. }
  76623. void ImageConvolutionKernel::applyToImage (Image& destImage,
  76624. const Image& sourceImage,
  76625. const Rectangle<int>& destinationArea) const
  76626. {
  76627. if (sourceImage == destImage)
  76628. {
  76629. destImage.duplicateIfShared();
  76630. }
  76631. else
  76632. {
  76633. if (sourceImage.getWidth() != destImage.getWidth()
  76634. || sourceImage.getHeight() != destImage.getHeight()
  76635. || sourceImage.getFormat() != destImage.getFormat())
  76636. {
  76637. jassertfalse;
  76638. return;
  76639. }
  76640. }
  76641. const Rectangle<int> area (destinationArea.getIntersection (destImage.getBounds()));
  76642. if (area.isEmpty())
  76643. return;
  76644. const int right = area.getRight();
  76645. const int bottom = area.getBottom();
  76646. const Image::BitmapData destData (destImage, area.getX(), area.getY(), area.getWidth(), area.getHeight(), true);
  76647. uint8* line = destData.data;
  76648. const Image::BitmapData srcData (sourceImage, 0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  76649. if (destData.pixelStride == 4)
  76650. {
  76651. for (int y = area.getY(); y < bottom; ++y)
  76652. {
  76653. uint8* dest = line;
  76654. line += destData.lineStride;
  76655. for (int x = area.getX(); x < right; ++x)
  76656. {
  76657. float c1 = 0;
  76658. float c2 = 0;
  76659. float c3 = 0;
  76660. float c4 = 0;
  76661. for (int yy = 0; yy < size; ++yy)
  76662. {
  76663. const int sy = y + yy - (size >> 1);
  76664. if (sy >= srcData.height)
  76665. break;
  76666. if (sy >= 0)
  76667. {
  76668. int sx = x - (size >> 1);
  76669. const uint8* src = srcData.getPixelPointer (sx, sy);
  76670. for (int xx = 0; xx < size; ++xx)
  76671. {
  76672. if (sx >= srcData.width)
  76673. break;
  76674. if (sx >= 0)
  76675. {
  76676. const float kernelMult = values [xx + yy * size];
  76677. c1 += kernelMult * *src++;
  76678. c2 += kernelMult * *src++;
  76679. c3 += kernelMult * *src++;
  76680. c4 += kernelMult * *src++;
  76681. }
  76682. else
  76683. {
  76684. src += 4;
  76685. }
  76686. ++sx;
  76687. }
  76688. }
  76689. }
  76690. *dest++ = (uint8) jmin (0xff, roundToInt (c1));
  76691. *dest++ = (uint8) jmin (0xff, roundToInt (c2));
  76692. *dest++ = (uint8) jmin (0xff, roundToInt (c3));
  76693. *dest++ = (uint8) jmin (0xff, roundToInt (c4));
  76694. }
  76695. }
  76696. }
  76697. else if (destData.pixelStride == 3)
  76698. {
  76699. for (int y = area.getY(); y < bottom; ++y)
  76700. {
  76701. uint8* dest = line;
  76702. line += destData.lineStride;
  76703. for (int x = area.getX(); x < right; ++x)
  76704. {
  76705. float c1 = 0;
  76706. float c2 = 0;
  76707. float c3 = 0;
  76708. for (int yy = 0; yy < size; ++yy)
  76709. {
  76710. const int sy = y + yy - (size >> 1);
  76711. if (sy >= srcData.height)
  76712. break;
  76713. if (sy >= 0)
  76714. {
  76715. int sx = x - (size >> 1);
  76716. const uint8* src = srcData.getPixelPointer (sx, sy);
  76717. for (int xx = 0; xx < size; ++xx)
  76718. {
  76719. if (sx >= srcData.width)
  76720. break;
  76721. if (sx >= 0)
  76722. {
  76723. const float kernelMult = values [xx + yy * size];
  76724. c1 += kernelMult * *src++;
  76725. c2 += kernelMult * *src++;
  76726. c3 += kernelMult * *src++;
  76727. }
  76728. else
  76729. {
  76730. src += 3;
  76731. }
  76732. ++sx;
  76733. }
  76734. }
  76735. }
  76736. *dest++ = (uint8) roundToInt (c1);
  76737. *dest++ = (uint8) roundToInt (c2);
  76738. *dest++ = (uint8) roundToInt (c3);
  76739. }
  76740. }
  76741. }
  76742. }
  76743. END_JUCE_NAMESPACE
  76744. /*** End of inlined file: juce_ImageConvolutionKernel.cpp ***/
  76745. /*** Start of inlined file: juce_ImageFileFormat.cpp ***/
  76746. BEGIN_JUCE_NAMESPACE
  76747. /*** Start of inlined file: juce_GIFLoader.h ***/
  76748. #ifndef __JUCE_GIFLOADER_JUCEHEADER__
  76749. #define __JUCE_GIFLOADER_JUCEHEADER__
  76750. #ifndef DOXYGEN
  76751. /**
  76752. Used internally by ImageFileFormat - don't use this class directly in your
  76753. application.
  76754. @see ImageFileFormat
  76755. */
  76756. class GIFLoader
  76757. {
  76758. public:
  76759. GIFLoader (InputStream& in);
  76760. ~GIFLoader();
  76761. const Image& getImage() const { return image; }
  76762. private:
  76763. Image image;
  76764. InputStream& input;
  76765. uint8 buffer [300];
  76766. uint8 palette [256][4];
  76767. bool dataBlockIsZero, fresh, finished;
  76768. int currentBit, lastBit, lastByteIndex;
  76769. int codeSize, setCodeSize;
  76770. int maxCode, maxCodeSize;
  76771. int firstcode, oldcode;
  76772. int clearCode, end_code;
  76773. enum { maxGifCode = 1 << 12 };
  76774. int table [2] [maxGifCode];
  76775. int stack [2 * maxGifCode];
  76776. int *sp;
  76777. bool getSizeFromHeader (int& width, int& height);
  76778. bool readPalette (const int numCols);
  76779. int readDataBlock (unsigned char* dest);
  76780. int processExtension (int type, int& transparent);
  76781. int readLZWByte (bool initialise, int input_code_size);
  76782. int getCode (int code_size, bool initialise);
  76783. bool readImage (int width, int height, int interlace, int transparent);
  76784. static inline int makeWord (const uint8 a, const uint8 b) { return (b << 8) | a; }
  76785. GIFLoader (const GIFLoader&);
  76786. GIFLoader& operator= (const GIFLoader&);
  76787. };
  76788. #endif // DOXYGEN
  76789. #endif // __JUCE_GIFLOADER_JUCEHEADER__
  76790. /*** End of inlined file: juce_GIFLoader.h ***/
  76791. class GIFImageFormat : public ImageFileFormat
  76792. {
  76793. public:
  76794. GIFImageFormat() {}
  76795. ~GIFImageFormat() {}
  76796. const String getFormatName()
  76797. {
  76798. return "GIF";
  76799. }
  76800. bool canUnderstand (InputStream& in)
  76801. {
  76802. const int bytesNeeded = 4;
  76803. char header [bytesNeeded];
  76804. return (in.read (header, bytesNeeded) == bytesNeeded)
  76805. && header[0] == 'G'
  76806. && header[1] == 'I'
  76807. && header[2] == 'F';
  76808. }
  76809. const Image decodeImage (InputStream& in)
  76810. {
  76811. const ScopedPointer <GIFLoader> loader (new GIFLoader (in));
  76812. return loader->getImage();
  76813. }
  76814. bool writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  76815. {
  76816. return false;
  76817. }
  76818. };
  76819. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  76820. {
  76821. static PNGImageFormat png;
  76822. static JPEGImageFormat jpg;
  76823. static GIFImageFormat gif;
  76824. ImageFileFormat* formats[4];
  76825. int numFormats = 0;
  76826. formats [numFormats++] = &png;
  76827. formats [numFormats++] = &jpg;
  76828. formats [numFormats++] = &gif;
  76829. const int64 streamPos = input.getPosition();
  76830. for (int i = 0; i < numFormats; ++i)
  76831. {
  76832. const bool found = formats[i]->canUnderstand (input);
  76833. input.setPosition (streamPos);
  76834. if (found)
  76835. return formats[i];
  76836. }
  76837. return 0;
  76838. }
  76839. const Image ImageFileFormat::loadFrom (InputStream& input)
  76840. {
  76841. ImageFileFormat* const format = findImageFormatForStream (input);
  76842. if (format != 0)
  76843. return format->decodeImage (input);
  76844. return Image();
  76845. }
  76846. const Image ImageFileFormat::loadFrom (const File& file)
  76847. {
  76848. InputStream* const in = file.createInputStream();
  76849. if (in != 0)
  76850. {
  76851. BufferedInputStream b (in, 8192, true);
  76852. return loadFrom (b);
  76853. }
  76854. return Image();
  76855. }
  76856. const Image ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  76857. {
  76858. if (rawData != 0 && numBytes > 4)
  76859. {
  76860. MemoryInputStream stream (rawData, numBytes, false);
  76861. return loadFrom (stream);
  76862. }
  76863. return Image();
  76864. }
  76865. END_JUCE_NAMESPACE
  76866. /*** End of inlined file: juce_ImageFileFormat.cpp ***/
  76867. /*** Start of inlined file: juce_GIFLoader.cpp ***/
  76868. BEGIN_JUCE_NAMESPACE
  76869. GIFLoader::GIFLoader (InputStream& in)
  76870. : image (0),
  76871. input (in),
  76872. dataBlockIsZero (false),
  76873. fresh (false),
  76874. finished (false)
  76875. {
  76876. currentBit = lastBit = lastByteIndex = 0;
  76877. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  76878. firstcode = oldcode = 0;
  76879. clearCode = end_code = 0;
  76880. int imageWidth, imageHeight;
  76881. int transparent = -1;
  76882. if (! getSizeFromHeader (imageWidth, imageHeight))
  76883. return;
  76884. if ((imageWidth <= 0) || (imageHeight <= 0))
  76885. return;
  76886. unsigned char buf [16];
  76887. if (in.read (buf, 3) != 3)
  76888. return;
  76889. int numColours = 2 << (buf[0] & 7);
  76890. if ((buf[0] & 0x80) != 0)
  76891. readPalette (numColours);
  76892. for (;;)
  76893. {
  76894. if (input.read (buf, 1) != 1)
  76895. break;
  76896. if (buf[0] == ';')
  76897. break;
  76898. if (buf[0] == '!')
  76899. {
  76900. if (input.read (buf, 1) != 1)
  76901. break;
  76902. if (processExtension (buf[0], transparent) < 0)
  76903. break;
  76904. continue;
  76905. }
  76906. if (buf[0] != ',')
  76907. continue;
  76908. if (input.read (buf, 9) != 9)
  76909. break;
  76910. imageWidth = makeWord (buf[4], buf[5]);
  76911. imageHeight = makeWord (buf[6], buf[7]);
  76912. numColours = 2 << (buf[8] & 7);
  76913. if ((buf[8] & 0x80) != 0)
  76914. if (! readPalette (numColours))
  76915. break;
  76916. image = Image ((transparent >= 0) ? Image::ARGB : Image::RGB,
  76917. imageWidth, imageHeight, (transparent >= 0));
  76918. readImage (imageWidth, imageHeight,
  76919. (buf[8] & 0x40) != 0,
  76920. transparent);
  76921. break;
  76922. }
  76923. }
  76924. GIFLoader::~GIFLoader()
  76925. {
  76926. }
  76927. bool GIFLoader::getSizeFromHeader (int& w, int& h)
  76928. {
  76929. char b[8];
  76930. if (input.read (b, 6) == 6)
  76931. {
  76932. if ((strncmp ("GIF87a", b, 6) == 0)
  76933. || (strncmp ("GIF89a", b, 6) == 0))
  76934. {
  76935. if (input.read (b, 4) == 4)
  76936. {
  76937. w = makeWord (b[0], b[1]);
  76938. h = makeWord (b[2], b[3]);
  76939. return true;
  76940. }
  76941. }
  76942. }
  76943. return false;
  76944. }
  76945. bool GIFLoader::readPalette (const int numCols)
  76946. {
  76947. unsigned char rgb[4];
  76948. for (int i = 0; i < numCols; ++i)
  76949. {
  76950. input.read (rgb, 3);
  76951. palette [i][0] = rgb[0];
  76952. palette [i][1] = rgb[1];
  76953. palette [i][2] = rgb[2];
  76954. palette [i][3] = 0xff;
  76955. }
  76956. return true;
  76957. }
  76958. int GIFLoader::readDataBlock (unsigned char* const dest)
  76959. {
  76960. unsigned char n;
  76961. if (input.read (&n, 1) == 1)
  76962. {
  76963. dataBlockIsZero = (n == 0);
  76964. if (dataBlockIsZero || (input.read (dest, n) == n))
  76965. return n;
  76966. }
  76967. return -1;
  76968. }
  76969. int GIFLoader::processExtension (const int type, int& transparent)
  76970. {
  76971. unsigned char b [300];
  76972. int n = 0;
  76973. if (type == 0xf9)
  76974. {
  76975. n = readDataBlock (b);
  76976. if (n < 0)
  76977. return 1;
  76978. if ((b[0] & 0x1) != 0)
  76979. transparent = b[3];
  76980. }
  76981. do
  76982. {
  76983. n = readDataBlock (b);
  76984. }
  76985. while (n > 0);
  76986. return n;
  76987. }
  76988. int GIFLoader::getCode (const int codeSize_, const bool initialise)
  76989. {
  76990. if (initialise)
  76991. {
  76992. currentBit = 0;
  76993. lastBit = 0;
  76994. finished = false;
  76995. return 0;
  76996. }
  76997. if ((currentBit + codeSize_) >= lastBit)
  76998. {
  76999. if (finished)
  77000. return -1;
  77001. buffer[0] = buffer [lastByteIndex - 2];
  77002. buffer[1] = buffer [lastByteIndex - 1];
  77003. const int n = readDataBlock (&buffer[2]);
  77004. if (n == 0)
  77005. finished = true;
  77006. lastByteIndex = 2 + n;
  77007. currentBit = (currentBit - lastBit) + 16;
  77008. lastBit = (2 + n) * 8 ;
  77009. }
  77010. int result = 0;
  77011. int i = currentBit;
  77012. for (int j = 0; j < codeSize_; ++j)
  77013. {
  77014. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  77015. ++i;
  77016. }
  77017. currentBit += codeSize_;
  77018. return result;
  77019. }
  77020. int GIFLoader::readLZWByte (const bool initialise, const int inputCodeSize)
  77021. {
  77022. int code, incode, i;
  77023. if (initialise)
  77024. {
  77025. setCodeSize = inputCodeSize;
  77026. codeSize = setCodeSize + 1;
  77027. clearCode = 1 << setCodeSize;
  77028. end_code = clearCode + 1;
  77029. maxCodeSize = 2 * clearCode;
  77030. maxCode = clearCode + 2;
  77031. getCode (0, true);
  77032. fresh = true;
  77033. for (i = 0; i < clearCode; ++i)
  77034. {
  77035. table[0][i] = 0;
  77036. table[1][i] = i;
  77037. }
  77038. for (; i < maxGifCode; ++i)
  77039. {
  77040. table[0][i] = 0;
  77041. table[1][i] = 0;
  77042. }
  77043. sp = stack;
  77044. return 0;
  77045. }
  77046. else if (fresh)
  77047. {
  77048. fresh = false;
  77049. do
  77050. {
  77051. firstcode = oldcode
  77052. = getCode (codeSize, false);
  77053. }
  77054. while (firstcode == clearCode);
  77055. return firstcode;
  77056. }
  77057. if (sp > stack)
  77058. return *--sp;
  77059. while ((code = getCode (codeSize, false)) >= 0)
  77060. {
  77061. if (code == clearCode)
  77062. {
  77063. for (i = 0; i < clearCode; ++i)
  77064. {
  77065. table[0][i] = 0;
  77066. table[1][i] = i;
  77067. }
  77068. for (; i < maxGifCode; ++i)
  77069. {
  77070. table[0][i] = 0;
  77071. table[1][i] = 0;
  77072. }
  77073. codeSize = setCodeSize + 1;
  77074. maxCodeSize = 2 * clearCode;
  77075. maxCode = clearCode + 2;
  77076. sp = stack;
  77077. firstcode = oldcode = getCode (codeSize, false);
  77078. return firstcode;
  77079. }
  77080. else if (code == end_code)
  77081. {
  77082. if (dataBlockIsZero)
  77083. return -2;
  77084. unsigned char buf [260];
  77085. int n;
  77086. while ((n = readDataBlock (buf)) > 0)
  77087. {}
  77088. if (n != 0)
  77089. return -2;
  77090. }
  77091. incode = code;
  77092. if (code >= maxCode)
  77093. {
  77094. *sp++ = firstcode;
  77095. code = oldcode;
  77096. }
  77097. while (code >= clearCode)
  77098. {
  77099. *sp++ = table[1][code];
  77100. if (code == table[0][code])
  77101. return -2;
  77102. code = table[0][code];
  77103. }
  77104. *sp++ = firstcode = table[1][code];
  77105. if ((code = maxCode) < maxGifCode)
  77106. {
  77107. table[0][code] = oldcode;
  77108. table[1][code] = firstcode;
  77109. ++maxCode;
  77110. if ((maxCode >= maxCodeSize)
  77111. && (maxCodeSize < maxGifCode))
  77112. {
  77113. maxCodeSize <<= 1;
  77114. ++codeSize;
  77115. }
  77116. }
  77117. oldcode = incode;
  77118. if (sp > stack)
  77119. return *--sp;
  77120. }
  77121. return code;
  77122. }
  77123. bool GIFLoader::readImage (const int width, const int height,
  77124. const int interlace, const int transparent)
  77125. {
  77126. unsigned char c;
  77127. if (input.read (&c, 1) != 1
  77128. || readLZWByte (true, c) < 0)
  77129. return false;
  77130. if (transparent >= 0)
  77131. {
  77132. palette [transparent][0] = 0;
  77133. palette [transparent][1] = 0;
  77134. palette [transparent][2] = 0;
  77135. palette [transparent][3] = 0;
  77136. }
  77137. int index;
  77138. int xpos = 0, ypos = 0, pass = 0;
  77139. const Image::BitmapData destData (image, 0, 0, width, height, true);
  77140. uint8* p = destData.data;
  77141. const bool hasAlpha = image.hasAlphaChannel();
  77142. while ((index = readLZWByte (false, c)) >= 0)
  77143. {
  77144. const uint8* const paletteEntry = palette [index];
  77145. if (hasAlpha)
  77146. {
  77147. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  77148. paletteEntry[0],
  77149. paletteEntry[1],
  77150. paletteEntry[2]);
  77151. ((PixelARGB*) p)->premultiply();
  77152. }
  77153. else
  77154. {
  77155. ((PixelRGB*) p)->setARGB (0,
  77156. paletteEntry[0],
  77157. paletteEntry[1],
  77158. paletteEntry[2]);
  77159. }
  77160. p += destData.pixelStride;
  77161. ++xpos;
  77162. if (xpos == width)
  77163. {
  77164. xpos = 0;
  77165. if (interlace)
  77166. {
  77167. switch (pass)
  77168. {
  77169. case 0:
  77170. case 1: ypos += 8; break;
  77171. case 2: ypos += 4; break;
  77172. case 3: ypos += 2; break;
  77173. }
  77174. while (ypos >= height)
  77175. {
  77176. ++pass;
  77177. switch (pass)
  77178. {
  77179. case 1: ypos = 4; break;
  77180. case 2: ypos = 2; break;
  77181. case 3: ypos = 1; break;
  77182. default: return true;
  77183. }
  77184. }
  77185. }
  77186. else
  77187. {
  77188. ++ypos;
  77189. }
  77190. p = destData.getPixelPointer (xpos, ypos);
  77191. }
  77192. if (ypos >= height)
  77193. break;
  77194. }
  77195. return true;
  77196. }
  77197. END_JUCE_NAMESPACE
  77198. /*** End of inlined file: juce_GIFLoader.cpp ***/
  77199. #endif
  77200. //==============================================================================
  77201. // some files include lots of library code, so leave them to the end to avoid cluttering
  77202. // up the build for the clean files.
  77203. #if JUCE_BUILD_CORE
  77204. /*** Start of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  77205. namespace zlibNamespace
  77206. {
  77207. #if JUCE_INCLUDE_ZLIB_CODE
  77208. #undef OS_CODE
  77209. #undef fdopen
  77210. /*** Start of inlined file: zlib.h ***/
  77211. #ifndef ZLIB_H
  77212. #define ZLIB_H
  77213. /*** Start of inlined file: zconf.h ***/
  77214. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  77215. #ifndef ZCONF_H
  77216. #define ZCONF_H
  77217. // *** Just a few hacks here to make it compile nicely with Juce..
  77218. #define Z_PREFIX 1
  77219. #undef __MACTYPES__
  77220. #ifdef _MSC_VER
  77221. #pragma warning (disable : 4131 4127 4244 4267)
  77222. #endif
  77223. /*
  77224. * If you *really* need a unique prefix for all types and library functions,
  77225. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  77226. */
  77227. #ifdef Z_PREFIX
  77228. # define deflateInit_ z_deflateInit_
  77229. # define deflate z_deflate
  77230. # define deflateEnd z_deflateEnd
  77231. # define inflateInit_ z_inflateInit_
  77232. # define inflate z_inflate
  77233. # define inflateEnd z_inflateEnd
  77234. # define inflatePrime z_inflatePrime
  77235. # define inflateGetHeader z_inflateGetHeader
  77236. # define adler32_combine z_adler32_combine
  77237. # define crc32_combine z_crc32_combine
  77238. # define deflateInit2_ z_deflateInit2_
  77239. # define deflateSetDictionary z_deflateSetDictionary
  77240. # define deflateCopy z_deflateCopy
  77241. # define deflateReset z_deflateReset
  77242. # define deflateParams z_deflateParams
  77243. # define deflateBound z_deflateBound
  77244. # define deflatePrime z_deflatePrime
  77245. # define inflateInit2_ z_inflateInit2_
  77246. # define inflateSetDictionary z_inflateSetDictionary
  77247. # define inflateSync z_inflateSync
  77248. # define inflateSyncPoint z_inflateSyncPoint
  77249. # define inflateCopy z_inflateCopy
  77250. # define inflateReset z_inflateReset
  77251. # define inflateBack z_inflateBack
  77252. # define inflateBackEnd z_inflateBackEnd
  77253. # define compress z_compress
  77254. # define compress2 z_compress2
  77255. # define compressBound z_compressBound
  77256. # define uncompress z_uncompress
  77257. # define adler32 z_adler32
  77258. # define crc32 z_crc32
  77259. # define get_crc_table z_get_crc_table
  77260. # define zError z_zError
  77261. # define alloc_func z_alloc_func
  77262. # define free_func z_free_func
  77263. # define in_func z_in_func
  77264. # define out_func z_out_func
  77265. # define Byte z_Byte
  77266. # define uInt z_uInt
  77267. # define uLong z_uLong
  77268. # define Bytef z_Bytef
  77269. # define charf z_charf
  77270. # define intf z_intf
  77271. # define uIntf z_uIntf
  77272. # define uLongf z_uLongf
  77273. # define voidpf z_voidpf
  77274. # define voidp z_voidp
  77275. #endif
  77276. #if defined(__MSDOS__) && !defined(MSDOS)
  77277. # define MSDOS
  77278. #endif
  77279. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  77280. # define OS2
  77281. #endif
  77282. #if defined(_WINDOWS) && !defined(WINDOWS)
  77283. # define WINDOWS
  77284. #endif
  77285. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  77286. # ifndef WIN32
  77287. # define WIN32
  77288. # endif
  77289. #endif
  77290. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  77291. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  77292. # ifndef SYS16BIT
  77293. # define SYS16BIT
  77294. # endif
  77295. # endif
  77296. #endif
  77297. /*
  77298. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  77299. * than 64k bytes at a time (needed on systems with 16-bit int).
  77300. */
  77301. #ifdef SYS16BIT
  77302. # define MAXSEG_64K
  77303. #endif
  77304. #ifdef MSDOS
  77305. # define UNALIGNED_OK
  77306. #endif
  77307. #ifdef __STDC_VERSION__
  77308. # ifndef STDC
  77309. # define STDC
  77310. # endif
  77311. # if __STDC_VERSION__ >= 199901L
  77312. # ifndef STDC99
  77313. # define STDC99
  77314. # endif
  77315. # endif
  77316. #endif
  77317. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  77318. # define STDC
  77319. #endif
  77320. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  77321. # define STDC
  77322. #endif
  77323. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  77324. # define STDC
  77325. #endif
  77326. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  77327. # define STDC
  77328. #endif
  77329. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  77330. # define STDC
  77331. #endif
  77332. #ifndef STDC
  77333. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  77334. # define const /* note: need a more gentle solution here */
  77335. # endif
  77336. #endif
  77337. /* Some Mac compilers merge all .h files incorrectly: */
  77338. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  77339. # define NO_DUMMY_DECL
  77340. #endif
  77341. /* Maximum value for memLevel in deflateInit2 */
  77342. #ifndef MAX_MEM_LEVEL
  77343. # ifdef MAXSEG_64K
  77344. # define MAX_MEM_LEVEL 8
  77345. # else
  77346. # define MAX_MEM_LEVEL 9
  77347. # endif
  77348. #endif
  77349. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  77350. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  77351. * created by gzip. (Files created by minigzip can still be extracted by
  77352. * gzip.)
  77353. */
  77354. #ifndef MAX_WBITS
  77355. # define MAX_WBITS 15 /* 32K LZ77 window */
  77356. #endif
  77357. /* The memory requirements for deflate are (in bytes):
  77358. (1 << (windowBits+2)) + (1 << (memLevel+9))
  77359. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  77360. plus a few kilobytes for small objects. For example, if you want to reduce
  77361. the default memory requirements from 256K to 128K, compile with
  77362. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  77363. Of course this will generally degrade compression (there's no free lunch).
  77364. The memory requirements for inflate are (in bytes) 1 << windowBits
  77365. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  77366. for small objects.
  77367. */
  77368. /* Type declarations */
  77369. #ifndef OF /* function prototypes */
  77370. # ifdef STDC
  77371. # define OF(args) args
  77372. # else
  77373. # define OF(args) ()
  77374. # endif
  77375. #endif
  77376. /* The following definitions for FAR are needed only for MSDOS mixed
  77377. * model programming (small or medium model with some far allocations).
  77378. * This was tested only with MSC; for other MSDOS compilers you may have
  77379. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  77380. * just define FAR to be empty.
  77381. */
  77382. #ifdef SYS16BIT
  77383. # if defined(M_I86SM) || defined(M_I86MM)
  77384. /* MSC small or medium model */
  77385. # define SMALL_MEDIUM
  77386. # ifdef _MSC_VER
  77387. # define FAR _far
  77388. # else
  77389. # define FAR far
  77390. # endif
  77391. # endif
  77392. # if (defined(__SMALL__) || defined(__MEDIUM__))
  77393. /* Turbo C small or medium model */
  77394. # define SMALL_MEDIUM
  77395. # ifdef __BORLANDC__
  77396. # define FAR _far
  77397. # else
  77398. # define FAR far
  77399. # endif
  77400. # endif
  77401. #endif
  77402. #if defined(WINDOWS) || defined(WIN32)
  77403. /* If building or using zlib as a DLL, define ZLIB_DLL.
  77404. * This is not mandatory, but it offers a little performance increase.
  77405. */
  77406. # ifdef ZLIB_DLL
  77407. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  77408. # ifdef ZLIB_INTERNAL
  77409. # define ZEXTERN extern __declspec(dllexport)
  77410. # else
  77411. # define ZEXTERN extern __declspec(dllimport)
  77412. # endif
  77413. # endif
  77414. # endif /* ZLIB_DLL */
  77415. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  77416. * define ZLIB_WINAPI.
  77417. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  77418. */
  77419. # ifdef ZLIB_WINAPI
  77420. # ifdef FAR
  77421. # undef FAR
  77422. # endif
  77423. # include <windows.h>
  77424. /* No need for _export, use ZLIB.DEF instead. */
  77425. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  77426. # define ZEXPORT WINAPI
  77427. # ifdef WIN32
  77428. # define ZEXPORTVA WINAPIV
  77429. # else
  77430. # define ZEXPORTVA FAR CDECL
  77431. # endif
  77432. # endif
  77433. #endif
  77434. #if defined (__BEOS__)
  77435. # ifdef ZLIB_DLL
  77436. # ifdef ZLIB_INTERNAL
  77437. # define ZEXPORT __declspec(dllexport)
  77438. # define ZEXPORTVA __declspec(dllexport)
  77439. # else
  77440. # define ZEXPORT __declspec(dllimport)
  77441. # define ZEXPORTVA __declspec(dllimport)
  77442. # endif
  77443. # endif
  77444. #endif
  77445. #ifndef ZEXTERN
  77446. # define ZEXTERN extern
  77447. #endif
  77448. #ifndef ZEXPORT
  77449. # define ZEXPORT
  77450. #endif
  77451. #ifndef ZEXPORTVA
  77452. # define ZEXPORTVA
  77453. #endif
  77454. #ifndef FAR
  77455. # define FAR
  77456. #endif
  77457. #if !defined(__MACTYPES__)
  77458. typedef unsigned char Byte; /* 8 bits */
  77459. #endif
  77460. typedef unsigned int uInt; /* 16 bits or more */
  77461. typedef unsigned long uLong; /* 32 bits or more */
  77462. #ifdef SMALL_MEDIUM
  77463. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  77464. # define Bytef Byte FAR
  77465. #else
  77466. typedef Byte FAR Bytef;
  77467. #endif
  77468. typedef char FAR charf;
  77469. typedef int FAR intf;
  77470. typedef uInt FAR uIntf;
  77471. typedef uLong FAR uLongf;
  77472. #ifdef STDC
  77473. typedef void const *voidpc;
  77474. typedef void FAR *voidpf;
  77475. typedef void *voidp;
  77476. #else
  77477. typedef Byte const *voidpc;
  77478. typedef Byte FAR *voidpf;
  77479. typedef Byte *voidp;
  77480. #endif
  77481. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  77482. # include <sys/types.h> /* for off_t */
  77483. # include <unistd.h> /* for SEEK_* and off_t */
  77484. # ifdef VMS
  77485. # include <unixio.h> /* for off_t */
  77486. # endif
  77487. # define z_off_t off_t
  77488. #endif
  77489. #ifndef SEEK_SET
  77490. # define SEEK_SET 0 /* Seek from beginning of file. */
  77491. # define SEEK_CUR 1 /* Seek from current position. */
  77492. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  77493. #endif
  77494. #ifndef z_off_t
  77495. # define z_off_t long
  77496. #endif
  77497. #if defined(__OS400__)
  77498. # define NO_vsnprintf
  77499. #endif
  77500. #if defined(__MVS__)
  77501. # define NO_vsnprintf
  77502. # ifdef FAR
  77503. # undef FAR
  77504. # endif
  77505. #endif
  77506. /* MVS linker does not support external names larger than 8 bytes */
  77507. #if defined(__MVS__)
  77508. # pragma map(deflateInit_,"DEIN")
  77509. # pragma map(deflateInit2_,"DEIN2")
  77510. # pragma map(deflateEnd,"DEEND")
  77511. # pragma map(deflateBound,"DEBND")
  77512. # pragma map(inflateInit_,"ININ")
  77513. # pragma map(inflateInit2_,"ININ2")
  77514. # pragma map(inflateEnd,"INEND")
  77515. # pragma map(inflateSync,"INSY")
  77516. # pragma map(inflateSetDictionary,"INSEDI")
  77517. # pragma map(compressBound,"CMBND")
  77518. # pragma map(inflate_table,"INTABL")
  77519. # pragma map(inflate_fast,"INFA")
  77520. # pragma map(inflate_copyright,"INCOPY")
  77521. #endif
  77522. #endif /* ZCONF_H */
  77523. /*** End of inlined file: zconf.h ***/
  77524. #ifdef __cplusplus
  77525. extern "C" {
  77526. #endif
  77527. #define ZLIB_VERSION "1.2.3"
  77528. #define ZLIB_VERNUM 0x1230
  77529. /*
  77530. The 'zlib' compression library provides in-memory compression and
  77531. decompression functions, including integrity checks of the uncompressed
  77532. data. This version of the library supports only one compression method
  77533. (deflation) but other algorithms will be added later and will have the same
  77534. stream interface.
  77535. Compression can be done in a single step if the buffers are large
  77536. enough (for example if an input file is mmap'ed), or can be done by
  77537. repeated calls of the compression function. In the latter case, the
  77538. application must provide more input and/or consume the output
  77539. (providing more output space) before each call.
  77540. The compressed data format used by default by the in-memory functions is
  77541. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  77542. around a deflate stream, which is itself documented in RFC 1951.
  77543. The library also supports reading and writing files in gzip (.gz) format
  77544. with an interface similar to that of stdio using the functions that start
  77545. with "gz". The gzip format is different from the zlib format. gzip is a
  77546. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  77547. This library can optionally read and write gzip streams in memory as well.
  77548. The zlib format was designed to be compact and fast for use in memory
  77549. and on communications channels. The gzip format was designed for single-
  77550. file compression on file systems, has a larger header than zlib to maintain
  77551. directory information, and uses a different, slower check method than zlib.
  77552. The library does not install any signal handler. The decoder checks
  77553. the consistency of the compressed data, so the library should never
  77554. crash even in case of corrupted input.
  77555. */
  77556. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  77557. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  77558. struct internal_state;
  77559. typedef struct z_stream_s {
  77560. Bytef *next_in; /* next input byte */
  77561. uInt avail_in; /* number of bytes available at next_in */
  77562. uLong total_in; /* total nb of input bytes read so far */
  77563. Bytef *next_out; /* next output byte should be put there */
  77564. uInt avail_out; /* remaining free space at next_out */
  77565. uLong total_out; /* total nb of bytes output so far */
  77566. char *msg; /* last error message, NULL if no error */
  77567. struct internal_state FAR *state; /* not visible by applications */
  77568. alloc_func zalloc; /* used to allocate the internal state */
  77569. free_func zfree; /* used to free the internal state */
  77570. voidpf opaque; /* private data object passed to zalloc and zfree */
  77571. int data_type; /* best guess about the data type: binary or text */
  77572. uLong adler; /* adler32 value of the uncompressed data */
  77573. uLong reserved; /* reserved for future use */
  77574. } z_stream;
  77575. typedef z_stream FAR *z_streamp;
  77576. /*
  77577. gzip header information passed to and from zlib routines. See RFC 1952
  77578. for more details on the meanings of these fields.
  77579. */
  77580. typedef struct gz_header_s {
  77581. int text; /* true if compressed data believed to be text */
  77582. uLong time; /* modification time */
  77583. int xflags; /* extra flags (not used when writing a gzip file) */
  77584. int os; /* operating system */
  77585. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  77586. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  77587. uInt extra_max; /* space at extra (only when reading header) */
  77588. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  77589. uInt name_max; /* space at name (only when reading header) */
  77590. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  77591. uInt comm_max; /* space at comment (only when reading header) */
  77592. int hcrc; /* true if there was or will be a header crc */
  77593. int done; /* true when done reading gzip header (not used
  77594. when writing a gzip file) */
  77595. } gz_header;
  77596. typedef gz_header FAR *gz_headerp;
  77597. /*
  77598. The application must update next_in and avail_in when avail_in has
  77599. dropped to zero. It must update next_out and avail_out when avail_out
  77600. has dropped to zero. The application must initialize zalloc, zfree and
  77601. opaque before calling the init function. All other fields are set by the
  77602. compression library and must not be updated by the application.
  77603. The opaque value provided by the application will be passed as the first
  77604. parameter for calls of zalloc and zfree. This can be useful for custom
  77605. memory management. The compression library attaches no meaning to the
  77606. opaque value.
  77607. zalloc must return Z_NULL if there is not enough memory for the object.
  77608. If zlib is used in a multi-threaded application, zalloc and zfree must be
  77609. thread safe.
  77610. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  77611. exactly 65536 bytes, but will not be required to allocate more than this
  77612. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  77613. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  77614. have their offset normalized to zero. The default allocation function
  77615. provided by this library ensures this (see zutil.c). To reduce memory
  77616. requirements and avoid any allocation of 64K objects, at the expense of
  77617. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  77618. The fields total_in and total_out can be used for statistics or
  77619. progress reports. After compression, total_in holds the total size of
  77620. the uncompressed data and may be saved for use in the decompressor
  77621. (particularly if the decompressor wants to decompress everything in
  77622. a single step).
  77623. */
  77624. /* constants */
  77625. #define Z_NO_FLUSH 0
  77626. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  77627. #define Z_SYNC_FLUSH 2
  77628. #define Z_FULL_FLUSH 3
  77629. #define Z_FINISH 4
  77630. #define Z_BLOCK 5
  77631. /* Allowed flush values; see deflate() and inflate() below for details */
  77632. #define Z_OK 0
  77633. #define Z_STREAM_END 1
  77634. #define Z_NEED_DICT 2
  77635. #define Z_ERRNO (-1)
  77636. #define Z_STREAM_ERROR (-2)
  77637. #define Z_DATA_ERROR (-3)
  77638. #define Z_MEM_ERROR (-4)
  77639. #define Z_BUF_ERROR (-5)
  77640. #define Z_VERSION_ERROR (-6)
  77641. /* Return codes for the compression/decompression functions. Negative
  77642. * values are errors, positive values are used for special but normal events.
  77643. */
  77644. #define Z_NO_COMPRESSION 0
  77645. #define Z_BEST_SPEED 1
  77646. #define Z_BEST_COMPRESSION 9
  77647. #define Z_DEFAULT_COMPRESSION (-1)
  77648. /* compression levels */
  77649. #define Z_FILTERED 1
  77650. #define Z_HUFFMAN_ONLY 2
  77651. #define Z_RLE 3
  77652. #define Z_FIXED 4
  77653. #define Z_DEFAULT_STRATEGY 0
  77654. /* compression strategy; see deflateInit2() below for details */
  77655. #define Z_BINARY 0
  77656. #define Z_TEXT 1
  77657. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  77658. #define Z_UNKNOWN 2
  77659. /* Possible values of the data_type field (though see inflate()) */
  77660. #define Z_DEFLATED 8
  77661. /* The deflate compression method (the only one supported in this version) */
  77662. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  77663. #define zlib_version zlibVersion()
  77664. /* for compatibility with versions < 1.0.2 */
  77665. /* basic functions */
  77666. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  77667. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  77668. If the first character differs, the library code actually used is
  77669. not compatible with the zlib.h header file used by the application.
  77670. This check is automatically made by deflateInit and inflateInit.
  77671. */
  77672. /*
  77673. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  77674. Initializes the internal stream state for compression. The fields
  77675. zalloc, zfree and opaque must be initialized before by the caller.
  77676. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  77677. use default allocation functions.
  77678. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  77679. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  77680. all (the input data is simply copied a block at a time).
  77681. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  77682. compression (currently equivalent to level 6).
  77683. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  77684. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  77685. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  77686. with the version assumed by the caller (ZLIB_VERSION).
  77687. msg is set to null if there is no error message. deflateInit does not
  77688. perform any compression: this will be done by deflate().
  77689. */
  77690. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  77691. /*
  77692. deflate compresses as much data as possible, and stops when the input
  77693. buffer becomes empty or the output buffer becomes full. It may introduce some
  77694. output latency (reading input without producing any output) except when
  77695. forced to flush.
  77696. The detailed semantics are as follows. deflate performs one or both of the
  77697. following actions:
  77698. - Compress more input starting at next_in and update next_in and avail_in
  77699. accordingly. If not all input can be processed (because there is not
  77700. enough room in the output buffer), next_in and avail_in are updated and
  77701. processing will resume at this point for the next call of deflate().
  77702. - Provide more output starting at next_out and update next_out and avail_out
  77703. accordingly. This action is forced if the parameter flush is non zero.
  77704. Forcing flush frequently degrades the compression ratio, so this parameter
  77705. should be set only when necessary (in interactive applications).
  77706. Some output may be provided even if flush is not set.
  77707. Before the call of deflate(), the application should ensure that at least
  77708. one of the actions is possible, by providing more input and/or consuming
  77709. more output, and updating avail_in or avail_out accordingly; avail_out
  77710. should never be zero before the call. The application can consume the
  77711. compressed output when it wants, for example when the output buffer is full
  77712. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  77713. and with zero avail_out, it must be called again after making room in the
  77714. output buffer because there might be more output pending.
  77715. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  77716. decide how much data to accumualte before producing output, in order to
  77717. maximize compression.
  77718. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  77719. flushed to the output buffer and the output is aligned on a byte boundary, so
  77720. that the decompressor can get all input data available so far. (In particular
  77721. avail_in is zero after the call if enough output space has been provided
  77722. before the call.) Flushing may degrade compression for some compression
  77723. algorithms and so it should be used only when necessary.
  77724. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  77725. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  77726. restart from this point if previous compressed data has been damaged or if
  77727. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  77728. compression.
  77729. If deflate returns with avail_out == 0, this function must be called again
  77730. with the same value of the flush parameter and more output space (updated
  77731. avail_out), until the flush is complete (deflate returns with non-zero
  77732. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  77733. avail_out is greater than six to avoid repeated flush markers due to
  77734. avail_out == 0 on return.
  77735. If the parameter flush is set to Z_FINISH, pending input is processed,
  77736. pending output is flushed and deflate returns with Z_STREAM_END if there
  77737. was enough output space; if deflate returns with Z_OK, this function must be
  77738. called again with Z_FINISH and more output space (updated avail_out) but no
  77739. more input data, until it returns with Z_STREAM_END or an error. After
  77740. deflate has returned Z_STREAM_END, the only possible operations on the
  77741. stream are deflateReset or deflateEnd.
  77742. Z_FINISH can be used immediately after deflateInit if all the compression
  77743. is to be done in a single step. In this case, avail_out must be at least
  77744. the value returned by deflateBound (see below). If deflate does not return
  77745. Z_STREAM_END, then it must be called again as described above.
  77746. deflate() sets strm->adler to the adler32 checksum of all input read
  77747. so far (that is, total_in bytes).
  77748. deflate() may update strm->data_type if it can make a good guess about
  77749. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  77750. binary. This field is only for information purposes and does not affect
  77751. the compression algorithm in any manner.
  77752. deflate() returns Z_OK if some progress has been made (more input
  77753. processed or more output produced), Z_STREAM_END if all input has been
  77754. consumed and all output has been produced (only when flush is set to
  77755. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  77756. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  77757. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  77758. fatal, and deflate() can be called again with more input and more output
  77759. space to continue compressing.
  77760. */
  77761. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  77762. /*
  77763. All dynamically allocated data structures for this stream are freed.
  77764. This function discards any unprocessed input and does not flush any
  77765. pending output.
  77766. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  77767. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  77768. prematurely (some input or output was discarded). In the error case,
  77769. msg may be set but then points to a static string (which must not be
  77770. deallocated).
  77771. */
  77772. /*
  77773. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  77774. Initializes the internal stream state for decompression. The fields
  77775. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  77776. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  77777. value depends on the compression method), inflateInit determines the
  77778. compression method from the zlib header and allocates all data structures
  77779. accordingly; otherwise the allocation will be deferred to the first call of
  77780. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  77781. use default allocation functions.
  77782. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  77783. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  77784. version assumed by the caller. msg is set to null if there is no error
  77785. message. inflateInit does not perform any decompression apart from reading
  77786. the zlib header if present: this will be done by inflate(). (So next_in and
  77787. avail_in may be modified, but next_out and avail_out are unchanged.)
  77788. */
  77789. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  77790. /*
  77791. inflate decompresses as much data as possible, and stops when the input
  77792. buffer becomes empty or the output buffer becomes full. It may introduce
  77793. some output latency (reading input without producing any output) except when
  77794. forced to flush.
  77795. The detailed semantics are as follows. inflate performs one or both of the
  77796. following actions:
  77797. - Decompress more input starting at next_in and update next_in and avail_in
  77798. accordingly. If not all input can be processed (because there is not
  77799. enough room in the output buffer), next_in is updated and processing
  77800. will resume at this point for the next call of inflate().
  77801. - Provide more output starting at next_out and update next_out and avail_out
  77802. accordingly. inflate() provides as much output as possible, until there
  77803. is no more input data or no more space in the output buffer (see below
  77804. about the flush parameter).
  77805. Before the call of inflate(), the application should ensure that at least
  77806. one of the actions is possible, by providing more input and/or consuming
  77807. more output, and updating the next_* and avail_* values accordingly.
  77808. The application can consume the uncompressed output when it wants, for
  77809. example when the output buffer is full (avail_out == 0), or after each
  77810. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  77811. must be called again after making room in the output buffer because there
  77812. might be more output pending.
  77813. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  77814. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  77815. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  77816. if and when it gets to the next deflate block boundary. When decoding the
  77817. zlib or gzip format, this will cause inflate() to return immediately after
  77818. the header and before the first block. When doing a raw inflate, inflate()
  77819. will go ahead and process the first block, and will return when it gets to
  77820. the end of that block, or when it runs out of data.
  77821. The Z_BLOCK option assists in appending to or combining deflate streams.
  77822. Also to assist in this, on return inflate() will set strm->data_type to the
  77823. number of unused bits in the last byte taken from strm->next_in, plus 64
  77824. if inflate() is currently decoding the last block in the deflate stream,
  77825. plus 128 if inflate() returned immediately after decoding an end-of-block
  77826. code or decoding the complete header up to just before the first byte of the
  77827. deflate stream. The end-of-block will not be indicated until all of the
  77828. uncompressed data from that block has been written to strm->next_out. The
  77829. number of unused bits may in general be greater than seven, except when
  77830. bit 7 of data_type is set, in which case the number of unused bits will be
  77831. less than eight.
  77832. inflate() should normally be called until it returns Z_STREAM_END or an
  77833. error. However if all decompression is to be performed in a single step
  77834. (a single call of inflate), the parameter flush should be set to
  77835. Z_FINISH. In this case all pending input is processed and all pending
  77836. output is flushed; avail_out must be large enough to hold all the
  77837. uncompressed data. (The size of the uncompressed data may have been saved
  77838. by the compressor for this purpose.) The next operation on this stream must
  77839. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  77840. is never required, but can be used to inform inflate that a faster approach
  77841. may be used for the single inflate() call.
  77842. In this implementation, inflate() always flushes as much output as
  77843. possible to the output buffer, and always uses the faster approach on the
  77844. first call. So the only effect of the flush parameter in this implementation
  77845. is on the return value of inflate(), as noted below, or when it returns early
  77846. because Z_BLOCK is used.
  77847. If a preset dictionary is needed after this call (see inflateSetDictionary
  77848. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  77849. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  77850. strm->adler to the adler32 checksum of all output produced so far (that is,
  77851. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  77852. below. At the end of the stream, inflate() checks that its computed adler32
  77853. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  77854. only if the checksum is correct.
  77855. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  77856. deflate data. The header type is detected automatically. Any information
  77857. contained in the gzip header is not retained, so applications that need that
  77858. information should instead use raw inflate, see inflateInit2() below, or
  77859. inflateBack() and perform their own processing of the gzip header and
  77860. trailer.
  77861. inflate() returns Z_OK if some progress has been made (more input processed
  77862. or more output produced), Z_STREAM_END if the end of the compressed data has
  77863. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  77864. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  77865. corrupted (input stream not conforming to the zlib format or incorrect check
  77866. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  77867. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  77868. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  77869. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  77870. inflate() can be called again with more input and more output space to
  77871. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  77872. call inflateSync() to look for a good compression block if a partial recovery
  77873. of the data is desired.
  77874. */
  77875. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  77876. /*
  77877. All dynamically allocated data structures for this stream are freed.
  77878. This function discards any unprocessed input and does not flush any
  77879. pending output.
  77880. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  77881. was inconsistent. In the error case, msg may be set but then points to a
  77882. static string (which must not be deallocated).
  77883. */
  77884. /* Advanced functions */
  77885. /*
  77886. The following functions are needed only in some special applications.
  77887. */
  77888. /*
  77889. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  77890. int level,
  77891. int method,
  77892. int windowBits,
  77893. int memLevel,
  77894. int strategy));
  77895. This is another version of deflateInit with more compression options. The
  77896. fields next_in, zalloc, zfree and opaque must be initialized before by
  77897. the caller.
  77898. The method parameter is the compression method. It must be Z_DEFLATED in
  77899. this version of the library.
  77900. The windowBits parameter is the base two logarithm of the window size
  77901. (the size of the history buffer). It should be in the range 8..15 for this
  77902. version of the library. Larger values of this parameter result in better
  77903. compression at the expense of memory usage. The default value is 15 if
  77904. deflateInit is used instead.
  77905. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  77906. determines the window size. deflate() will then generate raw deflate data
  77907. with no zlib header or trailer, and will not compute an adler32 check value.
  77908. windowBits can also be greater than 15 for optional gzip encoding. Add
  77909. 16 to windowBits to write a simple gzip header and trailer around the
  77910. compressed data instead of a zlib wrapper. The gzip header will have no
  77911. file name, no extra data, no comment, no modification time (set to zero),
  77912. no header crc, and the operating system will be set to 255 (unknown). If a
  77913. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  77914. The memLevel parameter specifies how much memory should be allocated
  77915. for the internal compression state. memLevel=1 uses minimum memory but
  77916. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  77917. for optimal speed. The default value is 8. See zconf.h for total memory
  77918. usage as a function of windowBits and memLevel.
  77919. The strategy parameter is used to tune the compression algorithm. Use the
  77920. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  77921. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  77922. string match), or Z_RLE to limit match distances to one (run-length
  77923. encoding). Filtered data consists mostly of small values with a somewhat
  77924. random distribution. In this case, the compression algorithm is tuned to
  77925. compress them better. The effect of Z_FILTERED is to force more Huffman
  77926. coding and less string matching; it is somewhat intermediate between
  77927. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  77928. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  77929. parameter only affects the compression ratio but not the correctness of the
  77930. compressed output even if it is not set appropriately. Z_FIXED prevents the
  77931. use of dynamic Huffman codes, allowing for a simpler decoder for special
  77932. applications.
  77933. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  77934. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  77935. method). msg is set to null if there is no error message. deflateInit2 does
  77936. not perform any compression: this will be done by deflate().
  77937. */
  77938. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  77939. const Bytef *dictionary,
  77940. uInt dictLength));
  77941. /*
  77942. Initializes the compression dictionary from the given byte sequence
  77943. without producing any compressed output. This function must be called
  77944. immediately after deflateInit, deflateInit2 or deflateReset, before any
  77945. call of deflate. The compressor and decompressor must use exactly the same
  77946. dictionary (see inflateSetDictionary).
  77947. The dictionary should consist of strings (byte sequences) that are likely
  77948. to be encountered later in the data to be compressed, with the most commonly
  77949. used strings preferably put towards the end of the dictionary. Using a
  77950. dictionary is most useful when the data to be compressed is short and can be
  77951. predicted with good accuracy; the data can then be compressed better than
  77952. with the default empty dictionary.
  77953. Depending on the size of the compression data structures selected by
  77954. deflateInit or deflateInit2, a part of the dictionary may in effect be
  77955. discarded, for example if the dictionary is larger than the window size in
  77956. deflate or deflate2. Thus the strings most likely to be useful should be
  77957. put at the end of the dictionary, not at the front. In addition, the
  77958. current implementation of deflate will use at most the window size minus
  77959. 262 bytes of the provided dictionary.
  77960. Upon return of this function, strm->adler is set to the adler32 value
  77961. of the dictionary; the decompressor may later use this value to determine
  77962. which dictionary has been used by the compressor. (The adler32 value
  77963. applies to the whole dictionary even if only a subset of the dictionary is
  77964. actually used by the compressor.) If a raw deflate was requested, then the
  77965. adler32 value is not computed and strm->adler is not set.
  77966. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  77967. parameter is invalid (such as NULL dictionary) or the stream state is
  77968. inconsistent (for example if deflate has already been called for this stream
  77969. or if the compression method is bsort). deflateSetDictionary does not
  77970. perform any compression: this will be done by deflate().
  77971. */
  77972. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  77973. z_streamp source));
  77974. /*
  77975. Sets the destination stream as a complete copy of the source stream.
  77976. This function can be useful when several compression strategies will be
  77977. tried, for example when there are several ways of pre-processing the input
  77978. data with a filter. The streams that will be discarded should then be freed
  77979. by calling deflateEnd. Note that deflateCopy duplicates the internal
  77980. compression state which can be quite large, so this strategy is slow and
  77981. can consume lots of memory.
  77982. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  77983. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  77984. (such as zalloc being NULL). msg is left unchanged in both source and
  77985. destination.
  77986. */
  77987. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  77988. /*
  77989. This function is equivalent to deflateEnd followed by deflateInit,
  77990. but does not free and reallocate all the internal compression state.
  77991. The stream will keep the same compression level and any other attributes
  77992. that may have been set by deflateInit2.
  77993. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  77994. stream state was inconsistent (such as zalloc or state being NULL).
  77995. */
  77996. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  77997. int level,
  77998. int strategy));
  77999. /*
  78000. Dynamically update the compression level and compression strategy. The
  78001. interpretation of level and strategy is as in deflateInit2. This can be
  78002. used to switch between compression and straight copy of the input data, or
  78003. to switch to a different kind of input data requiring a different
  78004. strategy. If the compression level is changed, the input available so far
  78005. is compressed with the old level (and may be flushed); the new level will
  78006. take effect only at the next call of deflate().
  78007. Before the call of deflateParams, the stream state must be set as for
  78008. a call of deflate(), since the currently available input may have to
  78009. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  78010. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  78011. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  78012. if strm->avail_out was zero.
  78013. */
  78014. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  78015. int good_length,
  78016. int max_lazy,
  78017. int nice_length,
  78018. int max_chain));
  78019. /*
  78020. Fine tune deflate's internal compression parameters. This should only be
  78021. used by someone who understands the algorithm used by zlib's deflate for
  78022. searching for the best matching string, and even then only by the most
  78023. fanatic optimizer trying to squeeze out the last compressed bit for their
  78024. specific input data. Read the deflate.c source code for the meaning of the
  78025. max_lazy, good_length, nice_length, and max_chain parameters.
  78026. deflateTune() can be called after deflateInit() or deflateInit2(), and
  78027. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  78028. */
  78029. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  78030. uLong sourceLen));
  78031. /*
  78032. deflateBound() returns an upper bound on the compressed size after
  78033. deflation of sourceLen bytes. It must be called after deflateInit()
  78034. or deflateInit2(). This would be used to allocate an output buffer
  78035. for deflation in a single pass, and so would be called before deflate().
  78036. */
  78037. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  78038. int bits,
  78039. int value));
  78040. /*
  78041. deflatePrime() inserts bits in the deflate output stream. The intent
  78042. is that this function is used to start off the deflate output with the
  78043. bits leftover from a previous deflate stream when appending to it. As such,
  78044. this function can only be used for raw deflate, and must be used before the
  78045. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  78046. less than or equal to 16, and that many of the least significant bits of
  78047. value will be inserted in the output.
  78048. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  78049. stream state was inconsistent.
  78050. */
  78051. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  78052. gz_headerp head));
  78053. /*
  78054. deflateSetHeader() provides gzip header information for when a gzip
  78055. stream is requested by deflateInit2(). deflateSetHeader() may be called
  78056. after deflateInit2() or deflateReset() and before the first call of
  78057. deflate(). The text, time, os, extra field, name, and comment information
  78058. in the provided gz_header structure are written to the gzip header (xflag is
  78059. ignored -- the extra flags are set according to the compression level). The
  78060. caller must assure that, if not Z_NULL, name and comment are terminated with
  78061. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  78062. available there. If hcrc is true, a gzip header crc is included. Note that
  78063. the current versions of the command-line version of gzip (up through version
  78064. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  78065. gzip file" and give up.
  78066. If deflateSetHeader is not used, the default gzip header has text false,
  78067. the time set to zero, and os set to 255, with no extra, name, or comment
  78068. fields. The gzip header is returned to the default state by deflateReset().
  78069. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  78070. stream state was inconsistent.
  78071. */
  78072. /*
  78073. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  78074. int windowBits));
  78075. This is another version of inflateInit with an extra parameter. The
  78076. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  78077. before by the caller.
  78078. The windowBits parameter is the base two logarithm of the maximum window
  78079. size (the size of the history buffer). It should be in the range 8..15 for
  78080. this version of the library. The default value is 15 if inflateInit is used
  78081. instead. windowBits must be greater than or equal to the windowBits value
  78082. provided to deflateInit2() while compressing, or it must be equal to 15 if
  78083. deflateInit2() was not used. If a compressed stream with a larger window
  78084. size is given as input, inflate() will return with the error code
  78085. Z_DATA_ERROR instead of trying to allocate a larger window.
  78086. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  78087. determines the window size. inflate() will then process raw deflate data,
  78088. not looking for a zlib or gzip header, not generating a check value, and not
  78089. looking for any check values for comparison at the end of the stream. This
  78090. is for use with other formats that use the deflate compressed data format
  78091. such as zip. Those formats provide their own check values. If a custom
  78092. format is developed using the raw deflate format for compressed data, it is
  78093. recommended that a check value such as an adler32 or a crc32 be applied to
  78094. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  78095. most applications, the zlib format should be used as is. Note that comments
  78096. above on the use in deflateInit2() applies to the magnitude of windowBits.
  78097. windowBits can also be greater than 15 for optional gzip decoding. Add
  78098. 32 to windowBits to enable zlib and gzip decoding with automatic header
  78099. detection, or add 16 to decode only the gzip format (the zlib format will
  78100. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  78101. a crc32 instead of an adler32.
  78102. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78103. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  78104. is set to null if there is no error message. inflateInit2 does not perform
  78105. any decompression apart from reading the zlib header if present: this will
  78106. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  78107. and avail_out are unchanged.)
  78108. */
  78109. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  78110. const Bytef *dictionary,
  78111. uInt dictLength));
  78112. /*
  78113. Initializes the decompression dictionary from the given uncompressed byte
  78114. sequence. This function must be called immediately after a call of inflate,
  78115. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  78116. can be determined from the adler32 value returned by that call of inflate.
  78117. The compressor and decompressor must use exactly the same dictionary (see
  78118. deflateSetDictionary). For raw inflate, this function can be called
  78119. immediately after inflateInit2() or inflateReset() and before any call of
  78120. inflate() to set the dictionary. The application must insure that the
  78121. dictionary that was used for compression is provided.
  78122. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  78123. parameter is invalid (such as NULL dictionary) or the stream state is
  78124. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  78125. expected one (incorrect adler32 value). inflateSetDictionary does not
  78126. perform any decompression: this will be done by subsequent calls of
  78127. inflate().
  78128. */
  78129. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  78130. /*
  78131. Skips invalid compressed data until a full flush point (see above the
  78132. description of deflate with Z_FULL_FLUSH) can be found, or until all
  78133. available input is skipped. No output is provided.
  78134. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  78135. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  78136. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  78137. case, the application may save the current current value of total_in which
  78138. indicates where valid compressed data was found. In the error case, the
  78139. application may repeatedly call inflateSync, providing more input each time,
  78140. until success or end of the input data.
  78141. */
  78142. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  78143. z_streamp source));
  78144. /*
  78145. Sets the destination stream as a complete copy of the source stream.
  78146. This function can be useful when randomly accessing a large stream. The
  78147. first pass through the stream can periodically record the inflate state,
  78148. allowing restarting inflate at those points when randomly accessing the
  78149. stream.
  78150. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  78151. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  78152. (such as zalloc being NULL). msg is left unchanged in both source and
  78153. destination.
  78154. */
  78155. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  78156. /*
  78157. This function is equivalent to inflateEnd followed by inflateInit,
  78158. but does not free and reallocate all the internal decompression state.
  78159. The stream will keep attributes that may have been set by inflateInit2.
  78160. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  78161. stream state was inconsistent (such as zalloc or state being NULL).
  78162. */
  78163. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  78164. int bits,
  78165. int value));
  78166. /*
  78167. This function inserts bits in the inflate input stream. The intent is
  78168. that this function is used to start inflating at a bit position in the
  78169. middle of a byte. The provided bits will be used before any bytes are used
  78170. from next_in. This function should only be used with raw inflate, and
  78171. should be used before the first inflate() call after inflateInit2() or
  78172. inflateReset(). bits must be less than or equal to 16, and that many of the
  78173. least significant bits of value will be inserted in the input.
  78174. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  78175. stream state was inconsistent.
  78176. */
  78177. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  78178. gz_headerp head));
  78179. /*
  78180. inflateGetHeader() requests that gzip header information be stored in the
  78181. provided gz_header structure. inflateGetHeader() may be called after
  78182. inflateInit2() or inflateReset(), and before the first call of inflate().
  78183. As inflate() processes the gzip stream, head->done is zero until the header
  78184. is completed, at which time head->done is set to one. If a zlib stream is
  78185. being decoded, then head->done is set to -1 to indicate that there will be
  78186. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  78187. force inflate() to return immediately after header processing is complete
  78188. and before any actual data is decompressed.
  78189. The text, time, xflags, and os fields are filled in with the gzip header
  78190. contents. hcrc is set to true if there is a header CRC. (The header CRC
  78191. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  78192. contains the maximum number of bytes to write to extra. Once done is true,
  78193. extra_len contains the actual extra field length, and extra contains the
  78194. extra field, or that field truncated if extra_max is less than extra_len.
  78195. If name is not Z_NULL, then up to name_max characters are written there,
  78196. terminated with a zero unless the length is greater than name_max. If
  78197. comment is not Z_NULL, then up to comm_max characters are written there,
  78198. terminated with a zero unless the length is greater than comm_max. When
  78199. any of extra, name, or comment are not Z_NULL and the respective field is
  78200. not present in the header, then that field is set to Z_NULL to signal its
  78201. absence. This allows the use of deflateSetHeader() with the returned
  78202. structure to duplicate the header. However if those fields are set to
  78203. allocated memory, then the application will need to save those pointers
  78204. elsewhere so that they can be eventually freed.
  78205. If inflateGetHeader is not used, then the header information is simply
  78206. discarded. The header is always checked for validity, including the header
  78207. CRC if present. inflateReset() will reset the process to discard the header
  78208. information. The application would need to call inflateGetHeader() again to
  78209. retrieve the header from the next gzip stream.
  78210. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  78211. stream state was inconsistent.
  78212. */
  78213. /*
  78214. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  78215. unsigned char FAR *window));
  78216. Initialize the internal stream state for decompression using inflateBack()
  78217. calls. The fields zalloc, zfree and opaque in strm must be initialized
  78218. before the call. If zalloc and zfree are Z_NULL, then the default library-
  78219. derived memory allocation routines are used. windowBits is the base two
  78220. logarithm of the window size, in the range 8..15. window is a caller
  78221. supplied buffer of that size. Except for special applications where it is
  78222. assured that deflate was used with small window sizes, windowBits must be 15
  78223. and a 32K byte window must be supplied to be able to decompress general
  78224. deflate streams.
  78225. See inflateBack() for the usage of these routines.
  78226. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  78227. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  78228. be allocated, or Z_VERSION_ERROR if the version of the library does not
  78229. match the version of the header file.
  78230. */
  78231. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  78232. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  78233. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  78234. in_func in, void FAR *in_desc,
  78235. out_func out, void FAR *out_desc));
  78236. /*
  78237. inflateBack() does a raw inflate with a single call using a call-back
  78238. interface for input and output. This is more efficient than inflate() for
  78239. file i/o applications in that it avoids copying between the output and the
  78240. sliding window by simply making the window itself the output buffer. This
  78241. function trusts the application to not change the output buffer passed by
  78242. the output function, at least until inflateBack() returns.
  78243. inflateBackInit() must be called first to allocate the internal state
  78244. and to initialize the state with the user-provided window buffer.
  78245. inflateBack() may then be used multiple times to inflate a complete, raw
  78246. deflate stream with each call. inflateBackEnd() is then called to free
  78247. the allocated state.
  78248. A raw deflate stream is one with no zlib or gzip header or trailer.
  78249. This routine would normally be used in a utility that reads zip or gzip
  78250. files and writes out uncompressed files. The utility would decode the
  78251. header and process the trailer on its own, hence this routine expects
  78252. only the raw deflate stream to decompress. This is different from the
  78253. normal behavior of inflate(), which expects either a zlib or gzip header and
  78254. trailer around the deflate stream.
  78255. inflateBack() uses two subroutines supplied by the caller that are then
  78256. called by inflateBack() for input and output. inflateBack() calls those
  78257. routines until it reads a complete deflate stream and writes out all of the
  78258. uncompressed data, or until it encounters an error. The function's
  78259. parameters and return types are defined above in the in_func and out_func
  78260. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  78261. number of bytes of provided input, and a pointer to that input in buf. If
  78262. there is no input available, in() must return zero--buf is ignored in that
  78263. case--and inflateBack() will return a buffer error. inflateBack() will call
  78264. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  78265. should return zero on success, or non-zero on failure. If out() returns
  78266. non-zero, inflateBack() will return with an error. Neither in() nor out()
  78267. are permitted to change the contents of the window provided to
  78268. inflateBackInit(), which is also the buffer that out() uses to write from.
  78269. The length written by out() will be at most the window size. Any non-zero
  78270. amount of input may be provided by in().
  78271. For convenience, inflateBack() can be provided input on the first call by
  78272. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  78273. in() will be called. Therefore strm->next_in must be initialized before
  78274. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  78275. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  78276. must also be initialized, and then if strm->avail_in is not zero, input will
  78277. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  78278. The in_desc and out_desc parameters of inflateBack() is passed as the
  78279. first parameter of in() and out() respectively when they are called. These
  78280. descriptors can be optionally used to pass any information that the caller-
  78281. supplied in() and out() functions need to do their job.
  78282. On return, inflateBack() will set strm->next_in and strm->avail_in to
  78283. pass back any unused input that was provided by the last in() call. The
  78284. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  78285. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  78286. error in the deflate stream (in which case strm->msg is set to indicate the
  78287. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  78288. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  78289. distinguished using strm->next_in which will be Z_NULL only if in() returned
  78290. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  78291. out() returning non-zero. (in() will always be called before out(), so
  78292. strm->next_in is assured to be defined if out() returns non-zero.) Note
  78293. that inflateBack() cannot return Z_OK.
  78294. */
  78295. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  78296. /*
  78297. All memory allocated by inflateBackInit() is freed.
  78298. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  78299. state was inconsistent.
  78300. */
  78301. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  78302. /* Return flags indicating compile-time options.
  78303. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  78304. 1.0: size of uInt
  78305. 3.2: size of uLong
  78306. 5.4: size of voidpf (pointer)
  78307. 7.6: size of z_off_t
  78308. Compiler, assembler, and debug options:
  78309. 8: DEBUG
  78310. 9: ASMV or ASMINF -- use ASM code
  78311. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  78312. 11: 0 (reserved)
  78313. One-time table building (smaller code, but not thread-safe if true):
  78314. 12: BUILDFIXED -- build static block decoding tables when needed
  78315. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  78316. 14,15: 0 (reserved)
  78317. Library content (indicates missing functionality):
  78318. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  78319. deflate code when not needed)
  78320. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  78321. and decode gzip streams (to avoid linking crc code)
  78322. 18-19: 0 (reserved)
  78323. Operation variations (changes in library functionality):
  78324. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  78325. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  78326. 22,23: 0 (reserved)
  78327. The sprintf variant used by gzprintf (zero is best):
  78328. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  78329. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  78330. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  78331. Remainder:
  78332. 27-31: 0 (reserved)
  78333. */
  78334. /* utility functions */
  78335. /*
  78336. The following utility functions are implemented on top of the
  78337. basic stream-oriented functions. To simplify the interface, some
  78338. default options are assumed (compression level and memory usage,
  78339. standard memory allocation functions). The source code of these
  78340. utility functions can easily be modified if you need special options.
  78341. */
  78342. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  78343. const Bytef *source, uLong sourceLen));
  78344. /*
  78345. Compresses the source buffer into the destination buffer. sourceLen is
  78346. the byte length of the source buffer. Upon entry, destLen is the total
  78347. size of the destination buffer, which must be at least the value returned
  78348. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  78349. compressed buffer.
  78350. This function can be used to compress a whole file at once if the
  78351. input file is mmap'ed.
  78352. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  78353. enough memory, Z_BUF_ERROR if there was not enough room in the output
  78354. buffer.
  78355. */
  78356. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  78357. const Bytef *source, uLong sourceLen,
  78358. int level));
  78359. /*
  78360. Compresses the source buffer into the destination buffer. The level
  78361. parameter has the same meaning as in deflateInit. sourceLen is the byte
  78362. length of the source buffer. Upon entry, destLen is the total size of the
  78363. destination buffer, which must be at least the value returned by
  78364. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  78365. compressed buffer.
  78366. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78367. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  78368. Z_STREAM_ERROR if the level parameter is invalid.
  78369. */
  78370. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  78371. /*
  78372. compressBound() returns an upper bound on the compressed size after
  78373. compress() or compress2() on sourceLen bytes. It would be used before
  78374. a compress() or compress2() call to allocate the destination buffer.
  78375. */
  78376. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  78377. const Bytef *source, uLong sourceLen));
  78378. /*
  78379. Decompresses the source buffer into the destination buffer. sourceLen is
  78380. the byte length of the source buffer. Upon entry, destLen is the total
  78381. size of the destination buffer, which must be large enough to hold the
  78382. entire uncompressed data. (The size of the uncompressed data must have
  78383. been saved previously by the compressor and transmitted to the decompressor
  78384. by some mechanism outside the scope of this compression library.)
  78385. Upon exit, destLen is the actual size of the compressed buffer.
  78386. This function can be used to decompress a whole file at once if the
  78387. input file is mmap'ed.
  78388. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  78389. enough memory, Z_BUF_ERROR if there was not enough room in the output
  78390. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  78391. */
  78392. typedef voidp gzFile;
  78393. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  78394. /*
  78395. Opens a gzip (.gz) file for reading or writing. The mode parameter
  78396. is as in fopen ("rb" or "wb") but can also include a compression level
  78397. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  78398. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  78399. as in "wb1R". (See the description of deflateInit2 for more information
  78400. about the strategy parameter.)
  78401. gzopen can be used to read a file which is not in gzip format; in this
  78402. case gzread will directly read from the file without decompression.
  78403. gzopen returns NULL if the file could not be opened or if there was
  78404. insufficient memory to allocate the (de)compression state; errno
  78405. can be checked to distinguish the two cases (if errno is zero, the
  78406. zlib error is Z_MEM_ERROR). */
  78407. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  78408. /*
  78409. gzdopen() associates a gzFile with the file descriptor fd. File
  78410. descriptors are obtained from calls like open, dup, creat, pipe or
  78411. fileno (in the file has been previously opened with fopen).
  78412. The mode parameter is as in gzopen.
  78413. The next call of gzclose on the returned gzFile will also close the
  78414. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  78415. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  78416. gzdopen returns NULL if there was insufficient memory to allocate
  78417. the (de)compression state.
  78418. */
  78419. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  78420. /*
  78421. Dynamically update the compression level or strategy. See the description
  78422. of deflateInit2 for the meaning of these parameters.
  78423. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  78424. opened for writing.
  78425. */
  78426. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  78427. /*
  78428. Reads the given number of uncompressed bytes from the compressed file.
  78429. If the input file was not in gzip format, gzread copies the given number
  78430. of bytes into the buffer.
  78431. gzread returns the number of uncompressed bytes actually read (0 for
  78432. end of file, -1 for error). */
  78433. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  78434. voidpc buf, unsigned len));
  78435. /*
  78436. Writes the given number of uncompressed bytes into the compressed file.
  78437. gzwrite returns the number of uncompressed bytes actually written
  78438. (0 in case of error).
  78439. */
  78440. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  78441. /*
  78442. Converts, formats, and writes the args to the compressed file under
  78443. control of the format string, as in fprintf. gzprintf returns the number of
  78444. uncompressed bytes actually written (0 in case of error). The number of
  78445. uncompressed bytes written is limited to 4095. The caller should assure that
  78446. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  78447. return an error (0) with nothing written. In this case, there may also be a
  78448. buffer overflow with unpredictable consequences, which is possible only if
  78449. zlib was compiled with the insecure functions sprintf() or vsprintf()
  78450. because the secure snprintf() or vsnprintf() functions were not available.
  78451. */
  78452. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  78453. /*
  78454. Writes the given null-terminated string to the compressed file, excluding
  78455. the terminating null character.
  78456. gzputs returns the number of characters written, or -1 in case of error.
  78457. */
  78458. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  78459. /*
  78460. Reads bytes from the compressed file until len-1 characters are read, or
  78461. a newline character is read and transferred to buf, or an end-of-file
  78462. condition is encountered. The string is then terminated with a null
  78463. character.
  78464. gzgets returns buf, or Z_NULL in case of error.
  78465. */
  78466. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  78467. /*
  78468. Writes c, converted to an unsigned char, into the compressed file.
  78469. gzputc returns the value that was written, or -1 in case of error.
  78470. */
  78471. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  78472. /*
  78473. Reads one byte from the compressed file. gzgetc returns this byte
  78474. or -1 in case of end of file or error.
  78475. */
  78476. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  78477. /*
  78478. Push one character back onto the stream to be read again later.
  78479. Only one character of push-back is allowed. gzungetc() returns the
  78480. character pushed, or -1 on failure. gzungetc() will fail if a
  78481. character has been pushed but not read yet, or if c is -1. The pushed
  78482. character will be discarded if the stream is repositioned with gzseek()
  78483. or gzrewind().
  78484. */
  78485. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  78486. /*
  78487. Flushes all pending output into the compressed file. The parameter
  78488. flush is as in the deflate() function. The return value is the zlib
  78489. error number (see function gzerror below). gzflush returns Z_OK if
  78490. the flush parameter is Z_FINISH and all output could be flushed.
  78491. gzflush should be called only when strictly necessary because it can
  78492. degrade compression.
  78493. */
  78494. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  78495. z_off_t offset, int whence));
  78496. /*
  78497. Sets the starting position for the next gzread or gzwrite on the
  78498. given compressed file. The offset represents a number of bytes in the
  78499. uncompressed data stream. The whence parameter is defined as in lseek(2);
  78500. the value SEEK_END is not supported.
  78501. If the file is opened for reading, this function is emulated but can be
  78502. extremely slow. If the file is opened for writing, only forward seeks are
  78503. supported; gzseek then compresses a sequence of zeroes up to the new
  78504. starting position.
  78505. gzseek returns the resulting offset location as measured in bytes from
  78506. the beginning of the uncompressed stream, or -1 in case of error, in
  78507. particular if the file is opened for writing and the new starting position
  78508. would be before the current position.
  78509. */
  78510. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  78511. /*
  78512. Rewinds the given file. This function is supported only for reading.
  78513. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  78514. */
  78515. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  78516. /*
  78517. Returns the starting position for the next gzread or gzwrite on the
  78518. given compressed file. This position represents a number of bytes in the
  78519. uncompressed data stream.
  78520. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  78521. */
  78522. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  78523. /*
  78524. Returns 1 when EOF has previously been detected reading the given
  78525. input stream, otherwise zero.
  78526. */
  78527. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  78528. /*
  78529. Returns 1 if file is being read directly without decompression, otherwise
  78530. zero.
  78531. */
  78532. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  78533. /*
  78534. Flushes all pending output if necessary, closes the compressed file
  78535. and deallocates all the (de)compression state. The return value is the zlib
  78536. error number (see function gzerror below).
  78537. */
  78538. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  78539. /*
  78540. Returns the error message for the last error which occurred on the
  78541. given compressed file. errnum is set to zlib error number. If an
  78542. error occurred in the file system and not in the compression library,
  78543. errnum is set to Z_ERRNO and the application may consult errno
  78544. to get the exact error code.
  78545. */
  78546. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  78547. /*
  78548. Clears the error and end-of-file flags for file. This is analogous to the
  78549. clearerr() function in stdio. This is useful for continuing to read a gzip
  78550. file that is being written concurrently.
  78551. */
  78552. /* checksum functions */
  78553. /*
  78554. These functions are not related to compression but are exported
  78555. anyway because they might be useful in applications using the
  78556. compression library.
  78557. */
  78558. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  78559. /*
  78560. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  78561. return the updated checksum. If buf is NULL, this function returns
  78562. the required initial value for the checksum.
  78563. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  78564. much faster. Usage example:
  78565. uLong adler = adler32(0L, Z_NULL, 0);
  78566. while (read_buffer(buffer, length) != EOF) {
  78567. adler = adler32(adler, buffer, length);
  78568. }
  78569. if (adler != original_adler) error();
  78570. */
  78571. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  78572. z_off_t len2));
  78573. /*
  78574. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  78575. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  78576. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  78577. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  78578. */
  78579. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  78580. /*
  78581. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  78582. updated CRC-32. If buf is NULL, this function returns the required initial
  78583. value for the for the crc. Pre- and post-conditioning (one's complement) is
  78584. performed within this function so it shouldn't be done by the application.
  78585. Usage example:
  78586. uLong crc = crc32(0L, Z_NULL, 0);
  78587. while (read_buffer(buffer, length) != EOF) {
  78588. crc = crc32(crc, buffer, length);
  78589. }
  78590. if (crc != original_crc) error();
  78591. */
  78592. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  78593. /*
  78594. Combine two CRC-32 check values into one. For two sequences of bytes,
  78595. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  78596. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  78597. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  78598. len2.
  78599. */
  78600. /* various hacks, don't look :) */
  78601. /* deflateInit and inflateInit are macros to allow checking the zlib version
  78602. * and the compiler's view of z_stream:
  78603. */
  78604. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  78605. const char *version, int stream_size));
  78606. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  78607. const char *version, int stream_size));
  78608. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  78609. int windowBits, int memLevel,
  78610. int strategy, const char *version,
  78611. int stream_size));
  78612. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  78613. const char *version, int stream_size));
  78614. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  78615. unsigned char FAR *window,
  78616. const char *version,
  78617. int stream_size));
  78618. #define deflateInit(strm, level) \
  78619. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  78620. #define inflateInit(strm) \
  78621. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  78622. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  78623. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  78624. (strategy), ZLIB_VERSION, sizeof(z_stream))
  78625. #define inflateInit2(strm, windowBits) \
  78626. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  78627. #define inflateBackInit(strm, windowBits, window) \
  78628. inflateBackInit_((strm), (windowBits), (window), \
  78629. ZLIB_VERSION, sizeof(z_stream))
  78630. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  78631. struct internal_state {int dummy;}; /* hack for buggy compilers */
  78632. #endif
  78633. ZEXTERN const char * ZEXPORT zError OF((int));
  78634. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  78635. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  78636. #ifdef __cplusplus
  78637. }
  78638. #endif
  78639. #endif /* ZLIB_H */
  78640. /*** End of inlined file: zlib.h ***/
  78641. #undef OS_CODE
  78642. #else
  78643. #include <zlib.h>
  78644. #endif
  78645. }
  78646. BEGIN_JUCE_NAMESPACE
  78647. // internal helper object that holds the zlib structures so they don't have to be
  78648. // included publicly.
  78649. class GZIPCompressorHelper
  78650. {
  78651. public:
  78652. GZIPCompressorHelper (const int compressionLevel, const bool nowrap)
  78653. : data (0),
  78654. dataSize (0),
  78655. compLevel (compressionLevel),
  78656. strategy (0),
  78657. setParams (true),
  78658. streamIsValid (false),
  78659. finished (false),
  78660. shouldFinish (false)
  78661. {
  78662. using namespace zlibNamespace;
  78663. zerostruct (stream);
  78664. streamIsValid = (deflateInit2 (&stream, compLevel, Z_DEFLATED,
  78665. nowrap ? -MAX_WBITS : MAX_WBITS,
  78666. 8, strategy) == Z_OK);
  78667. }
  78668. ~GZIPCompressorHelper()
  78669. {
  78670. using namespace zlibNamespace;
  78671. if (streamIsValid)
  78672. deflateEnd (&stream);
  78673. }
  78674. bool needsInput() const throw()
  78675. {
  78676. return dataSize <= 0;
  78677. }
  78678. void setInput (const uint8* const newData, const int size) throw()
  78679. {
  78680. data = newData;
  78681. dataSize = size;
  78682. }
  78683. int doNextBlock (uint8* const dest, const int destSize) throw()
  78684. {
  78685. using namespace zlibNamespace;
  78686. if (streamIsValid)
  78687. {
  78688. stream.next_in = const_cast <uint8*> (data);
  78689. stream.next_out = dest;
  78690. stream.avail_in = dataSize;
  78691. stream.avail_out = destSize;
  78692. const int result = setParams ? deflateParams (&stream, compLevel, strategy)
  78693. : deflate (&stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  78694. setParams = false;
  78695. switch (result)
  78696. {
  78697. case Z_STREAM_END:
  78698. finished = true;
  78699. // Deliberate fall-through..
  78700. case Z_OK:
  78701. data += dataSize - stream.avail_in;
  78702. dataSize = stream.avail_in;
  78703. return destSize - stream.avail_out;
  78704. default:
  78705. break;
  78706. }
  78707. }
  78708. return 0;
  78709. }
  78710. private:
  78711. zlibNamespace::z_stream stream;
  78712. const uint8* data;
  78713. int dataSize, compLevel, strategy;
  78714. bool setParams, streamIsValid;
  78715. public:
  78716. bool finished, shouldFinish;
  78717. };
  78718. const int gzipCompBufferSize = 32768;
  78719. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  78720. int compressionLevel,
  78721. const bool deleteDestStream,
  78722. const bool noWrap)
  78723. : destStream (destStream_),
  78724. streamToDelete (deleteDestStream ? destStream_ : 0),
  78725. buffer (gzipCompBufferSize)
  78726. {
  78727. if (compressionLevel < 1 || compressionLevel > 9)
  78728. compressionLevel = -1;
  78729. helper = new GZIPCompressorHelper (compressionLevel, noWrap);
  78730. }
  78731. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  78732. {
  78733. flush();
  78734. }
  78735. void GZIPCompressorOutputStream::flush()
  78736. {
  78737. if (! helper->finished)
  78738. {
  78739. helper->shouldFinish = true;
  78740. while (! helper->finished)
  78741. doNextBlock();
  78742. }
  78743. destStream->flush();
  78744. }
  78745. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  78746. {
  78747. if (! helper->finished)
  78748. {
  78749. helper->setInput (static_cast <const uint8*> (destBuffer), howMany);
  78750. while (! helper->needsInput())
  78751. {
  78752. if (! doNextBlock())
  78753. return false;
  78754. }
  78755. }
  78756. return true;
  78757. }
  78758. bool GZIPCompressorOutputStream::doNextBlock()
  78759. {
  78760. const int len = helper->doNextBlock (buffer, gzipCompBufferSize);
  78761. if (len > 0)
  78762. return destStream->write (buffer, len);
  78763. else
  78764. return true;
  78765. }
  78766. int64 GZIPCompressorOutputStream::getPosition()
  78767. {
  78768. return destStream->getPosition();
  78769. }
  78770. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  78771. {
  78772. jassertfalse; // can't do it!
  78773. return false;
  78774. }
  78775. END_JUCE_NAMESPACE
  78776. /*** End of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  78777. /*** Start of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  78778. #if JUCE_MSVC
  78779. #pragma warning (push)
  78780. #pragma warning (disable: 4309 4305)
  78781. #endif
  78782. namespace zlibNamespace
  78783. {
  78784. #if JUCE_INCLUDE_ZLIB_CODE
  78785. extern "C"
  78786. {
  78787. #undef OS_CODE
  78788. #undef fdopen
  78789. #define ZLIB_INTERNAL
  78790. #define NO_DUMMY_DECL
  78791. /*** Start of inlined file: adler32.c ***/
  78792. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  78793. #define ZLIB_INTERNAL
  78794. #define BASE 65521UL /* largest prime smaller than 65536 */
  78795. #define NMAX 5552
  78796. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  78797. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  78798. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  78799. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  78800. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  78801. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  78802. /* use NO_DIVIDE if your processor does not do division in hardware */
  78803. #ifdef NO_DIVIDE
  78804. # define MOD(a) \
  78805. do { \
  78806. if (a >= (BASE << 16)) a -= (BASE << 16); \
  78807. if (a >= (BASE << 15)) a -= (BASE << 15); \
  78808. if (a >= (BASE << 14)) a -= (BASE << 14); \
  78809. if (a >= (BASE << 13)) a -= (BASE << 13); \
  78810. if (a >= (BASE << 12)) a -= (BASE << 12); \
  78811. if (a >= (BASE << 11)) a -= (BASE << 11); \
  78812. if (a >= (BASE << 10)) a -= (BASE << 10); \
  78813. if (a >= (BASE << 9)) a -= (BASE << 9); \
  78814. if (a >= (BASE << 8)) a -= (BASE << 8); \
  78815. if (a >= (BASE << 7)) a -= (BASE << 7); \
  78816. if (a >= (BASE << 6)) a -= (BASE << 6); \
  78817. if (a >= (BASE << 5)) a -= (BASE << 5); \
  78818. if (a >= (BASE << 4)) a -= (BASE << 4); \
  78819. if (a >= (BASE << 3)) a -= (BASE << 3); \
  78820. if (a >= (BASE << 2)) a -= (BASE << 2); \
  78821. if (a >= (BASE << 1)) a -= (BASE << 1); \
  78822. if (a >= BASE) a -= BASE; \
  78823. } while (0)
  78824. # define MOD4(a) \
  78825. do { \
  78826. if (a >= (BASE << 4)) a -= (BASE << 4); \
  78827. if (a >= (BASE << 3)) a -= (BASE << 3); \
  78828. if (a >= (BASE << 2)) a -= (BASE << 2); \
  78829. if (a >= (BASE << 1)) a -= (BASE << 1); \
  78830. if (a >= BASE) a -= BASE; \
  78831. } while (0)
  78832. #else
  78833. # define MOD(a) a %= BASE
  78834. # define MOD4(a) a %= BASE
  78835. #endif
  78836. /* ========================================================================= */
  78837. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  78838. {
  78839. unsigned long sum2;
  78840. unsigned n;
  78841. /* split Adler-32 into component sums */
  78842. sum2 = (adler >> 16) & 0xffff;
  78843. adler &= 0xffff;
  78844. /* in case user likes doing a byte at a time, keep it fast */
  78845. if (len == 1) {
  78846. adler += buf[0];
  78847. if (adler >= BASE)
  78848. adler -= BASE;
  78849. sum2 += adler;
  78850. if (sum2 >= BASE)
  78851. sum2 -= BASE;
  78852. return adler | (sum2 << 16);
  78853. }
  78854. /* initial Adler-32 value (deferred check for len == 1 speed) */
  78855. if (buf == Z_NULL)
  78856. return 1L;
  78857. /* in case short lengths are provided, keep it somewhat fast */
  78858. if (len < 16) {
  78859. while (len--) {
  78860. adler += *buf++;
  78861. sum2 += adler;
  78862. }
  78863. if (adler >= BASE)
  78864. adler -= BASE;
  78865. MOD4(sum2); /* only added so many BASE's */
  78866. return adler | (sum2 << 16);
  78867. }
  78868. /* do length NMAX blocks -- requires just one modulo operation */
  78869. while (len >= NMAX) {
  78870. len -= NMAX;
  78871. n = NMAX / 16; /* NMAX is divisible by 16 */
  78872. do {
  78873. DO16(buf); /* 16 sums unrolled */
  78874. buf += 16;
  78875. } while (--n);
  78876. MOD(adler);
  78877. MOD(sum2);
  78878. }
  78879. /* do remaining bytes (less than NMAX, still just one modulo) */
  78880. if (len) { /* avoid modulos if none remaining */
  78881. while (len >= 16) {
  78882. len -= 16;
  78883. DO16(buf);
  78884. buf += 16;
  78885. }
  78886. while (len--) {
  78887. adler += *buf++;
  78888. sum2 += adler;
  78889. }
  78890. MOD(adler);
  78891. MOD(sum2);
  78892. }
  78893. /* return recombined sums */
  78894. return adler | (sum2 << 16);
  78895. }
  78896. /* ========================================================================= */
  78897. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  78898. {
  78899. unsigned long sum1;
  78900. unsigned long sum2;
  78901. unsigned rem;
  78902. /* the derivation of this formula is left as an exercise for the reader */
  78903. rem = (unsigned)(len2 % BASE);
  78904. sum1 = adler1 & 0xffff;
  78905. sum2 = rem * sum1;
  78906. MOD(sum2);
  78907. sum1 += (adler2 & 0xffff) + BASE - 1;
  78908. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  78909. if (sum1 > BASE) sum1 -= BASE;
  78910. if (sum1 > BASE) sum1 -= BASE;
  78911. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  78912. if (sum2 > BASE) sum2 -= BASE;
  78913. return sum1 | (sum2 << 16);
  78914. }
  78915. /*** End of inlined file: adler32.c ***/
  78916. /*** Start of inlined file: compress.c ***/
  78917. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  78918. #define ZLIB_INTERNAL
  78919. /* ===========================================================================
  78920. Compresses the source buffer into the destination buffer. The level
  78921. parameter has the same meaning as in deflateInit. sourceLen is the byte
  78922. length of the source buffer. Upon entry, destLen is the total size of the
  78923. destination buffer, which must be at least 0.1% larger than sourceLen plus
  78924. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  78925. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78926. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  78927. Z_STREAM_ERROR if the level parameter is invalid.
  78928. */
  78929. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  78930. uLong sourceLen, int level)
  78931. {
  78932. z_stream stream;
  78933. int err;
  78934. stream.next_in = (Bytef*)source;
  78935. stream.avail_in = (uInt)sourceLen;
  78936. #ifdef MAXSEG_64K
  78937. /* Check for source > 64K on 16-bit machine: */
  78938. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  78939. #endif
  78940. stream.next_out = dest;
  78941. stream.avail_out = (uInt)*destLen;
  78942. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  78943. stream.zalloc = (alloc_func)0;
  78944. stream.zfree = (free_func)0;
  78945. stream.opaque = (voidpf)0;
  78946. err = deflateInit(&stream, level);
  78947. if (err != Z_OK) return err;
  78948. err = deflate(&stream, Z_FINISH);
  78949. if (err != Z_STREAM_END) {
  78950. deflateEnd(&stream);
  78951. return err == Z_OK ? Z_BUF_ERROR : err;
  78952. }
  78953. *destLen = stream.total_out;
  78954. err = deflateEnd(&stream);
  78955. return err;
  78956. }
  78957. /* ===========================================================================
  78958. */
  78959. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  78960. {
  78961. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  78962. }
  78963. /* ===========================================================================
  78964. If the default memLevel or windowBits for deflateInit() is changed, then
  78965. this function needs to be updated.
  78966. */
  78967. uLong ZEXPORT compressBound (uLong sourceLen)
  78968. {
  78969. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  78970. }
  78971. /*** End of inlined file: compress.c ***/
  78972. #undef DO1
  78973. #undef DO8
  78974. /*** Start of inlined file: crc32.c ***/
  78975. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  78976. /*
  78977. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  78978. protection on the static variables used to control the first-use generation
  78979. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  78980. first call get_crc_table() to initialize the tables before allowing more than
  78981. one thread to use crc32().
  78982. */
  78983. #ifdef MAKECRCH
  78984. # include <stdio.h>
  78985. # ifndef DYNAMIC_CRC_TABLE
  78986. # define DYNAMIC_CRC_TABLE
  78987. # endif /* !DYNAMIC_CRC_TABLE */
  78988. #endif /* MAKECRCH */
  78989. /*** Start of inlined file: zutil.h ***/
  78990. /* WARNING: this file should *not* be used by applications. It is
  78991. part of the implementation of the compression library and is
  78992. subject to change. Applications should only use zlib.h.
  78993. */
  78994. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  78995. #ifndef ZUTIL_H
  78996. #define ZUTIL_H
  78997. #define ZLIB_INTERNAL
  78998. #ifdef STDC
  78999. # ifndef _WIN32_WCE
  79000. # include <stddef.h>
  79001. # endif
  79002. # include <string.h>
  79003. # include <stdlib.h>
  79004. #endif
  79005. #ifdef NO_ERRNO_H
  79006. # ifdef _WIN32_WCE
  79007. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  79008. * errno. We define it as a global variable to simplify porting.
  79009. * Its value is always 0 and should not be used. We rename it to
  79010. * avoid conflict with other libraries that use the same workaround.
  79011. */
  79012. # define errno z_errno
  79013. # endif
  79014. extern int errno;
  79015. #else
  79016. # ifndef _WIN32_WCE
  79017. # include <errno.h>
  79018. # endif
  79019. #endif
  79020. #ifndef local
  79021. # define local static
  79022. #endif
  79023. /* compile with -Dlocal if your debugger can't find static symbols */
  79024. typedef unsigned char uch;
  79025. typedef uch FAR uchf;
  79026. typedef unsigned short ush;
  79027. typedef ush FAR ushf;
  79028. typedef unsigned long ulg;
  79029. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  79030. /* (size given to avoid silly warnings with Visual C++) */
  79031. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  79032. #define ERR_RETURN(strm,err) \
  79033. return (strm->msg = (char*)ERR_MSG(err), (err))
  79034. /* To be used only when the state is known to be valid */
  79035. /* common constants */
  79036. #ifndef DEF_WBITS
  79037. # define DEF_WBITS MAX_WBITS
  79038. #endif
  79039. /* default windowBits for decompression. MAX_WBITS is for compression only */
  79040. #if MAX_MEM_LEVEL >= 8
  79041. # define DEF_MEM_LEVEL 8
  79042. #else
  79043. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  79044. #endif
  79045. /* default memLevel */
  79046. #define STORED_BLOCK 0
  79047. #define STATIC_TREES 1
  79048. #define DYN_TREES 2
  79049. /* The three kinds of block type */
  79050. #define MIN_MATCH 3
  79051. #define MAX_MATCH 258
  79052. /* The minimum and maximum match lengths */
  79053. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  79054. /* target dependencies */
  79055. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  79056. # define OS_CODE 0x00
  79057. # if defined(__TURBOC__) || defined(__BORLANDC__)
  79058. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  79059. /* Allow compilation with ANSI keywords only enabled */
  79060. void _Cdecl farfree( void *block );
  79061. void *_Cdecl farmalloc( unsigned long nbytes );
  79062. # else
  79063. # include <alloc.h>
  79064. # endif
  79065. # else /* MSC or DJGPP */
  79066. # include <malloc.h>
  79067. # endif
  79068. #endif
  79069. #ifdef AMIGA
  79070. # define OS_CODE 0x01
  79071. #endif
  79072. #if defined(VAXC) || defined(VMS)
  79073. # define OS_CODE 0x02
  79074. # define F_OPEN(name, mode) \
  79075. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  79076. #endif
  79077. #if defined(ATARI) || defined(atarist)
  79078. # define OS_CODE 0x05
  79079. #endif
  79080. #ifdef OS2
  79081. # define OS_CODE 0x06
  79082. # ifdef M_I86
  79083. #include <malloc.h>
  79084. # endif
  79085. #endif
  79086. #if defined(MACOS) || TARGET_OS_MAC
  79087. # define OS_CODE 0x07
  79088. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  79089. # include <unix.h> /* for fdopen */
  79090. # else
  79091. # ifndef fdopen
  79092. # define fdopen(fd,mode) NULL /* No fdopen() */
  79093. # endif
  79094. # endif
  79095. #endif
  79096. #ifdef TOPS20
  79097. # define OS_CODE 0x0a
  79098. #endif
  79099. #ifdef WIN32
  79100. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  79101. # define OS_CODE 0x0b
  79102. # endif
  79103. #endif
  79104. #ifdef __50SERIES /* Prime/PRIMOS */
  79105. # define OS_CODE 0x0f
  79106. #endif
  79107. #if defined(_BEOS_) || defined(RISCOS)
  79108. # define fdopen(fd,mode) NULL /* No fdopen() */
  79109. #endif
  79110. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  79111. # if defined(_WIN32_WCE)
  79112. # define fdopen(fd,mode) NULL /* No fdopen() */
  79113. # ifndef _PTRDIFF_T_DEFINED
  79114. typedef int ptrdiff_t;
  79115. # define _PTRDIFF_T_DEFINED
  79116. # endif
  79117. # else
  79118. # define fdopen(fd,type) _fdopen(fd,type)
  79119. # endif
  79120. #endif
  79121. /* common defaults */
  79122. #ifndef OS_CODE
  79123. # define OS_CODE 0x03 /* assume Unix */
  79124. #endif
  79125. #ifndef F_OPEN
  79126. # define F_OPEN(name, mode) fopen((name), (mode))
  79127. #endif
  79128. /* functions */
  79129. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  79130. # ifndef HAVE_VSNPRINTF
  79131. # define HAVE_VSNPRINTF
  79132. # endif
  79133. #endif
  79134. #if defined(__CYGWIN__)
  79135. # ifndef HAVE_VSNPRINTF
  79136. # define HAVE_VSNPRINTF
  79137. # endif
  79138. #endif
  79139. #ifndef HAVE_VSNPRINTF
  79140. # ifdef MSDOS
  79141. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  79142. but for now we just assume it doesn't. */
  79143. # define NO_vsnprintf
  79144. # endif
  79145. # ifdef __TURBOC__
  79146. # define NO_vsnprintf
  79147. # endif
  79148. # ifdef WIN32
  79149. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  79150. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  79151. # define vsnprintf _vsnprintf
  79152. # endif
  79153. # endif
  79154. # ifdef __SASC
  79155. # define NO_vsnprintf
  79156. # endif
  79157. #endif
  79158. #ifdef VMS
  79159. # define NO_vsnprintf
  79160. #endif
  79161. #if defined(pyr)
  79162. # define NO_MEMCPY
  79163. #endif
  79164. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  79165. /* Use our own functions for small and medium model with MSC <= 5.0.
  79166. * You may have to use the same strategy for Borland C (untested).
  79167. * The __SC__ check is for Symantec.
  79168. */
  79169. # define NO_MEMCPY
  79170. #endif
  79171. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  79172. # define HAVE_MEMCPY
  79173. #endif
  79174. #ifdef HAVE_MEMCPY
  79175. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  79176. # define zmemcpy _fmemcpy
  79177. # define zmemcmp _fmemcmp
  79178. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  79179. # else
  79180. # define zmemcpy memcpy
  79181. # define zmemcmp memcmp
  79182. # define zmemzero(dest, len) memset(dest, 0, len)
  79183. # endif
  79184. #else
  79185. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  79186. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  79187. extern void zmemzero OF((Bytef* dest, uInt len));
  79188. #endif
  79189. /* Diagnostic functions */
  79190. #ifdef DEBUG
  79191. # include <stdio.h>
  79192. extern int z_verbose;
  79193. extern void z_error OF((const char *m));
  79194. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  79195. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  79196. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  79197. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  79198. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  79199. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  79200. #else
  79201. # define Assert(cond,msg)
  79202. # define Trace(x)
  79203. # define Tracev(x)
  79204. # define Tracevv(x)
  79205. # define Tracec(c,x)
  79206. # define Tracecv(c,x)
  79207. #endif
  79208. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  79209. void zcfree OF((voidpf opaque, voidpf ptr));
  79210. #define ZALLOC(strm, items, size) \
  79211. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  79212. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  79213. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  79214. #endif /* ZUTIL_H */
  79215. /*** End of inlined file: zutil.h ***/
  79216. /* for STDC and FAR definitions */
  79217. #define local static
  79218. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  79219. #ifndef NOBYFOUR
  79220. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  79221. # include <limits.h>
  79222. # define BYFOUR
  79223. # if (UINT_MAX == 0xffffffffUL)
  79224. typedef unsigned int u4;
  79225. # else
  79226. # if (ULONG_MAX == 0xffffffffUL)
  79227. typedef unsigned long u4;
  79228. # else
  79229. # if (USHRT_MAX == 0xffffffffUL)
  79230. typedef unsigned short u4;
  79231. # else
  79232. # undef BYFOUR /* can't find a four-byte integer type! */
  79233. # endif
  79234. # endif
  79235. # endif
  79236. # endif /* STDC */
  79237. #endif /* !NOBYFOUR */
  79238. /* Definitions for doing the crc four data bytes at a time. */
  79239. #ifdef BYFOUR
  79240. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  79241. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  79242. local unsigned long crc32_little OF((unsigned long,
  79243. const unsigned char FAR *, unsigned));
  79244. local unsigned long crc32_big OF((unsigned long,
  79245. const unsigned char FAR *, unsigned));
  79246. # define TBLS 8
  79247. #else
  79248. # define TBLS 1
  79249. #endif /* BYFOUR */
  79250. /* Local functions for crc concatenation */
  79251. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  79252. unsigned long vec));
  79253. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  79254. #ifdef DYNAMIC_CRC_TABLE
  79255. local volatile int crc_table_empty = 1;
  79256. local unsigned long FAR crc_table[TBLS][256];
  79257. local void make_crc_table OF((void));
  79258. #ifdef MAKECRCH
  79259. local void write_table OF((FILE *, const unsigned long FAR *));
  79260. #endif /* MAKECRCH */
  79261. /*
  79262. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  79263. 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.
  79264. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  79265. with the lowest powers in the most significant bit. Then adding polynomials
  79266. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  79267. one. If we call the above polynomial p, and represent a byte as the
  79268. polynomial q, also with the lowest power in the most significant bit (so the
  79269. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  79270. where a mod b means the remainder after dividing a by b.
  79271. This calculation is done using the shift-register method of multiplying and
  79272. taking the remainder. The register is initialized to zero, and for each
  79273. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  79274. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  79275. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  79276. out is a one). We start with the highest power (least significant bit) of
  79277. q and repeat for all eight bits of q.
  79278. The first table is simply the CRC of all possible eight bit values. This is
  79279. all the information needed to generate CRCs on data a byte at a time for all
  79280. combinations of CRC register values and incoming bytes. The remaining tables
  79281. allow for word-at-a-time CRC calculation for both big-endian and little-
  79282. endian machines, where a word is four bytes.
  79283. */
  79284. local void make_crc_table()
  79285. {
  79286. unsigned long c;
  79287. int n, k;
  79288. unsigned long poly; /* polynomial exclusive-or pattern */
  79289. /* terms of polynomial defining this crc (except x^32): */
  79290. static volatile int first = 1; /* flag to limit concurrent making */
  79291. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  79292. /* See if another task is already doing this (not thread-safe, but better
  79293. than nothing -- significantly reduces duration of vulnerability in
  79294. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  79295. if (first) {
  79296. first = 0;
  79297. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  79298. poly = 0UL;
  79299. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  79300. poly |= 1UL << (31 - p[n]);
  79301. /* generate a crc for every 8-bit value */
  79302. for (n = 0; n < 256; n++) {
  79303. c = (unsigned long)n;
  79304. for (k = 0; k < 8; k++)
  79305. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  79306. crc_table[0][n] = c;
  79307. }
  79308. #ifdef BYFOUR
  79309. /* generate crc for each value followed by one, two, and three zeros,
  79310. and then the byte reversal of those as well as the first table */
  79311. for (n = 0; n < 256; n++) {
  79312. c = crc_table[0][n];
  79313. crc_table[4][n] = REV(c);
  79314. for (k = 1; k < 4; k++) {
  79315. c = crc_table[0][c & 0xff] ^ (c >> 8);
  79316. crc_table[k][n] = c;
  79317. crc_table[k + 4][n] = REV(c);
  79318. }
  79319. }
  79320. #endif /* BYFOUR */
  79321. crc_table_empty = 0;
  79322. }
  79323. else { /* not first */
  79324. /* wait for the other guy to finish (not efficient, but rare) */
  79325. while (crc_table_empty)
  79326. ;
  79327. }
  79328. #ifdef MAKECRCH
  79329. /* write out CRC tables to crc32.h */
  79330. {
  79331. FILE *out;
  79332. out = fopen("crc32.h", "w");
  79333. if (out == NULL) return;
  79334. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  79335. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  79336. fprintf(out, "local const unsigned long FAR ");
  79337. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  79338. write_table(out, crc_table[0]);
  79339. # ifdef BYFOUR
  79340. fprintf(out, "#ifdef BYFOUR\n");
  79341. for (k = 1; k < 8; k++) {
  79342. fprintf(out, " },\n {\n");
  79343. write_table(out, crc_table[k]);
  79344. }
  79345. fprintf(out, "#endif\n");
  79346. # endif /* BYFOUR */
  79347. fprintf(out, " }\n};\n");
  79348. fclose(out);
  79349. }
  79350. #endif /* MAKECRCH */
  79351. }
  79352. #ifdef MAKECRCH
  79353. local void write_table(out, table)
  79354. FILE *out;
  79355. const unsigned long FAR *table;
  79356. {
  79357. int n;
  79358. for (n = 0; n < 256; n++)
  79359. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  79360. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  79361. }
  79362. #endif /* MAKECRCH */
  79363. #else /* !DYNAMIC_CRC_TABLE */
  79364. /* ========================================================================
  79365. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  79366. */
  79367. /*** Start of inlined file: crc32.h ***/
  79368. local const unsigned long FAR crc_table[TBLS][256] =
  79369. {
  79370. {
  79371. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  79372. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  79373. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  79374. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  79375. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  79376. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  79377. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  79378. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  79379. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  79380. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  79381. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  79382. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  79383. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  79384. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  79385. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  79386. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  79387. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  79388. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  79389. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  79390. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  79391. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  79392. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  79393. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  79394. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  79395. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  79396. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  79397. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  79398. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  79399. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  79400. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  79401. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  79402. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  79403. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  79404. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  79405. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  79406. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  79407. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  79408. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  79409. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  79410. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  79411. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  79412. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  79413. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  79414. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  79415. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  79416. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  79417. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  79418. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  79419. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  79420. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  79421. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  79422. 0x2d02ef8dUL
  79423. #ifdef BYFOUR
  79424. },
  79425. {
  79426. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  79427. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  79428. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  79429. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  79430. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  79431. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  79432. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  79433. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  79434. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  79435. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  79436. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  79437. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  79438. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  79439. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  79440. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  79441. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  79442. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  79443. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  79444. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  79445. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  79446. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  79447. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  79448. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  79449. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  79450. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  79451. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  79452. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  79453. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  79454. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  79455. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  79456. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  79457. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  79458. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  79459. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  79460. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  79461. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  79462. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  79463. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  79464. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  79465. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  79466. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  79467. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  79468. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  79469. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  79470. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  79471. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  79472. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  79473. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  79474. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  79475. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  79476. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  79477. 0x9324fd72UL
  79478. },
  79479. {
  79480. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  79481. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  79482. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  79483. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  79484. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  79485. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  79486. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  79487. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  79488. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  79489. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  79490. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  79491. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  79492. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  79493. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  79494. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  79495. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  79496. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  79497. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  79498. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  79499. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  79500. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  79501. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  79502. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  79503. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  79504. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  79505. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  79506. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  79507. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  79508. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  79509. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  79510. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  79511. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  79512. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  79513. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  79514. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  79515. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  79516. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  79517. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  79518. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  79519. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  79520. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  79521. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  79522. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  79523. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  79524. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  79525. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  79526. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  79527. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  79528. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  79529. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  79530. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  79531. 0xbe9834edUL
  79532. },
  79533. {
  79534. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  79535. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  79536. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  79537. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  79538. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  79539. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  79540. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  79541. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  79542. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  79543. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  79544. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  79545. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  79546. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  79547. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  79548. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  79549. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  79550. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  79551. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  79552. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  79553. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  79554. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  79555. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  79556. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  79557. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  79558. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  79559. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  79560. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  79561. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  79562. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  79563. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  79564. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  79565. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  79566. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  79567. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  79568. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  79569. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  79570. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  79571. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  79572. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  79573. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  79574. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  79575. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  79576. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  79577. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  79578. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  79579. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  79580. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  79581. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  79582. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  79583. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  79584. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  79585. 0xde0506f1UL
  79586. },
  79587. {
  79588. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  79589. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  79590. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  79591. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  79592. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  79593. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  79594. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  79595. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  79596. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  79597. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  79598. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  79599. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  79600. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  79601. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  79602. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  79603. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  79604. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  79605. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  79606. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  79607. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  79608. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  79609. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  79610. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  79611. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  79612. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  79613. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  79614. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  79615. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  79616. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  79617. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  79618. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  79619. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  79620. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  79621. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  79622. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  79623. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  79624. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  79625. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  79626. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  79627. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  79628. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  79629. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  79630. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  79631. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  79632. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  79633. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  79634. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  79635. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  79636. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  79637. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  79638. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  79639. 0x8def022dUL
  79640. },
  79641. {
  79642. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  79643. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  79644. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  79645. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  79646. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  79647. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  79648. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  79649. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  79650. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  79651. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  79652. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  79653. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  79654. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  79655. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  79656. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  79657. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  79658. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  79659. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  79660. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  79661. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  79662. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  79663. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  79664. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  79665. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  79666. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  79667. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  79668. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  79669. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  79670. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  79671. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  79672. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  79673. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  79674. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  79675. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  79676. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  79677. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  79678. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  79679. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  79680. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  79681. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  79682. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  79683. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  79684. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  79685. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  79686. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  79687. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  79688. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  79689. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  79690. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  79691. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  79692. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  79693. 0x72fd2493UL
  79694. },
  79695. {
  79696. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  79697. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  79698. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  79699. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  79700. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  79701. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  79702. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  79703. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  79704. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  79705. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  79706. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  79707. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  79708. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  79709. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  79710. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  79711. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  79712. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  79713. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  79714. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  79715. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  79716. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  79717. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  79718. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  79719. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  79720. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  79721. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  79722. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  79723. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  79724. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  79725. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  79726. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  79727. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  79728. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  79729. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  79730. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  79731. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  79732. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  79733. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  79734. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  79735. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  79736. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  79737. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  79738. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  79739. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  79740. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  79741. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  79742. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  79743. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  79744. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  79745. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  79746. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  79747. 0xed3498beUL
  79748. },
  79749. {
  79750. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  79751. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  79752. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  79753. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  79754. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  79755. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  79756. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  79757. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  79758. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  79759. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  79760. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  79761. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  79762. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  79763. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  79764. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  79765. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  79766. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  79767. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  79768. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  79769. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  79770. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  79771. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  79772. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  79773. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  79774. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  79775. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  79776. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  79777. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  79778. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  79779. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  79780. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  79781. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  79782. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  79783. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  79784. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  79785. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  79786. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  79787. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  79788. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  79789. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  79790. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  79791. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  79792. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  79793. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  79794. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  79795. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  79796. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  79797. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  79798. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  79799. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  79800. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  79801. 0xf10605deUL
  79802. #endif
  79803. }
  79804. };
  79805. /*** End of inlined file: crc32.h ***/
  79806. #endif /* DYNAMIC_CRC_TABLE */
  79807. /* =========================================================================
  79808. * This function can be used by asm versions of crc32()
  79809. */
  79810. const unsigned long FAR * ZEXPORT get_crc_table()
  79811. {
  79812. #ifdef DYNAMIC_CRC_TABLE
  79813. if (crc_table_empty)
  79814. make_crc_table();
  79815. #endif /* DYNAMIC_CRC_TABLE */
  79816. return (const unsigned long FAR *)crc_table;
  79817. }
  79818. /* ========================================================================= */
  79819. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  79820. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  79821. /* ========================================================================= */
  79822. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  79823. {
  79824. if (buf == Z_NULL) return 0UL;
  79825. #ifdef DYNAMIC_CRC_TABLE
  79826. if (crc_table_empty)
  79827. make_crc_table();
  79828. #endif /* DYNAMIC_CRC_TABLE */
  79829. #ifdef BYFOUR
  79830. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  79831. u4 endian;
  79832. endian = 1;
  79833. if (*((unsigned char *)(&endian)))
  79834. return crc32_little(crc, buf, len);
  79835. else
  79836. return crc32_big(crc, buf, len);
  79837. }
  79838. #endif /* BYFOUR */
  79839. crc = crc ^ 0xffffffffUL;
  79840. while (len >= 8) {
  79841. DO8;
  79842. len -= 8;
  79843. }
  79844. if (len) do {
  79845. DO1;
  79846. } while (--len);
  79847. return crc ^ 0xffffffffUL;
  79848. }
  79849. #ifdef BYFOUR
  79850. /* ========================================================================= */
  79851. #define DOLIT4 c ^= *buf4++; \
  79852. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  79853. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  79854. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  79855. /* ========================================================================= */
  79856. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  79857. {
  79858. register u4 c;
  79859. register const u4 FAR *buf4;
  79860. c = (u4)crc;
  79861. c = ~c;
  79862. while (len && ((ptrdiff_t)buf & 3)) {
  79863. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  79864. len--;
  79865. }
  79866. buf4 = (const u4 FAR *)(const void FAR *)buf;
  79867. while (len >= 32) {
  79868. DOLIT32;
  79869. len -= 32;
  79870. }
  79871. while (len >= 4) {
  79872. DOLIT4;
  79873. len -= 4;
  79874. }
  79875. buf = (const unsigned char FAR *)buf4;
  79876. if (len) do {
  79877. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  79878. } while (--len);
  79879. c = ~c;
  79880. return (unsigned long)c;
  79881. }
  79882. /* ========================================================================= */
  79883. #define DOBIG4 c ^= *++buf4; \
  79884. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  79885. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  79886. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  79887. /* ========================================================================= */
  79888. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  79889. {
  79890. register u4 c;
  79891. register const u4 FAR *buf4;
  79892. c = REV((u4)crc);
  79893. c = ~c;
  79894. while (len && ((ptrdiff_t)buf & 3)) {
  79895. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  79896. len--;
  79897. }
  79898. buf4 = (const u4 FAR *)(const void FAR *)buf;
  79899. buf4--;
  79900. while (len >= 32) {
  79901. DOBIG32;
  79902. len -= 32;
  79903. }
  79904. while (len >= 4) {
  79905. DOBIG4;
  79906. len -= 4;
  79907. }
  79908. buf4++;
  79909. buf = (const unsigned char FAR *)buf4;
  79910. if (len) do {
  79911. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  79912. } while (--len);
  79913. c = ~c;
  79914. return (unsigned long)(REV(c));
  79915. }
  79916. #endif /* BYFOUR */
  79917. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  79918. /* ========================================================================= */
  79919. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  79920. {
  79921. unsigned long sum;
  79922. sum = 0;
  79923. while (vec) {
  79924. if (vec & 1)
  79925. sum ^= *mat;
  79926. vec >>= 1;
  79927. mat++;
  79928. }
  79929. return sum;
  79930. }
  79931. /* ========================================================================= */
  79932. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  79933. {
  79934. int n;
  79935. for (n = 0; n < GF2_DIM; n++)
  79936. square[n] = gf2_matrix_times(mat, mat[n]);
  79937. }
  79938. /* ========================================================================= */
  79939. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  79940. {
  79941. int n;
  79942. unsigned long row;
  79943. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  79944. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  79945. /* degenerate case */
  79946. if (len2 == 0)
  79947. return crc1;
  79948. /* put operator for one zero bit in odd */
  79949. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  79950. row = 1;
  79951. for (n = 1; n < GF2_DIM; n++) {
  79952. odd[n] = row;
  79953. row <<= 1;
  79954. }
  79955. /* put operator for two zero bits in even */
  79956. gf2_matrix_square(even, odd);
  79957. /* put operator for four zero bits in odd */
  79958. gf2_matrix_square(odd, even);
  79959. /* apply len2 zeros to crc1 (first square will put the operator for one
  79960. zero byte, eight zero bits, in even) */
  79961. do {
  79962. /* apply zeros operator for this bit of len2 */
  79963. gf2_matrix_square(even, odd);
  79964. if (len2 & 1)
  79965. crc1 = gf2_matrix_times(even, crc1);
  79966. len2 >>= 1;
  79967. /* if no more bits set, then done */
  79968. if (len2 == 0)
  79969. break;
  79970. /* another iteration of the loop with odd and even swapped */
  79971. gf2_matrix_square(odd, even);
  79972. if (len2 & 1)
  79973. crc1 = gf2_matrix_times(odd, crc1);
  79974. len2 >>= 1;
  79975. /* if no more bits set, then done */
  79976. } while (len2 != 0);
  79977. /* return combined crc */
  79978. crc1 ^= crc2;
  79979. return crc1;
  79980. }
  79981. /*** End of inlined file: crc32.c ***/
  79982. /*** Start of inlined file: deflate.c ***/
  79983. /*
  79984. * ALGORITHM
  79985. *
  79986. * The "deflation" process depends on being able to identify portions
  79987. * of the input text which are identical to earlier input (within a
  79988. * sliding window trailing behind the input currently being processed).
  79989. *
  79990. * The most straightforward technique turns out to be the fastest for
  79991. * most input files: try all possible matches and select the longest.
  79992. * The key feature of this algorithm is that insertions into the string
  79993. * dictionary are very simple and thus fast, and deletions are avoided
  79994. * completely. Insertions are performed at each input character, whereas
  79995. * string matches are performed only when the previous match ends. So it
  79996. * is preferable to spend more time in matches to allow very fast string
  79997. * insertions and avoid deletions. The matching algorithm for small
  79998. * strings is inspired from that of Rabin & Karp. A brute force approach
  79999. * is used to find longer strings when a small match has been found.
  80000. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  80001. * (by Leonid Broukhis).
  80002. * A previous version of this file used a more sophisticated algorithm
  80003. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  80004. * time, but has a larger average cost, uses more memory and is patented.
  80005. * However the F&G algorithm may be faster for some highly redundant
  80006. * files if the parameter max_chain_length (described below) is too large.
  80007. *
  80008. * ACKNOWLEDGEMENTS
  80009. *
  80010. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  80011. * I found it in 'freeze' written by Leonid Broukhis.
  80012. * Thanks to many people for bug reports and testing.
  80013. *
  80014. * REFERENCES
  80015. *
  80016. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  80017. * Available in http://www.ietf.org/rfc/rfc1951.txt
  80018. *
  80019. * A description of the Rabin and Karp algorithm is given in the book
  80020. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  80021. *
  80022. * Fiala,E.R., and Greene,D.H.
  80023. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  80024. *
  80025. */
  80026. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80027. /*** Start of inlined file: deflate.h ***/
  80028. /* WARNING: this file should *not* be used by applications. It is
  80029. part of the implementation of the compression library and is
  80030. subject to change. Applications should only use zlib.h.
  80031. */
  80032. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80033. #ifndef DEFLATE_H
  80034. #define DEFLATE_H
  80035. /* define NO_GZIP when compiling if you want to disable gzip header and
  80036. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  80037. the crc code when it is not needed. For shared libraries, gzip encoding
  80038. should be left enabled. */
  80039. #ifndef NO_GZIP
  80040. # define GZIP
  80041. #endif
  80042. #define NO_DUMMY_DECL
  80043. /* ===========================================================================
  80044. * Internal compression state.
  80045. */
  80046. #define LENGTH_CODES 29
  80047. /* number of length codes, not counting the special END_BLOCK code */
  80048. #define LITERALS 256
  80049. /* number of literal bytes 0..255 */
  80050. #define L_CODES (LITERALS+1+LENGTH_CODES)
  80051. /* number of Literal or Length codes, including the END_BLOCK code */
  80052. #define D_CODES 30
  80053. /* number of distance codes */
  80054. #define BL_CODES 19
  80055. /* number of codes used to transfer the bit lengths */
  80056. #define HEAP_SIZE (2*L_CODES+1)
  80057. /* maximum heap size */
  80058. #define MAX_BITS 15
  80059. /* All codes must not exceed MAX_BITS bits */
  80060. #define INIT_STATE 42
  80061. #define EXTRA_STATE 69
  80062. #define NAME_STATE 73
  80063. #define COMMENT_STATE 91
  80064. #define HCRC_STATE 103
  80065. #define BUSY_STATE 113
  80066. #define FINISH_STATE 666
  80067. /* Stream status */
  80068. /* Data structure describing a single value and its code string. */
  80069. typedef struct ct_data_s {
  80070. union {
  80071. ush freq; /* frequency count */
  80072. ush code; /* bit string */
  80073. } fc;
  80074. union {
  80075. ush dad; /* father node in Huffman tree */
  80076. ush len; /* length of bit string */
  80077. } dl;
  80078. } FAR ct_data;
  80079. #define Freq fc.freq
  80080. #define Code fc.code
  80081. #define Dad dl.dad
  80082. #define Len dl.len
  80083. typedef struct static_tree_desc_s static_tree_desc;
  80084. typedef struct tree_desc_s {
  80085. ct_data *dyn_tree; /* the dynamic tree */
  80086. int max_code; /* largest code with non zero frequency */
  80087. static_tree_desc *stat_desc; /* the corresponding static tree */
  80088. } FAR tree_desc;
  80089. typedef ush Pos;
  80090. typedef Pos FAR Posf;
  80091. typedef unsigned IPos;
  80092. /* A Pos is an index in the character window. We use short instead of int to
  80093. * save space in the various tables. IPos is used only for parameter passing.
  80094. */
  80095. typedef struct internal_state {
  80096. z_streamp strm; /* pointer back to this zlib stream */
  80097. int status; /* as the name implies */
  80098. Bytef *pending_buf; /* output still pending */
  80099. ulg pending_buf_size; /* size of pending_buf */
  80100. Bytef *pending_out; /* next pending byte to output to the stream */
  80101. uInt pending; /* nb of bytes in the pending buffer */
  80102. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  80103. gz_headerp gzhead; /* gzip header information to write */
  80104. uInt gzindex; /* where in extra, name, or comment */
  80105. Byte method; /* STORED (for zip only) or DEFLATED */
  80106. int last_flush; /* value of flush param for previous deflate call */
  80107. /* used by deflate.c: */
  80108. uInt w_size; /* LZ77 window size (32K by default) */
  80109. uInt w_bits; /* log2(w_size) (8..16) */
  80110. uInt w_mask; /* w_size - 1 */
  80111. Bytef *window;
  80112. /* Sliding window. Input bytes are read into the second half of the window,
  80113. * and move to the first half later to keep a dictionary of at least wSize
  80114. * bytes. With this organization, matches are limited to a distance of
  80115. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  80116. * performed with a length multiple of the block size. Also, it limits
  80117. * the window size to 64K, which is quite useful on MSDOS.
  80118. * To do: use the user input buffer as sliding window.
  80119. */
  80120. ulg window_size;
  80121. /* Actual size of window: 2*wSize, except when the user input buffer
  80122. * is directly used as sliding window.
  80123. */
  80124. Posf *prev;
  80125. /* Link to older string with same hash index. To limit the size of this
  80126. * array to 64K, this link is maintained only for the last 32K strings.
  80127. * An index in this array is thus a window index modulo 32K.
  80128. */
  80129. Posf *head; /* Heads of the hash chains or NIL. */
  80130. uInt ins_h; /* hash index of string to be inserted */
  80131. uInt hash_size; /* number of elements in hash table */
  80132. uInt hash_bits; /* log2(hash_size) */
  80133. uInt hash_mask; /* hash_size-1 */
  80134. uInt hash_shift;
  80135. /* Number of bits by which ins_h must be shifted at each input
  80136. * step. It must be such that after MIN_MATCH steps, the oldest
  80137. * byte no longer takes part in the hash key, that is:
  80138. * hash_shift * MIN_MATCH >= hash_bits
  80139. */
  80140. long block_start;
  80141. /* Window position at the beginning of the current output block. Gets
  80142. * negative when the window is moved backwards.
  80143. */
  80144. uInt match_length; /* length of best match */
  80145. IPos prev_match; /* previous match */
  80146. int match_available; /* set if previous match exists */
  80147. uInt strstart; /* start of string to insert */
  80148. uInt match_start; /* start of matching string */
  80149. uInt lookahead; /* number of valid bytes ahead in window */
  80150. uInt prev_length;
  80151. /* Length of the best match at previous step. Matches not greater than this
  80152. * are discarded. This is used in the lazy match evaluation.
  80153. */
  80154. uInt max_chain_length;
  80155. /* To speed up deflation, hash chains are never searched beyond this
  80156. * length. A higher limit improves compression ratio but degrades the
  80157. * speed.
  80158. */
  80159. uInt max_lazy_match;
  80160. /* Attempt to find a better match only when the current match is strictly
  80161. * smaller than this value. This mechanism is used only for compression
  80162. * levels >= 4.
  80163. */
  80164. # define max_insert_length max_lazy_match
  80165. /* Insert new strings in the hash table only if the match length is not
  80166. * greater than this length. This saves time but degrades compression.
  80167. * max_insert_length is used only for compression levels <= 3.
  80168. */
  80169. int level; /* compression level (1..9) */
  80170. int strategy; /* favor or force Huffman coding*/
  80171. uInt good_match;
  80172. /* Use a faster search when the previous match is longer than this */
  80173. int nice_match; /* Stop searching when current match exceeds this */
  80174. /* used by trees.c: */
  80175. /* Didn't use ct_data typedef below to supress compiler warning */
  80176. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  80177. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  80178. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  80179. struct tree_desc_s l_desc; /* desc. for literal tree */
  80180. struct tree_desc_s d_desc; /* desc. for distance tree */
  80181. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  80182. ush bl_count[MAX_BITS+1];
  80183. /* number of codes at each bit length for an optimal tree */
  80184. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  80185. int heap_len; /* number of elements in the heap */
  80186. int heap_max; /* element of largest frequency */
  80187. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  80188. * The same heap array is used to build all trees.
  80189. */
  80190. uch depth[2*L_CODES+1];
  80191. /* Depth of each subtree used as tie breaker for trees of equal frequency
  80192. */
  80193. uchf *l_buf; /* buffer for literals or lengths */
  80194. uInt lit_bufsize;
  80195. /* Size of match buffer for literals/lengths. There are 4 reasons for
  80196. * limiting lit_bufsize to 64K:
  80197. * - frequencies can be kept in 16 bit counters
  80198. * - if compression is not successful for the first block, all input
  80199. * data is still in the window so we can still emit a stored block even
  80200. * when input comes from standard input. (This can also be done for
  80201. * all blocks if lit_bufsize is not greater than 32K.)
  80202. * - if compression is not successful for a file smaller than 64K, we can
  80203. * even emit a stored file instead of a stored block (saving 5 bytes).
  80204. * This is applicable only for zip (not gzip or zlib).
  80205. * - creating new Huffman trees less frequently may not provide fast
  80206. * adaptation to changes in the input data statistics. (Take for
  80207. * example a binary file with poorly compressible code followed by
  80208. * a highly compressible string table.) Smaller buffer sizes give
  80209. * fast adaptation but have of course the overhead of transmitting
  80210. * trees more frequently.
  80211. * - I can't count above 4
  80212. */
  80213. uInt last_lit; /* running index in l_buf */
  80214. ushf *d_buf;
  80215. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  80216. * the same number of elements. To use different lengths, an extra flag
  80217. * array would be necessary.
  80218. */
  80219. ulg opt_len; /* bit length of current block with optimal trees */
  80220. ulg static_len; /* bit length of current block with static trees */
  80221. uInt matches; /* number of string matches in current block */
  80222. int last_eob_len; /* bit length of EOB code for last block */
  80223. #ifdef DEBUG
  80224. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  80225. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  80226. #endif
  80227. ush bi_buf;
  80228. /* Output buffer. bits are inserted starting at the bottom (least
  80229. * significant bits).
  80230. */
  80231. int bi_valid;
  80232. /* Number of valid bits in bi_buf. All bits above the last valid bit
  80233. * are always zero.
  80234. */
  80235. } FAR deflate_state;
  80236. /* Output a byte on the stream.
  80237. * IN assertion: there is enough room in pending_buf.
  80238. */
  80239. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  80240. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  80241. /* Minimum amount of lookahead, except at the end of the input file.
  80242. * See deflate.c for comments about the MIN_MATCH+1.
  80243. */
  80244. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  80245. /* In order to simplify the code, particularly on 16 bit machines, match
  80246. * distances are limited to MAX_DIST instead of WSIZE.
  80247. */
  80248. /* in trees.c */
  80249. void _tr_init OF((deflate_state *s));
  80250. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  80251. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  80252. int eof));
  80253. void _tr_align OF((deflate_state *s));
  80254. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  80255. int eof));
  80256. #define d_code(dist) \
  80257. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  80258. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  80259. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  80260. * used.
  80261. */
  80262. #ifndef DEBUG
  80263. /* Inline versions of _tr_tally for speed: */
  80264. #if defined(GEN_TREES_H) || !defined(STDC)
  80265. extern uch _length_code[];
  80266. extern uch _dist_code[];
  80267. #else
  80268. extern const uch _length_code[];
  80269. extern const uch _dist_code[];
  80270. #endif
  80271. # define _tr_tally_lit(s, c, flush) \
  80272. { uch cc = (c); \
  80273. s->d_buf[s->last_lit] = 0; \
  80274. s->l_buf[s->last_lit++] = cc; \
  80275. s->dyn_ltree[cc].Freq++; \
  80276. flush = (s->last_lit == s->lit_bufsize-1); \
  80277. }
  80278. # define _tr_tally_dist(s, distance, length, flush) \
  80279. { uch len = (length); \
  80280. ush dist = (distance); \
  80281. s->d_buf[s->last_lit] = dist; \
  80282. s->l_buf[s->last_lit++] = len; \
  80283. dist--; \
  80284. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  80285. s->dyn_dtree[d_code(dist)].Freq++; \
  80286. flush = (s->last_lit == s->lit_bufsize-1); \
  80287. }
  80288. #else
  80289. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  80290. # define _tr_tally_dist(s, distance, length, flush) \
  80291. flush = _tr_tally(s, distance, length)
  80292. #endif
  80293. #endif /* DEFLATE_H */
  80294. /*** End of inlined file: deflate.h ***/
  80295. const char deflate_copyright[] =
  80296. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  80297. /*
  80298. If you use the zlib library in a product, an acknowledgment is welcome
  80299. in the documentation of your product. If for some reason you cannot
  80300. include such an acknowledgment, I would appreciate that you keep this
  80301. copyright string in the executable of your product.
  80302. */
  80303. /* ===========================================================================
  80304. * Function prototypes.
  80305. */
  80306. typedef enum {
  80307. need_more, /* block not completed, need more input or more output */
  80308. block_done, /* block flush performed */
  80309. finish_started, /* finish started, need only more output at next deflate */
  80310. finish_done /* finish done, accept no more input or output */
  80311. } block_state;
  80312. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  80313. /* Compression function. Returns the block state after the call. */
  80314. local void fill_window OF((deflate_state *s));
  80315. local block_state deflate_stored OF((deflate_state *s, int flush));
  80316. local block_state deflate_fast OF((deflate_state *s, int flush));
  80317. #ifndef FASTEST
  80318. local block_state deflate_slow OF((deflate_state *s, int flush));
  80319. #endif
  80320. local void lm_init OF((deflate_state *s));
  80321. local void putShortMSB OF((deflate_state *s, uInt b));
  80322. local void flush_pending OF((z_streamp strm));
  80323. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  80324. #ifndef FASTEST
  80325. #ifdef ASMV
  80326. void match_init OF((void)); /* asm code initialization */
  80327. uInt longest_match OF((deflate_state *s, IPos cur_match));
  80328. #else
  80329. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  80330. #endif
  80331. #endif
  80332. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  80333. #ifdef DEBUG
  80334. local void check_match OF((deflate_state *s, IPos start, IPos match,
  80335. int length));
  80336. #endif
  80337. /* ===========================================================================
  80338. * Local data
  80339. */
  80340. #define NIL 0
  80341. /* Tail of hash chains */
  80342. #ifndef TOO_FAR
  80343. # define TOO_FAR 4096
  80344. #endif
  80345. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  80346. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  80347. /* Minimum amount of lookahead, except at the end of the input file.
  80348. * See deflate.c for comments about the MIN_MATCH+1.
  80349. */
  80350. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  80351. * the desired pack level (0..9). The values given below have been tuned to
  80352. * exclude worst case performance for pathological files. Better values may be
  80353. * found for specific files.
  80354. */
  80355. typedef struct config_s {
  80356. ush good_length; /* reduce lazy search above this match length */
  80357. ush max_lazy; /* do not perform lazy search above this match length */
  80358. ush nice_length; /* quit search above this match length */
  80359. ush max_chain;
  80360. compress_func func;
  80361. } config;
  80362. #ifdef FASTEST
  80363. local const config configuration_table[2] = {
  80364. /* good lazy nice chain */
  80365. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  80366. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  80367. #else
  80368. local const config configuration_table[10] = {
  80369. /* good lazy nice chain */
  80370. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  80371. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  80372. /* 2 */ {4, 5, 16, 8, deflate_fast},
  80373. /* 3 */ {4, 6, 32, 32, deflate_fast},
  80374. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  80375. /* 5 */ {8, 16, 32, 32, deflate_slow},
  80376. /* 6 */ {8, 16, 128, 128, deflate_slow},
  80377. /* 7 */ {8, 32, 128, 256, deflate_slow},
  80378. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  80379. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  80380. #endif
  80381. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  80382. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  80383. * meaning.
  80384. */
  80385. #define EQUAL 0
  80386. /* result of memcmp for equal strings */
  80387. #ifndef NO_DUMMY_DECL
  80388. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  80389. #endif
  80390. /* ===========================================================================
  80391. * Update a hash value with the given input byte
  80392. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  80393. * input characters, so that a running hash key can be computed from the
  80394. * previous key instead of complete recalculation each time.
  80395. */
  80396. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  80397. /* ===========================================================================
  80398. * Insert string str in the dictionary and set match_head to the previous head
  80399. * of the hash chain (the most recent string with same hash key). Return
  80400. * the previous length of the hash chain.
  80401. * If this file is compiled with -DFASTEST, the compression level is forced
  80402. * to 1, and no hash chains are maintained.
  80403. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  80404. * input characters and the first MIN_MATCH bytes of str are valid
  80405. * (except for the last MIN_MATCH-1 bytes of the input file).
  80406. */
  80407. #ifdef FASTEST
  80408. #define INSERT_STRING(s, str, match_head) \
  80409. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  80410. match_head = s->head[s->ins_h], \
  80411. s->head[s->ins_h] = (Pos)(str))
  80412. #else
  80413. #define INSERT_STRING(s, str, match_head) \
  80414. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  80415. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  80416. s->head[s->ins_h] = (Pos)(str))
  80417. #endif
  80418. /* ===========================================================================
  80419. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  80420. * prev[] will be initialized on the fly.
  80421. */
  80422. #define CLEAR_HASH(s) \
  80423. s->head[s->hash_size-1] = NIL; \
  80424. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  80425. /* ========================================================================= */
  80426. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  80427. {
  80428. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  80429. Z_DEFAULT_STRATEGY, version, stream_size);
  80430. /* To do: ignore strm->next_in if we use it as window */
  80431. }
  80432. /* ========================================================================= */
  80433. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  80434. {
  80435. deflate_state *s;
  80436. int wrap = 1;
  80437. static const char my_version[] = ZLIB_VERSION;
  80438. ushf *overlay;
  80439. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  80440. * output size for (length,distance) codes is <= 24 bits.
  80441. */
  80442. if (version == Z_NULL || version[0] != my_version[0] ||
  80443. stream_size != sizeof(z_stream)) {
  80444. return Z_VERSION_ERROR;
  80445. }
  80446. if (strm == Z_NULL) return Z_STREAM_ERROR;
  80447. strm->msg = Z_NULL;
  80448. if (strm->zalloc == (alloc_func)0) {
  80449. strm->zalloc = zcalloc;
  80450. strm->opaque = (voidpf)0;
  80451. }
  80452. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  80453. #ifdef FASTEST
  80454. if (level != 0) level = 1;
  80455. #else
  80456. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  80457. #endif
  80458. if (windowBits < 0) { /* suppress zlib wrapper */
  80459. wrap = 0;
  80460. windowBits = -windowBits;
  80461. }
  80462. #ifdef GZIP
  80463. else if (windowBits > 15) {
  80464. wrap = 2; /* write gzip wrapper instead */
  80465. windowBits -= 16;
  80466. }
  80467. #endif
  80468. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  80469. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  80470. strategy < 0 || strategy > Z_FIXED) {
  80471. return Z_STREAM_ERROR;
  80472. }
  80473. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  80474. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  80475. if (s == Z_NULL) return Z_MEM_ERROR;
  80476. strm->state = (struct internal_state FAR *)s;
  80477. s->strm = strm;
  80478. s->wrap = wrap;
  80479. s->gzhead = Z_NULL;
  80480. s->w_bits = windowBits;
  80481. s->w_size = 1 << s->w_bits;
  80482. s->w_mask = s->w_size - 1;
  80483. s->hash_bits = memLevel + 7;
  80484. s->hash_size = 1 << s->hash_bits;
  80485. s->hash_mask = s->hash_size - 1;
  80486. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  80487. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  80488. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  80489. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  80490. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  80491. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  80492. s->pending_buf = (uchf *) overlay;
  80493. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  80494. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  80495. s->pending_buf == Z_NULL) {
  80496. s->status = FINISH_STATE;
  80497. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  80498. deflateEnd (strm);
  80499. return Z_MEM_ERROR;
  80500. }
  80501. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  80502. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  80503. s->level = level;
  80504. s->strategy = strategy;
  80505. s->method = (Byte)method;
  80506. return deflateReset(strm);
  80507. }
  80508. /* ========================================================================= */
  80509. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  80510. {
  80511. deflate_state *s;
  80512. uInt length = dictLength;
  80513. uInt n;
  80514. IPos hash_head = 0;
  80515. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  80516. strm->state->wrap == 2 ||
  80517. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  80518. return Z_STREAM_ERROR;
  80519. s = strm->state;
  80520. if (s->wrap)
  80521. strm->adler = adler32(strm->adler, dictionary, dictLength);
  80522. if (length < MIN_MATCH) return Z_OK;
  80523. if (length > MAX_DIST(s)) {
  80524. length = MAX_DIST(s);
  80525. dictionary += dictLength - length; /* use the tail of the dictionary */
  80526. }
  80527. zmemcpy(s->window, dictionary, length);
  80528. s->strstart = length;
  80529. s->block_start = (long)length;
  80530. /* Insert all strings in the hash table (except for the last two bytes).
  80531. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  80532. * call of fill_window.
  80533. */
  80534. s->ins_h = s->window[0];
  80535. UPDATE_HASH(s, s->ins_h, s->window[1]);
  80536. for (n = 0; n <= length - MIN_MATCH; n++) {
  80537. INSERT_STRING(s, n, hash_head);
  80538. }
  80539. if (hash_head) hash_head = 0; /* to make compiler happy */
  80540. return Z_OK;
  80541. }
  80542. /* ========================================================================= */
  80543. int ZEXPORT deflateReset (z_streamp strm)
  80544. {
  80545. deflate_state *s;
  80546. if (strm == Z_NULL || strm->state == Z_NULL ||
  80547. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  80548. return Z_STREAM_ERROR;
  80549. }
  80550. strm->total_in = strm->total_out = 0;
  80551. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  80552. strm->data_type = Z_UNKNOWN;
  80553. s = (deflate_state *)strm->state;
  80554. s->pending = 0;
  80555. s->pending_out = s->pending_buf;
  80556. if (s->wrap < 0) {
  80557. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  80558. }
  80559. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  80560. strm->adler =
  80561. #ifdef GZIP
  80562. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  80563. #endif
  80564. adler32(0L, Z_NULL, 0);
  80565. s->last_flush = Z_NO_FLUSH;
  80566. _tr_init(s);
  80567. lm_init(s);
  80568. return Z_OK;
  80569. }
  80570. /* ========================================================================= */
  80571. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  80572. {
  80573. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80574. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  80575. strm->state->gzhead = head;
  80576. return Z_OK;
  80577. }
  80578. /* ========================================================================= */
  80579. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  80580. {
  80581. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80582. strm->state->bi_valid = bits;
  80583. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  80584. return Z_OK;
  80585. }
  80586. /* ========================================================================= */
  80587. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  80588. {
  80589. deflate_state *s;
  80590. compress_func func;
  80591. int err = Z_OK;
  80592. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80593. s = strm->state;
  80594. #ifdef FASTEST
  80595. if (level != 0) level = 1;
  80596. #else
  80597. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  80598. #endif
  80599. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  80600. return Z_STREAM_ERROR;
  80601. }
  80602. func = configuration_table[s->level].func;
  80603. if (func != configuration_table[level].func && strm->total_in != 0) {
  80604. /* Flush the last buffer: */
  80605. err = deflate(strm, Z_PARTIAL_FLUSH);
  80606. }
  80607. if (s->level != level) {
  80608. s->level = level;
  80609. s->max_lazy_match = configuration_table[level].max_lazy;
  80610. s->good_match = configuration_table[level].good_length;
  80611. s->nice_match = configuration_table[level].nice_length;
  80612. s->max_chain_length = configuration_table[level].max_chain;
  80613. }
  80614. s->strategy = strategy;
  80615. return err;
  80616. }
  80617. /* ========================================================================= */
  80618. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  80619. {
  80620. deflate_state *s;
  80621. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80622. s = strm->state;
  80623. s->good_match = good_length;
  80624. s->max_lazy_match = max_lazy;
  80625. s->nice_match = nice_length;
  80626. s->max_chain_length = max_chain;
  80627. return Z_OK;
  80628. }
  80629. /* =========================================================================
  80630. * For the default windowBits of 15 and memLevel of 8, this function returns
  80631. * a close to exact, as well as small, upper bound on the compressed size.
  80632. * They are coded as constants here for a reason--if the #define's are
  80633. * changed, then this function needs to be changed as well. The return
  80634. * value for 15 and 8 only works for those exact settings.
  80635. *
  80636. * For any setting other than those defaults for windowBits and memLevel,
  80637. * the value returned is a conservative worst case for the maximum expansion
  80638. * resulting from using fixed blocks instead of stored blocks, which deflate
  80639. * can emit on compressed data for some combinations of the parameters.
  80640. *
  80641. * This function could be more sophisticated to provide closer upper bounds
  80642. * for every combination of windowBits and memLevel, as well as wrap.
  80643. * But even the conservative upper bound of about 14% expansion does not
  80644. * seem onerous for output buffer allocation.
  80645. */
  80646. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  80647. {
  80648. deflate_state *s;
  80649. uLong destLen;
  80650. /* conservative upper bound */
  80651. destLen = sourceLen +
  80652. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  80653. /* if can't get parameters, return conservative bound */
  80654. if (strm == Z_NULL || strm->state == Z_NULL)
  80655. return destLen;
  80656. /* if not default parameters, return conservative bound */
  80657. s = strm->state;
  80658. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  80659. return destLen;
  80660. /* default settings: return tight bound for that case */
  80661. return compressBound(sourceLen);
  80662. }
  80663. /* =========================================================================
  80664. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  80665. * IN assertion: the stream state is correct and there is enough room in
  80666. * pending_buf.
  80667. */
  80668. local void putShortMSB (deflate_state *s, uInt b)
  80669. {
  80670. put_byte(s, (Byte)(b >> 8));
  80671. put_byte(s, (Byte)(b & 0xff));
  80672. }
  80673. /* =========================================================================
  80674. * Flush as much pending output as possible. All deflate() output goes
  80675. * through this function so some applications may wish to modify it
  80676. * to avoid allocating a large strm->next_out buffer and copying into it.
  80677. * (See also read_buf()).
  80678. */
  80679. local void flush_pending (z_streamp strm)
  80680. {
  80681. unsigned len = strm->state->pending;
  80682. if (len > strm->avail_out) len = strm->avail_out;
  80683. if (len == 0) return;
  80684. zmemcpy(strm->next_out, strm->state->pending_out, len);
  80685. strm->next_out += len;
  80686. strm->state->pending_out += len;
  80687. strm->total_out += len;
  80688. strm->avail_out -= len;
  80689. strm->state->pending -= len;
  80690. if (strm->state->pending == 0) {
  80691. strm->state->pending_out = strm->state->pending_buf;
  80692. }
  80693. }
  80694. /* ========================================================================= */
  80695. int ZEXPORT deflate (z_streamp strm, int flush)
  80696. {
  80697. int old_flush; /* value of flush param for previous deflate call */
  80698. deflate_state *s;
  80699. if (strm == Z_NULL || strm->state == Z_NULL ||
  80700. flush > Z_FINISH || flush < 0) {
  80701. return Z_STREAM_ERROR;
  80702. }
  80703. s = strm->state;
  80704. if (strm->next_out == Z_NULL ||
  80705. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  80706. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  80707. ERR_RETURN(strm, Z_STREAM_ERROR);
  80708. }
  80709. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  80710. s->strm = strm; /* just in case */
  80711. old_flush = s->last_flush;
  80712. s->last_flush = flush;
  80713. /* Write the header */
  80714. if (s->status == INIT_STATE) {
  80715. #ifdef GZIP
  80716. if (s->wrap == 2) {
  80717. strm->adler = crc32(0L, Z_NULL, 0);
  80718. put_byte(s, 31);
  80719. put_byte(s, 139);
  80720. put_byte(s, 8);
  80721. if (s->gzhead == NULL) {
  80722. put_byte(s, 0);
  80723. put_byte(s, 0);
  80724. put_byte(s, 0);
  80725. put_byte(s, 0);
  80726. put_byte(s, 0);
  80727. put_byte(s, s->level == 9 ? 2 :
  80728. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  80729. 4 : 0));
  80730. put_byte(s, OS_CODE);
  80731. s->status = BUSY_STATE;
  80732. }
  80733. else {
  80734. put_byte(s, (s->gzhead->text ? 1 : 0) +
  80735. (s->gzhead->hcrc ? 2 : 0) +
  80736. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  80737. (s->gzhead->name == Z_NULL ? 0 : 8) +
  80738. (s->gzhead->comment == Z_NULL ? 0 : 16)
  80739. );
  80740. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  80741. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  80742. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  80743. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  80744. put_byte(s, s->level == 9 ? 2 :
  80745. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  80746. 4 : 0));
  80747. put_byte(s, s->gzhead->os & 0xff);
  80748. if (s->gzhead->extra != NULL) {
  80749. put_byte(s, s->gzhead->extra_len & 0xff);
  80750. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  80751. }
  80752. if (s->gzhead->hcrc)
  80753. strm->adler = crc32(strm->adler, s->pending_buf,
  80754. s->pending);
  80755. s->gzindex = 0;
  80756. s->status = EXTRA_STATE;
  80757. }
  80758. }
  80759. else
  80760. #endif
  80761. {
  80762. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  80763. uInt level_flags;
  80764. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  80765. level_flags = 0;
  80766. else if (s->level < 6)
  80767. level_flags = 1;
  80768. else if (s->level == 6)
  80769. level_flags = 2;
  80770. else
  80771. level_flags = 3;
  80772. header |= (level_flags << 6);
  80773. if (s->strstart != 0) header |= PRESET_DICT;
  80774. header += 31 - (header % 31);
  80775. s->status = BUSY_STATE;
  80776. putShortMSB(s, header);
  80777. /* Save the adler32 of the preset dictionary: */
  80778. if (s->strstart != 0) {
  80779. putShortMSB(s, (uInt)(strm->adler >> 16));
  80780. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  80781. }
  80782. strm->adler = adler32(0L, Z_NULL, 0);
  80783. }
  80784. }
  80785. #ifdef GZIP
  80786. if (s->status == EXTRA_STATE) {
  80787. if (s->gzhead->extra != NULL) {
  80788. uInt beg = s->pending; /* start of bytes to update crc */
  80789. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  80790. if (s->pending == s->pending_buf_size) {
  80791. if (s->gzhead->hcrc && s->pending > beg)
  80792. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  80793. s->pending - beg);
  80794. flush_pending(strm);
  80795. beg = s->pending;
  80796. if (s->pending == s->pending_buf_size)
  80797. break;
  80798. }
  80799. put_byte(s, s->gzhead->extra[s->gzindex]);
  80800. s->gzindex++;
  80801. }
  80802. if (s->gzhead->hcrc && s->pending > beg)
  80803. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  80804. s->pending - beg);
  80805. if (s->gzindex == s->gzhead->extra_len) {
  80806. s->gzindex = 0;
  80807. s->status = NAME_STATE;
  80808. }
  80809. }
  80810. else
  80811. s->status = NAME_STATE;
  80812. }
  80813. if (s->status == NAME_STATE) {
  80814. if (s->gzhead->name != NULL) {
  80815. uInt beg = s->pending; /* start of bytes to update crc */
  80816. int val;
  80817. do {
  80818. if (s->pending == s->pending_buf_size) {
  80819. if (s->gzhead->hcrc && s->pending > beg)
  80820. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  80821. s->pending - beg);
  80822. flush_pending(strm);
  80823. beg = s->pending;
  80824. if (s->pending == s->pending_buf_size) {
  80825. val = 1;
  80826. break;
  80827. }
  80828. }
  80829. val = s->gzhead->name[s->gzindex++];
  80830. put_byte(s, val);
  80831. } while (val != 0);
  80832. if (s->gzhead->hcrc && s->pending > beg)
  80833. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  80834. s->pending - beg);
  80835. if (val == 0) {
  80836. s->gzindex = 0;
  80837. s->status = COMMENT_STATE;
  80838. }
  80839. }
  80840. else
  80841. s->status = COMMENT_STATE;
  80842. }
  80843. if (s->status == COMMENT_STATE) {
  80844. if (s->gzhead->comment != NULL) {
  80845. uInt beg = s->pending; /* start of bytes to update crc */
  80846. int val;
  80847. do {
  80848. if (s->pending == s->pending_buf_size) {
  80849. if (s->gzhead->hcrc && s->pending > beg)
  80850. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  80851. s->pending - beg);
  80852. flush_pending(strm);
  80853. beg = s->pending;
  80854. if (s->pending == s->pending_buf_size) {
  80855. val = 1;
  80856. break;
  80857. }
  80858. }
  80859. val = s->gzhead->comment[s->gzindex++];
  80860. put_byte(s, val);
  80861. } while (val != 0);
  80862. if (s->gzhead->hcrc && s->pending > beg)
  80863. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  80864. s->pending - beg);
  80865. if (val == 0)
  80866. s->status = HCRC_STATE;
  80867. }
  80868. else
  80869. s->status = HCRC_STATE;
  80870. }
  80871. if (s->status == HCRC_STATE) {
  80872. if (s->gzhead->hcrc) {
  80873. if (s->pending + 2 > s->pending_buf_size)
  80874. flush_pending(strm);
  80875. if (s->pending + 2 <= s->pending_buf_size) {
  80876. put_byte(s, (Byte)(strm->adler & 0xff));
  80877. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  80878. strm->adler = crc32(0L, Z_NULL, 0);
  80879. s->status = BUSY_STATE;
  80880. }
  80881. }
  80882. else
  80883. s->status = BUSY_STATE;
  80884. }
  80885. #endif
  80886. /* Flush as much pending output as possible */
  80887. if (s->pending != 0) {
  80888. flush_pending(strm);
  80889. if (strm->avail_out == 0) {
  80890. /* Since avail_out is 0, deflate will be called again with
  80891. * more output space, but possibly with both pending and
  80892. * avail_in equal to zero. There won't be anything to do,
  80893. * but this is not an error situation so make sure we
  80894. * return OK instead of BUF_ERROR at next call of deflate:
  80895. */
  80896. s->last_flush = -1;
  80897. return Z_OK;
  80898. }
  80899. /* Make sure there is something to do and avoid duplicate consecutive
  80900. * flushes. For repeated and useless calls with Z_FINISH, we keep
  80901. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  80902. */
  80903. } else if (strm->avail_in == 0 && flush <= old_flush &&
  80904. flush != Z_FINISH) {
  80905. ERR_RETURN(strm, Z_BUF_ERROR);
  80906. }
  80907. /* User must not provide more input after the first FINISH: */
  80908. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  80909. ERR_RETURN(strm, Z_BUF_ERROR);
  80910. }
  80911. /* Start a new block or continue the current one.
  80912. */
  80913. if (strm->avail_in != 0 || s->lookahead != 0 ||
  80914. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  80915. block_state bstate;
  80916. bstate = (*(configuration_table[s->level].func))(s, flush);
  80917. if (bstate == finish_started || bstate == finish_done) {
  80918. s->status = FINISH_STATE;
  80919. }
  80920. if (bstate == need_more || bstate == finish_started) {
  80921. if (strm->avail_out == 0) {
  80922. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  80923. }
  80924. return Z_OK;
  80925. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  80926. * of deflate should use the same flush parameter to make sure
  80927. * that the flush is complete. So we don't have to output an
  80928. * empty block here, this will be done at next call. This also
  80929. * ensures that for a very small output buffer, we emit at most
  80930. * one empty block.
  80931. */
  80932. }
  80933. if (bstate == block_done) {
  80934. if (flush == Z_PARTIAL_FLUSH) {
  80935. _tr_align(s);
  80936. } else { /* FULL_FLUSH or SYNC_FLUSH */
  80937. _tr_stored_block(s, (char*)0, 0L, 0);
  80938. /* For a full flush, this empty block will be recognized
  80939. * as a special marker by inflate_sync().
  80940. */
  80941. if (flush == Z_FULL_FLUSH) {
  80942. CLEAR_HASH(s); /* forget history */
  80943. }
  80944. }
  80945. flush_pending(strm);
  80946. if (strm->avail_out == 0) {
  80947. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  80948. return Z_OK;
  80949. }
  80950. }
  80951. }
  80952. Assert(strm->avail_out > 0, "bug2");
  80953. if (flush != Z_FINISH) return Z_OK;
  80954. if (s->wrap <= 0) return Z_STREAM_END;
  80955. /* Write the trailer */
  80956. #ifdef GZIP
  80957. if (s->wrap == 2) {
  80958. put_byte(s, (Byte)(strm->adler & 0xff));
  80959. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  80960. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  80961. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  80962. put_byte(s, (Byte)(strm->total_in & 0xff));
  80963. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  80964. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  80965. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  80966. }
  80967. else
  80968. #endif
  80969. {
  80970. putShortMSB(s, (uInt)(strm->adler >> 16));
  80971. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  80972. }
  80973. flush_pending(strm);
  80974. /* If avail_out is zero, the application will call deflate again
  80975. * to flush the rest.
  80976. */
  80977. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  80978. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  80979. }
  80980. /* ========================================================================= */
  80981. int ZEXPORT deflateEnd (z_streamp strm)
  80982. {
  80983. int status;
  80984. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  80985. status = strm->state->status;
  80986. if (status != INIT_STATE &&
  80987. status != EXTRA_STATE &&
  80988. status != NAME_STATE &&
  80989. status != COMMENT_STATE &&
  80990. status != HCRC_STATE &&
  80991. status != BUSY_STATE &&
  80992. status != FINISH_STATE) {
  80993. return Z_STREAM_ERROR;
  80994. }
  80995. /* Deallocate in reverse order of allocations: */
  80996. TRY_FREE(strm, strm->state->pending_buf);
  80997. TRY_FREE(strm, strm->state->head);
  80998. TRY_FREE(strm, strm->state->prev);
  80999. TRY_FREE(strm, strm->state->window);
  81000. ZFREE(strm, strm->state);
  81001. strm->state = Z_NULL;
  81002. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  81003. }
  81004. /* =========================================================================
  81005. * Copy the source state to the destination state.
  81006. * To simplify the source, this is not supported for 16-bit MSDOS (which
  81007. * doesn't have enough memory anyway to duplicate compression states).
  81008. */
  81009. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  81010. {
  81011. #ifdef MAXSEG_64K
  81012. return Z_STREAM_ERROR;
  81013. #else
  81014. deflate_state *ds;
  81015. deflate_state *ss;
  81016. ushf *overlay;
  81017. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  81018. return Z_STREAM_ERROR;
  81019. }
  81020. ss = source->state;
  81021. zmemcpy(dest, source, sizeof(z_stream));
  81022. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  81023. if (ds == Z_NULL) return Z_MEM_ERROR;
  81024. dest->state = (struct internal_state FAR *) ds;
  81025. zmemcpy(ds, ss, sizeof(deflate_state));
  81026. ds->strm = dest;
  81027. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  81028. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  81029. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  81030. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  81031. ds->pending_buf = (uchf *) overlay;
  81032. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  81033. ds->pending_buf == Z_NULL) {
  81034. deflateEnd (dest);
  81035. return Z_MEM_ERROR;
  81036. }
  81037. /* following zmemcpy do not work for 16-bit MSDOS */
  81038. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  81039. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  81040. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  81041. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  81042. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  81043. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  81044. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  81045. ds->l_desc.dyn_tree = ds->dyn_ltree;
  81046. ds->d_desc.dyn_tree = ds->dyn_dtree;
  81047. ds->bl_desc.dyn_tree = ds->bl_tree;
  81048. return Z_OK;
  81049. #endif /* MAXSEG_64K */
  81050. }
  81051. /* ===========================================================================
  81052. * Read a new buffer from the current input stream, update the adler32
  81053. * and total number of bytes read. All deflate() input goes through
  81054. * this function so some applications may wish to modify it to avoid
  81055. * allocating a large strm->next_in buffer and copying from it.
  81056. * (See also flush_pending()).
  81057. */
  81058. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  81059. {
  81060. unsigned len = strm->avail_in;
  81061. if (len > size) len = size;
  81062. if (len == 0) return 0;
  81063. strm->avail_in -= len;
  81064. if (strm->state->wrap == 1) {
  81065. strm->adler = adler32(strm->adler, strm->next_in, len);
  81066. }
  81067. #ifdef GZIP
  81068. else if (strm->state->wrap == 2) {
  81069. strm->adler = crc32(strm->adler, strm->next_in, len);
  81070. }
  81071. #endif
  81072. zmemcpy(buf, strm->next_in, len);
  81073. strm->next_in += len;
  81074. strm->total_in += len;
  81075. return (int)len;
  81076. }
  81077. /* ===========================================================================
  81078. * Initialize the "longest match" routines for a new zlib stream
  81079. */
  81080. local void lm_init (deflate_state *s)
  81081. {
  81082. s->window_size = (ulg)2L*s->w_size;
  81083. CLEAR_HASH(s);
  81084. /* Set the default configuration parameters:
  81085. */
  81086. s->max_lazy_match = configuration_table[s->level].max_lazy;
  81087. s->good_match = configuration_table[s->level].good_length;
  81088. s->nice_match = configuration_table[s->level].nice_length;
  81089. s->max_chain_length = configuration_table[s->level].max_chain;
  81090. s->strstart = 0;
  81091. s->block_start = 0L;
  81092. s->lookahead = 0;
  81093. s->match_length = s->prev_length = MIN_MATCH-1;
  81094. s->match_available = 0;
  81095. s->ins_h = 0;
  81096. #ifndef FASTEST
  81097. #ifdef ASMV
  81098. match_init(); /* initialize the asm code */
  81099. #endif
  81100. #endif
  81101. }
  81102. #ifndef FASTEST
  81103. /* ===========================================================================
  81104. * Set match_start to the longest match starting at the given string and
  81105. * return its length. Matches shorter or equal to prev_length are discarded,
  81106. * in which case the result is equal to prev_length and match_start is
  81107. * garbage.
  81108. * IN assertions: cur_match is the head of the hash chain for the current
  81109. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  81110. * OUT assertion: the match length is not greater than s->lookahead.
  81111. */
  81112. #ifndef ASMV
  81113. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  81114. * match.S. The code will be functionally equivalent.
  81115. */
  81116. local uInt longest_match(deflate_state *s, IPos cur_match)
  81117. {
  81118. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  81119. register Bytef *scan = s->window + s->strstart; /* current string */
  81120. register Bytef *match; /* matched string */
  81121. register int len; /* length of current match */
  81122. int best_len = s->prev_length; /* best match length so far */
  81123. int nice_match = s->nice_match; /* stop if match long enough */
  81124. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  81125. s->strstart - (IPos)MAX_DIST(s) : NIL;
  81126. /* Stop when cur_match becomes <= limit. To simplify the code,
  81127. * we prevent matches with the string of window index 0.
  81128. */
  81129. Posf *prev = s->prev;
  81130. uInt wmask = s->w_mask;
  81131. #ifdef UNALIGNED_OK
  81132. /* Compare two bytes at a time. Note: this is not always beneficial.
  81133. * Try with and without -DUNALIGNED_OK to check.
  81134. */
  81135. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  81136. register ush scan_start = *(ushf*)scan;
  81137. register ush scan_end = *(ushf*)(scan+best_len-1);
  81138. #else
  81139. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  81140. register Byte scan_end1 = scan[best_len-1];
  81141. register Byte scan_end = scan[best_len];
  81142. #endif
  81143. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  81144. * It is easy to get rid of this optimization if necessary.
  81145. */
  81146. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  81147. /* Do not waste too much time if we already have a good match: */
  81148. if (s->prev_length >= s->good_match) {
  81149. chain_length >>= 2;
  81150. }
  81151. /* Do not look for matches beyond the end of the input. This is necessary
  81152. * to make deflate deterministic.
  81153. */
  81154. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  81155. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  81156. do {
  81157. Assert(cur_match < s->strstart, "no future");
  81158. match = s->window + cur_match;
  81159. /* Skip to next match if the match length cannot increase
  81160. * or if the match length is less than 2. Note that the checks below
  81161. * for insufficient lookahead only occur occasionally for performance
  81162. * reasons. Therefore uninitialized memory will be accessed, and
  81163. * conditional jumps will be made that depend on those values.
  81164. * However the length of the match is limited to the lookahead, so
  81165. * the output of deflate is not affected by the uninitialized values.
  81166. */
  81167. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  81168. /* This code assumes sizeof(unsigned short) == 2. Do not use
  81169. * UNALIGNED_OK if your compiler uses a different size.
  81170. */
  81171. if (*(ushf*)(match+best_len-1) != scan_end ||
  81172. *(ushf*)match != scan_start) continue;
  81173. /* It is not necessary to compare scan[2] and match[2] since they are
  81174. * always equal when the other bytes match, given that the hash keys
  81175. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  81176. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  81177. * lookahead only every 4th comparison; the 128th check will be made
  81178. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  81179. * necessary to put more guard bytes at the end of the window, or
  81180. * to check more often for insufficient lookahead.
  81181. */
  81182. Assert(scan[2] == match[2], "scan[2]?");
  81183. scan++, match++;
  81184. do {
  81185. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81186. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81187. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81188. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81189. scan < strend);
  81190. /* The funny "do {}" generates better code on most compilers */
  81191. /* Here, scan <= window+strstart+257 */
  81192. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  81193. if (*scan == *match) scan++;
  81194. len = (MAX_MATCH - 1) - (int)(strend-scan);
  81195. scan = strend - (MAX_MATCH-1);
  81196. #else /* UNALIGNED_OK */
  81197. if (match[best_len] != scan_end ||
  81198. match[best_len-1] != scan_end1 ||
  81199. *match != *scan ||
  81200. *++match != scan[1]) continue;
  81201. /* The check at best_len-1 can be removed because it will be made
  81202. * again later. (This heuristic is not always a win.)
  81203. * It is not necessary to compare scan[2] and match[2] since they
  81204. * are always equal when the other bytes match, given that
  81205. * the hash keys are equal and that HASH_BITS >= 8.
  81206. */
  81207. scan += 2, match++;
  81208. Assert(*scan == *match, "match[2]?");
  81209. /* We check for insufficient lookahead only every 8th comparison;
  81210. * the 256th check will be made at strstart+258.
  81211. */
  81212. do {
  81213. } while (*++scan == *++match && *++scan == *++match &&
  81214. *++scan == *++match && *++scan == *++match &&
  81215. *++scan == *++match && *++scan == *++match &&
  81216. *++scan == *++match && *++scan == *++match &&
  81217. scan < strend);
  81218. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  81219. len = MAX_MATCH - (int)(strend - scan);
  81220. scan = strend - MAX_MATCH;
  81221. #endif /* UNALIGNED_OK */
  81222. if (len > best_len) {
  81223. s->match_start = cur_match;
  81224. best_len = len;
  81225. if (len >= nice_match) break;
  81226. #ifdef UNALIGNED_OK
  81227. scan_end = *(ushf*)(scan+best_len-1);
  81228. #else
  81229. scan_end1 = scan[best_len-1];
  81230. scan_end = scan[best_len];
  81231. #endif
  81232. }
  81233. } while ((cur_match = prev[cur_match & wmask]) > limit
  81234. && --chain_length != 0);
  81235. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  81236. return s->lookahead;
  81237. }
  81238. #endif /* ASMV */
  81239. #endif /* FASTEST */
  81240. /* ---------------------------------------------------------------------------
  81241. * Optimized version for level == 1 or strategy == Z_RLE only
  81242. */
  81243. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  81244. {
  81245. register Bytef *scan = s->window + s->strstart; /* current string */
  81246. register Bytef *match; /* matched string */
  81247. register int len; /* length of current match */
  81248. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  81249. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  81250. * It is easy to get rid of this optimization if necessary.
  81251. */
  81252. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  81253. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  81254. Assert(cur_match < s->strstart, "no future");
  81255. match = s->window + cur_match;
  81256. /* Return failure if the match length is less than 2:
  81257. */
  81258. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  81259. /* The check at best_len-1 can be removed because it will be made
  81260. * again later. (This heuristic is not always a win.)
  81261. * It is not necessary to compare scan[2] and match[2] since they
  81262. * are always equal when the other bytes match, given that
  81263. * the hash keys are equal and that HASH_BITS >= 8.
  81264. */
  81265. scan += 2, match += 2;
  81266. Assert(*scan == *match, "match[2]?");
  81267. /* We check for insufficient lookahead only every 8th comparison;
  81268. * the 256th check will be made at strstart+258.
  81269. */
  81270. do {
  81271. } while (*++scan == *++match && *++scan == *++match &&
  81272. *++scan == *++match && *++scan == *++match &&
  81273. *++scan == *++match && *++scan == *++match &&
  81274. *++scan == *++match && *++scan == *++match &&
  81275. scan < strend);
  81276. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  81277. len = MAX_MATCH - (int)(strend - scan);
  81278. if (len < MIN_MATCH) return MIN_MATCH - 1;
  81279. s->match_start = cur_match;
  81280. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  81281. }
  81282. #ifdef DEBUG
  81283. /* ===========================================================================
  81284. * Check that the match at match_start is indeed a match.
  81285. */
  81286. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  81287. {
  81288. /* check that the match is indeed a match */
  81289. if (zmemcmp(s->window + match,
  81290. s->window + start, length) != EQUAL) {
  81291. fprintf(stderr, " start %u, match %u, length %d\n",
  81292. start, match, length);
  81293. do {
  81294. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  81295. } while (--length != 0);
  81296. z_error("invalid match");
  81297. }
  81298. if (z_verbose > 1) {
  81299. fprintf(stderr,"\\[%d,%d]", start-match, length);
  81300. do { putc(s->window[start++], stderr); } while (--length != 0);
  81301. }
  81302. }
  81303. #else
  81304. # define check_match(s, start, match, length)
  81305. #endif /* DEBUG */
  81306. /* ===========================================================================
  81307. * Fill the window when the lookahead becomes insufficient.
  81308. * Updates strstart and lookahead.
  81309. *
  81310. * IN assertion: lookahead < MIN_LOOKAHEAD
  81311. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  81312. * At least one byte has been read, or avail_in == 0; reads are
  81313. * performed for at least two bytes (required for the zip translate_eol
  81314. * option -- not supported here).
  81315. */
  81316. local void fill_window (deflate_state *s)
  81317. {
  81318. register unsigned n, m;
  81319. register Posf *p;
  81320. unsigned more; /* Amount of free space at the end of the window. */
  81321. uInt wsize = s->w_size;
  81322. do {
  81323. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  81324. /* Deal with !@#$% 64K limit: */
  81325. if (sizeof(int) <= 2) {
  81326. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  81327. more = wsize;
  81328. } else if (more == (unsigned)(-1)) {
  81329. /* Very unlikely, but possible on 16 bit machine if
  81330. * strstart == 0 && lookahead == 1 (input done a byte at time)
  81331. */
  81332. more--;
  81333. }
  81334. }
  81335. /* If the window is almost full and there is insufficient lookahead,
  81336. * move the upper half to the lower one to make room in the upper half.
  81337. */
  81338. if (s->strstart >= wsize+MAX_DIST(s)) {
  81339. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  81340. s->match_start -= wsize;
  81341. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  81342. s->block_start -= (long) wsize;
  81343. /* Slide the hash table (could be avoided with 32 bit values
  81344. at the expense of memory usage). We slide even when level == 0
  81345. to keep the hash table consistent if we switch back to level > 0
  81346. later. (Using level 0 permanently is not an optimal usage of
  81347. zlib, so we don't care about this pathological case.)
  81348. */
  81349. /* %%% avoid this when Z_RLE */
  81350. n = s->hash_size;
  81351. p = &s->head[n];
  81352. do {
  81353. m = *--p;
  81354. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  81355. } while (--n);
  81356. n = wsize;
  81357. #ifndef FASTEST
  81358. p = &s->prev[n];
  81359. do {
  81360. m = *--p;
  81361. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  81362. /* If n is not on any hash chain, prev[n] is garbage but
  81363. * its value will never be used.
  81364. */
  81365. } while (--n);
  81366. #endif
  81367. more += wsize;
  81368. }
  81369. if (s->strm->avail_in == 0) return;
  81370. /* If there was no sliding:
  81371. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  81372. * more == window_size - lookahead - strstart
  81373. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  81374. * => more >= window_size - 2*WSIZE + 2
  81375. * In the BIG_MEM or MMAP case (not yet supported),
  81376. * window_size == input_size + MIN_LOOKAHEAD &&
  81377. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  81378. * Otherwise, window_size == 2*WSIZE so more >= 2.
  81379. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  81380. */
  81381. Assert(more >= 2, "more < 2");
  81382. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  81383. s->lookahead += n;
  81384. /* Initialize the hash value now that we have some input: */
  81385. if (s->lookahead >= MIN_MATCH) {
  81386. s->ins_h = s->window[s->strstart];
  81387. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  81388. #if MIN_MATCH != 3
  81389. Call UPDATE_HASH() MIN_MATCH-3 more times
  81390. #endif
  81391. }
  81392. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  81393. * but this is not important since only literal bytes will be emitted.
  81394. */
  81395. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  81396. }
  81397. /* ===========================================================================
  81398. * Flush the current block, with given end-of-file flag.
  81399. * IN assertion: strstart is set to the end of the current match.
  81400. */
  81401. #define FLUSH_BLOCK_ONLY(s, eof) { \
  81402. _tr_flush_block(s, (s->block_start >= 0L ? \
  81403. (charf *)&s->window[(unsigned)s->block_start] : \
  81404. (charf *)Z_NULL), \
  81405. (ulg)((long)s->strstart - s->block_start), \
  81406. (eof)); \
  81407. s->block_start = s->strstart; \
  81408. flush_pending(s->strm); \
  81409. Tracev((stderr,"[FLUSH]")); \
  81410. }
  81411. /* Same but force premature exit if necessary. */
  81412. #define FLUSH_BLOCK(s, eof) { \
  81413. FLUSH_BLOCK_ONLY(s, eof); \
  81414. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  81415. }
  81416. /* ===========================================================================
  81417. * Copy without compression as much as possible from the input stream, return
  81418. * the current block state.
  81419. * This function does not insert new strings in the dictionary since
  81420. * uncompressible data is probably not useful. This function is used
  81421. * only for the level=0 compression option.
  81422. * NOTE: this function should be optimized to avoid extra copying from
  81423. * window to pending_buf.
  81424. */
  81425. local block_state deflate_stored(deflate_state *s, int flush)
  81426. {
  81427. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  81428. * to pending_buf_size, and each stored block has a 5 byte header:
  81429. */
  81430. ulg max_block_size = 0xffff;
  81431. ulg max_start;
  81432. if (max_block_size > s->pending_buf_size - 5) {
  81433. max_block_size = s->pending_buf_size - 5;
  81434. }
  81435. /* Copy as much as possible from input to output: */
  81436. for (;;) {
  81437. /* Fill the window as much as possible: */
  81438. if (s->lookahead <= 1) {
  81439. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  81440. s->block_start >= (long)s->w_size, "slide too late");
  81441. fill_window(s);
  81442. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  81443. if (s->lookahead == 0) break; /* flush the current block */
  81444. }
  81445. Assert(s->block_start >= 0L, "block gone");
  81446. s->strstart += s->lookahead;
  81447. s->lookahead = 0;
  81448. /* Emit a stored block if pending_buf will be full: */
  81449. max_start = s->block_start + max_block_size;
  81450. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  81451. /* strstart == 0 is possible when wraparound on 16-bit machine */
  81452. s->lookahead = (uInt)(s->strstart - max_start);
  81453. s->strstart = (uInt)max_start;
  81454. FLUSH_BLOCK(s, 0);
  81455. }
  81456. /* Flush if we may have to slide, otherwise block_start may become
  81457. * negative and the data will be gone:
  81458. */
  81459. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  81460. FLUSH_BLOCK(s, 0);
  81461. }
  81462. }
  81463. FLUSH_BLOCK(s, flush == Z_FINISH);
  81464. return flush == Z_FINISH ? finish_done : block_done;
  81465. }
  81466. /* ===========================================================================
  81467. * Compress as much as possible from the input stream, return the current
  81468. * block state.
  81469. * This function does not perform lazy evaluation of matches and inserts
  81470. * new strings in the dictionary only for unmatched strings or for short
  81471. * matches. It is used only for the fast compression options.
  81472. */
  81473. local block_state deflate_fast(deflate_state *s, int flush)
  81474. {
  81475. IPos hash_head = NIL; /* head of the hash chain */
  81476. int bflush; /* set if current block must be flushed */
  81477. for (;;) {
  81478. /* Make sure that we always have enough lookahead, except
  81479. * at the end of the input file. We need MAX_MATCH bytes
  81480. * for the next match, plus MIN_MATCH bytes to insert the
  81481. * string following the next match.
  81482. */
  81483. if (s->lookahead < MIN_LOOKAHEAD) {
  81484. fill_window(s);
  81485. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  81486. return need_more;
  81487. }
  81488. if (s->lookahead == 0) break; /* flush the current block */
  81489. }
  81490. /* Insert the string window[strstart .. strstart+2] in the
  81491. * dictionary, and set hash_head to the head of the hash chain:
  81492. */
  81493. if (s->lookahead >= MIN_MATCH) {
  81494. INSERT_STRING(s, s->strstart, hash_head);
  81495. }
  81496. /* Find the longest match, discarding those <= prev_length.
  81497. * At this point we have always match_length < MIN_MATCH
  81498. */
  81499. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  81500. /* To simplify the code, we prevent matches with the string
  81501. * of window index 0 (in particular we have to avoid a match
  81502. * of the string with itself at the start of the input file).
  81503. */
  81504. #ifdef FASTEST
  81505. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  81506. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  81507. s->match_length = longest_match_fast (s, hash_head);
  81508. }
  81509. #else
  81510. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  81511. s->match_length = longest_match (s, hash_head);
  81512. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  81513. s->match_length = longest_match_fast (s, hash_head);
  81514. }
  81515. #endif
  81516. /* longest_match() or longest_match_fast() sets match_start */
  81517. }
  81518. if (s->match_length >= MIN_MATCH) {
  81519. check_match(s, s->strstart, s->match_start, s->match_length);
  81520. _tr_tally_dist(s, s->strstart - s->match_start,
  81521. s->match_length - MIN_MATCH, bflush);
  81522. s->lookahead -= s->match_length;
  81523. /* Insert new strings in the hash table only if the match length
  81524. * is not too large. This saves time but degrades compression.
  81525. */
  81526. #ifndef FASTEST
  81527. if (s->match_length <= s->max_insert_length &&
  81528. s->lookahead >= MIN_MATCH) {
  81529. s->match_length--; /* string at strstart already in table */
  81530. do {
  81531. s->strstart++;
  81532. INSERT_STRING(s, s->strstart, hash_head);
  81533. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  81534. * always MIN_MATCH bytes ahead.
  81535. */
  81536. } while (--s->match_length != 0);
  81537. s->strstart++;
  81538. } else
  81539. #endif
  81540. {
  81541. s->strstart += s->match_length;
  81542. s->match_length = 0;
  81543. s->ins_h = s->window[s->strstart];
  81544. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  81545. #if MIN_MATCH != 3
  81546. Call UPDATE_HASH() MIN_MATCH-3 more times
  81547. #endif
  81548. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  81549. * matter since it will be recomputed at next deflate call.
  81550. */
  81551. }
  81552. } else {
  81553. /* No match, output a literal byte */
  81554. Tracevv((stderr,"%c", s->window[s->strstart]));
  81555. _tr_tally_lit (s, s->window[s->strstart], bflush);
  81556. s->lookahead--;
  81557. s->strstart++;
  81558. }
  81559. if (bflush) FLUSH_BLOCK(s, 0);
  81560. }
  81561. FLUSH_BLOCK(s, flush == Z_FINISH);
  81562. return flush == Z_FINISH ? finish_done : block_done;
  81563. }
  81564. #ifndef FASTEST
  81565. /* ===========================================================================
  81566. * Same as above, but achieves better compression. We use a lazy
  81567. * evaluation for matches: a match is finally adopted only if there is
  81568. * no better match at the next window position.
  81569. */
  81570. local block_state deflate_slow(deflate_state *s, int flush)
  81571. {
  81572. IPos hash_head = NIL; /* head of hash chain */
  81573. int bflush; /* set if current block must be flushed */
  81574. /* Process the input block. */
  81575. for (;;) {
  81576. /* Make sure that we always have enough lookahead, except
  81577. * at the end of the input file. We need MAX_MATCH bytes
  81578. * for the next match, plus MIN_MATCH bytes to insert the
  81579. * string following the next match.
  81580. */
  81581. if (s->lookahead < MIN_LOOKAHEAD) {
  81582. fill_window(s);
  81583. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  81584. return need_more;
  81585. }
  81586. if (s->lookahead == 0) break; /* flush the current block */
  81587. }
  81588. /* Insert the string window[strstart .. strstart+2] in the
  81589. * dictionary, and set hash_head to the head of the hash chain:
  81590. */
  81591. if (s->lookahead >= MIN_MATCH) {
  81592. INSERT_STRING(s, s->strstart, hash_head);
  81593. }
  81594. /* Find the longest match, discarding those <= prev_length.
  81595. */
  81596. s->prev_length = s->match_length, s->prev_match = s->match_start;
  81597. s->match_length = MIN_MATCH-1;
  81598. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  81599. s->strstart - hash_head <= MAX_DIST(s)) {
  81600. /* To simplify the code, we prevent matches with the string
  81601. * of window index 0 (in particular we have to avoid a match
  81602. * of the string with itself at the start of the input file).
  81603. */
  81604. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  81605. s->match_length = longest_match (s, hash_head);
  81606. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  81607. s->match_length = longest_match_fast (s, hash_head);
  81608. }
  81609. /* longest_match() or longest_match_fast() sets match_start */
  81610. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  81611. #if TOO_FAR <= 32767
  81612. || (s->match_length == MIN_MATCH &&
  81613. s->strstart - s->match_start > TOO_FAR)
  81614. #endif
  81615. )) {
  81616. /* If prev_match is also MIN_MATCH, match_start is garbage
  81617. * but we will ignore the current match anyway.
  81618. */
  81619. s->match_length = MIN_MATCH-1;
  81620. }
  81621. }
  81622. /* If there was a match at the previous step and the current
  81623. * match is not better, output the previous match:
  81624. */
  81625. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  81626. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  81627. /* Do not insert strings in hash table beyond this. */
  81628. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  81629. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  81630. s->prev_length - MIN_MATCH, bflush);
  81631. /* Insert in hash table all strings up to the end of the match.
  81632. * strstart-1 and strstart are already inserted. If there is not
  81633. * enough lookahead, the last two strings are not inserted in
  81634. * the hash table.
  81635. */
  81636. s->lookahead -= s->prev_length-1;
  81637. s->prev_length -= 2;
  81638. do {
  81639. if (++s->strstart <= max_insert) {
  81640. INSERT_STRING(s, s->strstart, hash_head);
  81641. }
  81642. } while (--s->prev_length != 0);
  81643. s->match_available = 0;
  81644. s->match_length = MIN_MATCH-1;
  81645. s->strstart++;
  81646. if (bflush) FLUSH_BLOCK(s, 0);
  81647. } else if (s->match_available) {
  81648. /* If there was no match at the previous position, output a
  81649. * single literal. If there was a match but the current match
  81650. * is longer, truncate the previous match to a single literal.
  81651. */
  81652. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  81653. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  81654. if (bflush) {
  81655. FLUSH_BLOCK_ONLY(s, 0);
  81656. }
  81657. s->strstart++;
  81658. s->lookahead--;
  81659. if (s->strm->avail_out == 0) return need_more;
  81660. } else {
  81661. /* There is no previous match to compare with, wait for
  81662. * the next step to decide.
  81663. */
  81664. s->match_available = 1;
  81665. s->strstart++;
  81666. s->lookahead--;
  81667. }
  81668. }
  81669. Assert (flush != Z_NO_FLUSH, "no flush?");
  81670. if (s->match_available) {
  81671. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  81672. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  81673. s->match_available = 0;
  81674. }
  81675. FLUSH_BLOCK(s, flush == Z_FINISH);
  81676. return flush == Z_FINISH ? finish_done : block_done;
  81677. }
  81678. #endif /* FASTEST */
  81679. #if 0
  81680. /* ===========================================================================
  81681. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  81682. * one. Do not maintain a hash table. (It will be regenerated if this run of
  81683. * deflate switches away from Z_RLE.)
  81684. */
  81685. local block_state deflate_rle(s, flush)
  81686. deflate_state *s;
  81687. int flush;
  81688. {
  81689. int bflush; /* set if current block must be flushed */
  81690. uInt run; /* length of run */
  81691. uInt max; /* maximum length of run */
  81692. uInt prev; /* byte at distance one to match */
  81693. Bytef *scan; /* scan for end of run */
  81694. for (;;) {
  81695. /* Make sure that we always have enough lookahead, except
  81696. * at the end of the input file. We need MAX_MATCH bytes
  81697. * for the longest encodable run.
  81698. */
  81699. if (s->lookahead < MAX_MATCH) {
  81700. fill_window(s);
  81701. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  81702. return need_more;
  81703. }
  81704. if (s->lookahead == 0) break; /* flush the current block */
  81705. }
  81706. /* See how many times the previous byte repeats */
  81707. run = 0;
  81708. if (s->strstart > 0) { /* if there is a previous byte, that is */
  81709. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  81710. scan = s->window + s->strstart - 1;
  81711. prev = *scan++;
  81712. do {
  81713. if (*scan++ != prev)
  81714. break;
  81715. } while (++run < max);
  81716. }
  81717. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  81718. if (run >= MIN_MATCH) {
  81719. check_match(s, s->strstart, s->strstart - 1, run);
  81720. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  81721. s->lookahead -= run;
  81722. s->strstart += run;
  81723. } else {
  81724. /* No match, output a literal byte */
  81725. Tracevv((stderr,"%c", s->window[s->strstart]));
  81726. _tr_tally_lit (s, s->window[s->strstart], bflush);
  81727. s->lookahead--;
  81728. s->strstart++;
  81729. }
  81730. if (bflush) FLUSH_BLOCK(s, 0);
  81731. }
  81732. FLUSH_BLOCK(s, flush == Z_FINISH);
  81733. return flush == Z_FINISH ? finish_done : block_done;
  81734. }
  81735. #endif
  81736. /*** End of inlined file: deflate.c ***/
  81737. /*** Start of inlined file: inffast.c ***/
  81738. /*** Start of inlined file: inftrees.h ***/
  81739. /* WARNING: this file should *not* be used by applications. It is
  81740. part of the implementation of the compression library and is
  81741. subject to change. Applications should only use zlib.h.
  81742. */
  81743. #ifndef _INFTREES_H_
  81744. #define _INFTREES_H_
  81745. /* Structure for decoding tables. Each entry provides either the
  81746. information needed to do the operation requested by the code that
  81747. indexed that table entry, or it provides a pointer to another
  81748. table that indexes more bits of the code. op indicates whether
  81749. the entry is a pointer to another table, a literal, a length or
  81750. distance, an end-of-block, or an invalid code. For a table
  81751. pointer, the low four bits of op is the number of index bits of
  81752. that table. For a length or distance, the low four bits of op
  81753. is the number of extra bits to get after the code. bits is
  81754. the number of bits in this code or part of the code to drop off
  81755. of the bit buffer. val is the actual byte to output in the case
  81756. of a literal, the base length or distance, or the offset from
  81757. the current table to the next table. Each entry is four bytes. */
  81758. typedef struct {
  81759. unsigned char op; /* operation, extra bits, table bits */
  81760. unsigned char bits; /* bits in this part of the code */
  81761. unsigned short val; /* offset in table or code value */
  81762. } code;
  81763. /* op values as set by inflate_table():
  81764. 00000000 - literal
  81765. 0000tttt - table link, tttt != 0 is the number of table index bits
  81766. 0001eeee - length or distance, eeee is the number of extra bits
  81767. 01100000 - end of block
  81768. 01000000 - invalid code
  81769. */
  81770. /* Maximum size of dynamic tree. The maximum found in a long but non-
  81771. exhaustive search was 1444 code structures (852 for length/literals
  81772. and 592 for distances, the latter actually the result of an
  81773. exhaustive search). The true maximum is not known, but the value
  81774. below is more than safe. */
  81775. #define ENOUGH 2048
  81776. #define MAXD 592
  81777. /* Type of code to build for inftable() */
  81778. typedef enum {
  81779. CODES,
  81780. LENS,
  81781. DISTS
  81782. } codetype;
  81783. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  81784. unsigned codes, code FAR * FAR *table,
  81785. unsigned FAR *bits, unsigned short FAR *work));
  81786. #endif
  81787. /*** End of inlined file: inftrees.h ***/
  81788. /*** Start of inlined file: inflate.h ***/
  81789. /* WARNING: this file should *not* be used by applications. It is
  81790. part of the implementation of the compression library and is
  81791. subject to change. Applications should only use zlib.h.
  81792. */
  81793. #ifndef _INFLATE_H_
  81794. #define _INFLATE_H_
  81795. /* define NO_GZIP when compiling if you want to disable gzip header and
  81796. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  81797. the crc code when it is not needed. For shared libraries, gzip decoding
  81798. should be left enabled. */
  81799. #ifndef NO_GZIP
  81800. # define GUNZIP
  81801. #endif
  81802. /* Possible inflate modes between inflate() calls */
  81803. typedef enum {
  81804. HEAD, /* i: waiting for magic header */
  81805. FLAGS, /* i: waiting for method and flags (gzip) */
  81806. TIME, /* i: waiting for modification time (gzip) */
  81807. OS, /* i: waiting for extra flags and operating system (gzip) */
  81808. EXLEN, /* i: waiting for extra length (gzip) */
  81809. EXTRA, /* i: waiting for extra bytes (gzip) */
  81810. NAME, /* i: waiting for end of file name (gzip) */
  81811. COMMENT, /* i: waiting for end of comment (gzip) */
  81812. HCRC, /* i: waiting for header crc (gzip) */
  81813. DICTID, /* i: waiting for dictionary check value */
  81814. DICT, /* waiting for inflateSetDictionary() call */
  81815. TYPE, /* i: waiting for type bits, including last-flag bit */
  81816. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  81817. STORED, /* i: waiting for stored size (length and complement) */
  81818. COPY, /* i/o: waiting for input or output to copy stored block */
  81819. TABLE, /* i: waiting for dynamic block table lengths */
  81820. LENLENS, /* i: waiting for code length code lengths */
  81821. CODELENS, /* i: waiting for length/lit and distance code lengths */
  81822. LEN, /* i: waiting for length/lit code */
  81823. LENEXT, /* i: waiting for length extra bits */
  81824. DIST, /* i: waiting for distance code */
  81825. DISTEXT, /* i: waiting for distance extra bits */
  81826. MATCH, /* o: waiting for output space to copy string */
  81827. LIT, /* o: waiting for output space to write literal */
  81828. CHECK, /* i: waiting for 32-bit check value */
  81829. LENGTH, /* i: waiting for 32-bit length (gzip) */
  81830. DONE, /* finished check, done -- remain here until reset */
  81831. BAD, /* got a data error -- remain here until reset */
  81832. MEM, /* got an inflate() memory error -- remain here until reset */
  81833. SYNC /* looking for synchronization bytes to restart inflate() */
  81834. } inflate_mode;
  81835. /*
  81836. State transitions between above modes -
  81837. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  81838. Process header:
  81839. HEAD -> (gzip) or (zlib)
  81840. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  81841. NAME -> COMMENT -> HCRC -> TYPE
  81842. (zlib) -> DICTID or TYPE
  81843. DICTID -> DICT -> TYPE
  81844. Read deflate blocks:
  81845. TYPE -> STORED or TABLE or LEN or CHECK
  81846. STORED -> COPY -> TYPE
  81847. TABLE -> LENLENS -> CODELENS -> LEN
  81848. Read deflate codes:
  81849. LEN -> LENEXT or LIT or TYPE
  81850. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  81851. LIT -> LEN
  81852. Process trailer:
  81853. CHECK -> LENGTH -> DONE
  81854. */
  81855. /* state maintained between inflate() calls. Approximately 7K bytes. */
  81856. struct inflate_state {
  81857. inflate_mode mode; /* current inflate mode */
  81858. int last; /* true if processing last block */
  81859. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  81860. int havedict; /* true if dictionary provided */
  81861. int flags; /* gzip header method and flags (0 if zlib) */
  81862. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  81863. unsigned long check; /* protected copy of check value */
  81864. unsigned long total; /* protected copy of output count */
  81865. gz_headerp head; /* where to save gzip header information */
  81866. /* sliding window */
  81867. unsigned wbits; /* log base 2 of requested window size */
  81868. unsigned wsize; /* window size or zero if not using window */
  81869. unsigned whave; /* valid bytes in the window */
  81870. unsigned write; /* window write index */
  81871. unsigned char FAR *window; /* allocated sliding window, if needed */
  81872. /* bit accumulator */
  81873. unsigned long hold; /* input bit accumulator */
  81874. unsigned bits; /* number of bits in "in" */
  81875. /* for string and stored block copying */
  81876. unsigned length; /* literal or length of data to copy */
  81877. unsigned offset; /* distance back to copy string from */
  81878. /* for table and code decoding */
  81879. unsigned extra; /* extra bits needed */
  81880. /* fixed and dynamic code tables */
  81881. code const FAR *lencode; /* starting table for length/literal codes */
  81882. code const FAR *distcode; /* starting table for distance codes */
  81883. unsigned lenbits; /* index bits for lencode */
  81884. unsigned distbits; /* index bits for distcode */
  81885. /* dynamic table building */
  81886. unsigned ncode; /* number of code length code lengths */
  81887. unsigned nlen; /* number of length code lengths */
  81888. unsigned ndist; /* number of distance code lengths */
  81889. unsigned have; /* number of code lengths in lens[] */
  81890. code FAR *next; /* next available space in codes[] */
  81891. unsigned short lens[320]; /* temporary storage for code lengths */
  81892. unsigned short work[288]; /* work area for code table building */
  81893. code codes[ENOUGH]; /* space for code tables */
  81894. };
  81895. #endif
  81896. /*** End of inlined file: inflate.h ***/
  81897. /*** Start of inlined file: inffast.h ***/
  81898. /* WARNING: this file should *not* be used by applications. It is
  81899. part of the implementation of the compression library and is
  81900. subject to change. Applications should only use zlib.h.
  81901. */
  81902. void inflate_fast OF((z_streamp strm, unsigned start));
  81903. /*** End of inlined file: inffast.h ***/
  81904. #ifndef ASMINF
  81905. /* Allow machine dependent optimization for post-increment or pre-increment.
  81906. Based on testing to date,
  81907. Pre-increment preferred for:
  81908. - PowerPC G3 (Adler)
  81909. - MIPS R5000 (Randers-Pehrson)
  81910. Post-increment preferred for:
  81911. - none
  81912. No measurable difference:
  81913. - Pentium III (Anderson)
  81914. - M68060 (Nikl)
  81915. */
  81916. #ifdef POSTINC
  81917. # define OFF 0
  81918. # define PUP(a) *(a)++
  81919. #else
  81920. # define OFF 1
  81921. # define PUP(a) *++(a)
  81922. #endif
  81923. /*
  81924. Decode literal, length, and distance codes and write out the resulting
  81925. literal and match bytes until either not enough input or output is
  81926. available, an end-of-block is encountered, or a data error is encountered.
  81927. When large enough input and output buffers are supplied to inflate(), for
  81928. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  81929. inflate execution time is spent in this routine.
  81930. Entry assumptions:
  81931. state->mode == LEN
  81932. strm->avail_in >= 6
  81933. strm->avail_out >= 258
  81934. start >= strm->avail_out
  81935. state->bits < 8
  81936. On return, state->mode is one of:
  81937. LEN -- ran out of enough output space or enough available input
  81938. TYPE -- reached end of block code, inflate() to interpret next block
  81939. BAD -- error in block data
  81940. Notes:
  81941. - The maximum input bits used by a length/distance pair is 15 bits for the
  81942. length code, 5 bits for the length extra, 15 bits for the distance code,
  81943. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  81944. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  81945. checking for available input while decoding.
  81946. - The maximum bytes that a single length/distance pair can output is 258
  81947. bytes, which is the maximum length that can be coded. inflate_fast()
  81948. requires strm->avail_out >= 258 for each loop to avoid checking for
  81949. output space.
  81950. */
  81951. void inflate_fast (z_streamp strm, unsigned start)
  81952. {
  81953. struct inflate_state FAR *state;
  81954. unsigned char FAR *in; /* local strm->next_in */
  81955. unsigned char FAR *last; /* while in < last, enough input available */
  81956. unsigned char FAR *out; /* local strm->next_out */
  81957. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  81958. unsigned char FAR *end; /* while out < end, enough space available */
  81959. #ifdef INFLATE_STRICT
  81960. unsigned dmax; /* maximum distance from zlib header */
  81961. #endif
  81962. unsigned wsize; /* window size or zero if not using window */
  81963. unsigned whave; /* valid bytes in the window */
  81964. unsigned write; /* window write index */
  81965. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  81966. unsigned long hold; /* local strm->hold */
  81967. unsigned bits; /* local strm->bits */
  81968. code const FAR *lcode; /* local strm->lencode */
  81969. code const FAR *dcode; /* local strm->distcode */
  81970. unsigned lmask; /* mask for first level of length codes */
  81971. unsigned dmask; /* mask for first level of distance codes */
  81972. code thisx; /* retrieved table entry */
  81973. unsigned op; /* code bits, operation, extra bits, or */
  81974. /* window position, window bytes to copy */
  81975. unsigned len; /* match length, unused bytes */
  81976. unsigned dist; /* match distance */
  81977. unsigned char FAR *from; /* where to copy match from */
  81978. /* copy state to local variables */
  81979. state = (struct inflate_state FAR *)strm->state;
  81980. in = strm->next_in - OFF;
  81981. last = in + (strm->avail_in - 5);
  81982. out = strm->next_out - OFF;
  81983. beg = out - (start - strm->avail_out);
  81984. end = out + (strm->avail_out - 257);
  81985. #ifdef INFLATE_STRICT
  81986. dmax = state->dmax;
  81987. #endif
  81988. wsize = state->wsize;
  81989. whave = state->whave;
  81990. write = state->write;
  81991. window = state->window;
  81992. hold = state->hold;
  81993. bits = state->bits;
  81994. lcode = state->lencode;
  81995. dcode = state->distcode;
  81996. lmask = (1U << state->lenbits) - 1;
  81997. dmask = (1U << state->distbits) - 1;
  81998. /* decode literals and length/distances until end-of-block or not enough
  81999. input data or output space */
  82000. do {
  82001. if (bits < 15) {
  82002. hold += (unsigned long)(PUP(in)) << bits;
  82003. bits += 8;
  82004. hold += (unsigned long)(PUP(in)) << bits;
  82005. bits += 8;
  82006. }
  82007. thisx = lcode[hold & lmask];
  82008. dolen:
  82009. op = (unsigned)(thisx.bits);
  82010. hold >>= op;
  82011. bits -= op;
  82012. op = (unsigned)(thisx.op);
  82013. if (op == 0) { /* literal */
  82014. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  82015. "inflate: literal '%c'\n" :
  82016. "inflate: literal 0x%02x\n", thisx.val));
  82017. PUP(out) = (unsigned char)(thisx.val);
  82018. }
  82019. else if (op & 16) { /* length base */
  82020. len = (unsigned)(thisx.val);
  82021. op &= 15; /* number of extra bits */
  82022. if (op) {
  82023. if (bits < op) {
  82024. hold += (unsigned long)(PUP(in)) << bits;
  82025. bits += 8;
  82026. }
  82027. len += (unsigned)hold & ((1U << op) - 1);
  82028. hold >>= op;
  82029. bits -= op;
  82030. }
  82031. Tracevv((stderr, "inflate: length %u\n", len));
  82032. if (bits < 15) {
  82033. hold += (unsigned long)(PUP(in)) << bits;
  82034. bits += 8;
  82035. hold += (unsigned long)(PUP(in)) << bits;
  82036. bits += 8;
  82037. }
  82038. thisx = dcode[hold & dmask];
  82039. dodist:
  82040. op = (unsigned)(thisx.bits);
  82041. hold >>= op;
  82042. bits -= op;
  82043. op = (unsigned)(thisx.op);
  82044. if (op & 16) { /* distance base */
  82045. dist = (unsigned)(thisx.val);
  82046. op &= 15; /* number of extra bits */
  82047. if (bits < op) {
  82048. hold += (unsigned long)(PUP(in)) << bits;
  82049. bits += 8;
  82050. if (bits < op) {
  82051. hold += (unsigned long)(PUP(in)) << bits;
  82052. bits += 8;
  82053. }
  82054. }
  82055. dist += (unsigned)hold & ((1U << op) - 1);
  82056. #ifdef INFLATE_STRICT
  82057. if (dist > dmax) {
  82058. strm->msg = (char *)"invalid distance too far back";
  82059. state->mode = BAD;
  82060. break;
  82061. }
  82062. #endif
  82063. hold >>= op;
  82064. bits -= op;
  82065. Tracevv((stderr, "inflate: distance %u\n", dist));
  82066. op = (unsigned)(out - beg); /* max distance in output */
  82067. if (dist > op) { /* see if copy from window */
  82068. op = dist - op; /* distance back in window */
  82069. if (op > whave) {
  82070. strm->msg = (char *)"invalid distance too far back";
  82071. state->mode = BAD;
  82072. break;
  82073. }
  82074. from = window - OFF;
  82075. if (write == 0) { /* very common case */
  82076. from += wsize - op;
  82077. if (op < len) { /* some from window */
  82078. len -= op;
  82079. do {
  82080. PUP(out) = PUP(from);
  82081. } while (--op);
  82082. from = out - dist; /* rest from output */
  82083. }
  82084. }
  82085. else if (write < op) { /* wrap around window */
  82086. from += wsize + write - op;
  82087. op -= write;
  82088. if (op < len) { /* some from end of window */
  82089. len -= op;
  82090. do {
  82091. PUP(out) = PUP(from);
  82092. } while (--op);
  82093. from = window - OFF;
  82094. if (write < len) { /* some from start of window */
  82095. op = write;
  82096. len -= op;
  82097. do {
  82098. PUP(out) = PUP(from);
  82099. } while (--op);
  82100. from = out - dist; /* rest from output */
  82101. }
  82102. }
  82103. }
  82104. else { /* contiguous in window */
  82105. from += write - op;
  82106. if (op < len) { /* some from window */
  82107. len -= op;
  82108. do {
  82109. PUP(out) = PUP(from);
  82110. } while (--op);
  82111. from = out - dist; /* rest from output */
  82112. }
  82113. }
  82114. while (len > 2) {
  82115. PUP(out) = PUP(from);
  82116. PUP(out) = PUP(from);
  82117. PUP(out) = PUP(from);
  82118. len -= 3;
  82119. }
  82120. if (len) {
  82121. PUP(out) = PUP(from);
  82122. if (len > 1)
  82123. PUP(out) = PUP(from);
  82124. }
  82125. }
  82126. else {
  82127. from = out - dist; /* copy direct from output */
  82128. do { /* minimum length is three */
  82129. PUP(out) = PUP(from);
  82130. PUP(out) = PUP(from);
  82131. PUP(out) = PUP(from);
  82132. len -= 3;
  82133. } while (len > 2);
  82134. if (len) {
  82135. PUP(out) = PUP(from);
  82136. if (len > 1)
  82137. PUP(out) = PUP(from);
  82138. }
  82139. }
  82140. }
  82141. else if ((op & 64) == 0) { /* 2nd level distance code */
  82142. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  82143. goto dodist;
  82144. }
  82145. else {
  82146. strm->msg = (char *)"invalid distance code";
  82147. state->mode = BAD;
  82148. break;
  82149. }
  82150. }
  82151. else if ((op & 64) == 0) { /* 2nd level length code */
  82152. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  82153. goto dolen;
  82154. }
  82155. else if (op & 32) { /* end-of-block */
  82156. Tracevv((stderr, "inflate: end of block\n"));
  82157. state->mode = TYPE;
  82158. break;
  82159. }
  82160. else {
  82161. strm->msg = (char *)"invalid literal/length code";
  82162. state->mode = BAD;
  82163. break;
  82164. }
  82165. } while (in < last && out < end);
  82166. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  82167. len = bits >> 3;
  82168. in -= len;
  82169. bits -= len << 3;
  82170. hold &= (1U << bits) - 1;
  82171. /* update state and return */
  82172. strm->next_in = in + OFF;
  82173. strm->next_out = out + OFF;
  82174. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  82175. strm->avail_out = (unsigned)(out < end ?
  82176. 257 + (end - out) : 257 - (out - end));
  82177. state->hold = hold;
  82178. state->bits = bits;
  82179. return;
  82180. }
  82181. /*
  82182. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  82183. - Using bit fields for code structure
  82184. - Different op definition to avoid & for extra bits (do & for table bits)
  82185. - Three separate decoding do-loops for direct, window, and write == 0
  82186. - Special case for distance > 1 copies to do overlapped load and store copy
  82187. - Explicit branch predictions (based on measured branch probabilities)
  82188. - Deferring match copy and interspersed it with decoding subsequent codes
  82189. - Swapping literal/length else
  82190. - Swapping window/direct else
  82191. - Larger unrolled copy loops (three is about right)
  82192. - Moving len -= 3 statement into middle of loop
  82193. */
  82194. #endif /* !ASMINF */
  82195. /*** End of inlined file: inffast.c ***/
  82196. #undef PULLBYTE
  82197. #undef LOAD
  82198. #undef RESTORE
  82199. #undef INITBITS
  82200. #undef NEEDBITS
  82201. #undef DROPBITS
  82202. #undef BYTEBITS
  82203. /*** Start of inlined file: inflate.c ***/
  82204. /*
  82205. * Change history:
  82206. *
  82207. * 1.2.beta0 24 Nov 2002
  82208. * - First version -- complete rewrite of inflate to simplify code, avoid
  82209. * creation of window when not needed, minimize use of window when it is
  82210. * needed, make inffast.c even faster, implement gzip decoding, and to
  82211. * improve code readability and style over the previous zlib inflate code
  82212. *
  82213. * 1.2.beta1 25 Nov 2002
  82214. * - Use pointers for available input and output checking in inffast.c
  82215. * - Remove input and output counters in inffast.c
  82216. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  82217. * - Remove unnecessary second byte pull from length extra in inffast.c
  82218. * - Unroll direct copy to three copies per loop in inffast.c
  82219. *
  82220. * 1.2.beta2 4 Dec 2002
  82221. * - Change external routine names to reduce potential conflicts
  82222. * - Correct filename to inffixed.h for fixed tables in inflate.c
  82223. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  82224. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  82225. * to avoid negation problem on Alphas (64 bit) in inflate.c
  82226. *
  82227. * 1.2.beta3 22 Dec 2002
  82228. * - Add comments on state->bits assertion in inffast.c
  82229. * - Add comments on op field in inftrees.h
  82230. * - Fix bug in reuse of allocated window after inflateReset()
  82231. * - Remove bit fields--back to byte structure for speed
  82232. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  82233. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  82234. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  82235. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  82236. * - Use local copies of stream next and avail values, as well as local bit
  82237. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  82238. *
  82239. * 1.2.beta4 1 Jan 2003
  82240. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  82241. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  82242. * - Add comments in inffast.c to introduce the inflate_fast() routine
  82243. * - Rearrange window copies in inflate_fast() for speed and simplification
  82244. * - Unroll last copy for window match in inflate_fast()
  82245. * - Use local copies of window variables in inflate_fast() for speed
  82246. * - Pull out common write == 0 case for speed in inflate_fast()
  82247. * - Make op and len in inflate_fast() unsigned for consistency
  82248. * - Add FAR to lcode and dcode declarations in inflate_fast()
  82249. * - Simplified bad distance check in inflate_fast()
  82250. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  82251. * source file infback.c to provide a call-back interface to inflate for
  82252. * programs like gzip and unzip -- uses window as output buffer to avoid
  82253. * window copying
  82254. *
  82255. * 1.2.beta5 1 Jan 2003
  82256. * - Improved inflateBack() interface to allow the caller to provide initial
  82257. * input in strm.
  82258. * - Fixed stored blocks bug in inflateBack()
  82259. *
  82260. * 1.2.beta6 4 Jan 2003
  82261. * - Added comments in inffast.c on effectiveness of POSTINC
  82262. * - Typecasting all around to reduce compiler warnings
  82263. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  82264. * make compilers happy
  82265. * - Changed type of window in inflateBackInit() to unsigned char *
  82266. *
  82267. * 1.2.beta7 27 Jan 2003
  82268. * - Changed many types to unsigned or unsigned short to avoid warnings
  82269. * - Added inflateCopy() function
  82270. *
  82271. * 1.2.0 9 Mar 2003
  82272. * - Changed inflateBack() interface to provide separate opaque descriptors
  82273. * for the in() and out() functions
  82274. * - Changed inflateBack() argument and in_func typedef to swap the length
  82275. * and buffer address return values for the input function
  82276. * - Check next_in and next_out for Z_NULL on entry to inflate()
  82277. *
  82278. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  82279. */
  82280. /*** Start of inlined file: inffast.h ***/
  82281. /* WARNING: this file should *not* be used by applications. It is
  82282. part of the implementation of the compression library and is
  82283. subject to change. Applications should only use zlib.h.
  82284. */
  82285. void inflate_fast OF((z_streamp strm, unsigned start));
  82286. /*** End of inlined file: inffast.h ***/
  82287. #ifdef MAKEFIXED
  82288. # ifndef BUILDFIXED
  82289. # define BUILDFIXED
  82290. # endif
  82291. #endif
  82292. /* function prototypes */
  82293. local void fixedtables OF((struct inflate_state FAR *state));
  82294. local int updatewindow OF((z_streamp strm, unsigned out));
  82295. #ifdef BUILDFIXED
  82296. void makefixed OF((void));
  82297. #endif
  82298. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  82299. unsigned len));
  82300. int ZEXPORT inflateReset (z_streamp strm)
  82301. {
  82302. struct inflate_state FAR *state;
  82303. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  82304. state = (struct inflate_state FAR *)strm->state;
  82305. strm->total_in = strm->total_out = state->total = 0;
  82306. strm->msg = Z_NULL;
  82307. strm->adler = 1; /* to support ill-conceived Java test suite */
  82308. state->mode = HEAD;
  82309. state->last = 0;
  82310. state->havedict = 0;
  82311. state->dmax = 32768U;
  82312. state->head = Z_NULL;
  82313. state->wsize = 0;
  82314. state->whave = 0;
  82315. state->write = 0;
  82316. state->hold = 0;
  82317. state->bits = 0;
  82318. state->lencode = state->distcode = state->next = state->codes;
  82319. Tracev((stderr, "inflate: reset\n"));
  82320. return Z_OK;
  82321. }
  82322. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  82323. {
  82324. struct inflate_state FAR *state;
  82325. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  82326. state = (struct inflate_state FAR *)strm->state;
  82327. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  82328. value &= (1L << bits) - 1;
  82329. state->hold += value << state->bits;
  82330. state->bits += bits;
  82331. return Z_OK;
  82332. }
  82333. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  82334. {
  82335. struct inflate_state FAR *state;
  82336. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  82337. stream_size != (int)(sizeof(z_stream)))
  82338. return Z_VERSION_ERROR;
  82339. if (strm == Z_NULL) return Z_STREAM_ERROR;
  82340. strm->msg = Z_NULL; /* in case we return an error */
  82341. if (strm->zalloc == (alloc_func)0) {
  82342. strm->zalloc = zcalloc;
  82343. strm->opaque = (voidpf)0;
  82344. }
  82345. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  82346. state = (struct inflate_state FAR *)
  82347. ZALLOC(strm, 1, sizeof(struct inflate_state));
  82348. if (state == Z_NULL) return Z_MEM_ERROR;
  82349. Tracev((stderr, "inflate: allocated\n"));
  82350. strm->state = (struct internal_state FAR *)state;
  82351. if (windowBits < 0) {
  82352. state->wrap = 0;
  82353. windowBits = -windowBits;
  82354. }
  82355. else {
  82356. state->wrap = (windowBits >> 4) + 1;
  82357. #ifdef GUNZIP
  82358. if (windowBits < 48) windowBits &= 15;
  82359. #endif
  82360. }
  82361. if (windowBits < 8 || windowBits > 15) {
  82362. ZFREE(strm, state);
  82363. strm->state = Z_NULL;
  82364. return Z_STREAM_ERROR;
  82365. }
  82366. state->wbits = (unsigned)windowBits;
  82367. state->window = Z_NULL;
  82368. return inflateReset(strm);
  82369. }
  82370. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  82371. {
  82372. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  82373. }
  82374. /*
  82375. Return state with length and distance decoding tables and index sizes set to
  82376. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  82377. If BUILDFIXED is defined, then instead this routine builds the tables the
  82378. first time it's called, and returns those tables the first time and
  82379. thereafter. This reduces the size of the code by about 2K bytes, in
  82380. exchange for a little execution time. However, BUILDFIXED should not be
  82381. used for threaded applications, since the rewriting of the tables and virgin
  82382. may not be thread-safe.
  82383. */
  82384. local void fixedtables (struct inflate_state FAR *state)
  82385. {
  82386. #ifdef BUILDFIXED
  82387. static int virgin = 1;
  82388. static code *lenfix, *distfix;
  82389. static code fixed[544];
  82390. /* build fixed huffman tables if first call (may not be thread safe) */
  82391. if (virgin) {
  82392. unsigned sym, bits;
  82393. static code *next;
  82394. /* literal/length table */
  82395. sym = 0;
  82396. while (sym < 144) state->lens[sym++] = 8;
  82397. while (sym < 256) state->lens[sym++] = 9;
  82398. while (sym < 280) state->lens[sym++] = 7;
  82399. while (sym < 288) state->lens[sym++] = 8;
  82400. next = fixed;
  82401. lenfix = next;
  82402. bits = 9;
  82403. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  82404. /* distance table */
  82405. sym = 0;
  82406. while (sym < 32) state->lens[sym++] = 5;
  82407. distfix = next;
  82408. bits = 5;
  82409. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  82410. /* do this just once */
  82411. virgin = 0;
  82412. }
  82413. #else /* !BUILDFIXED */
  82414. /*** Start of inlined file: inffixed.h ***/
  82415. /* WARNING: this file should *not* be used by applications. It
  82416. is part of the implementation of the compression library and
  82417. is subject to change. Applications should only use zlib.h.
  82418. */
  82419. static const code lenfix[512] = {
  82420. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  82421. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  82422. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  82423. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  82424. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  82425. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  82426. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  82427. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  82428. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  82429. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  82430. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  82431. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  82432. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  82433. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  82434. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  82435. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  82436. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  82437. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  82438. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  82439. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  82440. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  82441. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  82442. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  82443. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  82444. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  82445. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  82446. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  82447. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  82448. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  82449. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  82450. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  82451. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  82452. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  82453. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  82454. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  82455. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  82456. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  82457. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  82458. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  82459. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  82460. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  82461. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  82462. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  82463. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  82464. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  82465. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  82466. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  82467. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  82468. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  82469. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  82470. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  82471. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  82472. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  82473. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  82474. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  82475. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  82476. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  82477. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  82478. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  82479. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  82480. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  82481. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  82482. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  82483. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  82484. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  82485. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  82486. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  82487. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  82488. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  82489. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  82490. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  82491. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  82492. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  82493. {0,9,255}
  82494. };
  82495. static const code distfix[32] = {
  82496. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  82497. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  82498. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  82499. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  82500. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  82501. {22,5,193},{64,5,0}
  82502. };
  82503. /*** End of inlined file: inffixed.h ***/
  82504. #endif /* BUILDFIXED */
  82505. state->lencode = lenfix;
  82506. state->lenbits = 9;
  82507. state->distcode = distfix;
  82508. state->distbits = 5;
  82509. }
  82510. #ifdef MAKEFIXED
  82511. #include <stdio.h>
  82512. /*
  82513. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  82514. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  82515. those tables to stdout, which would be piped to inffixed.h. A small program
  82516. can simply call makefixed to do this:
  82517. void makefixed(void);
  82518. int main(void)
  82519. {
  82520. makefixed();
  82521. return 0;
  82522. }
  82523. Then that can be linked with zlib built with MAKEFIXED defined and run:
  82524. a.out > inffixed.h
  82525. */
  82526. void makefixed()
  82527. {
  82528. unsigned low, size;
  82529. struct inflate_state state;
  82530. fixedtables(&state);
  82531. puts(" /* inffixed.h -- table for decoding fixed codes");
  82532. puts(" * Generated automatically by makefixed().");
  82533. puts(" */");
  82534. puts("");
  82535. puts(" /* WARNING: this file should *not* be used by applications.");
  82536. puts(" It is part of the implementation of this library and is");
  82537. puts(" subject to change. Applications should only use zlib.h.");
  82538. puts(" */");
  82539. puts("");
  82540. size = 1U << 9;
  82541. printf(" static const code lenfix[%u] = {", size);
  82542. low = 0;
  82543. for (;;) {
  82544. if ((low % 7) == 0) printf("\n ");
  82545. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  82546. state.lencode[low].val);
  82547. if (++low == size) break;
  82548. putchar(',');
  82549. }
  82550. puts("\n };");
  82551. size = 1U << 5;
  82552. printf("\n static const code distfix[%u] = {", size);
  82553. low = 0;
  82554. for (;;) {
  82555. if ((low % 6) == 0) printf("\n ");
  82556. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  82557. state.distcode[low].val);
  82558. if (++low == size) break;
  82559. putchar(',');
  82560. }
  82561. puts("\n };");
  82562. }
  82563. #endif /* MAKEFIXED */
  82564. /*
  82565. Update the window with the last wsize (normally 32K) bytes written before
  82566. returning. If window does not exist yet, create it. This is only called
  82567. when a window is already in use, or when output has been written during this
  82568. inflate call, but the end of the deflate stream has not been reached yet.
  82569. It is also called to create a window for dictionary data when a dictionary
  82570. is loaded.
  82571. Providing output buffers larger than 32K to inflate() should provide a speed
  82572. advantage, since only the last 32K of output is copied to the sliding window
  82573. upon return from inflate(), and since all distances after the first 32K of
  82574. output will fall in the output data, making match copies simpler and faster.
  82575. The advantage may be dependent on the size of the processor's data caches.
  82576. */
  82577. local int updatewindow (z_streamp strm, unsigned out)
  82578. {
  82579. struct inflate_state FAR *state;
  82580. unsigned copy, dist;
  82581. state = (struct inflate_state FAR *)strm->state;
  82582. /* if it hasn't been done already, allocate space for the window */
  82583. if (state->window == Z_NULL) {
  82584. state->window = (unsigned char FAR *)
  82585. ZALLOC(strm, 1U << state->wbits,
  82586. sizeof(unsigned char));
  82587. if (state->window == Z_NULL) return 1;
  82588. }
  82589. /* if window not in use yet, initialize */
  82590. if (state->wsize == 0) {
  82591. state->wsize = 1U << state->wbits;
  82592. state->write = 0;
  82593. state->whave = 0;
  82594. }
  82595. /* copy state->wsize or less output bytes into the circular window */
  82596. copy = out - strm->avail_out;
  82597. if (copy >= state->wsize) {
  82598. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  82599. state->write = 0;
  82600. state->whave = state->wsize;
  82601. }
  82602. else {
  82603. dist = state->wsize - state->write;
  82604. if (dist > copy) dist = copy;
  82605. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  82606. copy -= dist;
  82607. if (copy) {
  82608. zmemcpy(state->window, strm->next_out - copy, copy);
  82609. state->write = copy;
  82610. state->whave = state->wsize;
  82611. }
  82612. else {
  82613. state->write += dist;
  82614. if (state->write == state->wsize) state->write = 0;
  82615. if (state->whave < state->wsize) state->whave += dist;
  82616. }
  82617. }
  82618. return 0;
  82619. }
  82620. /* Macros for inflate(): */
  82621. /* check function to use adler32() for zlib or crc32() for gzip */
  82622. #ifdef GUNZIP
  82623. # define UPDATE(check, buf, len) \
  82624. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  82625. #else
  82626. # define UPDATE(check, buf, len) adler32(check, buf, len)
  82627. #endif
  82628. /* check macros for header crc */
  82629. #ifdef GUNZIP
  82630. # define CRC2(check, word) \
  82631. do { \
  82632. hbuf[0] = (unsigned char)(word); \
  82633. hbuf[1] = (unsigned char)((word) >> 8); \
  82634. check = crc32(check, hbuf, 2); \
  82635. } while (0)
  82636. # define CRC4(check, word) \
  82637. do { \
  82638. hbuf[0] = (unsigned char)(word); \
  82639. hbuf[1] = (unsigned char)((word) >> 8); \
  82640. hbuf[2] = (unsigned char)((word) >> 16); \
  82641. hbuf[3] = (unsigned char)((word) >> 24); \
  82642. check = crc32(check, hbuf, 4); \
  82643. } while (0)
  82644. #endif
  82645. /* Load registers with state in inflate() for speed */
  82646. #define LOAD() \
  82647. do { \
  82648. put = strm->next_out; \
  82649. left = strm->avail_out; \
  82650. next = strm->next_in; \
  82651. have = strm->avail_in; \
  82652. hold = state->hold; \
  82653. bits = state->bits; \
  82654. } while (0)
  82655. /* Restore state from registers in inflate() */
  82656. #define RESTORE() \
  82657. do { \
  82658. strm->next_out = put; \
  82659. strm->avail_out = left; \
  82660. strm->next_in = next; \
  82661. strm->avail_in = have; \
  82662. state->hold = hold; \
  82663. state->bits = bits; \
  82664. } while (0)
  82665. /* Clear the input bit accumulator */
  82666. #define INITBITS() \
  82667. do { \
  82668. hold = 0; \
  82669. bits = 0; \
  82670. } while (0)
  82671. /* Get a byte of input into the bit accumulator, or return from inflate()
  82672. if there is no input available. */
  82673. #define PULLBYTE() \
  82674. do { \
  82675. if (have == 0) goto inf_leave; \
  82676. have--; \
  82677. hold += (unsigned long)(*next++) << bits; \
  82678. bits += 8; \
  82679. } while (0)
  82680. /* Assure that there are at least n bits in the bit accumulator. If there is
  82681. not enough available input to do that, then return from inflate(). */
  82682. #define NEEDBITS(n) \
  82683. do { \
  82684. while (bits < (unsigned)(n)) \
  82685. PULLBYTE(); \
  82686. } while (0)
  82687. /* Return the low n bits of the bit accumulator (n < 16) */
  82688. #define BITS(n) \
  82689. ((unsigned)hold & ((1U << (n)) - 1))
  82690. /* Remove n bits from the bit accumulator */
  82691. #define DROPBITS(n) \
  82692. do { \
  82693. hold >>= (n); \
  82694. bits -= (unsigned)(n); \
  82695. } while (0)
  82696. /* Remove zero to seven bits as needed to go to a byte boundary */
  82697. #define BYTEBITS() \
  82698. do { \
  82699. hold >>= bits & 7; \
  82700. bits -= bits & 7; \
  82701. } while (0)
  82702. /* Reverse the bytes in a 32-bit value */
  82703. #define REVERSE(q) \
  82704. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  82705. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  82706. /*
  82707. inflate() uses a state machine to process as much input data and generate as
  82708. much output data as possible before returning. The state machine is
  82709. structured roughly as follows:
  82710. for (;;) switch (state) {
  82711. ...
  82712. case STATEn:
  82713. if (not enough input data or output space to make progress)
  82714. return;
  82715. ... make progress ...
  82716. state = STATEm;
  82717. break;
  82718. ...
  82719. }
  82720. so when inflate() is called again, the same case is attempted again, and
  82721. if the appropriate resources are provided, the machine proceeds to the
  82722. next state. The NEEDBITS() macro is usually the way the state evaluates
  82723. whether it can proceed or should return. NEEDBITS() does the return if
  82724. the requested bits are not available. The typical use of the BITS macros
  82725. is:
  82726. NEEDBITS(n);
  82727. ... do something with BITS(n) ...
  82728. DROPBITS(n);
  82729. where NEEDBITS(n) either returns from inflate() if there isn't enough
  82730. input left to load n bits into the accumulator, or it continues. BITS(n)
  82731. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  82732. the low n bits off the accumulator. INITBITS() clears the accumulator
  82733. and sets the number of available bits to zero. BYTEBITS() discards just
  82734. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  82735. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  82736. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  82737. if there is no input available. The decoding of variable length codes uses
  82738. PULLBYTE() directly in order to pull just enough bytes to decode the next
  82739. code, and no more.
  82740. Some states loop until they get enough input, making sure that enough
  82741. state information is maintained to continue the loop where it left off
  82742. if NEEDBITS() returns in the loop. For example, want, need, and keep
  82743. would all have to actually be part of the saved state in case NEEDBITS()
  82744. returns:
  82745. case STATEw:
  82746. while (want < need) {
  82747. NEEDBITS(n);
  82748. keep[want++] = BITS(n);
  82749. DROPBITS(n);
  82750. }
  82751. state = STATEx;
  82752. case STATEx:
  82753. As shown above, if the next state is also the next case, then the break
  82754. is omitted.
  82755. A state may also return if there is not enough output space available to
  82756. complete that state. Those states are copying stored data, writing a
  82757. literal byte, and copying a matching string.
  82758. When returning, a "goto inf_leave" is used to update the total counters,
  82759. update the check value, and determine whether any progress has been made
  82760. during that inflate() call in order to return the proper return code.
  82761. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  82762. When there is a window, goto inf_leave will update the window with the last
  82763. output written. If a goto inf_leave occurs in the middle of decompression
  82764. and there is no window currently, goto inf_leave will create one and copy
  82765. output to the window for the next call of inflate().
  82766. In this implementation, the flush parameter of inflate() only affects the
  82767. return code (per zlib.h). inflate() always writes as much as possible to
  82768. strm->next_out, given the space available and the provided input--the effect
  82769. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  82770. the allocation of and copying into a sliding window until necessary, which
  82771. provides the effect documented in zlib.h for Z_FINISH when the entire input
  82772. stream available. So the only thing the flush parameter actually does is:
  82773. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  82774. will return Z_BUF_ERROR if it has not reached the end of the stream.
  82775. */
  82776. int ZEXPORT inflate (z_streamp strm, int flush)
  82777. {
  82778. struct inflate_state FAR *state;
  82779. unsigned char FAR *next; /* next input */
  82780. unsigned char FAR *put; /* next output */
  82781. unsigned have, left; /* available input and output */
  82782. unsigned long hold; /* bit buffer */
  82783. unsigned bits; /* bits in bit buffer */
  82784. unsigned in, out; /* save starting available input and output */
  82785. unsigned copy; /* number of stored or match bytes to copy */
  82786. unsigned char FAR *from; /* where to copy match bytes from */
  82787. code thisx; /* current decoding table entry */
  82788. code last; /* parent table entry */
  82789. unsigned len; /* length to copy for repeats, bits to drop */
  82790. int ret; /* return code */
  82791. #ifdef GUNZIP
  82792. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  82793. #endif
  82794. static const unsigned short order[19] = /* permutation of code lengths */
  82795. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  82796. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  82797. (strm->next_in == Z_NULL && strm->avail_in != 0))
  82798. return Z_STREAM_ERROR;
  82799. state = (struct inflate_state FAR *)strm->state;
  82800. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  82801. LOAD();
  82802. in = have;
  82803. out = left;
  82804. ret = Z_OK;
  82805. for (;;)
  82806. switch (state->mode) {
  82807. case HEAD:
  82808. if (state->wrap == 0) {
  82809. state->mode = TYPEDO;
  82810. break;
  82811. }
  82812. NEEDBITS(16);
  82813. #ifdef GUNZIP
  82814. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  82815. state->check = crc32(0L, Z_NULL, 0);
  82816. CRC2(state->check, hold);
  82817. INITBITS();
  82818. state->mode = FLAGS;
  82819. break;
  82820. }
  82821. state->flags = 0; /* expect zlib header */
  82822. if (state->head != Z_NULL)
  82823. state->head->done = -1;
  82824. if (!(state->wrap & 1) || /* check if zlib header allowed */
  82825. #else
  82826. if (
  82827. #endif
  82828. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  82829. strm->msg = (char *)"incorrect header check";
  82830. state->mode = BAD;
  82831. break;
  82832. }
  82833. if (BITS(4) != Z_DEFLATED) {
  82834. strm->msg = (char *)"unknown compression method";
  82835. state->mode = BAD;
  82836. break;
  82837. }
  82838. DROPBITS(4);
  82839. len = BITS(4) + 8;
  82840. if (len > state->wbits) {
  82841. strm->msg = (char *)"invalid window size";
  82842. state->mode = BAD;
  82843. break;
  82844. }
  82845. state->dmax = 1U << len;
  82846. Tracev((stderr, "inflate: zlib header ok\n"));
  82847. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  82848. state->mode = hold & 0x200 ? DICTID : TYPE;
  82849. INITBITS();
  82850. break;
  82851. #ifdef GUNZIP
  82852. case FLAGS:
  82853. NEEDBITS(16);
  82854. state->flags = (int)(hold);
  82855. if ((state->flags & 0xff) != Z_DEFLATED) {
  82856. strm->msg = (char *)"unknown compression method";
  82857. state->mode = BAD;
  82858. break;
  82859. }
  82860. if (state->flags & 0xe000) {
  82861. strm->msg = (char *)"unknown header flags set";
  82862. state->mode = BAD;
  82863. break;
  82864. }
  82865. if (state->head != Z_NULL)
  82866. state->head->text = (int)((hold >> 8) & 1);
  82867. if (state->flags & 0x0200) CRC2(state->check, hold);
  82868. INITBITS();
  82869. state->mode = TIME;
  82870. case TIME:
  82871. NEEDBITS(32);
  82872. if (state->head != Z_NULL)
  82873. state->head->time = hold;
  82874. if (state->flags & 0x0200) CRC4(state->check, hold);
  82875. INITBITS();
  82876. state->mode = OS;
  82877. case OS:
  82878. NEEDBITS(16);
  82879. if (state->head != Z_NULL) {
  82880. state->head->xflags = (int)(hold & 0xff);
  82881. state->head->os = (int)(hold >> 8);
  82882. }
  82883. if (state->flags & 0x0200) CRC2(state->check, hold);
  82884. INITBITS();
  82885. state->mode = EXLEN;
  82886. case EXLEN:
  82887. if (state->flags & 0x0400) {
  82888. NEEDBITS(16);
  82889. state->length = (unsigned)(hold);
  82890. if (state->head != Z_NULL)
  82891. state->head->extra_len = (unsigned)hold;
  82892. if (state->flags & 0x0200) CRC2(state->check, hold);
  82893. INITBITS();
  82894. }
  82895. else if (state->head != Z_NULL)
  82896. state->head->extra = Z_NULL;
  82897. state->mode = EXTRA;
  82898. case EXTRA:
  82899. if (state->flags & 0x0400) {
  82900. copy = state->length;
  82901. if (copy > have) copy = have;
  82902. if (copy) {
  82903. if (state->head != Z_NULL &&
  82904. state->head->extra != Z_NULL) {
  82905. len = state->head->extra_len - state->length;
  82906. zmemcpy(state->head->extra + len, next,
  82907. len + copy > state->head->extra_max ?
  82908. state->head->extra_max - len : copy);
  82909. }
  82910. if (state->flags & 0x0200)
  82911. state->check = crc32(state->check, next, copy);
  82912. have -= copy;
  82913. next += copy;
  82914. state->length -= copy;
  82915. }
  82916. if (state->length) goto inf_leave;
  82917. }
  82918. state->length = 0;
  82919. state->mode = NAME;
  82920. case NAME:
  82921. if (state->flags & 0x0800) {
  82922. if (have == 0) goto inf_leave;
  82923. copy = 0;
  82924. do {
  82925. len = (unsigned)(next[copy++]);
  82926. if (state->head != Z_NULL &&
  82927. state->head->name != Z_NULL &&
  82928. state->length < state->head->name_max)
  82929. state->head->name[state->length++] = len;
  82930. } while (len && copy < have);
  82931. if (state->flags & 0x0200)
  82932. state->check = crc32(state->check, next, copy);
  82933. have -= copy;
  82934. next += copy;
  82935. if (len) goto inf_leave;
  82936. }
  82937. else if (state->head != Z_NULL)
  82938. state->head->name = Z_NULL;
  82939. state->length = 0;
  82940. state->mode = COMMENT;
  82941. case COMMENT:
  82942. if (state->flags & 0x1000) {
  82943. if (have == 0) goto inf_leave;
  82944. copy = 0;
  82945. do {
  82946. len = (unsigned)(next[copy++]);
  82947. if (state->head != Z_NULL &&
  82948. state->head->comment != Z_NULL &&
  82949. state->length < state->head->comm_max)
  82950. state->head->comment[state->length++] = len;
  82951. } while (len && copy < have);
  82952. if (state->flags & 0x0200)
  82953. state->check = crc32(state->check, next, copy);
  82954. have -= copy;
  82955. next += copy;
  82956. if (len) goto inf_leave;
  82957. }
  82958. else if (state->head != Z_NULL)
  82959. state->head->comment = Z_NULL;
  82960. state->mode = HCRC;
  82961. case HCRC:
  82962. if (state->flags & 0x0200) {
  82963. NEEDBITS(16);
  82964. if (hold != (state->check & 0xffff)) {
  82965. strm->msg = (char *)"header crc mismatch";
  82966. state->mode = BAD;
  82967. break;
  82968. }
  82969. INITBITS();
  82970. }
  82971. if (state->head != Z_NULL) {
  82972. state->head->hcrc = (int)((state->flags >> 9) & 1);
  82973. state->head->done = 1;
  82974. }
  82975. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  82976. state->mode = TYPE;
  82977. break;
  82978. #endif
  82979. case DICTID:
  82980. NEEDBITS(32);
  82981. strm->adler = state->check = REVERSE(hold);
  82982. INITBITS();
  82983. state->mode = DICT;
  82984. case DICT:
  82985. if (state->havedict == 0) {
  82986. RESTORE();
  82987. return Z_NEED_DICT;
  82988. }
  82989. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  82990. state->mode = TYPE;
  82991. case TYPE:
  82992. if (flush == Z_BLOCK) goto inf_leave;
  82993. case TYPEDO:
  82994. if (state->last) {
  82995. BYTEBITS();
  82996. state->mode = CHECK;
  82997. break;
  82998. }
  82999. NEEDBITS(3);
  83000. state->last = BITS(1);
  83001. DROPBITS(1);
  83002. switch (BITS(2)) {
  83003. case 0: /* stored block */
  83004. Tracev((stderr, "inflate: stored block%s\n",
  83005. state->last ? " (last)" : ""));
  83006. state->mode = STORED;
  83007. break;
  83008. case 1: /* fixed block */
  83009. fixedtables(state);
  83010. Tracev((stderr, "inflate: fixed codes block%s\n",
  83011. state->last ? " (last)" : ""));
  83012. state->mode = LEN; /* decode codes */
  83013. break;
  83014. case 2: /* dynamic block */
  83015. Tracev((stderr, "inflate: dynamic codes block%s\n",
  83016. state->last ? " (last)" : ""));
  83017. state->mode = TABLE;
  83018. break;
  83019. case 3:
  83020. strm->msg = (char *)"invalid block type";
  83021. state->mode = BAD;
  83022. }
  83023. DROPBITS(2);
  83024. break;
  83025. case STORED:
  83026. BYTEBITS(); /* go to byte boundary */
  83027. NEEDBITS(32);
  83028. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  83029. strm->msg = (char *)"invalid stored block lengths";
  83030. state->mode = BAD;
  83031. break;
  83032. }
  83033. state->length = (unsigned)hold & 0xffff;
  83034. Tracev((stderr, "inflate: stored length %u\n",
  83035. state->length));
  83036. INITBITS();
  83037. state->mode = COPY;
  83038. case COPY:
  83039. copy = state->length;
  83040. if (copy) {
  83041. if (copy > have) copy = have;
  83042. if (copy > left) copy = left;
  83043. if (copy == 0) goto inf_leave;
  83044. zmemcpy(put, next, copy);
  83045. have -= copy;
  83046. next += copy;
  83047. left -= copy;
  83048. put += copy;
  83049. state->length -= copy;
  83050. break;
  83051. }
  83052. Tracev((stderr, "inflate: stored end\n"));
  83053. state->mode = TYPE;
  83054. break;
  83055. case TABLE:
  83056. NEEDBITS(14);
  83057. state->nlen = BITS(5) + 257;
  83058. DROPBITS(5);
  83059. state->ndist = BITS(5) + 1;
  83060. DROPBITS(5);
  83061. state->ncode = BITS(4) + 4;
  83062. DROPBITS(4);
  83063. #ifndef PKZIP_BUG_WORKAROUND
  83064. if (state->nlen > 286 || state->ndist > 30) {
  83065. strm->msg = (char *)"too many length or distance symbols";
  83066. state->mode = BAD;
  83067. break;
  83068. }
  83069. #endif
  83070. Tracev((stderr, "inflate: table sizes ok\n"));
  83071. state->have = 0;
  83072. state->mode = LENLENS;
  83073. case LENLENS:
  83074. while (state->have < state->ncode) {
  83075. NEEDBITS(3);
  83076. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  83077. DROPBITS(3);
  83078. }
  83079. while (state->have < 19)
  83080. state->lens[order[state->have++]] = 0;
  83081. state->next = state->codes;
  83082. state->lencode = (code const FAR *)(state->next);
  83083. state->lenbits = 7;
  83084. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  83085. &(state->lenbits), state->work);
  83086. if (ret) {
  83087. strm->msg = (char *)"invalid code lengths set";
  83088. state->mode = BAD;
  83089. break;
  83090. }
  83091. Tracev((stderr, "inflate: code lengths ok\n"));
  83092. state->have = 0;
  83093. state->mode = CODELENS;
  83094. case CODELENS:
  83095. while (state->have < state->nlen + state->ndist) {
  83096. for (;;) {
  83097. thisx = state->lencode[BITS(state->lenbits)];
  83098. if ((unsigned)(thisx.bits) <= bits) break;
  83099. PULLBYTE();
  83100. }
  83101. if (thisx.val < 16) {
  83102. NEEDBITS(thisx.bits);
  83103. DROPBITS(thisx.bits);
  83104. state->lens[state->have++] = thisx.val;
  83105. }
  83106. else {
  83107. if (thisx.val == 16) {
  83108. NEEDBITS(thisx.bits + 2);
  83109. DROPBITS(thisx.bits);
  83110. if (state->have == 0) {
  83111. strm->msg = (char *)"invalid bit length repeat";
  83112. state->mode = BAD;
  83113. break;
  83114. }
  83115. len = state->lens[state->have - 1];
  83116. copy = 3 + BITS(2);
  83117. DROPBITS(2);
  83118. }
  83119. else if (thisx.val == 17) {
  83120. NEEDBITS(thisx.bits + 3);
  83121. DROPBITS(thisx.bits);
  83122. len = 0;
  83123. copy = 3 + BITS(3);
  83124. DROPBITS(3);
  83125. }
  83126. else {
  83127. NEEDBITS(thisx.bits + 7);
  83128. DROPBITS(thisx.bits);
  83129. len = 0;
  83130. copy = 11 + BITS(7);
  83131. DROPBITS(7);
  83132. }
  83133. if (state->have + copy > state->nlen + state->ndist) {
  83134. strm->msg = (char *)"invalid bit length repeat";
  83135. state->mode = BAD;
  83136. break;
  83137. }
  83138. while (copy--)
  83139. state->lens[state->have++] = (unsigned short)len;
  83140. }
  83141. }
  83142. /* handle error breaks in while */
  83143. if (state->mode == BAD) break;
  83144. /* build code tables */
  83145. state->next = state->codes;
  83146. state->lencode = (code const FAR *)(state->next);
  83147. state->lenbits = 9;
  83148. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  83149. &(state->lenbits), state->work);
  83150. if (ret) {
  83151. strm->msg = (char *)"invalid literal/lengths set";
  83152. state->mode = BAD;
  83153. break;
  83154. }
  83155. state->distcode = (code const FAR *)(state->next);
  83156. state->distbits = 6;
  83157. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  83158. &(state->next), &(state->distbits), state->work);
  83159. if (ret) {
  83160. strm->msg = (char *)"invalid distances set";
  83161. state->mode = BAD;
  83162. break;
  83163. }
  83164. Tracev((stderr, "inflate: codes ok\n"));
  83165. state->mode = LEN;
  83166. case LEN:
  83167. if (have >= 6 && left >= 258) {
  83168. RESTORE();
  83169. inflate_fast(strm, out);
  83170. LOAD();
  83171. break;
  83172. }
  83173. for (;;) {
  83174. thisx = state->lencode[BITS(state->lenbits)];
  83175. if ((unsigned)(thisx.bits) <= bits) break;
  83176. PULLBYTE();
  83177. }
  83178. if (thisx.op && (thisx.op & 0xf0) == 0) {
  83179. last = thisx;
  83180. for (;;) {
  83181. thisx = state->lencode[last.val +
  83182. (BITS(last.bits + last.op) >> last.bits)];
  83183. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  83184. PULLBYTE();
  83185. }
  83186. DROPBITS(last.bits);
  83187. }
  83188. DROPBITS(thisx.bits);
  83189. state->length = (unsigned)thisx.val;
  83190. if ((int)(thisx.op) == 0) {
  83191. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  83192. "inflate: literal '%c'\n" :
  83193. "inflate: literal 0x%02x\n", thisx.val));
  83194. state->mode = LIT;
  83195. break;
  83196. }
  83197. if (thisx.op & 32) {
  83198. Tracevv((stderr, "inflate: end of block\n"));
  83199. state->mode = TYPE;
  83200. break;
  83201. }
  83202. if (thisx.op & 64) {
  83203. strm->msg = (char *)"invalid literal/length code";
  83204. state->mode = BAD;
  83205. break;
  83206. }
  83207. state->extra = (unsigned)(thisx.op) & 15;
  83208. state->mode = LENEXT;
  83209. case LENEXT:
  83210. if (state->extra) {
  83211. NEEDBITS(state->extra);
  83212. state->length += BITS(state->extra);
  83213. DROPBITS(state->extra);
  83214. }
  83215. Tracevv((stderr, "inflate: length %u\n", state->length));
  83216. state->mode = DIST;
  83217. case DIST:
  83218. for (;;) {
  83219. thisx = state->distcode[BITS(state->distbits)];
  83220. if ((unsigned)(thisx.bits) <= bits) break;
  83221. PULLBYTE();
  83222. }
  83223. if ((thisx.op & 0xf0) == 0) {
  83224. last = thisx;
  83225. for (;;) {
  83226. thisx = state->distcode[last.val +
  83227. (BITS(last.bits + last.op) >> last.bits)];
  83228. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  83229. PULLBYTE();
  83230. }
  83231. DROPBITS(last.bits);
  83232. }
  83233. DROPBITS(thisx.bits);
  83234. if (thisx.op & 64) {
  83235. strm->msg = (char *)"invalid distance code";
  83236. state->mode = BAD;
  83237. break;
  83238. }
  83239. state->offset = (unsigned)thisx.val;
  83240. state->extra = (unsigned)(thisx.op) & 15;
  83241. state->mode = DISTEXT;
  83242. case DISTEXT:
  83243. if (state->extra) {
  83244. NEEDBITS(state->extra);
  83245. state->offset += BITS(state->extra);
  83246. DROPBITS(state->extra);
  83247. }
  83248. #ifdef INFLATE_STRICT
  83249. if (state->offset > state->dmax) {
  83250. strm->msg = (char *)"invalid distance too far back";
  83251. state->mode = BAD;
  83252. break;
  83253. }
  83254. #endif
  83255. if (state->offset > state->whave + out - left) {
  83256. strm->msg = (char *)"invalid distance too far back";
  83257. state->mode = BAD;
  83258. break;
  83259. }
  83260. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  83261. state->mode = MATCH;
  83262. case MATCH:
  83263. if (left == 0) goto inf_leave;
  83264. copy = out - left;
  83265. if (state->offset > copy) { /* copy from window */
  83266. copy = state->offset - copy;
  83267. if (copy > state->write) {
  83268. copy -= state->write;
  83269. from = state->window + (state->wsize - copy);
  83270. }
  83271. else
  83272. from = state->window + (state->write - copy);
  83273. if (copy > state->length) copy = state->length;
  83274. }
  83275. else { /* copy from output */
  83276. from = put - state->offset;
  83277. copy = state->length;
  83278. }
  83279. if (copy > left) copy = left;
  83280. left -= copy;
  83281. state->length -= copy;
  83282. do {
  83283. *put++ = *from++;
  83284. } while (--copy);
  83285. if (state->length == 0) state->mode = LEN;
  83286. break;
  83287. case LIT:
  83288. if (left == 0) goto inf_leave;
  83289. *put++ = (unsigned char)(state->length);
  83290. left--;
  83291. state->mode = LEN;
  83292. break;
  83293. case CHECK:
  83294. if (state->wrap) {
  83295. NEEDBITS(32);
  83296. out -= left;
  83297. strm->total_out += out;
  83298. state->total += out;
  83299. if (out)
  83300. strm->adler = state->check =
  83301. UPDATE(state->check, put - out, out);
  83302. out = left;
  83303. if ((
  83304. #ifdef GUNZIP
  83305. state->flags ? hold :
  83306. #endif
  83307. REVERSE(hold)) != state->check) {
  83308. strm->msg = (char *)"incorrect data check";
  83309. state->mode = BAD;
  83310. break;
  83311. }
  83312. INITBITS();
  83313. Tracev((stderr, "inflate: check matches trailer\n"));
  83314. }
  83315. #ifdef GUNZIP
  83316. state->mode = LENGTH;
  83317. case LENGTH:
  83318. if (state->wrap && state->flags) {
  83319. NEEDBITS(32);
  83320. if (hold != (state->total & 0xffffffffUL)) {
  83321. strm->msg = (char *)"incorrect length check";
  83322. state->mode = BAD;
  83323. break;
  83324. }
  83325. INITBITS();
  83326. Tracev((stderr, "inflate: length matches trailer\n"));
  83327. }
  83328. #endif
  83329. state->mode = DONE;
  83330. case DONE:
  83331. ret = Z_STREAM_END;
  83332. goto inf_leave;
  83333. case BAD:
  83334. ret = Z_DATA_ERROR;
  83335. goto inf_leave;
  83336. case MEM:
  83337. return Z_MEM_ERROR;
  83338. case SYNC:
  83339. default:
  83340. return Z_STREAM_ERROR;
  83341. }
  83342. /*
  83343. Return from inflate(), updating the total counts and the check value.
  83344. If there was no progress during the inflate() call, return a buffer
  83345. error. Call updatewindow() to create and/or update the window state.
  83346. Note: a memory error from inflate() is non-recoverable.
  83347. */
  83348. inf_leave:
  83349. RESTORE();
  83350. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  83351. if (updatewindow(strm, out)) {
  83352. state->mode = MEM;
  83353. return Z_MEM_ERROR;
  83354. }
  83355. in -= strm->avail_in;
  83356. out -= strm->avail_out;
  83357. strm->total_in += in;
  83358. strm->total_out += out;
  83359. state->total += out;
  83360. if (state->wrap && out)
  83361. strm->adler = state->check =
  83362. UPDATE(state->check, strm->next_out - out, out);
  83363. strm->data_type = state->bits + (state->last ? 64 : 0) +
  83364. (state->mode == TYPE ? 128 : 0);
  83365. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  83366. ret = Z_BUF_ERROR;
  83367. return ret;
  83368. }
  83369. int ZEXPORT inflateEnd (z_streamp strm)
  83370. {
  83371. struct inflate_state FAR *state;
  83372. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  83373. return Z_STREAM_ERROR;
  83374. state = (struct inflate_state FAR *)strm->state;
  83375. if (state->window != Z_NULL) ZFREE(strm, state->window);
  83376. ZFREE(strm, strm->state);
  83377. strm->state = Z_NULL;
  83378. Tracev((stderr, "inflate: end\n"));
  83379. return Z_OK;
  83380. }
  83381. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  83382. {
  83383. struct inflate_state FAR *state;
  83384. unsigned long id_;
  83385. /* check state */
  83386. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83387. state = (struct inflate_state FAR *)strm->state;
  83388. if (state->wrap != 0 && state->mode != DICT)
  83389. return Z_STREAM_ERROR;
  83390. /* check for correct dictionary id */
  83391. if (state->mode == DICT) {
  83392. id_ = adler32(0L, Z_NULL, 0);
  83393. id_ = adler32(id_, dictionary, dictLength);
  83394. if (id_ != state->check)
  83395. return Z_DATA_ERROR;
  83396. }
  83397. /* copy dictionary to window */
  83398. if (updatewindow(strm, strm->avail_out)) {
  83399. state->mode = MEM;
  83400. return Z_MEM_ERROR;
  83401. }
  83402. if (dictLength > state->wsize) {
  83403. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  83404. state->wsize);
  83405. state->whave = state->wsize;
  83406. }
  83407. else {
  83408. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  83409. dictLength);
  83410. state->whave = dictLength;
  83411. }
  83412. state->havedict = 1;
  83413. Tracev((stderr, "inflate: dictionary set\n"));
  83414. return Z_OK;
  83415. }
  83416. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  83417. {
  83418. struct inflate_state FAR *state;
  83419. /* check state */
  83420. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83421. state = (struct inflate_state FAR *)strm->state;
  83422. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  83423. /* save header structure */
  83424. state->head = head;
  83425. head->done = 0;
  83426. return Z_OK;
  83427. }
  83428. /*
  83429. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  83430. or when out of input. When called, *have is the number of pattern bytes
  83431. found in order so far, in 0..3. On return *have is updated to the new
  83432. state. If on return *have equals four, then the pattern was found and the
  83433. return value is how many bytes were read including the last byte of the
  83434. pattern. If *have is less than four, then the pattern has not been found
  83435. yet and the return value is len. In the latter case, syncsearch() can be
  83436. called again with more data and the *have state. *have is initialized to
  83437. zero for the first call.
  83438. */
  83439. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  83440. {
  83441. unsigned got;
  83442. unsigned next;
  83443. got = *have;
  83444. next = 0;
  83445. while (next < len && got < 4) {
  83446. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  83447. got++;
  83448. else if (buf[next])
  83449. got = 0;
  83450. else
  83451. got = 4 - got;
  83452. next++;
  83453. }
  83454. *have = got;
  83455. return next;
  83456. }
  83457. int ZEXPORT inflateSync (z_streamp strm)
  83458. {
  83459. unsigned len; /* number of bytes to look at or looked at */
  83460. unsigned long in, out; /* temporary to save total_in and total_out */
  83461. unsigned char buf[4]; /* to restore bit buffer to byte string */
  83462. struct inflate_state FAR *state;
  83463. /* check parameters */
  83464. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83465. state = (struct inflate_state FAR *)strm->state;
  83466. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  83467. /* if first time, start search in bit buffer */
  83468. if (state->mode != SYNC) {
  83469. state->mode = SYNC;
  83470. state->hold <<= state->bits & 7;
  83471. state->bits -= state->bits & 7;
  83472. len = 0;
  83473. while (state->bits >= 8) {
  83474. buf[len++] = (unsigned char)(state->hold);
  83475. state->hold >>= 8;
  83476. state->bits -= 8;
  83477. }
  83478. state->have = 0;
  83479. syncsearch(&(state->have), buf, len);
  83480. }
  83481. /* search available input */
  83482. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  83483. strm->avail_in -= len;
  83484. strm->next_in += len;
  83485. strm->total_in += len;
  83486. /* return no joy or set up to restart inflate() on a new block */
  83487. if (state->have != 4) return Z_DATA_ERROR;
  83488. in = strm->total_in; out = strm->total_out;
  83489. inflateReset(strm);
  83490. strm->total_in = in; strm->total_out = out;
  83491. state->mode = TYPE;
  83492. return Z_OK;
  83493. }
  83494. /*
  83495. Returns true if inflate is currently at the end of a block generated by
  83496. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  83497. implementation to provide an additional safety check. PPP uses
  83498. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  83499. block. When decompressing, PPP checks that at the end of input packet,
  83500. inflate is waiting for these length bytes.
  83501. */
  83502. int ZEXPORT inflateSyncPoint (z_streamp strm)
  83503. {
  83504. struct inflate_state FAR *state;
  83505. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83506. state = (struct inflate_state FAR *)strm->state;
  83507. return state->mode == STORED && state->bits == 0;
  83508. }
  83509. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  83510. {
  83511. struct inflate_state FAR *state;
  83512. struct inflate_state FAR *copy;
  83513. unsigned char FAR *window;
  83514. unsigned wsize;
  83515. /* check input */
  83516. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  83517. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  83518. return Z_STREAM_ERROR;
  83519. state = (struct inflate_state FAR *)source->state;
  83520. /* allocate space */
  83521. copy = (struct inflate_state FAR *)
  83522. ZALLOC(source, 1, sizeof(struct inflate_state));
  83523. if (copy == Z_NULL) return Z_MEM_ERROR;
  83524. window = Z_NULL;
  83525. if (state->window != Z_NULL) {
  83526. window = (unsigned char FAR *)
  83527. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  83528. if (window == Z_NULL) {
  83529. ZFREE(source, copy);
  83530. return Z_MEM_ERROR;
  83531. }
  83532. }
  83533. /* copy state */
  83534. zmemcpy(dest, source, sizeof(z_stream));
  83535. zmemcpy(copy, state, sizeof(struct inflate_state));
  83536. if (state->lencode >= state->codes &&
  83537. state->lencode <= state->codes + ENOUGH - 1) {
  83538. copy->lencode = copy->codes + (state->lencode - state->codes);
  83539. copy->distcode = copy->codes + (state->distcode - state->codes);
  83540. }
  83541. copy->next = copy->codes + (state->next - state->codes);
  83542. if (window != Z_NULL) {
  83543. wsize = 1U << state->wbits;
  83544. zmemcpy(window, state->window, wsize);
  83545. }
  83546. copy->window = window;
  83547. dest->state = (struct internal_state FAR *)copy;
  83548. return Z_OK;
  83549. }
  83550. /*** End of inlined file: inflate.c ***/
  83551. /*** Start of inlined file: inftrees.c ***/
  83552. #define MAXBITS 15
  83553. const char inflate_copyright[] =
  83554. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  83555. /*
  83556. If you use the zlib library in a product, an acknowledgment is welcome
  83557. in the documentation of your product. If for some reason you cannot
  83558. include such an acknowledgment, I would appreciate that you keep this
  83559. copyright string in the executable of your product.
  83560. */
  83561. /*
  83562. Build a set of tables to decode the provided canonical Huffman code.
  83563. The code lengths are lens[0..codes-1]. The result starts at *table,
  83564. whose indices are 0..2^bits-1. work is a writable array of at least
  83565. lens shorts, which is used as a work area. type is the type of code
  83566. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  83567. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  83568. on return points to the next available entry's address. bits is the
  83569. requested root table index bits, and on return it is the actual root
  83570. table index bits. It will differ if the request is greater than the
  83571. longest code or if it is less than the shortest code.
  83572. */
  83573. int inflate_table (codetype type,
  83574. unsigned short FAR *lens,
  83575. unsigned codes,
  83576. code FAR * FAR *table,
  83577. unsigned FAR *bits,
  83578. unsigned short FAR *work)
  83579. {
  83580. unsigned len; /* a code's length in bits */
  83581. unsigned sym; /* index of code symbols */
  83582. unsigned min, max; /* minimum and maximum code lengths */
  83583. unsigned root; /* number of index bits for root table */
  83584. unsigned curr; /* number of index bits for current table */
  83585. unsigned drop; /* code bits to drop for sub-table */
  83586. int left; /* number of prefix codes available */
  83587. unsigned used; /* code entries in table used */
  83588. unsigned huff; /* Huffman code */
  83589. unsigned incr; /* for incrementing code, index */
  83590. unsigned fill; /* index for replicating entries */
  83591. unsigned low; /* low bits for current root entry */
  83592. unsigned mask; /* mask for low root bits */
  83593. code thisx; /* table entry for duplication */
  83594. code FAR *next; /* next available space in table */
  83595. const unsigned short FAR *base; /* base value table to use */
  83596. const unsigned short FAR *extra; /* extra bits table to use */
  83597. int end; /* use base and extra for symbol > end */
  83598. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  83599. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  83600. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  83601. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  83602. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  83603. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  83604. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  83605. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  83606. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  83607. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  83608. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  83609. 8193, 12289, 16385, 24577, 0, 0};
  83610. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  83611. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  83612. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  83613. 28, 28, 29, 29, 64, 64};
  83614. /*
  83615. Process a set of code lengths to create a canonical Huffman code. The
  83616. code lengths are lens[0..codes-1]. Each length corresponds to the
  83617. symbols 0..codes-1. The Huffman code is generated by first sorting the
  83618. symbols by length from short to long, and retaining the symbol order
  83619. for codes with equal lengths. Then the code starts with all zero bits
  83620. for the first code of the shortest length, and the codes are integer
  83621. increments for the same length, and zeros are appended as the length
  83622. increases. For the deflate format, these bits are stored backwards
  83623. from their more natural integer increment ordering, and so when the
  83624. decoding tables are built in the large loop below, the integer codes
  83625. are incremented backwards.
  83626. This routine assumes, but does not check, that all of the entries in
  83627. lens[] are in the range 0..MAXBITS. The caller must assure this.
  83628. 1..MAXBITS is interpreted as that code length. zero means that that
  83629. symbol does not occur in this code.
  83630. The codes are sorted by computing a count of codes for each length,
  83631. creating from that a table of starting indices for each length in the
  83632. sorted table, and then entering the symbols in order in the sorted
  83633. table. The sorted table is work[], with that space being provided by
  83634. the caller.
  83635. The length counts are used for other purposes as well, i.e. finding
  83636. the minimum and maximum length codes, determining if there are any
  83637. codes at all, checking for a valid set of lengths, and looking ahead
  83638. at length counts to determine sub-table sizes when building the
  83639. decoding tables.
  83640. */
  83641. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  83642. for (len = 0; len <= MAXBITS; len++)
  83643. count[len] = 0;
  83644. for (sym = 0; sym < codes; sym++)
  83645. count[lens[sym]]++;
  83646. /* bound code lengths, force root to be within code lengths */
  83647. root = *bits;
  83648. for (max = MAXBITS; max >= 1; max--)
  83649. if (count[max] != 0) break;
  83650. if (root > max) root = max;
  83651. if (max == 0) { /* no symbols to code at all */
  83652. thisx.op = (unsigned char)64; /* invalid code marker */
  83653. thisx.bits = (unsigned char)1;
  83654. thisx.val = (unsigned short)0;
  83655. *(*table)++ = thisx; /* make a table to force an error */
  83656. *(*table)++ = thisx;
  83657. *bits = 1;
  83658. return 0; /* no symbols, but wait for decoding to report error */
  83659. }
  83660. for (min = 1; min <= MAXBITS; min++)
  83661. if (count[min] != 0) break;
  83662. if (root < min) root = min;
  83663. /* check for an over-subscribed or incomplete set of lengths */
  83664. left = 1;
  83665. for (len = 1; len <= MAXBITS; len++) {
  83666. left <<= 1;
  83667. left -= count[len];
  83668. if (left < 0) return -1; /* over-subscribed */
  83669. }
  83670. if (left > 0 && (type == CODES || max != 1))
  83671. return -1; /* incomplete set */
  83672. /* generate offsets into symbol table for each length for sorting */
  83673. offs[1] = 0;
  83674. for (len = 1; len < MAXBITS; len++)
  83675. offs[len + 1] = offs[len] + count[len];
  83676. /* sort symbols by length, by symbol order within each length */
  83677. for (sym = 0; sym < codes; sym++)
  83678. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  83679. /*
  83680. Create and fill in decoding tables. In this loop, the table being
  83681. filled is at next and has curr index bits. The code being used is huff
  83682. with length len. That code is converted to an index by dropping drop
  83683. bits off of the bottom. For codes where len is less than drop + curr,
  83684. those top drop + curr - len bits are incremented through all values to
  83685. fill the table with replicated entries.
  83686. root is the number of index bits for the root table. When len exceeds
  83687. root, sub-tables are created pointed to by the root entry with an index
  83688. of the low root bits of huff. This is saved in low to check for when a
  83689. new sub-table should be started. drop is zero when the root table is
  83690. being filled, and drop is root when sub-tables are being filled.
  83691. When a new sub-table is needed, it is necessary to look ahead in the
  83692. code lengths to determine what size sub-table is needed. The length
  83693. counts are used for this, and so count[] is decremented as codes are
  83694. entered in the tables.
  83695. used keeps track of how many table entries have been allocated from the
  83696. provided *table space. It is checked when a LENS table is being made
  83697. against the space in *table, ENOUGH, minus the maximum space needed by
  83698. the worst case distance code, MAXD. This should never happen, but the
  83699. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  83700. This assumes that when type == LENS, bits == 9.
  83701. sym increments through all symbols, and the loop terminates when
  83702. all codes of length max, i.e. all codes, have been processed. This
  83703. routine permits incomplete codes, so another loop after this one fills
  83704. in the rest of the decoding tables with invalid code markers.
  83705. */
  83706. /* set up for code type */
  83707. switch (type) {
  83708. case CODES:
  83709. base = extra = work; /* dummy value--not used */
  83710. end = 19;
  83711. break;
  83712. case LENS:
  83713. base = lbase;
  83714. base -= 257;
  83715. extra = lext;
  83716. extra -= 257;
  83717. end = 256;
  83718. break;
  83719. default: /* DISTS */
  83720. base = dbase;
  83721. extra = dext;
  83722. end = -1;
  83723. }
  83724. /* initialize state for loop */
  83725. huff = 0; /* starting code */
  83726. sym = 0; /* starting code symbol */
  83727. len = min; /* starting code length */
  83728. next = *table; /* current table to fill in */
  83729. curr = root; /* current table index bits */
  83730. drop = 0; /* current bits to drop from code for index */
  83731. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  83732. used = 1U << root; /* use root table entries */
  83733. mask = used - 1; /* mask for comparing low */
  83734. /* check available table space */
  83735. if (type == LENS && used >= ENOUGH - MAXD)
  83736. return 1;
  83737. /* process all codes and make table entries */
  83738. for (;;) {
  83739. /* create table entry */
  83740. thisx.bits = (unsigned char)(len - drop);
  83741. if ((int)(work[sym]) < end) {
  83742. thisx.op = (unsigned char)0;
  83743. thisx.val = work[sym];
  83744. }
  83745. else if ((int)(work[sym]) > end) {
  83746. thisx.op = (unsigned char)(extra[work[sym]]);
  83747. thisx.val = base[work[sym]];
  83748. }
  83749. else {
  83750. thisx.op = (unsigned char)(32 + 64); /* end of block */
  83751. thisx.val = 0;
  83752. }
  83753. /* replicate for those indices with low len bits equal to huff */
  83754. incr = 1U << (len - drop);
  83755. fill = 1U << curr;
  83756. min = fill; /* save offset to next table */
  83757. do {
  83758. fill -= incr;
  83759. next[(huff >> drop) + fill] = thisx;
  83760. } while (fill != 0);
  83761. /* backwards increment the len-bit code huff */
  83762. incr = 1U << (len - 1);
  83763. while (huff & incr)
  83764. incr >>= 1;
  83765. if (incr != 0) {
  83766. huff &= incr - 1;
  83767. huff += incr;
  83768. }
  83769. else
  83770. huff = 0;
  83771. /* go to next symbol, update count, len */
  83772. sym++;
  83773. if (--(count[len]) == 0) {
  83774. if (len == max) break;
  83775. len = lens[work[sym]];
  83776. }
  83777. /* create new sub-table if needed */
  83778. if (len > root && (huff & mask) != low) {
  83779. /* if first time, transition to sub-tables */
  83780. if (drop == 0)
  83781. drop = root;
  83782. /* increment past last table */
  83783. next += min; /* here min is 1 << curr */
  83784. /* determine length of next table */
  83785. curr = len - drop;
  83786. left = (int)(1 << curr);
  83787. while (curr + drop < max) {
  83788. left -= count[curr + drop];
  83789. if (left <= 0) break;
  83790. curr++;
  83791. left <<= 1;
  83792. }
  83793. /* check for enough space */
  83794. used += 1U << curr;
  83795. if (type == LENS && used >= ENOUGH - MAXD)
  83796. return 1;
  83797. /* point entry in root table to sub-table */
  83798. low = huff & mask;
  83799. (*table)[low].op = (unsigned char)curr;
  83800. (*table)[low].bits = (unsigned char)root;
  83801. (*table)[low].val = (unsigned short)(next - *table);
  83802. }
  83803. }
  83804. /*
  83805. Fill in rest of table for incomplete codes. This loop is similar to the
  83806. loop above in incrementing huff for table indices. It is assumed that
  83807. len is equal to curr + drop, so there is no loop needed to increment
  83808. through high index bits. When the current sub-table is filled, the loop
  83809. drops back to the root table to fill in any remaining entries there.
  83810. */
  83811. thisx.op = (unsigned char)64; /* invalid code marker */
  83812. thisx.bits = (unsigned char)(len - drop);
  83813. thisx.val = (unsigned short)0;
  83814. while (huff != 0) {
  83815. /* when done with sub-table, drop back to root table */
  83816. if (drop != 0 && (huff & mask) != low) {
  83817. drop = 0;
  83818. len = root;
  83819. next = *table;
  83820. thisx.bits = (unsigned char)len;
  83821. }
  83822. /* put invalid code marker in table */
  83823. next[huff >> drop] = thisx;
  83824. /* backwards increment the len-bit code huff */
  83825. incr = 1U << (len - 1);
  83826. while (huff & incr)
  83827. incr >>= 1;
  83828. if (incr != 0) {
  83829. huff &= incr - 1;
  83830. huff += incr;
  83831. }
  83832. else
  83833. huff = 0;
  83834. }
  83835. /* set return parameters */
  83836. *table += used;
  83837. *bits = root;
  83838. return 0;
  83839. }
  83840. /*** End of inlined file: inftrees.c ***/
  83841. /*** Start of inlined file: trees.c ***/
  83842. /*
  83843. * ALGORITHM
  83844. *
  83845. * The "deflation" process uses several Huffman trees. The more
  83846. * common source values are represented by shorter bit sequences.
  83847. *
  83848. * Each code tree is stored in a compressed form which is itself
  83849. * a Huffman encoding of the lengths of all the code strings (in
  83850. * ascending order by source values). The actual code strings are
  83851. * reconstructed from the lengths in the inflate process, as described
  83852. * in the deflate specification.
  83853. *
  83854. * REFERENCES
  83855. *
  83856. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  83857. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  83858. *
  83859. * Storer, James A.
  83860. * Data Compression: Methods and Theory, pp. 49-50.
  83861. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  83862. *
  83863. * Sedgewick, R.
  83864. * Algorithms, p290.
  83865. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  83866. */
  83867. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  83868. /* #define GEN_TREES_H */
  83869. #ifdef DEBUG
  83870. # include <ctype.h>
  83871. #endif
  83872. /* ===========================================================================
  83873. * Constants
  83874. */
  83875. #define MAX_BL_BITS 7
  83876. /* Bit length codes must not exceed MAX_BL_BITS bits */
  83877. #define END_BLOCK 256
  83878. /* end of block literal code */
  83879. #define REP_3_6 16
  83880. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  83881. #define REPZ_3_10 17
  83882. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  83883. #define REPZ_11_138 18
  83884. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  83885. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  83886. = {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};
  83887. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  83888. = {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};
  83889. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  83890. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  83891. local const uch bl_order[BL_CODES]
  83892. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  83893. /* The lengths of the bit length codes are sent in order of decreasing
  83894. * probability, to avoid transmitting the lengths for unused bit length codes.
  83895. */
  83896. #define Buf_size (8 * 2*sizeof(char))
  83897. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  83898. * more than 16 bits on some systems.)
  83899. */
  83900. /* ===========================================================================
  83901. * Local data. These are initialized only once.
  83902. */
  83903. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  83904. #if defined(GEN_TREES_H) || !defined(STDC)
  83905. /* non ANSI compilers may not accept trees.h */
  83906. local ct_data static_ltree[L_CODES+2];
  83907. /* The static literal tree. Since the bit lengths are imposed, there is no
  83908. * need for the L_CODES extra codes used during heap construction. However
  83909. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  83910. * below).
  83911. */
  83912. local ct_data static_dtree[D_CODES];
  83913. /* The static distance tree. (Actually a trivial tree since all codes use
  83914. * 5 bits.)
  83915. */
  83916. uch _dist_code[DIST_CODE_LEN];
  83917. /* Distance codes. The first 256 values correspond to the distances
  83918. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  83919. * the 15 bit distances.
  83920. */
  83921. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  83922. /* length code for each normalized match length (0 == MIN_MATCH) */
  83923. local int base_length[LENGTH_CODES];
  83924. /* First normalized length for each code (0 = MIN_MATCH) */
  83925. local int base_dist[D_CODES];
  83926. /* First normalized distance for each code (0 = distance of 1) */
  83927. #else
  83928. /*** Start of inlined file: trees.h ***/
  83929. local const ct_data static_ltree[L_CODES+2] = {
  83930. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  83931. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  83932. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  83933. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  83934. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  83935. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  83936. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  83937. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  83938. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  83939. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  83940. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  83941. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  83942. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  83943. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  83944. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  83945. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  83946. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  83947. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  83948. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  83949. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  83950. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  83951. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  83952. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  83953. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  83954. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  83955. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  83956. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  83957. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  83958. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  83959. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  83960. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  83961. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  83962. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  83963. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  83964. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  83965. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  83966. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  83967. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  83968. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  83969. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  83970. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  83971. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  83972. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  83973. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  83974. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  83975. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  83976. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  83977. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  83978. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  83979. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  83980. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  83981. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  83982. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  83983. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  83984. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  83985. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  83986. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  83987. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  83988. };
  83989. local const ct_data static_dtree[D_CODES] = {
  83990. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  83991. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  83992. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  83993. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  83994. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  83995. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  83996. };
  83997. const uch _dist_code[DIST_CODE_LEN] = {
  83998. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  83999. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  84000. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  84001. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  84002. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  84003. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  84004. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84005. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84006. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84007. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  84008. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  84009. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  84010. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  84011. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  84012. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84013. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  84014. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  84015. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  84016. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  84017. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84018. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84019. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84020. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84021. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84022. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84023. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  84024. };
  84025. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  84026. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  84027. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  84028. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  84029. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  84030. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  84031. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  84032. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84033. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84034. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  84035. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  84036. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  84037. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  84038. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  84039. };
  84040. local const int base_length[LENGTH_CODES] = {
  84041. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  84042. 64, 80, 96, 112, 128, 160, 192, 224, 0
  84043. };
  84044. local const int base_dist[D_CODES] = {
  84045. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  84046. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  84047. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  84048. };
  84049. /*** End of inlined file: trees.h ***/
  84050. #endif /* GEN_TREES_H */
  84051. struct static_tree_desc_s {
  84052. const ct_data *static_tree; /* static tree or NULL */
  84053. const intf *extra_bits; /* extra bits for each code or NULL */
  84054. int extra_base; /* base index for extra_bits */
  84055. int elems; /* max number of elements in the tree */
  84056. int max_length; /* max bit length for the codes */
  84057. };
  84058. local static_tree_desc static_l_desc =
  84059. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  84060. local static_tree_desc static_d_desc =
  84061. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  84062. local static_tree_desc static_bl_desc =
  84063. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  84064. /* ===========================================================================
  84065. * Local (static) routines in this file.
  84066. */
  84067. local void tr_static_init OF((void));
  84068. local void init_block OF((deflate_state *s));
  84069. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  84070. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  84071. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  84072. local void build_tree OF((deflate_state *s, tree_desc *desc));
  84073. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  84074. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  84075. local int build_bl_tree OF((deflate_state *s));
  84076. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  84077. int blcodes));
  84078. local void compress_block OF((deflate_state *s, ct_data *ltree,
  84079. ct_data *dtree));
  84080. local void set_data_type OF((deflate_state *s));
  84081. local unsigned bi_reverse OF((unsigned value, int length));
  84082. local void bi_windup OF((deflate_state *s));
  84083. local void bi_flush OF((deflate_state *s));
  84084. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  84085. int header));
  84086. #ifdef GEN_TREES_H
  84087. local void gen_trees_header OF((void));
  84088. #endif
  84089. #ifndef DEBUG
  84090. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  84091. /* Send a code of the given tree. c and tree must not have side effects */
  84092. #else /* DEBUG */
  84093. # define send_code(s, c, tree) \
  84094. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  84095. send_bits(s, tree[c].Code, tree[c].Len); }
  84096. #endif
  84097. /* ===========================================================================
  84098. * Output a short LSB first on the stream.
  84099. * IN assertion: there is enough room in pendingBuf.
  84100. */
  84101. #define put_short(s, w) { \
  84102. put_byte(s, (uch)((w) & 0xff)); \
  84103. put_byte(s, (uch)((ush)(w) >> 8)); \
  84104. }
  84105. /* ===========================================================================
  84106. * Send a value on a given number of bits.
  84107. * IN assertion: length <= 16 and value fits in length bits.
  84108. */
  84109. #ifdef DEBUG
  84110. local void send_bits OF((deflate_state *s, int value, int length));
  84111. local void send_bits (deflate_state *s, int value, int length)
  84112. {
  84113. Tracevv((stderr," l %2d v %4x ", length, value));
  84114. Assert(length > 0 && length <= 15, "invalid length");
  84115. s->bits_sent += (ulg)length;
  84116. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  84117. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  84118. * unused bits in value.
  84119. */
  84120. if (s->bi_valid > (int)Buf_size - length) {
  84121. s->bi_buf |= (value << s->bi_valid);
  84122. put_short(s, s->bi_buf);
  84123. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  84124. s->bi_valid += length - Buf_size;
  84125. } else {
  84126. s->bi_buf |= value << s->bi_valid;
  84127. s->bi_valid += length;
  84128. }
  84129. }
  84130. #else /* !DEBUG */
  84131. #define send_bits(s, value, length) \
  84132. { int len = length;\
  84133. if (s->bi_valid > (int)Buf_size - len) {\
  84134. int val = value;\
  84135. s->bi_buf |= (val << s->bi_valid);\
  84136. put_short(s, s->bi_buf);\
  84137. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  84138. s->bi_valid += len - Buf_size;\
  84139. } else {\
  84140. s->bi_buf |= (value) << s->bi_valid;\
  84141. s->bi_valid += len;\
  84142. }\
  84143. }
  84144. #endif /* DEBUG */
  84145. /* the arguments must not have side effects */
  84146. /* ===========================================================================
  84147. * Initialize the various 'constant' tables.
  84148. */
  84149. local void tr_static_init()
  84150. {
  84151. #if defined(GEN_TREES_H) || !defined(STDC)
  84152. static int static_init_done = 0;
  84153. int n; /* iterates over tree elements */
  84154. int bits; /* bit counter */
  84155. int length; /* length value */
  84156. int code; /* code value */
  84157. int dist; /* distance index */
  84158. ush bl_count[MAX_BITS+1];
  84159. /* number of codes at each bit length for an optimal tree */
  84160. if (static_init_done) return;
  84161. /* For some embedded targets, global variables are not initialized: */
  84162. static_l_desc.static_tree = static_ltree;
  84163. static_l_desc.extra_bits = extra_lbits;
  84164. static_d_desc.static_tree = static_dtree;
  84165. static_d_desc.extra_bits = extra_dbits;
  84166. static_bl_desc.extra_bits = extra_blbits;
  84167. /* Initialize the mapping length (0..255) -> length code (0..28) */
  84168. length = 0;
  84169. for (code = 0; code < LENGTH_CODES-1; code++) {
  84170. base_length[code] = length;
  84171. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  84172. _length_code[length++] = (uch)code;
  84173. }
  84174. }
  84175. Assert (length == 256, "tr_static_init: length != 256");
  84176. /* Note that the length 255 (match length 258) can be represented
  84177. * in two different ways: code 284 + 5 bits or code 285, so we
  84178. * overwrite length_code[255] to use the best encoding:
  84179. */
  84180. _length_code[length-1] = (uch)code;
  84181. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  84182. dist = 0;
  84183. for (code = 0 ; code < 16; code++) {
  84184. base_dist[code] = dist;
  84185. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  84186. _dist_code[dist++] = (uch)code;
  84187. }
  84188. }
  84189. Assert (dist == 256, "tr_static_init: dist != 256");
  84190. dist >>= 7; /* from now on, all distances are divided by 128 */
  84191. for ( ; code < D_CODES; code++) {
  84192. base_dist[code] = dist << 7;
  84193. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  84194. _dist_code[256 + dist++] = (uch)code;
  84195. }
  84196. }
  84197. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  84198. /* Construct the codes of the static literal tree */
  84199. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  84200. n = 0;
  84201. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  84202. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  84203. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  84204. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  84205. /* Codes 286 and 287 do not exist, but we must include them in the
  84206. * tree construction to get a canonical Huffman tree (longest code
  84207. * all ones)
  84208. */
  84209. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  84210. /* The static distance tree is trivial: */
  84211. for (n = 0; n < D_CODES; n++) {
  84212. static_dtree[n].Len = 5;
  84213. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  84214. }
  84215. static_init_done = 1;
  84216. # ifdef GEN_TREES_H
  84217. gen_trees_header();
  84218. # endif
  84219. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  84220. }
  84221. /* ===========================================================================
  84222. * Genererate the file trees.h describing the static trees.
  84223. */
  84224. #ifdef GEN_TREES_H
  84225. # ifndef DEBUG
  84226. # include <stdio.h>
  84227. # endif
  84228. # define SEPARATOR(i, last, width) \
  84229. ((i) == (last)? "\n};\n\n" : \
  84230. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  84231. void gen_trees_header()
  84232. {
  84233. FILE *header = fopen("trees.h", "w");
  84234. int i;
  84235. Assert (header != NULL, "Can't open trees.h");
  84236. fprintf(header,
  84237. "/* header created automatically with -DGEN_TREES_H */\n\n");
  84238. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  84239. for (i = 0; i < L_CODES+2; i++) {
  84240. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  84241. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  84242. }
  84243. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  84244. for (i = 0; i < D_CODES; i++) {
  84245. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  84246. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  84247. }
  84248. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  84249. for (i = 0; i < DIST_CODE_LEN; i++) {
  84250. fprintf(header, "%2u%s", _dist_code[i],
  84251. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  84252. }
  84253. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  84254. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  84255. fprintf(header, "%2u%s", _length_code[i],
  84256. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  84257. }
  84258. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  84259. for (i = 0; i < LENGTH_CODES; i++) {
  84260. fprintf(header, "%1u%s", base_length[i],
  84261. SEPARATOR(i, LENGTH_CODES-1, 20));
  84262. }
  84263. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  84264. for (i = 0; i < D_CODES; i++) {
  84265. fprintf(header, "%5u%s", base_dist[i],
  84266. SEPARATOR(i, D_CODES-1, 10));
  84267. }
  84268. fclose(header);
  84269. }
  84270. #endif /* GEN_TREES_H */
  84271. /* ===========================================================================
  84272. * Initialize the tree data structures for a new zlib stream.
  84273. */
  84274. void _tr_init(deflate_state *s)
  84275. {
  84276. tr_static_init();
  84277. s->l_desc.dyn_tree = s->dyn_ltree;
  84278. s->l_desc.stat_desc = &static_l_desc;
  84279. s->d_desc.dyn_tree = s->dyn_dtree;
  84280. s->d_desc.stat_desc = &static_d_desc;
  84281. s->bl_desc.dyn_tree = s->bl_tree;
  84282. s->bl_desc.stat_desc = &static_bl_desc;
  84283. s->bi_buf = 0;
  84284. s->bi_valid = 0;
  84285. s->last_eob_len = 8; /* enough lookahead for inflate */
  84286. #ifdef DEBUG
  84287. s->compressed_len = 0L;
  84288. s->bits_sent = 0L;
  84289. #endif
  84290. /* Initialize the first block of the first file: */
  84291. init_block(s);
  84292. }
  84293. /* ===========================================================================
  84294. * Initialize a new block.
  84295. */
  84296. local void init_block (deflate_state *s)
  84297. {
  84298. int n; /* iterates over tree elements */
  84299. /* Initialize the trees. */
  84300. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  84301. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  84302. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  84303. s->dyn_ltree[END_BLOCK].Freq = 1;
  84304. s->opt_len = s->static_len = 0L;
  84305. s->last_lit = s->matches = 0;
  84306. }
  84307. #define SMALLEST 1
  84308. /* Index within the heap array of least frequent node in the Huffman tree */
  84309. /* ===========================================================================
  84310. * Remove the smallest element from the heap and recreate the heap with
  84311. * one less element. Updates heap and heap_len.
  84312. */
  84313. #define pqremove(s, tree, top) \
  84314. {\
  84315. top = s->heap[SMALLEST]; \
  84316. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  84317. pqdownheap(s, tree, SMALLEST); \
  84318. }
  84319. /* ===========================================================================
  84320. * Compares to subtrees, using the tree depth as tie breaker when
  84321. * the subtrees have equal frequency. This minimizes the worst case length.
  84322. */
  84323. #define smaller(tree, n, m, depth) \
  84324. (tree[n].Freq < tree[m].Freq || \
  84325. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  84326. /* ===========================================================================
  84327. * Restore the heap property by moving down the tree starting at node k,
  84328. * exchanging a node with the smallest of its two sons if necessary, stopping
  84329. * when the heap property is re-established (each father smaller than its
  84330. * two sons).
  84331. */
  84332. local void pqdownheap (deflate_state *s,
  84333. ct_data *tree, /* the tree to restore */
  84334. int k) /* node to move down */
  84335. {
  84336. int v = s->heap[k];
  84337. int j = k << 1; /* left son of k */
  84338. while (j <= s->heap_len) {
  84339. /* Set j to the smallest of the two sons: */
  84340. if (j < s->heap_len &&
  84341. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  84342. j++;
  84343. }
  84344. /* Exit if v is smaller than both sons */
  84345. if (smaller(tree, v, s->heap[j], s->depth)) break;
  84346. /* Exchange v with the smallest son */
  84347. s->heap[k] = s->heap[j]; k = j;
  84348. /* And continue down the tree, setting j to the left son of k */
  84349. j <<= 1;
  84350. }
  84351. s->heap[k] = v;
  84352. }
  84353. /* ===========================================================================
  84354. * Compute the optimal bit lengths for a tree and update the total bit length
  84355. * for the current block.
  84356. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  84357. * above are the tree nodes sorted by increasing frequency.
  84358. * OUT assertions: the field len is set to the optimal bit length, the
  84359. * array bl_count contains the frequencies for each bit length.
  84360. * The length opt_len is updated; static_len is also updated if stree is
  84361. * not null.
  84362. */
  84363. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  84364. {
  84365. ct_data *tree = desc->dyn_tree;
  84366. int max_code = desc->max_code;
  84367. const ct_data *stree = desc->stat_desc->static_tree;
  84368. const intf *extra = desc->stat_desc->extra_bits;
  84369. int base = desc->stat_desc->extra_base;
  84370. int max_length = desc->stat_desc->max_length;
  84371. int h; /* heap index */
  84372. int n, m; /* iterate over the tree elements */
  84373. int bits; /* bit length */
  84374. int xbits; /* extra bits */
  84375. ush f; /* frequency */
  84376. int overflow = 0; /* number of elements with bit length too large */
  84377. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  84378. /* In a first pass, compute the optimal bit lengths (which may
  84379. * overflow in the case of the bit length tree).
  84380. */
  84381. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  84382. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  84383. n = s->heap[h];
  84384. bits = tree[tree[n].Dad].Len + 1;
  84385. if (bits > max_length) bits = max_length, overflow++;
  84386. tree[n].Len = (ush)bits;
  84387. /* We overwrite tree[n].Dad which is no longer needed */
  84388. if (n > max_code) continue; /* not a leaf node */
  84389. s->bl_count[bits]++;
  84390. xbits = 0;
  84391. if (n >= base) xbits = extra[n-base];
  84392. f = tree[n].Freq;
  84393. s->opt_len += (ulg)f * (bits + xbits);
  84394. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  84395. }
  84396. if (overflow == 0) return;
  84397. Trace((stderr,"\nbit length overflow\n"));
  84398. /* This happens for example on obj2 and pic of the Calgary corpus */
  84399. /* Find the first bit length which could increase: */
  84400. do {
  84401. bits = max_length-1;
  84402. while (s->bl_count[bits] == 0) bits--;
  84403. s->bl_count[bits]--; /* move one leaf down the tree */
  84404. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  84405. s->bl_count[max_length]--;
  84406. /* The brother of the overflow item also moves one step up,
  84407. * but this does not affect bl_count[max_length]
  84408. */
  84409. overflow -= 2;
  84410. } while (overflow > 0);
  84411. /* Now recompute all bit lengths, scanning in increasing frequency.
  84412. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  84413. * lengths instead of fixing only the wrong ones. This idea is taken
  84414. * from 'ar' written by Haruhiko Okumura.)
  84415. */
  84416. for (bits = max_length; bits != 0; bits--) {
  84417. n = s->bl_count[bits];
  84418. while (n != 0) {
  84419. m = s->heap[--h];
  84420. if (m > max_code) continue;
  84421. if ((unsigned) tree[m].Len != (unsigned) bits) {
  84422. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  84423. s->opt_len += ((long)bits - (long)tree[m].Len)
  84424. *(long)tree[m].Freq;
  84425. tree[m].Len = (ush)bits;
  84426. }
  84427. n--;
  84428. }
  84429. }
  84430. }
  84431. /* ===========================================================================
  84432. * Generate the codes for a given tree and bit counts (which need not be
  84433. * optimal).
  84434. * IN assertion: the array bl_count contains the bit length statistics for
  84435. * the given tree and the field len is set for all tree elements.
  84436. * OUT assertion: the field code is set for all tree elements of non
  84437. * zero code length.
  84438. */
  84439. local void gen_codes (ct_data *tree, /* the tree to decorate */
  84440. int max_code, /* largest code with non zero frequency */
  84441. ushf *bl_count) /* number of codes at each bit length */
  84442. {
  84443. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  84444. ush code = 0; /* running code value */
  84445. int bits; /* bit index */
  84446. int n; /* code index */
  84447. /* The distribution counts are first used to generate the code values
  84448. * without bit reversal.
  84449. */
  84450. for (bits = 1; bits <= MAX_BITS; bits++) {
  84451. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  84452. }
  84453. /* Check that the bit counts in bl_count are consistent. The last code
  84454. * must be all ones.
  84455. */
  84456. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  84457. "inconsistent bit counts");
  84458. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  84459. for (n = 0; n <= max_code; n++) {
  84460. int len = tree[n].Len;
  84461. if (len == 0) continue;
  84462. /* Now reverse the bits */
  84463. tree[n].Code = bi_reverse(next_code[len]++, len);
  84464. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  84465. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  84466. }
  84467. }
  84468. /* ===========================================================================
  84469. * Construct one Huffman tree and assigns the code bit strings and lengths.
  84470. * Update the total bit length for the current block.
  84471. * IN assertion: the field freq is set for all tree elements.
  84472. * OUT assertions: the fields len and code are set to the optimal bit length
  84473. * and corresponding code. The length opt_len is updated; static_len is
  84474. * also updated if stree is not null. The field max_code is set.
  84475. */
  84476. local void build_tree (deflate_state *s,
  84477. tree_desc *desc) /* the tree descriptor */
  84478. {
  84479. ct_data *tree = desc->dyn_tree;
  84480. const ct_data *stree = desc->stat_desc->static_tree;
  84481. int elems = desc->stat_desc->elems;
  84482. int n, m; /* iterate over heap elements */
  84483. int max_code = -1; /* largest code with non zero frequency */
  84484. int node; /* new node being created */
  84485. /* Construct the initial heap, with least frequent element in
  84486. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  84487. * heap[0] is not used.
  84488. */
  84489. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  84490. for (n = 0; n < elems; n++) {
  84491. if (tree[n].Freq != 0) {
  84492. s->heap[++(s->heap_len)] = max_code = n;
  84493. s->depth[n] = 0;
  84494. } else {
  84495. tree[n].Len = 0;
  84496. }
  84497. }
  84498. /* The pkzip format requires that at least one distance code exists,
  84499. * and that at least one bit should be sent even if there is only one
  84500. * possible code. So to avoid special checks later on we force at least
  84501. * two codes of non zero frequency.
  84502. */
  84503. while (s->heap_len < 2) {
  84504. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  84505. tree[node].Freq = 1;
  84506. s->depth[node] = 0;
  84507. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  84508. /* node is 0 or 1 so it does not have extra bits */
  84509. }
  84510. desc->max_code = max_code;
  84511. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  84512. * establish sub-heaps of increasing lengths:
  84513. */
  84514. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  84515. /* Construct the Huffman tree by repeatedly combining the least two
  84516. * frequent nodes.
  84517. */
  84518. node = elems; /* next internal node of the tree */
  84519. do {
  84520. pqremove(s, tree, n); /* n = node of least frequency */
  84521. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  84522. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  84523. s->heap[--(s->heap_max)] = m;
  84524. /* Create a new node father of n and m */
  84525. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  84526. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  84527. s->depth[n] : s->depth[m]) + 1);
  84528. tree[n].Dad = tree[m].Dad = (ush)node;
  84529. #ifdef DUMP_BL_TREE
  84530. if (tree == s->bl_tree) {
  84531. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  84532. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  84533. }
  84534. #endif
  84535. /* and insert the new node in the heap */
  84536. s->heap[SMALLEST] = node++;
  84537. pqdownheap(s, tree, SMALLEST);
  84538. } while (s->heap_len >= 2);
  84539. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  84540. /* At this point, the fields freq and dad are set. We can now
  84541. * generate the bit lengths.
  84542. */
  84543. gen_bitlen(s, (tree_desc *)desc);
  84544. /* The field len is now set, we can generate the bit codes */
  84545. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  84546. }
  84547. /* ===========================================================================
  84548. * Scan a literal or distance tree to determine the frequencies of the codes
  84549. * in the bit length tree.
  84550. */
  84551. local void scan_tree (deflate_state *s,
  84552. ct_data *tree, /* the tree to be scanned */
  84553. int max_code) /* and its largest code of non zero frequency */
  84554. {
  84555. int n; /* iterates over all tree elements */
  84556. int prevlen = -1; /* last emitted length */
  84557. int curlen; /* length of current code */
  84558. int nextlen = tree[0].Len; /* length of next code */
  84559. int count = 0; /* repeat count of the current code */
  84560. int max_count = 7; /* max repeat count */
  84561. int min_count = 4; /* min repeat count */
  84562. if (nextlen == 0) max_count = 138, min_count = 3;
  84563. tree[max_code+1].Len = (ush)0xffff; /* guard */
  84564. for (n = 0; n <= max_code; n++) {
  84565. curlen = nextlen; nextlen = tree[n+1].Len;
  84566. if (++count < max_count && curlen == nextlen) {
  84567. continue;
  84568. } else if (count < min_count) {
  84569. s->bl_tree[curlen].Freq += count;
  84570. } else if (curlen != 0) {
  84571. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  84572. s->bl_tree[REP_3_6].Freq++;
  84573. } else if (count <= 10) {
  84574. s->bl_tree[REPZ_3_10].Freq++;
  84575. } else {
  84576. s->bl_tree[REPZ_11_138].Freq++;
  84577. }
  84578. count = 0; prevlen = curlen;
  84579. if (nextlen == 0) {
  84580. max_count = 138, min_count = 3;
  84581. } else if (curlen == nextlen) {
  84582. max_count = 6, min_count = 3;
  84583. } else {
  84584. max_count = 7, min_count = 4;
  84585. }
  84586. }
  84587. }
  84588. /* ===========================================================================
  84589. * Send a literal or distance tree in compressed form, using the codes in
  84590. * bl_tree.
  84591. */
  84592. local void send_tree (deflate_state *s,
  84593. ct_data *tree, /* the tree to be scanned */
  84594. int max_code) /* and its largest code of non zero frequency */
  84595. {
  84596. int n; /* iterates over all tree elements */
  84597. int prevlen = -1; /* last emitted length */
  84598. int curlen; /* length of current code */
  84599. int nextlen = tree[0].Len; /* length of next code */
  84600. int count = 0; /* repeat count of the current code */
  84601. int max_count = 7; /* max repeat count */
  84602. int min_count = 4; /* min repeat count */
  84603. /* tree[max_code+1].Len = -1; */ /* guard already set */
  84604. if (nextlen == 0) max_count = 138, min_count = 3;
  84605. for (n = 0; n <= max_code; n++) {
  84606. curlen = nextlen; nextlen = tree[n+1].Len;
  84607. if (++count < max_count && curlen == nextlen) {
  84608. continue;
  84609. } else if (count < min_count) {
  84610. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  84611. } else if (curlen != 0) {
  84612. if (curlen != prevlen) {
  84613. send_code(s, curlen, s->bl_tree); count--;
  84614. }
  84615. Assert(count >= 3 && count <= 6, " 3_6?");
  84616. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  84617. } else if (count <= 10) {
  84618. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  84619. } else {
  84620. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  84621. }
  84622. count = 0; prevlen = curlen;
  84623. if (nextlen == 0) {
  84624. max_count = 138, min_count = 3;
  84625. } else if (curlen == nextlen) {
  84626. max_count = 6, min_count = 3;
  84627. } else {
  84628. max_count = 7, min_count = 4;
  84629. }
  84630. }
  84631. }
  84632. /* ===========================================================================
  84633. * Construct the Huffman tree for the bit lengths and return the index in
  84634. * bl_order of the last bit length code to send.
  84635. */
  84636. local int build_bl_tree (deflate_state *s)
  84637. {
  84638. int max_blindex; /* index of last bit length code of non zero freq */
  84639. /* Determine the bit length frequencies for literal and distance trees */
  84640. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  84641. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  84642. /* Build the bit length tree: */
  84643. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  84644. /* opt_len now includes the length of the tree representations, except
  84645. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  84646. */
  84647. /* Determine the number of bit length codes to send. The pkzip format
  84648. * requires that at least 4 bit length codes be sent. (appnote.txt says
  84649. * 3 but the actual value used is 4.)
  84650. */
  84651. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  84652. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  84653. }
  84654. /* Update opt_len to include the bit length tree and counts */
  84655. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  84656. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  84657. s->opt_len, s->static_len));
  84658. return max_blindex;
  84659. }
  84660. /* ===========================================================================
  84661. * Send the header for a block using dynamic Huffman trees: the counts, the
  84662. * lengths of the bit length codes, the literal tree and the distance tree.
  84663. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  84664. */
  84665. local void send_all_trees (deflate_state *s,
  84666. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  84667. {
  84668. int rank; /* index in bl_order */
  84669. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  84670. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  84671. "too many codes");
  84672. Tracev((stderr, "\nbl counts: "));
  84673. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  84674. send_bits(s, dcodes-1, 5);
  84675. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  84676. for (rank = 0; rank < blcodes; rank++) {
  84677. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  84678. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  84679. }
  84680. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  84681. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  84682. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  84683. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  84684. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  84685. }
  84686. /* ===========================================================================
  84687. * Send a stored block
  84688. */
  84689. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  84690. {
  84691. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  84692. #ifdef DEBUG
  84693. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  84694. s->compressed_len += (stored_len + 4) << 3;
  84695. #endif
  84696. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  84697. }
  84698. /* ===========================================================================
  84699. * Send one empty static block to give enough lookahead for inflate.
  84700. * This takes 10 bits, of which 7 may remain in the bit buffer.
  84701. * The current inflate code requires 9 bits of lookahead. If the
  84702. * last two codes for the previous block (real code plus EOB) were coded
  84703. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  84704. * the last real code. In this case we send two empty static blocks instead
  84705. * of one. (There are no problems if the previous block is stored or fixed.)
  84706. * To simplify the code, we assume the worst case of last real code encoded
  84707. * on one bit only.
  84708. */
  84709. void _tr_align (deflate_state *s)
  84710. {
  84711. send_bits(s, STATIC_TREES<<1, 3);
  84712. send_code(s, END_BLOCK, static_ltree);
  84713. #ifdef DEBUG
  84714. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  84715. #endif
  84716. bi_flush(s);
  84717. /* Of the 10 bits for the empty block, we have already sent
  84718. * (10 - bi_valid) bits. The lookahead for the last real code (before
  84719. * the EOB of the previous block) was thus at least one plus the length
  84720. * of the EOB plus what we have just sent of the empty static block.
  84721. */
  84722. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  84723. send_bits(s, STATIC_TREES<<1, 3);
  84724. send_code(s, END_BLOCK, static_ltree);
  84725. #ifdef DEBUG
  84726. s->compressed_len += 10L;
  84727. #endif
  84728. bi_flush(s);
  84729. }
  84730. s->last_eob_len = 7;
  84731. }
  84732. /* ===========================================================================
  84733. * Determine the best encoding for the current block: dynamic trees, static
  84734. * trees or store, and output the encoded block to the zip file.
  84735. */
  84736. void _tr_flush_block (deflate_state *s,
  84737. charf *buf, /* input block, or NULL if too old */
  84738. ulg stored_len, /* length of input block */
  84739. int eof) /* true if this is the last block for a file */
  84740. {
  84741. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  84742. int max_blindex = 0; /* index of last bit length code of non zero freq */
  84743. /* Build the Huffman trees unless a stored block is forced */
  84744. if (s->level > 0) {
  84745. /* Check if the file is binary or text */
  84746. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  84747. set_data_type(s);
  84748. /* Construct the literal and distance trees */
  84749. build_tree(s, (tree_desc *)(&(s->l_desc)));
  84750. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  84751. s->static_len));
  84752. build_tree(s, (tree_desc *)(&(s->d_desc)));
  84753. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  84754. s->static_len));
  84755. /* At this point, opt_len and static_len are the total bit lengths of
  84756. * the compressed block data, excluding the tree representations.
  84757. */
  84758. /* Build the bit length tree for the above two trees, and get the index
  84759. * in bl_order of the last bit length code to send.
  84760. */
  84761. max_blindex = build_bl_tree(s);
  84762. /* Determine the best encoding. Compute the block lengths in bytes. */
  84763. opt_lenb = (s->opt_len+3+7)>>3;
  84764. static_lenb = (s->static_len+3+7)>>3;
  84765. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  84766. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  84767. s->last_lit));
  84768. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  84769. } else {
  84770. Assert(buf != (char*)0, "lost buf");
  84771. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  84772. }
  84773. #ifdef FORCE_STORED
  84774. if (buf != (char*)0) { /* force stored block */
  84775. #else
  84776. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  84777. /* 4: two words for the lengths */
  84778. #endif
  84779. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  84780. * Otherwise we can't have processed more than WSIZE input bytes since
  84781. * the last block flush, because compression would have been
  84782. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  84783. * transform a block into a stored block.
  84784. */
  84785. _tr_stored_block(s, buf, stored_len, eof);
  84786. #ifdef FORCE_STATIC
  84787. } else if (static_lenb >= 0) { /* force static trees */
  84788. #else
  84789. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  84790. #endif
  84791. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  84792. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  84793. #ifdef DEBUG
  84794. s->compressed_len += 3 + s->static_len;
  84795. #endif
  84796. } else {
  84797. send_bits(s, (DYN_TREES<<1)+eof, 3);
  84798. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  84799. max_blindex+1);
  84800. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  84801. #ifdef DEBUG
  84802. s->compressed_len += 3 + s->opt_len;
  84803. #endif
  84804. }
  84805. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  84806. /* The above check is made mod 2^32, for files larger than 512 MB
  84807. * and uLong implemented on 32 bits.
  84808. */
  84809. init_block(s);
  84810. if (eof) {
  84811. bi_windup(s);
  84812. #ifdef DEBUG
  84813. s->compressed_len += 7; /* align on byte boundary */
  84814. #endif
  84815. }
  84816. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  84817. s->compressed_len-7*eof));
  84818. }
  84819. /* ===========================================================================
  84820. * Save the match info and tally the frequency counts. Return true if
  84821. * the current block must be flushed.
  84822. */
  84823. int _tr_tally (deflate_state *s,
  84824. unsigned dist, /* distance of matched string */
  84825. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  84826. {
  84827. s->d_buf[s->last_lit] = (ush)dist;
  84828. s->l_buf[s->last_lit++] = (uch)lc;
  84829. if (dist == 0) {
  84830. /* lc is the unmatched char */
  84831. s->dyn_ltree[lc].Freq++;
  84832. } else {
  84833. s->matches++;
  84834. /* Here, lc is the match length - MIN_MATCH */
  84835. dist--; /* dist = match distance - 1 */
  84836. Assert((ush)dist < (ush)MAX_DIST(s) &&
  84837. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  84838. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  84839. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  84840. s->dyn_dtree[d_code(dist)].Freq++;
  84841. }
  84842. #ifdef TRUNCATE_BLOCK
  84843. /* Try to guess if it is profitable to stop the current block here */
  84844. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  84845. /* Compute an upper bound for the compressed length */
  84846. ulg out_length = (ulg)s->last_lit*8L;
  84847. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  84848. int dcode;
  84849. for (dcode = 0; dcode < D_CODES; dcode++) {
  84850. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  84851. (5L+extra_dbits[dcode]);
  84852. }
  84853. out_length >>= 3;
  84854. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  84855. s->last_lit, in_length, out_length,
  84856. 100L - out_length*100L/in_length));
  84857. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  84858. }
  84859. #endif
  84860. return (s->last_lit == s->lit_bufsize-1);
  84861. /* We avoid equality with lit_bufsize because of wraparound at 64K
  84862. * on 16 bit machines and because stored blocks are restricted to
  84863. * 64K-1 bytes.
  84864. */
  84865. }
  84866. /* ===========================================================================
  84867. * Send the block data compressed using the given Huffman trees
  84868. */
  84869. local void compress_block (deflate_state *s,
  84870. ct_data *ltree, /* literal tree */
  84871. ct_data *dtree) /* distance tree */
  84872. {
  84873. unsigned dist; /* distance of matched string */
  84874. int lc; /* match length or unmatched char (if dist == 0) */
  84875. unsigned lx = 0; /* running index in l_buf */
  84876. unsigned code; /* the code to send */
  84877. int extra; /* number of extra bits to send */
  84878. if (s->last_lit != 0) do {
  84879. dist = s->d_buf[lx];
  84880. lc = s->l_buf[lx++];
  84881. if (dist == 0) {
  84882. send_code(s, lc, ltree); /* send a literal byte */
  84883. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  84884. } else {
  84885. /* Here, lc is the match length - MIN_MATCH */
  84886. code = _length_code[lc];
  84887. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  84888. extra = extra_lbits[code];
  84889. if (extra != 0) {
  84890. lc -= base_length[code];
  84891. send_bits(s, lc, extra); /* send the extra length bits */
  84892. }
  84893. dist--; /* dist is now the match distance - 1 */
  84894. code = d_code(dist);
  84895. Assert (code < D_CODES, "bad d_code");
  84896. send_code(s, code, dtree); /* send the distance code */
  84897. extra = extra_dbits[code];
  84898. if (extra != 0) {
  84899. dist -= base_dist[code];
  84900. send_bits(s, dist, extra); /* send the extra distance bits */
  84901. }
  84902. } /* literal or match pair ? */
  84903. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  84904. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  84905. "pendingBuf overflow");
  84906. } while (lx < s->last_lit);
  84907. send_code(s, END_BLOCK, ltree);
  84908. s->last_eob_len = ltree[END_BLOCK].Len;
  84909. }
  84910. /* ===========================================================================
  84911. * Set the data type to BINARY or TEXT, using a crude approximation:
  84912. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  84913. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  84914. * IN assertion: the fields Freq of dyn_ltree are set.
  84915. */
  84916. local void set_data_type (deflate_state *s)
  84917. {
  84918. int n;
  84919. for (n = 0; n < 9; n++)
  84920. if (s->dyn_ltree[n].Freq != 0)
  84921. break;
  84922. if (n == 9)
  84923. for (n = 14; n < 32; n++)
  84924. if (s->dyn_ltree[n].Freq != 0)
  84925. break;
  84926. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  84927. }
  84928. /* ===========================================================================
  84929. * Reverse the first len bits of a code, using straightforward code (a faster
  84930. * method would use a table)
  84931. * IN assertion: 1 <= len <= 15
  84932. */
  84933. local unsigned bi_reverse (unsigned code, int len)
  84934. {
  84935. register unsigned res = 0;
  84936. do {
  84937. res |= code & 1;
  84938. code >>= 1, res <<= 1;
  84939. } while (--len > 0);
  84940. return res >> 1;
  84941. }
  84942. /* ===========================================================================
  84943. * Flush the bit buffer, keeping at most 7 bits in it.
  84944. */
  84945. local void bi_flush (deflate_state *s)
  84946. {
  84947. if (s->bi_valid == 16) {
  84948. put_short(s, s->bi_buf);
  84949. s->bi_buf = 0;
  84950. s->bi_valid = 0;
  84951. } else if (s->bi_valid >= 8) {
  84952. put_byte(s, (Byte)s->bi_buf);
  84953. s->bi_buf >>= 8;
  84954. s->bi_valid -= 8;
  84955. }
  84956. }
  84957. /* ===========================================================================
  84958. * Flush the bit buffer and align the output on a byte boundary
  84959. */
  84960. local void bi_windup (deflate_state *s)
  84961. {
  84962. if (s->bi_valid > 8) {
  84963. put_short(s, s->bi_buf);
  84964. } else if (s->bi_valid > 0) {
  84965. put_byte(s, (Byte)s->bi_buf);
  84966. }
  84967. s->bi_buf = 0;
  84968. s->bi_valid = 0;
  84969. #ifdef DEBUG
  84970. s->bits_sent = (s->bits_sent+7) & ~7;
  84971. #endif
  84972. }
  84973. /* ===========================================================================
  84974. * Copy a stored block, storing first the length and its
  84975. * one's complement if requested.
  84976. */
  84977. local void copy_block(deflate_state *s,
  84978. charf *buf, /* the input data */
  84979. unsigned len, /* its length */
  84980. int header) /* true if block header must be written */
  84981. {
  84982. bi_windup(s); /* align on byte boundary */
  84983. s->last_eob_len = 8; /* enough lookahead for inflate */
  84984. if (header) {
  84985. put_short(s, (ush)len);
  84986. put_short(s, (ush)~len);
  84987. #ifdef DEBUG
  84988. s->bits_sent += 2*16;
  84989. #endif
  84990. }
  84991. #ifdef DEBUG
  84992. s->bits_sent += (ulg)len<<3;
  84993. #endif
  84994. while (len--) {
  84995. put_byte(s, *buf++);
  84996. }
  84997. }
  84998. /*** End of inlined file: trees.c ***/
  84999. /*** Start of inlined file: zutil.c ***/
  85000. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  85001. #ifndef NO_DUMMY_DECL
  85002. struct internal_state {int dummy;}; /* for buggy compilers */
  85003. #endif
  85004. const char * const z_errmsg[10] = {
  85005. "need dictionary", /* Z_NEED_DICT 2 */
  85006. "stream end", /* Z_STREAM_END 1 */
  85007. "", /* Z_OK 0 */
  85008. "file error", /* Z_ERRNO (-1) */
  85009. "stream error", /* Z_STREAM_ERROR (-2) */
  85010. "data error", /* Z_DATA_ERROR (-3) */
  85011. "insufficient memory", /* Z_MEM_ERROR (-4) */
  85012. "buffer error", /* Z_BUF_ERROR (-5) */
  85013. "incompatible version",/* Z_VERSION_ERROR (-6) */
  85014. ""};
  85015. /*const char * ZEXPORT zlibVersion()
  85016. {
  85017. return ZLIB_VERSION;
  85018. }
  85019. uLong ZEXPORT zlibCompileFlags()
  85020. {
  85021. uLong flags;
  85022. flags = 0;
  85023. switch (sizeof(uInt)) {
  85024. case 2: break;
  85025. case 4: flags += 1; break;
  85026. case 8: flags += 2; break;
  85027. default: flags += 3;
  85028. }
  85029. switch (sizeof(uLong)) {
  85030. case 2: break;
  85031. case 4: flags += 1 << 2; break;
  85032. case 8: flags += 2 << 2; break;
  85033. default: flags += 3 << 2;
  85034. }
  85035. switch (sizeof(voidpf)) {
  85036. case 2: break;
  85037. case 4: flags += 1 << 4; break;
  85038. case 8: flags += 2 << 4; break;
  85039. default: flags += 3 << 4;
  85040. }
  85041. switch (sizeof(z_off_t)) {
  85042. case 2: break;
  85043. case 4: flags += 1 << 6; break;
  85044. case 8: flags += 2 << 6; break;
  85045. default: flags += 3 << 6;
  85046. }
  85047. #ifdef DEBUG
  85048. flags += 1 << 8;
  85049. #endif
  85050. #if defined(ASMV) || defined(ASMINF)
  85051. flags += 1 << 9;
  85052. #endif
  85053. #ifdef ZLIB_WINAPI
  85054. flags += 1 << 10;
  85055. #endif
  85056. #ifdef BUILDFIXED
  85057. flags += 1 << 12;
  85058. #endif
  85059. #ifdef DYNAMIC_CRC_TABLE
  85060. flags += 1 << 13;
  85061. #endif
  85062. #ifdef NO_GZCOMPRESS
  85063. flags += 1L << 16;
  85064. #endif
  85065. #ifdef NO_GZIP
  85066. flags += 1L << 17;
  85067. #endif
  85068. #ifdef PKZIP_BUG_WORKAROUND
  85069. flags += 1L << 20;
  85070. #endif
  85071. #ifdef FASTEST
  85072. flags += 1L << 21;
  85073. #endif
  85074. #ifdef STDC
  85075. # ifdef NO_vsnprintf
  85076. flags += 1L << 25;
  85077. # ifdef HAS_vsprintf_void
  85078. flags += 1L << 26;
  85079. # endif
  85080. # else
  85081. # ifdef HAS_vsnprintf_void
  85082. flags += 1L << 26;
  85083. # endif
  85084. # endif
  85085. #else
  85086. flags += 1L << 24;
  85087. # ifdef NO_snprintf
  85088. flags += 1L << 25;
  85089. # ifdef HAS_sprintf_void
  85090. flags += 1L << 26;
  85091. # endif
  85092. # else
  85093. # ifdef HAS_snprintf_void
  85094. flags += 1L << 26;
  85095. # endif
  85096. # endif
  85097. #endif
  85098. return flags;
  85099. }*/
  85100. #ifdef DEBUG
  85101. # ifndef verbose
  85102. # define verbose 0
  85103. # endif
  85104. int z_verbose = verbose;
  85105. void z_error (const char *m)
  85106. {
  85107. fprintf(stderr, "%s\n", m);
  85108. exit(1);
  85109. }
  85110. #endif
  85111. /* exported to allow conversion of error code to string for compress() and
  85112. * uncompress()
  85113. */
  85114. const char * ZEXPORT zError(int err)
  85115. {
  85116. return ERR_MSG(err);
  85117. }
  85118. #if defined(_WIN32_WCE)
  85119. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  85120. * errno. We define it as a global variable to simplify porting.
  85121. * Its value is always 0 and should not be used.
  85122. */
  85123. int errno = 0;
  85124. #endif
  85125. #ifndef HAVE_MEMCPY
  85126. void zmemcpy(dest, source, len)
  85127. Bytef* dest;
  85128. const Bytef* source;
  85129. uInt len;
  85130. {
  85131. if (len == 0) return;
  85132. do {
  85133. *dest++ = *source++; /* ??? to be unrolled */
  85134. } while (--len != 0);
  85135. }
  85136. int zmemcmp(s1, s2, len)
  85137. const Bytef* s1;
  85138. const Bytef* s2;
  85139. uInt len;
  85140. {
  85141. uInt j;
  85142. for (j = 0; j < len; j++) {
  85143. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  85144. }
  85145. return 0;
  85146. }
  85147. void zmemzero(dest, len)
  85148. Bytef* dest;
  85149. uInt len;
  85150. {
  85151. if (len == 0) return;
  85152. do {
  85153. *dest++ = 0; /* ??? to be unrolled */
  85154. } while (--len != 0);
  85155. }
  85156. #endif
  85157. #ifdef SYS16BIT
  85158. #ifdef __TURBOC__
  85159. /* Turbo C in 16-bit mode */
  85160. # define MY_ZCALLOC
  85161. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  85162. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  85163. * must fix the pointer. Warning: the pointer must be put back to its
  85164. * original form in order to free it, use zcfree().
  85165. */
  85166. #define MAX_PTR 10
  85167. /* 10*64K = 640K */
  85168. local int next_ptr = 0;
  85169. typedef struct ptr_table_s {
  85170. voidpf org_ptr;
  85171. voidpf new_ptr;
  85172. } ptr_table;
  85173. local ptr_table table[MAX_PTR];
  85174. /* This table is used to remember the original form of pointers
  85175. * to large buffers (64K). Such pointers are normalized with a zero offset.
  85176. * Since MSDOS is not a preemptive multitasking OS, this table is not
  85177. * protected from concurrent access. This hack doesn't work anyway on
  85178. * a protected system like OS/2. Use Microsoft C instead.
  85179. */
  85180. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  85181. {
  85182. voidpf buf = opaque; /* just to make some compilers happy */
  85183. ulg bsize = (ulg)items*size;
  85184. /* If we allocate less than 65520 bytes, we assume that farmalloc
  85185. * will return a usable pointer which doesn't have to be normalized.
  85186. */
  85187. if (bsize < 65520L) {
  85188. buf = farmalloc(bsize);
  85189. if (*(ush*)&buf != 0) return buf;
  85190. } else {
  85191. buf = farmalloc(bsize + 16L);
  85192. }
  85193. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  85194. table[next_ptr].org_ptr = buf;
  85195. /* Normalize the pointer to seg:0 */
  85196. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  85197. *(ush*)&buf = 0;
  85198. table[next_ptr++].new_ptr = buf;
  85199. return buf;
  85200. }
  85201. void zcfree (voidpf opaque, voidpf ptr)
  85202. {
  85203. int n;
  85204. if (*(ush*)&ptr != 0) { /* object < 64K */
  85205. farfree(ptr);
  85206. return;
  85207. }
  85208. /* Find the original pointer */
  85209. for (n = 0; n < next_ptr; n++) {
  85210. if (ptr != table[n].new_ptr) continue;
  85211. farfree(table[n].org_ptr);
  85212. while (++n < next_ptr) {
  85213. table[n-1] = table[n];
  85214. }
  85215. next_ptr--;
  85216. return;
  85217. }
  85218. ptr = opaque; /* just to make some compilers happy */
  85219. Assert(0, "zcfree: ptr not found");
  85220. }
  85221. #endif /* __TURBOC__ */
  85222. #ifdef M_I86
  85223. /* Microsoft C in 16-bit mode */
  85224. # define MY_ZCALLOC
  85225. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  85226. # define _halloc halloc
  85227. # define _hfree hfree
  85228. #endif
  85229. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  85230. {
  85231. if (opaque) opaque = 0; /* to make compiler happy */
  85232. return _halloc((long)items, size);
  85233. }
  85234. void zcfree (voidpf opaque, voidpf ptr)
  85235. {
  85236. if (opaque) opaque = 0; /* to make compiler happy */
  85237. _hfree(ptr);
  85238. }
  85239. #endif /* M_I86 */
  85240. #endif /* SYS16BIT */
  85241. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  85242. #ifndef STDC
  85243. extern voidp malloc OF((uInt size));
  85244. extern voidp calloc OF((uInt items, uInt size));
  85245. extern void free OF((voidpf ptr));
  85246. #endif
  85247. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  85248. {
  85249. if (opaque) items += size - size; /* make compiler happy */
  85250. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  85251. (voidpf)calloc(items, size);
  85252. }
  85253. void zcfree (voidpf opaque, voidpf ptr)
  85254. {
  85255. free(ptr);
  85256. if (opaque) return; /* make compiler happy */
  85257. }
  85258. #endif /* MY_ZCALLOC */
  85259. /*** End of inlined file: zutil.c ***/
  85260. #undef Byte
  85261. }
  85262. #else
  85263. #include <zlib.h>
  85264. #endif
  85265. }
  85266. #if JUCE_MSVC
  85267. #pragma warning (pop)
  85268. #endif
  85269. BEGIN_JUCE_NAMESPACE
  85270. // internal helper object that holds the zlib structures so they don't have to be
  85271. // included publicly.
  85272. class GZIPDecompressHelper
  85273. {
  85274. public:
  85275. GZIPDecompressHelper (const bool noWrap)
  85276. : finished (true),
  85277. needsDictionary (false),
  85278. error (true),
  85279. streamIsValid (false),
  85280. data (0),
  85281. dataSize (0)
  85282. {
  85283. using namespace zlibNamespace;
  85284. zerostruct (stream);
  85285. streamIsValid = (inflateInit2 (&stream, noWrap ? -MAX_WBITS : MAX_WBITS) == Z_OK);
  85286. finished = error = ! streamIsValid;
  85287. }
  85288. ~GZIPDecompressHelper()
  85289. {
  85290. using namespace zlibNamespace;
  85291. if (streamIsValid)
  85292. inflateEnd (&stream);
  85293. }
  85294. bool needsInput() const throw() { return dataSize <= 0; }
  85295. void setInput (uint8* const data_, const int size) throw()
  85296. {
  85297. data = data_;
  85298. dataSize = size;
  85299. }
  85300. int doNextBlock (uint8* const dest, const int destSize)
  85301. {
  85302. using namespace zlibNamespace;
  85303. if (streamIsValid && data != 0 && ! finished)
  85304. {
  85305. stream.next_in = data;
  85306. stream.next_out = dest;
  85307. stream.avail_in = dataSize;
  85308. stream.avail_out = destSize;
  85309. switch (inflate (&stream, Z_PARTIAL_FLUSH))
  85310. {
  85311. case Z_STREAM_END:
  85312. finished = true;
  85313. // deliberate fall-through
  85314. case Z_OK:
  85315. data += dataSize - stream.avail_in;
  85316. dataSize = stream.avail_in;
  85317. return destSize - stream.avail_out;
  85318. case Z_NEED_DICT:
  85319. needsDictionary = true;
  85320. data += dataSize - stream.avail_in;
  85321. dataSize = stream.avail_in;
  85322. break;
  85323. case Z_DATA_ERROR:
  85324. case Z_MEM_ERROR:
  85325. error = true;
  85326. default:
  85327. break;
  85328. }
  85329. }
  85330. return 0;
  85331. }
  85332. bool finished, needsDictionary, error, streamIsValid;
  85333. private:
  85334. zlibNamespace::z_stream stream;
  85335. uint8* data;
  85336. int dataSize;
  85337. GZIPDecompressHelper (const GZIPDecompressHelper&);
  85338. GZIPDecompressHelper& operator= (const GZIPDecompressHelper&);
  85339. };
  85340. const int gzipDecompBufferSize = 32768;
  85341. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  85342. const bool deleteSourceWhenDestroyed,
  85343. const bool noWrap_,
  85344. const int64 uncompressedStreamLength_)
  85345. : sourceStream (sourceStream_),
  85346. streamToDelete (deleteSourceWhenDestroyed ? sourceStream_ : 0),
  85347. uncompressedStreamLength (uncompressedStreamLength_),
  85348. noWrap (noWrap_),
  85349. isEof (false),
  85350. activeBufferSize (0),
  85351. originalSourcePos (sourceStream_->getPosition()),
  85352. currentPos (0),
  85353. buffer (gzipDecompBufferSize),
  85354. helper (new GZIPDecompressHelper (noWrap_))
  85355. {
  85356. }
  85357. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  85358. {
  85359. }
  85360. int64 GZIPDecompressorInputStream::getTotalLength()
  85361. {
  85362. return uncompressedStreamLength;
  85363. }
  85364. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  85365. {
  85366. if ((howMany > 0) && ! isEof)
  85367. {
  85368. jassert (destBuffer != 0);
  85369. if (destBuffer != 0)
  85370. {
  85371. int numRead = 0;
  85372. uint8* d = static_cast <uint8*> (destBuffer);
  85373. while (! helper->error)
  85374. {
  85375. const int n = helper->doNextBlock (d, howMany);
  85376. currentPos += n;
  85377. if (n == 0)
  85378. {
  85379. if (helper->finished || helper->needsDictionary)
  85380. {
  85381. isEof = true;
  85382. return numRead;
  85383. }
  85384. if (helper->needsInput())
  85385. {
  85386. activeBufferSize = sourceStream->read (buffer, gzipDecompBufferSize);
  85387. if (activeBufferSize > 0)
  85388. {
  85389. helper->setInput (buffer, activeBufferSize);
  85390. }
  85391. else
  85392. {
  85393. isEof = true;
  85394. return numRead;
  85395. }
  85396. }
  85397. }
  85398. else
  85399. {
  85400. numRead += n;
  85401. howMany -= n;
  85402. d += n;
  85403. if (howMany <= 0)
  85404. return numRead;
  85405. }
  85406. }
  85407. }
  85408. }
  85409. return 0;
  85410. }
  85411. bool GZIPDecompressorInputStream::isExhausted()
  85412. {
  85413. return helper->error || isEof;
  85414. }
  85415. int64 GZIPDecompressorInputStream::getPosition()
  85416. {
  85417. return currentPos;
  85418. }
  85419. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  85420. {
  85421. if (newPos < currentPos)
  85422. {
  85423. // to go backwards, reset the stream and start again..
  85424. isEof = false;
  85425. activeBufferSize = 0;
  85426. currentPos = 0;
  85427. helper = new GZIPDecompressHelper (noWrap);
  85428. sourceStream->setPosition (originalSourcePos);
  85429. }
  85430. skipNextBytes (newPos - currentPos);
  85431. return true;
  85432. }
  85433. END_JUCE_NAMESPACE
  85434. /*** End of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  85435. #endif
  85436. #if JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  85437. /*** Start of inlined file: juce_FlacAudioFormat.cpp ***/
  85438. #if JUCE_USE_FLAC
  85439. #if JUCE_WINDOWS
  85440. #include <windows.h>
  85441. #endif
  85442. namespace FlacNamespace
  85443. {
  85444. #if JUCE_INCLUDE_FLAC_CODE
  85445. #if JUCE_MSVC
  85446. #pragma warning (disable : 4505) // (unreferenced static function removal warning)
  85447. #endif
  85448. #define FLAC__NO_DLL 1
  85449. #if ! defined (SIZE_MAX)
  85450. #define SIZE_MAX 0xffffffff
  85451. #endif
  85452. #define __STDC_LIMIT_MACROS 1
  85453. /*** Start of inlined file: all.h ***/
  85454. #ifndef FLAC__ALL_H
  85455. #define FLAC__ALL_H
  85456. /*** Start of inlined file: export.h ***/
  85457. #ifndef FLAC__EXPORT_H
  85458. #define FLAC__EXPORT_H
  85459. /** \file include/FLAC/export.h
  85460. *
  85461. * \brief
  85462. * This module contains #defines and symbols for exporting function
  85463. * calls, and providing version information and compiled-in features.
  85464. *
  85465. * See the \link flac_export export \endlink module.
  85466. */
  85467. /** \defgroup flac_export FLAC/export.h: export symbols
  85468. * \ingroup flac
  85469. *
  85470. * \brief
  85471. * This module contains #defines and symbols for exporting function
  85472. * calls, and providing version information and compiled-in features.
  85473. *
  85474. * If you are compiling with MSVC and will link to the static library
  85475. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  85476. * make sure the symbols are exported properly.
  85477. *
  85478. * \{
  85479. */
  85480. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  85481. #define FLAC_API
  85482. #else
  85483. #ifdef FLAC_API_EXPORTS
  85484. #define FLAC_API _declspec(dllexport)
  85485. #else
  85486. #define FLAC_API _declspec(dllimport)
  85487. #endif
  85488. #endif
  85489. /** These #defines will mirror the libtool-based library version number, see
  85490. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  85491. */
  85492. #define FLAC_API_VERSION_CURRENT 10
  85493. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  85494. #define FLAC_API_VERSION_AGE 2 /**< see above */
  85495. #ifdef __cplusplus
  85496. extern "C" {
  85497. #endif
  85498. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  85499. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  85500. #ifdef __cplusplus
  85501. }
  85502. #endif
  85503. /* \} */
  85504. #endif
  85505. /*** End of inlined file: export.h ***/
  85506. /*** Start of inlined file: assert.h ***/
  85507. #ifndef FLAC__ASSERT_H
  85508. #define FLAC__ASSERT_H
  85509. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  85510. #ifdef DEBUG
  85511. #include <assert.h>
  85512. #define FLAC__ASSERT(x) assert(x)
  85513. #define FLAC__ASSERT_DECLARATION(x) x
  85514. #else
  85515. #define FLAC__ASSERT(x)
  85516. #define FLAC__ASSERT_DECLARATION(x)
  85517. #endif
  85518. #endif
  85519. /*** End of inlined file: assert.h ***/
  85520. /*** Start of inlined file: callback.h ***/
  85521. #ifndef FLAC__CALLBACK_H
  85522. #define FLAC__CALLBACK_H
  85523. /*** Start of inlined file: ordinals.h ***/
  85524. #ifndef FLAC__ORDINALS_H
  85525. #define FLAC__ORDINALS_H
  85526. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  85527. #include <inttypes.h>
  85528. #endif
  85529. typedef signed char FLAC__int8;
  85530. typedef unsigned char FLAC__uint8;
  85531. #if defined(_MSC_VER) || defined(__BORLANDC__)
  85532. typedef __int16 FLAC__int16;
  85533. typedef __int32 FLAC__int32;
  85534. typedef __int64 FLAC__int64;
  85535. typedef unsigned __int16 FLAC__uint16;
  85536. typedef unsigned __int32 FLAC__uint32;
  85537. typedef unsigned __int64 FLAC__uint64;
  85538. #elif defined(__EMX__)
  85539. typedef short FLAC__int16;
  85540. typedef long FLAC__int32;
  85541. typedef long long FLAC__int64;
  85542. typedef unsigned short FLAC__uint16;
  85543. typedef unsigned long FLAC__uint32;
  85544. typedef unsigned long long FLAC__uint64;
  85545. #else
  85546. typedef int16_t FLAC__int16;
  85547. typedef int32_t FLAC__int32;
  85548. typedef int64_t FLAC__int64;
  85549. typedef uint16_t FLAC__uint16;
  85550. typedef uint32_t FLAC__uint32;
  85551. typedef uint64_t FLAC__uint64;
  85552. #endif
  85553. typedef int FLAC__bool;
  85554. typedef FLAC__uint8 FLAC__byte;
  85555. #ifdef true
  85556. #undef true
  85557. #endif
  85558. #ifdef false
  85559. #undef false
  85560. #endif
  85561. #ifndef __cplusplus
  85562. #define true 1
  85563. #define false 0
  85564. #endif
  85565. #endif
  85566. /*** End of inlined file: ordinals.h ***/
  85567. #include <stdlib.h> /* for size_t */
  85568. /** \file include/FLAC/callback.h
  85569. *
  85570. * \brief
  85571. * This module defines the structures for describing I/O callbacks
  85572. * to the other FLAC interfaces.
  85573. *
  85574. * See the detailed documentation for callbacks in the
  85575. * \link flac_callbacks callbacks \endlink module.
  85576. */
  85577. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  85578. * \ingroup flac
  85579. *
  85580. * \brief
  85581. * This module defines the structures for describing I/O callbacks
  85582. * to the other FLAC interfaces.
  85583. *
  85584. * The purpose of the I/O callback functions is to create a common way
  85585. * for the metadata interfaces to handle I/O.
  85586. *
  85587. * Originally the metadata interfaces required filenames as the way of
  85588. * specifying FLAC files to operate on. This is problematic in some
  85589. * environments so there is an additional option to specify a set of
  85590. * callbacks for doing I/O on the FLAC file, instead of the filename.
  85591. *
  85592. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  85593. * opaque structure for a data source.
  85594. *
  85595. * The callback function prototypes are similar (but not identical) to the
  85596. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  85597. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  85598. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  85599. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  85600. * is required. \warning You generally CANNOT directly use fseek or ftell
  85601. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  85602. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  85603. * large files. You will have to find an equivalent function (e.g. ftello),
  85604. * or write a wrapper. The same is true for feof() since this is usually
  85605. * implemented as a macro, not as a function whose address can be taken.
  85606. *
  85607. * \{
  85608. */
  85609. #ifdef __cplusplus
  85610. extern "C" {
  85611. #endif
  85612. /** This is the opaque handle type used by the callbacks. Typically
  85613. * this is a \c FILE* or address of a file descriptor.
  85614. */
  85615. typedef void* FLAC__IOHandle;
  85616. /** Signature for the read callback.
  85617. * The signature and semantics match POSIX fread() implementations
  85618. * and can generally be used interchangeably.
  85619. *
  85620. * \param ptr The address of the read buffer.
  85621. * \param size The size of the records to be read.
  85622. * \param nmemb The number of records to be read.
  85623. * \param handle The handle to the data source.
  85624. * \retval size_t
  85625. * The number of records read.
  85626. */
  85627. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  85628. /** Signature for the write callback.
  85629. * The signature and semantics match POSIX fwrite() implementations
  85630. * and can generally be used interchangeably.
  85631. *
  85632. * \param ptr The address of the write buffer.
  85633. * \param size The size of the records to be written.
  85634. * \param nmemb The number of records to be written.
  85635. * \param handle The handle to the data source.
  85636. * \retval size_t
  85637. * The number of records written.
  85638. */
  85639. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  85640. /** Signature for the seek callback.
  85641. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  85642. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  85643. * and 32-bits wide.
  85644. *
  85645. * \param handle The handle to the data source.
  85646. * \param offset The new position, relative to \a whence
  85647. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  85648. * \retval int
  85649. * \c 0 on success, \c -1 on error.
  85650. */
  85651. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  85652. /** Signature for the tell callback.
  85653. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  85654. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  85655. * and 32-bits wide.
  85656. *
  85657. * \param handle The handle to the data source.
  85658. * \retval FLAC__int64
  85659. * The current position on success, \c -1 on error.
  85660. */
  85661. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  85662. /** Signature for the EOF callback.
  85663. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  85664. * on many systems, feof() is a macro, so in this case a wrapper function
  85665. * must be provided instead.
  85666. *
  85667. * \param handle The handle to the data source.
  85668. * \retval int
  85669. * \c 0 if not at end of file, nonzero if at end of file.
  85670. */
  85671. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  85672. /** Signature for the close callback.
  85673. * The signature and semantics match POSIX fclose() implementations
  85674. * and can generally be used interchangeably.
  85675. *
  85676. * \param handle The handle to the data source.
  85677. * \retval int
  85678. * \c 0 on success, \c EOF on error.
  85679. */
  85680. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  85681. /** A structure for holding a set of callbacks.
  85682. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  85683. * describe which of the callbacks are required. The ones that are not
  85684. * required may be set to NULL.
  85685. *
  85686. * If the seek requirement for an interface is optional, you can signify that
  85687. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  85688. */
  85689. typedef struct {
  85690. FLAC__IOCallback_Read read;
  85691. FLAC__IOCallback_Write write;
  85692. FLAC__IOCallback_Seek seek;
  85693. FLAC__IOCallback_Tell tell;
  85694. FLAC__IOCallback_Eof eof;
  85695. FLAC__IOCallback_Close close;
  85696. } FLAC__IOCallbacks;
  85697. /* \} */
  85698. #ifdef __cplusplus
  85699. }
  85700. #endif
  85701. #endif
  85702. /*** End of inlined file: callback.h ***/
  85703. /*** Start of inlined file: format.h ***/
  85704. #ifndef FLAC__FORMAT_H
  85705. #define FLAC__FORMAT_H
  85706. #ifdef __cplusplus
  85707. extern "C" {
  85708. #endif
  85709. /** \file include/FLAC/format.h
  85710. *
  85711. * \brief
  85712. * This module contains structure definitions for the representation
  85713. * of FLAC format components in memory. These are the basic
  85714. * structures used by the rest of the interfaces.
  85715. *
  85716. * See the detailed documentation in the
  85717. * \link flac_format format \endlink module.
  85718. */
  85719. /** \defgroup flac_format FLAC/format.h: format components
  85720. * \ingroup flac
  85721. *
  85722. * \brief
  85723. * This module contains structure definitions for the representation
  85724. * of FLAC format components in memory. These are the basic
  85725. * structures used by the rest of the interfaces.
  85726. *
  85727. * First, you should be familiar with the
  85728. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  85729. * follow directly from the specification. As a user of libFLAC, the
  85730. * interesting parts really are the structures that describe the frame
  85731. * header and metadata blocks.
  85732. *
  85733. * The format structures here are very primitive, designed to store
  85734. * information in an efficient way. Reading information from the
  85735. * structures is easy but creating or modifying them directly is
  85736. * more complex. For the most part, as a user of a library, editing
  85737. * is not necessary; however, for metadata blocks it is, so there are
  85738. * convenience functions provided in the \link flac_metadata metadata
  85739. * module \endlink to simplify the manipulation of metadata blocks.
  85740. *
  85741. * \note
  85742. * It's not the best convention, but symbols ending in _LEN are in bits
  85743. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  85744. * global variables because they are usually used when declaring byte
  85745. * arrays and some compilers require compile-time knowledge of array
  85746. * sizes when declared on the stack.
  85747. *
  85748. * \{
  85749. */
  85750. /*
  85751. Most of the values described in this file are defined by the FLAC
  85752. format specification. There is nothing to tune here.
  85753. */
  85754. /** The largest legal metadata type code. */
  85755. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  85756. /** The minimum block size, in samples, permitted by the format. */
  85757. #define FLAC__MIN_BLOCK_SIZE (16u)
  85758. /** The maximum block size, in samples, permitted by the format. */
  85759. #define FLAC__MAX_BLOCK_SIZE (65535u)
  85760. /** The maximum block size, in samples, permitted by the FLAC subset for
  85761. * sample rates up to 48kHz. */
  85762. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  85763. /** The maximum number of channels permitted by the format. */
  85764. #define FLAC__MAX_CHANNELS (8u)
  85765. /** The minimum sample resolution permitted by the format. */
  85766. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  85767. /** The maximum sample resolution permitted by the format. */
  85768. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  85769. /** The maximum sample resolution permitted by libFLAC.
  85770. *
  85771. * \warning
  85772. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  85773. * the reference encoder/decoder is currently limited to 24 bits because
  85774. * of prevalent 32-bit math, so make sure and use this value when
  85775. * appropriate.
  85776. */
  85777. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  85778. /** The maximum sample rate permitted by the format. The value is
  85779. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  85780. * as to why.
  85781. */
  85782. #define FLAC__MAX_SAMPLE_RATE (655350u)
  85783. /** The maximum LPC order permitted by the format. */
  85784. #define FLAC__MAX_LPC_ORDER (32u)
  85785. /** The maximum LPC order permitted by the FLAC subset for sample rates
  85786. * up to 48kHz. */
  85787. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  85788. /** The minimum quantized linear predictor coefficient precision
  85789. * permitted by the format.
  85790. */
  85791. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  85792. /** The maximum quantized linear predictor coefficient precision
  85793. * permitted by the format.
  85794. */
  85795. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  85796. /** The maximum order of the fixed predictors permitted by the format. */
  85797. #define FLAC__MAX_FIXED_ORDER (4u)
  85798. /** The maximum Rice partition order permitted by the format. */
  85799. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  85800. /** The maximum Rice partition order permitted by the FLAC Subset. */
  85801. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  85802. /** The version string of the release, stamped onto the libraries and binaries.
  85803. *
  85804. * \note
  85805. * This does not correspond to the shared library version number, which
  85806. * is used to determine binary compatibility.
  85807. */
  85808. extern FLAC_API const char *FLAC__VERSION_STRING;
  85809. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  85810. * This is a NUL-terminated ASCII string; when inserted into the
  85811. * VORBIS_COMMENT the trailing null is stripped.
  85812. */
  85813. extern FLAC_API const char *FLAC__VENDOR_STRING;
  85814. /** The byte string representation of the beginning of a FLAC stream. */
  85815. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  85816. /** The 32-bit integer big-endian representation of the beginning of
  85817. * a FLAC stream.
  85818. */
  85819. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  85820. /** The length of the FLAC signature in bits. */
  85821. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  85822. /** The length of the FLAC signature in bytes. */
  85823. #define FLAC__STREAM_SYNC_LENGTH (4u)
  85824. /*****************************************************************************
  85825. *
  85826. * Subframe structures
  85827. *
  85828. *****************************************************************************/
  85829. /*****************************************************************************/
  85830. /** An enumeration of the available entropy coding methods. */
  85831. typedef enum {
  85832. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  85833. /**< Residual is coded by partitioning into contexts, each with it's own
  85834. * 4-bit Rice parameter. */
  85835. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  85836. /**< Residual is coded by partitioning into contexts, each with it's own
  85837. * 5-bit Rice parameter. */
  85838. } FLAC__EntropyCodingMethodType;
  85839. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  85840. *
  85841. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  85842. * give the string equivalent. The contents should not be modified.
  85843. */
  85844. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  85845. /** Contents of a Rice partitioned residual
  85846. */
  85847. typedef struct {
  85848. unsigned *parameters;
  85849. /**< The Rice parameters for each context. */
  85850. unsigned *raw_bits;
  85851. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  85852. * partitions and zero for unescaped partitions.
  85853. */
  85854. unsigned capacity_by_order;
  85855. /**< The capacity of the \a parameters and \a raw_bits arrays
  85856. * specified as an order, i.e. the number of array elements
  85857. * allocated is 2 ^ \a capacity_by_order.
  85858. */
  85859. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  85860. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  85861. */
  85862. typedef struct {
  85863. unsigned order;
  85864. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  85865. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  85866. /**< The context's Rice parameters and/or raw bits. */
  85867. } FLAC__EntropyCodingMethod_PartitionedRice;
  85868. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  85869. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  85870. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  85871. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  85872. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  85873. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  85874. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  85875. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  85876. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  85877. */
  85878. typedef struct {
  85879. FLAC__EntropyCodingMethodType type;
  85880. union {
  85881. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  85882. } data;
  85883. } FLAC__EntropyCodingMethod;
  85884. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  85885. /*****************************************************************************/
  85886. /** An enumeration of the available subframe types. */
  85887. typedef enum {
  85888. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  85889. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  85890. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  85891. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  85892. } FLAC__SubframeType;
  85893. /** Maps a FLAC__SubframeType to a C string.
  85894. *
  85895. * Using a FLAC__SubframeType as the index to this array will
  85896. * give the string equivalent. The contents should not be modified.
  85897. */
  85898. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  85899. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  85900. */
  85901. typedef struct {
  85902. FLAC__int32 value; /**< The constant signal value. */
  85903. } FLAC__Subframe_Constant;
  85904. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  85905. */
  85906. typedef struct {
  85907. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  85908. } FLAC__Subframe_Verbatim;
  85909. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  85910. */
  85911. typedef struct {
  85912. FLAC__EntropyCodingMethod entropy_coding_method;
  85913. /**< The residual coding method. */
  85914. unsigned order;
  85915. /**< The polynomial order. */
  85916. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  85917. /**< Warmup samples to prime the predictor, length == order. */
  85918. const FLAC__int32 *residual;
  85919. /**< The residual signal, length == (blocksize minus order) samples. */
  85920. } FLAC__Subframe_Fixed;
  85921. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  85922. */
  85923. typedef struct {
  85924. FLAC__EntropyCodingMethod entropy_coding_method;
  85925. /**< The residual coding method. */
  85926. unsigned order;
  85927. /**< The FIR order. */
  85928. unsigned qlp_coeff_precision;
  85929. /**< Quantized FIR filter coefficient precision in bits. */
  85930. int quantization_level;
  85931. /**< The qlp coeff shift needed. */
  85932. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  85933. /**< FIR filter coefficients. */
  85934. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  85935. /**< Warmup samples to prime the predictor, length == order. */
  85936. const FLAC__int32 *residual;
  85937. /**< The residual signal, length == (blocksize minus order) samples. */
  85938. } FLAC__Subframe_LPC;
  85939. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  85940. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  85941. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  85942. */
  85943. typedef struct {
  85944. FLAC__SubframeType type;
  85945. union {
  85946. FLAC__Subframe_Constant constant;
  85947. FLAC__Subframe_Fixed fixed;
  85948. FLAC__Subframe_LPC lpc;
  85949. FLAC__Subframe_Verbatim verbatim;
  85950. } data;
  85951. unsigned wasted_bits;
  85952. } FLAC__Subframe;
  85953. /** == 1 (bit)
  85954. *
  85955. * This used to be a zero-padding bit (hence the name
  85956. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  85957. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  85958. * to mean something else.
  85959. */
  85960. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  85961. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  85962. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  85963. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  85964. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  85965. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  85966. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  85967. /*****************************************************************************/
  85968. /*****************************************************************************
  85969. *
  85970. * Frame structures
  85971. *
  85972. *****************************************************************************/
  85973. /** An enumeration of the available channel assignments. */
  85974. typedef enum {
  85975. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  85976. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  85977. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  85978. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  85979. } FLAC__ChannelAssignment;
  85980. /** Maps a FLAC__ChannelAssignment to a C string.
  85981. *
  85982. * Using a FLAC__ChannelAssignment as the index to this array will
  85983. * give the string equivalent. The contents should not be modified.
  85984. */
  85985. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  85986. /** An enumeration of the possible frame numbering methods. */
  85987. typedef enum {
  85988. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  85989. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  85990. } FLAC__FrameNumberType;
  85991. /** Maps a FLAC__FrameNumberType to a C string.
  85992. *
  85993. * Using a FLAC__FrameNumberType as the index to this array will
  85994. * give the string equivalent. The contents should not be modified.
  85995. */
  85996. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  85997. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  85998. */
  85999. typedef struct {
  86000. unsigned blocksize;
  86001. /**< The number of samples per subframe. */
  86002. unsigned sample_rate;
  86003. /**< The sample rate in Hz. */
  86004. unsigned channels;
  86005. /**< The number of channels (== number of subframes). */
  86006. FLAC__ChannelAssignment channel_assignment;
  86007. /**< The channel assignment for the frame. */
  86008. unsigned bits_per_sample;
  86009. /**< The sample resolution. */
  86010. FLAC__FrameNumberType number_type;
  86011. /**< The numbering scheme used for the frame. As a convenience, the
  86012. * decoder will always convert a frame number to a sample number because
  86013. * the rules are complex. */
  86014. union {
  86015. FLAC__uint32 frame_number;
  86016. FLAC__uint64 sample_number;
  86017. } number;
  86018. /**< The frame number or sample number of first sample in frame;
  86019. * use the \a number_type value to determine which to use. */
  86020. FLAC__uint8 crc;
  86021. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  86022. * of the raw frame header bytes, meaning everything before the CRC byte
  86023. * including the sync code.
  86024. */
  86025. } FLAC__FrameHeader;
  86026. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  86027. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  86028. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  86029. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  86030. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  86031. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  86032. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  86033. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  86034. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  86035. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  86036. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  86037. */
  86038. typedef struct {
  86039. FLAC__uint16 crc;
  86040. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  86041. * 0) of the bytes before the crc, back to and including the frame header
  86042. * sync code.
  86043. */
  86044. } FLAC__FrameFooter;
  86045. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  86046. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  86047. */
  86048. typedef struct {
  86049. FLAC__FrameHeader header;
  86050. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  86051. FLAC__FrameFooter footer;
  86052. } FLAC__Frame;
  86053. /*****************************************************************************/
  86054. /*****************************************************************************
  86055. *
  86056. * Meta-data structures
  86057. *
  86058. *****************************************************************************/
  86059. /** An enumeration of the available metadata block types. */
  86060. typedef enum {
  86061. FLAC__METADATA_TYPE_STREAMINFO = 0,
  86062. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  86063. FLAC__METADATA_TYPE_PADDING = 1,
  86064. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  86065. FLAC__METADATA_TYPE_APPLICATION = 2,
  86066. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  86067. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  86068. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  86069. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  86070. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  86071. FLAC__METADATA_TYPE_CUESHEET = 5,
  86072. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  86073. FLAC__METADATA_TYPE_PICTURE = 6,
  86074. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  86075. FLAC__METADATA_TYPE_UNDEFINED = 7
  86076. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  86077. } FLAC__MetadataType;
  86078. /** Maps a FLAC__MetadataType to a C string.
  86079. *
  86080. * Using a FLAC__MetadataType as the index to this array will
  86081. * give the string equivalent. The contents should not be modified.
  86082. */
  86083. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  86084. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  86085. */
  86086. typedef struct {
  86087. unsigned min_blocksize, max_blocksize;
  86088. unsigned min_framesize, max_framesize;
  86089. unsigned sample_rate;
  86090. unsigned channels;
  86091. unsigned bits_per_sample;
  86092. FLAC__uint64 total_samples;
  86093. FLAC__byte md5sum[16];
  86094. } FLAC__StreamMetadata_StreamInfo;
  86095. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  86096. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  86097. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  86098. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  86099. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  86100. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  86101. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  86102. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  86103. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  86104. /** The total stream length of the STREAMINFO block in bytes. */
  86105. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  86106. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  86107. */
  86108. typedef struct {
  86109. int dummy;
  86110. /**< Conceptually this is an empty struct since we don't store the
  86111. * padding bytes. Empty structs are not allowed by some C compilers,
  86112. * hence the dummy.
  86113. */
  86114. } FLAC__StreamMetadata_Padding;
  86115. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  86116. */
  86117. typedef struct {
  86118. FLAC__byte id[4];
  86119. FLAC__byte *data;
  86120. } FLAC__StreamMetadata_Application;
  86121. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  86122. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  86123. */
  86124. typedef struct {
  86125. FLAC__uint64 sample_number;
  86126. /**< The sample number of the target frame. */
  86127. FLAC__uint64 stream_offset;
  86128. /**< The offset, in bytes, of the target frame with respect to
  86129. * beginning of the first frame. */
  86130. unsigned frame_samples;
  86131. /**< The number of samples in the target frame. */
  86132. } FLAC__StreamMetadata_SeekPoint;
  86133. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  86134. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  86135. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  86136. /** The total stream length of a seek point in bytes. */
  86137. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  86138. /** The value used in the \a sample_number field of
  86139. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  86140. * point (== 0xffffffffffffffff).
  86141. */
  86142. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  86143. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  86144. *
  86145. * \note From the format specification:
  86146. * - The seek points must be sorted by ascending sample number.
  86147. * - Each seek point's sample number must be the first sample of the
  86148. * target frame.
  86149. * - Each seek point's sample number must be unique within the table.
  86150. * - Existence of a SEEKTABLE block implies a correct setting of
  86151. * total_samples in the stream_info block.
  86152. * - Behavior is undefined when more than one SEEKTABLE block is
  86153. * present in a stream.
  86154. */
  86155. typedef struct {
  86156. unsigned num_points;
  86157. FLAC__StreamMetadata_SeekPoint *points;
  86158. } FLAC__StreamMetadata_SeekTable;
  86159. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  86160. *
  86161. * For convenience, the APIs maintain a trailing NUL character at the end of
  86162. * \a entry which is not counted toward \a length, i.e.
  86163. * \code strlen(entry) == length \endcode
  86164. */
  86165. typedef struct {
  86166. FLAC__uint32 length;
  86167. FLAC__byte *entry;
  86168. } FLAC__StreamMetadata_VorbisComment_Entry;
  86169. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  86170. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  86171. */
  86172. typedef struct {
  86173. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  86174. FLAC__uint32 num_comments;
  86175. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  86176. } FLAC__StreamMetadata_VorbisComment;
  86177. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  86178. /** FLAC CUESHEET track index structure. (See the
  86179. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  86180. * the full description of each field.)
  86181. */
  86182. typedef struct {
  86183. FLAC__uint64 offset;
  86184. /**< Offset in samples, relative to the track offset, of the index
  86185. * point.
  86186. */
  86187. FLAC__byte number;
  86188. /**< The index point number. */
  86189. } FLAC__StreamMetadata_CueSheet_Index;
  86190. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  86191. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  86192. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  86193. /** FLAC CUESHEET track structure. (See the
  86194. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  86195. * the full description of each field.)
  86196. */
  86197. typedef struct {
  86198. FLAC__uint64 offset;
  86199. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  86200. FLAC__byte number;
  86201. /**< The track number. */
  86202. char isrc[13];
  86203. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  86204. unsigned type:1;
  86205. /**< The track type: 0 for audio, 1 for non-audio. */
  86206. unsigned pre_emphasis:1;
  86207. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  86208. FLAC__byte num_indices;
  86209. /**< The number of track index points. */
  86210. FLAC__StreamMetadata_CueSheet_Index *indices;
  86211. /**< NULL if num_indices == 0, else pointer to array of index points. */
  86212. } FLAC__StreamMetadata_CueSheet_Track;
  86213. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  86214. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  86215. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  86216. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  86217. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  86218. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  86219. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  86220. /** FLAC CUESHEET structure. (See the
  86221. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  86222. * for the full description of each field.)
  86223. */
  86224. typedef struct {
  86225. char media_catalog_number[129];
  86226. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  86227. * general, the media catalog number may be 0 to 128 bytes long; any
  86228. * unused characters should be right-padded with NUL characters.
  86229. */
  86230. FLAC__uint64 lead_in;
  86231. /**< The number of lead-in samples. */
  86232. FLAC__bool is_cd;
  86233. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  86234. unsigned num_tracks;
  86235. /**< The number of tracks. */
  86236. FLAC__StreamMetadata_CueSheet_Track *tracks;
  86237. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  86238. } FLAC__StreamMetadata_CueSheet;
  86239. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  86240. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  86241. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  86242. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  86243. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  86244. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  86245. typedef enum {
  86246. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  86247. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  86248. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  86249. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  86250. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  86251. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  86252. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  86253. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  86254. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  86255. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  86256. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  86257. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  86258. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  86259. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  86260. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  86261. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  86262. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  86263. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  86264. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  86265. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  86266. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  86267. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  86268. } FLAC__StreamMetadata_Picture_Type;
  86269. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  86270. *
  86271. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  86272. * will give the string equivalent. The contents should not be
  86273. * modified.
  86274. */
  86275. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  86276. /** FLAC PICTURE structure. (See the
  86277. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  86278. * for the full description of each field.)
  86279. */
  86280. typedef struct {
  86281. FLAC__StreamMetadata_Picture_Type type;
  86282. /**< The kind of picture stored. */
  86283. char *mime_type;
  86284. /**< Picture data's MIME type, in ASCII printable characters
  86285. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  86286. * use picture data of MIME type \c image/jpeg or \c image/png. A
  86287. * MIME type of '-->' is also allowed, in which case the picture
  86288. * data should be a complete URL. In file storage, the MIME type is
  86289. * stored as a 32-bit length followed by the ASCII string with no NUL
  86290. * terminator, but is converted to a plain C string in this structure
  86291. * for convenience.
  86292. */
  86293. FLAC__byte *description;
  86294. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  86295. * the description is stored as a 32-bit length followed by the UTF-8
  86296. * string with no NUL terminator, but is converted to a plain C string
  86297. * in this structure for convenience.
  86298. */
  86299. FLAC__uint32 width;
  86300. /**< Picture's width in pixels. */
  86301. FLAC__uint32 height;
  86302. /**< Picture's height in pixels. */
  86303. FLAC__uint32 depth;
  86304. /**< Picture's color depth in bits-per-pixel. */
  86305. FLAC__uint32 colors;
  86306. /**< For indexed palettes (like GIF), picture's number of colors (the
  86307. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  86308. */
  86309. FLAC__uint32 data_length;
  86310. /**< Length of binary picture data in bytes. */
  86311. FLAC__byte *data;
  86312. /**< Binary picture data. */
  86313. } FLAC__StreamMetadata_Picture;
  86314. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  86315. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  86316. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  86317. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  86318. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  86319. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  86320. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  86321. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  86322. /** Structure that is used when a metadata block of unknown type is loaded.
  86323. * The contents are opaque. The structure is used only internally to
  86324. * correctly handle unknown metadata.
  86325. */
  86326. typedef struct {
  86327. FLAC__byte *data;
  86328. } FLAC__StreamMetadata_Unknown;
  86329. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  86330. */
  86331. typedef struct {
  86332. FLAC__MetadataType type;
  86333. /**< The type of the metadata block; used determine which member of the
  86334. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  86335. * then \a data.unknown must be used. */
  86336. FLAC__bool is_last;
  86337. /**< \c true if this metadata block is the last, else \a false */
  86338. unsigned length;
  86339. /**< Length, in bytes, of the block data as it appears in the stream. */
  86340. union {
  86341. FLAC__StreamMetadata_StreamInfo stream_info;
  86342. FLAC__StreamMetadata_Padding padding;
  86343. FLAC__StreamMetadata_Application application;
  86344. FLAC__StreamMetadata_SeekTable seek_table;
  86345. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  86346. FLAC__StreamMetadata_CueSheet cue_sheet;
  86347. FLAC__StreamMetadata_Picture picture;
  86348. FLAC__StreamMetadata_Unknown unknown;
  86349. } data;
  86350. /**< Polymorphic block data; use the \a type value to determine which
  86351. * to use. */
  86352. } FLAC__StreamMetadata;
  86353. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  86354. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  86355. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  86356. /** The total stream length of a metadata block header in bytes. */
  86357. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  86358. /*****************************************************************************/
  86359. /*****************************************************************************
  86360. *
  86361. * Utility functions
  86362. *
  86363. *****************************************************************************/
  86364. /** Tests that a sample rate is valid for FLAC.
  86365. *
  86366. * \param sample_rate The sample rate to test for compliance.
  86367. * \retval FLAC__bool
  86368. * \c true if the given sample rate conforms to the specification, else
  86369. * \c false.
  86370. */
  86371. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  86372. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  86373. * for valid sample rates are slightly more complex since the rate has to
  86374. * be expressible completely in the frame header.
  86375. *
  86376. * \param sample_rate The sample rate to test for compliance.
  86377. * \retval FLAC__bool
  86378. * \c true if the given sample rate conforms to the specification for the
  86379. * subset, else \c false.
  86380. */
  86381. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  86382. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  86383. * comment specification.
  86384. *
  86385. * Vorbis comment names must be composed only of characters from
  86386. * [0x20-0x3C,0x3E-0x7D].
  86387. *
  86388. * \param name A NUL-terminated string to be checked.
  86389. * \assert
  86390. * \code name != NULL \endcode
  86391. * \retval FLAC__bool
  86392. * \c false if entry name is illegal, else \c true.
  86393. */
  86394. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  86395. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  86396. * comment specification.
  86397. *
  86398. * Vorbis comment values must be valid UTF-8 sequences.
  86399. *
  86400. * \param value A string to be checked.
  86401. * \param length A the length of \a value in bytes. May be
  86402. * \c (unsigned)(-1) to indicate that \a value is a plain
  86403. * UTF-8 NUL-terminated string.
  86404. * \assert
  86405. * \code value != NULL \endcode
  86406. * \retval FLAC__bool
  86407. * \c false if entry name is illegal, else \c true.
  86408. */
  86409. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  86410. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  86411. * comment specification.
  86412. *
  86413. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  86414. * 'value' must be legal according to
  86415. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  86416. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  86417. *
  86418. * \param entry An entry to be checked.
  86419. * \param length The length of \a entry in bytes.
  86420. * \assert
  86421. * \code value != NULL \endcode
  86422. * \retval FLAC__bool
  86423. * \c false if entry name is illegal, else \c true.
  86424. */
  86425. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  86426. /** Check a seek table to see if it conforms to the FLAC specification.
  86427. * See the format specification for limits on the contents of the
  86428. * seek table.
  86429. *
  86430. * \param seek_table A pointer to a seek table to be checked.
  86431. * \assert
  86432. * \code seek_table != NULL \endcode
  86433. * \retval FLAC__bool
  86434. * \c false if seek table is illegal, else \c true.
  86435. */
  86436. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  86437. /** Sort a seek table's seek points according to the format specification.
  86438. * This includes a "unique-ification" step to remove duplicates, i.e.
  86439. * seek points with identical \a sample_number values. Duplicate seek
  86440. * points are converted into placeholder points and sorted to the end of
  86441. * the table.
  86442. *
  86443. * \param seek_table A pointer to a seek table to be sorted.
  86444. * \assert
  86445. * \code seek_table != NULL \endcode
  86446. * \retval unsigned
  86447. * The number of duplicate seek points converted into placeholders.
  86448. */
  86449. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  86450. /** Check a cue sheet to see if it conforms to the FLAC specification.
  86451. * See the format specification for limits on the contents of the
  86452. * cue sheet.
  86453. *
  86454. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  86455. * \param check_cd_da_subset If \c true, check CUESHEET against more
  86456. * stringent requirements for a CD-DA (audio) disc.
  86457. * \param violation Address of a pointer to a string. If there is a
  86458. * violation, a pointer to a string explanation of the
  86459. * violation will be returned here. \a violation may be
  86460. * \c NULL if you don't need the returned string. Do not
  86461. * free the returned string; it will always point to static
  86462. * data.
  86463. * \assert
  86464. * \code cue_sheet != NULL \endcode
  86465. * \retval FLAC__bool
  86466. * \c false if cue sheet is illegal, else \c true.
  86467. */
  86468. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  86469. /** Check picture data to see if it conforms to the FLAC specification.
  86470. * See the format specification for limits on the contents of the
  86471. * PICTURE block.
  86472. *
  86473. * \param picture A pointer to existing picture data to be checked.
  86474. * \param violation Address of a pointer to a string. If there is a
  86475. * violation, a pointer to a string explanation of the
  86476. * violation will be returned here. \a violation may be
  86477. * \c NULL if you don't need the returned string. Do not
  86478. * free the returned string; it will always point to static
  86479. * data.
  86480. * \assert
  86481. * \code picture != NULL \endcode
  86482. * \retval FLAC__bool
  86483. * \c false if picture data is illegal, else \c true.
  86484. */
  86485. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  86486. /* \} */
  86487. #ifdef __cplusplus
  86488. }
  86489. #endif
  86490. #endif
  86491. /*** End of inlined file: format.h ***/
  86492. /*** Start of inlined file: metadata.h ***/
  86493. #ifndef FLAC__METADATA_H
  86494. #define FLAC__METADATA_H
  86495. #include <sys/types.h> /* for off_t */
  86496. /* --------------------------------------------------------------------
  86497. (For an example of how all these routines are used, see the source
  86498. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  86499. metaflac in src/metaflac/)
  86500. ------------------------------------------------------------------*/
  86501. /** \file include/FLAC/metadata.h
  86502. *
  86503. * \brief
  86504. * This module provides functions for creating and manipulating FLAC
  86505. * metadata blocks in memory, and three progressively more powerful
  86506. * interfaces for traversing and editing metadata in FLAC files.
  86507. *
  86508. * See the detailed documentation for each interface in the
  86509. * \link flac_metadata metadata \endlink module.
  86510. */
  86511. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  86512. * \ingroup flac
  86513. *
  86514. * \brief
  86515. * This module provides functions for creating and manipulating FLAC
  86516. * metadata blocks in memory, and three progressively more powerful
  86517. * interfaces for traversing and editing metadata in native FLAC files.
  86518. * Note that currently only the Chain interface (level 2) supports Ogg
  86519. * FLAC files, and it is read-only i.e. no writing back changed
  86520. * metadata to file.
  86521. *
  86522. * There are three metadata interfaces of increasing complexity:
  86523. *
  86524. * Level 0:
  86525. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  86526. * PICTURE blocks.
  86527. *
  86528. * Level 1:
  86529. * Read-write access to all metadata blocks. This level is write-
  86530. * efficient in most cases (more on this below), and uses less memory
  86531. * than level 2.
  86532. *
  86533. * Level 2:
  86534. * Read-write access to all metadata blocks. This level is write-
  86535. * efficient in all cases, but uses more memory since all metadata for
  86536. * the whole file is read into memory and manipulated before writing
  86537. * out again.
  86538. *
  86539. * What do we mean by efficient? Since FLAC metadata appears at the
  86540. * beginning of the file, when writing metadata back to a FLAC file
  86541. * it is possible to grow or shrink the metadata such that the entire
  86542. * file must be rewritten. However, if the size remains the same during
  86543. * changes or PADDING blocks are utilized, only the metadata needs to be
  86544. * overwritten, which is much faster.
  86545. *
  86546. * Efficient means the whole file is rewritten at most one time, and only
  86547. * when necessary. Level 1 is not efficient only in the case that you
  86548. * cause more than one metadata block to grow or shrink beyond what can
  86549. * be accomodated by padding. In this case you should probably use level
  86550. * 2, which allows you to edit all the metadata for a file in memory and
  86551. * write it out all at once.
  86552. *
  86553. * All levels know how to skip over and not disturb an ID3v2 tag at the
  86554. * front of the file.
  86555. *
  86556. * All levels access files via their filenames. In addition, level 2
  86557. * has additional alternative read and write functions that take an I/O
  86558. * handle and callbacks, for situations where access by filename is not
  86559. * possible.
  86560. *
  86561. * In addition to the three interfaces, this module defines functions for
  86562. * creating and manipulating various metadata objects in memory. As we see
  86563. * from the Format module, FLAC metadata blocks in memory are very primitive
  86564. * structures for storing information in an efficient way. Reading
  86565. * information from the structures is easy but creating or modifying them
  86566. * directly is more complex. The metadata object routines here facilitate
  86567. * this by taking care of the consistency and memory management drudgery.
  86568. *
  86569. * Unless you will be using the level 1 or 2 interfaces to modify existing
  86570. * metadata however, you will not probably not need these.
  86571. *
  86572. * From a dependency standpoint, none of the encoders or decoders require
  86573. * the metadata module. This is so that embedded users can strip out the
  86574. * metadata module from libFLAC to reduce the size and complexity.
  86575. */
  86576. #ifdef __cplusplus
  86577. extern "C" {
  86578. #endif
  86579. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  86580. * \ingroup flac_metadata
  86581. *
  86582. * \brief
  86583. * The level 0 interface consists of individual routines to read the
  86584. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  86585. * only a filename.
  86586. *
  86587. * They try to skip any ID3v2 tag at the head of the file.
  86588. *
  86589. * \{
  86590. */
  86591. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  86592. * will try to skip any ID3v2 tag at the head of the file.
  86593. *
  86594. * \param filename The path to the FLAC file to read.
  86595. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  86596. * FLAC__StreamMetadata is a simple structure with no
  86597. * memory allocation involved, you pass the address of
  86598. * an existing structure. It need not be initialized.
  86599. * \assert
  86600. * \code filename != NULL \endcode
  86601. * \code streaminfo != NULL \endcode
  86602. * \retval FLAC__bool
  86603. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  86604. * \c false if there was a memory allocation error, a file decoder error,
  86605. * or the file contained no STREAMINFO block. (A memory allocation error
  86606. * is possible because this function must set up a file decoder.)
  86607. */
  86608. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  86609. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  86610. * function will try to skip any ID3v2 tag at the head of the file.
  86611. *
  86612. * \param filename The path to the FLAC file to read.
  86613. * \param tags The address where the returned pointer will be
  86614. * stored. The \a tags object must be deleted by
  86615. * the caller using FLAC__metadata_object_delete().
  86616. * \assert
  86617. * \code filename != NULL \endcode
  86618. * \code tags != NULL \endcode
  86619. * \retval FLAC__bool
  86620. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  86621. * and \a *tags will be set to the address of the metadata structure.
  86622. * Returns \c false if there was a memory allocation error, a file
  86623. * decoder error, or the file contained no VORBIS_COMMENT block, and
  86624. * \a *tags will be set to \c NULL.
  86625. */
  86626. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  86627. /** Read the CUESHEET metadata block of the given FLAC file. This
  86628. * function will try to skip any ID3v2 tag at the head of the file.
  86629. *
  86630. * \param filename The path to the FLAC file to read.
  86631. * \param cuesheet The address where the returned pointer will be
  86632. * stored. The \a cuesheet object must be deleted by
  86633. * the caller using FLAC__metadata_object_delete().
  86634. * \assert
  86635. * \code filename != NULL \endcode
  86636. * \code cuesheet != NULL \endcode
  86637. * \retval FLAC__bool
  86638. * \c true if a valid CUESHEET block was read from \a filename,
  86639. * and \a *cuesheet will be set to the address of the metadata
  86640. * structure. Returns \c false if there was a memory allocation
  86641. * error, a file decoder error, or the file contained no CUESHEET
  86642. * block, and \a *cuesheet will be set to \c NULL.
  86643. */
  86644. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  86645. /** Read a PICTURE metadata block of the given FLAC file. This
  86646. * function will try to skip any ID3v2 tag at the head of the file.
  86647. * Since there can be more than one PICTURE block in a file, this
  86648. * function takes a number of parameters that act as constraints to
  86649. * the search. The PICTURE block with the largest area matching all
  86650. * the constraints will be returned, or \a *picture will be set to
  86651. * \c NULL if there was no such block.
  86652. *
  86653. * \param filename The path to the FLAC file to read.
  86654. * \param picture The address where the returned pointer will be
  86655. * stored. The \a picture object must be deleted by
  86656. * the caller using FLAC__metadata_object_delete().
  86657. * \param type The desired picture type. Use \c -1 to mean
  86658. * "any type".
  86659. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  86660. * string will be matched exactly. Use \c NULL to
  86661. * mean "any MIME type".
  86662. * \param description The desired description. The string will be
  86663. * matched exactly. Use \c NULL to mean "any
  86664. * description".
  86665. * \param max_width The maximum width in pixels desired. Use
  86666. * \c (unsigned)(-1) to mean "any width".
  86667. * \param max_height The maximum height in pixels desired. Use
  86668. * \c (unsigned)(-1) to mean "any height".
  86669. * \param max_depth The maximum color depth in bits-per-pixel desired.
  86670. * Use \c (unsigned)(-1) to mean "any depth".
  86671. * \param max_colors The maximum number of colors desired. Use
  86672. * \c (unsigned)(-1) to mean "any number of colors".
  86673. * \assert
  86674. * \code filename != NULL \endcode
  86675. * \code picture != NULL \endcode
  86676. * \retval FLAC__bool
  86677. * \c true if a valid PICTURE block was read from \a filename,
  86678. * and \a *picture will be set to the address of the metadata
  86679. * structure. Returns \c false if there was a memory allocation
  86680. * error, a file decoder error, or the file contained no PICTURE
  86681. * block, and \a *picture will be set to \c NULL.
  86682. */
  86683. 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);
  86684. /* \} */
  86685. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  86686. * \ingroup flac_metadata
  86687. *
  86688. * \brief
  86689. * The level 1 interface provides read-write access to FLAC file metadata and
  86690. * operates directly on the FLAC file.
  86691. *
  86692. * The general usage of this interface is:
  86693. *
  86694. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  86695. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  86696. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  86697. * see if the file is writable, or only read access is allowed.
  86698. * - Use FLAC__metadata_simple_iterator_next() and
  86699. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  86700. * This is does not read the actual blocks themselves.
  86701. * FLAC__metadata_simple_iterator_next() is relatively fast.
  86702. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  86703. * forward from the front of the file.
  86704. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  86705. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  86706. * the current iterator position. The returned object is yours to modify
  86707. * and free.
  86708. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  86709. * back. You must have write permission to the original file. Make sure to
  86710. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  86711. * below.
  86712. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  86713. * Use the object creation functions from
  86714. * \link flac_metadata_object here \endlink to generate new objects.
  86715. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  86716. * currently referred to by the iterator, or replace it with padding.
  86717. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  86718. * finished.
  86719. *
  86720. * \note
  86721. * The FLAC file remains open the whole time between
  86722. * FLAC__metadata_simple_iterator_init() and
  86723. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  86724. * the file during this time.
  86725. *
  86726. * \note
  86727. * Do not modify the \a is_last, \a length, or \a type fields of returned
  86728. * FLAC__StreamMetadata objects. These are managed automatically.
  86729. *
  86730. * \note
  86731. * If any of the modification functions
  86732. * (FLAC__metadata_simple_iterator_set_block(),
  86733. * FLAC__metadata_simple_iterator_delete_block(),
  86734. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  86735. * you should delete the iterator as it may no longer be valid.
  86736. *
  86737. * \{
  86738. */
  86739. struct FLAC__Metadata_SimpleIterator;
  86740. /** The opaque structure definition for the level 1 iterator type.
  86741. * See the
  86742. * \link flac_metadata_level1 metadata level 1 module \endlink
  86743. * for a detailed description.
  86744. */
  86745. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  86746. /** Status type for FLAC__Metadata_SimpleIterator.
  86747. *
  86748. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  86749. */
  86750. typedef enum {
  86751. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  86752. /**< The iterator is in the normal OK state */
  86753. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  86754. /**< The data passed into a function violated the function's usage criteria */
  86755. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  86756. /**< The iterator could not open the target file */
  86757. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  86758. /**< The iterator could not find the FLAC signature at the start of the file */
  86759. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  86760. /**< The iterator tried to write to a file that was not writable */
  86761. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  86762. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  86763. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  86764. /**< The iterator encountered an error while reading the FLAC file */
  86765. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  86766. /**< The iterator encountered an error while seeking in the FLAC file */
  86767. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  86768. /**< The iterator encountered an error while writing the FLAC file */
  86769. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  86770. /**< The iterator encountered an error renaming the FLAC file */
  86771. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  86772. /**< The iterator encountered an error removing the temporary file */
  86773. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  86774. /**< Memory allocation failed */
  86775. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  86776. /**< The caller violated an assertion or an unexpected error occurred */
  86777. } FLAC__Metadata_SimpleIteratorStatus;
  86778. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  86779. *
  86780. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  86781. * will give the string equivalent. The contents should not be modified.
  86782. */
  86783. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  86784. /** Create a new iterator instance.
  86785. *
  86786. * \retval FLAC__Metadata_SimpleIterator*
  86787. * \c NULL if there was an error allocating memory, else the new instance.
  86788. */
  86789. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  86790. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  86791. *
  86792. * \param iterator A pointer to an existing iterator.
  86793. * \assert
  86794. * \code iterator != NULL \endcode
  86795. */
  86796. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  86797. /** Get the current status of the iterator. Call this after a function
  86798. * returns \c false to get the reason for the error. Also resets the status
  86799. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  86800. *
  86801. * \param iterator A pointer to an existing iterator.
  86802. * \assert
  86803. * \code iterator != NULL \endcode
  86804. * \retval FLAC__Metadata_SimpleIteratorStatus
  86805. * The current status of the iterator.
  86806. */
  86807. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  86808. /** Initialize the iterator to point to the first metadata block in the
  86809. * given FLAC file.
  86810. *
  86811. * \param iterator A pointer to an existing iterator.
  86812. * \param filename The path to the FLAC file.
  86813. * \param read_only If \c true, the FLAC file will be opened
  86814. * in read-only mode; if \c false, the FLAC
  86815. * file will be opened for edit even if no
  86816. * edits are performed.
  86817. * \param preserve_file_stats If \c true, the owner and modification
  86818. * time will be preserved even if the FLAC
  86819. * file is written to.
  86820. * \assert
  86821. * \code iterator != NULL \endcode
  86822. * \code filename != NULL \endcode
  86823. * \retval FLAC__bool
  86824. * \c false if a memory allocation error occurs, the file can't be
  86825. * opened, or another error occurs, else \c true.
  86826. */
  86827. 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);
  86828. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  86829. * FLAC__metadata_simple_iterator_set_block() and
  86830. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  86831. *
  86832. * \param iterator A pointer to an existing iterator.
  86833. * \assert
  86834. * \code iterator != NULL \endcode
  86835. * \retval FLAC__bool
  86836. * See above.
  86837. */
  86838. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  86839. /** Moves the iterator forward one metadata block, returning \c false if
  86840. * already at the end.
  86841. *
  86842. * \param iterator A pointer to an existing initialized iterator.
  86843. * \assert
  86844. * \code iterator != NULL \endcode
  86845. * \a iterator has been successfully initialized with
  86846. * FLAC__metadata_simple_iterator_init()
  86847. * \retval FLAC__bool
  86848. * \c false if already at the last metadata block of the chain, else
  86849. * \c true.
  86850. */
  86851. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  86852. /** Moves the iterator backward one metadata block, returning \c false if
  86853. * already at the beginning.
  86854. *
  86855. * \param iterator A pointer to an existing initialized iterator.
  86856. * \assert
  86857. * \code iterator != NULL \endcode
  86858. * \a iterator has been successfully initialized with
  86859. * FLAC__metadata_simple_iterator_init()
  86860. * \retval FLAC__bool
  86861. * \c false if already at the first metadata block of the chain, else
  86862. * \c true.
  86863. */
  86864. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  86865. /** Returns a flag telling if the current metadata block is the last.
  86866. *
  86867. * \param iterator A pointer to an existing initialized iterator.
  86868. * \assert
  86869. * \code iterator != NULL \endcode
  86870. * \a iterator has been successfully initialized with
  86871. * FLAC__metadata_simple_iterator_init()
  86872. * \retval FLAC__bool
  86873. * \c true if the current metadata block is the last in the file,
  86874. * else \c false.
  86875. */
  86876. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  86877. /** Get the offset of the metadata block at the current position. This
  86878. * avoids reading the actual block data which can save time for large
  86879. * blocks.
  86880. *
  86881. * \param iterator A pointer to an existing initialized iterator.
  86882. * \assert
  86883. * \code iterator != NULL \endcode
  86884. * \a iterator has been successfully initialized with
  86885. * FLAC__metadata_simple_iterator_init()
  86886. * \retval off_t
  86887. * The offset of the metadata block at the current iterator position.
  86888. * This is the byte offset relative to the beginning of the file of
  86889. * the current metadata block's header.
  86890. */
  86891. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  86892. /** Get the type of the metadata block at the current position. This
  86893. * avoids reading the actual block data which can save time for large
  86894. * blocks.
  86895. *
  86896. * \param iterator A pointer to an existing initialized iterator.
  86897. * \assert
  86898. * \code iterator != NULL \endcode
  86899. * \a iterator has been successfully initialized with
  86900. * FLAC__metadata_simple_iterator_init()
  86901. * \retval FLAC__MetadataType
  86902. * The type of the metadata block at the current iterator position.
  86903. */
  86904. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  86905. /** Get the length of the metadata block at the current position. This
  86906. * avoids reading the actual block data which can save time for large
  86907. * blocks.
  86908. *
  86909. * \param iterator A pointer to an existing initialized iterator.
  86910. * \assert
  86911. * \code iterator != NULL \endcode
  86912. * \a iterator has been successfully initialized with
  86913. * FLAC__metadata_simple_iterator_init()
  86914. * \retval unsigned
  86915. * The length of the metadata block at the current iterator position.
  86916. * The is same length as that in the
  86917. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  86918. * i.e. the length of the metadata body that follows the header.
  86919. */
  86920. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  86921. /** Get the application ID of the \c APPLICATION block at the current
  86922. * position. This avoids reading the actual block data which can save
  86923. * time for large blocks.
  86924. *
  86925. * \param iterator A pointer to an existing initialized iterator.
  86926. * \param id A pointer to a buffer of at least \c 4 bytes where
  86927. * the ID will be stored.
  86928. * \assert
  86929. * \code iterator != NULL \endcode
  86930. * \code id != NULL \endcode
  86931. * \a iterator has been successfully initialized with
  86932. * FLAC__metadata_simple_iterator_init()
  86933. * \retval FLAC__bool
  86934. * \c true if the ID was successfully read, else \c false, in which
  86935. * case you should check FLAC__metadata_simple_iterator_status() to
  86936. * find out why. If the status is
  86937. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  86938. * current metadata block is not an \c APPLICATION block. Otherwise
  86939. * if the status is
  86940. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  86941. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  86942. * occurred and the iterator can no longer be used.
  86943. */
  86944. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  86945. /** Get the metadata block at the current position. You can modify the
  86946. * block but must use FLAC__metadata_simple_iterator_set_block() to
  86947. * write it back to the FLAC file.
  86948. *
  86949. * You must call FLAC__metadata_object_delete() on the returned object
  86950. * when you are finished with it.
  86951. *
  86952. * \param iterator A pointer to an existing initialized iterator.
  86953. * \assert
  86954. * \code iterator != NULL \endcode
  86955. * \a iterator has been successfully initialized with
  86956. * FLAC__metadata_simple_iterator_init()
  86957. * \retval FLAC__StreamMetadata*
  86958. * The current metadata block, or \c NULL if there was a memory
  86959. * allocation error.
  86960. */
  86961. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  86962. /** Write a block back to the FLAC file. This function tries to be
  86963. * as efficient as possible; how the block is actually written is
  86964. * shown by the following:
  86965. *
  86966. * Existing block is a STREAMINFO block and the new block is a
  86967. * STREAMINFO block: the new block is written in place. Make sure
  86968. * you know what you're doing when changing the values of a
  86969. * STREAMINFO block.
  86970. *
  86971. * Existing block is a STREAMINFO block and the new block is a
  86972. * not a STREAMINFO block: this is an error since the first block
  86973. * must be a STREAMINFO block. Returns \c false without altering the
  86974. * file.
  86975. *
  86976. * Existing block is not a STREAMINFO block and the new block is a
  86977. * STREAMINFO block: this is an error since there may be only one
  86978. * STREAMINFO block. Returns \c false without altering the file.
  86979. *
  86980. * Existing block and new block are the same length: the existing
  86981. * block will be replaced by the new block, written in place.
  86982. *
  86983. * Existing block is longer than new block: if use_padding is \c true,
  86984. * the existing block will be overwritten in place with the new
  86985. * block followed by a PADDING block, if possible, to make the total
  86986. * size the same as the existing block. Remember that a padding
  86987. * block requires at least four bytes so if the difference in size
  86988. * between the new block and existing block is less than that, the
  86989. * entire file will have to be rewritten, using the new block's
  86990. * exact size. If use_padding is \c false, the entire file will be
  86991. * rewritten, replacing the existing block by the new block.
  86992. *
  86993. * Existing block is shorter than new block: if use_padding is \c true,
  86994. * the function will try and expand the new block into the following
  86995. * PADDING block, if it exists and doing so won't shrink the PADDING
  86996. * block to less than 4 bytes. If there is no following PADDING
  86997. * block, or it will shrink to less than 4 bytes, or use_padding is
  86998. * \c false, the entire file is rewritten, replacing the existing block
  86999. * with the new block. Note that in this case any following PADDING
  87000. * block is preserved as is.
  87001. *
  87002. * After writing the block, the iterator will remain in the same
  87003. * place, i.e. pointing to the new block.
  87004. *
  87005. * \param iterator A pointer to an existing initialized iterator.
  87006. * \param block The block to set.
  87007. * \param use_padding See above.
  87008. * \assert
  87009. * \code iterator != NULL \endcode
  87010. * \a iterator has been successfully initialized with
  87011. * FLAC__metadata_simple_iterator_init()
  87012. * \code block != NULL \endcode
  87013. * \retval FLAC__bool
  87014. * \c true if successful, else \c false.
  87015. */
  87016. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  87017. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  87018. * except that instead of writing over an existing block, it appends
  87019. * a block after the existing block. \a use_padding is again used to
  87020. * tell the function to try an expand into following padding in an
  87021. * attempt to avoid rewriting the entire file.
  87022. *
  87023. * This function will fail and return \c false if given a STREAMINFO
  87024. * block.
  87025. *
  87026. * After writing the block, the iterator will be pointing to the
  87027. * new block.
  87028. *
  87029. * \param iterator A pointer to an existing initialized iterator.
  87030. * \param block The block to set.
  87031. * \param use_padding See above.
  87032. * \assert
  87033. * \code iterator != NULL \endcode
  87034. * \a iterator has been successfully initialized with
  87035. * FLAC__metadata_simple_iterator_init()
  87036. * \code block != NULL \endcode
  87037. * \retval FLAC__bool
  87038. * \c true if successful, else \c false.
  87039. */
  87040. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  87041. /** Deletes the block at the current position. This will cause the
  87042. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  87043. * in which case the block will be replaced by an equal-sized PADDING
  87044. * block. The iterator will be left pointing to the block before the
  87045. * one just deleted.
  87046. *
  87047. * You may not delete the STREAMINFO block.
  87048. *
  87049. * \param iterator A pointer to an existing initialized iterator.
  87050. * \param use_padding See above.
  87051. * \assert
  87052. * \code iterator != NULL \endcode
  87053. * \a iterator has been successfully initialized with
  87054. * FLAC__metadata_simple_iterator_init()
  87055. * \retval FLAC__bool
  87056. * \c true if successful, else \c false.
  87057. */
  87058. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  87059. /* \} */
  87060. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  87061. * \ingroup flac_metadata
  87062. *
  87063. * \brief
  87064. * The level 2 interface provides read-write access to FLAC file metadata;
  87065. * all metadata is read into memory, operated on in memory, and then written
  87066. * to file, which is more efficient than level 1 when editing multiple blocks.
  87067. *
  87068. * Currently Ogg FLAC is supported for read only, via
  87069. * FLAC__metadata_chain_read_ogg() but a subsequent
  87070. * FLAC__metadata_chain_write() will fail.
  87071. *
  87072. * The general usage of this interface is:
  87073. *
  87074. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  87075. * linked list of FLAC metadata blocks.
  87076. * - Read all metadata into the the chain from a FLAC file using
  87077. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  87078. * check the status.
  87079. * - Optionally, consolidate the padding using
  87080. * FLAC__metadata_chain_merge_padding() or
  87081. * FLAC__metadata_chain_sort_padding().
  87082. * - Create a new iterator using FLAC__metadata_iterator_new()
  87083. * - Initialize the iterator to point to the first element in the chain
  87084. * using FLAC__metadata_iterator_init()
  87085. * - Traverse the chain using FLAC__metadata_iterator_next and
  87086. * FLAC__metadata_iterator_prev().
  87087. * - Get a block for reading or modification using
  87088. * FLAC__metadata_iterator_get_block(). The pointer to the object
  87089. * inside the chain is returned, so the block is yours to modify.
  87090. * Changes will be reflected in the FLAC file when you write the
  87091. * chain. You can also add and delete blocks (see functions below).
  87092. * - When done, write out the chain using FLAC__metadata_chain_write().
  87093. * Make sure to read the whole comment to the function below.
  87094. * - Delete the chain using FLAC__metadata_chain_delete().
  87095. *
  87096. * \note
  87097. * Even though the FLAC file is not open while the chain is being
  87098. * manipulated, you must not alter the file externally during
  87099. * this time. The chain assumes the FLAC file will not change
  87100. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  87101. * and FLAC__metadata_chain_write().
  87102. *
  87103. * \note
  87104. * Do not modify the is_last, length, or type fields of returned
  87105. * FLAC__StreamMetadata objects. These are managed automatically.
  87106. *
  87107. * \note
  87108. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  87109. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  87110. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  87111. * become owned by the chain and they will be deleted when the chain is
  87112. * deleted.
  87113. *
  87114. * \{
  87115. */
  87116. struct FLAC__Metadata_Chain;
  87117. /** The opaque structure definition for the level 2 chain type.
  87118. */
  87119. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  87120. struct FLAC__Metadata_Iterator;
  87121. /** The opaque structure definition for the level 2 iterator type.
  87122. */
  87123. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  87124. typedef enum {
  87125. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  87126. /**< The chain is in the normal OK state */
  87127. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  87128. /**< The data passed into a function violated the function's usage criteria */
  87129. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  87130. /**< The chain could not open the target file */
  87131. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  87132. /**< The chain could not find the FLAC signature at the start of the file */
  87133. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  87134. /**< The chain tried to write to a file that was not writable */
  87135. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  87136. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  87137. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  87138. /**< The chain encountered an error while reading the FLAC file */
  87139. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  87140. /**< The chain encountered an error while seeking in the FLAC file */
  87141. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  87142. /**< The chain encountered an error while writing the FLAC file */
  87143. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  87144. /**< The chain encountered an error renaming the FLAC file */
  87145. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  87146. /**< The chain encountered an error removing the temporary file */
  87147. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  87148. /**< Memory allocation failed */
  87149. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  87150. /**< The caller violated an assertion or an unexpected error occurred */
  87151. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  87152. /**< One or more of the required callbacks was NULL */
  87153. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  87154. /**< FLAC__metadata_chain_write() was called on a chain read by
  87155. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  87156. * or
  87157. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  87158. * was called on a chain read by
  87159. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  87160. * Matching read/write methods must always be used. */
  87161. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  87162. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  87163. * chain write requires a tempfile; use
  87164. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  87165. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  87166. * called when the chain write does not require a tempfile; use
  87167. * FLAC__metadata_chain_write_with_callbacks() instead.
  87168. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  87169. * before writing via callbacks. */
  87170. } FLAC__Metadata_ChainStatus;
  87171. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  87172. *
  87173. * Using a FLAC__Metadata_ChainStatus as the index to this array
  87174. * will give the string equivalent. The contents should not be modified.
  87175. */
  87176. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  87177. /*********** FLAC__Metadata_Chain ***********/
  87178. /** Create a new chain instance.
  87179. *
  87180. * \retval FLAC__Metadata_Chain*
  87181. * \c NULL if there was an error allocating memory, else the new instance.
  87182. */
  87183. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  87184. /** Free a chain instance. Deletes the object pointed to by \a chain.
  87185. *
  87186. * \param chain A pointer to an existing chain.
  87187. * \assert
  87188. * \code chain != NULL \endcode
  87189. */
  87190. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  87191. /** Get the current status of the chain. Call this after a function
  87192. * returns \c false to get the reason for the error. Also resets the
  87193. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  87194. *
  87195. * \param chain A pointer to an existing chain.
  87196. * \assert
  87197. * \code chain != NULL \endcode
  87198. * \retval FLAC__Metadata_ChainStatus
  87199. * The current status of the chain.
  87200. */
  87201. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  87202. /** Read all metadata from a FLAC file into the chain.
  87203. *
  87204. * \param chain A pointer to an existing chain.
  87205. * \param filename The path to the FLAC file to read.
  87206. * \assert
  87207. * \code chain != NULL \endcode
  87208. * \code filename != NULL \endcode
  87209. * \retval FLAC__bool
  87210. * \c true if a valid list of metadata blocks was read from
  87211. * \a filename, else \c false. On failure, check the status with
  87212. * FLAC__metadata_chain_status().
  87213. */
  87214. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  87215. /** Read all metadata from an Ogg FLAC file into the chain.
  87216. *
  87217. * \note Ogg FLAC metadata data writing is not supported yet and
  87218. * FLAC__metadata_chain_write() will fail.
  87219. *
  87220. * \param chain A pointer to an existing chain.
  87221. * \param filename The path to the Ogg FLAC file to read.
  87222. * \assert
  87223. * \code chain != NULL \endcode
  87224. * \code filename != NULL \endcode
  87225. * \retval FLAC__bool
  87226. * \c true if a valid list of metadata blocks was read from
  87227. * \a filename, else \c false. On failure, check the status with
  87228. * FLAC__metadata_chain_status().
  87229. */
  87230. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  87231. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  87232. *
  87233. * The \a handle need only be open for reading, but must be seekable.
  87234. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  87235. * for Windows).
  87236. *
  87237. * \param chain A pointer to an existing chain.
  87238. * \param handle The I/O handle of the FLAC stream to read. The
  87239. * handle will NOT be closed after the metadata is read;
  87240. * that is the duty of the caller.
  87241. * \param callbacks
  87242. * A set of callbacks to use for I/O. The mandatory
  87243. * callbacks are \a read, \a seek, and \a tell.
  87244. * \assert
  87245. * \code chain != NULL \endcode
  87246. * \retval FLAC__bool
  87247. * \c true if a valid list of metadata blocks was read from
  87248. * \a handle, else \c false. On failure, check the status with
  87249. * FLAC__metadata_chain_status().
  87250. */
  87251. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  87252. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  87253. *
  87254. * The \a handle need only be open for reading, but must be seekable.
  87255. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  87256. * for Windows).
  87257. *
  87258. * \note Ogg FLAC metadata data writing is not supported yet and
  87259. * FLAC__metadata_chain_write() will fail.
  87260. *
  87261. * \param chain A pointer to an existing chain.
  87262. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  87263. * handle will NOT be closed after the metadata is read;
  87264. * that is the duty of the caller.
  87265. * \param callbacks
  87266. * A set of callbacks to use for I/O. The mandatory
  87267. * callbacks are \a read, \a seek, and \a tell.
  87268. * \assert
  87269. * \code chain != NULL \endcode
  87270. * \retval FLAC__bool
  87271. * \c true if a valid list of metadata blocks was read from
  87272. * \a handle, else \c false. On failure, check the status with
  87273. * FLAC__metadata_chain_status().
  87274. */
  87275. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  87276. /** Checks if writing the given chain would require the use of a
  87277. * temporary file, or if it could be written in place.
  87278. *
  87279. * Under certain conditions, padding can be utilized so that writing
  87280. * edited metadata back to the FLAC file does not require rewriting the
  87281. * entire file. If rewriting is required, then a temporary workfile is
  87282. * required. When writing metadata using callbacks, you must check
  87283. * this function to know whether to call
  87284. * FLAC__metadata_chain_write_with_callbacks() or
  87285. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  87286. * writing with FLAC__metadata_chain_write(), the temporary file is
  87287. * handled internally.
  87288. *
  87289. * \param chain A pointer to an existing chain.
  87290. * \param use_padding
  87291. * Whether or not padding will be allowed to be used
  87292. * during the write. The value of \a use_padding given
  87293. * here must match the value later passed to
  87294. * FLAC__metadata_chain_write_with_callbacks() or
  87295. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  87296. * \assert
  87297. * \code chain != NULL \endcode
  87298. * \retval FLAC__bool
  87299. * \c true if writing the current chain would require a tempfile, or
  87300. * \c false if metadata can be written in place.
  87301. */
  87302. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  87303. /** Write all metadata out to the FLAC file. This function tries to be as
  87304. * efficient as possible; how the metadata is actually written is shown by
  87305. * the following:
  87306. *
  87307. * If the current chain is the same size as the existing metadata, the new
  87308. * data is written in place.
  87309. *
  87310. * If the current chain is longer than the existing metadata, and
  87311. * \a use_padding is \c true, and the last block is a PADDING block of
  87312. * sufficient length, the function will truncate the final padding block
  87313. * so that the overall size of the metadata is the same as the existing
  87314. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  87315. * the above conditions are met, the entire FLAC file must be rewritten.
  87316. * If you want to use padding this way it is a good idea to call
  87317. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  87318. * amount of padding to work with, unless you need to preserve ordering
  87319. * of the PADDING blocks for some reason.
  87320. *
  87321. * If the current chain is shorter than the existing metadata, and
  87322. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  87323. * is extended to make the overall size the same as the existing data. If
  87324. * \a use_padding is \c true and the last block is not a PADDING block, a new
  87325. * PADDING block is added to the end of the new data to make it the same
  87326. * size as the existing data (if possible, see the note to
  87327. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  87328. * and the new data is written in place. If none of the above apply or
  87329. * \a use_padding is \c false, the entire FLAC file is rewritten.
  87330. *
  87331. * If \a preserve_file_stats is \c true, the owner and modification time will
  87332. * be preserved even if the FLAC file is written.
  87333. *
  87334. * For this write function to be used, the chain must have been read with
  87335. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  87336. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  87337. *
  87338. * \param chain A pointer to an existing chain.
  87339. * \param use_padding See above.
  87340. * \param preserve_file_stats See above.
  87341. * \assert
  87342. * \code chain != NULL \endcode
  87343. * \retval FLAC__bool
  87344. * \c true if the write succeeded, else \c false. On failure,
  87345. * check the status with FLAC__metadata_chain_status().
  87346. */
  87347. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  87348. /** Write all metadata out to a FLAC stream via callbacks.
  87349. *
  87350. * (See FLAC__metadata_chain_write() for the details on how padding is
  87351. * used to write metadata in place if possible.)
  87352. *
  87353. * The \a handle must be open for updating and be seekable. The
  87354. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  87355. * for Windows).
  87356. *
  87357. * For this write function to be used, the chain must have been read with
  87358. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  87359. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  87360. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  87361. * \c false.
  87362. *
  87363. * \param chain A pointer to an existing chain.
  87364. * \param use_padding See FLAC__metadata_chain_write()
  87365. * \param handle The I/O handle of the FLAC stream to write. The
  87366. * handle will NOT be closed after the metadata is
  87367. * written; that is the duty of the caller.
  87368. * \param callbacks A set of callbacks to use for I/O. The mandatory
  87369. * callbacks are \a write and \a seek.
  87370. * \assert
  87371. * \code chain != NULL \endcode
  87372. * \retval FLAC__bool
  87373. * \c true if the write succeeded, else \c false. On failure,
  87374. * check the status with FLAC__metadata_chain_status().
  87375. */
  87376. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  87377. /** Write all metadata out to a FLAC stream via callbacks.
  87378. *
  87379. * (See FLAC__metadata_chain_write() for the details on how padding is
  87380. * used to write metadata in place if possible.)
  87381. *
  87382. * This version of the write-with-callbacks function must be used when
  87383. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  87384. * this function, you must supply an I/O handle corresponding to the
  87385. * FLAC file to edit, and a temporary handle to which the new FLAC
  87386. * file will be written. It is the caller's job to move this temporary
  87387. * FLAC file on top of the original FLAC file to complete the metadata
  87388. * edit.
  87389. *
  87390. * The \a handle must be open for reading and be seekable. The
  87391. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  87392. * for Windows).
  87393. *
  87394. * The \a temp_handle must be open for writing. The
  87395. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  87396. * for Windows). It should be an empty stream, or at least positioned
  87397. * at the start-of-file (in which case it is the caller's duty to
  87398. * truncate it on return).
  87399. *
  87400. * For this write function to be used, the chain must have been read with
  87401. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  87402. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  87403. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  87404. * \c true.
  87405. *
  87406. * \param chain A pointer to an existing chain.
  87407. * \param use_padding See FLAC__metadata_chain_write()
  87408. * \param handle The I/O handle of the original FLAC stream to read.
  87409. * The handle will NOT be closed after the metadata is
  87410. * written; that is the duty of the caller.
  87411. * \param callbacks A set of callbacks to use for I/O on \a handle.
  87412. * The mandatory callbacks are \a read, \a seek, and
  87413. * \a eof.
  87414. * \param temp_handle The I/O handle of the FLAC stream to write. The
  87415. * handle will NOT be closed after the metadata is
  87416. * written; that is the duty of the caller.
  87417. * \param temp_callbacks
  87418. * A set of callbacks to use for I/O on temp_handle.
  87419. * The only mandatory callback is \a write.
  87420. * \assert
  87421. * \code chain != NULL \endcode
  87422. * \retval FLAC__bool
  87423. * \c true if the write succeeded, else \c false. On failure,
  87424. * check the status with FLAC__metadata_chain_status().
  87425. */
  87426. 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);
  87427. /** Merge adjacent PADDING blocks into a single block.
  87428. *
  87429. * \note This function does not write to the FLAC file, it only
  87430. * modifies the chain.
  87431. *
  87432. * \warning Any iterator on the current chain will become invalid after this
  87433. * call. You should delete the iterator and get a new one.
  87434. *
  87435. * \param chain A pointer to an existing chain.
  87436. * \assert
  87437. * \code chain != NULL \endcode
  87438. */
  87439. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  87440. /** This function will move all PADDING blocks to the end on the metadata,
  87441. * then merge them into a single block.
  87442. *
  87443. * \note This function does not write to the FLAC file, it only
  87444. * modifies the chain.
  87445. *
  87446. * \warning Any iterator on the current chain will become invalid after this
  87447. * call. You should delete the iterator and get a new one.
  87448. *
  87449. * \param chain A pointer to an existing chain.
  87450. * \assert
  87451. * \code chain != NULL \endcode
  87452. */
  87453. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  87454. /*********** FLAC__Metadata_Iterator ***********/
  87455. /** Create a new iterator instance.
  87456. *
  87457. * \retval FLAC__Metadata_Iterator*
  87458. * \c NULL if there was an error allocating memory, else the new instance.
  87459. */
  87460. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  87461. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  87462. *
  87463. * \param iterator A pointer to an existing iterator.
  87464. * \assert
  87465. * \code iterator != NULL \endcode
  87466. */
  87467. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  87468. /** Initialize the iterator to point to the first metadata block in the
  87469. * given chain.
  87470. *
  87471. * \param iterator A pointer to an existing iterator.
  87472. * \param chain A pointer to an existing and initialized (read) chain.
  87473. * \assert
  87474. * \code iterator != NULL \endcode
  87475. * \code chain != NULL \endcode
  87476. */
  87477. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  87478. /** Moves the iterator forward one metadata block, returning \c false if
  87479. * already at the end.
  87480. *
  87481. * \param iterator A pointer to an existing initialized iterator.
  87482. * \assert
  87483. * \code iterator != NULL \endcode
  87484. * \a iterator has been successfully initialized with
  87485. * FLAC__metadata_iterator_init()
  87486. * \retval FLAC__bool
  87487. * \c false if already at the last metadata block of the chain, else
  87488. * \c true.
  87489. */
  87490. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  87491. /** Moves the iterator backward one metadata block, returning \c false if
  87492. * already at the beginning.
  87493. *
  87494. * \param iterator A pointer to an existing initialized iterator.
  87495. * \assert
  87496. * \code iterator != NULL \endcode
  87497. * \a iterator has been successfully initialized with
  87498. * FLAC__metadata_iterator_init()
  87499. * \retval FLAC__bool
  87500. * \c false if already at the first metadata block of the chain, else
  87501. * \c true.
  87502. */
  87503. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  87504. /** Get the type of the metadata block at the current position.
  87505. *
  87506. * \param iterator A pointer to an existing initialized iterator.
  87507. * \assert
  87508. * \code iterator != NULL \endcode
  87509. * \a iterator has been successfully initialized with
  87510. * FLAC__metadata_iterator_init()
  87511. * \retval FLAC__MetadataType
  87512. * The type of the metadata block at the current iterator position.
  87513. */
  87514. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  87515. /** Get the metadata block at the current position. You can modify
  87516. * the block in place but must write the chain before the changes
  87517. * are reflected to the FLAC file. You do not need to call
  87518. * FLAC__metadata_iterator_set_block() to reflect the changes;
  87519. * the pointer returned by FLAC__metadata_iterator_get_block()
  87520. * points directly into the chain.
  87521. *
  87522. * \warning
  87523. * Do not call FLAC__metadata_object_delete() on the returned object;
  87524. * to delete a block use FLAC__metadata_iterator_delete_block().
  87525. *
  87526. * \param iterator A pointer to an existing initialized iterator.
  87527. * \assert
  87528. * \code iterator != NULL \endcode
  87529. * \a iterator has been successfully initialized with
  87530. * FLAC__metadata_iterator_init()
  87531. * \retval FLAC__StreamMetadata*
  87532. * The current metadata block.
  87533. */
  87534. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  87535. /** Set the metadata block at the current position, replacing the existing
  87536. * block. The new block passed in becomes owned by the chain and it will be
  87537. * deleted when the chain is deleted.
  87538. *
  87539. * \param iterator A pointer to an existing initialized iterator.
  87540. * \param block A pointer to a metadata block.
  87541. * \assert
  87542. * \code iterator != NULL \endcode
  87543. * \a iterator has been successfully initialized with
  87544. * FLAC__metadata_iterator_init()
  87545. * \code block != NULL \endcode
  87546. * \retval FLAC__bool
  87547. * \c false if the conditions in the above description are not met, or
  87548. * a memory allocation error occurs, otherwise \c true.
  87549. */
  87550. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  87551. /** Removes the current block from the chain. If \a replace_with_padding is
  87552. * \c true, the block will instead be replaced with a padding block of equal
  87553. * size. You can not delete the STREAMINFO block. The iterator will be
  87554. * left pointing to the block before the one just "deleted", even if
  87555. * \a replace_with_padding is \c true.
  87556. *
  87557. * \param iterator A pointer to an existing initialized iterator.
  87558. * \param replace_with_padding See above.
  87559. * \assert
  87560. * \code iterator != NULL \endcode
  87561. * \a iterator has been successfully initialized with
  87562. * FLAC__metadata_iterator_init()
  87563. * \retval FLAC__bool
  87564. * \c false if the conditions in the above description are not met,
  87565. * otherwise \c true.
  87566. */
  87567. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  87568. /** Insert a new block before the current block. You cannot insert a block
  87569. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  87570. * as there can be only one, the one that already exists at the head when you
  87571. * read in a chain. The chain takes ownership of the new block and it will be
  87572. * deleted when the chain is deleted. The iterator will be left pointing to
  87573. * the new block.
  87574. *
  87575. * \param iterator A pointer to an existing initialized iterator.
  87576. * \param block A pointer to a metadata block to insert.
  87577. * \assert
  87578. * \code iterator != NULL \endcode
  87579. * \a iterator has been successfully initialized with
  87580. * FLAC__metadata_iterator_init()
  87581. * \retval FLAC__bool
  87582. * \c false if the conditions in the above description are not met, or
  87583. * a memory allocation error occurs, otherwise \c true.
  87584. */
  87585. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  87586. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  87587. * block as there can be only one, the one that already exists at the head when
  87588. * you read in a chain. The chain takes ownership of the new block and it will
  87589. * be deleted when the chain is deleted. The iterator will be left pointing to
  87590. * the new block.
  87591. *
  87592. * \param iterator A pointer to an existing initialized iterator.
  87593. * \param block A pointer to a metadata block to insert.
  87594. * \assert
  87595. * \code iterator != NULL \endcode
  87596. * \a iterator has been successfully initialized with
  87597. * FLAC__metadata_iterator_init()
  87598. * \retval FLAC__bool
  87599. * \c false if the conditions in the above description are not met, or
  87600. * a memory allocation error occurs, otherwise \c true.
  87601. */
  87602. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  87603. /* \} */
  87604. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  87605. * \ingroup flac_metadata
  87606. *
  87607. * \brief
  87608. * This module contains methods for manipulating FLAC metadata objects.
  87609. *
  87610. * Since many are variable length we have to be careful about the memory
  87611. * management. We decree that all pointers to data in the object are
  87612. * owned by the object and memory-managed by the object.
  87613. *
  87614. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  87615. * functions to create all instances. When using the
  87616. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  87617. * \a copy to \c true to have the function make it's own copy of the data, or
  87618. * to \c false to give the object ownership of your data. In the latter case
  87619. * your pointer must be freeable by free() and will be free()d when the object
  87620. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  87621. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  87622. * the length argument is 0 and the \a copy argument is \c false.
  87623. *
  87624. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  87625. * will return \c NULL in the case of a memory allocation error, otherwise a new
  87626. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  87627. * case of a memory allocation error.
  87628. *
  87629. * We don't have the convenience of C++ here, so note that the library relies
  87630. * on you to keep the types straight. In other words, if you pass, for
  87631. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  87632. * FLAC__metadata_object_application_set_data(), you will get an assertion
  87633. * failure.
  87634. *
  87635. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  87636. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  87637. * toward the length or stored in the stream, but it can make working with plain
  87638. * comments (those that don't contain embedded-NULs in the value) easier.
  87639. * Entries passed into these functions have trailing NULs added if missing, and
  87640. * returned entries are guaranteed to have a trailing NUL.
  87641. *
  87642. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  87643. * comment entry/name/value will first validate that it complies with the Vorbis
  87644. * comment specification and return false if it does not.
  87645. *
  87646. * There is no need to recalculate the length field on metadata blocks you
  87647. * have modified. They will be calculated automatically before they are
  87648. * written back to a file.
  87649. *
  87650. * \{
  87651. */
  87652. /** Create a new metadata object instance of the given type.
  87653. *
  87654. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  87655. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  87656. * the vendor string set (but zero comments).
  87657. *
  87658. * Do not pass in a value greater than or equal to
  87659. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  87660. * doing.
  87661. *
  87662. * \param type Type of object to create
  87663. * \retval FLAC__StreamMetadata*
  87664. * \c NULL if there was an error allocating memory or the type code is
  87665. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  87666. */
  87667. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  87668. /** Create a copy of an existing metadata object.
  87669. *
  87670. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  87671. * object is also copied. The caller takes ownership of the new block and
  87672. * is responsible for freeing it with FLAC__metadata_object_delete().
  87673. *
  87674. * \param object Pointer to object to copy.
  87675. * \assert
  87676. * \code object != NULL \endcode
  87677. * \retval FLAC__StreamMetadata*
  87678. * \c NULL if there was an error allocating memory, else the new instance.
  87679. */
  87680. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  87681. /** Free a metadata object. Deletes the object pointed to by \a object.
  87682. *
  87683. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  87684. * object is also deleted.
  87685. *
  87686. * \param object A pointer to an existing object.
  87687. * \assert
  87688. * \code object != NULL \endcode
  87689. */
  87690. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  87691. /** Compares two metadata objects.
  87692. *
  87693. * The compare is "deep", i.e. dynamically allocated data within the
  87694. * object is also compared.
  87695. *
  87696. * \param block1 A pointer to an existing object.
  87697. * \param block2 A pointer to an existing object.
  87698. * \assert
  87699. * \code block1 != NULL \endcode
  87700. * \code block2 != NULL \endcode
  87701. * \retval FLAC__bool
  87702. * \c true if objects are identical, else \c false.
  87703. */
  87704. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  87705. /** Sets the application data of an APPLICATION block.
  87706. *
  87707. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  87708. * takes ownership of the pointer. The existing data will be freed if this
  87709. * function is successful, otherwise the original data will remain if \a copy
  87710. * is \c true and malloc() fails.
  87711. *
  87712. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  87713. *
  87714. * \param object A pointer to an existing APPLICATION object.
  87715. * \param data A pointer to the data to set.
  87716. * \param length The length of \a data in bytes.
  87717. * \param copy See above.
  87718. * \assert
  87719. * \code object != NULL \endcode
  87720. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  87721. * \code (data != NULL && length > 0) ||
  87722. * (data == NULL && length == 0 && copy == false) \endcode
  87723. * \retval FLAC__bool
  87724. * \c false if \a copy is \c true and malloc() fails, else \c true.
  87725. */
  87726. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  87727. /** Resize the seekpoint array.
  87728. *
  87729. * If the size shrinks, elements will truncated; if it grows, new placeholder
  87730. * points will be added to the end.
  87731. *
  87732. * \param object A pointer to an existing SEEKTABLE object.
  87733. * \param new_num_points The desired length of the array; may be \c 0.
  87734. * \assert
  87735. * \code object != NULL \endcode
  87736. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87737. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  87738. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  87739. * \retval FLAC__bool
  87740. * \c false if memory allocation error, else \c true.
  87741. */
  87742. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  87743. /** Set a seekpoint in a seektable.
  87744. *
  87745. * \param object A pointer to an existing SEEKTABLE object.
  87746. * \param point_num Index into seekpoint array to set.
  87747. * \param point The point to set.
  87748. * \assert
  87749. * \code object != NULL \endcode
  87750. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87751. * \code object->data.seek_table.num_points > point_num \endcode
  87752. */
  87753. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  87754. /** Insert a seekpoint into a seektable.
  87755. *
  87756. * \param object A pointer to an existing SEEKTABLE object.
  87757. * \param point_num Index into seekpoint array to set.
  87758. * \param point The point to set.
  87759. * \assert
  87760. * \code object != NULL \endcode
  87761. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87762. * \code object->data.seek_table.num_points >= point_num \endcode
  87763. * \retval FLAC__bool
  87764. * \c false if memory allocation error, else \c true.
  87765. */
  87766. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  87767. /** Delete a seekpoint from a seektable.
  87768. *
  87769. * \param object A pointer to an existing SEEKTABLE object.
  87770. * \param point_num Index into seekpoint array to set.
  87771. * \assert
  87772. * \code object != NULL \endcode
  87773. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87774. * \code object->data.seek_table.num_points > point_num \endcode
  87775. * \retval FLAC__bool
  87776. * \c false if memory allocation error, else \c true.
  87777. */
  87778. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  87779. /** Check a seektable to see if it conforms to the FLAC specification.
  87780. * See the format specification for limits on the contents of the
  87781. * seektable.
  87782. *
  87783. * \param object A pointer to an existing SEEKTABLE object.
  87784. * \assert
  87785. * \code object != NULL \endcode
  87786. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87787. * \retval FLAC__bool
  87788. * \c false if seek table is illegal, else \c true.
  87789. */
  87790. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  87791. /** Append a number of placeholder points to the end of a seek table.
  87792. *
  87793. * \note
  87794. * As with the other ..._seektable_template_... functions, you should
  87795. * call FLAC__metadata_object_seektable_template_sort() when finished
  87796. * to make the seek table legal.
  87797. *
  87798. * \param object A pointer to an existing SEEKTABLE object.
  87799. * \param num The number of placeholder points to append.
  87800. * \assert
  87801. * \code object != NULL \endcode
  87802. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87803. * \retval FLAC__bool
  87804. * \c false if memory allocation fails, else \c true.
  87805. */
  87806. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  87807. /** Append a specific seek point template to the end of a seek table.
  87808. *
  87809. * \note
  87810. * As with the other ..._seektable_template_... functions, you should
  87811. * call FLAC__metadata_object_seektable_template_sort() when finished
  87812. * to make the seek table legal.
  87813. *
  87814. * \param object A pointer to an existing SEEKTABLE object.
  87815. * \param sample_number The sample number of the seek point template.
  87816. * \assert
  87817. * \code object != NULL \endcode
  87818. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87819. * \retval FLAC__bool
  87820. * \c false if memory allocation fails, else \c true.
  87821. */
  87822. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  87823. /** Append specific seek point templates to the end of a seek table.
  87824. *
  87825. * \note
  87826. * As with the other ..._seektable_template_... functions, you should
  87827. * call FLAC__metadata_object_seektable_template_sort() when finished
  87828. * to make the seek table legal.
  87829. *
  87830. * \param object A pointer to an existing SEEKTABLE object.
  87831. * \param sample_numbers An array of sample numbers for the seek points.
  87832. * \param num The number of seek point templates to append.
  87833. * \assert
  87834. * \code object != NULL \endcode
  87835. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87836. * \retval FLAC__bool
  87837. * \c false if memory allocation fails, else \c true.
  87838. */
  87839. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  87840. /** Append a set of evenly-spaced seek point templates to the end of a
  87841. * seek table.
  87842. *
  87843. * \note
  87844. * As with the other ..._seektable_template_... functions, you should
  87845. * call FLAC__metadata_object_seektable_template_sort() when finished
  87846. * to make the seek table legal.
  87847. *
  87848. * \param object A pointer to an existing SEEKTABLE object.
  87849. * \param num The number of placeholder points to append.
  87850. * \param total_samples The total number of samples to be encoded;
  87851. * the seekpoints will be spaced approximately
  87852. * \a total_samples / \a num samples apart.
  87853. * \assert
  87854. * \code object != NULL \endcode
  87855. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87856. * \code total_samples > 0 \endcode
  87857. * \retval FLAC__bool
  87858. * \c false if memory allocation fails, else \c true.
  87859. */
  87860. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  87861. /** Append a set of evenly-spaced seek point templates to the end of a
  87862. * seek table.
  87863. *
  87864. * \note
  87865. * As with the other ..._seektable_template_... functions, you should
  87866. * call FLAC__metadata_object_seektable_template_sort() when finished
  87867. * to make the seek table legal.
  87868. *
  87869. * \param object A pointer to an existing SEEKTABLE object.
  87870. * \param samples The number of samples apart to space the placeholder
  87871. * points. The first point will be at sample \c 0, the
  87872. * second at sample \a samples, then 2*\a samples, and
  87873. * so on. As long as \a samples and \a total_samples
  87874. * are greater than \c 0, there will always be at least
  87875. * one seekpoint at sample \c 0.
  87876. * \param total_samples The total number of samples to be encoded;
  87877. * the seekpoints will be spaced
  87878. * \a samples samples apart.
  87879. * \assert
  87880. * \code object != NULL \endcode
  87881. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87882. * \code samples > 0 \endcode
  87883. * \code total_samples > 0 \endcode
  87884. * \retval FLAC__bool
  87885. * \c false if memory allocation fails, else \c true.
  87886. */
  87887. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  87888. /** Sort a seek table's seek points according to the format specification,
  87889. * removing duplicates.
  87890. *
  87891. * \param object A pointer to a seek table to be sorted.
  87892. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  87893. * If \c true, duplicates are deleted and the seek table is
  87894. * shrunk appropriately; the number of placeholder points
  87895. * present in the seek table will be the same after the call
  87896. * as before.
  87897. * \assert
  87898. * \code object != NULL \endcode
  87899. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  87900. * \retval FLAC__bool
  87901. * \c false if realloc() fails, else \c true.
  87902. */
  87903. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  87904. /** Sets the vendor string in a VORBIS_COMMENT block.
  87905. *
  87906. * For convenience, a trailing NUL is added to the entry if it doesn't have
  87907. * one already.
  87908. *
  87909. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  87910. * takes ownership of the \c entry.entry pointer.
  87911. *
  87912. * \note If this function returns \c false, the caller still owns the
  87913. * pointer.
  87914. *
  87915. * \param object A pointer to an existing VORBIS_COMMENT object.
  87916. * \param entry The entry to set the vendor string to.
  87917. * \param copy See above.
  87918. * \assert
  87919. * \code object != NULL \endcode
  87920. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  87921. * \code (entry.entry != NULL && entry.length > 0) ||
  87922. * (entry.entry == NULL && entry.length == 0) \endcode
  87923. * \retval FLAC__bool
  87924. * \c false if memory allocation fails or \a entry does not comply with the
  87925. * Vorbis comment specification, else \c true.
  87926. */
  87927. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  87928. /** Resize the comment array.
  87929. *
  87930. * If the size shrinks, elements will truncated; if it grows, new empty
  87931. * fields will be added to the end.
  87932. *
  87933. * \param object A pointer to an existing VORBIS_COMMENT object.
  87934. * \param new_num_comments The desired length of the array; may be \c 0.
  87935. * \assert
  87936. * \code object != NULL \endcode
  87937. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  87938. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  87939. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  87940. * \retval FLAC__bool
  87941. * \c false if memory allocation fails, else \c true.
  87942. */
  87943. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  87944. /** Sets a comment in a VORBIS_COMMENT block.
  87945. *
  87946. * For convenience, a trailing NUL is added to the entry if it doesn't have
  87947. * one already.
  87948. *
  87949. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  87950. * takes ownership of the \c entry.entry pointer.
  87951. *
  87952. * \note If this function returns \c false, the caller still owns the
  87953. * pointer.
  87954. *
  87955. * \param object A pointer to an existing VORBIS_COMMENT object.
  87956. * \param comment_num Index into comment array to set.
  87957. * \param entry The entry to set the comment to.
  87958. * \param copy See above.
  87959. * \assert
  87960. * \code object != NULL \endcode
  87961. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  87962. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  87963. * \code (entry.entry != NULL && entry.length > 0) ||
  87964. * (entry.entry == NULL && entry.length == 0) \endcode
  87965. * \retval FLAC__bool
  87966. * \c false if memory allocation fails or \a entry does not comply with the
  87967. * Vorbis comment specification, else \c true.
  87968. */
  87969. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  87970. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  87971. *
  87972. * For convenience, a trailing NUL is added to the entry if it doesn't have
  87973. * one already.
  87974. *
  87975. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  87976. * takes ownership of the \c entry.entry pointer.
  87977. *
  87978. * \note If this function returns \c false, the caller still owns the
  87979. * pointer.
  87980. *
  87981. * \param object A pointer to an existing VORBIS_COMMENT object.
  87982. * \param comment_num The index at which to insert the comment. The comments
  87983. * at and after \a comment_num move right one position.
  87984. * To append a comment to the end, set \a comment_num to
  87985. * \c object->data.vorbis_comment.num_comments .
  87986. * \param entry The comment to insert.
  87987. * \param copy See above.
  87988. * \assert
  87989. * \code object != NULL \endcode
  87990. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  87991. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  87992. * \code (entry.entry != NULL && entry.length > 0) ||
  87993. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  87994. * \retval FLAC__bool
  87995. * \c false if memory allocation fails or \a entry does not comply with the
  87996. * Vorbis comment specification, else \c true.
  87997. */
  87998. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  87999. /** Appends a comment to a VORBIS_COMMENT block.
  88000. *
  88001. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88002. * one already.
  88003. *
  88004. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88005. * takes ownership of the \c entry.entry pointer.
  88006. *
  88007. * \note If this function returns \c false, the caller still owns the
  88008. * pointer.
  88009. *
  88010. * \param object A pointer to an existing VORBIS_COMMENT object.
  88011. * \param entry The comment to insert.
  88012. * \param copy See above.
  88013. * \assert
  88014. * \code object != NULL \endcode
  88015. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88016. * \code (entry.entry != NULL && entry.length > 0) ||
  88017. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88018. * \retval FLAC__bool
  88019. * \c false if memory allocation fails or \a entry does not comply with the
  88020. * Vorbis comment specification, else \c true.
  88021. */
  88022. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88023. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  88024. *
  88025. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88026. * one already.
  88027. *
  88028. * Depending on the the value of \a all, either all or just the first comment
  88029. * whose field name(s) match the given entry's name will be replaced by the
  88030. * given entry. If no comments match, \a entry will simply be appended.
  88031. *
  88032. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88033. * takes ownership of the \c entry.entry pointer.
  88034. *
  88035. * \note If this function returns \c false, the caller still owns the
  88036. * pointer.
  88037. *
  88038. * \param object A pointer to an existing VORBIS_COMMENT object.
  88039. * \param entry The comment to insert.
  88040. * \param all If \c true, all comments whose field name matches
  88041. * \a entry's field name will be removed, and \a entry will
  88042. * be inserted at the position of the first matching
  88043. * comment. If \c false, only the first comment whose
  88044. * field name matches \a entry's field name will be
  88045. * replaced with \a entry.
  88046. * \param copy See above.
  88047. * \assert
  88048. * \code object != NULL \endcode
  88049. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88050. * \code (entry.entry != NULL && entry.length > 0) ||
  88051. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88052. * \retval FLAC__bool
  88053. * \c false if memory allocation fails or \a entry does not comply with the
  88054. * Vorbis comment specification, else \c true.
  88055. */
  88056. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  88057. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  88058. *
  88059. * \param object A pointer to an existing VORBIS_COMMENT object.
  88060. * \param comment_num The index of the comment to delete.
  88061. * \assert
  88062. * \code object != NULL \endcode
  88063. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88064. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  88065. * \retval FLAC__bool
  88066. * \c false if realloc() fails, else \c true.
  88067. */
  88068. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  88069. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  88070. *
  88071. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  88072. * memory and shall be owned by the caller. For convenience the entry will
  88073. * have a terminating NUL.
  88074. *
  88075. * \param entry A pointer to a Vorbis comment entry. The entry's
  88076. * \c entry pointer should not point to allocated
  88077. * memory as it will be overwritten.
  88078. * \param field_name The field name in ASCII, \c NUL terminated.
  88079. * \param field_value The field value in UTF-8, \c NUL terminated.
  88080. * \assert
  88081. * \code entry != NULL \endcode
  88082. * \code field_name != NULL \endcode
  88083. * \code field_value != NULL \endcode
  88084. * \retval FLAC__bool
  88085. * \c false if malloc() fails, or if \a field_name or \a field_value does
  88086. * not comply with the Vorbis comment specification, else \c true.
  88087. */
  88088. 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);
  88089. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  88090. *
  88091. * The returned pointers to name and value will be allocated by malloc()
  88092. * and shall be owned by the caller.
  88093. *
  88094. * \param entry An existing Vorbis comment entry.
  88095. * \param field_name The address of where the returned pointer to the
  88096. * field name will be stored.
  88097. * \param field_value The address of where the returned pointer to the
  88098. * field value will be stored.
  88099. * \assert
  88100. * \code (entry.entry != NULL && entry.length > 0) \endcode
  88101. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  88102. * \code field_name != NULL \endcode
  88103. * \code field_value != NULL \endcode
  88104. * \retval FLAC__bool
  88105. * \c false if memory allocation fails or \a entry does not comply with the
  88106. * Vorbis comment specification, else \c true.
  88107. */
  88108. 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);
  88109. /** Check if the given Vorbis comment entry's field name matches the given
  88110. * field name.
  88111. *
  88112. * \param entry An existing Vorbis comment entry.
  88113. * \param field_name The field name to check.
  88114. * \param field_name_length The length of \a field_name, not including the
  88115. * terminating \c NUL.
  88116. * \assert
  88117. * \code (entry.entry != NULL && entry.length > 0) \endcode
  88118. * \retval FLAC__bool
  88119. * \c true if the field names match, else \c false
  88120. */
  88121. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  88122. /** Find a Vorbis comment with the given field name.
  88123. *
  88124. * The search begins at entry number \a offset; use an offset of 0 to
  88125. * search from the beginning of the comment array.
  88126. *
  88127. * \param object A pointer to an existing VORBIS_COMMENT object.
  88128. * \param offset The offset into the comment array from where to start
  88129. * the search.
  88130. * \param field_name The field name of the comment to find.
  88131. * \assert
  88132. * \code object != NULL \endcode
  88133. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88134. * \code field_name != NULL \endcode
  88135. * \retval int
  88136. * The offset in the comment array of the first comment whose field
  88137. * name matches \a field_name, or \c -1 if no match was found.
  88138. */
  88139. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  88140. /** Remove first Vorbis comment matching the given field name.
  88141. *
  88142. * \param object A pointer to an existing VORBIS_COMMENT object.
  88143. * \param field_name The field name of comment to delete.
  88144. * \assert
  88145. * \code object != NULL \endcode
  88146. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88147. * \retval int
  88148. * \c -1 for memory allocation error, \c 0 for no matching entries,
  88149. * \c 1 for one matching entry deleted.
  88150. */
  88151. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  88152. /** Remove all Vorbis comments matching the given field name.
  88153. *
  88154. * \param object A pointer to an existing VORBIS_COMMENT object.
  88155. * \param field_name The field name of comments to delete.
  88156. * \assert
  88157. * \code object != NULL \endcode
  88158. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88159. * \retval int
  88160. * \c -1 for memory allocation error, \c 0 for no matching entries,
  88161. * else the number of matching entries deleted.
  88162. */
  88163. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  88164. /** Create a new CUESHEET track instance.
  88165. *
  88166. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  88167. *
  88168. * \retval FLAC__StreamMetadata_CueSheet_Track*
  88169. * \c NULL if there was an error allocating memory, else the new instance.
  88170. */
  88171. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  88172. /** Create a copy of an existing CUESHEET track object.
  88173. *
  88174. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  88175. * object is also copied. The caller takes ownership of the new object and
  88176. * is responsible for freeing it with
  88177. * FLAC__metadata_object_cuesheet_track_delete().
  88178. *
  88179. * \param object Pointer to object to copy.
  88180. * \assert
  88181. * \code object != NULL \endcode
  88182. * \retval FLAC__StreamMetadata_CueSheet_Track*
  88183. * \c NULL if there was an error allocating memory, else the new instance.
  88184. */
  88185. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  88186. /** Delete a CUESHEET track object
  88187. *
  88188. * \param object A pointer to an existing CUESHEET track object.
  88189. * \assert
  88190. * \code object != NULL \endcode
  88191. */
  88192. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  88193. /** Resize a track's index point array.
  88194. *
  88195. * If the size shrinks, elements will truncated; if it grows, new blank
  88196. * indices will be added to the end.
  88197. *
  88198. * \param object A pointer to an existing CUESHEET object.
  88199. * \param track_num The index of the track to modify. NOTE: this is not
  88200. * necessarily the same as the track's \a number field.
  88201. * \param new_num_indices The desired length of the array; may be \c 0.
  88202. * \assert
  88203. * \code object != NULL \endcode
  88204. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88205. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88206. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  88207. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  88208. * \retval FLAC__bool
  88209. * \c false if memory allocation error, else \c true.
  88210. */
  88211. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  88212. /** Insert an index point in a CUESHEET track at the given index.
  88213. *
  88214. * \param object A pointer to an existing CUESHEET object.
  88215. * \param track_num The index of the track to modify. NOTE: this is not
  88216. * necessarily the same as the track's \a number field.
  88217. * \param index_num The index into the track's index array at which to
  88218. * insert the index point. NOTE: this is not necessarily
  88219. * the same as the index point's \a number field. The
  88220. * indices at and after \a index_num move right one
  88221. * position. To append an index point to the end, set
  88222. * \a index_num to
  88223. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  88224. * \param index The index point to insert.
  88225. * \assert
  88226. * \code object != NULL \endcode
  88227. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88228. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88229. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  88230. * \retval FLAC__bool
  88231. * \c false if realloc() fails, else \c true.
  88232. */
  88233. 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);
  88234. /** Insert a blank index point in a CUESHEET track at the given index.
  88235. *
  88236. * A blank index point is one in which all field values are zero.
  88237. *
  88238. * \param object A pointer to an existing CUESHEET object.
  88239. * \param track_num The index of the track to modify. NOTE: this is not
  88240. * necessarily the same as the track's \a number field.
  88241. * \param index_num The index into the track's index array at which to
  88242. * insert the index point. NOTE: this is not necessarily
  88243. * the same as the index point's \a number field. The
  88244. * indices at and after \a index_num move right one
  88245. * position. To append an index point to the end, set
  88246. * \a index_num to
  88247. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  88248. * \assert
  88249. * \code object != NULL \endcode
  88250. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88251. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88252. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  88253. * \retval FLAC__bool
  88254. * \c false if realloc() fails, else \c true.
  88255. */
  88256. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  88257. /** Delete an index point in a CUESHEET track at the given index.
  88258. *
  88259. * \param object A pointer to an existing CUESHEET object.
  88260. * \param track_num The index into the track array of the track to
  88261. * modify. NOTE: this is not necessarily the same
  88262. * as the track's \a number field.
  88263. * \param index_num The index into the track's index array of the index
  88264. * to delete. NOTE: this is not necessarily the same
  88265. * as the index's \a number field.
  88266. * \assert
  88267. * \code object != NULL \endcode
  88268. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88269. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88270. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  88271. * \retval FLAC__bool
  88272. * \c false if realloc() fails, else \c true.
  88273. */
  88274. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  88275. /** Resize the track array.
  88276. *
  88277. * If the size shrinks, elements will truncated; if it grows, new blank
  88278. * tracks will be added to the end.
  88279. *
  88280. * \param object A pointer to an existing CUESHEET object.
  88281. * \param new_num_tracks The desired length of the array; may be \c 0.
  88282. * \assert
  88283. * \code object != NULL \endcode
  88284. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88285. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  88286. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  88287. * \retval FLAC__bool
  88288. * \c false if memory allocation error, else \c true.
  88289. */
  88290. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  88291. /** Sets a track in a CUESHEET block.
  88292. *
  88293. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  88294. * takes ownership of the \a track pointer.
  88295. *
  88296. * \param object A pointer to an existing CUESHEET object.
  88297. * \param track_num Index into track array to set. NOTE: this is not
  88298. * necessarily the same as the track's \a number field.
  88299. * \param track The track to set the track to. You may safely pass in
  88300. * a const pointer if \a copy is \c true.
  88301. * \param copy See above.
  88302. * \assert
  88303. * \code object != NULL \endcode
  88304. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88305. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  88306. * \code (track->indices != NULL && track->num_indices > 0) ||
  88307. * (track->indices == NULL && track->num_indices == 0)
  88308. * \retval FLAC__bool
  88309. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88310. */
  88311. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  88312. /** Insert a track in a CUESHEET block at the given index.
  88313. *
  88314. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  88315. * takes ownership of the \a track pointer.
  88316. *
  88317. * \param object A pointer to an existing CUESHEET object.
  88318. * \param track_num The index at which to insert the track. NOTE: this
  88319. * is not necessarily the same as the track's \a number
  88320. * field. The tracks at and after \a track_num move right
  88321. * one position. To append a track to the end, set
  88322. * \a track_num to \c object->data.cue_sheet.num_tracks .
  88323. * \param track The track to insert. You may safely pass in a const
  88324. * pointer if \a copy is \c true.
  88325. * \param copy See above.
  88326. * \assert
  88327. * \code object != NULL \endcode
  88328. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88329. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  88330. * \retval FLAC__bool
  88331. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88332. */
  88333. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  88334. /** Insert a blank track in a CUESHEET block at the given index.
  88335. *
  88336. * A blank track is one in which all field values are zero.
  88337. *
  88338. * \param object A pointer to an existing CUESHEET object.
  88339. * \param track_num The index at which to insert the track. NOTE: this
  88340. * is not necessarily the same as the track's \a number
  88341. * field. The tracks at and after \a track_num move right
  88342. * one position. To append a track to the end, set
  88343. * \a track_num to \c object->data.cue_sheet.num_tracks .
  88344. * \assert
  88345. * \code object != NULL \endcode
  88346. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88347. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  88348. * \retval FLAC__bool
  88349. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88350. */
  88351. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  88352. /** Delete a track in a CUESHEET block at the given index.
  88353. *
  88354. * \param object A pointer to an existing CUESHEET object.
  88355. * \param track_num The index into the track array of the track to
  88356. * delete. NOTE: this is not necessarily the same
  88357. * as the track's \a number field.
  88358. * \assert
  88359. * \code object != NULL \endcode
  88360. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88361. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88362. * \retval FLAC__bool
  88363. * \c false if realloc() fails, else \c true.
  88364. */
  88365. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  88366. /** Check a cue sheet to see if it conforms to the FLAC specification.
  88367. * See the format specification for limits on the contents of the
  88368. * cue sheet.
  88369. *
  88370. * \param object A pointer to an existing CUESHEET object.
  88371. * \param check_cd_da_subset If \c true, check CUESHEET against more
  88372. * stringent requirements for a CD-DA (audio) disc.
  88373. * \param violation Address of a pointer to a string. If there is a
  88374. * violation, a pointer to a string explanation of the
  88375. * violation will be returned here. \a violation may be
  88376. * \c NULL if you don't need the returned string. Do not
  88377. * free the returned string; it will always point to static
  88378. * data.
  88379. * \assert
  88380. * \code object != NULL \endcode
  88381. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88382. * \retval FLAC__bool
  88383. * \c false if cue sheet is illegal, else \c true.
  88384. */
  88385. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  88386. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  88387. * assumes the cue sheet corresponds to a CD; the result is undefined
  88388. * if the cuesheet's is_cd bit is not set.
  88389. *
  88390. * \param object A pointer to an existing CUESHEET object.
  88391. * \assert
  88392. * \code object != NULL \endcode
  88393. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88394. * \retval FLAC__uint32
  88395. * The unsigned integer representation of the CDDB/freedb ID
  88396. */
  88397. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  88398. /** Sets the MIME type of a PICTURE block.
  88399. *
  88400. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  88401. * takes ownership of the pointer. The existing string will be freed if this
  88402. * function is successful, otherwise the original string will remain if \a copy
  88403. * is \c true and malloc() fails.
  88404. *
  88405. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  88406. *
  88407. * \param object A pointer to an existing PICTURE object.
  88408. * \param mime_type A pointer to the MIME type string. The string must be
  88409. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  88410. * is done.
  88411. * \param copy See above.
  88412. * \assert
  88413. * \code object != NULL \endcode
  88414. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  88415. * \code (mime_type != NULL) \endcode
  88416. * \retval FLAC__bool
  88417. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88418. */
  88419. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  88420. /** Sets the description of a PICTURE block.
  88421. *
  88422. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  88423. * takes ownership of the pointer. The existing string will be freed if this
  88424. * function is successful, otherwise the original string will remain if \a copy
  88425. * is \c true and malloc() fails.
  88426. *
  88427. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  88428. *
  88429. * \param object A pointer to an existing PICTURE object.
  88430. * \param description A pointer to the description string. The string must be
  88431. * valid UTF-8, NUL-terminated. No validation is done.
  88432. * \param copy See above.
  88433. * \assert
  88434. * \code object != NULL \endcode
  88435. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  88436. * \code (description != NULL) \endcode
  88437. * \retval FLAC__bool
  88438. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88439. */
  88440. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  88441. /** Sets the picture data of a PICTURE block.
  88442. *
  88443. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  88444. * takes ownership of the pointer. Also sets the \a data_length field of the
  88445. * metadata object to what is passed in as the \a length parameter. The
  88446. * existing data will be freed if this function is successful, otherwise the
  88447. * original data and data_length will remain if \a copy is \c true and
  88448. * malloc() fails.
  88449. *
  88450. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  88451. *
  88452. * \param object A pointer to an existing PICTURE object.
  88453. * \param data A pointer to the data to set.
  88454. * \param length The length of \a data in bytes.
  88455. * \param copy See above.
  88456. * \assert
  88457. * \code object != NULL \endcode
  88458. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  88459. * \code (data != NULL && length > 0) ||
  88460. * (data == NULL && length == 0 && copy == false) \endcode
  88461. * \retval FLAC__bool
  88462. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88463. */
  88464. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  88465. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  88466. * See the format specification for limits on the contents of the
  88467. * PICTURE block.
  88468. *
  88469. * \param object A pointer to existing PICTURE block to be checked.
  88470. * \param violation Address of a pointer to a string. If there is a
  88471. * violation, a pointer to a string explanation of the
  88472. * violation will be returned here. \a violation may be
  88473. * \c NULL if you don't need the returned string. Do not
  88474. * free the returned string; it will always point to static
  88475. * data.
  88476. * \assert
  88477. * \code object != NULL \endcode
  88478. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  88479. * \retval FLAC__bool
  88480. * \c false if PICTURE block is illegal, else \c true.
  88481. */
  88482. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  88483. /* \} */
  88484. #ifdef __cplusplus
  88485. }
  88486. #endif
  88487. #endif
  88488. /*** End of inlined file: metadata.h ***/
  88489. /*** Start of inlined file: stream_decoder.h ***/
  88490. #ifndef FLAC__STREAM_DECODER_H
  88491. #define FLAC__STREAM_DECODER_H
  88492. #include <stdio.h> /* for FILE */
  88493. #ifdef __cplusplus
  88494. extern "C" {
  88495. #endif
  88496. /** \file include/FLAC/stream_decoder.h
  88497. *
  88498. * \brief
  88499. * This module contains the functions which implement the stream
  88500. * decoder.
  88501. *
  88502. * See the detailed documentation in the
  88503. * \link flac_stream_decoder stream decoder \endlink module.
  88504. */
  88505. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  88506. * \ingroup flac
  88507. *
  88508. * \brief
  88509. * This module describes the decoder layers provided by libFLAC.
  88510. *
  88511. * The stream decoder can be used to decode complete streams either from
  88512. * the client via callbacks, or directly from a file, depending on how
  88513. * it is initialized. When decoding via callbacks, the client provides
  88514. * callbacks for reading FLAC data and writing decoded samples, and
  88515. * handling metadata and errors. If the client also supplies seek-related
  88516. * callback, the decoder function for sample-accurate seeking within the
  88517. * FLAC input is also available. When decoding from a file, the client
  88518. * needs only supply a filename or open \c FILE* and write/metadata/error
  88519. * callbacks; the rest of the callbacks are supplied internally. For more
  88520. * info see the \link flac_stream_decoder stream decoder \endlink module.
  88521. */
  88522. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  88523. * \ingroup flac_decoder
  88524. *
  88525. * \brief
  88526. * This module contains the functions which implement the stream
  88527. * decoder.
  88528. *
  88529. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  88530. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  88531. *
  88532. * The basic usage of this decoder is as follows:
  88533. * - The program creates an instance of a decoder using
  88534. * FLAC__stream_decoder_new().
  88535. * - The program overrides the default settings using
  88536. * FLAC__stream_decoder_set_*() functions.
  88537. * - The program initializes the instance to validate the settings and
  88538. * prepare for decoding using
  88539. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  88540. * or FLAC__stream_decoder_init_file() for native FLAC,
  88541. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  88542. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  88543. * - The program calls the FLAC__stream_decoder_process_*() functions
  88544. * to decode data, which subsequently calls the callbacks.
  88545. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  88546. * which flushes the input and output and resets the decoder to the
  88547. * uninitialized state.
  88548. * - The instance may be used again or deleted with
  88549. * FLAC__stream_decoder_delete().
  88550. *
  88551. * In more detail, the program will create a new instance by calling
  88552. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  88553. * functions to override the default decoder options, and call
  88554. * one of the FLAC__stream_decoder_init_*() functions.
  88555. *
  88556. * There are three initialization functions for native FLAC, one for
  88557. * setting up the decoder to decode FLAC data from the client via
  88558. * callbacks, and two for decoding directly from a FLAC file.
  88559. *
  88560. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  88561. * You must also supply several callbacks for handling I/O. Some (like
  88562. * seeking) are optional, depending on the capabilities of the input.
  88563. *
  88564. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  88565. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  88566. * \c FILE* or filename and fewer callbacks; the decoder will handle
  88567. * the other callbacks internally.
  88568. *
  88569. * There are three similarly-named init functions for decoding from Ogg
  88570. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  88571. * library has been built with Ogg support.
  88572. *
  88573. * Once the decoder is initialized, your program will call one of several
  88574. * functions to start the decoding process:
  88575. *
  88576. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  88577. * most one metadata block or audio frame and return, calling either the
  88578. * metadata callback or write callback, respectively, once. If the decoder
  88579. * loses sync it will return with only the error callback being called.
  88580. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  88581. * to process the stream from the current location and stop upon reaching
  88582. * the first audio frame. The client will get one metadata, write, or error
  88583. * callback per metadata block, audio frame, or sync error, respectively.
  88584. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  88585. * to process the stream from the current location until the read callback
  88586. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  88587. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  88588. * write, or error callback per metadata block, audio frame, or sync error,
  88589. * respectively.
  88590. *
  88591. * When the decoder has finished decoding (normally or through an abort),
  88592. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  88593. * ensures the decoder is in the correct state and frees memory. Then the
  88594. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  88595. * again to decode another stream.
  88596. *
  88597. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  88598. * At any point after the stream decoder has been initialized, the client can
  88599. * call this function to seek to an exact sample within the stream.
  88600. * Subsequently, the first time the write callback is called it will be
  88601. * passed a (possibly partial) block starting at that sample.
  88602. *
  88603. * If the client cannot seek via the callback interface provided, but still
  88604. * has another way of seeking, it can flush the decoder using
  88605. * FLAC__stream_decoder_flush() and start feeding data from the new position
  88606. * through the read callback.
  88607. *
  88608. * The stream decoder also provides MD5 signature checking. If this is
  88609. * turned on before initialization, FLAC__stream_decoder_finish() will
  88610. * report when the decoded MD5 signature does not match the one stored
  88611. * in the STREAMINFO block. MD5 checking is automatically turned off
  88612. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  88613. * in the STREAMINFO block or when a seek is attempted.
  88614. *
  88615. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  88616. * attention. By default, the decoder only calls the metadata_callback for
  88617. * the STREAMINFO block. These functions allow you to tell the decoder
  88618. * explicitly which blocks to parse and return via the metadata_callback
  88619. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  88620. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  88621. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  88622. * which blocks to return. Remember that metadata blocks can potentially
  88623. * be big (for example, cover art) so filtering out the ones you don't
  88624. * use can reduce the memory requirements of the decoder. Also note the
  88625. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  88626. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  88627. * filtering APPLICATION blocks based on the application ID.
  88628. *
  88629. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  88630. * they still can legally be filtered from the metadata_callback.
  88631. *
  88632. * \note
  88633. * The "set" functions may only be called when the decoder is in the
  88634. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  88635. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  88636. * before FLAC__stream_decoder_init_*(). If this is the case they will
  88637. * return \c true, otherwise \c false.
  88638. *
  88639. * \note
  88640. * FLAC__stream_decoder_finish() resets all settings to the constructor
  88641. * defaults, including the callbacks.
  88642. *
  88643. * \{
  88644. */
  88645. /** State values for a FLAC__StreamDecoder
  88646. *
  88647. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  88648. */
  88649. typedef enum {
  88650. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  88651. /**< The decoder is ready to search for metadata. */
  88652. FLAC__STREAM_DECODER_READ_METADATA,
  88653. /**< The decoder is ready to or is in the process of reading metadata. */
  88654. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  88655. /**< The decoder is ready to or is in the process of searching for the
  88656. * frame sync code.
  88657. */
  88658. FLAC__STREAM_DECODER_READ_FRAME,
  88659. /**< The decoder is ready to or is in the process of reading a frame. */
  88660. FLAC__STREAM_DECODER_END_OF_STREAM,
  88661. /**< The decoder has reached the end of the stream. */
  88662. FLAC__STREAM_DECODER_OGG_ERROR,
  88663. /**< An error occurred in the underlying Ogg layer. */
  88664. FLAC__STREAM_DECODER_SEEK_ERROR,
  88665. /**< An error occurred while seeking. The decoder must be flushed
  88666. * with FLAC__stream_decoder_flush() or reset with
  88667. * FLAC__stream_decoder_reset() before decoding can continue.
  88668. */
  88669. FLAC__STREAM_DECODER_ABORTED,
  88670. /**< The decoder was aborted by the read callback. */
  88671. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  88672. /**< An error occurred allocating memory. The decoder is in an invalid
  88673. * state and can no longer be used.
  88674. */
  88675. FLAC__STREAM_DECODER_UNINITIALIZED
  88676. /**< The decoder is in the uninitialized state; one of the
  88677. * FLAC__stream_decoder_init_*() functions must be called before samples
  88678. * can be processed.
  88679. */
  88680. } FLAC__StreamDecoderState;
  88681. /** Maps a FLAC__StreamDecoderState to a C string.
  88682. *
  88683. * Using a FLAC__StreamDecoderState as the index to this array
  88684. * will give the string equivalent. The contents should not be modified.
  88685. */
  88686. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  88687. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  88688. */
  88689. typedef enum {
  88690. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  88691. /**< Initialization was successful. */
  88692. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  88693. /**< The library was not compiled with support for the given container
  88694. * format.
  88695. */
  88696. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  88697. /**< A required callback was not supplied. */
  88698. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  88699. /**< An error occurred allocating memory. */
  88700. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  88701. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  88702. * FLAC__stream_decoder_init_ogg_file(). */
  88703. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  88704. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  88705. * already initialized, usually because
  88706. * FLAC__stream_decoder_finish() was not called.
  88707. */
  88708. } FLAC__StreamDecoderInitStatus;
  88709. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  88710. *
  88711. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  88712. * will give the string equivalent. The contents should not be modified.
  88713. */
  88714. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  88715. /** Return values for the FLAC__StreamDecoder read callback.
  88716. */
  88717. typedef enum {
  88718. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  88719. /**< The read was OK and decoding can continue. */
  88720. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  88721. /**< The read was attempted while at the end of the stream. Note that
  88722. * the client must only return this value when the read callback was
  88723. * called when already at the end of the stream. Otherwise, if the read
  88724. * itself moves to the end of the stream, the client should still return
  88725. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  88726. * the next read callback it should return
  88727. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  88728. * of \c 0.
  88729. */
  88730. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  88731. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  88732. } FLAC__StreamDecoderReadStatus;
  88733. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  88734. *
  88735. * Using a FLAC__StreamDecoderReadStatus as the index to this array
  88736. * will give the string equivalent. The contents should not be modified.
  88737. */
  88738. extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
  88739. /** Return values for the FLAC__StreamDecoder seek callback.
  88740. */
  88741. typedef enum {
  88742. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  88743. /**< The seek was OK and decoding can continue. */
  88744. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  88745. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  88746. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  88747. /**< Client does not support seeking. */
  88748. } FLAC__StreamDecoderSeekStatus;
  88749. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  88750. *
  88751. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  88752. * will give the string equivalent. The contents should not be modified.
  88753. */
  88754. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  88755. /** Return values for the FLAC__StreamDecoder tell callback.
  88756. */
  88757. typedef enum {
  88758. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  88759. /**< The tell was OK and decoding can continue. */
  88760. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  88761. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  88762. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  88763. /**< Client does not support telling the position. */
  88764. } FLAC__StreamDecoderTellStatus;
  88765. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  88766. *
  88767. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  88768. * will give the string equivalent. The contents should not be modified.
  88769. */
  88770. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  88771. /** Return values for the FLAC__StreamDecoder length callback.
  88772. */
  88773. typedef enum {
  88774. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  88775. /**< The length call was OK and decoding can continue. */
  88776. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  88777. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  88778. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  88779. /**< Client does not support reporting the length. */
  88780. } FLAC__StreamDecoderLengthStatus;
  88781. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  88782. *
  88783. * Using a FLAC__StreamDecoderLengthStatus as the index to this array
  88784. * will give the string equivalent. The contents should not be modified.
  88785. */
  88786. extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
  88787. /** Return values for the FLAC__StreamDecoder write callback.
  88788. */
  88789. typedef enum {
  88790. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  88791. /**< The write was OK and decoding can continue. */
  88792. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  88793. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  88794. } FLAC__StreamDecoderWriteStatus;
  88795. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  88796. *
  88797. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  88798. * will give the string equivalent. The contents should not be modified.
  88799. */
  88800. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  88801. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  88802. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  88803. * all. The rest could be caused by bad sync (false synchronization on
  88804. * data that is not the start of a frame) or corrupted data. The error
  88805. * itself is the decoder's best guess at what happened assuming a correct
  88806. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  88807. * could be caused by a correct sync on the start of a frame, but some
  88808. * data in the frame header was corrupted. Or it could be the result of
  88809. * syncing on a point the stream that looked like the starting of a frame
  88810. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  88811. * could be because the decoder encountered a valid frame made by a future
  88812. * version of the encoder which it cannot parse, or because of a false
  88813. * sync making it appear as though an encountered frame was generated by
  88814. * a future encoder.
  88815. */
  88816. typedef enum {
  88817. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  88818. /**< An error in the stream caused the decoder to lose synchronization. */
  88819. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  88820. /**< The decoder encountered a corrupted frame header. */
  88821. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  88822. /**< The frame's data did not match the CRC in the footer. */
  88823. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  88824. /**< The decoder encountered reserved fields in use in the stream. */
  88825. } FLAC__StreamDecoderErrorStatus;
  88826. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  88827. *
  88828. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  88829. * will give the string equivalent. The contents should not be modified.
  88830. */
  88831. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  88832. /***********************************************************************
  88833. *
  88834. * class FLAC__StreamDecoder
  88835. *
  88836. ***********************************************************************/
  88837. struct FLAC__StreamDecoderProtected;
  88838. struct FLAC__StreamDecoderPrivate;
  88839. /** The opaque structure definition for the stream decoder type.
  88840. * See the \link flac_stream_decoder stream decoder module \endlink
  88841. * for a detailed description.
  88842. */
  88843. typedef struct {
  88844. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  88845. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  88846. } FLAC__StreamDecoder;
  88847. /** Signature for the read callback.
  88848. *
  88849. * A function pointer matching this signature must be passed to
  88850. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  88851. * called when the decoder needs more input data. The address of the
  88852. * buffer to be filled is supplied, along with the number of bytes the
  88853. * buffer can hold. The callback may choose to supply less data and
  88854. * modify the byte count but must be careful not to overflow the buffer.
  88855. * The callback then returns a status code chosen from
  88856. * FLAC__StreamDecoderReadStatus.
  88857. *
  88858. * Here is an example of a read callback for stdio streams:
  88859. * \code
  88860. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  88861. * {
  88862. * FILE *file = ((MyClientData*)client_data)->file;
  88863. * if(*bytes > 0) {
  88864. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  88865. * if(ferror(file))
  88866. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  88867. * else if(*bytes == 0)
  88868. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  88869. * else
  88870. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  88871. * }
  88872. * else
  88873. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  88874. * }
  88875. * \endcode
  88876. *
  88877. * \note In general, FLAC__StreamDecoder functions which change the
  88878. * state should not be called on the \a decoder while in the callback.
  88879. *
  88880. * \param decoder The decoder instance calling the callback.
  88881. * \param buffer A pointer to a location for the callee to store
  88882. * data to be decoded.
  88883. * \param bytes A pointer to the size of the buffer. On entry
  88884. * to the callback, it contains the maximum number
  88885. * of bytes that may be stored in \a buffer. The
  88886. * callee must set it to the actual number of bytes
  88887. * stored (0 in case of error or end-of-stream) before
  88888. * returning.
  88889. * \param client_data The callee's client data set through
  88890. * FLAC__stream_decoder_init_*().
  88891. * \retval FLAC__StreamDecoderReadStatus
  88892. * The callee's return status. Note that the callback should return
  88893. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  88894. * zero bytes were read and there is no more data to be read.
  88895. */
  88896. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  88897. /** Signature for the seek callback.
  88898. *
  88899. * A function pointer matching this signature may be passed to
  88900. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  88901. * called when the decoder needs to seek the input stream. The decoder
  88902. * will pass the absolute byte offset to seek to, 0 meaning the
  88903. * beginning of the stream.
  88904. *
  88905. * Here is an example of a seek callback for stdio streams:
  88906. * \code
  88907. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  88908. * {
  88909. * FILE *file = ((MyClientData*)client_data)->file;
  88910. * if(file == stdin)
  88911. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  88912. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  88913. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  88914. * else
  88915. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  88916. * }
  88917. * \endcode
  88918. *
  88919. * \note In general, FLAC__StreamDecoder functions which change the
  88920. * state should not be called on the \a decoder while in the callback.
  88921. *
  88922. * \param decoder The decoder instance calling the callback.
  88923. * \param absolute_byte_offset The offset from the beginning of the stream
  88924. * to seek to.
  88925. * \param client_data The callee's client data set through
  88926. * FLAC__stream_decoder_init_*().
  88927. * \retval FLAC__StreamDecoderSeekStatus
  88928. * The callee's return status.
  88929. */
  88930. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  88931. /** Signature for the tell callback.
  88932. *
  88933. * A function pointer matching this signature may be passed to
  88934. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  88935. * called when the decoder wants to know the current position of the
  88936. * stream. The callback should return the byte offset from the
  88937. * beginning of the stream.
  88938. *
  88939. * Here is an example of a tell callback for stdio streams:
  88940. * \code
  88941. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  88942. * {
  88943. * FILE *file = ((MyClientData*)client_data)->file;
  88944. * off_t pos;
  88945. * if(file == stdin)
  88946. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  88947. * else if((pos = ftello(file)) < 0)
  88948. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  88949. * else {
  88950. * *absolute_byte_offset = (FLAC__uint64)pos;
  88951. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  88952. * }
  88953. * }
  88954. * \endcode
  88955. *
  88956. * \note In general, FLAC__StreamDecoder functions which change the
  88957. * state should not be called on the \a decoder while in the callback.
  88958. *
  88959. * \param decoder The decoder instance calling the callback.
  88960. * \param absolute_byte_offset A pointer to storage for the current offset
  88961. * from the beginning of the stream.
  88962. * \param client_data The callee's client data set through
  88963. * FLAC__stream_decoder_init_*().
  88964. * \retval FLAC__StreamDecoderTellStatus
  88965. * The callee's return status.
  88966. */
  88967. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  88968. /** Signature for the length callback.
  88969. *
  88970. * A function pointer matching this signature may be passed to
  88971. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  88972. * called when the decoder wants to know the total length of the stream
  88973. * in bytes.
  88974. *
  88975. * Here is an example of a length callback for stdio streams:
  88976. * \code
  88977. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  88978. * {
  88979. * FILE *file = ((MyClientData*)client_data)->file;
  88980. * struct stat filestats;
  88981. *
  88982. * if(file == stdin)
  88983. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  88984. * else if(fstat(fileno(file), &filestats) != 0)
  88985. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  88986. * else {
  88987. * *stream_length = (FLAC__uint64)filestats.st_size;
  88988. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  88989. * }
  88990. * }
  88991. * \endcode
  88992. *
  88993. * \note In general, FLAC__StreamDecoder functions which change the
  88994. * state should not be called on the \a decoder while in the callback.
  88995. *
  88996. * \param decoder The decoder instance calling the callback.
  88997. * \param stream_length A pointer to storage for the length of the stream
  88998. * in bytes.
  88999. * \param client_data The callee's client data set through
  89000. * FLAC__stream_decoder_init_*().
  89001. * \retval FLAC__StreamDecoderLengthStatus
  89002. * The callee's return status.
  89003. */
  89004. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  89005. /** Signature for the EOF callback.
  89006. *
  89007. * A function pointer matching this signature may be passed to
  89008. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89009. * called when the decoder needs to know if the end of the stream has
  89010. * been reached.
  89011. *
  89012. * Here is an example of a EOF callback for stdio streams:
  89013. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  89014. * \code
  89015. * {
  89016. * FILE *file = ((MyClientData*)client_data)->file;
  89017. * return feof(file)? true : false;
  89018. * }
  89019. * \endcode
  89020. *
  89021. * \note In general, FLAC__StreamDecoder functions which change the
  89022. * state should not be called on the \a decoder while in the callback.
  89023. *
  89024. * \param decoder The decoder instance calling the callback.
  89025. * \param client_data The callee's client data set through
  89026. * FLAC__stream_decoder_init_*().
  89027. * \retval FLAC__bool
  89028. * \c true if the currently at the end of the stream, else \c false.
  89029. */
  89030. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  89031. /** Signature for the write callback.
  89032. *
  89033. * A function pointer matching this signature must be passed to one of
  89034. * the FLAC__stream_decoder_init_*() functions.
  89035. * The supplied function will be called when the decoder has decoded a
  89036. * single audio frame. The decoder will pass the frame metadata as well
  89037. * as an array of pointers (one for each channel) pointing to the
  89038. * decoded audio.
  89039. *
  89040. * \note In general, FLAC__StreamDecoder functions which change the
  89041. * state should not be called on the \a decoder while in the callback.
  89042. *
  89043. * \param decoder The decoder instance calling the callback.
  89044. * \param frame The description of the decoded frame. See
  89045. * FLAC__Frame.
  89046. * \param buffer An array of pointers to decoded channels of data.
  89047. * Each pointer will point to an array of signed
  89048. * samples of length \a frame->header.blocksize.
  89049. * Channels will be ordered according to the FLAC
  89050. * specification; see the documentation for the
  89051. * <A HREF="../format.html#frame_header">frame header</A>.
  89052. * \param client_data The callee's client data set through
  89053. * FLAC__stream_decoder_init_*().
  89054. * \retval FLAC__StreamDecoderWriteStatus
  89055. * The callee's return status.
  89056. */
  89057. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  89058. /** Signature for the metadata callback.
  89059. *
  89060. * A function pointer matching this signature must be passed to one of
  89061. * the FLAC__stream_decoder_init_*() functions.
  89062. * The supplied function will be called when the decoder has decoded a
  89063. * metadata block. In a valid FLAC file there will always be one
  89064. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  89065. * These will be supplied by the decoder in the same order as they
  89066. * appear in the stream and always before the first audio frame (i.e.
  89067. * write callback). The metadata block that is passed in must not be
  89068. * modified, and it doesn't live beyond the callback, so you should make
  89069. * a copy of it with FLAC__metadata_object_clone() if you will need it
  89070. * elsewhere. Since metadata blocks can potentially be large, by
  89071. * default the decoder only calls the metadata callback for the
  89072. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  89073. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  89074. *
  89075. * \note In general, FLAC__StreamDecoder functions which change the
  89076. * state should not be called on the \a decoder while in the callback.
  89077. *
  89078. * \param decoder The decoder instance calling the callback.
  89079. * \param metadata The decoded metadata block.
  89080. * \param client_data The callee's client data set through
  89081. * FLAC__stream_decoder_init_*().
  89082. */
  89083. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  89084. /** Signature for the error callback.
  89085. *
  89086. * A function pointer matching this signature must be passed to one of
  89087. * the FLAC__stream_decoder_init_*() functions.
  89088. * The supplied function will be called whenever an error occurs during
  89089. * decoding.
  89090. *
  89091. * \note In general, FLAC__StreamDecoder functions which change the
  89092. * state should not be called on the \a decoder while in the callback.
  89093. *
  89094. * \param decoder The decoder instance calling the callback.
  89095. * \param status The error encountered by the decoder.
  89096. * \param client_data The callee's client data set through
  89097. * FLAC__stream_decoder_init_*().
  89098. */
  89099. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  89100. /***********************************************************************
  89101. *
  89102. * Class constructor/destructor
  89103. *
  89104. ***********************************************************************/
  89105. /** Create a new stream decoder instance. The instance is created with
  89106. * default settings; see the individual FLAC__stream_decoder_set_*()
  89107. * functions for each setting's default.
  89108. *
  89109. * \retval FLAC__StreamDecoder*
  89110. * \c NULL if there was an error allocating memory, else the new instance.
  89111. */
  89112. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  89113. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  89114. *
  89115. * \param decoder A pointer to an existing decoder.
  89116. * \assert
  89117. * \code decoder != NULL \endcode
  89118. */
  89119. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  89120. /***********************************************************************
  89121. *
  89122. * Public class method prototypes
  89123. *
  89124. ***********************************************************************/
  89125. /** Set the serial number for the FLAC stream within the Ogg container.
  89126. * The default behavior is to use the serial number of the first Ogg
  89127. * page. Setting a serial number here will explicitly specify which
  89128. * stream is to be decoded.
  89129. *
  89130. * \note
  89131. * This does not need to be set for native FLAC decoding.
  89132. *
  89133. * \default \c use serial number of first page
  89134. * \param decoder A decoder instance to set.
  89135. * \param serial_number See above.
  89136. * \assert
  89137. * \code decoder != NULL \endcode
  89138. * \retval FLAC__bool
  89139. * \c false if the decoder is already initialized, else \c true.
  89140. */
  89141. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  89142. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  89143. * compute the MD5 signature of the unencoded audio data while decoding
  89144. * and compare it to the signature from the STREAMINFO block, if it
  89145. * exists, during FLAC__stream_decoder_finish().
  89146. *
  89147. * MD5 signature checking will be turned off (until the next
  89148. * FLAC__stream_decoder_reset()) if there is no signature in the
  89149. * STREAMINFO block or when a seek is attempted.
  89150. *
  89151. * Clients that do not use the MD5 check should leave this off to speed
  89152. * up decoding.
  89153. *
  89154. * \default \c false
  89155. * \param decoder A decoder instance to set.
  89156. * \param value Flag value (see above).
  89157. * \assert
  89158. * \code decoder != NULL \endcode
  89159. * \retval FLAC__bool
  89160. * \c false if the decoder is already initialized, else \c true.
  89161. */
  89162. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  89163. /** Direct the decoder to pass on all metadata blocks of type \a type.
  89164. *
  89165. * \default By default, only the \c STREAMINFO block is returned via the
  89166. * metadata callback.
  89167. * \param decoder A decoder instance to set.
  89168. * \param type See above.
  89169. * \assert
  89170. * \code decoder != NULL \endcode
  89171. * \a type is valid
  89172. * \retval FLAC__bool
  89173. * \c false if the decoder is already initialized, else \c true.
  89174. */
  89175. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  89176. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  89177. * given \a id.
  89178. *
  89179. * \default By default, only the \c STREAMINFO block is returned via the
  89180. * metadata callback.
  89181. * \param decoder A decoder instance to set.
  89182. * \param id See above.
  89183. * \assert
  89184. * \code decoder != NULL \endcode
  89185. * \code id != NULL \endcode
  89186. * \retval FLAC__bool
  89187. * \c false if the decoder is already initialized, else \c true.
  89188. */
  89189. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  89190. /** Direct the decoder to pass on all metadata blocks of any type.
  89191. *
  89192. * \default By default, only the \c STREAMINFO block is returned via the
  89193. * metadata callback.
  89194. * \param decoder A decoder instance to set.
  89195. * \assert
  89196. * \code decoder != NULL \endcode
  89197. * \retval FLAC__bool
  89198. * \c false if the decoder is already initialized, else \c true.
  89199. */
  89200. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  89201. /** Direct the decoder to filter out all metadata blocks of type \a type.
  89202. *
  89203. * \default By default, only the \c STREAMINFO block is returned via the
  89204. * metadata callback.
  89205. * \param decoder A decoder instance to set.
  89206. * \param type See above.
  89207. * \assert
  89208. * \code decoder != NULL \endcode
  89209. * \a type is valid
  89210. * \retval FLAC__bool
  89211. * \c false if the decoder is already initialized, else \c true.
  89212. */
  89213. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  89214. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  89215. * the given \a id.
  89216. *
  89217. * \default By default, only the \c STREAMINFO block is returned via the
  89218. * metadata callback.
  89219. * \param decoder A decoder instance to set.
  89220. * \param id See above.
  89221. * \assert
  89222. * \code decoder != NULL \endcode
  89223. * \code id != NULL \endcode
  89224. * \retval FLAC__bool
  89225. * \c false if the decoder is already initialized, else \c true.
  89226. */
  89227. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  89228. /** Direct the decoder to filter out all metadata blocks of any type.
  89229. *
  89230. * \default By default, only the \c STREAMINFO block is returned via the
  89231. * metadata callback.
  89232. * \param decoder A decoder instance to set.
  89233. * \assert
  89234. * \code decoder != NULL \endcode
  89235. * \retval FLAC__bool
  89236. * \c false if the decoder is already initialized, else \c true.
  89237. */
  89238. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  89239. /** Get the current decoder state.
  89240. *
  89241. * \param decoder A decoder instance to query.
  89242. * \assert
  89243. * \code decoder != NULL \endcode
  89244. * \retval FLAC__StreamDecoderState
  89245. * The current decoder state.
  89246. */
  89247. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  89248. /** Get the current decoder state as a C string.
  89249. *
  89250. * \param decoder A decoder instance to query.
  89251. * \assert
  89252. * \code decoder != NULL \endcode
  89253. * \retval const char *
  89254. * The decoder state as a C string. Do not modify the contents.
  89255. */
  89256. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  89257. /** Get the "MD5 signature checking" flag.
  89258. * This is the value of the setting, not whether or not the decoder is
  89259. * currently checking the MD5 (remember, it can be turned off automatically
  89260. * by a seek). When the decoder is reset the flag will be restored to the
  89261. * value returned by this function.
  89262. *
  89263. * \param decoder A decoder instance to query.
  89264. * \assert
  89265. * \code decoder != NULL \endcode
  89266. * \retval FLAC__bool
  89267. * See above.
  89268. */
  89269. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  89270. /** Get the total number of samples in the stream being decoded.
  89271. * Will only be valid after decoding has started and will contain the
  89272. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  89273. *
  89274. * \param decoder A decoder instance to query.
  89275. * \assert
  89276. * \code decoder != NULL \endcode
  89277. * \retval unsigned
  89278. * See above.
  89279. */
  89280. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  89281. /** Get the current number of channels in the stream being decoded.
  89282. * Will only be valid after decoding has started and will contain the
  89283. * value from the most recently decoded frame header.
  89284. *
  89285. * \param decoder A decoder instance to query.
  89286. * \assert
  89287. * \code decoder != NULL \endcode
  89288. * \retval unsigned
  89289. * See above.
  89290. */
  89291. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  89292. /** Get the current channel assignment in the stream being decoded.
  89293. * Will only be valid after decoding has started and will contain the
  89294. * value from the most recently decoded frame header.
  89295. *
  89296. * \param decoder A decoder instance to query.
  89297. * \assert
  89298. * \code decoder != NULL \endcode
  89299. * \retval FLAC__ChannelAssignment
  89300. * See above.
  89301. */
  89302. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  89303. /** Get the current sample resolution in the stream being decoded.
  89304. * Will only be valid after decoding has started and will contain the
  89305. * value from the most recently decoded frame header.
  89306. *
  89307. * \param decoder A decoder instance to query.
  89308. * \assert
  89309. * \code decoder != NULL \endcode
  89310. * \retval unsigned
  89311. * See above.
  89312. */
  89313. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  89314. /** Get the current sample rate in Hz of the stream being decoded.
  89315. * Will only be valid after decoding has started and will contain the
  89316. * value from the most recently decoded frame header.
  89317. *
  89318. * \param decoder A decoder instance to query.
  89319. * \assert
  89320. * \code decoder != NULL \endcode
  89321. * \retval unsigned
  89322. * See above.
  89323. */
  89324. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  89325. /** Get the current blocksize of the stream being decoded.
  89326. * Will only be valid after decoding has started and will contain the
  89327. * value from the most recently decoded frame header.
  89328. *
  89329. * \param decoder A decoder instance to query.
  89330. * \assert
  89331. * \code decoder != NULL \endcode
  89332. * \retval unsigned
  89333. * See above.
  89334. */
  89335. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  89336. /** Returns the decoder's current read position within the stream.
  89337. * The position is the byte offset from the start of the stream.
  89338. * Bytes before this position have been fully decoded. Note that
  89339. * there may still be undecoded bytes in the decoder's read FIFO.
  89340. * The returned position is correct even after a seek.
  89341. *
  89342. * \warning This function currently only works for native FLAC,
  89343. * not Ogg FLAC streams.
  89344. *
  89345. * \param decoder A decoder instance to query.
  89346. * \param position Address at which to return the desired position.
  89347. * \assert
  89348. * \code decoder != NULL \endcode
  89349. * \code position != NULL \endcode
  89350. * \retval FLAC__bool
  89351. * \c true if successful, \c false if the stream is not native FLAC,
  89352. * or there was an error from the 'tell' callback or it returned
  89353. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  89354. */
  89355. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  89356. /** Initialize the decoder instance to decode native FLAC streams.
  89357. *
  89358. * This flavor of initialization sets up the decoder to decode from a
  89359. * native FLAC stream. I/O is performed via callbacks to the client.
  89360. * For decoding from a plain file via filename or open FILE*,
  89361. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  89362. * provide a simpler interface.
  89363. *
  89364. * This function should be called after FLAC__stream_decoder_new() and
  89365. * FLAC__stream_decoder_set_*() but before any of the
  89366. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89367. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89368. * if initialization succeeded.
  89369. *
  89370. * \param decoder An uninitialized decoder instance.
  89371. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  89372. * pointer must not be \c NULL.
  89373. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  89374. * pointer may be \c NULL if seeking is not
  89375. * supported. If \a seek_callback is not \c NULL then a
  89376. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  89377. * Alternatively, a dummy seek callback that just
  89378. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89379. * may also be supplied, all though this is slightly
  89380. * less efficient for the decoder.
  89381. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  89382. * pointer may be \c NULL if not supported by the client. If
  89383. * \a seek_callback is not \c NULL then a
  89384. * \a tell_callback must also be supplied.
  89385. * Alternatively, a dummy tell callback that just
  89386. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89387. * may also be supplied, all though this is slightly
  89388. * less efficient for the decoder.
  89389. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  89390. * pointer may be \c NULL if not supported by the client. If
  89391. * \a seek_callback is not \c NULL then a
  89392. * \a length_callback must also be supplied.
  89393. * Alternatively, a dummy length callback that just
  89394. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89395. * may also be supplied, all though this is slightly
  89396. * less efficient for the decoder.
  89397. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  89398. * pointer may be \c NULL if not supported by the client. If
  89399. * \a seek_callback is not \c NULL then a
  89400. * \a eof_callback must also be supplied.
  89401. * Alternatively, a dummy length callback that just
  89402. * returns \c false
  89403. * may also be supplied, all though this is slightly
  89404. * less efficient for the decoder.
  89405. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89406. * pointer must not be \c NULL.
  89407. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89408. * pointer may be \c NULL if the callback is not
  89409. * desired.
  89410. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89411. * pointer must not be \c NULL.
  89412. * \param client_data This value will be supplied to callbacks in their
  89413. * \a client_data argument.
  89414. * \assert
  89415. * \code decoder != NULL \endcode
  89416. * \retval FLAC__StreamDecoderInitStatus
  89417. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89418. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89419. */
  89420. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  89421. FLAC__StreamDecoder *decoder,
  89422. FLAC__StreamDecoderReadCallback read_callback,
  89423. FLAC__StreamDecoderSeekCallback seek_callback,
  89424. FLAC__StreamDecoderTellCallback tell_callback,
  89425. FLAC__StreamDecoderLengthCallback length_callback,
  89426. FLAC__StreamDecoderEofCallback eof_callback,
  89427. FLAC__StreamDecoderWriteCallback write_callback,
  89428. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89429. FLAC__StreamDecoderErrorCallback error_callback,
  89430. void *client_data
  89431. );
  89432. /** Initialize the decoder instance to decode Ogg FLAC streams.
  89433. *
  89434. * This flavor of initialization sets up the decoder to decode from a
  89435. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  89436. * client. For decoding from a plain file via filename or open FILE*,
  89437. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  89438. * provide a simpler interface.
  89439. *
  89440. * This function should be called after FLAC__stream_decoder_new() and
  89441. * FLAC__stream_decoder_set_*() but before any of the
  89442. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89443. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89444. * if initialization succeeded.
  89445. *
  89446. * \note Support for Ogg FLAC in the library is optional. If this
  89447. * library has been built without support for Ogg FLAC, this function
  89448. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  89449. *
  89450. * \param decoder An uninitialized decoder instance.
  89451. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  89452. * pointer must not be \c NULL.
  89453. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  89454. * pointer may be \c NULL if seeking is not
  89455. * supported. If \a seek_callback is not \c NULL then a
  89456. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  89457. * Alternatively, a dummy seek callback that just
  89458. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89459. * may also be supplied, all though this is slightly
  89460. * less efficient for the decoder.
  89461. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  89462. * pointer may be \c NULL if not supported by the client. If
  89463. * \a seek_callback is not \c NULL then a
  89464. * \a tell_callback must also be supplied.
  89465. * Alternatively, a dummy tell callback that just
  89466. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89467. * may also be supplied, all though this is slightly
  89468. * less efficient for the decoder.
  89469. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  89470. * pointer may be \c NULL if not supported by the client. If
  89471. * \a seek_callback is not \c NULL then a
  89472. * \a length_callback must also be supplied.
  89473. * Alternatively, a dummy length callback that just
  89474. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89475. * may also be supplied, all though this is slightly
  89476. * less efficient for the decoder.
  89477. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  89478. * pointer may be \c NULL if not supported by the client. If
  89479. * \a seek_callback is not \c NULL then a
  89480. * \a eof_callback must also be supplied.
  89481. * Alternatively, a dummy length callback that just
  89482. * returns \c false
  89483. * may also be supplied, all though this is slightly
  89484. * less efficient for the decoder.
  89485. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89486. * pointer must not be \c NULL.
  89487. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89488. * pointer may be \c NULL if the callback is not
  89489. * desired.
  89490. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89491. * pointer must not be \c NULL.
  89492. * \param client_data This value will be supplied to callbacks in their
  89493. * \a client_data argument.
  89494. * \assert
  89495. * \code decoder != NULL \endcode
  89496. * \retval FLAC__StreamDecoderInitStatus
  89497. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89498. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89499. */
  89500. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  89501. FLAC__StreamDecoder *decoder,
  89502. FLAC__StreamDecoderReadCallback read_callback,
  89503. FLAC__StreamDecoderSeekCallback seek_callback,
  89504. FLAC__StreamDecoderTellCallback tell_callback,
  89505. FLAC__StreamDecoderLengthCallback length_callback,
  89506. FLAC__StreamDecoderEofCallback eof_callback,
  89507. FLAC__StreamDecoderWriteCallback write_callback,
  89508. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89509. FLAC__StreamDecoderErrorCallback error_callback,
  89510. void *client_data
  89511. );
  89512. /** Initialize the decoder instance to decode native FLAC files.
  89513. *
  89514. * This flavor of initialization sets up the decoder to decode from a
  89515. * plain native FLAC file. For non-stdio streams, you must use
  89516. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  89517. *
  89518. * This function should be called after FLAC__stream_decoder_new() and
  89519. * FLAC__stream_decoder_set_*() but before any of the
  89520. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89521. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89522. * if initialization succeeded.
  89523. *
  89524. * \param decoder An uninitialized decoder instance.
  89525. * \param file An open FLAC file. The file should have been
  89526. * opened with mode \c "rb" and rewound. The file
  89527. * becomes owned by the decoder and should not be
  89528. * manipulated by the client while decoding.
  89529. * Unless \a file is \c stdin, it will be closed
  89530. * when FLAC__stream_decoder_finish() is called.
  89531. * Note however that seeking will not work when
  89532. * decoding from \c stdout since it is not seekable.
  89533. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89534. * pointer must not be \c NULL.
  89535. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89536. * pointer may be \c NULL if the callback is not
  89537. * desired.
  89538. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89539. * pointer must not be \c NULL.
  89540. * \param client_data This value will be supplied to callbacks in their
  89541. * \a client_data argument.
  89542. * \assert
  89543. * \code decoder != NULL \endcode
  89544. * \code file != NULL \endcode
  89545. * \retval FLAC__StreamDecoderInitStatus
  89546. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89547. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89548. */
  89549. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  89550. FLAC__StreamDecoder *decoder,
  89551. FILE *file,
  89552. FLAC__StreamDecoderWriteCallback write_callback,
  89553. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89554. FLAC__StreamDecoderErrorCallback error_callback,
  89555. void *client_data
  89556. );
  89557. /** Initialize the decoder instance to decode Ogg FLAC files.
  89558. *
  89559. * This flavor of initialization sets up the decoder to decode from a
  89560. * plain Ogg FLAC file. For non-stdio streams, you must use
  89561. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  89562. *
  89563. * This function should be called after FLAC__stream_decoder_new() and
  89564. * FLAC__stream_decoder_set_*() but before any of the
  89565. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89566. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89567. * if initialization succeeded.
  89568. *
  89569. * \note Support for Ogg FLAC in the library is optional. If this
  89570. * library has been built without support for Ogg FLAC, this function
  89571. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  89572. *
  89573. * \param decoder An uninitialized decoder instance.
  89574. * \param file An open FLAC file. The file should have been
  89575. * opened with mode \c "rb" and rewound. The file
  89576. * becomes owned by the decoder and should not be
  89577. * manipulated by the client while decoding.
  89578. * Unless \a file is \c stdin, it will be closed
  89579. * when FLAC__stream_decoder_finish() is called.
  89580. * Note however that seeking will not work when
  89581. * decoding from \c stdout since it is not seekable.
  89582. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89583. * pointer must not be \c NULL.
  89584. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89585. * pointer may be \c NULL if the callback is not
  89586. * desired.
  89587. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89588. * pointer must not be \c NULL.
  89589. * \param client_data This value will be supplied to callbacks in their
  89590. * \a client_data argument.
  89591. * \assert
  89592. * \code decoder != NULL \endcode
  89593. * \code file != NULL \endcode
  89594. * \retval FLAC__StreamDecoderInitStatus
  89595. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89596. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89597. */
  89598. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  89599. FLAC__StreamDecoder *decoder,
  89600. FILE *file,
  89601. FLAC__StreamDecoderWriteCallback write_callback,
  89602. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89603. FLAC__StreamDecoderErrorCallback error_callback,
  89604. void *client_data
  89605. );
  89606. /** Initialize the decoder instance to decode native FLAC files.
  89607. *
  89608. * This flavor of initialization sets up the decoder to decode from a plain
  89609. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  89610. * example, with Unicode filenames on Windows), you must use
  89611. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  89612. * and provide callbacks for the I/O.
  89613. *
  89614. * This function should be called after FLAC__stream_decoder_new() and
  89615. * FLAC__stream_decoder_set_*() but before any of the
  89616. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89617. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89618. * if initialization succeeded.
  89619. *
  89620. * \param decoder An uninitialized decoder instance.
  89621. * \param filename The name of the file to decode from. The file will
  89622. * be opened with fopen(). Use \c NULL to decode from
  89623. * \c stdin. Note that \c stdin is not seekable.
  89624. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89625. * pointer must not be \c NULL.
  89626. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89627. * pointer may be \c NULL if the callback is not
  89628. * desired.
  89629. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89630. * pointer must not be \c NULL.
  89631. * \param client_data This value will be supplied to callbacks in their
  89632. * \a client_data argument.
  89633. * \assert
  89634. * \code decoder != NULL \endcode
  89635. * \retval FLAC__StreamDecoderInitStatus
  89636. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89637. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89638. */
  89639. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  89640. FLAC__StreamDecoder *decoder,
  89641. const char *filename,
  89642. FLAC__StreamDecoderWriteCallback write_callback,
  89643. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89644. FLAC__StreamDecoderErrorCallback error_callback,
  89645. void *client_data
  89646. );
  89647. /** Initialize the decoder instance to decode Ogg FLAC files.
  89648. *
  89649. * This flavor of initialization sets up the decoder to decode from a plain
  89650. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  89651. * example, with Unicode filenames on Windows), you must use
  89652. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  89653. * and provide callbacks for the I/O.
  89654. *
  89655. * This function should be called after FLAC__stream_decoder_new() and
  89656. * FLAC__stream_decoder_set_*() but before any of the
  89657. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89658. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89659. * if initialization succeeded.
  89660. *
  89661. * \note Support for Ogg FLAC in the library is optional. If this
  89662. * library has been built without support for Ogg FLAC, this function
  89663. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  89664. *
  89665. * \param decoder An uninitialized decoder instance.
  89666. * \param filename The name of the file to decode from. The file will
  89667. * be opened with fopen(). Use \c NULL to decode from
  89668. * \c stdin. Note that \c stdin is not seekable.
  89669. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89670. * pointer must not be \c NULL.
  89671. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89672. * pointer may be \c NULL if the callback is not
  89673. * desired.
  89674. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89675. * pointer must not be \c NULL.
  89676. * \param client_data This value will be supplied to callbacks in their
  89677. * \a client_data argument.
  89678. * \assert
  89679. * \code decoder != NULL \endcode
  89680. * \retval FLAC__StreamDecoderInitStatus
  89681. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89682. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89683. */
  89684. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  89685. FLAC__StreamDecoder *decoder,
  89686. const char *filename,
  89687. FLAC__StreamDecoderWriteCallback write_callback,
  89688. FLAC__StreamDecoderMetadataCallback metadata_callback,
  89689. FLAC__StreamDecoderErrorCallback error_callback,
  89690. void *client_data
  89691. );
  89692. /** Finish the decoding process.
  89693. * Flushes the decoding buffer, releases resources, resets the decoder
  89694. * settings to their defaults, and returns the decoder state to
  89695. * FLAC__STREAM_DECODER_UNINITIALIZED.
  89696. *
  89697. * In the event of a prematurely-terminated decode, it is not strictly
  89698. * necessary to call this immediately before FLAC__stream_decoder_delete()
  89699. * but it is good practice to match every FLAC__stream_decoder_init_*()
  89700. * with a FLAC__stream_decoder_finish().
  89701. *
  89702. * \param decoder An uninitialized decoder instance.
  89703. * \assert
  89704. * \code decoder != NULL \endcode
  89705. * \retval FLAC__bool
  89706. * \c false if MD5 checking is on AND a STREAMINFO block was available
  89707. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  89708. * signature does not match the one computed by the decoder; else
  89709. * \c true.
  89710. */
  89711. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  89712. /** Flush the stream input.
  89713. * The decoder's input buffer will be cleared and the state set to
  89714. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  89715. * off MD5 checking.
  89716. *
  89717. * \param decoder A decoder instance.
  89718. * \assert
  89719. * \code decoder != NULL \endcode
  89720. * \retval FLAC__bool
  89721. * \c true if successful, else \c false if a memory allocation
  89722. * error occurs (in which case the state will be set to
  89723. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  89724. */
  89725. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  89726. /** Reset the decoding process.
  89727. * The decoder's input buffer will be cleared and the state set to
  89728. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  89729. * FLAC__stream_decoder_finish() except that the settings are
  89730. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  89731. * before decoding again. MD5 checking will be restored to its original
  89732. * setting.
  89733. *
  89734. * If the decoder is seekable, or was initialized with
  89735. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  89736. * the decoder will also attempt to seek to the beginning of the file.
  89737. * If this rewind fails, this function will return \c false. It follows
  89738. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  89739. * \c stdin.
  89740. *
  89741. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  89742. * and is not seekable (i.e. no seek callback was provided or the seek
  89743. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  89744. * is the duty of the client to start feeding data from the beginning of
  89745. * the stream on the next FLAC__stream_decoder_process() or
  89746. * FLAC__stream_decoder_process_interleaved() call.
  89747. *
  89748. * \param decoder A decoder instance.
  89749. * \assert
  89750. * \code decoder != NULL \endcode
  89751. * \retval FLAC__bool
  89752. * \c true if successful, else \c false if a memory allocation occurs
  89753. * (in which case the state will be set to
  89754. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  89755. * occurs (the state will be unchanged).
  89756. */
  89757. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  89758. /** Decode one metadata block or audio frame.
  89759. * This version instructs the decoder to decode a either a single metadata
  89760. * block or a single frame and stop, unless the callbacks return a fatal
  89761. * error or the read callback returns
  89762. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  89763. *
  89764. * As the decoder needs more input it will call the read callback.
  89765. * Depending on what was decoded, the metadata or write callback will be
  89766. * called with the decoded metadata block or audio frame.
  89767. *
  89768. * Unless there is a fatal read error or end of stream, this function
  89769. * will return once one whole frame is decoded. In other words, if the
  89770. * stream is not synchronized or points to a corrupt frame header, the
  89771. * decoder will continue to try and resync until it gets to a valid
  89772. * frame, then decode one frame, then return. If the decoder points to
  89773. * a frame whose frame CRC in the frame footer does not match the
  89774. * computed frame CRC, this function will issue a
  89775. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  89776. * error callback, and return, having decoded one complete, although
  89777. * corrupt, frame. (Such corrupted frames are sent as silence of the
  89778. * correct length to the write callback.)
  89779. *
  89780. * \param decoder An initialized decoder instance.
  89781. * \assert
  89782. * \code decoder != NULL \endcode
  89783. * \retval FLAC__bool
  89784. * \c false if any fatal read, write, or memory allocation error
  89785. * occurred (meaning decoding must stop), else \c true; for more
  89786. * information about the decoder, check the decoder state with
  89787. * FLAC__stream_decoder_get_state().
  89788. */
  89789. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  89790. /** Decode until the end of the metadata.
  89791. * This version instructs the decoder to decode from the current position
  89792. * and continue until all the metadata has been read, or until the
  89793. * callbacks return a fatal error or the read callback returns
  89794. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  89795. *
  89796. * As the decoder needs more input it will call the read callback.
  89797. * As each metadata block is decoded, the metadata callback will be called
  89798. * with the decoded metadata.
  89799. *
  89800. * \param decoder An initialized decoder instance.
  89801. * \assert
  89802. * \code decoder != NULL \endcode
  89803. * \retval FLAC__bool
  89804. * \c false if any fatal read, write, or memory allocation error
  89805. * occurred (meaning decoding must stop), else \c true; for more
  89806. * information about the decoder, check the decoder state with
  89807. * FLAC__stream_decoder_get_state().
  89808. */
  89809. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  89810. /** Decode until the end of the stream.
  89811. * This version instructs the decoder to decode from the current position
  89812. * and continue until the end of stream (the read callback returns
  89813. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  89814. * callbacks return a fatal error.
  89815. *
  89816. * As the decoder needs more input it will call the read callback.
  89817. * As each metadata block and frame is decoded, the metadata or write
  89818. * callback will be called with the decoded metadata or frame.
  89819. *
  89820. * \param decoder An initialized decoder instance.
  89821. * \assert
  89822. * \code decoder != NULL \endcode
  89823. * \retval FLAC__bool
  89824. * \c false if any fatal read, write, or memory allocation error
  89825. * occurred (meaning decoding must stop), else \c true; for more
  89826. * information about the decoder, check the decoder state with
  89827. * FLAC__stream_decoder_get_state().
  89828. */
  89829. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  89830. /** Skip one audio frame.
  89831. * This version instructs the decoder to 'skip' a single frame and stop,
  89832. * unless the callbacks return a fatal error or the read callback returns
  89833. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  89834. *
  89835. * The decoding flow is the same as what occurs when
  89836. * FLAC__stream_decoder_process_single() is called to process an audio
  89837. * frame, except that this function does not decode the parsed data into
  89838. * PCM or call the write callback. The integrity of the frame is still
  89839. * checked the same way as in the other process functions.
  89840. *
  89841. * This function will return once one whole frame is skipped, in the
  89842. * same way that FLAC__stream_decoder_process_single() will return once
  89843. * one whole frame is decoded.
  89844. *
  89845. * This function can be used in more quickly determining FLAC frame
  89846. * boundaries when decoding of the actual data is not needed, for
  89847. * example when an application is separating a FLAC stream into frames
  89848. * for editing or storing in a container. To do this, the application
  89849. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  89850. * to the next frame, then use
  89851. * FLAC__stream_decoder_get_decode_position() to find the new frame
  89852. * boundary.
  89853. *
  89854. * This function should only be called when the stream has advanced
  89855. * past all the metadata, otherwise it will return \c false.
  89856. *
  89857. * \param decoder An initialized decoder instance not in a metadata
  89858. * state.
  89859. * \assert
  89860. * \code decoder != NULL \endcode
  89861. * \retval FLAC__bool
  89862. * \c false if any fatal read, write, or memory allocation error
  89863. * occurred (meaning decoding must stop), or if the decoder
  89864. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  89865. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  89866. * information about the decoder, check the decoder state with
  89867. * FLAC__stream_decoder_get_state().
  89868. */
  89869. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  89870. /** Flush the input and seek to an absolute sample.
  89871. * Decoding will resume at the given sample. Note that because of
  89872. * this, the next write callback may contain a partial block. The
  89873. * client must support seeking the input or this function will fail
  89874. * and return \c false. Furthermore, if the decoder state is
  89875. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  89876. * with FLAC__stream_decoder_flush() or reset with
  89877. * FLAC__stream_decoder_reset() before decoding can continue.
  89878. *
  89879. * \param decoder A decoder instance.
  89880. * \param sample The target sample number to seek to.
  89881. * \assert
  89882. * \code decoder != NULL \endcode
  89883. * \retval FLAC__bool
  89884. * \c true if successful, else \c false.
  89885. */
  89886. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  89887. /* \} */
  89888. #ifdef __cplusplus
  89889. }
  89890. #endif
  89891. #endif
  89892. /*** End of inlined file: stream_decoder.h ***/
  89893. /*** Start of inlined file: stream_encoder.h ***/
  89894. #ifndef FLAC__STREAM_ENCODER_H
  89895. #define FLAC__STREAM_ENCODER_H
  89896. #include <stdio.h> /* for FILE */
  89897. #ifdef __cplusplus
  89898. extern "C" {
  89899. #endif
  89900. /** \file include/FLAC/stream_encoder.h
  89901. *
  89902. * \brief
  89903. * This module contains the functions which implement the stream
  89904. * encoder.
  89905. *
  89906. * See the detailed documentation in the
  89907. * \link flac_stream_encoder stream encoder \endlink module.
  89908. */
  89909. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  89910. * \ingroup flac
  89911. *
  89912. * \brief
  89913. * This module describes the encoder layers provided by libFLAC.
  89914. *
  89915. * The stream encoder can be used to encode complete streams either to the
  89916. * client via callbacks, or directly to a file, depending on how it is
  89917. * initialized. When encoding via callbacks, the client provides a write
  89918. * callback which will be called whenever FLAC data is ready to be written.
  89919. * If the client also supplies a seek callback, the encoder will also
  89920. * automatically handle the writing back of metadata discovered while
  89921. * encoding, like stream info, seek points offsets, etc. When encoding to
  89922. * a file, the client needs only supply a filename or open \c FILE* and an
  89923. * optional progress callback for periodic notification of progress; the
  89924. * write and seek callbacks are supplied internally. For more info see the
  89925. * \link flac_stream_encoder stream encoder \endlink module.
  89926. */
  89927. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  89928. * \ingroup flac_encoder
  89929. *
  89930. * \brief
  89931. * This module contains the functions which implement the stream
  89932. * encoder.
  89933. *
  89934. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  89935. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  89936. *
  89937. * The basic usage of this encoder is as follows:
  89938. * - The program creates an instance of an encoder using
  89939. * FLAC__stream_encoder_new().
  89940. * - The program overrides the default settings using
  89941. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  89942. * functions should be called:
  89943. * - FLAC__stream_encoder_set_channels()
  89944. * - FLAC__stream_encoder_set_bits_per_sample()
  89945. * - FLAC__stream_encoder_set_sample_rate()
  89946. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  89947. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  89948. * - If the application wants to control the compression level or set its own
  89949. * metadata, then the following should also be called:
  89950. * - FLAC__stream_encoder_set_compression_level()
  89951. * - FLAC__stream_encoder_set_verify()
  89952. * - FLAC__stream_encoder_set_metadata()
  89953. * - The rest of the set functions should only be called if the client needs
  89954. * exact control over how the audio is compressed; thorough understanding
  89955. * of the FLAC format is necessary to achieve good results.
  89956. * - The program initializes the instance to validate the settings and
  89957. * prepare for encoding using
  89958. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  89959. * or FLAC__stream_encoder_init_file() for native FLAC
  89960. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  89961. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  89962. * - The program calls FLAC__stream_encoder_process() or
  89963. * FLAC__stream_encoder_process_interleaved() to encode data, which
  89964. * subsequently calls the callbacks when there is encoder data ready
  89965. * to be written.
  89966. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  89967. * which causes the encoder to encode any data still in its input pipe,
  89968. * update the metadata with the final encoding statistics if output
  89969. * seeking is possible, and finally reset the encoder to the
  89970. * uninitialized state.
  89971. * - The instance may be used again or deleted with
  89972. * FLAC__stream_encoder_delete().
  89973. *
  89974. * In more detail, the stream encoder functions similarly to the
  89975. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  89976. * callbacks and more options. Typically the client will create a new
  89977. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  89978. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  89979. * calling one of the FLAC__stream_encoder_init_*() functions.
  89980. *
  89981. * Unlike the decoders, the stream encoder has many options that can
  89982. * affect the speed and compression ratio. When setting these parameters
  89983. * you should have some basic knowledge of the format (see the
  89984. * <A HREF="../documentation.html#format">user-level documentation</A>
  89985. * or the <A HREF="../format.html">formal description</A>). The
  89986. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  89987. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  89988. * functions will do this, so make sure to pay attention to the state
  89989. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  89990. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  89991. * before FLAC__stream_encoder_init_*() will take on the defaults from
  89992. * the constructor.
  89993. *
  89994. * There are three initialization functions for native FLAC, one for
  89995. * setting up the encoder to encode FLAC data to the client via
  89996. * callbacks, and two for encoding directly to a file.
  89997. *
  89998. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  89999. * You must also supply a write callback which will be called anytime
  90000. * there is raw encoded data to write. If the client can seek the output
  90001. * it is best to also supply seek and tell callbacks, as this allows the
  90002. * encoder to go back after encoding is finished to write back
  90003. * information that was collected while encoding, like seek point offsets,
  90004. * frame sizes, etc.
  90005. *
  90006. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  90007. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  90008. * filename or open \c FILE*; the encoder will handle all the callbacks
  90009. * internally. You may also supply a progress callback for periodic
  90010. * notification of the encoding progress.
  90011. *
  90012. * There are three similarly-named init functions for encoding to Ogg
  90013. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  90014. * library has been built with Ogg support.
  90015. *
  90016. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  90017. * call the write callback several times, once with the \c fLaC signature,
  90018. * and once for each encoded metadata block. Note that for Ogg FLAC
  90019. * encoding you will usually get at least twice the number of callbacks than
  90020. * with native FLAC, one for the Ogg page header and one for the page body.
  90021. *
  90022. * After initializing the instance, the client may feed audio data to the
  90023. * encoder in one of two ways:
  90024. *
  90025. * - Channel separate, through FLAC__stream_encoder_process() - The client
  90026. * will pass an array of pointers to buffers, one for each channel, to
  90027. * the encoder, each of the same length. The samples need not be
  90028. * block-aligned, but each channel should have the same number of samples.
  90029. * - Channel interleaved, through
  90030. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  90031. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  90032. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  90033. * Again, the samples need not be block-aligned but they must be
  90034. * sample-aligned, i.e. the first value should be channel0_sample0 and
  90035. * the last value channelN_sampleM.
  90036. *
  90037. * Note that for either process call, each sample in the buffers should be a
  90038. * signed integer, right-justified to the resolution set by
  90039. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  90040. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  90041. *
  90042. * When the client is finished encoding data, it calls
  90043. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  90044. * data still in its input pipe, and call the metadata callback with the
  90045. * final encoding statistics. Then the instance may be deleted with
  90046. * FLAC__stream_encoder_delete() or initialized again to encode another
  90047. * stream.
  90048. *
  90049. * For programs that write their own metadata, but that do not know the
  90050. * actual metadata until after encoding, it is advantageous to instruct
  90051. * the encoder to write a PADDING block of the correct size, so that
  90052. * instead of rewriting the whole stream after encoding, the program can
  90053. * just overwrite the PADDING block. If only the maximum size of the
  90054. * metadata is known, the program can write a slightly larger padding
  90055. * block, then split it after encoding.
  90056. *
  90057. * Make sure you understand how lengths are calculated. All FLAC metadata
  90058. * blocks have a 4 byte header which contains the type and length. This
  90059. * length does not include the 4 bytes of the header. See the format page
  90060. * for the specification of metadata blocks and their lengths.
  90061. *
  90062. * \note
  90063. * If you are writing the FLAC data to a file via callbacks, make sure it
  90064. * is open for update (e.g. mode "w+" for stdio streams). This is because
  90065. * after the first encoding pass, the encoder will try to seek back to the
  90066. * beginning of the stream, to the STREAMINFO block, to write some data
  90067. * there. (If using FLAC__stream_encoder_init*_file() or
  90068. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  90069. *
  90070. * \note
  90071. * The "set" functions may only be called when the encoder is in the
  90072. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  90073. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  90074. * before FLAC__stream_encoder_init_*(). If this is the case they will
  90075. * return \c true, otherwise \c false.
  90076. *
  90077. * \note
  90078. * FLAC__stream_encoder_finish() resets all settings to the constructor
  90079. * defaults.
  90080. *
  90081. * \{
  90082. */
  90083. /** State values for a FLAC__StreamEncoder.
  90084. *
  90085. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  90086. *
  90087. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  90088. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  90089. * must be deleted with FLAC__stream_encoder_delete().
  90090. */
  90091. typedef enum {
  90092. FLAC__STREAM_ENCODER_OK = 0,
  90093. /**< The encoder is in the normal OK state and samples can be processed. */
  90094. FLAC__STREAM_ENCODER_UNINITIALIZED,
  90095. /**< The encoder is in the uninitialized state; one of the
  90096. * FLAC__stream_encoder_init_*() functions must be called before samples
  90097. * can be processed.
  90098. */
  90099. FLAC__STREAM_ENCODER_OGG_ERROR,
  90100. /**< An error occurred in the underlying Ogg layer. */
  90101. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  90102. /**< An error occurred in the underlying verify stream decoder;
  90103. * check FLAC__stream_encoder_get_verify_decoder_state().
  90104. */
  90105. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  90106. /**< The verify decoder detected a mismatch between the original
  90107. * audio signal and the decoded audio signal.
  90108. */
  90109. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  90110. /**< One of the callbacks returned a fatal error. */
  90111. FLAC__STREAM_ENCODER_IO_ERROR,
  90112. /**< An I/O error occurred while opening/reading/writing a file.
  90113. * Check \c errno.
  90114. */
  90115. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  90116. /**< An error occurred while writing the stream; usually, the
  90117. * write_callback returned an error.
  90118. */
  90119. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  90120. /**< Memory allocation failed. */
  90121. } FLAC__StreamEncoderState;
  90122. /** Maps a FLAC__StreamEncoderState to a C string.
  90123. *
  90124. * Using a FLAC__StreamEncoderState as the index to this array
  90125. * will give the string equivalent. The contents should not be modified.
  90126. */
  90127. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  90128. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  90129. */
  90130. typedef enum {
  90131. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  90132. /**< Initialization was successful. */
  90133. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  90134. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  90135. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  90136. /**< The library was not compiled with support for the given container
  90137. * format.
  90138. */
  90139. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  90140. /**< A required callback was not supplied. */
  90141. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  90142. /**< The encoder has an invalid setting for number of channels. */
  90143. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  90144. /**< The encoder has an invalid setting for bits-per-sample.
  90145. * FLAC supports 4-32 bps but the reference encoder currently supports
  90146. * only up to 24 bps.
  90147. */
  90148. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  90149. /**< The encoder has an invalid setting for the input sample rate. */
  90150. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  90151. /**< The encoder has an invalid setting for the block size. */
  90152. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  90153. /**< The encoder has an invalid setting for the maximum LPC order. */
  90154. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  90155. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  90156. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  90157. /**< The specified block size is less than the maximum LPC order. */
  90158. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  90159. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  90160. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  90161. /**< The metadata input to the encoder is invalid, in one of the following ways:
  90162. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  90163. * - One of the metadata blocks contains an undefined type
  90164. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  90165. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  90166. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  90167. */
  90168. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  90169. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  90170. * already initialized, usually because
  90171. * FLAC__stream_encoder_finish() was not called.
  90172. */
  90173. } FLAC__StreamEncoderInitStatus;
  90174. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  90175. *
  90176. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  90177. * will give the string equivalent. The contents should not be modified.
  90178. */
  90179. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  90180. /** Return values for the FLAC__StreamEncoder read callback.
  90181. */
  90182. typedef enum {
  90183. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  90184. /**< The read was OK and decoding can continue. */
  90185. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  90186. /**< The read was attempted at the end of the stream. */
  90187. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  90188. /**< An unrecoverable error occurred. */
  90189. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  90190. /**< Client does not support reading back from the output. */
  90191. } FLAC__StreamEncoderReadStatus;
  90192. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  90193. *
  90194. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  90195. * will give the string equivalent. The contents should not be modified.
  90196. */
  90197. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  90198. /** Return values for the FLAC__StreamEncoder write callback.
  90199. */
  90200. typedef enum {
  90201. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  90202. /**< The write was OK and encoding can continue. */
  90203. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  90204. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  90205. } FLAC__StreamEncoderWriteStatus;
  90206. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  90207. *
  90208. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  90209. * will give the string equivalent. The contents should not be modified.
  90210. */
  90211. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  90212. /** Return values for the FLAC__StreamEncoder seek callback.
  90213. */
  90214. typedef enum {
  90215. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  90216. /**< The seek was OK and encoding can continue. */
  90217. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  90218. /**< An unrecoverable error occurred. */
  90219. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  90220. /**< Client does not support seeking. */
  90221. } FLAC__StreamEncoderSeekStatus;
  90222. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  90223. *
  90224. * Using a FLAC__StreamEncoderSeekStatus as the index to this array
  90225. * will give the string equivalent. The contents should not be modified.
  90226. */
  90227. extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
  90228. /** Return values for the FLAC__StreamEncoder tell callback.
  90229. */
  90230. typedef enum {
  90231. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  90232. /**< The tell was OK and encoding can continue. */
  90233. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  90234. /**< An unrecoverable error occurred. */
  90235. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  90236. /**< Client does not support seeking. */
  90237. } FLAC__StreamEncoderTellStatus;
  90238. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  90239. *
  90240. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  90241. * will give the string equivalent. The contents should not be modified.
  90242. */
  90243. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  90244. /***********************************************************************
  90245. *
  90246. * class FLAC__StreamEncoder
  90247. *
  90248. ***********************************************************************/
  90249. struct FLAC__StreamEncoderProtected;
  90250. struct FLAC__StreamEncoderPrivate;
  90251. /** The opaque structure definition for the stream encoder type.
  90252. * See the \link flac_stream_encoder stream encoder module \endlink
  90253. * for a detailed description.
  90254. */
  90255. typedef struct {
  90256. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  90257. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  90258. } FLAC__StreamEncoder;
  90259. /** Signature for the read callback.
  90260. *
  90261. * A function pointer matching this signature must be passed to
  90262. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  90263. * The supplied function will be called when the encoder needs to read back
  90264. * encoded data. This happens during the metadata callback, when the encoder
  90265. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  90266. * while encoding. The address of the buffer to be filled is supplied, along
  90267. * with the number of bytes the buffer can hold. The callback may choose to
  90268. * supply less data and modify the byte count but must be careful not to
  90269. * overflow the buffer. The callback then returns a status code chosen from
  90270. * FLAC__StreamEncoderReadStatus.
  90271. *
  90272. * Here is an example of a read callback for stdio streams:
  90273. * \code
  90274. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  90275. * {
  90276. * FILE *file = ((MyClientData*)client_data)->file;
  90277. * if(*bytes > 0) {
  90278. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  90279. * if(ferror(file))
  90280. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  90281. * else if(*bytes == 0)
  90282. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  90283. * else
  90284. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  90285. * }
  90286. * else
  90287. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  90288. * }
  90289. * \endcode
  90290. *
  90291. * \note In general, FLAC__StreamEncoder functions which change the
  90292. * state should not be called on the \a encoder while in the callback.
  90293. *
  90294. * \param encoder The encoder instance calling the callback.
  90295. * \param buffer A pointer to a location for the callee to store
  90296. * data to be encoded.
  90297. * \param bytes A pointer to the size of the buffer. On entry
  90298. * to the callback, it contains the maximum number
  90299. * of bytes that may be stored in \a buffer. The
  90300. * callee must set it to the actual number of bytes
  90301. * stored (0 in case of error or end-of-stream) before
  90302. * returning.
  90303. * \param client_data The callee's client data set through
  90304. * FLAC__stream_encoder_set_client_data().
  90305. * \retval FLAC__StreamEncoderReadStatus
  90306. * The callee's return status.
  90307. */
  90308. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  90309. /** Signature for the write callback.
  90310. *
  90311. * A function pointer matching this signature must be passed to
  90312. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  90313. * by the encoder anytime there is raw encoded data ready to write. It may
  90314. * include metadata mixed with encoded audio frames and the data is not
  90315. * guaranteed to be aligned on frame or metadata block boundaries.
  90316. *
  90317. * The only duty of the callback is to write out the \a bytes worth of data
  90318. * in \a buffer to the current position in the output stream. The arguments
  90319. * \a samples and \a current_frame are purely informational. If \a samples
  90320. * is greater than \c 0, then \a current_frame will hold the current frame
  90321. * number that is being written; otherwise it indicates that the write
  90322. * callback is being called to write metadata.
  90323. *
  90324. * \note
  90325. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  90326. * write callback will be called twice when writing each audio
  90327. * frame; once for the page header, and once for the page body.
  90328. * When writing the page header, the \a samples argument to the
  90329. * write callback will be \c 0.
  90330. *
  90331. * \note In general, FLAC__StreamEncoder functions which change the
  90332. * state should not be called on the \a encoder while in the callback.
  90333. *
  90334. * \param encoder The encoder instance calling the callback.
  90335. * \param buffer An array of encoded data of length \a bytes.
  90336. * \param bytes The byte length of \a buffer.
  90337. * \param samples The number of samples encoded by \a buffer.
  90338. * \c 0 has a special meaning; see above.
  90339. * \param current_frame The number of the current frame being encoded.
  90340. * \param client_data The callee's client data set through
  90341. * FLAC__stream_encoder_init_*().
  90342. * \retval FLAC__StreamEncoderWriteStatus
  90343. * The callee's return status.
  90344. */
  90345. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  90346. /** Signature for the seek callback.
  90347. *
  90348. * A function pointer matching this signature may be passed to
  90349. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  90350. * when the encoder needs to seek the output stream. The encoder will pass
  90351. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  90352. *
  90353. * Here is an example of a seek callback for stdio streams:
  90354. * \code
  90355. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  90356. * {
  90357. * FILE *file = ((MyClientData*)client_data)->file;
  90358. * if(file == stdin)
  90359. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  90360. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  90361. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  90362. * else
  90363. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  90364. * }
  90365. * \endcode
  90366. *
  90367. * \note In general, FLAC__StreamEncoder functions which change the
  90368. * state should not be called on the \a encoder while in the callback.
  90369. *
  90370. * \param encoder The encoder instance calling the callback.
  90371. * \param absolute_byte_offset The offset from the beginning of the stream
  90372. * to seek to.
  90373. * \param client_data The callee's client data set through
  90374. * FLAC__stream_encoder_init_*().
  90375. * \retval FLAC__StreamEncoderSeekStatus
  90376. * The callee's return status.
  90377. */
  90378. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  90379. /** Signature for the tell callback.
  90380. *
  90381. * A function pointer matching this signature may be passed to
  90382. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  90383. * when the encoder needs to know the current position of the output stream.
  90384. *
  90385. * \warning
  90386. * The callback must return the true current byte offset of the output to
  90387. * which the encoder is writing. If you are buffering the output, make
  90388. * sure and take this into account. If you are writing directly to a
  90389. * FILE* from your write callback, ftell() is sufficient. If you are
  90390. * writing directly to a file descriptor from your write callback, you
  90391. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  90392. * these points to rewrite metadata after encoding.
  90393. *
  90394. * Here is an example of a tell callback for stdio streams:
  90395. * \code
  90396. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  90397. * {
  90398. * FILE *file = ((MyClientData*)client_data)->file;
  90399. * off_t pos;
  90400. * if(file == stdin)
  90401. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  90402. * else if((pos = ftello(file)) < 0)
  90403. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  90404. * else {
  90405. * *absolute_byte_offset = (FLAC__uint64)pos;
  90406. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  90407. * }
  90408. * }
  90409. * \endcode
  90410. *
  90411. * \note In general, FLAC__StreamEncoder functions which change the
  90412. * state should not be called on the \a encoder while in the callback.
  90413. *
  90414. * \param encoder The encoder instance calling the callback.
  90415. * \param absolute_byte_offset The address at which to store the current
  90416. * position of the output.
  90417. * \param client_data The callee's client data set through
  90418. * FLAC__stream_encoder_init_*().
  90419. * \retval FLAC__StreamEncoderTellStatus
  90420. * The callee's return status.
  90421. */
  90422. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  90423. /** Signature for the metadata callback.
  90424. *
  90425. * A function pointer matching this signature may be passed to
  90426. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  90427. * once at the end of encoding with the populated STREAMINFO structure. This
  90428. * is so the client can seek back to the beginning of the file and write the
  90429. * STREAMINFO block with the correct statistics after encoding (like
  90430. * minimum/maximum frame size and total samples).
  90431. *
  90432. * \note In general, FLAC__StreamEncoder functions which change the
  90433. * state should not be called on the \a encoder while in the callback.
  90434. *
  90435. * \param encoder The encoder instance calling the callback.
  90436. * \param metadata The final populated STREAMINFO block.
  90437. * \param client_data The callee's client data set through
  90438. * FLAC__stream_encoder_init_*().
  90439. */
  90440. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  90441. /** Signature for the progress callback.
  90442. *
  90443. * A function pointer matching this signature may be passed to
  90444. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  90445. * The supplied function will be called when the encoder has finished
  90446. * writing a frame. The \c total_frames_estimate argument to the
  90447. * callback will be based on the value from
  90448. * FLAC__stream_encoder_set_total_samples_estimate().
  90449. *
  90450. * \note In general, FLAC__StreamEncoder functions which change the
  90451. * state should not be called on the \a encoder while in the callback.
  90452. *
  90453. * \param encoder The encoder instance calling the callback.
  90454. * \param bytes_written Bytes written so far.
  90455. * \param samples_written Samples written so far.
  90456. * \param frames_written Frames written so far.
  90457. * \param total_frames_estimate The estimate of the total number of
  90458. * frames to be written.
  90459. * \param client_data The callee's client data set through
  90460. * FLAC__stream_encoder_init_*().
  90461. */
  90462. 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);
  90463. /***********************************************************************
  90464. *
  90465. * Class constructor/destructor
  90466. *
  90467. ***********************************************************************/
  90468. /** Create a new stream encoder instance. The instance is created with
  90469. * default settings; see the individual FLAC__stream_encoder_set_*()
  90470. * functions for each setting's default.
  90471. *
  90472. * \retval FLAC__StreamEncoder*
  90473. * \c NULL if there was an error allocating memory, else the new instance.
  90474. */
  90475. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  90476. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  90477. *
  90478. * \param encoder A pointer to an existing encoder.
  90479. * \assert
  90480. * \code encoder != NULL \endcode
  90481. */
  90482. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  90483. /***********************************************************************
  90484. *
  90485. * Public class method prototypes
  90486. *
  90487. ***********************************************************************/
  90488. /** Set the serial number for the FLAC stream to use in the Ogg container.
  90489. *
  90490. * \note
  90491. * This does not need to be set for native FLAC encoding.
  90492. *
  90493. * \note
  90494. * It is recommended to set a serial number explicitly as the default of '0'
  90495. * may collide with other streams.
  90496. *
  90497. * \default \c 0
  90498. * \param encoder An encoder instance to set.
  90499. * \param serial_number See above.
  90500. * \assert
  90501. * \code encoder != NULL \endcode
  90502. * \retval FLAC__bool
  90503. * \c false if the encoder is already initialized, else \c true.
  90504. */
  90505. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  90506. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  90507. * encoded output by feeding it through an internal decoder and comparing
  90508. * the original signal against the decoded signal. If a mismatch occurs,
  90509. * the process call will return \c false. Note that this will slow the
  90510. * encoding process by the extra time required for decoding and comparison.
  90511. *
  90512. * \default \c false
  90513. * \param encoder An encoder instance to set.
  90514. * \param value Flag value (see above).
  90515. * \assert
  90516. * \code encoder != NULL \endcode
  90517. * \retval FLAC__bool
  90518. * \c false if the encoder is already initialized, else \c true.
  90519. */
  90520. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  90521. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  90522. * the encoder will comply with the Subset and will check the
  90523. * settings during FLAC__stream_encoder_init_*() to see if all settings
  90524. * comply. If \c false, the settings may take advantage of the full
  90525. * range that the format allows.
  90526. *
  90527. * Make sure you know what it entails before setting this to \c false.
  90528. *
  90529. * \default \c true
  90530. * \param encoder An encoder instance to set.
  90531. * \param value Flag value (see above).
  90532. * \assert
  90533. * \code encoder != NULL \endcode
  90534. * \retval FLAC__bool
  90535. * \c false if the encoder is already initialized, else \c true.
  90536. */
  90537. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  90538. /** Set the number of channels to be encoded.
  90539. *
  90540. * \default \c 2
  90541. * \param encoder An encoder instance to set.
  90542. * \param value See above.
  90543. * \assert
  90544. * \code encoder != NULL \endcode
  90545. * \retval FLAC__bool
  90546. * \c false if the encoder is already initialized, else \c true.
  90547. */
  90548. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
  90549. /** Set the sample resolution of the input to be encoded.
  90550. *
  90551. * \warning
  90552. * Do not feed the encoder data that is wider than the value you
  90553. * set here or you will generate an invalid stream.
  90554. *
  90555. * \default \c 16
  90556. * \param encoder An encoder instance to set.
  90557. * \param value See above.
  90558. * \assert
  90559. * \code encoder != NULL \endcode
  90560. * \retval FLAC__bool
  90561. * \c false if the encoder is already initialized, else \c true.
  90562. */
  90563. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  90564. /** Set the sample rate (in Hz) of the input to be encoded.
  90565. *
  90566. * \default \c 44100
  90567. * \param encoder An encoder instance to set.
  90568. * \param value See above.
  90569. * \assert
  90570. * \code encoder != NULL \endcode
  90571. * \retval FLAC__bool
  90572. * \c false if the encoder is already initialized, else \c true.
  90573. */
  90574. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  90575. /** Set the compression level
  90576. *
  90577. * The compression level is roughly proportional to the amount of effort
  90578. * the encoder expends to compress the file. A higher level usually
  90579. * means more computation but higher compression. The default level is
  90580. * suitable for most applications.
  90581. *
  90582. * Currently the levels range from \c 0 (fastest, least compression) to
  90583. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  90584. * treated as \c 8.
  90585. *
  90586. * This function automatically calls the following other \c _set_
  90587. * functions with appropriate values, so the client does not need to
  90588. * unless it specifically wants to override them:
  90589. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  90590. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  90591. * - FLAC__stream_encoder_set_apodization()
  90592. * - FLAC__stream_encoder_set_max_lpc_order()
  90593. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  90594. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  90595. * - FLAC__stream_encoder_set_do_escape_coding()
  90596. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  90597. * - FLAC__stream_encoder_set_min_residual_partition_order()
  90598. * - FLAC__stream_encoder_set_max_residual_partition_order()
  90599. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  90600. *
  90601. * The actual values set for each level are:
  90602. * <table>
  90603. * <tr>
  90604. * <td><b>level</b><td>
  90605. * <td>do mid-side stereo<td>
  90606. * <td>loose mid-side stereo<td>
  90607. * <td>apodization<td>
  90608. * <td>max lpc order<td>
  90609. * <td>qlp coeff precision<td>
  90610. * <td>qlp coeff prec search<td>
  90611. * <td>escape coding<td>
  90612. * <td>exhaustive model search<td>
  90613. * <td>min residual partition order<td>
  90614. * <td>max residual partition order<td>
  90615. * <td>rice parameter search dist<td>
  90616. * </tr>
  90617. * <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>
  90618. * <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>
  90619. * <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>
  90620. * <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>
  90621. * <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>
  90622. * <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>
  90623. * <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>
  90624. * <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>
  90625. * <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>
  90626. * </table>
  90627. *
  90628. * \default \c 5
  90629. * \param encoder An encoder instance to set.
  90630. * \param value See above.
  90631. * \assert
  90632. * \code encoder != NULL \endcode
  90633. * \retval FLAC__bool
  90634. * \c false if the encoder is already initialized, else \c true.
  90635. */
  90636. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  90637. /** Set the blocksize to use while encoding.
  90638. *
  90639. * The number of samples to use per frame. Use \c 0 to let the encoder
  90640. * estimate a blocksize; this is usually best.
  90641. *
  90642. * \default \c 0
  90643. * \param encoder An encoder instance to set.
  90644. * \param value See above.
  90645. * \assert
  90646. * \code encoder != NULL \endcode
  90647. * \retval FLAC__bool
  90648. * \c false if the encoder is already initialized, else \c true.
  90649. */
  90650. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  90651. /** Set to \c true to enable mid-side encoding on stereo input. The
  90652. * number of channels must be 2 for this to have any effect. Set to
  90653. * \c false to use only independent channel coding.
  90654. *
  90655. * \default \c false
  90656. * \param encoder An encoder instance to set.
  90657. * \param value Flag value (see above).
  90658. * \assert
  90659. * \code encoder != NULL \endcode
  90660. * \retval FLAC__bool
  90661. * \c false if the encoder is already initialized, else \c true.
  90662. */
  90663. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  90664. /** Set to \c true to enable adaptive switching between mid-side and
  90665. * left-right encoding on stereo input. Set to \c false to use
  90666. * exhaustive searching. Setting this to \c true requires
  90667. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  90668. * \c true in order to have any effect.
  90669. *
  90670. * \default \c false
  90671. * \param encoder An encoder instance to set.
  90672. * \param value Flag value (see above).
  90673. * \assert
  90674. * \code encoder != NULL \endcode
  90675. * \retval FLAC__bool
  90676. * \c false if the encoder is already initialized, else \c true.
  90677. */
  90678. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  90679. /** Sets the apodization function(s) the encoder will use when windowing
  90680. * audio data for LPC analysis.
  90681. *
  90682. * The \a specification is a plain ASCII string which specifies exactly
  90683. * which functions to use. There may be more than one (up to 32),
  90684. * separated by \c ';' characters. Some functions take one or more
  90685. * comma-separated arguments in parentheses.
  90686. *
  90687. * The available functions are \c bartlett, \c bartlett_hann,
  90688. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  90689. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  90690. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  90691. *
  90692. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  90693. * (0<STDDEV<=0.5).
  90694. *
  90695. * For \c tukey(P), P specifies the fraction of the window that is
  90696. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  90697. * corresponds to \c hann.
  90698. *
  90699. * Example specifications are \c "blackman" or
  90700. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  90701. *
  90702. * Any function that is specified erroneously is silently dropped. Up
  90703. * to 32 functions are kept, the rest are dropped. If the specification
  90704. * is empty the encoder defaults to \c "tukey(0.5)".
  90705. *
  90706. * When more than one function is specified, then for every subframe the
  90707. * encoder will try each of them separately and choose the window that
  90708. * results in the smallest compressed subframe.
  90709. *
  90710. * Note that each function specified causes the encoder to occupy a
  90711. * floating point array in which to store the window.
  90712. *
  90713. * \default \c "tukey(0.5)"
  90714. * \param encoder An encoder instance to set.
  90715. * \param specification See above.
  90716. * \assert
  90717. * \code encoder != NULL \endcode
  90718. * \code specification != NULL \endcode
  90719. * \retval FLAC__bool
  90720. * \c false if the encoder is already initialized, else \c true.
  90721. */
  90722. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  90723. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  90724. *
  90725. * \default \c 0
  90726. * \param encoder An encoder instance to set.
  90727. * \param value See above.
  90728. * \assert
  90729. * \code encoder != NULL \endcode
  90730. * \retval FLAC__bool
  90731. * \c false if the encoder is already initialized, else \c true.
  90732. */
  90733. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  90734. /** Set the precision, in bits, of the quantized linear predictor
  90735. * coefficients, or \c 0 to let the encoder select it based on the
  90736. * blocksize.
  90737. *
  90738. * \note
  90739. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  90740. * be less than 32.
  90741. *
  90742. * \default \c 0
  90743. * \param encoder An encoder instance to set.
  90744. * \param value See above.
  90745. * \assert
  90746. * \code encoder != NULL \endcode
  90747. * \retval FLAC__bool
  90748. * \c false if the encoder is already initialized, else \c true.
  90749. */
  90750. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  90751. /** Set to \c false to use only the specified quantized linear predictor
  90752. * coefficient precision, or \c true to search neighboring precision
  90753. * values and use the best one.
  90754. *
  90755. * \default \c false
  90756. * \param encoder An encoder instance to set.
  90757. * \param value See above.
  90758. * \assert
  90759. * \code encoder != NULL \endcode
  90760. * \retval FLAC__bool
  90761. * \c false if the encoder is already initialized, else \c true.
  90762. */
  90763. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  90764. /** Deprecated. Setting this value has no effect.
  90765. *
  90766. * \default \c false
  90767. * \param encoder An encoder instance to set.
  90768. * \param value See above.
  90769. * \assert
  90770. * \code encoder != NULL \endcode
  90771. * \retval FLAC__bool
  90772. * \c false if the encoder is already initialized, else \c true.
  90773. */
  90774. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  90775. /** Set to \c false to let the encoder estimate the best model order
  90776. * based on the residual signal energy, or \c true to force the
  90777. * encoder to evaluate all order models and select the best.
  90778. *
  90779. * \default \c false
  90780. * \param encoder An encoder instance to set.
  90781. * \param value See above.
  90782. * \assert
  90783. * \code encoder != NULL \endcode
  90784. * \retval FLAC__bool
  90785. * \c false if the encoder is already initialized, else \c true.
  90786. */
  90787. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  90788. /** Set the minimum partition order to search when coding the residual.
  90789. * This is used in tandem with
  90790. * FLAC__stream_encoder_set_max_residual_partition_order().
  90791. *
  90792. * The partition order determines the context size in the residual.
  90793. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  90794. *
  90795. * Set both min and max values to \c 0 to force a single context,
  90796. * whose Rice parameter is based on the residual signal variance.
  90797. * Otherwise, set a min and max order, and the encoder will search
  90798. * all orders, using the mean of each context for its Rice parameter,
  90799. * and use the best.
  90800. *
  90801. * \default \c 0
  90802. * \param encoder An encoder instance to set.
  90803. * \param value See above.
  90804. * \assert
  90805. * \code encoder != NULL \endcode
  90806. * \retval FLAC__bool
  90807. * \c false if the encoder is already initialized, else \c true.
  90808. */
  90809. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  90810. /** Set the maximum partition order to search when coding the residual.
  90811. * This is used in tandem with
  90812. * FLAC__stream_encoder_set_min_residual_partition_order().
  90813. *
  90814. * The partition order determines the context size in the residual.
  90815. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  90816. *
  90817. * Set both min and max values to \c 0 to force a single context,
  90818. * whose Rice parameter is based on the residual signal variance.
  90819. * Otherwise, set a min and max order, and the encoder will search
  90820. * all orders, using the mean of each context for its Rice parameter,
  90821. * and use the best.
  90822. *
  90823. * \default \c 0
  90824. * \param encoder An encoder instance to set.
  90825. * \param value See above.
  90826. * \assert
  90827. * \code encoder != NULL \endcode
  90828. * \retval FLAC__bool
  90829. * \c false if the encoder is already initialized, else \c true.
  90830. */
  90831. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  90832. /** Deprecated. Setting this value has no effect.
  90833. *
  90834. * \default \c 0
  90835. * \param encoder An encoder instance to set.
  90836. * \param value See above.
  90837. * \assert
  90838. * \code encoder != NULL \endcode
  90839. * \retval FLAC__bool
  90840. * \c false if the encoder is already initialized, else \c true.
  90841. */
  90842. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  90843. /** Set an estimate of the total samples that will be encoded.
  90844. * This is merely an estimate and may be set to \c 0 if unknown.
  90845. * This value will be written to the STREAMINFO block before encoding,
  90846. * and can remove the need for the caller to rewrite the value later
  90847. * if the value is known before encoding.
  90848. *
  90849. * \default \c 0
  90850. * \param encoder An encoder instance to set.
  90851. * \param value See above.
  90852. * \assert
  90853. * \code encoder != NULL \endcode
  90854. * \retval FLAC__bool
  90855. * \c false if the encoder is already initialized, else \c true.
  90856. */
  90857. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  90858. /** Set the metadata blocks to be emitted to the stream before encoding.
  90859. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  90860. * array of pointers to metadata blocks. The array is non-const since
  90861. * the encoder may need to change the \a is_last flag inside them, and
  90862. * in some cases update seek point offsets. Otherwise, the encoder will
  90863. * not modify or free the blocks. It is up to the caller to free the
  90864. * metadata blocks after encoding finishes.
  90865. *
  90866. * \note
  90867. * The encoder stores only copies of the pointers in the \a metadata array;
  90868. * the metadata blocks themselves must survive at least until after
  90869. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  90870. *
  90871. * \note
  90872. * The STREAMINFO block is always written and no STREAMINFO block may
  90873. * occur in the supplied array.
  90874. *
  90875. * \note
  90876. * By default the encoder does not create a SEEKTABLE. If one is supplied
  90877. * in the \a metadata array, but the client has specified that it does not
  90878. * support seeking, then the SEEKTABLE will be written verbatim. However
  90879. * by itself this is not very useful as the client will not know the stream
  90880. * offsets for the seekpoints ahead of time. In order to get a proper
  90881. * seektable the client must support seeking. See next note.
  90882. *
  90883. * \note
  90884. * SEEKTABLE blocks are handled specially. Since you will not know
  90885. * the values for the seek point stream offsets, you should pass in
  90886. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  90887. * required sample numbers (or placeholder points), with \c 0 for the
  90888. * \a frame_samples and \a stream_offset fields for each point. If the
  90889. * client has specified that it supports seeking by providing a seek
  90890. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  90891. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  90892. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  90893. * then while it is encoding the encoder will fill the stream offsets in
  90894. * for you and when encoding is finished, it will seek back and write the
  90895. * real values into the SEEKTABLE block in the stream. There are helper
  90896. * routines for manipulating seektable template blocks; see metadata.h:
  90897. * FLAC__metadata_object_seektable_template_*(). If the client does
  90898. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  90899. * will slow down or remove the ability to seek in the FLAC stream.
  90900. *
  90901. * \note
  90902. * The encoder instance \b will modify the first \c SEEKTABLE block
  90903. * as it transforms the template to a valid seektable while encoding,
  90904. * but it is still up to the caller to free all metadata blocks after
  90905. * encoding.
  90906. *
  90907. * \note
  90908. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  90909. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  90910. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  90911. * will simply write it's own into the stream. If no VORBIS_COMMENT
  90912. * block is present in the \a metadata array, libFLAC will write an
  90913. * empty one, containing only the vendor string.
  90914. *
  90915. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  90916. * the second metadata block of the stream. The encoder already supplies
  90917. * the STREAMINFO block automatically. If \a metadata does not contain a
  90918. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  90919. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  90920. * first, the init function will reorder \a metadata by moving the
  90921. * VORBIS_COMMENT block to the front; the relative ordering of the other
  90922. * blocks will remain as they were.
  90923. *
  90924. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  90925. * stream to \c 65535. If \a num_blocks exceeds this the function will
  90926. * return \c false.
  90927. *
  90928. * \default \c NULL, 0
  90929. * \param encoder An encoder instance to set.
  90930. * \param metadata See above.
  90931. * \param num_blocks See above.
  90932. * \assert
  90933. * \code encoder != NULL \endcode
  90934. * \retval FLAC__bool
  90935. * \c false if the encoder is already initialized, else \c true.
  90936. * \c false if the encoder is already initialized, or if
  90937. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  90938. */
  90939. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  90940. /** Get the current encoder state.
  90941. *
  90942. * \param encoder An encoder instance to query.
  90943. * \assert
  90944. * \code encoder != NULL \endcode
  90945. * \retval FLAC__StreamEncoderState
  90946. * The current encoder state.
  90947. */
  90948. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  90949. /** Get the state of the verify stream decoder.
  90950. * Useful when the stream encoder state is
  90951. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  90952. *
  90953. * \param encoder An encoder instance to query.
  90954. * \assert
  90955. * \code encoder != NULL \endcode
  90956. * \retval FLAC__StreamDecoderState
  90957. * The verify stream decoder state.
  90958. */
  90959. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  90960. /** Get the current encoder state as a C string.
  90961. * This version automatically resolves
  90962. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  90963. * verify decoder's state.
  90964. *
  90965. * \param encoder A encoder instance to query.
  90966. * \assert
  90967. * \code encoder != NULL \endcode
  90968. * \retval const char *
  90969. * The encoder state as a C string. Do not modify the contents.
  90970. */
  90971. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  90972. /** Get relevant values about the nature of a verify decoder error.
  90973. * Useful when the stream encoder state is
  90974. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  90975. * be addresses in which the stats will be returned, or NULL if value
  90976. * is not desired.
  90977. *
  90978. * \param encoder An encoder instance to query.
  90979. * \param absolute_sample The absolute sample number of the mismatch.
  90980. * \param frame_number The number of the frame in which the mismatch occurred.
  90981. * \param channel The channel in which the mismatch occurred.
  90982. * \param sample The number of the sample (relative to the frame) in
  90983. * which the mismatch occurred.
  90984. * \param expected The expected value for the sample in question.
  90985. * \param got The actual value returned by the decoder.
  90986. * \assert
  90987. * \code encoder != NULL \endcode
  90988. */
  90989. 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);
  90990. /** Get the "verify" flag.
  90991. *
  90992. * \param encoder An encoder instance to query.
  90993. * \assert
  90994. * \code encoder != NULL \endcode
  90995. * \retval FLAC__bool
  90996. * See FLAC__stream_encoder_set_verify().
  90997. */
  90998. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  90999. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  91000. *
  91001. * \param encoder An encoder instance to query.
  91002. * \assert
  91003. * \code encoder != NULL \endcode
  91004. * \retval FLAC__bool
  91005. * See FLAC__stream_encoder_set_streamable_subset().
  91006. */
  91007. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  91008. /** Get the number of input channels being processed.
  91009. *
  91010. * \param encoder An encoder instance to query.
  91011. * \assert
  91012. * \code encoder != NULL \endcode
  91013. * \retval unsigned
  91014. * See FLAC__stream_encoder_set_channels().
  91015. */
  91016. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  91017. /** Get the input sample resolution setting.
  91018. *
  91019. * \param encoder An encoder instance to query.
  91020. * \assert
  91021. * \code encoder != NULL \endcode
  91022. * \retval unsigned
  91023. * See FLAC__stream_encoder_set_bits_per_sample().
  91024. */
  91025. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  91026. /** Get the input sample rate setting.
  91027. *
  91028. * \param encoder An encoder instance to query.
  91029. * \assert
  91030. * \code encoder != NULL \endcode
  91031. * \retval unsigned
  91032. * See FLAC__stream_encoder_set_sample_rate().
  91033. */
  91034. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  91035. /** Get the blocksize setting.
  91036. *
  91037. * \param encoder An encoder instance to query.
  91038. * \assert
  91039. * \code encoder != NULL \endcode
  91040. * \retval unsigned
  91041. * See FLAC__stream_encoder_set_blocksize().
  91042. */
  91043. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  91044. /** Get the "mid/side stereo coding" flag.
  91045. *
  91046. * \param encoder An encoder instance to query.
  91047. * \assert
  91048. * \code encoder != NULL \endcode
  91049. * \retval FLAC__bool
  91050. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  91051. */
  91052. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  91053. /** Get the "adaptive mid/side switching" flag.
  91054. *
  91055. * \param encoder An encoder instance to query.
  91056. * \assert
  91057. * \code encoder != NULL \endcode
  91058. * \retval FLAC__bool
  91059. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  91060. */
  91061. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  91062. /** Get the maximum LPC order setting.
  91063. *
  91064. * \param encoder An encoder instance to query.
  91065. * \assert
  91066. * \code encoder != NULL \endcode
  91067. * \retval unsigned
  91068. * See FLAC__stream_encoder_set_max_lpc_order().
  91069. */
  91070. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  91071. /** Get the quantized linear predictor coefficient precision setting.
  91072. *
  91073. * \param encoder An encoder instance to query.
  91074. * \assert
  91075. * \code encoder != NULL \endcode
  91076. * \retval unsigned
  91077. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  91078. */
  91079. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  91080. /** Get the qlp coefficient precision search flag.
  91081. *
  91082. * \param encoder An encoder instance to query.
  91083. * \assert
  91084. * \code encoder != NULL \endcode
  91085. * \retval FLAC__bool
  91086. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  91087. */
  91088. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  91089. /** Get the "escape coding" flag.
  91090. *
  91091. * \param encoder An encoder instance to query.
  91092. * \assert
  91093. * \code encoder != NULL \endcode
  91094. * \retval FLAC__bool
  91095. * See FLAC__stream_encoder_set_do_escape_coding().
  91096. */
  91097. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  91098. /** Get the exhaustive model search flag.
  91099. *
  91100. * \param encoder An encoder instance to query.
  91101. * \assert
  91102. * \code encoder != NULL \endcode
  91103. * \retval FLAC__bool
  91104. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  91105. */
  91106. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  91107. /** Get the minimum residual partition order setting.
  91108. *
  91109. * \param encoder An encoder instance to query.
  91110. * \assert
  91111. * \code encoder != NULL \endcode
  91112. * \retval unsigned
  91113. * See FLAC__stream_encoder_set_min_residual_partition_order().
  91114. */
  91115. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  91116. /** Get maximum residual partition order setting.
  91117. *
  91118. * \param encoder An encoder instance to query.
  91119. * \assert
  91120. * \code encoder != NULL \endcode
  91121. * \retval unsigned
  91122. * See FLAC__stream_encoder_set_max_residual_partition_order().
  91123. */
  91124. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  91125. /** Get the Rice parameter search distance setting.
  91126. *
  91127. * \param encoder An encoder instance to query.
  91128. * \assert
  91129. * \code encoder != NULL \endcode
  91130. * \retval unsigned
  91131. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  91132. */
  91133. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  91134. /** Get the previously set estimate of the total samples to be encoded.
  91135. * The encoder merely mimics back the value given to
  91136. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  91137. * other way of knowing how many samples the client will encode.
  91138. *
  91139. * \param encoder An encoder instance to set.
  91140. * \assert
  91141. * \code encoder != NULL \endcode
  91142. * \retval FLAC__uint64
  91143. * See FLAC__stream_encoder_get_total_samples_estimate().
  91144. */
  91145. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  91146. /** Initialize the encoder instance to encode native FLAC streams.
  91147. *
  91148. * This flavor of initialization sets up the encoder to encode to a
  91149. * native FLAC stream. I/O is performed via callbacks to the client.
  91150. * For encoding to a plain file via filename or open \c FILE*,
  91151. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  91152. * provide a simpler interface.
  91153. *
  91154. * This function should be called after FLAC__stream_encoder_new() and
  91155. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91156. * or FLAC__stream_encoder_process_interleaved().
  91157. * initialization succeeded.
  91158. *
  91159. * The call to FLAC__stream_encoder_init_stream() currently will also
  91160. * immediately call the write callback several times, once with the \c fLaC
  91161. * signature, and once for each encoded metadata block.
  91162. *
  91163. * \param encoder An uninitialized encoder instance.
  91164. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  91165. * pointer must not be \c NULL.
  91166. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  91167. * pointer may be \c NULL if seeking is not
  91168. * supported. The encoder uses seeking to go back
  91169. * and write some some stream statistics to the
  91170. * STREAMINFO block; this is recommended but not
  91171. * necessary to create a valid FLAC stream. If
  91172. * \a seek_callback is not \c NULL then a
  91173. * \a tell_callback must also be supplied.
  91174. * Alternatively, a dummy seek callback that just
  91175. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  91176. * may also be supplied, all though this is slightly
  91177. * less efficient for the encoder.
  91178. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  91179. * pointer may be \c NULL if seeking is not
  91180. * supported. If \a seek_callback is \c NULL then
  91181. * this argument will be ignored. If
  91182. * \a seek_callback is not \c NULL then a
  91183. * \a tell_callback must also be supplied.
  91184. * Alternatively, a dummy tell callback that just
  91185. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  91186. * may also be supplied, all though this is slightly
  91187. * less efficient for the encoder.
  91188. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  91189. * pointer may be \c NULL if the callback is not
  91190. * desired. If the client provides a seek callback,
  91191. * this function is not necessary as the encoder
  91192. * will automatically seek back and update the
  91193. * STREAMINFO block. It may also be \c NULL if the
  91194. * client does not support seeking, since it will
  91195. * have no way of going back to update the
  91196. * STREAMINFO. However the client can still supply
  91197. * a callback if it would like to know the details
  91198. * from the STREAMINFO.
  91199. * \param client_data This value will be supplied to callbacks in their
  91200. * \a client_data argument.
  91201. * \assert
  91202. * \code encoder != NULL \endcode
  91203. * \retval FLAC__StreamEncoderInitStatus
  91204. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91205. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91206. */
  91207. 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);
  91208. /** Initialize the encoder instance to encode Ogg FLAC streams.
  91209. *
  91210. * This flavor of initialization sets up the encoder to encode to a FLAC
  91211. * stream in an Ogg container. I/O is performed via callbacks to the
  91212. * client. For encoding to a plain file via filename or open \c FILE*,
  91213. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  91214. * provide a simpler interface.
  91215. *
  91216. * This function should be called after FLAC__stream_encoder_new() and
  91217. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91218. * or FLAC__stream_encoder_process_interleaved().
  91219. * initialization succeeded.
  91220. *
  91221. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  91222. * immediately call the write callback several times to write the metadata
  91223. * packets.
  91224. *
  91225. * \param encoder An uninitialized encoder instance.
  91226. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  91227. * pointer must not be \c NULL if \a seek_callback
  91228. * is non-NULL since they are both needed to be
  91229. * able to write data back to the Ogg FLAC stream
  91230. * in the post-encode phase.
  91231. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  91232. * pointer must not be \c NULL.
  91233. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  91234. * pointer may be \c NULL if seeking is not
  91235. * supported. The encoder uses seeking to go back
  91236. * and write some some stream statistics to the
  91237. * STREAMINFO block; this is recommended but not
  91238. * necessary to create a valid FLAC stream. If
  91239. * \a seek_callback is not \c NULL then a
  91240. * \a tell_callback must also be supplied.
  91241. * Alternatively, a dummy seek callback that just
  91242. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  91243. * may also be supplied, all though this is slightly
  91244. * less efficient for the encoder.
  91245. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  91246. * pointer may be \c NULL if seeking is not
  91247. * supported. If \a seek_callback is \c NULL then
  91248. * this argument will be ignored. If
  91249. * \a seek_callback is not \c NULL then a
  91250. * \a tell_callback must also be supplied.
  91251. * Alternatively, a dummy tell callback that just
  91252. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  91253. * may also be supplied, all though this is slightly
  91254. * less efficient for the encoder.
  91255. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  91256. * pointer may be \c NULL if the callback is not
  91257. * desired. If the client provides a seek callback,
  91258. * this function is not necessary as the encoder
  91259. * will automatically seek back and update the
  91260. * STREAMINFO block. It may also be \c NULL if the
  91261. * client does not support seeking, since it will
  91262. * have no way of going back to update the
  91263. * STREAMINFO. However the client can still supply
  91264. * a callback if it would like to know the details
  91265. * from the STREAMINFO.
  91266. * \param client_data This value will be supplied to callbacks in their
  91267. * \a client_data argument.
  91268. * \assert
  91269. * \code encoder != NULL \endcode
  91270. * \retval FLAC__StreamEncoderInitStatus
  91271. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91272. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91273. */
  91274. 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);
  91275. /** Initialize the encoder instance to encode native FLAC files.
  91276. *
  91277. * This flavor of initialization sets up the encoder to encode to a
  91278. * plain native FLAC file. For non-stdio streams, you must use
  91279. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  91280. *
  91281. * This function should be called after FLAC__stream_encoder_new() and
  91282. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91283. * or FLAC__stream_encoder_process_interleaved().
  91284. * initialization succeeded.
  91285. *
  91286. * \param encoder An uninitialized encoder instance.
  91287. * \param file An open file. The file should have been opened
  91288. * with mode \c "w+b" and rewound. The file
  91289. * becomes owned by the encoder and should not be
  91290. * manipulated by the client while encoding.
  91291. * Unless \a file is \c stdout, it will be closed
  91292. * when FLAC__stream_encoder_finish() is called.
  91293. * Note however that a proper SEEKTABLE cannot be
  91294. * created when encoding to \c stdout since it is
  91295. * not seekable.
  91296. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91297. * pointer may be \c NULL if the callback is not
  91298. * desired.
  91299. * \param client_data This value will be supplied to callbacks in their
  91300. * \a client_data argument.
  91301. * \assert
  91302. * \code encoder != NULL \endcode
  91303. * \code file != NULL \endcode
  91304. * \retval FLAC__StreamEncoderInitStatus
  91305. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91306. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91307. */
  91308. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91309. /** Initialize the encoder instance to encode Ogg FLAC files.
  91310. *
  91311. * This flavor of initialization sets up the encoder to encode to a
  91312. * plain Ogg FLAC file. For non-stdio streams, you must use
  91313. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  91314. *
  91315. * This function should be called after FLAC__stream_encoder_new() and
  91316. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91317. * or FLAC__stream_encoder_process_interleaved().
  91318. * initialization succeeded.
  91319. *
  91320. * \param encoder An uninitialized encoder instance.
  91321. * \param file An open file. The file should have been opened
  91322. * with mode \c "w+b" and rewound. The file
  91323. * becomes owned by the encoder and should not be
  91324. * manipulated by the client while encoding.
  91325. * Unless \a file is \c stdout, it will be closed
  91326. * when FLAC__stream_encoder_finish() is called.
  91327. * Note however that a proper SEEKTABLE cannot be
  91328. * created when encoding to \c stdout since it is
  91329. * not seekable.
  91330. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91331. * pointer may be \c NULL if the callback is not
  91332. * desired.
  91333. * \param client_data This value will be supplied to callbacks in their
  91334. * \a client_data argument.
  91335. * \assert
  91336. * \code encoder != NULL \endcode
  91337. * \code file != NULL \endcode
  91338. * \retval FLAC__StreamEncoderInitStatus
  91339. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91340. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91341. */
  91342. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91343. /** Initialize the encoder instance to encode native FLAC files.
  91344. *
  91345. * This flavor of initialization sets up the encoder to encode to a plain
  91346. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  91347. * with Unicode filenames on Windows), you must use
  91348. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  91349. * and provide callbacks for the I/O.
  91350. *
  91351. * This function should be called after FLAC__stream_encoder_new() and
  91352. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91353. * or FLAC__stream_encoder_process_interleaved().
  91354. * initialization succeeded.
  91355. *
  91356. * \param encoder An uninitialized encoder instance.
  91357. * \param filename The name of the file to encode to. The file will
  91358. * be opened with fopen(). Use \c NULL to encode to
  91359. * \c stdout. Note however that a proper SEEKTABLE
  91360. * cannot be created when encoding to \c stdout since
  91361. * it is not seekable.
  91362. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91363. * pointer may be \c NULL if the callback is not
  91364. * desired.
  91365. * \param client_data This value will be supplied to callbacks in their
  91366. * \a client_data argument.
  91367. * \assert
  91368. * \code encoder != NULL \endcode
  91369. * \retval FLAC__StreamEncoderInitStatus
  91370. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91371. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91372. */
  91373. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91374. /** Initialize the encoder instance to encode Ogg FLAC files.
  91375. *
  91376. * This flavor of initialization sets up the encoder to encode to a plain
  91377. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  91378. * with Unicode filenames on Windows), you must use
  91379. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  91380. * and provide callbacks for the I/O.
  91381. *
  91382. * This function should be called after FLAC__stream_encoder_new() and
  91383. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91384. * or FLAC__stream_encoder_process_interleaved().
  91385. * initialization succeeded.
  91386. *
  91387. * \param encoder An uninitialized encoder instance.
  91388. * \param filename The name of the file to encode to. The file will
  91389. * be opened with fopen(). Use \c NULL to encode to
  91390. * \c stdout. Note however that a proper SEEKTABLE
  91391. * cannot be created when encoding to \c stdout since
  91392. * it is not seekable.
  91393. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91394. * pointer may be \c NULL if the callback is not
  91395. * desired.
  91396. * \param client_data This value will be supplied to callbacks in their
  91397. * \a client_data argument.
  91398. * \assert
  91399. * \code encoder != NULL \endcode
  91400. * \retval FLAC__StreamEncoderInitStatus
  91401. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91402. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91403. */
  91404. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91405. /** Finish the encoding process.
  91406. * Flushes the encoding buffer, releases resources, resets the encoder
  91407. * settings to their defaults, and returns the encoder state to
  91408. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  91409. * one or more write callbacks before returning, and will generate
  91410. * a metadata callback.
  91411. *
  91412. * Note that in the course of processing the last frame, errors can
  91413. * occur, so the caller should be sure to check the return value to
  91414. * ensure the file was encoded properly.
  91415. *
  91416. * In the event of a prematurely-terminated encode, it is not strictly
  91417. * necessary to call this immediately before FLAC__stream_encoder_delete()
  91418. * but it is good practice to match every FLAC__stream_encoder_init_*()
  91419. * with a FLAC__stream_encoder_finish().
  91420. *
  91421. * \param encoder An uninitialized encoder instance.
  91422. * \assert
  91423. * \code encoder != NULL \endcode
  91424. * \retval FLAC__bool
  91425. * \c false if an error occurred processing the last frame; or if verify
  91426. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  91427. * verify mismatch; else \c true. If \c false, caller should check the
  91428. * state with FLAC__stream_encoder_get_state() for more information
  91429. * about the error.
  91430. */
  91431. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  91432. /** Submit data for encoding.
  91433. * This version allows you to supply the input data via an array of
  91434. * pointers, each pointer pointing to an array of \a samples samples
  91435. * representing one channel. The samples need not be block-aligned,
  91436. * but each channel should have the same number of samples. Each sample
  91437. * should be a signed integer, right-justified to the resolution set by
  91438. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  91439. * resolution is 16 bits per sample, the samples should all be in the
  91440. * range [-32768,32767].
  91441. *
  91442. * For applications where channel order is important, channels must
  91443. * follow the order as described in the
  91444. * <A HREF="../format.html#frame_header">frame header</A>.
  91445. *
  91446. * \param encoder An initialized encoder instance in the OK state.
  91447. * \param buffer An array of pointers to each channel's signal.
  91448. * \param samples The number of samples in one channel.
  91449. * \assert
  91450. * \code encoder != NULL \endcode
  91451. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  91452. * \retval FLAC__bool
  91453. * \c true if successful, else \c false; in this case, check the
  91454. * encoder state with FLAC__stream_encoder_get_state() to see what
  91455. * went wrong.
  91456. */
  91457. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  91458. /** Submit data for encoding.
  91459. * This version allows you to supply the input data where the channels
  91460. * are interleaved into a single array (i.e. channel0_sample0,
  91461. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  91462. * The samples need not be block-aligned but they must be
  91463. * sample-aligned, i.e. the first value should be channel0_sample0
  91464. * and the last value channelN_sampleM. Each sample should be a signed
  91465. * integer, right-justified to the resolution set by
  91466. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  91467. * resolution is 16 bits per sample, the samples should all be in the
  91468. * range [-32768,32767].
  91469. *
  91470. * For applications where channel order is important, channels must
  91471. * follow the order as described in the
  91472. * <A HREF="../format.html#frame_header">frame header</A>.
  91473. *
  91474. * \param encoder An initialized encoder instance in the OK state.
  91475. * \param buffer An array of channel-interleaved data (see above).
  91476. * \param samples The number of samples in one channel, the same as for
  91477. * FLAC__stream_encoder_process(). For example, if
  91478. * encoding two channels, \c 1000 \a samples corresponds
  91479. * to a \a buffer of 2000 values.
  91480. * \assert
  91481. * \code encoder != NULL \endcode
  91482. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  91483. * \retval FLAC__bool
  91484. * \c true if successful, else \c false; in this case, check the
  91485. * encoder state with FLAC__stream_encoder_get_state() to see what
  91486. * went wrong.
  91487. */
  91488. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  91489. /* \} */
  91490. #ifdef __cplusplus
  91491. }
  91492. #endif
  91493. #endif
  91494. /*** End of inlined file: stream_encoder.h ***/
  91495. #ifdef _MSC_VER
  91496. /* OPT: an MSVC built-in would be better */
  91497. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  91498. {
  91499. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  91500. return (x>>16) | (x<<16);
  91501. }
  91502. #endif
  91503. #if defined(_MSC_VER) && defined(_X86_)
  91504. /* OPT: an MSVC built-in would be better */
  91505. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  91506. {
  91507. __asm {
  91508. mov edx, start
  91509. mov ecx, len
  91510. test ecx, ecx
  91511. loop1:
  91512. jz done1
  91513. mov eax, [edx]
  91514. bswap eax
  91515. mov [edx], eax
  91516. add edx, 4
  91517. dec ecx
  91518. jmp short loop1
  91519. done1:
  91520. }
  91521. }
  91522. #endif
  91523. /** \mainpage
  91524. *
  91525. * \section intro Introduction
  91526. *
  91527. * This is the documentation for the FLAC C and C++ APIs. It is
  91528. * highly interconnected; this introduction should give you a top
  91529. * level idea of the structure and how to find the information you
  91530. * need. As a prerequisite you should have at least a basic
  91531. * knowledge of the FLAC format, documented
  91532. * <A HREF="../format.html">here</A>.
  91533. *
  91534. * \section c_api FLAC C API
  91535. *
  91536. * The FLAC C API is the interface to libFLAC, a set of structures
  91537. * describing the components of FLAC streams, and functions for
  91538. * encoding and decoding streams, as well as manipulating FLAC
  91539. * metadata in files. The public include files will be installed
  91540. * in your include area (for example /usr/include/FLAC/...).
  91541. *
  91542. * By writing a little code and linking against libFLAC, it is
  91543. * relatively easy to add FLAC support to another program. The
  91544. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  91545. * Complete source code of libFLAC as well as the command-line
  91546. * encoder and plugins is available and is a useful source of
  91547. * examples.
  91548. *
  91549. * Aside from encoders and decoders, libFLAC provides a powerful
  91550. * metadata interface for manipulating metadata in FLAC files. It
  91551. * allows the user to add, delete, and modify FLAC metadata blocks
  91552. * and it can automatically take advantage of PADDING blocks to avoid
  91553. * rewriting the entire FLAC file when changing the size of the
  91554. * metadata.
  91555. *
  91556. * libFLAC usually only requires the standard C library and C math
  91557. * library. In particular, threading is not used so there is no
  91558. * dependency on a thread library. However, libFLAC does not use
  91559. * global variables and should be thread-safe.
  91560. *
  91561. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  91562. * However the metadata editing interfaces currently have limited
  91563. * read-only support for Ogg FLAC files.
  91564. *
  91565. * \section cpp_api FLAC C++ API
  91566. *
  91567. * The FLAC C++ API is a set of classes that encapsulate the
  91568. * structures and functions in libFLAC. They provide slightly more
  91569. * functionality with respect to metadata but are otherwise
  91570. * equivalent. For the most part, they share the same usage as
  91571. * their counterparts in libFLAC, and the FLAC C API documentation
  91572. * can be used as a supplement. The public include files
  91573. * for the C++ API will be installed in your include area (for
  91574. * example /usr/include/FLAC++/...).
  91575. *
  91576. * libFLAC++ is also licensed under
  91577. * <A HREF="../license.html">Xiph's BSD license</A>.
  91578. *
  91579. * \section getting_started Getting Started
  91580. *
  91581. * A good starting point for learning the API is to browse through
  91582. * the <A HREF="modules.html">modules</A>. Modules are logical
  91583. * groupings of related functions or classes, which correspond roughly
  91584. * to header files or sections of header files. Each module includes a
  91585. * detailed description of the general usage of its functions or
  91586. * classes.
  91587. *
  91588. * From there you can go on to look at the documentation of
  91589. * individual functions. You can see different views of the individual
  91590. * functions through the links in top bar across this page.
  91591. *
  91592. * If you prefer a more hands-on approach, you can jump right to some
  91593. * <A HREF="../documentation_example_code.html">example code</A>.
  91594. *
  91595. * \section porting_guide Porting Guide
  91596. *
  91597. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  91598. * has been introduced which gives detailed instructions on how to
  91599. * port your code to newer versions of FLAC.
  91600. *
  91601. * \section embedded_developers Embedded Developers
  91602. *
  91603. * libFLAC has grown larger over time as more functionality has been
  91604. * included, but much of it may be unnecessary for a particular embedded
  91605. * implementation. Unused parts may be pruned by some simple editing of
  91606. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  91607. * metadata interface are all independent from each other.
  91608. *
  91609. * It is easiest to just describe the dependencies:
  91610. *
  91611. * - All modules depend on the \link flac_format Format \endlink module.
  91612. * - The decoders and encoders depend on the bitbuffer.
  91613. * - The decoder is independent of the encoder. The encoder uses the
  91614. * decoder because of the verify feature, but this can be removed if
  91615. * not needed.
  91616. * - Parts of the metadata interface require the stream decoder (but not
  91617. * the encoder).
  91618. * - Ogg support is selectable through the compile time macro
  91619. * \c FLAC__HAS_OGG.
  91620. *
  91621. * For example, if your application only requires the stream decoder, no
  91622. * encoder, and no metadata interface, you can remove the stream encoder
  91623. * and the metadata interface, which will greatly reduce the size of the
  91624. * library.
  91625. *
  91626. * Also, there are several places in the libFLAC code with comments marked
  91627. * with "OPT:" where a #define can be changed to enable code that might be
  91628. * faster on a specific platform. Experimenting with these can yield faster
  91629. * binaries.
  91630. */
  91631. /** \defgroup porting Porting Guide for New Versions
  91632. *
  91633. * This module describes differences in the library interfaces from
  91634. * version to version. It assists in the porting of code that uses
  91635. * the libraries to newer versions of FLAC.
  91636. *
  91637. * One simple facility for making porting easier that has been added
  91638. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  91639. * library's includes (e.g. \c include/FLAC/export.h). The
  91640. * \c #defines mirror the libraries'
  91641. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  91642. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  91643. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  91644. * These can be used to support multiple versions of an API during the
  91645. * transition phase, e.g.
  91646. *
  91647. * \code
  91648. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  91649. * legacy code
  91650. * #else
  91651. * new code
  91652. * #endif
  91653. * \endcode
  91654. *
  91655. * The the source will work for multiple versions and the legacy code can
  91656. * easily be removed when the transition is complete.
  91657. *
  91658. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  91659. * include/FLAC/export.h), which can be used to determine whether or not
  91660. * the library has been compiled with support for Ogg FLAC. This is
  91661. * simpler than trying to call an Ogg init function and catching the
  91662. * error.
  91663. */
  91664. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  91665. * \ingroup porting
  91666. *
  91667. * \brief
  91668. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  91669. *
  91670. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  91671. * been simplified. First, libOggFLAC has been merged into libFLAC and
  91672. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  91673. * decoding layers and three encoding layers have been merged into a
  91674. * single stream decoder and stream encoder. That is, the functionality
  91675. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  91676. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  91677. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  91678. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  91679. * is there is now a single API that can be used to encode or decode
  91680. * streams to/from native FLAC or Ogg FLAC and the single API can work
  91681. * on both seekable and non-seekable streams.
  91682. *
  91683. * Instead of creating an encoder or decoder of a certain layer, now the
  91684. * client will always create a FLAC__StreamEncoder or
  91685. * FLAC__StreamDecoder. The old layers are now differentiated by the
  91686. * initialization function. For example, for the decoder,
  91687. * FLAC__stream_decoder_init() has been replaced by
  91688. * FLAC__stream_decoder_init_stream(). This init function takes
  91689. * callbacks for the I/O, and the seeking callbacks are optional. This
  91690. * allows the client to use the same object for seekable and
  91691. * non-seekable streams. For decoding a FLAC file directly, the client
  91692. * can use FLAC__stream_decoder_init_file() and pass just a filename
  91693. * and fewer callbacks; most of the other callbacks are supplied
  91694. * internally. For situations where fopen()ing by filename is not
  91695. * possible (e.g. Unicode filenames on Windows) the client can instead
  91696. * open the file itself and supply the FILE* to
  91697. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  91698. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  91699. * Since the callbacks and client data are now passed to the init
  91700. * function, the FLAC__stream_decoder_set_*_callback() functions and
  91701. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  91702. * rest of the calls to the decoder are the same as before.
  91703. *
  91704. * There are counterpart init functions for Ogg FLAC, e.g.
  91705. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  91706. * and callbacks are the same as for native FLAC.
  91707. *
  91708. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  91709. * been set up like so:
  91710. *
  91711. * \code
  91712. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  91713. * if(decoder == NULL) do_something;
  91714. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  91715. * [... other settings ...]
  91716. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  91717. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  91718. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  91719. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  91720. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  91721. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  91722. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  91723. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  91724. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  91725. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  91726. * \endcode
  91727. *
  91728. * In FLAC 1.1.3 it is like this:
  91729. *
  91730. * \code
  91731. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  91732. * if(decoder == NULL) do_something;
  91733. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  91734. * [... other settings ...]
  91735. * if(FLAC__stream_decoder_init_stream(
  91736. * decoder,
  91737. * my_read_callback,
  91738. * my_seek_callback, // or NULL
  91739. * my_tell_callback, // or NULL
  91740. * my_length_callback, // or NULL
  91741. * my_eof_callback, // or NULL
  91742. * my_write_callback,
  91743. * my_metadata_callback, // or NULL
  91744. * my_error_callback,
  91745. * my_client_data
  91746. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  91747. * \endcode
  91748. *
  91749. * or you could do;
  91750. *
  91751. * \code
  91752. * [...]
  91753. * FILE *file = fopen("somefile.flac","rb");
  91754. * if(file == NULL) do_somthing;
  91755. * if(FLAC__stream_decoder_init_FILE(
  91756. * decoder,
  91757. * file,
  91758. * my_write_callback,
  91759. * my_metadata_callback, // or NULL
  91760. * my_error_callback,
  91761. * my_client_data
  91762. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  91763. * \endcode
  91764. *
  91765. * or just:
  91766. *
  91767. * \code
  91768. * [...]
  91769. * if(FLAC__stream_decoder_init_file(
  91770. * decoder,
  91771. * "somefile.flac",
  91772. * my_write_callback,
  91773. * my_metadata_callback, // or NULL
  91774. * my_error_callback,
  91775. * my_client_data
  91776. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  91777. * \endcode
  91778. *
  91779. * Another small change to the decoder is in how it handles unparseable
  91780. * streams. Before, when the decoder found an unparseable stream
  91781. * (reserved for when the decoder encounters a stream from a future
  91782. * encoder that it can't parse), it changed the state to
  91783. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  91784. * drops sync and calls the error callback with a new error code
  91785. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  91786. * more robust. If your error callback does not discriminate on the the
  91787. * error state, your code does not need to be changed.
  91788. *
  91789. * The encoder now has a new setting:
  91790. * FLAC__stream_encoder_set_apodization(). This is for setting the
  91791. * method used to window the data before LPC analysis. You only need to
  91792. * add a call to this function if the default is not suitable. There
  91793. * are also two new convenience functions that may be useful:
  91794. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  91795. * FLAC__metadata_get_cuesheet().
  91796. *
  91797. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  91798. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  91799. * is now \c size_t instead of \c unsigned.
  91800. */
  91801. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  91802. * \ingroup porting
  91803. *
  91804. * \brief
  91805. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  91806. *
  91807. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  91808. * There was a slight change in the implementation of
  91809. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  91810. * of the \a metadata array of pointers so the client no longer needs
  91811. * to maintain it after the call. The objects themselves that are
  91812. * pointed to by the array are still not copied though and must be
  91813. * maintained until the call to FLAC__stream_encoder_finish().
  91814. */
  91815. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  91816. * \ingroup porting
  91817. *
  91818. * \brief
  91819. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  91820. *
  91821. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  91822. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  91823. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  91824. *
  91825. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  91826. * has changed to reflect the conversion of one of the reserved bits
  91827. * into active use. It used to be \c 2 and now is \c 1. However the
  91828. * FLAC frame header length has not changed, so to skip the proper
  91829. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  91830. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  91831. */
  91832. /** \defgroup flac FLAC C API
  91833. *
  91834. * The FLAC C API is the interface to libFLAC, a set of structures
  91835. * describing the components of FLAC streams, and functions for
  91836. * encoding and decoding streams, as well as manipulating FLAC
  91837. * metadata in files.
  91838. *
  91839. * You should start with the format components as all other modules
  91840. * are dependent on it.
  91841. */
  91842. #endif
  91843. /*** End of inlined file: all.h ***/
  91844. /*** Start of inlined file: bitmath.c ***/
  91845. /*** Start of inlined file: juce_FlacHeader.h ***/
  91846. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  91847. // tasks..
  91848. #define VERSION "1.2.1"
  91849. #define FLAC__NO_DLL 1
  91850. #if JUCE_MSVC
  91851. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  91852. #endif
  91853. #if JUCE_MAC
  91854. #define FLAC__SYS_DARWIN 1
  91855. #endif
  91856. /*** End of inlined file: juce_FlacHeader.h ***/
  91857. #if JUCE_USE_FLAC
  91858. #if HAVE_CONFIG_H
  91859. # include <config.h>
  91860. #endif
  91861. /*** Start of inlined file: bitmath.h ***/
  91862. #ifndef FLAC__PRIVATE__BITMATH_H
  91863. #define FLAC__PRIVATE__BITMATH_H
  91864. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  91865. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  91866. unsigned FLAC__bitmath_silog2(int v);
  91867. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  91868. #endif
  91869. /*** End of inlined file: bitmath.h ***/
  91870. /* An example of what FLAC__bitmath_ilog2() computes:
  91871. *
  91872. * ilog2( 0) = assertion failure
  91873. * ilog2( 1) = 0
  91874. * ilog2( 2) = 1
  91875. * ilog2( 3) = 1
  91876. * ilog2( 4) = 2
  91877. * ilog2( 5) = 2
  91878. * ilog2( 6) = 2
  91879. * ilog2( 7) = 2
  91880. * ilog2( 8) = 3
  91881. * ilog2( 9) = 3
  91882. * ilog2(10) = 3
  91883. * ilog2(11) = 3
  91884. * ilog2(12) = 3
  91885. * ilog2(13) = 3
  91886. * ilog2(14) = 3
  91887. * ilog2(15) = 3
  91888. * ilog2(16) = 4
  91889. * ilog2(17) = 4
  91890. * ilog2(18) = 4
  91891. */
  91892. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  91893. {
  91894. unsigned l = 0;
  91895. FLAC__ASSERT(v > 0);
  91896. while(v >>= 1)
  91897. l++;
  91898. return l;
  91899. }
  91900. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  91901. {
  91902. unsigned l = 0;
  91903. FLAC__ASSERT(v > 0);
  91904. while(v >>= 1)
  91905. l++;
  91906. return l;
  91907. }
  91908. /* An example of what FLAC__bitmath_silog2() computes:
  91909. *
  91910. * silog2(-10) = 5
  91911. * silog2(- 9) = 5
  91912. * silog2(- 8) = 4
  91913. * silog2(- 7) = 4
  91914. * silog2(- 6) = 4
  91915. * silog2(- 5) = 4
  91916. * silog2(- 4) = 3
  91917. * silog2(- 3) = 3
  91918. * silog2(- 2) = 2
  91919. * silog2(- 1) = 2
  91920. * silog2( 0) = 0
  91921. * silog2( 1) = 2
  91922. * silog2( 2) = 3
  91923. * silog2( 3) = 3
  91924. * silog2( 4) = 4
  91925. * silog2( 5) = 4
  91926. * silog2( 6) = 4
  91927. * silog2( 7) = 4
  91928. * silog2( 8) = 5
  91929. * silog2( 9) = 5
  91930. * silog2( 10) = 5
  91931. */
  91932. unsigned FLAC__bitmath_silog2(int v)
  91933. {
  91934. while(1) {
  91935. if(v == 0) {
  91936. return 0;
  91937. }
  91938. else if(v > 0) {
  91939. unsigned l = 0;
  91940. while(v) {
  91941. l++;
  91942. v >>= 1;
  91943. }
  91944. return l+1;
  91945. }
  91946. else if(v == -1) {
  91947. return 2;
  91948. }
  91949. else {
  91950. v++;
  91951. v = -v;
  91952. }
  91953. }
  91954. }
  91955. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  91956. {
  91957. while(1) {
  91958. if(v == 0) {
  91959. return 0;
  91960. }
  91961. else if(v > 0) {
  91962. unsigned l = 0;
  91963. while(v) {
  91964. l++;
  91965. v >>= 1;
  91966. }
  91967. return l+1;
  91968. }
  91969. else if(v == -1) {
  91970. return 2;
  91971. }
  91972. else {
  91973. v++;
  91974. v = -v;
  91975. }
  91976. }
  91977. }
  91978. #endif
  91979. /*** End of inlined file: bitmath.c ***/
  91980. /*** Start of inlined file: bitreader.c ***/
  91981. /*** Start of inlined file: juce_FlacHeader.h ***/
  91982. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  91983. // tasks..
  91984. #define VERSION "1.2.1"
  91985. #define FLAC__NO_DLL 1
  91986. #if JUCE_MSVC
  91987. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  91988. #endif
  91989. #if JUCE_MAC
  91990. #define FLAC__SYS_DARWIN 1
  91991. #endif
  91992. /*** End of inlined file: juce_FlacHeader.h ***/
  91993. #if JUCE_USE_FLAC
  91994. #if HAVE_CONFIG_H
  91995. # include <config.h>
  91996. #endif
  91997. #include <stdlib.h> /* for malloc() */
  91998. #include <string.h> /* for memcpy(), memset() */
  91999. #ifdef _MSC_VER
  92000. #include <winsock.h> /* for ntohl() */
  92001. #elif defined FLAC__SYS_DARWIN
  92002. #include <machine/endian.h> /* for ntohl() */
  92003. #elif defined __MINGW32__
  92004. #include <winsock.h> /* for ntohl() */
  92005. #else
  92006. #include <netinet/in.h> /* for ntohl() */
  92007. #endif
  92008. /*** Start of inlined file: bitreader.h ***/
  92009. #ifndef FLAC__PRIVATE__BITREADER_H
  92010. #define FLAC__PRIVATE__BITREADER_H
  92011. #include <stdio.h> /* for FILE */
  92012. /*** Start of inlined file: cpu.h ***/
  92013. #ifndef FLAC__PRIVATE__CPU_H
  92014. #define FLAC__PRIVATE__CPU_H
  92015. #ifdef HAVE_CONFIG_H
  92016. #include <config.h>
  92017. #endif
  92018. typedef enum {
  92019. FLAC__CPUINFO_TYPE_IA32,
  92020. FLAC__CPUINFO_TYPE_PPC,
  92021. FLAC__CPUINFO_TYPE_UNKNOWN
  92022. } FLAC__CPUInfo_Type;
  92023. typedef struct {
  92024. FLAC__bool cpuid;
  92025. FLAC__bool bswap;
  92026. FLAC__bool cmov;
  92027. FLAC__bool mmx;
  92028. FLAC__bool fxsr;
  92029. FLAC__bool sse;
  92030. FLAC__bool sse2;
  92031. FLAC__bool sse3;
  92032. FLAC__bool ssse3;
  92033. FLAC__bool _3dnow;
  92034. FLAC__bool ext3dnow;
  92035. FLAC__bool extmmx;
  92036. } FLAC__CPUInfo_IA32;
  92037. typedef struct {
  92038. FLAC__bool altivec;
  92039. FLAC__bool ppc64;
  92040. } FLAC__CPUInfo_PPC;
  92041. typedef struct {
  92042. FLAC__bool use_asm;
  92043. FLAC__CPUInfo_Type type;
  92044. union {
  92045. FLAC__CPUInfo_IA32 ia32;
  92046. FLAC__CPUInfo_PPC ppc;
  92047. } data;
  92048. } FLAC__CPUInfo;
  92049. void FLAC__cpu_info(FLAC__CPUInfo *info);
  92050. #ifndef FLAC__NO_ASM
  92051. #ifdef FLAC__CPU_IA32
  92052. #ifdef FLAC__HAS_NASM
  92053. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  92054. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  92055. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  92056. #endif
  92057. #endif
  92058. #endif
  92059. #endif
  92060. /*** End of inlined file: cpu.h ***/
  92061. /*
  92062. * opaque structure definition
  92063. */
  92064. struct FLAC__BitReader;
  92065. typedef struct FLAC__BitReader FLAC__BitReader;
  92066. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  92067. /*
  92068. * construction, deletion, initialization, etc functions
  92069. */
  92070. FLAC__BitReader *FLAC__bitreader_new(void);
  92071. void FLAC__bitreader_delete(FLAC__BitReader *br);
  92072. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  92073. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  92074. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  92075. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  92076. /*
  92077. * CRC functions
  92078. */
  92079. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  92080. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  92081. /*
  92082. * info functions
  92083. */
  92084. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  92085. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  92086. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  92087. /*
  92088. * read functions
  92089. */
  92090. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  92091. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  92092. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  92093. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  92094. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  92095. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  92096. 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! */
  92097. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  92098. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  92099. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  92100. #ifndef FLAC__NO_ASM
  92101. # ifdef FLAC__CPU_IA32
  92102. # ifdef FLAC__HAS_NASM
  92103. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  92104. # endif
  92105. # endif
  92106. #endif
  92107. #if 0 /* UNUSED */
  92108. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  92109. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  92110. #endif
  92111. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  92112. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  92113. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  92114. #endif
  92115. /*** End of inlined file: bitreader.h ***/
  92116. /*** Start of inlined file: crc.h ***/
  92117. #ifndef FLAC__PRIVATE__CRC_H
  92118. #define FLAC__PRIVATE__CRC_H
  92119. /* 8 bit CRC generator, MSB shifted first
  92120. ** polynomial = x^8 + x^2 + x^1 + x^0
  92121. ** init = 0
  92122. */
  92123. extern FLAC__byte const FLAC__crc8_table[256];
  92124. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  92125. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  92126. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  92127. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  92128. /* 16 bit CRC generator, MSB shifted first
  92129. ** polynomial = x^16 + x^15 + x^2 + x^0
  92130. ** init = 0
  92131. */
  92132. extern unsigned FLAC__crc16_table[256];
  92133. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  92134. /* this alternate may be faster on some systems/compilers */
  92135. #if 0
  92136. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  92137. #endif
  92138. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  92139. #endif
  92140. /*** End of inlined file: crc.h ***/
  92141. /* Things should be fastest when this matches the machine word size */
  92142. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  92143. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  92144. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  92145. typedef FLAC__uint32 brword;
  92146. #define FLAC__BYTES_PER_WORD 4
  92147. #define FLAC__BITS_PER_WORD 32
  92148. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  92149. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  92150. #if WORDS_BIGENDIAN
  92151. #define SWAP_BE_WORD_TO_HOST(x) (x)
  92152. #else
  92153. #if defined (_MSC_VER) && defined (_X86_)
  92154. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  92155. #else
  92156. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  92157. #endif
  92158. #endif
  92159. /* counts the # of zero MSBs in a word */
  92160. #define COUNT_ZERO_MSBS(word) ( \
  92161. (word) <= 0xffff ? \
  92162. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  92163. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  92164. )
  92165. /* this alternate might be slightly faster on some systems/compilers: */
  92166. #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])) )
  92167. /*
  92168. * This should be at least twice as large as the largest number of words
  92169. * required to represent any 'number' (in any encoding) you are going to
  92170. * read. With FLAC this is on the order of maybe a few hundred bits.
  92171. * If the buffer is smaller than that, the decoder won't be able to read
  92172. * in a whole number that is in a variable length encoding (e.g. Rice).
  92173. * But to be practical it should be at least 1K bytes.
  92174. *
  92175. * Increase this number to decrease the number of read callbacks, at the
  92176. * expense of using more memory. Or decrease for the reverse effect,
  92177. * keeping in mind the limit from the first paragraph. The optimal size
  92178. * also depends on the CPU cache size and other factors; some twiddling
  92179. * may be necessary to squeeze out the best performance.
  92180. */
  92181. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  92182. static const unsigned char byte_to_unary_table[] = {
  92183. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  92184. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  92185. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  92186. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  92187. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92188. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92189. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92190. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  92199. };
  92200. #ifdef min
  92201. #undef min
  92202. #endif
  92203. #define min(x,y) ((x)<(y)?(x):(y))
  92204. #ifdef max
  92205. #undef max
  92206. #endif
  92207. #define max(x,y) ((x)>(y)?(x):(y))
  92208. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  92209. #ifdef _MSC_VER
  92210. #define FLAC__U64L(x) x
  92211. #else
  92212. #define FLAC__U64L(x) x##LLU
  92213. #endif
  92214. #ifndef FLaC__INLINE
  92215. #define FLaC__INLINE
  92216. #endif
  92217. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  92218. struct FLAC__BitReader {
  92219. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  92220. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  92221. brword *buffer;
  92222. unsigned capacity; /* in words */
  92223. unsigned words; /* # of completed words in buffer */
  92224. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  92225. unsigned consumed_words; /* #words ... */
  92226. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  92227. unsigned read_crc16; /* the running frame CRC */
  92228. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  92229. FLAC__BitReaderReadCallback read_callback;
  92230. void *client_data;
  92231. FLAC__CPUInfo cpu_info;
  92232. };
  92233. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  92234. {
  92235. register unsigned crc = br->read_crc16;
  92236. #if FLAC__BYTES_PER_WORD == 4
  92237. switch(br->crc16_align) {
  92238. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  92239. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  92240. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  92241. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  92242. }
  92243. #elif FLAC__BYTES_PER_WORD == 8
  92244. switch(br->crc16_align) {
  92245. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  92246. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  92247. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  92248. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  92249. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  92250. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  92251. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  92252. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  92253. }
  92254. #else
  92255. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  92256. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  92257. br->read_crc16 = crc;
  92258. #endif
  92259. br->crc16_align = 0;
  92260. }
  92261. /* would be static except it needs to be called by asm routines */
  92262. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  92263. {
  92264. unsigned start, end;
  92265. size_t bytes;
  92266. FLAC__byte *target;
  92267. /* first shift the unconsumed buffer data toward the front as much as possible */
  92268. if(br->consumed_words > 0) {
  92269. start = br->consumed_words;
  92270. end = br->words + (br->bytes? 1:0);
  92271. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  92272. br->words -= start;
  92273. br->consumed_words = 0;
  92274. }
  92275. /*
  92276. * set the target for reading, taking into account word alignment and endianness
  92277. */
  92278. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  92279. if(bytes == 0)
  92280. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  92281. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  92282. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  92283. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  92284. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  92285. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  92286. * ^^-------target, bytes=3
  92287. * on LE machines, have to byteswap the odd tail word so nothing is
  92288. * overwritten:
  92289. */
  92290. #if WORDS_BIGENDIAN
  92291. #else
  92292. if(br->bytes)
  92293. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  92294. #endif
  92295. /* now it looks like:
  92296. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  92297. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  92298. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  92299. * ^^-------target, bytes=3
  92300. */
  92301. /* read in the data; note that the callback may return a smaller number of bytes */
  92302. if(!br->read_callback(target, &bytes, br->client_data))
  92303. return false;
  92304. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  92305. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  92306. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  92307. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  92308. * now have to byteswap on LE machines:
  92309. */
  92310. #if WORDS_BIGENDIAN
  92311. #else
  92312. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  92313. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  92314. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  92315. start = br->words;
  92316. local_swap32_block_(br->buffer + start, end - start);
  92317. }
  92318. else
  92319. # endif
  92320. for(start = br->words; start < end; start++)
  92321. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  92322. #endif
  92323. /* now it looks like:
  92324. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  92325. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  92326. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  92327. * finally we'll update the reader values:
  92328. */
  92329. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  92330. br->words = end / FLAC__BYTES_PER_WORD;
  92331. br->bytes = end % FLAC__BYTES_PER_WORD;
  92332. return true;
  92333. }
  92334. /***********************************************************************
  92335. *
  92336. * Class constructor/destructor
  92337. *
  92338. ***********************************************************************/
  92339. FLAC__BitReader *FLAC__bitreader_new(void)
  92340. {
  92341. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  92342. /* calloc() implies:
  92343. memset(br, 0, sizeof(FLAC__BitReader));
  92344. br->buffer = 0;
  92345. br->capacity = 0;
  92346. br->words = br->bytes = 0;
  92347. br->consumed_words = br->consumed_bits = 0;
  92348. br->read_callback = 0;
  92349. br->client_data = 0;
  92350. */
  92351. return br;
  92352. }
  92353. void FLAC__bitreader_delete(FLAC__BitReader *br)
  92354. {
  92355. FLAC__ASSERT(0 != br);
  92356. FLAC__bitreader_free(br);
  92357. free(br);
  92358. }
  92359. /***********************************************************************
  92360. *
  92361. * Public class methods
  92362. *
  92363. ***********************************************************************/
  92364. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  92365. {
  92366. FLAC__ASSERT(0 != br);
  92367. br->words = br->bytes = 0;
  92368. br->consumed_words = br->consumed_bits = 0;
  92369. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  92370. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  92371. if(br->buffer == 0)
  92372. return false;
  92373. br->read_callback = rcb;
  92374. br->client_data = cd;
  92375. br->cpu_info = cpu;
  92376. return true;
  92377. }
  92378. void FLAC__bitreader_free(FLAC__BitReader *br)
  92379. {
  92380. FLAC__ASSERT(0 != br);
  92381. if(0 != br->buffer)
  92382. free(br->buffer);
  92383. br->buffer = 0;
  92384. br->capacity = 0;
  92385. br->words = br->bytes = 0;
  92386. br->consumed_words = br->consumed_bits = 0;
  92387. br->read_callback = 0;
  92388. br->client_data = 0;
  92389. }
  92390. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  92391. {
  92392. br->words = br->bytes = 0;
  92393. br->consumed_words = br->consumed_bits = 0;
  92394. return true;
  92395. }
  92396. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  92397. {
  92398. unsigned i, j;
  92399. if(br == 0) {
  92400. fprintf(out, "bitreader is NULL\n");
  92401. }
  92402. else {
  92403. 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);
  92404. for(i = 0; i < br->words; i++) {
  92405. fprintf(out, "%08X: ", i);
  92406. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  92407. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  92408. fprintf(out, ".");
  92409. else
  92410. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  92411. fprintf(out, "\n");
  92412. }
  92413. if(br->bytes > 0) {
  92414. fprintf(out, "%08X: ", i);
  92415. for(j = 0; j < br->bytes*8; j++)
  92416. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  92417. fprintf(out, ".");
  92418. else
  92419. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  92420. fprintf(out, "\n");
  92421. }
  92422. }
  92423. }
  92424. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  92425. {
  92426. FLAC__ASSERT(0 != br);
  92427. FLAC__ASSERT(0 != br->buffer);
  92428. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  92429. br->read_crc16 = (unsigned)seed;
  92430. br->crc16_align = br->consumed_bits;
  92431. }
  92432. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  92433. {
  92434. FLAC__ASSERT(0 != br);
  92435. FLAC__ASSERT(0 != br->buffer);
  92436. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  92437. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  92438. /* CRC any tail bytes in a partially-consumed word */
  92439. if(br->consumed_bits) {
  92440. const brword tail = br->buffer[br->consumed_words];
  92441. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  92442. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  92443. }
  92444. return br->read_crc16;
  92445. }
  92446. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  92447. {
  92448. return ((br->consumed_bits & 7) == 0);
  92449. }
  92450. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  92451. {
  92452. return 8 - (br->consumed_bits & 7);
  92453. }
  92454. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  92455. {
  92456. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  92457. }
  92458. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  92459. {
  92460. FLAC__ASSERT(0 != br);
  92461. FLAC__ASSERT(0 != br->buffer);
  92462. FLAC__ASSERT(bits <= 32);
  92463. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  92464. FLAC__ASSERT(br->consumed_words <= br->words);
  92465. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  92466. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  92467. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  92468. *val = 0;
  92469. return true;
  92470. }
  92471. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  92472. if(!bitreader_read_from_client_(br))
  92473. return false;
  92474. }
  92475. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  92476. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  92477. if(br->consumed_bits) {
  92478. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  92479. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  92480. const brword word = br->buffer[br->consumed_words];
  92481. if(bits < n) {
  92482. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  92483. br->consumed_bits += bits;
  92484. return true;
  92485. }
  92486. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  92487. bits -= n;
  92488. crc16_update_word_(br, word);
  92489. br->consumed_words++;
  92490. br->consumed_bits = 0;
  92491. 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 */
  92492. *val <<= bits;
  92493. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  92494. br->consumed_bits = bits;
  92495. }
  92496. return true;
  92497. }
  92498. else {
  92499. const brword word = br->buffer[br->consumed_words];
  92500. if(bits < FLAC__BITS_PER_WORD) {
  92501. *val = word >> (FLAC__BITS_PER_WORD-bits);
  92502. br->consumed_bits = bits;
  92503. return true;
  92504. }
  92505. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  92506. *val = word;
  92507. crc16_update_word_(br, word);
  92508. br->consumed_words++;
  92509. return true;
  92510. }
  92511. }
  92512. else {
  92513. /* in this case we're starting our read at a partial tail word;
  92514. * the reader has guaranteed that we have at least 'bits' bits
  92515. * available to read, which makes this case simpler.
  92516. */
  92517. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  92518. if(br->consumed_bits) {
  92519. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  92520. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  92521. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  92522. br->consumed_bits += bits;
  92523. return true;
  92524. }
  92525. else {
  92526. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  92527. br->consumed_bits += bits;
  92528. return true;
  92529. }
  92530. }
  92531. }
  92532. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  92533. {
  92534. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  92535. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  92536. return false;
  92537. /* sign-extend: */
  92538. *val <<= (32-bits);
  92539. *val >>= (32-bits);
  92540. return true;
  92541. }
  92542. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  92543. {
  92544. FLAC__uint32 hi, lo;
  92545. if(bits > 32) {
  92546. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  92547. return false;
  92548. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  92549. return false;
  92550. *val = hi;
  92551. *val <<= 32;
  92552. *val |= lo;
  92553. }
  92554. else {
  92555. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  92556. return false;
  92557. *val = lo;
  92558. }
  92559. return true;
  92560. }
  92561. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  92562. {
  92563. FLAC__uint32 x8, x32 = 0;
  92564. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  92565. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  92566. return false;
  92567. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  92568. return false;
  92569. x32 |= (x8 << 8);
  92570. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  92571. return false;
  92572. x32 |= (x8 << 16);
  92573. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  92574. return false;
  92575. x32 |= (x8 << 24);
  92576. *val = x32;
  92577. return true;
  92578. }
  92579. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  92580. {
  92581. /*
  92582. * OPT: a faster implementation is possible but probably not that useful
  92583. * since this is only called a couple of times in the metadata readers.
  92584. */
  92585. FLAC__ASSERT(0 != br);
  92586. FLAC__ASSERT(0 != br->buffer);
  92587. if(bits > 0) {
  92588. const unsigned n = br->consumed_bits & 7;
  92589. unsigned m;
  92590. FLAC__uint32 x;
  92591. if(n != 0) {
  92592. m = min(8-n, bits);
  92593. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  92594. return false;
  92595. bits -= m;
  92596. }
  92597. m = bits / 8;
  92598. if(m > 0) {
  92599. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  92600. return false;
  92601. bits %= 8;
  92602. }
  92603. if(bits > 0) {
  92604. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  92605. return false;
  92606. }
  92607. }
  92608. return true;
  92609. }
  92610. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  92611. {
  92612. FLAC__uint32 x;
  92613. FLAC__ASSERT(0 != br);
  92614. FLAC__ASSERT(0 != br->buffer);
  92615. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  92616. /* step 1: skip over partial head word to get word aligned */
  92617. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  92618. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  92619. return false;
  92620. nvals--;
  92621. }
  92622. if(0 == nvals)
  92623. return true;
  92624. /* step 2: skip whole words in chunks */
  92625. while(nvals >= FLAC__BYTES_PER_WORD) {
  92626. if(br->consumed_words < br->words) {
  92627. br->consumed_words++;
  92628. nvals -= FLAC__BYTES_PER_WORD;
  92629. }
  92630. else if(!bitreader_read_from_client_(br))
  92631. return false;
  92632. }
  92633. /* step 3: skip any remainder from partial tail bytes */
  92634. while(nvals) {
  92635. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  92636. return false;
  92637. nvals--;
  92638. }
  92639. return true;
  92640. }
  92641. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  92642. {
  92643. FLAC__uint32 x;
  92644. FLAC__ASSERT(0 != br);
  92645. FLAC__ASSERT(0 != br->buffer);
  92646. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  92647. /* step 1: read from partial head word to get word aligned */
  92648. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  92649. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  92650. return false;
  92651. *val++ = (FLAC__byte)x;
  92652. nvals--;
  92653. }
  92654. if(0 == nvals)
  92655. return true;
  92656. /* step 2: read whole words in chunks */
  92657. while(nvals >= FLAC__BYTES_PER_WORD) {
  92658. if(br->consumed_words < br->words) {
  92659. const brword word = br->buffer[br->consumed_words++];
  92660. #if FLAC__BYTES_PER_WORD == 4
  92661. val[0] = (FLAC__byte)(word >> 24);
  92662. val[1] = (FLAC__byte)(word >> 16);
  92663. val[2] = (FLAC__byte)(word >> 8);
  92664. val[3] = (FLAC__byte)word;
  92665. #elif FLAC__BYTES_PER_WORD == 8
  92666. val[0] = (FLAC__byte)(word >> 56);
  92667. val[1] = (FLAC__byte)(word >> 48);
  92668. val[2] = (FLAC__byte)(word >> 40);
  92669. val[3] = (FLAC__byte)(word >> 32);
  92670. val[4] = (FLAC__byte)(word >> 24);
  92671. val[5] = (FLAC__byte)(word >> 16);
  92672. val[6] = (FLAC__byte)(word >> 8);
  92673. val[7] = (FLAC__byte)word;
  92674. #else
  92675. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  92676. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  92677. #endif
  92678. val += FLAC__BYTES_PER_WORD;
  92679. nvals -= FLAC__BYTES_PER_WORD;
  92680. }
  92681. else if(!bitreader_read_from_client_(br))
  92682. return false;
  92683. }
  92684. /* step 3: read any remainder from partial tail bytes */
  92685. while(nvals) {
  92686. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  92687. return false;
  92688. *val++ = (FLAC__byte)x;
  92689. nvals--;
  92690. }
  92691. return true;
  92692. }
  92693. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  92694. #if 0 /* slow but readable version */
  92695. {
  92696. unsigned bit;
  92697. FLAC__ASSERT(0 != br);
  92698. FLAC__ASSERT(0 != br->buffer);
  92699. *val = 0;
  92700. while(1) {
  92701. if(!FLAC__bitreader_read_bit(br, &bit))
  92702. return false;
  92703. if(bit)
  92704. break;
  92705. else
  92706. *val++;
  92707. }
  92708. return true;
  92709. }
  92710. #else
  92711. {
  92712. unsigned i;
  92713. FLAC__ASSERT(0 != br);
  92714. FLAC__ASSERT(0 != br->buffer);
  92715. *val = 0;
  92716. while(1) {
  92717. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  92718. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  92719. if(b) {
  92720. i = COUNT_ZERO_MSBS(b);
  92721. *val += i;
  92722. i++;
  92723. br->consumed_bits += i;
  92724. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  92725. crc16_update_word_(br, br->buffer[br->consumed_words]);
  92726. br->consumed_words++;
  92727. br->consumed_bits = 0;
  92728. }
  92729. return true;
  92730. }
  92731. else {
  92732. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  92733. crc16_update_word_(br, br->buffer[br->consumed_words]);
  92734. br->consumed_words++;
  92735. br->consumed_bits = 0;
  92736. /* didn't find stop bit yet, have to keep going... */
  92737. }
  92738. }
  92739. /* at this point we've eaten up all the whole words; have to try
  92740. * reading through any tail bytes before calling the read callback.
  92741. * this is a repeat of the above logic adjusted for the fact we
  92742. * don't have a whole word. note though if the client is feeding
  92743. * us data a byte at a time (unlikely), br->consumed_bits may not
  92744. * be zero.
  92745. */
  92746. if(br->bytes) {
  92747. const unsigned end = br->bytes * 8;
  92748. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  92749. if(b) {
  92750. i = COUNT_ZERO_MSBS(b);
  92751. *val += i;
  92752. i++;
  92753. br->consumed_bits += i;
  92754. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  92755. return true;
  92756. }
  92757. else {
  92758. *val += end - br->consumed_bits;
  92759. br->consumed_bits += end;
  92760. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  92761. /* didn't find stop bit yet, have to keep going... */
  92762. }
  92763. }
  92764. if(!bitreader_read_from_client_(br))
  92765. return false;
  92766. }
  92767. }
  92768. #endif
  92769. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  92770. {
  92771. FLAC__uint32 lsbs = 0, msbs = 0;
  92772. unsigned uval;
  92773. FLAC__ASSERT(0 != br);
  92774. FLAC__ASSERT(0 != br->buffer);
  92775. FLAC__ASSERT(parameter <= 31);
  92776. /* read the unary MSBs and end bit */
  92777. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  92778. return false;
  92779. /* read the binary LSBs */
  92780. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  92781. return false;
  92782. /* compose the value */
  92783. uval = (msbs << parameter) | lsbs;
  92784. if(uval & 1)
  92785. *val = -((int)(uval >> 1)) - 1;
  92786. else
  92787. *val = (int)(uval >> 1);
  92788. return true;
  92789. }
  92790. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  92791. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  92792. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  92793. /* OPT: possibly faster version for use with MSVC */
  92794. #ifdef _MSC_VER
  92795. {
  92796. unsigned i;
  92797. unsigned uval = 0;
  92798. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  92799. /* try and get br->consumed_words and br->consumed_bits into register;
  92800. * must remember to flush them back to *br before calling other
  92801. * bitwriter functions that use them, and before returning */
  92802. register unsigned cwords;
  92803. register unsigned cbits;
  92804. FLAC__ASSERT(0 != br);
  92805. FLAC__ASSERT(0 != br->buffer);
  92806. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  92807. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  92808. FLAC__ASSERT(parameter < 32);
  92809. /* 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 */
  92810. if(nvals == 0)
  92811. return true;
  92812. cbits = br->consumed_bits;
  92813. cwords = br->consumed_words;
  92814. while(1) {
  92815. /* read unary part */
  92816. while(1) {
  92817. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  92818. brword b = br->buffer[cwords] << cbits;
  92819. if(b) {
  92820. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  92821. __asm {
  92822. bsr eax, b
  92823. not eax
  92824. and eax, 31
  92825. mov i, eax
  92826. }
  92827. #else
  92828. i = COUNT_ZERO_MSBS(b);
  92829. #endif
  92830. uval += i;
  92831. bits = parameter;
  92832. i++;
  92833. cbits += i;
  92834. if(cbits == FLAC__BITS_PER_WORD) {
  92835. crc16_update_word_(br, br->buffer[cwords]);
  92836. cwords++;
  92837. cbits = 0;
  92838. }
  92839. goto break1;
  92840. }
  92841. else {
  92842. uval += FLAC__BITS_PER_WORD - cbits;
  92843. crc16_update_word_(br, br->buffer[cwords]);
  92844. cwords++;
  92845. cbits = 0;
  92846. /* didn't find stop bit yet, have to keep going... */
  92847. }
  92848. }
  92849. /* at this point we've eaten up all the whole words; have to try
  92850. * reading through any tail bytes before calling the read callback.
  92851. * this is a repeat of the above logic adjusted for the fact we
  92852. * don't have a whole word. note though if the client is feeding
  92853. * us data a byte at a time (unlikely), br->consumed_bits may not
  92854. * be zero.
  92855. */
  92856. if(br->bytes) {
  92857. const unsigned end = br->bytes * 8;
  92858. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  92859. if(b) {
  92860. i = COUNT_ZERO_MSBS(b);
  92861. uval += i;
  92862. bits = parameter;
  92863. i++;
  92864. cbits += i;
  92865. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  92866. goto break1;
  92867. }
  92868. else {
  92869. uval += end - cbits;
  92870. cbits += end;
  92871. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  92872. /* didn't find stop bit yet, have to keep going... */
  92873. }
  92874. }
  92875. /* flush registers and read; bitreader_read_from_client_() does
  92876. * not touch br->consumed_bits at all but we still need to set
  92877. * it in case it fails and we have to return false.
  92878. */
  92879. br->consumed_bits = cbits;
  92880. br->consumed_words = cwords;
  92881. if(!bitreader_read_from_client_(br))
  92882. return false;
  92883. cwords = br->consumed_words;
  92884. }
  92885. break1:
  92886. /* read binary part */
  92887. FLAC__ASSERT(cwords <= br->words);
  92888. if(bits) {
  92889. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  92890. /* flush registers and read; bitreader_read_from_client_() does
  92891. * not touch br->consumed_bits at all but we still need to set
  92892. * it in case it fails and we have to return false.
  92893. */
  92894. br->consumed_bits = cbits;
  92895. br->consumed_words = cwords;
  92896. if(!bitreader_read_from_client_(br))
  92897. return false;
  92898. cwords = br->consumed_words;
  92899. }
  92900. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  92901. if(cbits) {
  92902. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  92903. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  92904. const brword word = br->buffer[cwords];
  92905. if(bits < n) {
  92906. uval <<= bits;
  92907. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  92908. cbits += bits;
  92909. goto break2;
  92910. }
  92911. uval <<= n;
  92912. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  92913. bits -= n;
  92914. crc16_update_word_(br, word);
  92915. cwords++;
  92916. cbits = 0;
  92917. 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 */
  92918. uval <<= bits;
  92919. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  92920. cbits = bits;
  92921. }
  92922. goto break2;
  92923. }
  92924. else {
  92925. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  92926. uval <<= bits;
  92927. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  92928. cbits = bits;
  92929. goto break2;
  92930. }
  92931. }
  92932. else {
  92933. /* in this case we're starting our read at a partial tail word;
  92934. * the reader has guaranteed that we have at least 'bits' bits
  92935. * available to read, which makes this case simpler.
  92936. */
  92937. uval <<= bits;
  92938. if(cbits) {
  92939. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  92940. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  92941. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  92942. cbits += bits;
  92943. goto break2;
  92944. }
  92945. else {
  92946. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  92947. cbits += bits;
  92948. goto break2;
  92949. }
  92950. }
  92951. }
  92952. break2:
  92953. /* compose the value */
  92954. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  92955. /* are we done? */
  92956. --nvals;
  92957. if(nvals == 0) {
  92958. br->consumed_bits = cbits;
  92959. br->consumed_words = cwords;
  92960. return true;
  92961. }
  92962. uval = 0;
  92963. ++vals;
  92964. }
  92965. }
  92966. #else
  92967. {
  92968. unsigned i;
  92969. unsigned uval = 0;
  92970. /* try and get br->consumed_words and br->consumed_bits into register;
  92971. * must remember to flush them back to *br before calling other
  92972. * bitwriter functions that use them, and before returning */
  92973. register unsigned cwords;
  92974. register unsigned cbits;
  92975. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  92976. FLAC__ASSERT(0 != br);
  92977. FLAC__ASSERT(0 != br->buffer);
  92978. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  92979. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  92980. FLAC__ASSERT(parameter < 32);
  92981. /* 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 */
  92982. if(nvals == 0)
  92983. return true;
  92984. cbits = br->consumed_bits;
  92985. cwords = br->consumed_words;
  92986. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  92987. while(1) {
  92988. /* read unary part */
  92989. while(1) {
  92990. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  92991. brword b = br->buffer[cwords] << cbits;
  92992. if(b) {
  92993. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  92994. asm volatile (
  92995. "bsrl %1, %0;"
  92996. "notl %0;"
  92997. "andl $31, %0;"
  92998. : "=r"(i)
  92999. : "r"(b)
  93000. );
  93001. #else
  93002. i = COUNT_ZERO_MSBS(b);
  93003. #endif
  93004. uval += i;
  93005. cbits += i;
  93006. cbits++; /* skip over stop bit */
  93007. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  93008. crc16_update_word_(br, br->buffer[cwords]);
  93009. cwords++;
  93010. cbits = 0;
  93011. }
  93012. goto break1;
  93013. }
  93014. else {
  93015. uval += FLAC__BITS_PER_WORD - cbits;
  93016. crc16_update_word_(br, br->buffer[cwords]);
  93017. cwords++;
  93018. cbits = 0;
  93019. /* didn't find stop bit yet, have to keep going... */
  93020. }
  93021. }
  93022. /* at this point we've eaten up all the whole words; have to try
  93023. * reading through any tail bytes before calling the read callback.
  93024. * this is a repeat of the above logic adjusted for the fact we
  93025. * don't have a whole word. note though if the client is feeding
  93026. * us data a byte at a time (unlikely), br->consumed_bits may not
  93027. * be zero.
  93028. */
  93029. if(br->bytes) {
  93030. const unsigned end = br->bytes * 8;
  93031. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  93032. if(b) {
  93033. i = COUNT_ZERO_MSBS(b);
  93034. uval += i;
  93035. cbits += i;
  93036. cbits++; /* skip over stop bit */
  93037. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93038. goto break1;
  93039. }
  93040. else {
  93041. uval += end - cbits;
  93042. cbits += end;
  93043. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93044. /* didn't find stop bit yet, have to keep going... */
  93045. }
  93046. }
  93047. /* flush registers and read; bitreader_read_from_client_() does
  93048. * not touch br->consumed_bits at all but we still need to set
  93049. * it in case it fails and we have to return false.
  93050. */
  93051. br->consumed_bits = cbits;
  93052. br->consumed_words = cwords;
  93053. if(!bitreader_read_from_client_(br))
  93054. return false;
  93055. cwords = br->consumed_words;
  93056. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  93057. /* + uval to offset our count by the # of unary bits already
  93058. * consumed before the read, because we will add these back
  93059. * in all at once at break1
  93060. */
  93061. }
  93062. break1:
  93063. ucbits -= uval;
  93064. ucbits--; /* account for stop bit */
  93065. /* read binary part */
  93066. FLAC__ASSERT(cwords <= br->words);
  93067. if(parameter) {
  93068. while(ucbits < parameter) {
  93069. /* flush registers and read; bitreader_read_from_client_() does
  93070. * not touch br->consumed_bits at all but we still need to set
  93071. * it in case it fails and we have to return false.
  93072. */
  93073. br->consumed_bits = cbits;
  93074. br->consumed_words = cwords;
  93075. if(!bitreader_read_from_client_(br))
  93076. return false;
  93077. cwords = br->consumed_words;
  93078. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  93079. }
  93080. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93081. if(cbits) {
  93082. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  93083. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  93084. const brword word = br->buffer[cwords];
  93085. if(parameter < n) {
  93086. uval <<= parameter;
  93087. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  93088. cbits += parameter;
  93089. }
  93090. else {
  93091. uval <<= n;
  93092. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  93093. crc16_update_word_(br, word);
  93094. cwords++;
  93095. cbits = parameter - n;
  93096. 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 */
  93097. uval <<= cbits;
  93098. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  93099. }
  93100. }
  93101. }
  93102. else {
  93103. cbits = parameter;
  93104. uval <<= parameter;
  93105. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  93106. }
  93107. }
  93108. else {
  93109. /* in this case we're starting our read at a partial tail word;
  93110. * the reader has guaranteed that we have at least 'parameter'
  93111. * bits available to read, which makes this case simpler.
  93112. */
  93113. uval <<= parameter;
  93114. if(cbits) {
  93115. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93116. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  93117. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  93118. cbits += parameter;
  93119. }
  93120. else {
  93121. cbits = parameter;
  93122. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  93123. }
  93124. }
  93125. }
  93126. ucbits -= parameter;
  93127. /* compose the value */
  93128. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  93129. /* are we done? */
  93130. --nvals;
  93131. if(nvals == 0) {
  93132. br->consumed_bits = cbits;
  93133. br->consumed_words = cwords;
  93134. return true;
  93135. }
  93136. uval = 0;
  93137. ++vals;
  93138. }
  93139. }
  93140. #endif
  93141. #if 0 /* UNUSED */
  93142. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  93143. {
  93144. FLAC__uint32 lsbs = 0, msbs = 0;
  93145. unsigned bit, uval, k;
  93146. FLAC__ASSERT(0 != br);
  93147. FLAC__ASSERT(0 != br->buffer);
  93148. k = FLAC__bitmath_ilog2(parameter);
  93149. /* read the unary MSBs and end bit */
  93150. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  93151. return false;
  93152. /* read the binary LSBs */
  93153. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  93154. return false;
  93155. if(parameter == 1u<<k) {
  93156. /* compose the value */
  93157. uval = (msbs << k) | lsbs;
  93158. }
  93159. else {
  93160. unsigned d = (1 << (k+1)) - parameter;
  93161. if(lsbs >= d) {
  93162. if(!FLAC__bitreader_read_bit(br, &bit))
  93163. return false;
  93164. lsbs <<= 1;
  93165. lsbs |= bit;
  93166. lsbs -= d;
  93167. }
  93168. /* compose the value */
  93169. uval = msbs * parameter + lsbs;
  93170. }
  93171. /* unfold unsigned to signed */
  93172. if(uval & 1)
  93173. *val = -((int)(uval >> 1)) - 1;
  93174. else
  93175. *val = (int)(uval >> 1);
  93176. return true;
  93177. }
  93178. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  93179. {
  93180. FLAC__uint32 lsbs, msbs = 0;
  93181. unsigned bit, k;
  93182. FLAC__ASSERT(0 != br);
  93183. FLAC__ASSERT(0 != br->buffer);
  93184. k = FLAC__bitmath_ilog2(parameter);
  93185. /* read the unary MSBs and end bit */
  93186. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  93187. return false;
  93188. /* read the binary LSBs */
  93189. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  93190. return false;
  93191. if(parameter == 1u<<k) {
  93192. /* compose the value */
  93193. *val = (msbs << k) | lsbs;
  93194. }
  93195. else {
  93196. unsigned d = (1 << (k+1)) - parameter;
  93197. if(lsbs >= d) {
  93198. if(!FLAC__bitreader_read_bit(br, &bit))
  93199. return false;
  93200. lsbs <<= 1;
  93201. lsbs |= bit;
  93202. lsbs -= d;
  93203. }
  93204. /* compose the value */
  93205. *val = msbs * parameter + lsbs;
  93206. }
  93207. return true;
  93208. }
  93209. #endif /* UNUSED */
  93210. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  93211. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  93212. {
  93213. FLAC__uint32 v = 0;
  93214. FLAC__uint32 x;
  93215. unsigned i;
  93216. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93217. return false;
  93218. if(raw)
  93219. raw[(*rawlen)++] = (FLAC__byte)x;
  93220. if(!(x & 0x80)) { /* 0xxxxxxx */
  93221. v = x;
  93222. i = 0;
  93223. }
  93224. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  93225. v = x & 0x1F;
  93226. i = 1;
  93227. }
  93228. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  93229. v = x & 0x0F;
  93230. i = 2;
  93231. }
  93232. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  93233. v = x & 0x07;
  93234. i = 3;
  93235. }
  93236. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  93237. v = x & 0x03;
  93238. i = 4;
  93239. }
  93240. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  93241. v = x & 0x01;
  93242. i = 5;
  93243. }
  93244. else {
  93245. *val = 0xffffffff;
  93246. return true;
  93247. }
  93248. for( ; i; i--) {
  93249. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93250. return false;
  93251. if(raw)
  93252. raw[(*rawlen)++] = (FLAC__byte)x;
  93253. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  93254. *val = 0xffffffff;
  93255. return true;
  93256. }
  93257. v <<= 6;
  93258. v |= (x & 0x3F);
  93259. }
  93260. *val = v;
  93261. return true;
  93262. }
  93263. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  93264. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  93265. {
  93266. FLAC__uint64 v = 0;
  93267. FLAC__uint32 x;
  93268. unsigned i;
  93269. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93270. return false;
  93271. if(raw)
  93272. raw[(*rawlen)++] = (FLAC__byte)x;
  93273. if(!(x & 0x80)) { /* 0xxxxxxx */
  93274. v = x;
  93275. i = 0;
  93276. }
  93277. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  93278. v = x & 0x1F;
  93279. i = 1;
  93280. }
  93281. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  93282. v = x & 0x0F;
  93283. i = 2;
  93284. }
  93285. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  93286. v = x & 0x07;
  93287. i = 3;
  93288. }
  93289. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  93290. v = x & 0x03;
  93291. i = 4;
  93292. }
  93293. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  93294. v = x & 0x01;
  93295. i = 5;
  93296. }
  93297. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  93298. v = 0;
  93299. i = 6;
  93300. }
  93301. else {
  93302. *val = FLAC__U64L(0xffffffffffffffff);
  93303. return true;
  93304. }
  93305. for( ; i; i--) {
  93306. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93307. return false;
  93308. if(raw)
  93309. raw[(*rawlen)++] = (FLAC__byte)x;
  93310. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  93311. *val = FLAC__U64L(0xffffffffffffffff);
  93312. return true;
  93313. }
  93314. v <<= 6;
  93315. v |= (x & 0x3F);
  93316. }
  93317. *val = v;
  93318. return true;
  93319. }
  93320. #endif
  93321. /*** End of inlined file: bitreader.c ***/
  93322. /*** Start of inlined file: bitwriter.c ***/
  93323. /*** Start of inlined file: juce_FlacHeader.h ***/
  93324. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  93325. // tasks..
  93326. #define VERSION "1.2.1"
  93327. #define FLAC__NO_DLL 1
  93328. #if JUCE_MSVC
  93329. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  93330. #endif
  93331. #if JUCE_MAC
  93332. #define FLAC__SYS_DARWIN 1
  93333. #endif
  93334. /*** End of inlined file: juce_FlacHeader.h ***/
  93335. #if JUCE_USE_FLAC
  93336. #if HAVE_CONFIG_H
  93337. # include <config.h>
  93338. #endif
  93339. #include <stdlib.h> /* for malloc() */
  93340. #include <string.h> /* for memcpy(), memset() */
  93341. #ifdef _MSC_VER
  93342. #include <winsock.h> /* for ntohl() */
  93343. #elif defined FLAC__SYS_DARWIN
  93344. #include <machine/endian.h> /* for ntohl() */
  93345. #elif defined __MINGW32__
  93346. #include <winsock.h> /* for ntohl() */
  93347. #else
  93348. #include <netinet/in.h> /* for ntohl() */
  93349. #endif
  93350. #if 0 /* UNUSED */
  93351. #endif
  93352. /*** Start of inlined file: bitwriter.h ***/
  93353. #ifndef FLAC__PRIVATE__BITWRITER_H
  93354. #define FLAC__PRIVATE__BITWRITER_H
  93355. #include <stdio.h> /* for FILE */
  93356. /*
  93357. * opaque structure definition
  93358. */
  93359. struct FLAC__BitWriter;
  93360. typedef struct FLAC__BitWriter FLAC__BitWriter;
  93361. /*
  93362. * construction, deletion, initialization, etc functions
  93363. */
  93364. FLAC__BitWriter *FLAC__bitwriter_new(void);
  93365. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  93366. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  93367. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  93368. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  93369. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  93370. /*
  93371. * CRC functions
  93372. *
  93373. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  93374. */
  93375. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  93376. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  93377. /*
  93378. * info functions
  93379. */
  93380. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  93381. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  93382. /*
  93383. * direct buffer access
  93384. *
  93385. * there may be no calls on the bitwriter between get and release.
  93386. * the bitwriter continues to own the returned buffer.
  93387. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  93388. */
  93389. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  93390. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  93391. /*
  93392. * write functions
  93393. */
  93394. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  93395. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  93396. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  93397. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  93398. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  93399. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  93400. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  93401. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  93402. #if 0 /* UNUSED */
  93403. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  93404. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  93405. #endif
  93406. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  93407. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  93408. #if 0 /* UNUSED */
  93409. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  93410. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  93411. #endif
  93412. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  93413. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  93414. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  93415. #endif
  93416. /*** End of inlined file: bitwriter.h ***/
  93417. /*** Start of inlined file: alloc.h ***/
  93418. #ifndef FLAC__SHARE__ALLOC_H
  93419. #define FLAC__SHARE__ALLOC_H
  93420. #if HAVE_CONFIG_H
  93421. # include <config.h>
  93422. #endif
  93423. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  93424. * before #including this file, otherwise SIZE_MAX might not be defined
  93425. */
  93426. #include <limits.h> /* for SIZE_MAX */
  93427. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  93428. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  93429. #endif
  93430. #include <stdlib.h> /* for size_t, malloc(), etc */
  93431. #ifndef SIZE_MAX
  93432. # ifndef SIZE_T_MAX
  93433. # ifdef _MSC_VER
  93434. # define SIZE_T_MAX UINT_MAX
  93435. # else
  93436. # error
  93437. # endif
  93438. # endif
  93439. # define SIZE_MAX SIZE_T_MAX
  93440. #endif
  93441. #ifndef FLaC__INLINE
  93442. #define FLaC__INLINE
  93443. #endif
  93444. /* avoid malloc()ing 0 bytes, see:
  93445. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  93446. */
  93447. static FLaC__INLINE void *safe_malloc_(size_t size)
  93448. {
  93449. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  93450. if(!size)
  93451. size++;
  93452. return malloc(size);
  93453. }
  93454. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  93455. {
  93456. if(!nmemb || !size)
  93457. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  93458. return calloc(nmemb, size);
  93459. }
  93460. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  93461. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  93462. {
  93463. size2 += size1;
  93464. if(size2 < size1)
  93465. return 0;
  93466. return safe_malloc_(size2);
  93467. }
  93468. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  93469. {
  93470. size2 += size1;
  93471. if(size2 < size1)
  93472. return 0;
  93473. size3 += size2;
  93474. if(size3 < size2)
  93475. return 0;
  93476. return safe_malloc_(size3);
  93477. }
  93478. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  93479. {
  93480. size2 += size1;
  93481. if(size2 < size1)
  93482. return 0;
  93483. size3 += size2;
  93484. if(size3 < size2)
  93485. return 0;
  93486. size4 += size3;
  93487. if(size4 < size3)
  93488. return 0;
  93489. return safe_malloc_(size4);
  93490. }
  93491. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  93492. #if 0
  93493. needs support for cases where sizeof(size_t) != 4
  93494. {
  93495. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  93496. if(sizeof(size_t) == 4) {
  93497. if ((double)size1 * (double)size2 < 4294967296.0)
  93498. return malloc(size1*size2);
  93499. }
  93500. return 0;
  93501. }
  93502. #else
  93503. /* better? */
  93504. {
  93505. if(!size1 || !size2)
  93506. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  93507. if(size1 > SIZE_MAX / size2)
  93508. return 0;
  93509. return malloc(size1*size2);
  93510. }
  93511. #endif
  93512. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  93513. {
  93514. if(!size1 || !size2 || !size3)
  93515. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  93516. if(size1 > SIZE_MAX / size2)
  93517. return 0;
  93518. size1 *= size2;
  93519. if(size1 > SIZE_MAX / size3)
  93520. return 0;
  93521. return malloc(size1*size3);
  93522. }
  93523. /* size1*size2 + size3 */
  93524. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  93525. {
  93526. if(!size1 || !size2)
  93527. return safe_malloc_(size3);
  93528. if(size1 > SIZE_MAX / size2)
  93529. return 0;
  93530. return safe_malloc_add_2op_(size1*size2, size3);
  93531. }
  93532. /* size1 * (size2 + size3) */
  93533. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  93534. {
  93535. if(!size1 || (!size2 && !size3))
  93536. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  93537. size2 += size3;
  93538. if(size2 < size3)
  93539. return 0;
  93540. return safe_malloc_mul_2op_(size1, size2);
  93541. }
  93542. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  93543. {
  93544. size2 += size1;
  93545. if(size2 < size1)
  93546. return 0;
  93547. return realloc(ptr, size2);
  93548. }
  93549. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  93550. {
  93551. size2 += size1;
  93552. if(size2 < size1)
  93553. return 0;
  93554. size3 += size2;
  93555. if(size3 < size2)
  93556. return 0;
  93557. return realloc(ptr, size3);
  93558. }
  93559. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  93560. {
  93561. size2 += size1;
  93562. if(size2 < size1)
  93563. return 0;
  93564. size3 += size2;
  93565. if(size3 < size2)
  93566. return 0;
  93567. size4 += size3;
  93568. if(size4 < size3)
  93569. return 0;
  93570. return realloc(ptr, size4);
  93571. }
  93572. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  93573. {
  93574. if(!size1 || !size2)
  93575. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  93576. if(size1 > SIZE_MAX / size2)
  93577. return 0;
  93578. return realloc(ptr, size1*size2);
  93579. }
  93580. /* size1 * (size2 + size3) */
  93581. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  93582. {
  93583. if(!size1 || (!size2 && !size3))
  93584. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  93585. size2 += size3;
  93586. if(size2 < size3)
  93587. return 0;
  93588. return safe_realloc_mul_2op_(ptr, size1, size2);
  93589. }
  93590. #endif
  93591. /*** End of inlined file: alloc.h ***/
  93592. /* Things should be fastest when this matches the machine word size */
  93593. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  93594. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  93595. typedef FLAC__uint32 bwword;
  93596. #define FLAC__BYTES_PER_WORD 4
  93597. #define FLAC__BITS_PER_WORD 32
  93598. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  93599. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  93600. #if WORDS_BIGENDIAN
  93601. #define SWAP_BE_WORD_TO_HOST(x) (x)
  93602. #else
  93603. #ifdef _MSC_VER
  93604. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  93605. #else
  93606. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  93607. #endif
  93608. #endif
  93609. /*
  93610. * The default capacity here doesn't matter too much. The buffer always grows
  93611. * to hold whatever is written to it. Usually the encoder will stop adding at
  93612. * a frame or metadata block, then write that out and clear the buffer for the
  93613. * next one.
  93614. */
  93615. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  93616. /* When growing, increment 4K at a time */
  93617. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  93618. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  93619. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  93620. #ifdef min
  93621. #undef min
  93622. #endif
  93623. #define min(x,y) ((x)<(y)?(x):(y))
  93624. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  93625. #ifdef _MSC_VER
  93626. #define FLAC__U64L(x) x
  93627. #else
  93628. #define FLAC__U64L(x) x##LLU
  93629. #endif
  93630. #ifndef FLaC__INLINE
  93631. #define FLaC__INLINE
  93632. #endif
  93633. struct FLAC__BitWriter {
  93634. bwword *buffer;
  93635. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  93636. unsigned capacity; /* capacity of buffer in words */
  93637. unsigned words; /* # of complete words in buffer */
  93638. unsigned bits; /* # of used bits in accum */
  93639. };
  93640. /* * WATCHOUT: The current implementation only grows the buffer. */
  93641. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  93642. {
  93643. unsigned new_capacity;
  93644. bwword *new_buffer;
  93645. FLAC__ASSERT(0 != bw);
  93646. FLAC__ASSERT(0 != bw->buffer);
  93647. /* calculate total words needed to store 'bits_to_add' additional bits */
  93648. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  93649. /* it's possible (due to pessimism in the growth estimation that
  93650. * leads to this call) that we don't actually need to grow
  93651. */
  93652. if(bw->capacity >= new_capacity)
  93653. return true;
  93654. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  93655. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  93656. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  93657. /* make sure we got everything right */
  93658. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  93659. FLAC__ASSERT(new_capacity > bw->capacity);
  93660. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  93661. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  93662. if(new_buffer == 0)
  93663. return false;
  93664. bw->buffer = new_buffer;
  93665. bw->capacity = new_capacity;
  93666. return true;
  93667. }
  93668. /***********************************************************************
  93669. *
  93670. * Class constructor/destructor
  93671. *
  93672. ***********************************************************************/
  93673. FLAC__BitWriter *FLAC__bitwriter_new(void)
  93674. {
  93675. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  93676. /* note that calloc() sets all members to 0 for us */
  93677. return bw;
  93678. }
  93679. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  93680. {
  93681. FLAC__ASSERT(0 != bw);
  93682. FLAC__bitwriter_free(bw);
  93683. free(bw);
  93684. }
  93685. /***********************************************************************
  93686. *
  93687. * Public class methods
  93688. *
  93689. ***********************************************************************/
  93690. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  93691. {
  93692. FLAC__ASSERT(0 != bw);
  93693. bw->words = bw->bits = 0;
  93694. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  93695. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  93696. if(bw->buffer == 0)
  93697. return false;
  93698. return true;
  93699. }
  93700. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  93701. {
  93702. FLAC__ASSERT(0 != bw);
  93703. if(0 != bw->buffer)
  93704. free(bw->buffer);
  93705. bw->buffer = 0;
  93706. bw->capacity = 0;
  93707. bw->words = bw->bits = 0;
  93708. }
  93709. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  93710. {
  93711. bw->words = bw->bits = 0;
  93712. }
  93713. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  93714. {
  93715. unsigned i, j;
  93716. if(bw == 0) {
  93717. fprintf(out, "bitwriter is NULL\n");
  93718. }
  93719. else {
  93720. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  93721. for(i = 0; i < bw->words; i++) {
  93722. fprintf(out, "%08X: ", i);
  93723. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  93724. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  93725. fprintf(out, "\n");
  93726. }
  93727. if(bw->bits > 0) {
  93728. fprintf(out, "%08X: ", i);
  93729. for(j = 0; j < bw->bits; j++)
  93730. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  93731. fprintf(out, "\n");
  93732. }
  93733. }
  93734. }
  93735. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  93736. {
  93737. const FLAC__byte *buffer;
  93738. size_t bytes;
  93739. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  93740. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  93741. return false;
  93742. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  93743. FLAC__bitwriter_release_buffer(bw);
  93744. return true;
  93745. }
  93746. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  93747. {
  93748. const FLAC__byte *buffer;
  93749. size_t bytes;
  93750. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  93751. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  93752. return false;
  93753. *crc = FLAC__crc8(buffer, bytes);
  93754. FLAC__bitwriter_release_buffer(bw);
  93755. return true;
  93756. }
  93757. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  93758. {
  93759. return ((bw->bits & 7) == 0);
  93760. }
  93761. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  93762. {
  93763. return FLAC__TOTAL_BITS(bw);
  93764. }
  93765. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  93766. {
  93767. FLAC__ASSERT((bw->bits & 7) == 0);
  93768. /* double protection */
  93769. if(bw->bits & 7)
  93770. return false;
  93771. /* if we have bits in the accumulator we have to flush those to the buffer first */
  93772. if(bw->bits) {
  93773. FLAC__ASSERT(bw->words <= bw->capacity);
  93774. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  93775. return false;
  93776. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  93777. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  93778. }
  93779. /* now we can just return what we have */
  93780. *buffer = (FLAC__byte*)bw->buffer;
  93781. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  93782. return true;
  93783. }
  93784. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  93785. {
  93786. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  93787. * get-mode' flag could be added everywhere and then cleared here
  93788. */
  93789. (void)bw;
  93790. }
  93791. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  93792. {
  93793. unsigned n;
  93794. FLAC__ASSERT(0 != bw);
  93795. FLAC__ASSERT(0 != bw->buffer);
  93796. if(bits == 0)
  93797. return true;
  93798. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  93799. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  93800. return false;
  93801. /* first part gets to word alignment */
  93802. if(bw->bits) {
  93803. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  93804. bw->accum <<= n;
  93805. bits -= n;
  93806. bw->bits += n;
  93807. if(bw->bits == FLAC__BITS_PER_WORD) {
  93808. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  93809. bw->bits = 0;
  93810. }
  93811. else
  93812. return true;
  93813. }
  93814. /* do whole words */
  93815. while(bits >= FLAC__BITS_PER_WORD) {
  93816. bw->buffer[bw->words++] = 0;
  93817. bits -= FLAC__BITS_PER_WORD;
  93818. }
  93819. /* do any leftovers */
  93820. if(bits > 0) {
  93821. bw->accum = 0;
  93822. bw->bits = bits;
  93823. }
  93824. return true;
  93825. }
  93826. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  93827. {
  93828. register unsigned left;
  93829. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93830. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93831. FLAC__ASSERT(0 != bw);
  93832. FLAC__ASSERT(0 != bw->buffer);
  93833. FLAC__ASSERT(bits <= 32);
  93834. if(bits == 0)
  93835. return true;
  93836. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  93837. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  93838. return false;
  93839. left = FLAC__BITS_PER_WORD - bw->bits;
  93840. if(bits < left) {
  93841. bw->accum <<= bits;
  93842. bw->accum |= val;
  93843. bw->bits += bits;
  93844. }
  93845. 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 */
  93846. bw->accum <<= left;
  93847. bw->accum |= val >> (bw->bits = bits - left);
  93848. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  93849. bw->accum = val;
  93850. }
  93851. else {
  93852. bw->accum = val;
  93853. bw->bits = 0;
  93854. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  93855. }
  93856. return true;
  93857. }
  93858. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  93859. {
  93860. /* zero-out unused bits */
  93861. if(bits < 32)
  93862. val &= (~(0xffffffff << bits));
  93863. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  93864. }
  93865. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  93866. {
  93867. /* this could be a little faster but it's not used for much */
  93868. if(bits > 32) {
  93869. return
  93870. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  93871. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  93872. }
  93873. else
  93874. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  93875. }
  93876. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  93877. {
  93878. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  93879. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  93880. return false;
  93881. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  93882. return false;
  93883. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  93884. return false;
  93885. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  93886. return false;
  93887. return true;
  93888. }
  93889. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  93890. {
  93891. unsigned i;
  93892. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  93893. for(i = 0; i < nvals; i++) {
  93894. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  93895. return false;
  93896. }
  93897. return true;
  93898. }
  93899. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  93900. {
  93901. if(val < 32)
  93902. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  93903. else
  93904. return
  93905. FLAC__bitwriter_write_zeroes(bw, val) &&
  93906. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  93907. }
  93908. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  93909. {
  93910. FLAC__uint32 uval;
  93911. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  93912. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  93913. uval = (val<<1) ^ (val>>31);
  93914. return 1 + parameter + (uval >> parameter);
  93915. }
  93916. #if 0 /* UNUSED */
  93917. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  93918. {
  93919. unsigned bits, msbs, uval;
  93920. unsigned k;
  93921. FLAC__ASSERT(parameter > 0);
  93922. /* fold signed to unsigned */
  93923. if(val < 0)
  93924. uval = (unsigned)(((-(++val)) << 1) + 1);
  93925. else
  93926. uval = (unsigned)(val << 1);
  93927. k = FLAC__bitmath_ilog2(parameter);
  93928. if(parameter == 1u<<k) {
  93929. FLAC__ASSERT(k <= 30);
  93930. msbs = uval >> k;
  93931. bits = 1 + k + msbs;
  93932. }
  93933. else {
  93934. unsigned q, r, d;
  93935. d = (1 << (k+1)) - parameter;
  93936. q = uval / parameter;
  93937. r = uval - (q * parameter);
  93938. bits = 1 + q + k;
  93939. if(r >= d)
  93940. bits++;
  93941. }
  93942. return bits;
  93943. }
  93944. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  93945. {
  93946. unsigned bits, msbs;
  93947. unsigned k;
  93948. FLAC__ASSERT(parameter > 0);
  93949. k = FLAC__bitmath_ilog2(parameter);
  93950. if(parameter == 1u<<k) {
  93951. FLAC__ASSERT(k <= 30);
  93952. msbs = uval >> k;
  93953. bits = 1 + k + msbs;
  93954. }
  93955. else {
  93956. unsigned q, r, d;
  93957. d = (1 << (k+1)) - parameter;
  93958. q = uval / parameter;
  93959. r = uval - (q * parameter);
  93960. bits = 1 + q + k;
  93961. if(r >= d)
  93962. bits++;
  93963. }
  93964. return bits;
  93965. }
  93966. #endif /* UNUSED */
  93967. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  93968. {
  93969. unsigned total_bits, interesting_bits, msbs;
  93970. FLAC__uint32 uval, pattern;
  93971. FLAC__ASSERT(0 != bw);
  93972. FLAC__ASSERT(0 != bw->buffer);
  93973. FLAC__ASSERT(parameter < 8*sizeof(uval));
  93974. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  93975. uval = (val<<1) ^ (val>>31);
  93976. msbs = uval >> parameter;
  93977. interesting_bits = 1 + parameter;
  93978. total_bits = interesting_bits + msbs;
  93979. pattern = 1 << parameter; /* the unary end bit */
  93980. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  93981. if(total_bits <= 32)
  93982. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  93983. else
  93984. return
  93985. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  93986. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  93987. }
  93988. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  93989. {
  93990. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  93991. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  93992. FLAC__uint32 uval;
  93993. unsigned left;
  93994. const unsigned lsbits = 1 + parameter;
  93995. unsigned msbits;
  93996. FLAC__ASSERT(0 != bw);
  93997. FLAC__ASSERT(0 != bw->buffer);
  93998. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  93999. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94000. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94001. while(nvals) {
  94002. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94003. uval = (*vals<<1) ^ (*vals>>31);
  94004. msbits = uval >> parameter;
  94005. #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) */
  94006. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  94007. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  94008. bw->bits = bw->bits + msbits + lsbits;
  94009. uval |= mask1; /* set stop bit */
  94010. uval &= mask2; /* mask off unused top bits */
  94011. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  94012. bw->accum <<= msbits;
  94013. bw->accum <<= lsbits;
  94014. bw->accum |= uval;
  94015. if(bw->bits == FLAC__BITS_PER_WORD) {
  94016. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94017. bw->bits = 0;
  94018. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  94019. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  94020. FLAC__ASSERT(bw->capacity == bw->words);
  94021. return false;
  94022. }
  94023. }
  94024. }
  94025. else {
  94026. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  94027. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  94028. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  94029. bw->bits = bw->bits + msbits + lsbits;
  94030. uval |= mask1; /* set stop bit */
  94031. uval &= mask2; /* mask off unused top bits */
  94032. bw->accum <<= msbits + lsbits;
  94033. bw->accum |= uval;
  94034. }
  94035. else {
  94036. #endif
  94037. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94038. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  94039. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  94040. return false;
  94041. if(msbits) {
  94042. /* first part gets to word alignment */
  94043. if(bw->bits) {
  94044. left = FLAC__BITS_PER_WORD - bw->bits;
  94045. if(msbits < left) {
  94046. bw->accum <<= msbits;
  94047. bw->bits += msbits;
  94048. goto break1;
  94049. }
  94050. else {
  94051. bw->accum <<= left;
  94052. msbits -= left;
  94053. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94054. bw->bits = 0;
  94055. }
  94056. }
  94057. /* do whole words */
  94058. while(msbits >= FLAC__BITS_PER_WORD) {
  94059. bw->buffer[bw->words++] = 0;
  94060. msbits -= FLAC__BITS_PER_WORD;
  94061. }
  94062. /* do any leftovers */
  94063. if(msbits > 0) {
  94064. bw->accum = 0;
  94065. bw->bits = msbits;
  94066. }
  94067. }
  94068. break1:
  94069. uval |= mask1; /* set stop bit */
  94070. uval &= mask2; /* mask off unused top bits */
  94071. left = FLAC__BITS_PER_WORD - bw->bits;
  94072. if(lsbits < left) {
  94073. bw->accum <<= lsbits;
  94074. bw->accum |= uval;
  94075. bw->bits += lsbits;
  94076. }
  94077. else {
  94078. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  94079. * be > lsbits (because of previous assertions) so it would have
  94080. * triggered the (lsbits<left) case above.
  94081. */
  94082. FLAC__ASSERT(bw->bits);
  94083. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  94084. bw->accum <<= left;
  94085. bw->accum |= uval >> (bw->bits = lsbits - left);
  94086. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94087. bw->accum = uval;
  94088. }
  94089. #if 1
  94090. }
  94091. #endif
  94092. vals++;
  94093. nvals--;
  94094. }
  94095. return true;
  94096. }
  94097. #if 0 /* UNUSED */
  94098. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  94099. {
  94100. unsigned total_bits, msbs, uval;
  94101. unsigned k;
  94102. FLAC__ASSERT(0 != bw);
  94103. FLAC__ASSERT(0 != bw->buffer);
  94104. FLAC__ASSERT(parameter > 0);
  94105. /* fold signed to unsigned */
  94106. if(val < 0)
  94107. uval = (unsigned)(((-(++val)) << 1) + 1);
  94108. else
  94109. uval = (unsigned)(val << 1);
  94110. k = FLAC__bitmath_ilog2(parameter);
  94111. if(parameter == 1u<<k) {
  94112. unsigned pattern;
  94113. FLAC__ASSERT(k <= 30);
  94114. msbs = uval >> k;
  94115. total_bits = 1 + k + msbs;
  94116. pattern = 1 << k; /* the unary end bit */
  94117. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  94118. if(total_bits <= 32) {
  94119. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  94120. return false;
  94121. }
  94122. else {
  94123. /* write the unary MSBs */
  94124. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  94125. return false;
  94126. /* write the unary end bit and binary LSBs */
  94127. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  94128. return false;
  94129. }
  94130. }
  94131. else {
  94132. unsigned q, r, d;
  94133. d = (1 << (k+1)) - parameter;
  94134. q = uval / parameter;
  94135. r = uval - (q * parameter);
  94136. /* write the unary MSBs */
  94137. if(!FLAC__bitwriter_write_zeroes(bw, q))
  94138. return false;
  94139. /* write the unary end bit */
  94140. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  94141. return false;
  94142. /* write the binary LSBs */
  94143. if(r >= d) {
  94144. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  94145. return false;
  94146. }
  94147. else {
  94148. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  94149. return false;
  94150. }
  94151. }
  94152. return true;
  94153. }
  94154. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  94155. {
  94156. unsigned total_bits, msbs;
  94157. unsigned k;
  94158. FLAC__ASSERT(0 != bw);
  94159. FLAC__ASSERT(0 != bw->buffer);
  94160. FLAC__ASSERT(parameter > 0);
  94161. k = FLAC__bitmath_ilog2(parameter);
  94162. if(parameter == 1u<<k) {
  94163. unsigned pattern;
  94164. FLAC__ASSERT(k <= 30);
  94165. msbs = uval >> k;
  94166. total_bits = 1 + k + msbs;
  94167. pattern = 1 << k; /* the unary end bit */
  94168. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  94169. if(total_bits <= 32) {
  94170. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  94171. return false;
  94172. }
  94173. else {
  94174. /* write the unary MSBs */
  94175. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  94176. return false;
  94177. /* write the unary end bit and binary LSBs */
  94178. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  94179. return false;
  94180. }
  94181. }
  94182. else {
  94183. unsigned q, r, d;
  94184. d = (1 << (k+1)) - parameter;
  94185. q = uval / parameter;
  94186. r = uval - (q * parameter);
  94187. /* write the unary MSBs */
  94188. if(!FLAC__bitwriter_write_zeroes(bw, q))
  94189. return false;
  94190. /* write the unary end bit */
  94191. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  94192. return false;
  94193. /* write the binary LSBs */
  94194. if(r >= d) {
  94195. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  94196. return false;
  94197. }
  94198. else {
  94199. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  94200. return false;
  94201. }
  94202. }
  94203. return true;
  94204. }
  94205. #endif /* UNUSED */
  94206. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  94207. {
  94208. FLAC__bool ok = 1;
  94209. FLAC__ASSERT(0 != bw);
  94210. FLAC__ASSERT(0 != bw->buffer);
  94211. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  94212. if(val < 0x80) {
  94213. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  94214. }
  94215. else if(val < 0x800) {
  94216. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  94217. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94218. }
  94219. else if(val < 0x10000) {
  94220. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  94221. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94222. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94223. }
  94224. else if(val < 0x200000) {
  94225. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  94226. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  94227. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94228. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94229. }
  94230. else if(val < 0x4000000) {
  94231. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  94232. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  94233. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  94234. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94235. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94236. }
  94237. else {
  94238. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  94239. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  94240. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  94241. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  94242. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94243. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94244. }
  94245. return ok;
  94246. }
  94247. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  94248. {
  94249. FLAC__bool ok = 1;
  94250. FLAC__ASSERT(0 != bw);
  94251. FLAC__ASSERT(0 != bw->buffer);
  94252. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  94253. if(val < 0x80) {
  94254. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  94255. }
  94256. else if(val < 0x800) {
  94257. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  94258. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94259. }
  94260. else if(val < 0x10000) {
  94261. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  94262. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94263. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94264. }
  94265. else if(val < 0x200000) {
  94266. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  94267. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94268. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94269. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94270. }
  94271. else if(val < 0x4000000) {
  94272. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  94273. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  94274. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94275. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94276. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94277. }
  94278. else if(val < 0x80000000) {
  94279. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  94280. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  94281. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  94282. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94283. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94284. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94285. }
  94286. else {
  94287. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  94288. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  94289. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  94290. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  94291. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94292. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94293. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94294. }
  94295. return ok;
  94296. }
  94297. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  94298. {
  94299. /* 0-pad to byte boundary */
  94300. if(bw->bits & 7u)
  94301. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  94302. else
  94303. return true;
  94304. }
  94305. #endif
  94306. /*** End of inlined file: bitwriter.c ***/
  94307. /*** Start of inlined file: cpu.c ***/
  94308. /*** Start of inlined file: juce_FlacHeader.h ***/
  94309. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94310. // tasks..
  94311. #define VERSION "1.2.1"
  94312. #define FLAC__NO_DLL 1
  94313. #if JUCE_MSVC
  94314. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94315. #endif
  94316. #if JUCE_MAC
  94317. #define FLAC__SYS_DARWIN 1
  94318. #endif
  94319. /*** End of inlined file: juce_FlacHeader.h ***/
  94320. #if JUCE_USE_FLAC
  94321. #if HAVE_CONFIG_H
  94322. # include <config.h>
  94323. #endif
  94324. #include <stdlib.h>
  94325. #include <stdio.h>
  94326. #if defined FLAC__CPU_IA32
  94327. # include <signal.h>
  94328. #elif defined FLAC__CPU_PPC
  94329. # if !defined FLAC__NO_ASM
  94330. # if defined FLAC__SYS_DARWIN
  94331. # include <sys/sysctl.h>
  94332. # include <mach/mach.h>
  94333. # include <mach/mach_host.h>
  94334. # include <mach/host_info.h>
  94335. # include <mach/machine.h>
  94336. # ifndef CPU_SUBTYPE_POWERPC_970
  94337. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  94338. # endif
  94339. # else /* FLAC__SYS_DARWIN */
  94340. # include <signal.h>
  94341. # include <setjmp.h>
  94342. static sigjmp_buf jmpbuf;
  94343. static volatile sig_atomic_t canjump = 0;
  94344. static void sigill_handler (int sig)
  94345. {
  94346. if (!canjump) {
  94347. signal (sig, SIG_DFL);
  94348. raise (sig);
  94349. }
  94350. canjump = 0;
  94351. siglongjmp (jmpbuf, 1);
  94352. }
  94353. # endif /* FLAC__SYS_DARWIN */
  94354. # endif /* FLAC__NO_ASM */
  94355. #endif /* FLAC__CPU_PPC */
  94356. #if defined (__NetBSD__) || defined(__OpenBSD__)
  94357. #include <sys/param.h>
  94358. #include <sys/sysctl.h>
  94359. #include <machine/cpu.h>
  94360. #endif
  94361. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  94362. #include <sys/types.h>
  94363. #include <sys/sysctl.h>
  94364. #endif
  94365. #if defined(__APPLE__)
  94366. /* how to get sysctlbyname()? */
  94367. #endif
  94368. /* these are flags in EDX of CPUID AX=00000001 */
  94369. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  94370. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  94371. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  94372. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  94373. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  94374. /* these are flags in ECX of CPUID AX=00000001 */
  94375. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  94376. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  94377. /* these are flags in EDX of CPUID AX=80000001 */
  94378. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  94379. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  94380. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  94381. /*
  94382. * Extra stuff needed for detection of OS support for SSE on IA-32
  94383. */
  94384. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  94385. # if defined(__linux__)
  94386. /*
  94387. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  94388. * modify the return address to jump over the offending SSE instruction
  94389. * and also the operation following it that indicates the instruction
  94390. * executed successfully. In this way we use no global variables and
  94391. * stay thread-safe.
  94392. *
  94393. * 3 + 3 + 6:
  94394. * 3 bytes for "xorps xmm0,xmm0"
  94395. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  94396. * 6 bytes extra in case our estimate is wrong
  94397. * 12 bytes puts us in the NOP "landing zone"
  94398. */
  94399. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  94400. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  94401. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  94402. {
  94403. (void)signal;
  94404. sc.eip += 3 + 3 + 6;
  94405. }
  94406. # else
  94407. # include <sys/ucontext.h>
  94408. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  94409. {
  94410. (void)signal, (void)si;
  94411. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  94412. }
  94413. # endif
  94414. # elif defined(_MSC_VER)
  94415. # include <windows.h>
  94416. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  94417. # ifdef USE_TRY_CATCH_FLAVOR
  94418. # else
  94419. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  94420. {
  94421. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  94422. ep->ContextRecord->Eip += 3 + 3 + 6;
  94423. return EXCEPTION_CONTINUE_EXECUTION;
  94424. }
  94425. return EXCEPTION_CONTINUE_SEARCH;
  94426. }
  94427. # endif
  94428. # endif
  94429. #endif
  94430. void FLAC__cpu_info(FLAC__CPUInfo *info)
  94431. {
  94432. /*
  94433. * IA32-specific
  94434. */
  94435. #ifdef FLAC__CPU_IA32
  94436. info->type = FLAC__CPUINFO_TYPE_IA32;
  94437. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  94438. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  94439. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  94440. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  94441. info->data.ia32.cmov = false;
  94442. info->data.ia32.mmx = false;
  94443. info->data.ia32.fxsr = false;
  94444. info->data.ia32.sse = false;
  94445. info->data.ia32.sse2 = false;
  94446. info->data.ia32.sse3 = false;
  94447. info->data.ia32.ssse3 = false;
  94448. info->data.ia32._3dnow = false;
  94449. info->data.ia32.ext3dnow = false;
  94450. info->data.ia32.extmmx = false;
  94451. if(info->data.ia32.cpuid) {
  94452. /* http://www.sandpile.org/ia32/cpuid.htm */
  94453. FLAC__uint32 flags_edx, flags_ecx;
  94454. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  94455. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  94456. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  94457. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  94458. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  94459. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  94460. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  94461. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  94462. #ifdef FLAC__USE_3DNOW
  94463. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  94464. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  94465. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  94466. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  94467. #else
  94468. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  94469. #endif
  94470. #ifdef DEBUG
  94471. fprintf(stderr, "CPU info (IA-32):\n");
  94472. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  94473. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  94474. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  94475. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  94476. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  94477. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  94478. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  94479. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  94480. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  94481. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  94482. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  94483. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  94484. #endif
  94485. /*
  94486. * now have to check for OS support of SSE/SSE2
  94487. */
  94488. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  94489. #if defined FLAC__NO_SSE_OS
  94490. /* assume user knows better than us; turn it off */
  94491. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94492. #elif defined FLAC__SSE_OS
  94493. /* assume user knows better than us; leave as detected above */
  94494. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  94495. int sse = 0;
  94496. size_t len;
  94497. /* at least one of these must work: */
  94498. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  94499. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  94500. if(!sse)
  94501. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94502. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  94503. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  94504. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  94505. size_t len = sizeof(val);
  94506. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  94507. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94508. else { /* double-check SSE2 */
  94509. mib[1] = CPU_SSE2;
  94510. len = sizeof(val);
  94511. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  94512. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94513. }
  94514. # else
  94515. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94516. # endif
  94517. #elif defined(__linux__)
  94518. int sse = 0;
  94519. struct sigaction sigill_save;
  94520. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  94521. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  94522. #else
  94523. struct sigaction sigill_sse;
  94524. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  94525. __sigemptyset(&sigill_sse.sa_mask);
  94526. 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 */
  94527. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  94528. #endif
  94529. {
  94530. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  94531. /* see sigill_handler_sse_os() for an explanation of the following: */
  94532. asm volatile (
  94533. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  94534. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  94535. "incl %0\n\t" /* SIGILL handler will jump over this */
  94536. /* landing zone */
  94537. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  94538. "nop\n\t"
  94539. "nop\n\t"
  94540. "nop\n\t"
  94541. "nop\n\t"
  94542. "nop\n\t"
  94543. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  94544. "nop\n\t"
  94545. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  94546. : "=r"(sse)
  94547. : "r"(sse)
  94548. );
  94549. sigaction(SIGILL, &sigill_save, NULL);
  94550. }
  94551. if(!sse)
  94552. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94553. #elif defined(_MSC_VER)
  94554. # ifdef USE_TRY_CATCH_FLAVOR
  94555. _try {
  94556. __asm {
  94557. # if _MSC_VER <= 1200
  94558. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  94559. _emit 0x0F
  94560. _emit 0x57
  94561. _emit 0xC0
  94562. # else
  94563. xorps xmm0,xmm0
  94564. # endif
  94565. }
  94566. }
  94567. _except(EXCEPTION_EXECUTE_HANDLER) {
  94568. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  94569. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94570. }
  94571. # else
  94572. int sse = 0;
  94573. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  94574. /* see GCC version above for explanation */
  94575. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  94576. /* http://www.codeproject.com/cpp/gccasm.asp */
  94577. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  94578. __asm {
  94579. # if _MSC_VER <= 1200
  94580. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  94581. _emit 0x0F
  94582. _emit 0x57
  94583. _emit 0xC0
  94584. # else
  94585. xorps xmm0,xmm0
  94586. # endif
  94587. inc sse
  94588. nop
  94589. nop
  94590. nop
  94591. nop
  94592. nop
  94593. nop
  94594. nop
  94595. nop
  94596. nop
  94597. }
  94598. SetUnhandledExceptionFilter(save);
  94599. if(!sse)
  94600. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94601. # endif
  94602. #else
  94603. /* no way to test, disable to be safe */
  94604. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  94605. #endif
  94606. #ifdef DEBUG
  94607. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  94608. #endif
  94609. }
  94610. }
  94611. #else
  94612. info->use_asm = false;
  94613. #endif
  94614. /*
  94615. * PPC-specific
  94616. */
  94617. #elif defined FLAC__CPU_PPC
  94618. info->type = FLAC__CPUINFO_TYPE_PPC;
  94619. # if !defined FLAC__NO_ASM
  94620. info->use_asm = true;
  94621. # ifdef FLAC__USE_ALTIVEC
  94622. # if defined FLAC__SYS_DARWIN
  94623. {
  94624. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  94625. size_t len = sizeof(val);
  94626. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  94627. }
  94628. {
  94629. host_basic_info_data_t hostInfo;
  94630. mach_msg_type_number_t infoCount;
  94631. infoCount = HOST_BASIC_INFO_COUNT;
  94632. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  94633. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  94634. }
  94635. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  94636. {
  94637. /* no Darwin, do it the brute-force way */
  94638. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  94639. info->data.ppc.altivec = 0;
  94640. info->data.ppc.ppc64 = 0;
  94641. signal (SIGILL, sigill_handler);
  94642. canjump = 0;
  94643. if (!sigsetjmp (jmpbuf, 1)) {
  94644. canjump = 1;
  94645. asm volatile (
  94646. "mtspr 256, %0\n\t"
  94647. "vand %%v0, %%v0, %%v0"
  94648. :
  94649. : "r" (-1)
  94650. );
  94651. info->data.ppc.altivec = 1;
  94652. }
  94653. canjump = 0;
  94654. if (!sigsetjmp (jmpbuf, 1)) {
  94655. int x = 0;
  94656. canjump = 1;
  94657. /* PPC64 hardware implements the cntlzd instruction */
  94658. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  94659. info->data.ppc.ppc64 = 1;
  94660. }
  94661. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  94662. }
  94663. # endif
  94664. # else /* !FLAC__USE_ALTIVEC */
  94665. info->data.ppc.altivec = 0;
  94666. info->data.ppc.ppc64 = 0;
  94667. # endif
  94668. # else
  94669. info->use_asm = false;
  94670. # endif
  94671. /*
  94672. * unknown CPI
  94673. */
  94674. #else
  94675. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  94676. info->use_asm = false;
  94677. #endif
  94678. }
  94679. #endif
  94680. /*** End of inlined file: cpu.c ***/
  94681. /*** Start of inlined file: crc.c ***/
  94682. /*** Start of inlined file: juce_FlacHeader.h ***/
  94683. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94684. // tasks..
  94685. #define VERSION "1.2.1"
  94686. #define FLAC__NO_DLL 1
  94687. #if JUCE_MSVC
  94688. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94689. #endif
  94690. #if JUCE_MAC
  94691. #define FLAC__SYS_DARWIN 1
  94692. #endif
  94693. /*** End of inlined file: juce_FlacHeader.h ***/
  94694. #if JUCE_USE_FLAC
  94695. #if HAVE_CONFIG_H
  94696. # include <config.h>
  94697. #endif
  94698. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  94699. FLAC__byte const FLAC__crc8_table[256] = {
  94700. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  94701. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  94702. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  94703. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  94704. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  94705. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  94706. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  94707. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  94708. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  94709. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  94710. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  94711. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  94712. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  94713. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  94714. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  94715. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  94716. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  94717. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  94718. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  94719. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  94720. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  94721. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  94722. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  94723. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  94724. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  94725. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  94726. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  94727. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  94728. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  94729. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  94730. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  94731. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  94732. };
  94733. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  94734. unsigned FLAC__crc16_table[256] = {
  94735. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  94736. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  94737. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  94738. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  94739. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  94740. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  94741. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  94742. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  94743. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  94744. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  94745. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  94746. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  94747. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  94748. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  94749. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  94750. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  94751. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  94752. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  94753. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  94754. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  94755. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  94756. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  94757. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  94758. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  94759. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  94760. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  94761. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  94762. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  94763. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  94764. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  94765. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  94766. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  94767. };
  94768. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  94769. {
  94770. *crc = FLAC__crc8_table[*crc ^ data];
  94771. }
  94772. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  94773. {
  94774. while(len--)
  94775. *crc = FLAC__crc8_table[*crc ^ *data++];
  94776. }
  94777. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  94778. {
  94779. FLAC__uint8 crc = 0;
  94780. while(len--)
  94781. crc = FLAC__crc8_table[crc ^ *data++];
  94782. return crc;
  94783. }
  94784. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  94785. {
  94786. unsigned crc = 0;
  94787. while(len--)
  94788. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  94789. return crc;
  94790. }
  94791. #endif
  94792. /*** End of inlined file: crc.c ***/
  94793. /*** Start of inlined file: fixed.c ***/
  94794. /*** Start of inlined file: juce_FlacHeader.h ***/
  94795. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94796. // tasks..
  94797. #define VERSION "1.2.1"
  94798. #define FLAC__NO_DLL 1
  94799. #if JUCE_MSVC
  94800. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94801. #endif
  94802. #if JUCE_MAC
  94803. #define FLAC__SYS_DARWIN 1
  94804. #endif
  94805. /*** End of inlined file: juce_FlacHeader.h ***/
  94806. #if JUCE_USE_FLAC
  94807. #if HAVE_CONFIG_H
  94808. # include <config.h>
  94809. #endif
  94810. #include <math.h>
  94811. #include <string.h>
  94812. /*** Start of inlined file: fixed.h ***/
  94813. #ifndef FLAC__PRIVATE__FIXED_H
  94814. #define FLAC__PRIVATE__FIXED_H
  94815. #ifdef HAVE_CONFIG_H
  94816. #include <config.h>
  94817. #endif
  94818. /*** Start of inlined file: float.h ***/
  94819. #ifndef FLAC__PRIVATE__FLOAT_H
  94820. #define FLAC__PRIVATE__FLOAT_H
  94821. #ifdef HAVE_CONFIG_H
  94822. #include <config.h>
  94823. #endif
  94824. /*
  94825. * These typedefs make it easier to ensure that integer versions of
  94826. * the library really only contain integer operations. All the code
  94827. * in libFLAC should use FLAC__float and FLAC__double in place of
  94828. * float and double, and be protected by checks of the macro
  94829. * FLAC__INTEGER_ONLY_LIBRARY.
  94830. *
  94831. * FLAC__real is the basic floating point type used in LPC analysis.
  94832. */
  94833. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  94834. typedef double FLAC__double;
  94835. typedef float FLAC__float;
  94836. /*
  94837. * WATCHOUT: changing FLAC__real will change the signatures of many
  94838. * functions that have assembly language equivalents and break them.
  94839. */
  94840. typedef float FLAC__real;
  94841. #else
  94842. /*
  94843. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  94844. * for the integer part and lower 16 bits for the fractional part.
  94845. */
  94846. typedef FLAC__int32 FLAC__fixedpoint;
  94847. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  94848. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  94849. extern const FLAC__fixedpoint FLAC__FP_ONE;
  94850. extern const FLAC__fixedpoint FLAC__FP_LN2;
  94851. extern const FLAC__fixedpoint FLAC__FP_E;
  94852. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  94853. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  94854. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  94855. /*
  94856. * FLAC__fixedpoint_log2()
  94857. * --------------------------------------------------------------------
  94858. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  94859. * algorithm by Knuth for x >= 1.0
  94860. *
  94861. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  94862. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  94863. *
  94864. * 'precision' roughly limits the number of iterations that are done;
  94865. * use (unsigned)(-1) for maximum precision.
  94866. *
  94867. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  94868. * function will punt and return 0.
  94869. *
  94870. * The return value will also have 'fracbits' fractional bits.
  94871. */
  94872. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  94873. #endif
  94874. #endif
  94875. /*** End of inlined file: float.h ***/
  94876. /*** Start of inlined file: format.h ***/
  94877. #ifndef FLAC__PRIVATE__FORMAT_H
  94878. #define FLAC__PRIVATE__FORMAT_H
  94879. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  94880. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  94881. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  94882. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  94883. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  94884. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  94885. #endif
  94886. /*** End of inlined file: format.h ***/
  94887. /*
  94888. * FLAC__fixed_compute_best_predictor()
  94889. * --------------------------------------------------------------------
  94890. * Compute the best fixed predictor and the expected bits-per-sample
  94891. * of the residual signal for each order. The _wide() version uses
  94892. * 64-bit integers which is statistically necessary when bits-per-
  94893. * sample + log2(blocksize) > 30
  94894. *
  94895. * IN data[0,data_len-1]
  94896. * IN data_len
  94897. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  94898. */
  94899. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  94900. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  94901. # ifndef FLAC__NO_ASM
  94902. # ifdef FLAC__CPU_IA32
  94903. # ifdef FLAC__HAS_NASM
  94904. 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]);
  94905. # endif
  94906. # endif
  94907. # endif
  94908. 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]);
  94909. #else
  94910. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  94911. 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]);
  94912. #endif
  94913. /*
  94914. * FLAC__fixed_compute_residual()
  94915. * --------------------------------------------------------------------
  94916. * Compute the residual signal obtained from sutracting the predicted
  94917. * signal from the original.
  94918. *
  94919. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  94920. * IN data_len length of original signal
  94921. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  94922. * OUT residual[0,data_len-1] residual signal
  94923. */
  94924. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  94925. /*
  94926. * FLAC__fixed_restore_signal()
  94927. * --------------------------------------------------------------------
  94928. * Restore the original signal by summing the residual and the
  94929. * predictor.
  94930. *
  94931. * IN residual[0,data_len-1] residual signal
  94932. * IN data_len length of original signal
  94933. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  94934. * *** IMPORTANT: the caller must pass in the historical samples:
  94935. * IN data[-order,-1] previously-reconstructed historical samples
  94936. * OUT data[0,data_len-1] original signal
  94937. */
  94938. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  94939. #endif
  94940. /*** End of inlined file: fixed.h ***/
  94941. #ifndef M_LN2
  94942. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  94943. #define M_LN2 0.69314718055994530942
  94944. #endif
  94945. #ifdef min
  94946. #undef min
  94947. #endif
  94948. #define min(x,y) ((x) < (y)? (x) : (y))
  94949. #ifdef local_abs
  94950. #undef local_abs
  94951. #endif
  94952. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  94953. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  94954. /* rbps stands for residual bits per sample
  94955. *
  94956. * (ln(2) * err)
  94957. * rbps = log (-----------)
  94958. * 2 ( n )
  94959. */
  94960. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  94961. {
  94962. FLAC__uint32 rbps;
  94963. unsigned bits; /* the number of bits required to represent a number */
  94964. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  94965. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  94966. FLAC__ASSERT(err > 0);
  94967. FLAC__ASSERT(n > 0);
  94968. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  94969. if(err <= n)
  94970. return 0;
  94971. /*
  94972. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  94973. * These allow us later to know we won't lose too much precision in the
  94974. * fixed-point division (err<<fracbits)/n.
  94975. */
  94976. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  94977. err <<= fracbits;
  94978. err /= n;
  94979. /* err now holds err/n with fracbits fractional bits */
  94980. /*
  94981. * Whittle err down to 16 bits max. 16 significant bits is enough for
  94982. * our purposes.
  94983. */
  94984. FLAC__ASSERT(err > 0);
  94985. bits = FLAC__bitmath_ilog2(err)+1;
  94986. if(bits > 16) {
  94987. err >>= (bits-16);
  94988. fracbits -= (bits-16);
  94989. }
  94990. rbps = (FLAC__uint32)err;
  94991. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  94992. rbps *= FLAC__FP_LN2;
  94993. fracbits += 16;
  94994. FLAC__ASSERT(fracbits >= 0);
  94995. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  94996. {
  94997. const int f = fracbits & 3;
  94998. if(f) {
  94999. rbps >>= f;
  95000. fracbits -= f;
  95001. }
  95002. }
  95003. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  95004. if(rbps == 0)
  95005. return 0;
  95006. /*
  95007. * The return value must have 16 fractional bits. Since the whole part
  95008. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  95009. * must be >= -3, these assertion allows us to be able to shift rbps
  95010. * left if necessary to get 16 fracbits without losing any bits of the
  95011. * whole part of rbps.
  95012. *
  95013. * There is a slight chance due to accumulated error that the whole part
  95014. * will require 6 bits, so we use 6 in the assertion. Really though as
  95015. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  95016. */
  95017. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  95018. FLAC__ASSERT(fracbits >= -3);
  95019. /* now shift the decimal point into place */
  95020. if(fracbits < 16)
  95021. return rbps << (16-fracbits);
  95022. else if(fracbits > 16)
  95023. return rbps >> (fracbits-16);
  95024. else
  95025. return rbps;
  95026. }
  95027. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  95028. {
  95029. FLAC__uint32 rbps;
  95030. unsigned bits; /* the number of bits required to represent a number */
  95031. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  95032. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  95033. FLAC__ASSERT(err > 0);
  95034. FLAC__ASSERT(n > 0);
  95035. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  95036. if(err <= n)
  95037. return 0;
  95038. /*
  95039. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  95040. * These allow us later to know we won't lose too much precision in the
  95041. * fixed-point division (err<<fracbits)/n.
  95042. */
  95043. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  95044. err <<= fracbits;
  95045. err /= n;
  95046. /* err now holds err/n with fracbits fractional bits */
  95047. /*
  95048. * Whittle err down to 16 bits max. 16 significant bits is enough for
  95049. * our purposes.
  95050. */
  95051. FLAC__ASSERT(err > 0);
  95052. bits = FLAC__bitmath_ilog2_wide(err)+1;
  95053. if(bits > 16) {
  95054. err >>= (bits-16);
  95055. fracbits -= (bits-16);
  95056. }
  95057. rbps = (FLAC__uint32)err;
  95058. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  95059. rbps *= FLAC__FP_LN2;
  95060. fracbits += 16;
  95061. FLAC__ASSERT(fracbits >= 0);
  95062. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  95063. {
  95064. const int f = fracbits & 3;
  95065. if(f) {
  95066. rbps >>= f;
  95067. fracbits -= f;
  95068. }
  95069. }
  95070. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  95071. if(rbps == 0)
  95072. return 0;
  95073. /*
  95074. * The return value must have 16 fractional bits. Since the whole part
  95075. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  95076. * must be >= -3, these assertion allows us to be able to shift rbps
  95077. * left if necessary to get 16 fracbits without losing any bits of the
  95078. * whole part of rbps.
  95079. *
  95080. * There is a slight chance due to accumulated error that the whole part
  95081. * will require 6 bits, so we use 6 in the assertion. Really though as
  95082. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  95083. */
  95084. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  95085. FLAC__ASSERT(fracbits >= -3);
  95086. /* now shift the decimal point into place */
  95087. if(fracbits < 16)
  95088. return rbps << (16-fracbits);
  95089. else if(fracbits > 16)
  95090. return rbps >> (fracbits-16);
  95091. else
  95092. return rbps;
  95093. }
  95094. #endif
  95095. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95096. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  95097. #else
  95098. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  95099. #endif
  95100. {
  95101. FLAC__int32 last_error_0 = data[-1];
  95102. FLAC__int32 last_error_1 = data[-1] - data[-2];
  95103. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  95104. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  95105. FLAC__int32 error, save;
  95106. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  95107. unsigned i, order;
  95108. for(i = 0; i < data_len; i++) {
  95109. error = data[i] ; total_error_0 += local_abs(error); save = error;
  95110. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  95111. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  95112. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  95113. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  95114. }
  95115. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  95116. order = 0;
  95117. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  95118. order = 1;
  95119. else if(total_error_2 < min(total_error_3, total_error_4))
  95120. order = 2;
  95121. else if(total_error_3 < total_error_4)
  95122. order = 3;
  95123. else
  95124. order = 4;
  95125. /* Estimate the expected number of bits per residual signal sample. */
  95126. /* 'total_error*' is linearly related to the variance of the residual */
  95127. /* signal, so we use it directly to compute E(|x|) */
  95128. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  95129. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  95130. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  95131. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  95132. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  95133. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95134. 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);
  95135. 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);
  95136. 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);
  95137. 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);
  95138. 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);
  95139. #else
  95140. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  95141. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  95142. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  95143. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  95144. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  95145. #endif
  95146. return order;
  95147. }
  95148. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95149. 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])
  95150. #else
  95151. 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])
  95152. #endif
  95153. {
  95154. FLAC__int32 last_error_0 = data[-1];
  95155. FLAC__int32 last_error_1 = data[-1] - data[-2];
  95156. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  95157. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  95158. FLAC__int32 error, save;
  95159. /* total_error_* are 64-bits to avoid overflow when encoding
  95160. * erratic signals when the bits-per-sample and blocksize are
  95161. * large.
  95162. */
  95163. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  95164. unsigned i, order;
  95165. for(i = 0; i < data_len; i++) {
  95166. error = data[i] ; total_error_0 += local_abs(error); save = error;
  95167. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  95168. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  95169. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  95170. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  95171. }
  95172. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  95173. order = 0;
  95174. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  95175. order = 1;
  95176. else if(total_error_2 < min(total_error_3, total_error_4))
  95177. order = 2;
  95178. else if(total_error_3 < total_error_4)
  95179. order = 3;
  95180. else
  95181. order = 4;
  95182. /* Estimate the expected number of bits per residual signal sample. */
  95183. /* 'total_error*' is linearly related to the variance of the residual */
  95184. /* signal, so we use it directly to compute E(|x|) */
  95185. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  95186. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  95187. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  95188. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  95189. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  95190. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95191. #if defined _MSC_VER || defined __MINGW32__
  95192. /* with MSVC you have to spoon feed it the casting */
  95193. 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);
  95194. 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);
  95195. 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);
  95196. 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);
  95197. 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);
  95198. #else
  95199. 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);
  95200. 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);
  95201. 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);
  95202. 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);
  95203. 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);
  95204. #endif
  95205. #else
  95206. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  95207. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  95208. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  95209. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  95210. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  95211. #endif
  95212. return order;
  95213. }
  95214. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  95215. {
  95216. const int idata_len = (int)data_len;
  95217. int i;
  95218. switch(order) {
  95219. case 0:
  95220. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  95221. memcpy(residual, data, sizeof(residual[0])*data_len);
  95222. break;
  95223. case 1:
  95224. for(i = 0; i < idata_len; i++)
  95225. residual[i] = data[i] - data[i-1];
  95226. break;
  95227. case 2:
  95228. for(i = 0; i < idata_len; i++)
  95229. #if 1 /* OPT: may be faster with some compilers on some systems */
  95230. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  95231. #else
  95232. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  95233. #endif
  95234. break;
  95235. case 3:
  95236. for(i = 0; i < idata_len; i++)
  95237. #if 1 /* OPT: may be faster with some compilers on some systems */
  95238. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  95239. #else
  95240. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  95241. #endif
  95242. break;
  95243. case 4:
  95244. for(i = 0; i < idata_len; i++)
  95245. #if 1 /* OPT: may be faster with some compilers on some systems */
  95246. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  95247. #else
  95248. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  95249. #endif
  95250. break;
  95251. default:
  95252. FLAC__ASSERT(0);
  95253. }
  95254. }
  95255. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  95256. {
  95257. int i, idata_len = (int)data_len;
  95258. switch(order) {
  95259. case 0:
  95260. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  95261. memcpy(data, residual, sizeof(residual[0])*data_len);
  95262. break;
  95263. case 1:
  95264. for(i = 0; i < idata_len; i++)
  95265. data[i] = residual[i] + data[i-1];
  95266. break;
  95267. case 2:
  95268. for(i = 0; i < idata_len; i++)
  95269. #if 1 /* OPT: may be faster with some compilers on some systems */
  95270. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  95271. #else
  95272. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  95273. #endif
  95274. break;
  95275. case 3:
  95276. for(i = 0; i < idata_len; i++)
  95277. #if 1 /* OPT: may be faster with some compilers on some systems */
  95278. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  95279. #else
  95280. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  95281. #endif
  95282. break;
  95283. case 4:
  95284. for(i = 0; i < idata_len; i++)
  95285. #if 1 /* OPT: may be faster with some compilers on some systems */
  95286. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  95287. #else
  95288. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  95289. #endif
  95290. break;
  95291. default:
  95292. FLAC__ASSERT(0);
  95293. }
  95294. }
  95295. #endif
  95296. /*** End of inlined file: fixed.c ***/
  95297. /*** Start of inlined file: float.c ***/
  95298. /*** Start of inlined file: juce_FlacHeader.h ***/
  95299. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95300. // tasks..
  95301. #define VERSION "1.2.1"
  95302. #define FLAC__NO_DLL 1
  95303. #if JUCE_MSVC
  95304. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95305. #endif
  95306. #if JUCE_MAC
  95307. #define FLAC__SYS_DARWIN 1
  95308. #endif
  95309. /*** End of inlined file: juce_FlacHeader.h ***/
  95310. #if JUCE_USE_FLAC
  95311. #if HAVE_CONFIG_H
  95312. # include <config.h>
  95313. #endif
  95314. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  95315. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  95316. #ifdef _MSC_VER
  95317. #define FLAC__U64L(x) x
  95318. #else
  95319. #define FLAC__U64L(x) x##LLU
  95320. #endif
  95321. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  95322. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  95323. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  95324. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  95325. const FLAC__fixedpoint FLAC__FP_E = 178145;
  95326. /* Lookup tables for Knuth's logarithm algorithm */
  95327. #define LOG2_LOOKUP_PRECISION 16
  95328. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  95329. {
  95330. /*
  95331. * 0 fraction bits
  95332. */
  95333. /* undefined */ 0x00000000,
  95334. /* lg(2/1) = */ 0x00000001,
  95335. /* lg(4/3) = */ 0x00000000,
  95336. /* lg(8/7) = */ 0x00000000,
  95337. /* lg(16/15) = */ 0x00000000,
  95338. /* lg(32/31) = */ 0x00000000,
  95339. /* lg(64/63) = */ 0x00000000,
  95340. /* lg(128/127) = */ 0x00000000,
  95341. /* lg(256/255) = */ 0x00000000,
  95342. /* lg(512/511) = */ 0x00000000,
  95343. /* lg(1024/1023) = */ 0x00000000,
  95344. /* lg(2048/2047) = */ 0x00000000,
  95345. /* lg(4096/4095) = */ 0x00000000,
  95346. /* lg(8192/8191) = */ 0x00000000,
  95347. /* lg(16384/16383) = */ 0x00000000,
  95348. /* lg(32768/32767) = */ 0x00000000
  95349. },
  95350. {
  95351. /*
  95352. * 4 fraction bits
  95353. */
  95354. /* undefined */ 0x00000000,
  95355. /* lg(2/1) = */ 0x00000010,
  95356. /* lg(4/3) = */ 0x00000007,
  95357. /* lg(8/7) = */ 0x00000003,
  95358. /* lg(16/15) = */ 0x00000001,
  95359. /* lg(32/31) = */ 0x00000001,
  95360. /* lg(64/63) = */ 0x00000000,
  95361. /* lg(128/127) = */ 0x00000000,
  95362. /* lg(256/255) = */ 0x00000000,
  95363. /* lg(512/511) = */ 0x00000000,
  95364. /* lg(1024/1023) = */ 0x00000000,
  95365. /* lg(2048/2047) = */ 0x00000000,
  95366. /* lg(4096/4095) = */ 0x00000000,
  95367. /* lg(8192/8191) = */ 0x00000000,
  95368. /* lg(16384/16383) = */ 0x00000000,
  95369. /* lg(32768/32767) = */ 0x00000000
  95370. },
  95371. {
  95372. /*
  95373. * 8 fraction bits
  95374. */
  95375. /* undefined */ 0x00000000,
  95376. /* lg(2/1) = */ 0x00000100,
  95377. /* lg(4/3) = */ 0x0000006a,
  95378. /* lg(8/7) = */ 0x00000031,
  95379. /* lg(16/15) = */ 0x00000018,
  95380. /* lg(32/31) = */ 0x0000000c,
  95381. /* lg(64/63) = */ 0x00000006,
  95382. /* lg(128/127) = */ 0x00000003,
  95383. /* lg(256/255) = */ 0x00000001,
  95384. /* lg(512/511) = */ 0x00000001,
  95385. /* lg(1024/1023) = */ 0x00000000,
  95386. /* lg(2048/2047) = */ 0x00000000,
  95387. /* lg(4096/4095) = */ 0x00000000,
  95388. /* lg(8192/8191) = */ 0x00000000,
  95389. /* lg(16384/16383) = */ 0x00000000,
  95390. /* lg(32768/32767) = */ 0x00000000
  95391. },
  95392. {
  95393. /*
  95394. * 12 fraction bits
  95395. */
  95396. /* undefined */ 0x00000000,
  95397. /* lg(2/1) = */ 0x00001000,
  95398. /* lg(4/3) = */ 0x000006a4,
  95399. /* lg(8/7) = */ 0x00000315,
  95400. /* lg(16/15) = */ 0x0000017d,
  95401. /* lg(32/31) = */ 0x000000bc,
  95402. /* lg(64/63) = */ 0x0000005d,
  95403. /* lg(128/127) = */ 0x0000002e,
  95404. /* lg(256/255) = */ 0x00000017,
  95405. /* lg(512/511) = */ 0x0000000c,
  95406. /* lg(1024/1023) = */ 0x00000006,
  95407. /* lg(2048/2047) = */ 0x00000003,
  95408. /* lg(4096/4095) = */ 0x00000001,
  95409. /* lg(8192/8191) = */ 0x00000001,
  95410. /* lg(16384/16383) = */ 0x00000000,
  95411. /* lg(32768/32767) = */ 0x00000000
  95412. },
  95413. {
  95414. /*
  95415. * 16 fraction bits
  95416. */
  95417. /* undefined */ 0x00000000,
  95418. /* lg(2/1) = */ 0x00010000,
  95419. /* lg(4/3) = */ 0x00006a40,
  95420. /* lg(8/7) = */ 0x00003151,
  95421. /* lg(16/15) = */ 0x000017d6,
  95422. /* lg(32/31) = */ 0x00000bba,
  95423. /* lg(64/63) = */ 0x000005d1,
  95424. /* lg(128/127) = */ 0x000002e6,
  95425. /* lg(256/255) = */ 0x00000172,
  95426. /* lg(512/511) = */ 0x000000b9,
  95427. /* lg(1024/1023) = */ 0x0000005c,
  95428. /* lg(2048/2047) = */ 0x0000002e,
  95429. /* lg(4096/4095) = */ 0x00000017,
  95430. /* lg(8192/8191) = */ 0x0000000c,
  95431. /* lg(16384/16383) = */ 0x00000006,
  95432. /* lg(32768/32767) = */ 0x00000003
  95433. },
  95434. {
  95435. /*
  95436. * 20 fraction bits
  95437. */
  95438. /* undefined */ 0x00000000,
  95439. /* lg(2/1) = */ 0x00100000,
  95440. /* lg(4/3) = */ 0x0006a3fe,
  95441. /* lg(8/7) = */ 0x00031513,
  95442. /* lg(16/15) = */ 0x00017d60,
  95443. /* lg(32/31) = */ 0x0000bb9d,
  95444. /* lg(64/63) = */ 0x00005d10,
  95445. /* lg(128/127) = */ 0x00002e59,
  95446. /* lg(256/255) = */ 0x00001721,
  95447. /* lg(512/511) = */ 0x00000b8e,
  95448. /* lg(1024/1023) = */ 0x000005c6,
  95449. /* lg(2048/2047) = */ 0x000002e3,
  95450. /* lg(4096/4095) = */ 0x00000171,
  95451. /* lg(8192/8191) = */ 0x000000b9,
  95452. /* lg(16384/16383) = */ 0x0000005c,
  95453. /* lg(32768/32767) = */ 0x0000002e
  95454. },
  95455. {
  95456. /*
  95457. * 24 fraction bits
  95458. */
  95459. /* undefined */ 0x00000000,
  95460. /* lg(2/1) = */ 0x01000000,
  95461. /* lg(4/3) = */ 0x006a3fe6,
  95462. /* lg(8/7) = */ 0x00315130,
  95463. /* lg(16/15) = */ 0x0017d605,
  95464. /* lg(32/31) = */ 0x000bb9ca,
  95465. /* lg(64/63) = */ 0x0005d0fc,
  95466. /* lg(128/127) = */ 0x0002e58f,
  95467. /* lg(256/255) = */ 0x0001720e,
  95468. /* lg(512/511) = */ 0x0000b8d8,
  95469. /* lg(1024/1023) = */ 0x00005c61,
  95470. /* lg(2048/2047) = */ 0x00002e2d,
  95471. /* lg(4096/4095) = */ 0x00001716,
  95472. /* lg(8192/8191) = */ 0x00000b8b,
  95473. /* lg(16384/16383) = */ 0x000005c5,
  95474. /* lg(32768/32767) = */ 0x000002e3
  95475. },
  95476. {
  95477. /*
  95478. * 28 fraction bits
  95479. */
  95480. /* undefined */ 0x00000000,
  95481. /* lg(2/1) = */ 0x10000000,
  95482. /* lg(4/3) = */ 0x06a3fe5c,
  95483. /* lg(8/7) = */ 0x03151301,
  95484. /* lg(16/15) = */ 0x017d6049,
  95485. /* lg(32/31) = */ 0x00bb9ca6,
  95486. /* lg(64/63) = */ 0x005d0fba,
  95487. /* lg(128/127) = */ 0x002e58f7,
  95488. /* lg(256/255) = */ 0x001720da,
  95489. /* lg(512/511) = */ 0x000b8d87,
  95490. /* lg(1024/1023) = */ 0x0005c60b,
  95491. /* lg(2048/2047) = */ 0x0002e2d7,
  95492. /* lg(4096/4095) = */ 0x00017160,
  95493. /* lg(8192/8191) = */ 0x0000b8ad,
  95494. /* lg(16384/16383) = */ 0x00005c56,
  95495. /* lg(32768/32767) = */ 0x00002e2b
  95496. }
  95497. };
  95498. #if 0
  95499. static const FLAC__uint64 log2_lookup_wide[] = {
  95500. {
  95501. /*
  95502. * 32 fraction bits
  95503. */
  95504. /* undefined */ 0x00000000,
  95505. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  95506. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  95507. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  95508. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  95509. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  95510. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  95511. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  95512. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  95513. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  95514. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  95515. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  95516. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  95517. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  95518. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  95519. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  95520. },
  95521. {
  95522. /*
  95523. * 48 fraction bits
  95524. */
  95525. /* undefined */ 0x00000000,
  95526. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  95527. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  95528. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  95529. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  95530. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  95531. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  95532. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  95533. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  95534. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  95535. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  95536. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  95537. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  95538. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  95539. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  95540. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  95541. }
  95542. };
  95543. #endif
  95544. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  95545. {
  95546. const FLAC__uint32 ONE = (1u << fracbits);
  95547. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  95548. FLAC__ASSERT(fracbits < 32);
  95549. FLAC__ASSERT((fracbits & 0x3) == 0);
  95550. if(x < ONE)
  95551. return 0;
  95552. if(precision > LOG2_LOOKUP_PRECISION)
  95553. precision = LOG2_LOOKUP_PRECISION;
  95554. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  95555. {
  95556. FLAC__uint32 y = 0;
  95557. FLAC__uint32 z = x >> 1, k = 1;
  95558. while (x > ONE && k < precision) {
  95559. if (x - z >= ONE) {
  95560. x -= z;
  95561. z = x >> k;
  95562. y += table[k];
  95563. }
  95564. else {
  95565. z >>= 1;
  95566. k++;
  95567. }
  95568. }
  95569. return y;
  95570. }
  95571. }
  95572. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  95573. #endif
  95574. /*** End of inlined file: float.c ***/
  95575. /*** Start of inlined file: format.c ***/
  95576. /*** Start of inlined file: juce_FlacHeader.h ***/
  95577. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95578. // tasks..
  95579. #define VERSION "1.2.1"
  95580. #define FLAC__NO_DLL 1
  95581. #if JUCE_MSVC
  95582. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95583. #endif
  95584. #if JUCE_MAC
  95585. #define FLAC__SYS_DARWIN 1
  95586. #endif
  95587. /*** End of inlined file: juce_FlacHeader.h ***/
  95588. #if JUCE_USE_FLAC
  95589. #if HAVE_CONFIG_H
  95590. # include <config.h>
  95591. #endif
  95592. #include <stdio.h>
  95593. #include <stdlib.h> /* for qsort() */
  95594. #include <string.h> /* for memset() */
  95595. #ifndef FLaC__INLINE
  95596. #define FLaC__INLINE
  95597. #endif
  95598. #ifdef min
  95599. #undef min
  95600. #endif
  95601. #define min(a,b) ((a)<(b)?(a):(b))
  95602. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  95603. #ifdef _MSC_VER
  95604. #define FLAC__U64L(x) x
  95605. #else
  95606. #define FLAC__U64L(x) x##LLU
  95607. #endif
  95608. /* VERSION should come from configure */
  95609. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  95610. ;
  95611. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  95612. /* yet one more hack because of MSVC6: */
  95613. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  95614. #else
  95615. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  95616. #endif
  95617. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  95618. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  95619. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  95620. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  95621. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  95622. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  95623. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  95624. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  95625. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  95626. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  95627. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  95628. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  95629. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  95630. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  95631. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  95632. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  95633. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  95634. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  95635. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  95636. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  95637. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  95638. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  95639. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  95640. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  95641. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  95642. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  95643. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  95644. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  95645. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  95646. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  95647. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  95648. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  95649. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  95650. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  95651. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  95652. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  95653. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  95654. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  95655. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  95656. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  95657. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  95658. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  95659. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  95660. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  95661. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  95662. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  95663. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  95664. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  95665. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  95666. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  95667. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  95668. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  95669. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  95670. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  95671. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  95672. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  95673. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  95674. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  95675. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  95676. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  95677. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  95678. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  95679. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  95680. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  95681. "PARTITIONED_RICE",
  95682. "PARTITIONED_RICE2"
  95683. };
  95684. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  95685. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  95686. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  95687. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  95688. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  95689. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  95690. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  95691. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  95692. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  95693. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  95694. "CONSTANT",
  95695. "VERBATIM",
  95696. "FIXED",
  95697. "LPC"
  95698. };
  95699. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  95700. "INDEPENDENT",
  95701. "LEFT_SIDE",
  95702. "RIGHT_SIDE",
  95703. "MID_SIDE"
  95704. };
  95705. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  95706. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  95707. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  95708. };
  95709. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  95710. "STREAMINFO",
  95711. "PADDING",
  95712. "APPLICATION",
  95713. "SEEKTABLE",
  95714. "VORBIS_COMMENT",
  95715. "CUESHEET",
  95716. "PICTURE"
  95717. };
  95718. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  95719. "Other",
  95720. "32x32 pixels 'file icon' (PNG only)",
  95721. "Other file icon",
  95722. "Cover (front)",
  95723. "Cover (back)",
  95724. "Leaflet page",
  95725. "Media (e.g. label side of CD)",
  95726. "Lead artist/lead performer/soloist",
  95727. "Artist/performer",
  95728. "Conductor",
  95729. "Band/Orchestra",
  95730. "Composer",
  95731. "Lyricist/text writer",
  95732. "Recording Location",
  95733. "During recording",
  95734. "During performance",
  95735. "Movie/video screen capture",
  95736. "A bright coloured fish",
  95737. "Illustration",
  95738. "Band/artist logotype",
  95739. "Publisher/Studio logotype"
  95740. };
  95741. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  95742. {
  95743. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  95744. return false;
  95745. }
  95746. else
  95747. return true;
  95748. }
  95749. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  95750. {
  95751. if(
  95752. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  95753. (
  95754. sample_rate >= (1u << 16) &&
  95755. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  95756. )
  95757. ) {
  95758. return false;
  95759. }
  95760. else
  95761. return true;
  95762. }
  95763. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  95764. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  95765. {
  95766. unsigned i;
  95767. FLAC__uint64 prev_sample_number = 0;
  95768. FLAC__bool got_prev = false;
  95769. FLAC__ASSERT(0 != seek_table);
  95770. for(i = 0; i < seek_table->num_points; i++) {
  95771. if(got_prev) {
  95772. if(
  95773. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  95774. seek_table->points[i].sample_number <= prev_sample_number
  95775. )
  95776. return false;
  95777. }
  95778. prev_sample_number = seek_table->points[i].sample_number;
  95779. got_prev = true;
  95780. }
  95781. return true;
  95782. }
  95783. /* used as the sort predicate for qsort() */
  95784. static int seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  95785. {
  95786. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  95787. if(l->sample_number == r->sample_number)
  95788. return 0;
  95789. else if(l->sample_number < r->sample_number)
  95790. return -1;
  95791. else
  95792. return 1;
  95793. }
  95794. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  95795. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  95796. {
  95797. unsigned i, j;
  95798. FLAC__bool first;
  95799. FLAC__ASSERT(0 != seek_table);
  95800. /* sort the seekpoints */
  95801. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare_);
  95802. /* uniquify the seekpoints */
  95803. first = true;
  95804. for(i = j = 0; i < seek_table->num_points; i++) {
  95805. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  95806. if(!first) {
  95807. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  95808. continue;
  95809. }
  95810. }
  95811. first = false;
  95812. seek_table->points[j++] = seek_table->points[i];
  95813. }
  95814. for(i = j; i < seek_table->num_points; i++) {
  95815. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  95816. seek_table->points[i].stream_offset = 0;
  95817. seek_table->points[i].frame_samples = 0;
  95818. }
  95819. return j;
  95820. }
  95821. /*
  95822. * also disallows non-shortest-form encodings, c.f.
  95823. * http://www.unicode.org/versions/corrigendum1.html
  95824. * and a more clear explanation at the end of this section:
  95825. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  95826. */
  95827. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  95828. {
  95829. FLAC__ASSERT(0 != utf8);
  95830. if ((utf8[0] & 0x80) == 0) {
  95831. return 1;
  95832. }
  95833. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  95834. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  95835. return 0;
  95836. return 2;
  95837. }
  95838. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  95839. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  95840. return 0;
  95841. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  95842. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  95843. return 0;
  95844. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  95845. return 0;
  95846. return 3;
  95847. }
  95848. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  95849. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  95850. return 0;
  95851. return 4;
  95852. }
  95853. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  95854. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  95855. return 0;
  95856. return 5;
  95857. }
  95858. 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) {
  95859. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  95860. return 0;
  95861. return 6;
  95862. }
  95863. else {
  95864. return 0;
  95865. }
  95866. }
  95867. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  95868. {
  95869. char c;
  95870. for(c = *name; c; c = *(++name))
  95871. if(c < 0x20 || c == 0x3d || c > 0x7d)
  95872. return false;
  95873. return true;
  95874. }
  95875. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  95876. {
  95877. if(length == (unsigned)(-1)) {
  95878. while(*value) {
  95879. unsigned n = utf8len_(value);
  95880. if(n == 0)
  95881. return false;
  95882. value += n;
  95883. }
  95884. }
  95885. else {
  95886. const FLAC__byte *end = value + length;
  95887. while(value < end) {
  95888. unsigned n = utf8len_(value);
  95889. if(n == 0)
  95890. return false;
  95891. value += n;
  95892. }
  95893. if(value != end)
  95894. return false;
  95895. }
  95896. return true;
  95897. }
  95898. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  95899. {
  95900. const FLAC__byte *s, *end;
  95901. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  95902. if(*s < 0x20 || *s > 0x7D)
  95903. return false;
  95904. }
  95905. if(s == end)
  95906. return false;
  95907. s++; /* skip '=' */
  95908. while(s < end) {
  95909. unsigned n = utf8len_(s);
  95910. if(n == 0)
  95911. return false;
  95912. s += n;
  95913. }
  95914. if(s != end)
  95915. return false;
  95916. return true;
  95917. }
  95918. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  95919. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  95920. {
  95921. unsigned i, j;
  95922. if(check_cd_da_subset) {
  95923. if(cue_sheet->lead_in < 2 * 44100) {
  95924. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  95925. return false;
  95926. }
  95927. if(cue_sheet->lead_in % 588 != 0) {
  95928. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  95929. return false;
  95930. }
  95931. }
  95932. if(cue_sheet->num_tracks == 0) {
  95933. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  95934. return false;
  95935. }
  95936. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  95937. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  95938. return false;
  95939. }
  95940. for(i = 0; i < cue_sheet->num_tracks; i++) {
  95941. if(cue_sheet->tracks[i].number == 0) {
  95942. if(violation) *violation = "cue sheet may not have a track number 0";
  95943. return false;
  95944. }
  95945. if(check_cd_da_subset) {
  95946. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  95947. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  95948. return false;
  95949. }
  95950. }
  95951. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  95952. if(violation) {
  95953. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  95954. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  95955. else
  95956. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  95957. }
  95958. return false;
  95959. }
  95960. if(i < cue_sheet->num_tracks - 1) {
  95961. if(cue_sheet->tracks[i].num_indices == 0) {
  95962. if(violation) *violation = "cue sheet track must have at least one index point";
  95963. return false;
  95964. }
  95965. if(cue_sheet->tracks[i].indices[0].number > 1) {
  95966. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  95967. return false;
  95968. }
  95969. }
  95970. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  95971. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  95972. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  95973. return false;
  95974. }
  95975. if(j > 0) {
  95976. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  95977. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  95978. return false;
  95979. }
  95980. }
  95981. }
  95982. }
  95983. return true;
  95984. }
  95985. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  95986. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  95987. {
  95988. char *p;
  95989. FLAC__byte *b;
  95990. for(p = picture->mime_type; *p; p++) {
  95991. if(*p < 0x20 || *p > 0x7e) {
  95992. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  95993. return false;
  95994. }
  95995. }
  95996. for(b = picture->description; *b; ) {
  95997. unsigned n = utf8len_(b);
  95998. if(n == 0) {
  95999. if(violation) *violation = "description string must be valid UTF-8";
  96000. return false;
  96001. }
  96002. b += n;
  96003. }
  96004. return true;
  96005. }
  96006. /*
  96007. * These routines are private to libFLAC
  96008. */
  96009. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  96010. {
  96011. return
  96012. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  96013. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  96014. blocksize,
  96015. predictor_order
  96016. );
  96017. }
  96018. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  96019. {
  96020. unsigned max_rice_partition_order = 0;
  96021. while(!(blocksize & 1)) {
  96022. max_rice_partition_order++;
  96023. blocksize >>= 1;
  96024. }
  96025. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  96026. }
  96027. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  96028. {
  96029. unsigned max_rice_partition_order = limit;
  96030. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  96031. max_rice_partition_order--;
  96032. FLAC__ASSERT(
  96033. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  96034. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  96035. );
  96036. return max_rice_partition_order;
  96037. }
  96038. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  96039. {
  96040. FLAC__ASSERT(0 != object);
  96041. object->parameters = 0;
  96042. object->raw_bits = 0;
  96043. object->capacity_by_order = 0;
  96044. }
  96045. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  96046. {
  96047. FLAC__ASSERT(0 != object);
  96048. if(0 != object->parameters)
  96049. free(object->parameters);
  96050. if(0 != object->raw_bits)
  96051. free(object->raw_bits);
  96052. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  96053. }
  96054. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  96055. {
  96056. FLAC__ASSERT(0 != object);
  96057. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  96058. if(object->capacity_by_order < max_partition_order) {
  96059. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  96060. return false;
  96061. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  96062. return false;
  96063. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  96064. object->capacity_by_order = max_partition_order;
  96065. }
  96066. return true;
  96067. }
  96068. #endif
  96069. /*** End of inlined file: format.c ***/
  96070. /*** Start of inlined file: lpc_flac.c ***/
  96071. /*** Start of inlined file: juce_FlacHeader.h ***/
  96072. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96073. // tasks..
  96074. #define VERSION "1.2.1"
  96075. #define FLAC__NO_DLL 1
  96076. #if JUCE_MSVC
  96077. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96078. #endif
  96079. #if JUCE_MAC
  96080. #define FLAC__SYS_DARWIN 1
  96081. #endif
  96082. /*** End of inlined file: juce_FlacHeader.h ***/
  96083. #if JUCE_USE_FLAC
  96084. #if HAVE_CONFIG_H
  96085. # include <config.h>
  96086. #endif
  96087. #include <math.h>
  96088. /*** Start of inlined file: lpc.h ***/
  96089. #ifndef FLAC__PRIVATE__LPC_H
  96090. #define FLAC__PRIVATE__LPC_H
  96091. #ifdef HAVE_CONFIG_H
  96092. #include <config.h>
  96093. #endif
  96094. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96095. /*
  96096. * FLAC__lpc_window_data()
  96097. * --------------------------------------------------------------------
  96098. * Applies the given window to the data.
  96099. * OPT: asm implementation
  96100. *
  96101. * IN in[0,data_len-1]
  96102. * IN window[0,data_len-1]
  96103. * OUT out[0,lag-1]
  96104. * IN data_len
  96105. */
  96106. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  96107. /*
  96108. * FLAC__lpc_compute_autocorrelation()
  96109. * --------------------------------------------------------------------
  96110. * Compute the autocorrelation for lags between 0 and lag-1.
  96111. * Assumes data[] outside of [0,data_len-1] == 0.
  96112. * Asserts that lag > 0.
  96113. *
  96114. * IN data[0,data_len-1]
  96115. * IN data_len
  96116. * IN 0 < lag <= data_len
  96117. * OUT autoc[0,lag-1]
  96118. */
  96119. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96120. #ifndef FLAC__NO_ASM
  96121. # ifdef FLAC__CPU_IA32
  96122. # ifdef FLAC__HAS_NASM
  96123. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96124. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96125. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96126. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96127. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96128. # endif
  96129. # endif
  96130. #endif
  96131. /*
  96132. * FLAC__lpc_compute_lp_coefficients()
  96133. * --------------------------------------------------------------------
  96134. * Computes LP coefficients for orders 1..max_order.
  96135. * Do not call if autoc[0] == 0.0. This means the signal is zero
  96136. * and there is no point in calculating a predictor.
  96137. *
  96138. * IN autoc[0,max_order] autocorrelation values
  96139. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  96140. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  96141. * *** IMPORTANT:
  96142. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  96143. * OUT error[0,max_order-1] error for each order (more
  96144. * specifically, the variance of
  96145. * the error signal times # of
  96146. * samples in the signal)
  96147. *
  96148. * Example: if max_order is 9, the LP coefficients for order 9 will be
  96149. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  96150. * in lp_coeff[7][0,7], etc.
  96151. */
  96152. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  96153. /*
  96154. * FLAC__lpc_quantize_coefficients()
  96155. * --------------------------------------------------------------------
  96156. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  96157. * must be less than 32 (sizeof(FLAC__int32)*8).
  96158. *
  96159. * IN lp_coeff[0,order-1] LP coefficients
  96160. * IN order LP order
  96161. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  96162. * desired precision (in bits, including sign
  96163. * bit) of largest coefficient
  96164. * OUT qlp_coeff[0,order-1] quantized coefficients
  96165. * OUT shift # of bits to shift right to get approximated
  96166. * LP coefficients. NOTE: could be negative.
  96167. * RETURN 0 => quantization OK
  96168. * 1 => coefficients require too much shifting for *shift to
  96169. * fit in the LPC subframe header. 'shift' is unset.
  96170. * 2 => coefficients are all zero, which is bad. 'shift' is
  96171. * unset.
  96172. */
  96173. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  96174. /*
  96175. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  96176. * --------------------------------------------------------------------
  96177. * Compute the residual signal obtained from sutracting the predicted
  96178. * signal from the original.
  96179. *
  96180. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  96181. * IN data_len length of original signal
  96182. * IN qlp_coeff[0,order-1] quantized LP coefficients
  96183. * IN order > 0 LP order
  96184. * IN lp_quantization quantization of LP coefficients in bits
  96185. * OUT residual[0,data_len-1] residual signal
  96186. */
  96187. 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[]);
  96188. 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[]);
  96189. #ifndef FLAC__NO_ASM
  96190. # ifdef FLAC__CPU_IA32
  96191. # ifdef FLAC__HAS_NASM
  96192. 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[]);
  96193. 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[]);
  96194. # endif
  96195. # endif
  96196. #endif
  96197. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  96198. /*
  96199. * FLAC__lpc_restore_signal()
  96200. * --------------------------------------------------------------------
  96201. * Restore the original signal by summing the residual and the
  96202. * predictor.
  96203. *
  96204. * IN residual[0,data_len-1] residual signal
  96205. * IN data_len length of original signal
  96206. * IN qlp_coeff[0,order-1] quantized LP coefficients
  96207. * IN order > 0 LP order
  96208. * IN lp_quantization quantization of LP coefficients in bits
  96209. * *** IMPORTANT: the caller must pass in the historical samples:
  96210. * IN data[-order,-1] previously-reconstructed historical samples
  96211. * OUT data[0,data_len-1] original signal
  96212. */
  96213. 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[]);
  96214. 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[]);
  96215. #ifndef FLAC__NO_ASM
  96216. # ifdef FLAC__CPU_IA32
  96217. # ifdef FLAC__HAS_NASM
  96218. 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[]);
  96219. 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[]);
  96220. # endif /* FLAC__HAS_NASM */
  96221. # elif defined FLAC__CPU_PPC
  96222. 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[]);
  96223. 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[]);
  96224. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  96225. #endif /* FLAC__NO_ASM */
  96226. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96227. /*
  96228. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  96229. * --------------------------------------------------------------------
  96230. * Compute the expected number of bits per residual signal sample
  96231. * based on the LP error (which is related to the residual variance).
  96232. *
  96233. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  96234. * IN total_samples > 0 # of samples in residual signal
  96235. * RETURN expected bits per sample
  96236. */
  96237. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  96238. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  96239. /*
  96240. * FLAC__lpc_compute_best_order()
  96241. * --------------------------------------------------------------------
  96242. * Compute the best order from the array of signal errors returned
  96243. * during coefficient computation.
  96244. *
  96245. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  96246. * IN max_order > 0 max LP order
  96247. * IN total_samples > 0 # of samples in residual signal
  96248. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  96249. * (includes warmup sample size and quantized LP coefficient)
  96250. * RETURN [1,max_order] best order
  96251. */
  96252. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  96253. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  96254. #endif
  96255. /*** End of inlined file: lpc.h ***/
  96256. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  96257. #include <stdio.h>
  96258. #endif
  96259. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96260. #ifndef M_LN2
  96261. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  96262. #define M_LN2 0.69314718055994530942
  96263. #endif
  96264. /* OPT: #undef'ing this may improve the speed on some architectures */
  96265. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  96266. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  96267. {
  96268. unsigned i;
  96269. for(i = 0; i < data_len; i++)
  96270. out[i] = in[i] * window[i];
  96271. }
  96272. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  96273. {
  96274. /* a readable, but slower, version */
  96275. #if 0
  96276. FLAC__real d;
  96277. unsigned i;
  96278. FLAC__ASSERT(lag > 0);
  96279. FLAC__ASSERT(lag <= data_len);
  96280. /*
  96281. * Technically we should subtract the mean first like so:
  96282. * for(i = 0; i < data_len; i++)
  96283. * data[i] -= mean;
  96284. * but it appears not to make enough of a difference to matter, and
  96285. * most signals are already closely centered around zero
  96286. */
  96287. while(lag--) {
  96288. for(i = lag, d = 0.0; i < data_len; i++)
  96289. d += data[i] * data[i - lag];
  96290. autoc[lag] = d;
  96291. }
  96292. #endif
  96293. /*
  96294. * this version tends to run faster because of better data locality
  96295. * ('data_len' is usually much larger than 'lag')
  96296. */
  96297. FLAC__real d;
  96298. unsigned sample, coeff;
  96299. const unsigned limit = data_len - lag;
  96300. FLAC__ASSERT(lag > 0);
  96301. FLAC__ASSERT(lag <= data_len);
  96302. for(coeff = 0; coeff < lag; coeff++)
  96303. autoc[coeff] = 0.0;
  96304. for(sample = 0; sample <= limit; sample++) {
  96305. d = data[sample];
  96306. for(coeff = 0; coeff < lag; coeff++)
  96307. autoc[coeff] += d * data[sample+coeff];
  96308. }
  96309. for(; sample < data_len; sample++) {
  96310. d = data[sample];
  96311. for(coeff = 0; coeff < data_len - sample; coeff++)
  96312. autoc[coeff] += d * data[sample+coeff];
  96313. }
  96314. }
  96315. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  96316. {
  96317. unsigned i, j;
  96318. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  96319. FLAC__ASSERT(0 != max_order);
  96320. FLAC__ASSERT(0 < *max_order);
  96321. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  96322. FLAC__ASSERT(autoc[0] != 0.0);
  96323. err = autoc[0];
  96324. for(i = 0; i < *max_order; i++) {
  96325. /* Sum up this iteration's reflection coefficient. */
  96326. r = -autoc[i+1];
  96327. for(j = 0; j < i; j++)
  96328. r -= lpc[j] * autoc[i-j];
  96329. ref[i] = (r/=err);
  96330. /* Update LPC coefficients and total error. */
  96331. lpc[i]=r;
  96332. for(j = 0; j < (i>>1); j++) {
  96333. FLAC__double tmp = lpc[j];
  96334. lpc[j] += r * lpc[i-1-j];
  96335. lpc[i-1-j] += r * tmp;
  96336. }
  96337. if(i & 1)
  96338. lpc[j] += lpc[j] * r;
  96339. err *= (1.0 - r * r);
  96340. /* save this order */
  96341. for(j = 0; j <= i; j++)
  96342. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  96343. error[i] = err;
  96344. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  96345. if(err == 0.0) {
  96346. *max_order = i+1;
  96347. return;
  96348. }
  96349. }
  96350. }
  96351. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  96352. {
  96353. unsigned i;
  96354. FLAC__double cmax;
  96355. FLAC__int32 qmax, qmin;
  96356. FLAC__ASSERT(precision > 0);
  96357. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  96358. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  96359. precision--;
  96360. qmax = 1 << precision;
  96361. qmin = -qmax;
  96362. qmax--;
  96363. /* calc cmax = max( |lp_coeff[i]| ) */
  96364. cmax = 0.0;
  96365. for(i = 0; i < order; i++) {
  96366. const FLAC__double d = fabs(lp_coeff[i]);
  96367. if(d > cmax)
  96368. cmax = d;
  96369. }
  96370. if(cmax <= 0.0) {
  96371. /* => coefficients are all 0, which means our constant-detect didn't work */
  96372. return 2;
  96373. }
  96374. else {
  96375. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  96376. const int min_shiftlimit = -max_shiftlimit - 1;
  96377. int log2cmax;
  96378. (void)frexp(cmax, &log2cmax);
  96379. log2cmax--;
  96380. *shift = (int)precision - log2cmax - 1;
  96381. if(*shift > max_shiftlimit)
  96382. *shift = max_shiftlimit;
  96383. else if(*shift < min_shiftlimit)
  96384. return 1;
  96385. }
  96386. if(*shift >= 0) {
  96387. FLAC__double error = 0.0;
  96388. FLAC__int32 q;
  96389. for(i = 0; i < order; i++) {
  96390. error += lp_coeff[i] * (1 << *shift);
  96391. #if 1 /* unfortunately lround() is C99 */
  96392. if(error >= 0.0)
  96393. q = (FLAC__int32)(error + 0.5);
  96394. else
  96395. q = (FLAC__int32)(error - 0.5);
  96396. #else
  96397. q = lround(error);
  96398. #endif
  96399. #ifdef FLAC__OVERFLOW_DETECT
  96400. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  96401. 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]);
  96402. else if(q < qmin)
  96403. 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]);
  96404. #endif
  96405. if(q > qmax)
  96406. q = qmax;
  96407. else if(q < qmin)
  96408. q = qmin;
  96409. error -= q;
  96410. qlp_coeff[i] = q;
  96411. }
  96412. }
  96413. /* negative shift is very rare but due to design flaw, negative shift is
  96414. * a NOP in the decoder, so it must be handled specially by scaling down
  96415. * coeffs
  96416. */
  96417. else {
  96418. const int nshift = -(*shift);
  96419. FLAC__double error = 0.0;
  96420. FLAC__int32 q;
  96421. #ifdef DEBUG
  96422. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  96423. #endif
  96424. for(i = 0; i < order; i++) {
  96425. error += lp_coeff[i] / (1 << nshift);
  96426. #if 1 /* unfortunately lround() is C99 */
  96427. if(error >= 0.0)
  96428. q = (FLAC__int32)(error + 0.5);
  96429. else
  96430. q = (FLAC__int32)(error - 0.5);
  96431. #else
  96432. q = lround(error);
  96433. #endif
  96434. #ifdef FLAC__OVERFLOW_DETECT
  96435. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  96436. 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]);
  96437. else if(q < qmin)
  96438. 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]);
  96439. #endif
  96440. if(q > qmax)
  96441. q = qmax;
  96442. else if(q < qmin)
  96443. q = qmin;
  96444. error -= q;
  96445. qlp_coeff[i] = q;
  96446. }
  96447. *shift = 0;
  96448. }
  96449. return 0;
  96450. }
  96451. 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[])
  96452. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  96453. {
  96454. FLAC__int64 sumo;
  96455. unsigned i, j;
  96456. FLAC__int32 sum;
  96457. const FLAC__int32 *history;
  96458. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  96459. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  96460. for(i=0;i<order;i++)
  96461. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  96462. fprintf(stderr,"\n");
  96463. #endif
  96464. FLAC__ASSERT(order > 0);
  96465. for(i = 0; i < data_len; i++) {
  96466. sumo = 0;
  96467. sum = 0;
  96468. history = data;
  96469. for(j = 0; j < order; j++) {
  96470. sum += qlp_coeff[j] * (*(--history));
  96471. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  96472. #if defined _MSC_VER
  96473. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  96474. 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);
  96475. #else
  96476. if(sumo > 2147483647ll || sumo < -2147483648ll)
  96477. 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);
  96478. #endif
  96479. }
  96480. *(residual++) = *(data++) - (sum >> lp_quantization);
  96481. }
  96482. /* Here's a slower but clearer version:
  96483. for(i = 0; i < data_len; i++) {
  96484. sum = 0;
  96485. for(j = 0; j < order; j++)
  96486. sum += qlp_coeff[j] * data[i-j-1];
  96487. residual[i] = data[i] - (sum >> lp_quantization);
  96488. }
  96489. */
  96490. }
  96491. #else /* fully unrolled version for normal use */
  96492. {
  96493. int i;
  96494. FLAC__int32 sum;
  96495. FLAC__ASSERT(order > 0);
  96496. FLAC__ASSERT(order <= 32);
  96497. /*
  96498. * We do unique versions up to 12th order since that's the subset limit.
  96499. * Also they are roughly ordered to match frequency of occurrence to
  96500. * minimize branching.
  96501. */
  96502. if(order <= 12) {
  96503. if(order > 8) {
  96504. if(order > 10) {
  96505. if(order == 12) {
  96506. for(i = 0; i < (int)data_len; i++) {
  96507. sum = 0;
  96508. sum += qlp_coeff[11] * data[i-12];
  96509. sum += qlp_coeff[10] * data[i-11];
  96510. sum += qlp_coeff[9] * data[i-10];
  96511. sum += qlp_coeff[8] * data[i-9];
  96512. sum += qlp_coeff[7] * data[i-8];
  96513. sum += qlp_coeff[6] * data[i-7];
  96514. sum += qlp_coeff[5] * data[i-6];
  96515. sum += qlp_coeff[4] * data[i-5];
  96516. sum += qlp_coeff[3] * data[i-4];
  96517. sum += qlp_coeff[2] * data[i-3];
  96518. sum += qlp_coeff[1] * data[i-2];
  96519. sum += qlp_coeff[0] * data[i-1];
  96520. residual[i] = data[i] - (sum >> lp_quantization);
  96521. }
  96522. }
  96523. else { /* order == 11 */
  96524. for(i = 0; i < (int)data_len; i++) {
  96525. sum = 0;
  96526. sum += qlp_coeff[10] * data[i-11];
  96527. sum += qlp_coeff[9] * data[i-10];
  96528. sum += qlp_coeff[8] * data[i-9];
  96529. sum += qlp_coeff[7] * data[i-8];
  96530. sum += qlp_coeff[6] * data[i-7];
  96531. sum += qlp_coeff[5] * data[i-6];
  96532. sum += qlp_coeff[4] * data[i-5];
  96533. sum += qlp_coeff[3] * data[i-4];
  96534. sum += qlp_coeff[2] * data[i-3];
  96535. sum += qlp_coeff[1] * data[i-2];
  96536. sum += qlp_coeff[0] * data[i-1];
  96537. residual[i] = data[i] - (sum >> lp_quantization);
  96538. }
  96539. }
  96540. }
  96541. else {
  96542. if(order == 10) {
  96543. for(i = 0; i < (int)data_len; i++) {
  96544. sum = 0;
  96545. sum += qlp_coeff[9] * data[i-10];
  96546. sum += qlp_coeff[8] * data[i-9];
  96547. sum += qlp_coeff[7] * data[i-8];
  96548. sum += qlp_coeff[6] * data[i-7];
  96549. sum += qlp_coeff[5] * data[i-6];
  96550. sum += qlp_coeff[4] * data[i-5];
  96551. sum += qlp_coeff[3] * data[i-4];
  96552. sum += qlp_coeff[2] * data[i-3];
  96553. sum += qlp_coeff[1] * data[i-2];
  96554. sum += qlp_coeff[0] * data[i-1];
  96555. residual[i] = data[i] - (sum >> lp_quantization);
  96556. }
  96557. }
  96558. else { /* order == 9 */
  96559. for(i = 0; i < (int)data_len; i++) {
  96560. sum = 0;
  96561. sum += qlp_coeff[8] * data[i-9];
  96562. sum += qlp_coeff[7] * data[i-8];
  96563. sum += qlp_coeff[6] * data[i-7];
  96564. sum += qlp_coeff[5] * data[i-6];
  96565. sum += qlp_coeff[4] * data[i-5];
  96566. sum += qlp_coeff[3] * data[i-4];
  96567. sum += qlp_coeff[2] * data[i-3];
  96568. sum += qlp_coeff[1] * data[i-2];
  96569. sum += qlp_coeff[0] * data[i-1];
  96570. residual[i] = data[i] - (sum >> lp_quantization);
  96571. }
  96572. }
  96573. }
  96574. }
  96575. else if(order > 4) {
  96576. if(order > 6) {
  96577. if(order == 8) {
  96578. for(i = 0; i < (int)data_len; i++) {
  96579. sum = 0;
  96580. sum += qlp_coeff[7] * data[i-8];
  96581. sum += qlp_coeff[6] * data[i-7];
  96582. sum += qlp_coeff[5] * data[i-6];
  96583. sum += qlp_coeff[4] * data[i-5];
  96584. sum += qlp_coeff[3] * data[i-4];
  96585. sum += qlp_coeff[2] * data[i-3];
  96586. sum += qlp_coeff[1] * data[i-2];
  96587. sum += qlp_coeff[0] * data[i-1];
  96588. residual[i] = data[i] - (sum >> lp_quantization);
  96589. }
  96590. }
  96591. else { /* order == 7 */
  96592. for(i = 0; i < (int)data_len; i++) {
  96593. sum = 0;
  96594. sum += qlp_coeff[6] * data[i-7];
  96595. sum += qlp_coeff[5] * data[i-6];
  96596. sum += qlp_coeff[4] * data[i-5];
  96597. sum += qlp_coeff[3] * data[i-4];
  96598. sum += qlp_coeff[2] * data[i-3];
  96599. sum += qlp_coeff[1] * data[i-2];
  96600. sum += qlp_coeff[0] * data[i-1];
  96601. residual[i] = data[i] - (sum >> lp_quantization);
  96602. }
  96603. }
  96604. }
  96605. else {
  96606. if(order == 6) {
  96607. for(i = 0; i < (int)data_len; i++) {
  96608. sum = 0;
  96609. sum += qlp_coeff[5] * data[i-6];
  96610. sum += qlp_coeff[4] * data[i-5];
  96611. sum += qlp_coeff[3] * data[i-4];
  96612. sum += qlp_coeff[2] * data[i-3];
  96613. sum += qlp_coeff[1] * data[i-2];
  96614. sum += qlp_coeff[0] * data[i-1];
  96615. residual[i] = data[i] - (sum >> lp_quantization);
  96616. }
  96617. }
  96618. else { /* order == 5 */
  96619. for(i = 0; i < (int)data_len; i++) {
  96620. sum = 0;
  96621. sum += qlp_coeff[4] * data[i-5];
  96622. sum += qlp_coeff[3] * data[i-4];
  96623. sum += qlp_coeff[2] * data[i-3];
  96624. sum += qlp_coeff[1] * data[i-2];
  96625. sum += qlp_coeff[0] * data[i-1];
  96626. residual[i] = data[i] - (sum >> lp_quantization);
  96627. }
  96628. }
  96629. }
  96630. }
  96631. else {
  96632. if(order > 2) {
  96633. if(order == 4) {
  96634. for(i = 0; i < (int)data_len; i++) {
  96635. sum = 0;
  96636. sum += qlp_coeff[3] * data[i-4];
  96637. sum += qlp_coeff[2] * data[i-3];
  96638. sum += qlp_coeff[1] * data[i-2];
  96639. sum += qlp_coeff[0] * data[i-1];
  96640. residual[i] = data[i] - (sum >> lp_quantization);
  96641. }
  96642. }
  96643. else { /* order == 3 */
  96644. for(i = 0; i < (int)data_len; i++) {
  96645. sum = 0;
  96646. sum += qlp_coeff[2] * data[i-3];
  96647. sum += qlp_coeff[1] * data[i-2];
  96648. sum += qlp_coeff[0] * data[i-1];
  96649. residual[i] = data[i] - (sum >> lp_quantization);
  96650. }
  96651. }
  96652. }
  96653. else {
  96654. if(order == 2) {
  96655. for(i = 0; i < (int)data_len; i++) {
  96656. sum = 0;
  96657. sum += qlp_coeff[1] * data[i-2];
  96658. sum += qlp_coeff[0] * data[i-1];
  96659. residual[i] = data[i] - (sum >> lp_quantization);
  96660. }
  96661. }
  96662. else { /* order == 1 */
  96663. for(i = 0; i < (int)data_len; i++)
  96664. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  96665. }
  96666. }
  96667. }
  96668. }
  96669. else { /* order > 12 */
  96670. for(i = 0; i < (int)data_len; i++) {
  96671. sum = 0;
  96672. switch(order) {
  96673. case 32: sum += qlp_coeff[31] * data[i-32];
  96674. case 31: sum += qlp_coeff[30] * data[i-31];
  96675. case 30: sum += qlp_coeff[29] * data[i-30];
  96676. case 29: sum += qlp_coeff[28] * data[i-29];
  96677. case 28: sum += qlp_coeff[27] * data[i-28];
  96678. case 27: sum += qlp_coeff[26] * data[i-27];
  96679. case 26: sum += qlp_coeff[25] * data[i-26];
  96680. case 25: sum += qlp_coeff[24] * data[i-25];
  96681. case 24: sum += qlp_coeff[23] * data[i-24];
  96682. case 23: sum += qlp_coeff[22] * data[i-23];
  96683. case 22: sum += qlp_coeff[21] * data[i-22];
  96684. case 21: sum += qlp_coeff[20] * data[i-21];
  96685. case 20: sum += qlp_coeff[19] * data[i-20];
  96686. case 19: sum += qlp_coeff[18] * data[i-19];
  96687. case 18: sum += qlp_coeff[17] * data[i-18];
  96688. case 17: sum += qlp_coeff[16] * data[i-17];
  96689. case 16: sum += qlp_coeff[15] * data[i-16];
  96690. case 15: sum += qlp_coeff[14] * data[i-15];
  96691. case 14: sum += qlp_coeff[13] * data[i-14];
  96692. case 13: sum += qlp_coeff[12] * data[i-13];
  96693. sum += qlp_coeff[11] * data[i-12];
  96694. sum += qlp_coeff[10] * data[i-11];
  96695. sum += qlp_coeff[ 9] * data[i-10];
  96696. sum += qlp_coeff[ 8] * data[i- 9];
  96697. sum += qlp_coeff[ 7] * data[i- 8];
  96698. sum += qlp_coeff[ 6] * data[i- 7];
  96699. sum += qlp_coeff[ 5] * data[i- 6];
  96700. sum += qlp_coeff[ 4] * data[i- 5];
  96701. sum += qlp_coeff[ 3] * data[i- 4];
  96702. sum += qlp_coeff[ 2] * data[i- 3];
  96703. sum += qlp_coeff[ 1] * data[i- 2];
  96704. sum += qlp_coeff[ 0] * data[i- 1];
  96705. }
  96706. residual[i] = data[i] - (sum >> lp_quantization);
  96707. }
  96708. }
  96709. }
  96710. #endif
  96711. 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[])
  96712. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  96713. {
  96714. unsigned i, j;
  96715. FLAC__int64 sum;
  96716. const FLAC__int32 *history;
  96717. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  96718. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  96719. for(i=0;i<order;i++)
  96720. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  96721. fprintf(stderr,"\n");
  96722. #endif
  96723. FLAC__ASSERT(order > 0);
  96724. for(i = 0; i < data_len; i++) {
  96725. sum = 0;
  96726. history = data;
  96727. for(j = 0; j < order; j++)
  96728. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  96729. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  96730. #if defined _MSC_VER
  96731. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  96732. #else
  96733. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  96734. #endif
  96735. break;
  96736. }
  96737. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  96738. #if defined _MSC_VER
  96739. 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));
  96740. #else
  96741. 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)));
  96742. #endif
  96743. break;
  96744. }
  96745. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  96746. }
  96747. }
  96748. #else /* fully unrolled version for normal use */
  96749. {
  96750. int i;
  96751. FLAC__int64 sum;
  96752. FLAC__ASSERT(order > 0);
  96753. FLAC__ASSERT(order <= 32);
  96754. /*
  96755. * We do unique versions up to 12th order since that's the subset limit.
  96756. * Also they are roughly ordered to match frequency of occurrence to
  96757. * minimize branching.
  96758. */
  96759. if(order <= 12) {
  96760. if(order > 8) {
  96761. if(order > 10) {
  96762. if(order == 12) {
  96763. for(i = 0; i < (int)data_len; i++) {
  96764. sum = 0;
  96765. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  96766. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  96767. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  96768. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  96769. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  96770. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  96771. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  96772. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  96773. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  96774. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96775. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96776. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96777. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96778. }
  96779. }
  96780. else { /* order == 11 */
  96781. for(i = 0; i < (int)data_len; i++) {
  96782. sum = 0;
  96783. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  96784. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  96785. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  96786. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  96787. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  96788. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  96789. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  96790. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  96791. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96792. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96793. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96794. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96795. }
  96796. }
  96797. }
  96798. else {
  96799. if(order == 10) {
  96800. for(i = 0; i < (int)data_len; i++) {
  96801. sum = 0;
  96802. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  96803. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  96804. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  96805. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  96806. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  96807. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  96808. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  96809. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96810. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96811. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96812. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96813. }
  96814. }
  96815. else { /* order == 9 */
  96816. for(i = 0; i < (int)data_len; i++) {
  96817. sum = 0;
  96818. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  96819. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  96820. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  96821. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  96822. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  96823. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  96824. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96825. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96826. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96827. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96828. }
  96829. }
  96830. }
  96831. }
  96832. else if(order > 4) {
  96833. if(order > 6) {
  96834. if(order == 8) {
  96835. for(i = 0; i < (int)data_len; i++) {
  96836. sum = 0;
  96837. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  96838. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  96839. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  96840. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  96841. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  96842. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96843. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96844. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96845. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96846. }
  96847. }
  96848. else { /* order == 7 */
  96849. for(i = 0; i < (int)data_len; i++) {
  96850. sum = 0;
  96851. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  96852. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  96853. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  96854. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  96855. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96856. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96857. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96858. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96859. }
  96860. }
  96861. }
  96862. else {
  96863. if(order == 6) {
  96864. for(i = 0; i < (int)data_len; i++) {
  96865. sum = 0;
  96866. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  96867. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  96868. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  96869. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96870. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96871. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96872. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96873. }
  96874. }
  96875. else { /* order == 5 */
  96876. for(i = 0; i < (int)data_len; i++) {
  96877. sum = 0;
  96878. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  96879. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  96880. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96881. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96882. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96883. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96884. }
  96885. }
  96886. }
  96887. }
  96888. else {
  96889. if(order > 2) {
  96890. if(order == 4) {
  96891. for(i = 0; i < (int)data_len; i++) {
  96892. sum = 0;
  96893. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  96894. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96895. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96896. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96897. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96898. }
  96899. }
  96900. else { /* order == 3 */
  96901. for(i = 0; i < (int)data_len; i++) {
  96902. sum = 0;
  96903. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  96904. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96905. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96906. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96907. }
  96908. }
  96909. }
  96910. else {
  96911. if(order == 2) {
  96912. for(i = 0; i < (int)data_len; i++) {
  96913. sum = 0;
  96914. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  96915. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  96916. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96917. }
  96918. }
  96919. else { /* order == 1 */
  96920. for(i = 0; i < (int)data_len; i++)
  96921. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  96922. }
  96923. }
  96924. }
  96925. }
  96926. else { /* order > 12 */
  96927. for(i = 0; i < (int)data_len; i++) {
  96928. sum = 0;
  96929. switch(order) {
  96930. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  96931. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  96932. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  96933. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  96934. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  96935. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  96936. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  96937. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  96938. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  96939. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  96940. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  96941. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  96942. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  96943. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  96944. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  96945. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  96946. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  96947. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  96948. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  96949. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  96950. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  96951. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  96952. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  96953. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  96954. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  96955. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  96956. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  96957. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  96958. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  96959. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  96960. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  96961. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  96962. }
  96963. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  96964. }
  96965. }
  96966. }
  96967. #endif
  96968. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  96969. 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[])
  96970. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  96971. {
  96972. FLAC__int64 sumo;
  96973. unsigned i, j;
  96974. FLAC__int32 sum;
  96975. const FLAC__int32 *r = residual, *history;
  96976. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  96977. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  96978. for(i=0;i<order;i++)
  96979. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  96980. fprintf(stderr,"\n");
  96981. #endif
  96982. FLAC__ASSERT(order > 0);
  96983. for(i = 0; i < data_len; i++) {
  96984. sumo = 0;
  96985. sum = 0;
  96986. history = data;
  96987. for(j = 0; j < order; j++) {
  96988. sum += qlp_coeff[j] * (*(--history));
  96989. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  96990. #if defined _MSC_VER
  96991. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  96992. 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);
  96993. #else
  96994. if(sumo > 2147483647ll || sumo < -2147483648ll)
  96995. 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);
  96996. #endif
  96997. }
  96998. *(data++) = *(r++) + (sum >> lp_quantization);
  96999. }
  97000. /* Here's a slower but clearer version:
  97001. for(i = 0; i < data_len; i++) {
  97002. sum = 0;
  97003. for(j = 0; j < order; j++)
  97004. sum += qlp_coeff[j] * data[i-j-1];
  97005. data[i] = residual[i] + (sum >> lp_quantization);
  97006. }
  97007. */
  97008. }
  97009. #else /* fully unrolled version for normal use */
  97010. {
  97011. int i;
  97012. FLAC__int32 sum;
  97013. FLAC__ASSERT(order > 0);
  97014. FLAC__ASSERT(order <= 32);
  97015. /*
  97016. * We do unique versions up to 12th order since that's the subset limit.
  97017. * Also they are roughly ordered to match frequency of occurrence to
  97018. * minimize branching.
  97019. */
  97020. if(order <= 12) {
  97021. if(order > 8) {
  97022. if(order > 10) {
  97023. if(order == 12) {
  97024. for(i = 0; i < (int)data_len; i++) {
  97025. sum = 0;
  97026. sum += qlp_coeff[11] * data[i-12];
  97027. sum += qlp_coeff[10] * data[i-11];
  97028. sum += qlp_coeff[9] * data[i-10];
  97029. sum += qlp_coeff[8] * data[i-9];
  97030. sum += qlp_coeff[7] * data[i-8];
  97031. sum += qlp_coeff[6] * data[i-7];
  97032. sum += qlp_coeff[5] * data[i-6];
  97033. sum += qlp_coeff[4] * data[i-5];
  97034. sum += qlp_coeff[3] * data[i-4];
  97035. sum += qlp_coeff[2] * data[i-3];
  97036. sum += qlp_coeff[1] * data[i-2];
  97037. sum += qlp_coeff[0] * data[i-1];
  97038. data[i] = residual[i] + (sum >> lp_quantization);
  97039. }
  97040. }
  97041. else { /* order == 11 */
  97042. for(i = 0; i < (int)data_len; i++) {
  97043. sum = 0;
  97044. sum += qlp_coeff[10] * data[i-11];
  97045. sum += qlp_coeff[9] * data[i-10];
  97046. sum += qlp_coeff[8] * data[i-9];
  97047. sum += qlp_coeff[7] * data[i-8];
  97048. sum += qlp_coeff[6] * data[i-7];
  97049. sum += qlp_coeff[5] * data[i-6];
  97050. sum += qlp_coeff[4] * data[i-5];
  97051. sum += qlp_coeff[3] * data[i-4];
  97052. sum += qlp_coeff[2] * data[i-3];
  97053. sum += qlp_coeff[1] * data[i-2];
  97054. sum += qlp_coeff[0] * data[i-1];
  97055. data[i] = residual[i] + (sum >> lp_quantization);
  97056. }
  97057. }
  97058. }
  97059. else {
  97060. if(order == 10) {
  97061. for(i = 0; i < (int)data_len; i++) {
  97062. sum = 0;
  97063. sum += qlp_coeff[9] * data[i-10];
  97064. sum += qlp_coeff[8] * data[i-9];
  97065. sum += qlp_coeff[7] * data[i-8];
  97066. sum += qlp_coeff[6] * data[i-7];
  97067. sum += qlp_coeff[5] * data[i-6];
  97068. sum += qlp_coeff[4] * data[i-5];
  97069. sum += qlp_coeff[3] * data[i-4];
  97070. sum += qlp_coeff[2] * data[i-3];
  97071. sum += qlp_coeff[1] * data[i-2];
  97072. sum += qlp_coeff[0] * data[i-1];
  97073. data[i] = residual[i] + (sum >> lp_quantization);
  97074. }
  97075. }
  97076. else { /* order == 9 */
  97077. for(i = 0; i < (int)data_len; i++) {
  97078. sum = 0;
  97079. sum += qlp_coeff[8] * data[i-9];
  97080. sum += qlp_coeff[7] * data[i-8];
  97081. sum += qlp_coeff[6] * data[i-7];
  97082. sum += qlp_coeff[5] * data[i-6];
  97083. sum += qlp_coeff[4] * data[i-5];
  97084. sum += qlp_coeff[3] * data[i-4];
  97085. sum += qlp_coeff[2] * data[i-3];
  97086. sum += qlp_coeff[1] * data[i-2];
  97087. sum += qlp_coeff[0] * data[i-1];
  97088. data[i] = residual[i] + (sum >> lp_quantization);
  97089. }
  97090. }
  97091. }
  97092. }
  97093. else if(order > 4) {
  97094. if(order > 6) {
  97095. if(order == 8) {
  97096. for(i = 0; i < (int)data_len; i++) {
  97097. sum = 0;
  97098. sum += qlp_coeff[7] * data[i-8];
  97099. sum += qlp_coeff[6] * data[i-7];
  97100. sum += qlp_coeff[5] * data[i-6];
  97101. sum += qlp_coeff[4] * data[i-5];
  97102. sum += qlp_coeff[3] * data[i-4];
  97103. sum += qlp_coeff[2] * data[i-3];
  97104. sum += qlp_coeff[1] * data[i-2];
  97105. sum += qlp_coeff[0] * data[i-1];
  97106. data[i] = residual[i] + (sum >> lp_quantization);
  97107. }
  97108. }
  97109. else { /* order == 7 */
  97110. for(i = 0; i < (int)data_len; i++) {
  97111. sum = 0;
  97112. sum += qlp_coeff[6] * data[i-7];
  97113. sum += qlp_coeff[5] * data[i-6];
  97114. sum += qlp_coeff[4] * data[i-5];
  97115. sum += qlp_coeff[3] * data[i-4];
  97116. sum += qlp_coeff[2] * data[i-3];
  97117. sum += qlp_coeff[1] * data[i-2];
  97118. sum += qlp_coeff[0] * data[i-1];
  97119. data[i] = residual[i] + (sum >> lp_quantization);
  97120. }
  97121. }
  97122. }
  97123. else {
  97124. if(order == 6) {
  97125. for(i = 0; i < (int)data_len; i++) {
  97126. sum = 0;
  97127. sum += qlp_coeff[5] * data[i-6];
  97128. sum += qlp_coeff[4] * data[i-5];
  97129. sum += qlp_coeff[3] * data[i-4];
  97130. sum += qlp_coeff[2] * data[i-3];
  97131. sum += qlp_coeff[1] * data[i-2];
  97132. sum += qlp_coeff[0] * data[i-1];
  97133. data[i] = residual[i] + (sum >> lp_quantization);
  97134. }
  97135. }
  97136. else { /* order == 5 */
  97137. for(i = 0; i < (int)data_len; i++) {
  97138. sum = 0;
  97139. sum += qlp_coeff[4] * data[i-5];
  97140. sum += qlp_coeff[3] * data[i-4];
  97141. sum += qlp_coeff[2] * data[i-3];
  97142. sum += qlp_coeff[1] * data[i-2];
  97143. sum += qlp_coeff[0] * data[i-1];
  97144. data[i] = residual[i] + (sum >> lp_quantization);
  97145. }
  97146. }
  97147. }
  97148. }
  97149. else {
  97150. if(order > 2) {
  97151. if(order == 4) {
  97152. for(i = 0; i < (int)data_len; i++) {
  97153. sum = 0;
  97154. sum += qlp_coeff[3] * data[i-4];
  97155. sum += qlp_coeff[2] * data[i-3];
  97156. sum += qlp_coeff[1] * data[i-2];
  97157. sum += qlp_coeff[0] * data[i-1];
  97158. data[i] = residual[i] + (sum >> lp_quantization);
  97159. }
  97160. }
  97161. else { /* order == 3 */
  97162. for(i = 0; i < (int)data_len; i++) {
  97163. sum = 0;
  97164. sum += qlp_coeff[2] * data[i-3];
  97165. sum += qlp_coeff[1] * data[i-2];
  97166. sum += qlp_coeff[0] * data[i-1];
  97167. data[i] = residual[i] + (sum >> lp_quantization);
  97168. }
  97169. }
  97170. }
  97171. else {
  97172. if(order == 2) {
  97173. for(i = 0; i < (int)data_len; i++) {
  97174. sum = 0;
  97175. sum += qlp_coeff[1] * data[i-2];
  97176. sum += qlp_coeff[0] * data[i-1];
  97177. data[i] = residual[i] + (sum >> lp_quantization);
  97178. }
  97179. }
  97180. else { /* order == 1 */
  97181. for(i = 0; i < (int)data_len; i++)
  97182. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  97183. }
  97184. }
  97185. }
  97186. }
  97187. else { /* order > 12 */
  97188. for(i = 0; i < (int)data_len; i++) {
  97189. sum = 0;
  97190. switch(order) {
  97191. case 32: sum += qlp_coeff[31] * data[i-32];
  97192. case 31: sum += qlp_coeff[30] * data[i-31];
  97193. case 30: sum += qlp_coeff[29] * data[i-30];
  97194. case 29: sum += qlp_coeff[28] * data[i-29];
  97195. case 28: sum += qlp_coeff[27] * data[i-28];
  97196. case 27: sum += qlp_coeff[26] * data[i-27];
  97197. case 26: sum += qlp_coeff[25] * data[i-26];
  97198. case 25: sum += qlp_coeff[24] * data[i-25];
  97199. case 24: sum += qlp_coeff[23] * data[i-24];
  97200. case 23: sum += qlp_coeff[22] * data[i-23];
  97201. case 22: sum += qlp_coeff[21] * data[i-22];
  97202. case 21: sum += qlp_coeff[20] * data[i-21];
  97203. case 20: sum += qlp_coeff[19] * data[i-20];
  97204. case 19: sum += qlp_coeff[18] * data[i-19];
  97205. case 18: sum += qlp_coeff[17] * data[i-18];
  97206. case 17: sum += qlp_coeff[16] * data[i-17];
  97207. case 16: sum += qlp_coeff[15] * data[i-16];
  97208. case 15: sum += qlp_coeff[14] * data[i-15];
  97209. case 14: sum += qlp_coeff[13] * data[i-14];
  97210. case 13: sum += qlp_coeff[12] * data[i-13];
  97211. sum += qlp_coeff[11] * data[i-12];
  97212. sum += qlp_coeff[10] * data[i-11];
  97213. sum += qlp_coeff[ 9] * data[i-10];
  97214. sum += qlp_coeff[ 8] * data[i- 9];
  97215. sum += qlp_coeff[ 7] * data[i- 8];
  97216. sum += qlp_coeff[ 6] * data[i- 7];
  97217. sum += qlp_coeff[ 5] * data[i- 6];
  97218. sum += qlp_coeff[ 4] * data[i- 5];
  97219. sum += qlp_coeff[ 3] * data[i- 4];
  97220. sum += qlp_coeff[ 2] * data[i- 3];
  97221. sum += qlp_coeff[ 1] * data[i- 2];
  97222. sum += qlp_coeff[ 0] * data[i- 1];
  97223. }
  97224. data[i] = residual[i] + (sum >> lp_quantization);
  97225. }
  97226. }
  97227. }
  97228. #endif
  97229. 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[])
  97230. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97231. {
  97232. unsigned i, j;
  97233. FLAC__int64 sum;
  97234. const FLAC__int32 *r = residual, *history;
  97235. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97236. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97237. for(i=0;i<order;i++)
  97238. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97239. fprintf(stderr,"\n");
  97240. #endif
  97241. FLAC__ASSERT(order > 0);
  97242. for(i = 0; i < data_len; i++) {
  97243. sum = 0;
  97244. history = data;
  97245. for(j = 0; j < order; j++)
  97246. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  97247. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  97248. #ifdef _MSC_VER
  97249. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  97250. #else
  97251. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  97252. #endif
  97253. break;
  97254. }
  97255. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  97256. #ifdef _MSC_VER
  97257. 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));
  97258. #else
  97259. 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)));
  97260. #endif
  97261. break;
  97262. }
  97263. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  97264. }
  97265. }
  97266. #else /* fully unrolled version for normal use */
  97267. {
  97268. int i;
  97269. FLAC__int64 sum;
  97270. FLAC__ASSERT(order > 0);
  97271. FLAC__ASSERT(order <= 32);
  97272. /*
  97273. * We do unique versions up to 12th order since that's the subset limit.
  97274. * Also they are roughly ordered to match frequency of occurrence to
  97275. * minimize branching.
  97276. */
  97277. if(order <= 12) {
  97278. if(order > 8) {
  97279. if(order > 10) {
  97280. if(order == 12) {
  97281. for(i = 0; i < (int)data_len; i++) {
  97282. sum = 0;
  97283. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97284. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97285. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97286. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97287. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97288. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97289. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97290. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97291. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97292. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97293. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97294. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97295. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97296. }
  97297. }
  97298. else { /* order == 11 */
  97299. for(i = 0; i < (int)data_len; i++) {
  97300. sum = 0;
  97301. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97302. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97303. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97304. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97305. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97306. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97307. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97308. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97309. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97310. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97311. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97312. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97313. }
  97314. }
  97315. }
  97316. else {
  97317. if(order == 10) {
  97318. for(i = 0; i < (int)data_len; i++) {
  97319. sum = 0;
  97320. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97321. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97322. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97323. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97324. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97325. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97326. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97327. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97328. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97329. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97330. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97331. }
  97332. }
  97333. else { /* order == 9 */
  97334. for(i = 0; i < (int)data_len; i++) {
  97335. sum = 0;
  97336. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97337. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97338. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97339. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97340. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97341. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97342. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97343. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97344. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97345. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97346. }
  97347. }
  97348. }
  97349. }
  97350. else if(order > 4) {
  97351. if(order > 6) {
  97352. if(order == 8) {
  97353. for(i = 0; i < (int)data_len; i++) {
  97354. sum = 0;
  97355. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97356. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97357. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97358. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97359. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97360. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97361. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97362. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97363. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97364. }
  97365. }
  97366. else { /* order == 7 */
  97367. for(i = 0; i < (int)data_len; i++) {
  97368. sum = 0;
  97369. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97370. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97371. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97372. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97373. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97374. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97375. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97376. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97377. }
  97378. }
  97379. }
  97380. else {
  97381. if(order == 6) {
  97382. for(i = 0; i < (int)data_len; i++) {
  97383. sum = 0;
  97384. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97385. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97386. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97387. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97388. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97389. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97390. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97391. }
  97392. }
  97393. else { /* order == 5 */
  97394. for(i = 0; i < (int)data_len; i++) {
  97395. sum = 0;
  97396. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97397. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97398. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97399. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97400. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97401. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97402. }
  97403. }
  97404. }
  97405. }
  97406. else {
  97407. if(order > 2) {
  97408. if(order == 4) {
  97409. for(i = 0; i < (int)data_len; i++) {
  97410. sum = 0;
  97411. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97412. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97413. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97414. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97415. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97416. }
  97417. }
  97418. else { /* order == 3 */
  97419. for(i = 0; i < (int)data_len; i++) {
  97420. sum = 0;
  97421. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97422. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97423. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97424. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97425. }
  97426. }
  97427. }
  97428. else {
  97429. if(order == 2) {
  97430. for(i = 0; i < (int)data_len; i++) {
  97431. sum = 0;
  97432. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97433. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97434. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97435. }
  97436. }
  97437. else { /* order == 1 */
  97438. for(i = 0; i < (int)data_len; i++)
  97439. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  97440. }
  97441. }
  97442. }
  97443. }
  97444. else { /* order > 12 */
  97445. for(i = 0; i < (int)data_len; i++) {
  97446. sum = 0;
  97447. switch(order) {
  97448. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  97449. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  97450. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  97451. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  97452. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  97453. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  97454. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  97455. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  97456. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  97457. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  97458. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  97459. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  97460. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  97461. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  97462. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  97463. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  97464. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  97465. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  97466. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  97467. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  97468. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97469. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97470. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  97471. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  97472. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  97473. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  97474. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  97475. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  97476. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  97477. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  97478. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  97479. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  97480. }
  97481. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97482. }
  97483. }
  97484. }
  97485. #endif
  97486. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97487. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  97488. {
  97489. FLAC__double error_scale;
  97490. FLAC__ASSERT(total_samples > 0);
  97491. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  97492. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  97493. }
  97494. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  97495. {
  97496. if(lpc_error > 0.0) {
  97497. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  97498. if(bps >= 0.0)
  97499. return bps;
  97500. else
  97501. return 0.0;
  97502. }
  97503. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  97504. return 1e32;
  97505. }
  97506. else {
  97507. return 0.0;
  97508. }
  97509. }
  97510. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  97511. {
  97512. 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 */
  97513. FLAC__double bits, best_bits, error_scale;
  97514. FLAC__ASSERT(max_order > 0);
  97515. FLAC__ASSERT(total_samples > 0);
  97516. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  97517. best_index = 0;
  97518. best_bits = (unsigned)(-1);
  97519. for(index = 0, order = 1; index < max_order; index++, order++) {
  97520. 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);
  97521. if(bits < best_bits) {
  97522. best_index = index;
  97523. best_bits = bits;
  97524. }
  97525. }
  97526. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  97527. }
  97528. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97529. #endif
  97530. /*** End of inlined file: lpc_flac.c ***/
  97531. /*** Start of inlined file: md5.c ***/
  97532. /*** Start of inlined file: juce_FlacHeader.h ***/
  97533. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  97534. // tasks..
  97535. #define VERSION "1.2.1"
  97536. #define FLAC__NO_DLL 1
  97537. #if JUCE_MSVC
  97538. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  97539. #endif
  97540. #if JUCE_MAC
  97541. #define FLAC__SYS_DARWIN 1
  97542. #endif
  97543. /*** End of inlined file: juce_FlacHeader.h ***/
  97544. #if JUCE_USE_FLAC
  97545. #if HAVE_CONFIG_H
  97546. # include <config.h>
  97547. #endif
  97548. #include <stdlib.h> /* for malloc() */
  97549. #include <string.h> /* for memcpy() */
  97550. /*** Start of inlined file: md5.h ***/
  97551. #ifndef FLAC__PRIVATE__MD5_H
  97552. #define FLAC__PRIVATE__MD5_H
  97553. /*
  97554. * This is the header file for the MD5 message-digest algorithm.
  97555. * The algorithm is due to Ron Rivest. This code was
  97556. * written by Colin Plumb in 1993, no copyright is claimed.
  97557. * This code is in the public domain; do with it what you wish.
  97558. *
  97559. * Equivalent code is available from RSA Data Security, Inc.
  97560. * This code has been tested against that, and is equivalent,
  97561. * except that you don't need to include two pages of legalese
  97562. * with every copy.
  97563. *
  97564. * To compute the message digest of a chunk of bytes, declare an
  97565. * MD5Context structure, pass it to MD5Init, call MD5Update as
  97566. * needed on buffers full of bytes, and then call MD5Final, which
  97567. * will fill a supplied 16-byte array with the digest.
  97568. *
  97569. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  97570. * header definitions; now uses stuff from dpkg's config.h
  97571. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  97572. * Still in the public domain.
  97573. *
  97574. * Josh Coalson: made some changes to integrate with libFLAC.
  97575. * Still in the public domain, with no warranty.
  97576. */
  97577. typedef struct {
  97578. FLAC__uint32 in[16];
  97579. FLAC__uint32 buf[4];
  97580. FLAC__uint32 bytes[2];
  97581. FLAC__byte *internal_buf;
  97582. size_t capacity;
  97583. } FLAC__MD5Context;
  97584. void FLAC__MD5Init(FLAC__MD5Context *context);
  97585. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  97586. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  97587. #endif
  97588. /*** End of inlined file: md5.h ***/
  97589. #ifndef FLaC__INLINE
  97590. #define FLaC__INLINE
  97591. #endif
  97592. /*
  97593. * This code implements the MD5 message-digest algorithm.
  97594. * The algorithm is due to Ron Rivest. This code was
  97595. * written by Colin Plumb in 1993, no copyright is claimed.
  97596. * This code is in the public domain; do with it what you wish.
  97597. *
  97598. * Equivalent code is available from RSA Data Security, Inc.
  97599. * This code has been tested against that, and is equivalent,
  97600. * except that you don't need to include two pages of legalese
  97601. * with every copy.
  97602. *
  97603. * To compute the message digest of a chunk of bytes, declare an
  97604. * MD5Context structure, pass it to MD5Init, call MD5Update as
  97605. * needed on buffers full of bytes, and then call MD5Final, which
  97606. * will fill a supplied 16-byte array with the digest.
  97607. *
  97608. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  97609. * definitions; now uses stuff from dpkg's config.h.
  97610. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  97611. * Still in the public domain.
  97612. *
  97613. * Josh Coalson: made some changes to integrate with libFLAC.
  97614. * Still in the public domain.
  97615. */
  97616. /* The four core functions - F1 is optimized somewhat */
  97617. /* #define F1(x, y, z) (x & y | ~x & z) */
  97618. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  97619. #define F2(x, y, z) F1(z, x, y)
  97620. #define F3(x, y, z) (x ^ y ^ z)
  97621. #define F4(x, y, z) (y ^ (x | ~z))
  97622. /* This is the central step in the MD5 algorithm. */
  97623. #define MD5STEP(f,w,x,y,z,in,s) \
  97624. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  97625. /*
  97626. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  97627. * reflect the addition of 16 longwords of new data. MD5Update blocks
  97628. * the data and converts bytes into longwords for this routine.
  97629. */
  97630. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  97631. {
  97632. register FLAC__uint32 a, b, c, d;
  97633. a = buf[0];
  97634. b = buf[1];
  97635. c = buf[2];
  97636. d = buf[3];
  97637. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  97638. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  97639. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  97640. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  97641. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  97642. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  97643. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  97644. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  97645. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  97646. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  97647. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  97648. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  97649. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  97650. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  97651. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  97652. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  97653. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  97654. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  97655. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  97656. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  97657. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  97658. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  97659. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  97660. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  97661. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  97662. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  97663. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  97664. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  97665. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  97666. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  97667. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  97668. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  97669. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  97670. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  97671. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  97672. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  97673. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  97674. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  97675. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  97676. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  97677. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  97678. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  97679. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  97680. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  97681. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  97682. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  97683. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  97684. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  97685. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  97686. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  97687. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  97688. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  97689. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  97690. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  97691. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  97692. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  97693. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  97694. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  97695. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  97696. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  97697. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  97698. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  97699. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  97700. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  97701. buf[0] += a;
  97702. buf[1] += b;
  97703. buf[2] += c;
  97704. buf[3] += d;
  97705. }
  97706. #if WORDS_BIGENDIAN
  97707. //@@@@@@ OPT: use bswap/intrinsics
  97708. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  97709. {
  97710. register FLAC__uint32 x;
  97711. do {
  97712. x = *buf;
  97713. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  97714. *buf++ = (x >> 16) | (x << 16);
  97715. } while (--words);
  97716. }
  97717. static void byteSwapX16(FLAC__uint32 *buf)
  97718. {
  97719. register FLAC__uint32 x;
  97720. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97721. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97722. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97723. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97724. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97725. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97726. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97727. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97728. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97729. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97730. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97731. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97732. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97733. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97734. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  97735. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  97736. }
  97737. #else
  97738. #define byteSwap(buf, words)
  97739. #define byteSwapX16(buf)
  97740. #endif
  97741. /*
  97742. * Update context to reflect the concatenation of another buffer full
  97743. * of bytes.
  97744. */
  97745. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  97746. {
  97747. FLAC__uint32 t;
  97748. /* Update byte count */
  97749. t = ctx->bytes[0];
  97750. if ((ctx->bytes[0] = t + len) < t)
  97751. ctx->bytes[1]++; /* Carry from low to high */
  97752. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  97753. if (t > len) {
  97754. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  97755. return;
  97756. }
  97757. /* First chunk is an odd size */
  97758. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  97759. byteSwapX16(ctx->in);
  97760. FLAC__MD5Transform(ctx->buf, ctx->in);
  97761. buf += t;
  97762. len -= t;
  97763. /* Process data in 64-byte chunks */
  97764. while (len >= 64) {
  97765. memcpy(ctx->in, buf, 64);
  97766. byteSwapX16(ctx->in);
  97767. FLAC__MD5Transform(ctx->buf, ctx->in);
  97768. buf += 64;
  97769. len -= 64;
  97770. }
  97771. /* Handle any remaining bytes of data. */
  97772. memcpy(ctx->in, buf, len);
  97773. }
  97774. /*
  97775. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  97776. * initialization constants.
  97777. */
  97778. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  97779. {
  97780. ctx->buf[0] = 0x67452301;
  97781. ctx->buf[1] = 0xefcdab89;
  97782. ctx->buf[2] = 0x98badcfe;
  97783. ctx->buf[3] = 0x10325476;
  97784. ctx->bytes[0] = 0;
  97785. ctx->bytes[1] = 0;
  97786. ctx->internal_buf = 0;
  97787. ctx->capacity = 0;
  97788. }
  97789. /*
  97790. * Final wrapup - pad to 64-byte boundary with the bit pattern
  97791. * 1 0* (64-bit count of bits processed, MSB-first)
  97792. */
  97793. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  97794. {
  97795. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  97796. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  97797. /* Set the first char of padding to 0x80. There is always room. */
  97798. *p++ = 0x80;
  97799. /* Bytes of padding needed to make 56 bytes (-8..55) */
  97800. count = 56 - 1 - count;
  97801. if (count < 0) { /* Padding forces an extra block */
  97802. memset(p, 0, count + 8);
  97803. byteSwapX16(ctx->in);
  97804. FLAC__MD5Transform(ctx->buf, ctx->in);
  97805. p = (FLAC__byte *)ctx->in;
  97806. count = 56;
  97807. }
  97808. memset(p, 0, count);
  97809. byteSwap(ctx->in, 14);
  97810. /* Append length in bits and transform */
  97811. ctx->in[14] = ctx->bytes[0] << 3;
  97812. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  97813. FLAC__MD5Transform(ctx->buf, ctx->in);
  97814. byteSwap(ctx->buf, 4);
  97815. memcpy(digest, ctx->buf, 16);
  97816. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  97817. if(0 != ctx->internal_buf) {
  97818. free(ctx->internal_buf);
  97819. ctx->internal_buf = 0;
  97820. ctx->capacity = 0;
  97821. }
  97822. }
  97823. /*
  97824. * Convert the incoming audio signal to a byte stream
  97825. */
  97826. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  97827. {
  97828. unsigned channel, sample;
  97829. register FLAC__int32 a_word;
  97830. register FLAC__byte *buf_ = buf;
  97831. #if WORDS_BIGENDIAN
  97832. #else
  97833. if(channels == 2 && bytes_per_sample == 2) {
  97834. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  97835. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  97836. for(sample = 0; sample < samples; sample++, buf1_+=2)
  97837. *buf1_ = (FLAC__int16)signal[1][sample];
  97838. }
  97839. else if(channels == 1 && bytes_per_sample == 2) {
  97840. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  97841. for(sample = 0; sample < samples; sample++)
  97842. *buf1_++ = (FLAC__int16)signal[0][sample];
  97843. }
  97844. else
  97845. #endif
  97846. if(bytes_per_sample == 2) {
  97847. if(channels == 2) {
  97848. for(sample = 0; sample < samples; sample++) {
  97849. a_word = signal[0][sample];
  97850. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97851. *buf_++ = (FLAC__byte)a_word;
  97852. a_word = signal[1][sample];
  97853. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97854. *buf_++ = (FLAC__byte)a_word;
  97855. }
  97856. }
  97857. else if(channels == 1) {
  97858. for(sample = 0; sample < samples; sample++) {
  97859. a_word = signal[0][sample];
  97860. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97861. *buf_++ = (FLAC__byte)a_word;
  97862. }
  97863. }
  97864. else {
  97865. for(sample = 0; sample < samples; sample++) {
  97866. for(channel = 0; channel < channels; channel++) {
  97867. a_word = signal[channel][sample];
  97868. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97869. *buf_++ = (FLAC__byte)a_word;
  97870. }
  97871. }
  97872. }
  97873. }
  97874. else if(bytes_per_sample == 3) {
  97875. if(channels == 2) {
  97876. for(sample = 0; sample < samples; sample++) {
  97877. a_word = signal[0][sample];
  97878. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97879. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97880. *buf_++ = (FLAC__byte)a_word;
  97881. a_word = signal[1][sample];
  97882. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97883. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97884. *buf_++ = (FLAC__byte)a_word;
  97885. }
  97886. }
  97887. else if(channels == 1) {
  97888. for(sample = 0; sample < samples; sample++) {
  97889. a_word = signal[0][sample];
  97890. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97891. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97892. *buf_++ = (FLAC__byte)a_word;
  97893. }
  97894. }
  97895. else {
  97896. for(sample = 0; sample < samples; sample++) {
  97897. for(channel = 0; channel < channels; channel++) {
  97898. a_word = signal[channel][sample];
  97899. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97900. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97901. *buf_++ = (FLAC__byte)a_word;
  97902. }
  97903. }
  97904. }
  97905. }
  97906. else if(bytes_per_sample == 1) {
  97907. if(channels == 2) {
  97908. for(sample = 0; sample < samples; sample++) {
  97909. a_word = signal[0][sample];
  97910. *buf_++ = (FLAC__byte)a_word;
  97911. a_word = signal[1][sample];
  97912. *buf_++ = (FLAC__byte)a_word;
  97913. }
  97914. }
  97915. else if(channels == 1) {
  97916. for(sample = 0; sample < samples; sample++) {
  97917. a_word = signal[0][sample];
  97918. *buf_++ = (FLAC__byte)a_word;
  97919. }
  97920. }
  97921. else {
  97922. for(sample = 0; sample < samples; sample++) {
  97923. for(channel = 0; channel < channels; channel++) {
  97924. a_word = signal[channel][sample];
  97925. *buf_++ = (FLAC__byte)a_word;
  97926. }
  97927. }
  97928. }
  97929. }
  97930. else { /* bytes_per_sample == 4, maybe optimize more later */
  97931. for(sample = 0; sample < samples; sample++) {
  97932. for(channel = 0; channel < channels; channel++) {
  97933. a_word = signal[channel][sample];
  97934. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97935. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97936. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  97937. *buf_++ = (FLAC__byte)a_word;
  97938. }
  97939. }
  97940. }
  97941. }
  97942. /*
  97943. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  97944. */
  97945. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  97946. {
  97947. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  97948. /* overflow check */
  97949. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  97950. return false;
  97951. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  97952. return false;
  97953. if(ctx->capacity < bytes_needed) {
  97954. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  97955. if(0 == tmp) {
  97956. free(ctx->internal_buf);
  97957. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  97958. return false;
  97959. }
  97960. ctx->internal_buf = tmp;
  97961. ctx->capacity = bytes_needed;
  97962. }
  97963. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  97964. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  97965. return true;
  97966. }
  97967. #endif
  97968. /*** End of inlined file: md5.c ***/
  97969. /*** Start of inlined file: memory.c ***/
  97970. /*** Start of inlined file: juce_FlacHeader.h ***/
  97971. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  97972. // tasks..
  97973. #define VERSION "1.2.1"
  97974. #define FLAC__NO_DLL 1
  97975. #if JUCE_MSVC
  97976. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  97977. #endif
  97978. #if JUCE_MAC
  97979. #define FLAC__SYS_DARWIN 1
  97980. #endif
  97981. /*** End of inlined file: juce_FlacHeader.h ***/
  97982. #if JUCE_USE_FLAC
  97983. #if HAVE_CONFIG_H
  97984. # include <config.h>
  97985. #endif
  97986. /*** Start of inlined file: memory.h ***/
  97987. #ifndef FLAC__PRIVATE__MEMORY_H
  97988. #define FLAC__PRIVATE__MEMORY_H
  97989. #ifdef HAVE_CONFIG_H
  97990. #include <config.h>
  97991. #endif
  97992. #include <stdlib.h> /* for size_t */
  97993. /* Returns the unaligned address returned by malloc.
  97994. * Use free() on this address to deallocate.
  97995. */
  97996. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  97997. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  97998. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  97999. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  98000. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  98001. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98002. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  98003. #endif
  98004. #endif
  98005. /*** End of inlined file: memory.h ***/
  98006. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  98007. {
  98008. void *x;
  98009. FLAC__ASSERT(0 != aligned_address);
  98010. #ifdef FLAC__ALIGN_MALLOC_DATA
  98011. /* align on 32-byte (256-bit) boundary */
  98012. x = safe_malloc_add_2op_(bytes, /*+*/31);
  98013. #ifdef SIZEOF_VOIDP
  98014. #if SIZEOF_VOIDP == 4
  98015. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  98016. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  98017. #elif SIZEOF_VOIDP == 8
  98018. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  98019. #else
  98020. # error Unsupported sizeof(void*)
  98021. #endif
  98022. #else
  98023. /* there's got to be a better way to do this right for all archs */
  98024. if(sizeof(void*) == sizeof(unsigned))
  98025. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  98026. else if(sizeof(void*) == sizeof(FLAC__uint64))
  98027. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  98028. else
  98029. return 0;
  98030. #endif
  98031. #else
  98032. x = safe_malloc_(bytes);
  98033. *aligned_address = x;
  98034. #endif
  98035. return x;
  98036. }
  98037. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  98038. {
  98039. FLAC__int32 *pu; /* unaligned pointer */
  98040. union { /* union needed to comply with C99 pointer aliasing rules */
  98041. FLAC__int32 *pa; /* aligned pointer */
  98042. void *pv; /* aligned pointer alias */
  98043. } u;
  98044. FLAC__ASSERT(elements > 0);
  98045. FLAC__ASSERT(0 != unaligned_pointer);
  98046. FLAC__ASSERT(0 != aligned_pointer);
  98047. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98048. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  98049. if(0 == pu) {
  98050. return false;
  98051. }
  98052. else {
  98053. if(*unaligned_pointer != 0)
  98054. free(*unaligned_pointer);
  98055. *unaligned_pointer = pu;
  98056. *aligned_pointer = u.pa;
  98057. return true;
  98058. }
  98059. }
  98060. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  98061. {
  98062. FLAC__uint32 *pu; /* unaligned pointer */
  98063. union { /* union needed to comply with C99 pointer aliasing rules */
  98064. FLAC__uint32 *pa; /* aligned pointer */
  98065. void *pv; /* aligned pointer alias */
  98066. } u;
  98067. FLAC__ASSERT(elements > 0);
  98068. FLAC__ASSERT(0 != unaligned_pointer);
  98069. FLAC__ASSERT(0 != aligned_pointer);
  98070. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98071. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98072. if(0 == pu) {
  98073. return false;
  98074. }
  98075. else {
  98076. if(*unaligned_pointer != 0)
  98077. free(*unaligned_pointer);
  98078. *unaligned_pointer = pu;
  98079. *aligned_pointer = u.pa;
  98080. return true;
  98081. }
  98082. }
  98083. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  98084. {
  98085. FLAC__uint64 *pu; /* unaligned pointer */
  98086. union { /* union needed to comply with C99 pointer aliasing rules */
  98087. FLAC__uint64 *pa; /* aligned pointer */
  98088. void *pv; /* aligned pointer alias */
  98089. } u;
  98090. FLAC__ASSERT(elements > 0);
  98091. FLAC__ASSERT(0 != unaligned_pointer);
  98092. FLAC__ASSERT(0 != aligned_pointer);
  98093. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98094. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98095. if(0 == pu) {
  98096. return false;
  98097. }
  98098. else {
  98099. if(*unaligned_pointer != 0)
  98100. free(*unaligned_pointer);
  98101. *unaligned_pointer = pu;
  98102. *aligned_pointer = u.pa;
  98103. return true;
  98104. }
  98105. }
  98106. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  98107. {
  98108. unsigned *pu; /* unaligned pointer */
  98109. union { /* union needed to comply with C99 pointer aliasing rules */
  98110. unsigned *pa; /* aligned pointer */
  98111. void *pv; /* aligned pointer alias */
  98112. } u;
  98113. FLAC__ASSERT(elements > 0);
  98114. FLAC__ASSERT(0 != unaligned_pointer);
  98115. FLAC__ASSERT(0 != aligned_pointer);
  98116. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98117. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98118. if(0 == pu) {
  98119. return false;
  98120. }
  98121. else {
  98122. if(*unaligned_pointer != 0)
  98123. free(*unaligned_pointer);
  98124. *unaligned_pointer = pu;
  98125. *aligned_pointer = u.pa;
  98126. return true;
  98127. }
  98128. }
  98129. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98130. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  98131. {
  98132. FLAC__real *pu; /* unaligned pointer */
  98133. union { /* union needed to comply with C99 pointer aliasing rules */
  98134. FLAC__real *pa; /* aligned pointer */
  98135. void *pv; /* aligned pointer alias */
  98136. } u;
  98137. FLAC__ASSERT(elements > 0);
  98138. FLAC__ASSERT(0 != unaligned_pointer);
  98139. FLAC__ASSERT(0 != aligned_pointer);
  98140. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98141. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98142. if(0 == pu) {
  98143. return false;
  98144. }
  98145. else {
  98146. if(*unaligned_pointer != 0)
  98147. free(*unaligned_pointer);
  98148. *unaligned_pointer = pu;
  98149. *aligned_pointer = u.pa;
  98150. return true;
  98151. }
  98152. }
  98153. #endif
  98154. #endif
  98155. /*** End of inlined file: memory.c ***/
  98156. /*** Start of inlined file: stream_decoder.c ***/
  98157. /*** Start of inlined file: juce_FlacHeader.h ***/
  98158. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98159. // tasks..
  98160. #define VERSION "1.2.1"
  98161. #define FLAC__NO_DLL 1
  98162. #if JUCE_MSVC
  98163. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98164. #endif
  98165. #if JUCE_MAC
  98166. #define FLAC__SYS_DARWIN 1
  98167. #endif
  98168. /*** End of inlined file: juce_FlacHeader.h ***/
  98169. #if JUCE_USE_FLAC
  98170. #if HAVE_CONFIG_H
  98171. # include <config.h>
  98172. #endif
  98173. #if defined _MSC_VER || defined __MINGW32__
  98174. #include <io.h> /* for _setmode() */
  98175. #include <fcntl.h> /* for _O_BINARY */
  98176. #endif
  98177. #if defined __CYGWIN__ || defined __EMX__
  98178. #include <io.h> /* for setmode(), O_BINARY */
  98179. #include <fcntl.h> /* for _O_BINARY */
  98180. #endif
  98181. #include <stdio.h>
  98182. #include <stdlib.h> /* for malloc() */
  98183. #include <string.h> /* for memset/memcpy() */
  98184. #include <sys/stat.h> /* for stat() */
  98185. #include <sys/types.h> /* for off_t */
  98186. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  98187. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  98188. #define fseeko fseek
  98189. #define ftello ftell
  98190. #endif
  98191. #endif
  98192. /*** Start of inlined file: stream_decoder.h ***/
  98193. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  98194. #define FLAC__PROTECTED__STREAM_DECODER_H
  98195. #if FLAC__HAS_OGG
  98196. #include "include/private/ogg_decoder_aspect.h"
  98197. #endif
  98198. typedef struct FLAC__StreamDecoderProtected {
  98199. FLAC__StreamDecoderState state;
  98200. unsigned channels;
  98201. FLAC__ChannelAssignment channel_assignment;
  98202. unsigned bits_per_sample;
  98203. unsigned sample_rate; /* in Hz */
  98204. unsigned blocksize; /* in samples (per channel) */
  98205. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  98206. #if FLAC__HAS_OGG
  98207. FLAC__OggDecoderAspect ogg_decoder_aspect;
  98208. #endif
  98209. } FLAC__StreamDecoderProtected;
  98210. /*
  98211. * return the number of input bytes consumed
  98212. */
  98213. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  98214. #endif
  98215. /*** End of inlined file: stream_decoder.h ***/
  98216. #ifdef max
  98217. #undef max
  98218. #endif
  98219. #define max(a,b) ((a)>(b)?(a):(b))
  98220. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  98221. #ifdef _MSC_VER
  98222. #define FLAC__U64L(x) x
  98223. #else
  98224. #define FLAC__U64L(x) x##LLU
  98225. #endif
  98226. /* technically this should be in an "export.c" but this is convenient enough */
  98227. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  98228. #if FLAC__HAS_OGG
  98229. 1
  98230. #else
  98231. 0
  98232. #endif
  98233. ;
  98234. /***********************************************************************
  98235. *
  98236. * Private static data
  98237. *
  98238. ***********************************************************************/
  98239. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  98240. /***********************************************************************
  98241. *
  98242. * Private class method prototypes
  98243. *
  98244. ***********************************************************************/
  98245. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  98246. static FILE *get_binary_stdin_(void);
  98247. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  98248. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  98249. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  98250. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  98251. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  98252. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  98253. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  98254. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  98255. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  98256. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  98257. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  98258. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  98259. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  98260. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  98261. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  98262. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  98263. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  98264. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  98265. 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);
  98266. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  98267. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  98268. #if FLAC__HAS_OGG
  98269. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  98270. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  98271. #endif
  98272. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  98273. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  98274. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  98275. #if FLAC__HAS_OGG
  98276. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  98277. #endif
  98278. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  98279. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  98280. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  98281. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  98282. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  98283. /***********************************************************************
  98284. *
  98285. * Private class data
  98286. *
  98287. ***********************************************************************/
  98288. typedef struct FLAC__StreamDecoderPrivate {
  98289. #if FLAC__HAS_OGG
  98290. FLAC__bool is_ogg;
  98291. #endif
  98292. FLAC__StreamDecoderReadCallback read_callback;
  98293. FLAC__StreamDecoderSeekCallback seek_callback;
  98294. FLAC__StreamDecoderTellCallback tell_callback;
  98295. FLAC__StreamDecoderLengthCallback length_callback;
  98296. FLAC__StreamDecoderEofCallback eof_callback;
  98297. FLAC__StreamDecoderWriteCallback write_callback;
  98298. FLAC__StreamDecoderMetadataCallback metadata_callback;
  98299. FLAC__StreamDecoderErrorCallback error_callback;
  98300. /* generic 32-bit datapath: */
  98301. 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[]);
  98302. /* generic 64-bit datapath: */
  98303. 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[]);
  98304. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  98305. 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[]);
  98306. /* 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: */
  98307. 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[]);
  98308. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  98309. void *client_data;
  98310. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  98311. FLAC__BitReader *input;
  98312. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  98313. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  98314. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  98315. unsigned output_capacity, output_channels;
  98316. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  98317. FLAC__uint64 samples_decoded;
  98318. FLAC__bool has_stream_info, has_seek_table;
  98319. FLAC__StreamMetadata stream_info;
  98320. FLAC__StreamMetadata seek_table;
  98321. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  98322. FLAC__byte *metadata_filter_ids;
  98323. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  98324. FLAC__Frame frame;
  98325. FLAC__bool cached; /* true if there is a byte in lookahead */
  98326. FLAC__CPUInfo cpuinfo;
  98327. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  98328. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  98329. /* unaligned (original) pointers to allocated data */
  98330. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  98331. 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 */
  98332. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  98333. FLAC__bool is_seeking;
  98334. FLAC__MD5Context md5context;
  98335. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  98336. /* (the rest of these are only used for seeking) */
  98337. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  98338. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  98339. FLAC__uint64 target_sample;
  98340. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  98341. #if FLAC__HAS_OGG
  98342. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  98343. #endif
  98344. } FLAC__StreamDecoderPrivate;
  98345. /***********************************************************************
  98346. *
  98347. * Public static class data
  98348. *
  98349. ***********************************************************************/
  98350. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  98351. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  98352. "FLAC__STREAM_DECODER_READ_METADATA",
  98353. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  98354. "FLAC__STREAM_DECODER_READ_FRAME",
  98355. "FLAC__STREAM_DECODER_END_OF_STREAM",
  98356. "FLAC__STREAM_DECODER_OGG_ERROR",
  98357. "FLAC__STREAM_DECODER_SEEK_ERROR",
  98358. "FLAC__STREAM_DECODER_ABORTED",
  98359. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  98360. "FLAC__STREAM_DECODER_UNINITIALIZED"
  98361. };
  98362. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  98363. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  98364. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  98365. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  98366. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  98367. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  98368. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  98369. };
  98370. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  98371. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  98372. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  98373. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  98374. };
  98375. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  98376. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  98377. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  98378. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  98379. };
  98380. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  98381. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  98382. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  98383. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  98384. };
  98385. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  98386. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  98387. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  98388. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  98389. };
  98390. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  98391. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  98392. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  98393. };
  98394. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  98395. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  98396. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  98397. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  98398. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  98399. };
  98400. /***********************************************************************
  98401. *
  98402. * Class constructor/destructor
  98403. *
  98404. ***********************************************************************/
  98405. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  98406. {
  98407. FLAC__StreamDecoder *decoder;
  98408. unsigned i;
  98409. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  98410. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  98411. if(decoder == 0) {
  98412. return 0;
  98413. }
  98414. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  98415. if(decoder->protected_ == 0) {
  98416. free(decoder);
  98417. return 0;
  98418. }
  98419. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  98420. if(decoder->private_ == 0) {
  98421. free(decoder->protected_);
  98422. free(decoder);
  98423. return 0;
  98424. }
  98425. decoder->private_->input = FLAC__bitreader_new();
  98426. if(decoder->private_->input == 0) {
  98427. free(decoder->private_);
  98428. free(decoder->protected_);
  98429. free(decoder);
  98430. return 0;
  98431. }
  98432. decoder->private_->metadata_filter_ids_capacity = 16;
  98433. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  98434. FLAC__bitreader_delete(decoder->private_->input);
  98435. free(decoder->private_);
  98436. free(decoder->protected_);
  98437. free(decoder);
  98438. return 0;
  98439. }
  98440. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  98441. decoder->private_->output[i] = 0;
  98442. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  98443. }
  98444. decoder->private_->output_capacity = 0;
  98445. decoder->private_->output_channels = 0;
  98446. decoder->private_->has_seek_table = false;
  98447. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  98448. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  98449. decoder->private_->file = 0;
  98450. set_defaults_dec(decoder);
  98451. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  98452. return decoder;
  98453. }
  98454. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  98455. {
  98456. unsigned i;
  98457. FLAC__ASSERT(0 != decoder);
  98458. FLAC__ASSERT(0 != decoder->protected_);
  98459. FLAC__ASSERT(0 != decoder->private_);
  98460. FLAC__ASSERT(0 != decoder->private_->input);
  98461. (void)FLAC__stream_decoder_finish(decoder);
  98462. if(0 != decoder->private_->metadata_filter_ids)
  98463. free(decoder->private_->metadata_filter_ids);
  98464. FLAC__bitreader_delete(decoder->private_->input);
  98465. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  98466. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  98467. free(decoder->private_);
  98468. free(decoder->protected_);
  98469. free(decoder);
  98470. }
  98471. /***********************************************************************
  98472. *
  98473. * Public class methods
  98474. *
  98475. ***********************************************************************/
  98476. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  98477. FLAC__StreamDecoder *decoder,
  98478. FLAC__StreamDecoderReadCallback read_callback,
  98479. FLAC__StreamDecoderSeekCallback seek_callback,
  98480. FLAC__StreamDecoderTellCallback tell_callback,
  98481. FLAC__StreamDecoderLengthCallback length_callback,
  98482. FLAC__StreamDecoderEofCallback eof_callback,
  98483. FLAC__StreamDecoderWriteCallback write_callback,
  98484. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98485. FLAC__StreamDecoderErrorCallback error_callback,
  98486. void *client_data,
  98487. FLAC__bool is_ogg
  98488. )
  98489. {
  98490. FLAC__ASSERT(0 != decoder);
  98491. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98492. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  98493. #if !FLAC__HAS_OGG
  98494. if(is_ogg)
  98495. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  98496. #endif
  98497. if(
  98498. 0 == read_callback ||
  98499. 0 == write_callback ||
  98500. 0 == error_callback ||
  98501. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  98502. )
  98503. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  98504. #if FLAC__HAS_OGG
  98505. decoder->private_->is_ogg = is_ogg;
  98506. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  98507. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  98508. #endif
  98509. /*
  98510. * get the CPU info and set the function pointers
  98511. */
  98512. FLAC__cpu_info(&decoder->private_->cpuinfo);
  98513. /* first default to the non-asm routines */
  98514. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  98515. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  98516. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  98517. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  98518. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  98519. /* now override with asm where appropriate */
  98520. #ifndef FLAC__NO_ASM
  98521. if(decoder->private_->cpuinfo.use_asm) {
  98522. #ifdef FLAC__CPU_IA32
  98523. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  98524. #ifdef FLAC__HAS_NASM
  98525. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  98526. if(decoder->private_->cpuinfo.data.ia32.bswap)
  98527. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  98528. #endif
  98529. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  98530. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  98531. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  98532. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  98533. }
  98534. else {
  98535. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  98536. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  98537. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  98538. }
  98539. #endif
  98540. #elif defined FLAC__CPU_PPC
  98541. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  98542. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  98543. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  98544. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  98545. }
  98546. #endif
  98547. }
  98548. #endif
  98549. /* from here on, errors are fatal */
  98550. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  98551. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  98552. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  98553. }
  98554. decoder->private_->read_callback = read_callback;
  98555. decoder->private_->seek_callback = seek_callback;
  98556. decoder->private_->tell_callback = tell_callback;
  98557. decoder->private_->length_callback = length_callback;
  98558. decoder->private_->eof_callback = eof_callback;
  98559. decoder->private_->write_callback = write_callback;
  98560. decoder->private_->metadata_callback = metadata_callback;
  98561. decoder->private_->error_callback = error_callback;
  98562. decoder->private_->client_data = client_data;
  98563. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  98564. decoder->private_->samples_decoded = 0;
  98565. decoder->private_->has_stream_info = false;
  98566. decoder->private_->cached = false;
  98567. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  98568. decoder->private_->is_seeking = false;
  98569. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  98570. if(!FLAC__stream_decoder_reset(decoder)) {
  98571. /* above call sets the state for us */
  98572. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  98573. }
  98574. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  98575. }
  98576. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  98577. FLAC__StreamDecoder *decoder,
  98578. FLAC__StreamDecoderReadCallback read_callback,
  98579. FLAC__StreamDecoderSeekCallback seek_callback,
  98580. FLAC__StreamDecoderTellCallback tell_callback,
  98581. FLAC__StreamDecoderLengthCallback length_callback,
  98582. FLAC__StreamDecoderEofCallback eof_callback,
  98583. FLAC__StreamDecoderWriteCallback write_callback,
  98584. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98585. FLAC__StreamDecoderErrorCallback error_callback,
  98586. void *client_data
  98587. )
  98588. {
  98589. return init_stream_internal_dec(
  98590. decoder,
  98591. read_callback,
  98592. seek_callback,
  98593. tell_callback,
  98594. length_callback,
  98595. eof_callback,
  98596. write_callback,
  98597. metadata_callback,
  98598. error_callback,
  98599. client_data,
  98600. /*is_ogg=*/false
  98601. );
  98602. }
  98603. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  98604. FLAC__StreamDecoder *decoder,
  98605. FLAC__StreamDecoderReadCallback read_callback,
  98606. FLAC__StreamDecoderSeekCallback seek_callback,
  98607. FLAC__StreamDecoderTellCallback tell_callback,
  98608. FLAC__StreamDecoderLengthCallback length_callback,
  98609. FLAC__StreamDecoderEofCallback eof_callback,
  98610. FLAC__StreamDecoderWriteCallback write_callback,
  98611. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98612. FLAC__StreamDecoderErrorCallback error_callback,
  98613. void *client_data
  98614. )
  98615. {
  98616. return init_stream_internal_dec(
  98617. decoder,
  98618. read_callback,
  98619. seek_callback,
  98620. tell_callback,
  98621. length_callback,
  98622. eof_callback,
  98623. write_callback,
  98624. metadata_callback,
  98625. error_callback,
  98626. client_data,
  98627. /*is_ogg=*/true
  98628. );
  98629. }
  98630. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  98631. FLAC__StreamDecoder *decoder,
  98632. FILE *file,
  98633. FLAC__StreamDecoderWriteCallback write_callback,
  98634. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98635. FLAC__StreamDecoderErrorCallback error_callback,
  98636. void *client_data,
  98637. FLAC__bool is_ogg
  98638. )
  98639. {
  98640. FLAC__ASSERT(0 != decoder);
  98641. FLAC__ASSERT(0 != file);
  98642. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98643. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  98644. if(0 == write_callback || 0 == error_callback)
  98645. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  98646. /*
  98647. * To make sure that our file does not go unclosed after an error, we
  98648. * must assign the FILE pointer before any further error can occur in
  98649. * this routine.
  98650. */
  98651. if(file == stdin)
  98652. file = get_binary_stdin_(); /* just to be safe */
  98653. decoder->private_->file = file;
  98654. return init_stream_internal_dec(
  98655. decoder,
  98656. file_read_callback_dec,
  98657. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  98658. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  98659. decoder->private_->file == stdin? 0: file_length_callback_,
  98660. file_eof_callback_,
  98661. write_callback,
  98662. metadata_callback,
  98663. error_callback,
  98664. client_data,
  98665. is_ogg
  98666. );
  98667. }
  98668. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  98669. FLAC__StreamDecoder *decoder,
  98670. FILE *file,
  98671. FLAC__StreamDecoderWriteCallback write_callback,
  98672. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98673. FLAC__StreamDecoderErrorCallback error_callback,
  98674. void *client_data
  98675. )
  98676. {
  98677. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  98678. }
  98679. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  98680. FLAC__StreamDecoder *decoder,
  98681. FILE *file,
  98682. FLAC__StreamDecoderWriteCallback write_callback,
  98683. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98684. FLAC__StreamDecoderErrorCallback error_callback,
  98685. void *client_data
  98686. )
  98687. {
  98688. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  98689. }
  98690. static FLAC__StreamDecoderInitStatus init_file_internal_(
  98691. FLAC__StreamDecoder *decoder,
  98692. const char *filename,
  98693. FLAC__StreamDecoderWriteCallback write_callback,
  98694. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98695. FLAC__StreamDecoderErrorCallback error_callback,
  98696. void *client_data,
  98697. FLAC__bool is_ogg
  98698. )
  98699. {
  98700. FILE *file;
  98701. FLAC__ASSERT(0 != decoder);
  98702. /*
  98703. * To make sure that our file does not go unclosed after an error, we
  98704. * have to do the same entrance checks here that are later performed
  98705. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  98706. */
  98707. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98708. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  98709. if(0 == write_callback || 0 == error_callback)
  98710. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  98711. file = filename? fopen(filename, "rb") : stdin;
  98712. if(0 == file)
  98713. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  98714. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  98715. }
  98716. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  98717. FLAC__StreamDecoder *decoder,
  98718. const char *filename,
  98719. FLAC__StreamDecoderWriteCallback write_callback,
  98720. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98721. FLAC__StreamDecoderErrorCallback error_callback,
  98722. void *client_data
  98723. )
  98724. {
  98725. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  98726. }
  98727. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  98728. FLAC__StreamDecoder *decoder,
  98729. const char *filename,
  98730. FLAC__StreamDecoderWriteCallback write_callback,
  98731. FLAC__StreamDecoderMetadataCallback metadata_callback,
  98732. FLAC__StreamDecoderErrorCallback error_callback,
  98733. void *client_data
  98734. )
  98735. {
  98736. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  98737. }
  98738. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  98739. {
  98740. FLAC__bool md5_failed = false;
  98741. unsigned i;
  98742. FLAC__ASSERT(0 != decoder);
  98743. FLAC__ASSERT(0 != decoder->private_);
  98744. FLAC__ASSERT(0 != decoder->protected_);
  98745. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  98746. return true;
  98747. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  98748. * always call FLAC__MD5Final()
  98749. */
  98750. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  98751. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  98752. free(decoder->private_->seek_table.data.seek_table.points);
  98753. decoder->private_->seek_table.data.seek_table.points = 0;
  98754. decoder->private_->has_seek_table = false;
  98755. }
  98756. FLAC__bitreader_free(decoder->private_->input);
  98757. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  98758. /* WATCHOUT:
  98759. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  98760. * output arrays have a buffer of up to 3 zeroes in front
  98761. * (at negative indices) for alignment purposes; we use 4
  98762. * to keep the data well-aligned.
  98763. */
  98764. if(0 != decoder->private_->output[i]) {
  98765. free(decoder->private_->output[i]-4);
  98766. decoder->private_->output[i] = 0;
  98767. }
  98768. if(0 != decoder->private_->residual_unaligned[i]) {
  98769. free(decoder->private_->residual_unaligned[i]);
  98770. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  98771. }
  98772. }
  98773. decoder->private_->output_capacity = 0;
  98774. decoder->private_->output_channels = 0;
  98775. #if FLAC__HAS_OGG
  98776. if(decoder->private_->is_ogg)
  98777. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  98778. #endif
  98779. if(0 != decoder->private_->file) {
  98780. if(decoder->private_->file != stdin)
  98781. fclose(decoder->private_->file);
  98782. decoder->private_->file = 0;
  98783. }
  98784. if(decoder->private_->do_md5_checking) {
  98785. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  98786. md5_failed = true;
  98787. }
  98788. decoder->private_->is_seeking = false;
  98789. set_defaults_dec(decoder);
  98790. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  98791. return !md5_failed;
  98792. }
  98793. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  98794. {
  98795. FLAC__ASSERT(0 != decoder);
  98796. FLAC__ASSERT(0 != decoder->private_);
  98797. FLAC__ASSERT(0 != decoder->protected_);
  98798. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98799. return false;
  98800. #if FLAC__HAS_OGG
  98801. /* can't check decoder->private_->is_ogg since that's not set until init time */
  98802. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  98803. return true;
  98804. #else
  98805. (void)value;
  98806. return false;
  98807. #endif
  98808. }
  98809. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  98810. {
  98811. FLAC__ASSERT(0 != decoder);
  98812. FLAC__ASSERT(0 != decoder->protected_);
  98813. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98814. return false;
  98815. decoder->protected_->md5_checking = value;
  98816. return true;
  98817. }
  98818. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  98819. {
  98820. FLAC__ASSERT(0 != decoder);
  98821. FLAC__ASSERT(0 != decoder->private_);
  98822. FLAC__ASSERT(0 != decoder->protected_);
  98823. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  98824. /* double protection */
  98825. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  98826. return false;
  98827. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98828. return false;
  98829. decoder->private_->metadata_filter[type] = true;
  98830. if(type == FLAC__METADATA_TYPE_APPLICATION)
  98831. decoder->private_->metadata_filter_ids_count = 0;
  98832. return true;
  98833. }
  98834. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  98835. {
  98836. FLAC__ASSERT(0 != decoder);
  98837. FLAC__ASSERT(0 != decoder->private_);
  98838. FLAC__ASSERT(0 != decoder->protected_);
  98839. FLAC__ASSERT(0 != id);
  98840. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98841. return false;
  98842. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  98843. return true;
  98844. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  98845. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  98846. 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))) {
  98847. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  98848. return false;
  98849. }
  98850. decoder->private_->metadata_filter_ids_capacity *= 2;
  98851. }
  98852. 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));
  98853. decoder->private_->metadata_filter_ids_count++;
  98854. return true;
  98855. }
  98856. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  98857. {
  98858. unsigned i;
  98859. FLAC__ASSERT(0 != decoder);
  98860. FLAC__ASSERT(0 != decoder->private_);
  98861. FLAC__ASSERT(0 != decoder->protected_);
  98862. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98863. return false;
  98864. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  98865. decoder->private_->metadata_filter[i] = true;
  98866. decoder->private_->metadata_filter_ids_count = 0;
  98867. return true;
  98868. }
  98869. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  98870. {
  98871. FLAC__ASSERT(0 != decoder);
  98872. FLAC__ASSERT(0 != decoder->private_);
  98873. FLAC__ASSERT(0 != decoder->protected_);
  98874. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  98875. /* double protection */
  98876. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  98877. return false;
  98878. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98879. return false;
  98880. decoder->private_->metadata_filter[type] = false;
  98881. if(type == FLAC__METADATA_TYPE_APPLICATION)
  98882. decoder->private_->metadata_filter_ids_count = 0;
  98883. return true;
  98884. }
  98885. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  98886. {
  98887. FLAC__ASSERT(0 != decoder);
  98888. FLAC__ASSERT(0 != decoder->private_);
  98889. FLAC__ASSERT(0 != decoder->protected_);
  98890. FLAC__ASSERT(0 != id);
  98891. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98892. return false;
  98893. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  98894. return true;
  98895. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  98896. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  98897. 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))) {
  98898. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  98899. return false;
  98900. }
  98901. decoder->private_->metadata_filter_ids_capacity *= 2;
  98902. }
  98903. 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));
  98904. decoder->private_->metadata_filter_ids_count++;
  98905. return true;
  98906. }
  98907. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  98908. {
  98909. FLAC__ASSERT(0 != decoder);
  98910. FLAC__ASSERT(0 != decoder->private_);
  98911. FLAC__ASSERT(0 != decoder->protected_);
  98912. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  98913. return false;
  98914. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  98915. decoder->private_->metadata_filter_ids_count = 0;
  98916. return true;
  98917. }
  98918. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  98919. {
  98920. FLAC__ASSERT(0 != decoder);
  98921. FLAC__ASSERT(0 != decoder->protected_);
  98922. return decoder->protected_->state;
  98923. }
  98924. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  98925. {
  98926. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  98927. }
  98928. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  98929. {
  98930. FLAC__ASSERT(0 != decoder);
  98931. FLAC__ASSERT(0 != decoder->protected_);
  98932. return decoder->protected_->md5_checking;
  98933. }
  98934. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  98935. {
  98936. FLAC__ASSERT(0 != decoder);
  98937. FLAC__ASSERT(0 != decoder->protected_);
  98938. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  98939. }
  98940. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  98941. {
  98942. FLAC__ASSERT(0 != decoder);
  98943. FLAC__ASSERT(0 != decoder->protected_);
  98944. return decoder->protected_->channels;
  98945. }
  98946. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  98947. {
  98948. FLAC__ASSERT(0 != decoder);
  98949. FLAC__ASSERT(0 != decoder->protected_);
  98950. return decoder->protected_->channel_assignment;
  98951. }
  98952. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  98953. {
  98954. FLAC__ASSERT(0 != decoder);
  98955. FLAC__ASSERT(0 != decoder->protected_);
  98956. return decoder->protected_->bits_per_sample;
  98957. }
  98958. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  98959. {
  98960. FLAC__ASSERT(0 != decoder);
  98961. FLAC__ASSERT(0 != decoder->protected_);
  98962. return decoder->protected_->sample_rate;
  98963. }
  98964. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  98965. {
  98966. FLAC__ASSERT(0 != decoder);
  98967. FLAC__ASSERT(0 != decoder->protected_);
  98968. return decoder->protected_->blocksize;
  98969. }
  98970. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  98971. {
  98972. FLAC__ASSERT(0 != decoder);
  98973. FLAC__ASSERT(0 != decoder->private_);
  98974. FLAC__ASSERT(0 != position);
  98975. #if FLAC__HAS_OGG
  98976. if(decoder->private_->is_ogg)
  98977. return false;
  98978. #endif
  98979. if(0 == decoder->private_->tell_callback)
  98980. return false;
  98981. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  98982. return false;
  98983. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  98984. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  98985. return false;
  98986. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  98987. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  98988. return true;
  98989. }
  98990. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  98991. {
  98992. FLAC__ASSERT(0 != decoder);
  98993. FLAC__ASSERT(0 != decoder->private_);
  98994. FLAC__ASSERT(0 != decoder->protected_);
  98995. decoder->private_->samples_decoded = 0;
  98996. decoder->private_->do_md5_checking = false;
  98997. #if FLAC__HAS_OGG
  98998. if(decoder->private_->is_ogg)
  98999. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  99000. #endif
  99001. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  99002. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99003. return false;
  99004. }
  99005. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  99006. return true;
  99007. }
  99008. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  99009. {
  99010. FLAC__ASSERT(0 != decoder);
  99011. FLAC__ASSERT(0 != decoder->private_);
  99012. FLAC__ASSERT(0 != decoder->protected_);
  99013. if(!FLAC__stream_decoder_flush(decoder)) {
  99014. /* above call sets the state for us */
  99015. return false;
  99016. }
  99017. #if FLAC__HAS_OGG
  99018. /*@@@ could go in !internal_reset_hack block below */
  99019. if(decoder->private_->is_ogg)
  99020. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  99021. #endif
  99022. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  99023. * (internal_reset_hack) don't try to rewind since we are already at
  99024. * the beginning of the stream and don't want to fail if the input is
  99025. * not seekable.
  99026. */
  99027. if(!decoder->private_->internal_reset_hack) {
  99028. if(decoder->private_->file == stdin)
  99029. return false; /* can't rewind stdin, reset fails */
  99030. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  99031. return false; /* seekable and seek fails, reset fails */
  99032. }
  99033. else
  99034. decoder->private_->internal_reset_hack = false;
  99035. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  99036. decoder->private_->has_stream_info = false;
  99037. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99038. free(decoder->private_->seek_table.data.seek_table.points);
  99039. decoder->private_->seek_table.data.seek_table.points = 0;
  99040. decoder->private_->has_seek_table = false;
  99041. }
  99042. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  99043. /*
  99044. * This goes in reset() and not flush() because according to the spec, a
  99045. * fixed-blocksize stream must stay that way through the whole stream.
  99046. */
  99047. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  99048. /* We initialize the FLAC__MD5Context even though we may never use it. This
  99049. * is because md5 checking may be turned on to start and then turned off if
  99050. * a seek occurs. So we init the context here and finalize it in
  99051. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  99052. * properly.
  99053. */
  99054. FLAC__MD5Init(&decoder->private_->md5context);
  99055. decoder->private_->first_frame_offset = 0;
  99056. decoder->private_->unparseable_frame_count = 0;
  99057. return true;
  99058. }
  99059. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  99060. {
  99061. FLAC__bool got_a_frame;
  99062. FLAC__ASSERT(0 != decoder);
  99063. FLAC__ASSERT(0 != decoder->protected_);
  99064. while(1) {
  99065. switch(decoder->protected_->state) {
  99066. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99067. if(!find_metadata_(decoder))
  99068. return false; /* above function sets the status for us */
  99069. break;
  99070. case FLAC__STREAM_DECODER_READ_METADATA:
  99071. if(!read_metadata_(decoder))
  99072. return false; /* above function sets the status for us */
  99073. else
  99074. return true;
  99075. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99076. if(!frame_sync_(decoder))
  99077. return true; /* above function sets the status for us */
  99078. break;
  99079. case FLAC__STREAM_DECODER_READ_FRAME:
  99080. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  99081. return false; /* above function sets the status for us */
  99082. if(got_a_frame)
  99083. return true; /* above function sets the status for us */
  99084. break;
  99085. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99086. case FLAC__STREAM_DECODER_ABORTED:
  99087. return true;
  99088. default:
  99089. FLAC__ASSERT(0);
  99090. return false;
  99091. }
  99092. }
  99093. }
  99094. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  99095. {
  99096. FLAC__ASSERT(0 != decoder);
  99097. FLAC__ASSERT(0 != decoder->protected_);
  99098. while(1) {
  99099. switch(decoder->protected_->state) {
  99100. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99101. if(!find_metadata_(decoder))
  99102. return false; /* above function sets the status for us */
  99103. break;
  99104. case FLAC__STREAM_DECODER_READ_METADATA:
  99105. if(!read_metadata_(decoder))
  99106. return false; /* above function sets the status for us */
  99107. break;
  99108. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99109. case FLAC__STREAM_DECODER_READ_FRAME:
  99110. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99111. case FLAC__STREAM_DECODER_ABORTED:
  99112. return true;
  99113. default:
  99114. FLAC__ASSERT(0);
  99115. return false;
  99116. }
  99117. }
  99118. }
  99119. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  99120. {
  99121. FLAC__bool dummy;
  99122. FLAC__ASSERT(0 != decoder);
  99123. FLAC__ASSERT(0 != decoder->protected_);
  99124. while(1) {
  99125. switch(decoder->protected_->state) {
  99126. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99127. if(!find_metadata_(decoder))
  99128. return false; /* above function sets the status for us */
  99129. break;
  99130. case FLAC__STREAM_DECODER_READ_METADATA:
  99131. if(!read_metadata_(decoder))
  99132. return false; /* above function sets the status for us */
  99133. break;
  99134. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99135. if(!frame_sync_(decoder))
  99136. return true; /* above function sets the status for us */
  99137. break;
  99138. case FLAC__STREAM_DECODER_READ_FRAME:
  99139. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  99140. return false; /* above function sets the status for us */
  99141. break;
  99142. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99143. case FLAC__STREAM_DECODER_ABORTED:
  99144. return true;
  99145. default:
  99146. FLAC__ASSERT(0);
  99147. return false;
  99148. }
  99149. }
  99150. }
  99151. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  99152. {
  99153. FLAC__bool got_a_frame;
  99154. FLAC__ASSERT(0 != decoder);
  99155. FLAC__ASSERT(0 != decoder->protected_);
  99156. while(1) {
  99157. switch(decoder->protected_->state) {
  99158. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99159. case FLAC__STREAM_DECODER_READ_METADATA:
  99160. return false; /* above function sets the status for us */
  99161. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99162. if(!frame_sync_(decoder))
  99163. return true; /* above function sets the status for us */
  99164. break;
  99165. case FLAC__STREAM_DECODER_READ_FRAME:
  99166. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  99167. return false; /* above function sets the status for us */
  99168. if(got_a_frame)
  99169. return true; /* above function sets the status for us */
  99170. break;
  99171. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99172. case FLAC__STREAM_DECODER_ABORTED:
  99173. return true;
  99174. default:
  99175. FLAC__ASSERT(0);
  99176. return false;
  99177. }
  99178. }
  99179. }
  99180. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  99181. {
  99182. FLAC__uint64 length;
  99183. FLAC__ASSERT(0 != decoder);
  99184. if(
  99185. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  99186. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  99187. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  99188. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  99189. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  99190. )
  99191. return false;
  99192. if(0 == decoder->private_->seek_callback)
  99193. return false;
  99194. FLAC__ASSERT(decoder->private_->seek_callback);
  99195. FLAC__ASSERT(decoder->private_->tell_callback);
  99196. FLAC__ASSERT(decoder->private_->length_callback);
  99197. FLAC__ASSERT(decoder->private_->eof_callback);
  99198. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  99199. return false;
  99200. decoder->private_->is_seeking = true;
  99201. /* turn off md5 checking if a seek is attempted */
  99202. decoder->private_->do_md5_checking = false;
  99203. /* 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) */
  99204. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  99205. decoder->private_->is_seeking = false;
  99206. return false;
  99207. }
  99208. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  99209. if(
  99210. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  99211. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  99212. ) {
  99213. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  99214. /* above call sets the state for us */
  99215. decoder->private_->is_seeking = false;
  99216. return false;
  99217. }
  99218. /* check this again in case we didn't know total_samples the first time */
  99219. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  99220. decoder->private_->is_seeking = false;
  99221. return false;
  99222. }
  99223. }
  99224. {
  99225. const FLAC__bool ok =
  99226. #if FLAC__HAS_OGG
  99227. decoder->private_->is_ogg?
  99228. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  99229. #endif
  99230. seek_to_absolute_sample_(decoder, length, sample)
  99231. ;
  99232. decoder->private_->is_seeking = false;
  99233. return ok;
  99234. }
  99235. }
  99236. /***********************************************************************
  99237. *
  99238. * Protected class methods
  99239. *
  99240. ***********************************************************************/
  99241. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  99242. {
  99243. FLAC__ASSERT(0 != decoder);
  99244. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99245. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  99246. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  99247. }
  99248. /***********************************************************************
  99249. *
  99250. * Private class methods
  99251. *
  99252. ***********************************************************************/
  99253. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  99254. {
  99255. #if FLAC__HAS_OGG
  99256. decoder->private_->is_ogg = false;
  99257. #endif
  99258. decoder->private_->read_callback = 0;
  99259. decoder->private_->seek_callback = 0;
  99260. decoder->private_->tell_callback = 0;
  99261. decoder->private_->length_callback = 0;
  99262. decoder->private_->eof_callback = 0;
  99263. decoder->private_->write_callback = 0;
  99264. decoder->private_->metadata_callback = 0;
  99265. decoder->private_->error_callback = 0;
  99266. decoder->private_->client_data = 0;
  99267. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  99268. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  99269. decoder->private_->metadata_filter_ids_count = 0;
  99270. decoder->protected_->md5_checking = false;
  99271. #if FLAC__HAS_OGG
  99272. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  99273. #endif
  99274. }
  99275. /*
  99276. * This will forcibly set stdin to binary mode (for OSes that require it)
  99277. */
  99278. FILE *get_binary_stdin_(void)
  99279. {
  99280. /* if something breaks here it is probably due to the presence or
  99281. * absence of an underscore before the identifiers 'setmode',
  99282. * 'fileno', and/or 'O_BINARY'; check your system header files.
  99283. */
  99284. #if defined _MSC_VER || defined __MINGW32__
  99285. _setmode(_fileno(stdin), _O_BINARY);
  99286. #elif defined __CYGWIN__
  99287. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  99288. setmode(_fileno(stdin), _O_BINARY);
  99289. #elif defined __EMX__
  99290. setmode(fileno(stdin), O_BINARY);
  99291. #endif
  99292. return stdin;
  99293. }
  99294. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  99295. {
  99296. unsigned i;
  99297. FLAC__int32 *tmp;
  99298. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  99299. return true;
  99300. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  99301. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99302. if(0 != decoder->private_->output[i]) {
  99303. free(decoder->private_->output[i]-4);
  99304. decoder->private_->output[i] = 0;
  99305. }
  99306. if(0 != decoder->private_->residual_unaligned[i]) {
  99307. free(decoder->private_->residual_unaligned[i]);
  99308. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99309. }
  99310. }
  99311. for(i = 0; i < channels; i++) {
  99312. /* WATCHOUT:
  99313. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  99314. * output arrays have a buffer of up to 3 zeroes in front
  99315. * (at negative indices) for alignment purposes; we use 4
  99316. * to keep the data well-aligned.
  99317. */
  99318. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  99319. if(tmp == 0) {
  99320. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99321. return false;
  99322. }
  99323. memset(tmp, 0, sizeof(FLAC__int32)*4);
  99324. decoder->private_->output[i] = tmp + 4;
  99325. /* WATCHOUT:
  99326. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  99327. */
  99328. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  99329. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99330. return false;
  99331. }
  99332. }
  99333. decoder->private_->output_capacity = size;
  99334. decoder->private_->output_channels = channels;
  99335. return true;
  99336. }
  99337. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  99338. {
  99339. size_t i;
  99340. FLAC__ASSERT(0 != decoder);
  99341. FLAC__ASSERT(0 != decoder->private_);
  99342. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  99343. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  99344. return true;
  99345. return false;
  99346. }
  99347. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  99348. {
  99349. FLAC__uint32 x;
  99350. unsigned i, id_;
  99351. FLAC__bool first = true;
  99352. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99353. for(i = id_ = 0; i < 4; ) {
  99354. if(decoder->private_->cached) {
  99355. x = (FLAC__uint32)decoder->private_->lookahead;
  99356. decoder->private_->cached = false;
  99357. }
  99358. else {
  99359. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  99360. return false; /* read_callback_ sets the state for us */
  99361. }
  99362. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  99363. first = true;
  99364. i++;
  99365. id_ = 0;
  99366. continue;
  99367. }
  99368. if(x == ID3V2_TAG_[id_]) {
  99369. id_++;
  99370. i = 0;
  99371. if(id_ == 3) {
  99372. if(!skip_id3v2_tag_(decoder))
  99373. return false; /* skip_id3v2_tag_ sets the state for us */
  99374. }
  99375. continue;
  99376. }
  99377. id_ = 0;
  99378. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  99379. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  99380. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  99381. return false; /* read_callback_ sets the state for us */
  99382. /* 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 */
  99383. /* else we have to check if the second byte is the end of a sync code */
  99384. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  99385. decoder->private_->lookahead = (FLAC__byte)x;
  99386. decoder->private_->cached = true;
  99387. }
  99388. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  99389. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  99390. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  99391. return true;
  99392. }
  99393. }
  99394. i = 0;
  99395. if(first) {
  99396. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  99397. first = false;
  99398. }
  99399. }
  99400. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  99401. return true;
  99402. }
  99403. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  99404. {
  99405. FLAC__bool is_last;
  99406. FLAC__uint32 i, x, type, length;
  99407. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99408. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  99409. return false; /* read_callback_ sets the state for us */
  99410. is_last = x? true : false;
  99411. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  99412. return false; /* read_callback_ sets the state for us */
  99413. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  99414. return false; /* read_callback_ sets the state for us */
  99415. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  99416. if(!read_metadata_streaminfo_(decoder, is_last, length))
  99417. return false;
  99418. decoder->private_->has_stream_info = true;
  99419. 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))
  99420. decoder->private_->do_md5_checking = false;
  99421. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  99422. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  99423. }
  99424. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  99425. if(!read_metadata_seektable_(decoder, is_last, length))
  99426. return false;
  99427. decoder->private_->has_seek_table = true;
  99428. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  99429. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  99430. }
  99431. else {
  99432. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  99433. unsigned real_length = length;
  99434. FLAC__StreamMetadata block;
  99435. block.is_last = is_last;
  99436. block.type = (FLAC__MetadataType)type;
  99437. block.length = length;
  99438. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  99439. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  99440. return false; /* read_callback_ sets the state for us */
  99441. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  99442. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  99443. return false;
  99444. }
  99445. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  99446. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  99447. skip_it = !skip_it;
  99448. }
  99449. if(skip_it) {
  99450. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  99451. return false; /* read_callback_ sets the state for us */
  99452. }
  99453. else {
  99454. switch(type) {
  99455. case FLAC__METADATA_TYPE_PADDING:
  99456. /* skip the padding bytes */
  99457. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  99458. return false; /* read_callback_ sets the state for us */
  99459. break;
  99460. case FLAC__METADATA_TYPE_APPLICATION:
  99461. /* remember, we read the ID already */
  99462. if(real_length > 0) {
  99463. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  99464. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99465. return false;
  99466. }
  99467. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  99468. return false; /* read_callback_ sets the state for us */
  99469. }
  99470. else
  99471. block.data.application.data = 0;
  99472. break;
  99473. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  99474. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  99475. return false;
  99476. break;
  99477. case FLAC__METADATA_TYPE_CUESHEET:
  99478. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  99479. return false;
  99480. break;
  99481. case FLAC__METADATA_TYPE_PICTURE:
  99482. if(!read_metadata_picture_(decoder, &block.data.picture))
  99483. return false;
  99484. break;
  99485. case FLAC__METADATA_TYPE_STREAMINFO:
  99486. case FLAC__METADATA_TYPE_SEEKTABLE:
  99487. FLAC__ASSERT(0);
  99488. break;
  99489. default:
  99490. if(real_length > 0) {
  99491. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  99492. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99493. return false;
  99494. }
  99495. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  99496. return false; /* read_callback_ sets the state for us */
  99497. }
  99498. else
  99499. block.data.unknown.data = 0;
  99500. break;
  99501. }
  99502. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  99503. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  99504. /* now we have to free any malloc()ed data in the block */
  99505. switch(type) {
  99506. case FLAC__METADATA_TYPE_PADDING:
  99507. break;
  99508. case FLAC__METADATA_TYPE_APPLICATION:
  99509. if(0 != block.data.application.data)
  99510. free(block.data.application.data);
  99511. break;
  99512. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  99513. if(0 != block.data.vorbis_comment.vendor_string.entry)
  99514. free(block.data.vorbis_comment.vendor_string.entry);
  99515. if(block.data.vorbis_comment.num_comments > 0)
  99516. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  99517. if(0 != block.data.vorbis_comment.comments[i].entry)
  99518. free(block.data.vorbis_comment.comments[i].entry);
  99519. if(0 != block.data.vorbis_comment.comments)
  99520. free(block.data.vorbis_comment.comments);
  99521. break;
  99522. case FLAC__METADATA_TYPE_CUESHEET:
  99523. if(block.data.cue_sheet.num_tracks > 0)
  99524. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  99525. if(0 != block.data.cue_sheet.tracks[i].indices)
  99526. free(block.data.cue_sheet.tracks[i].indices);
  99527. if(0 != block.data.cue_sheet.tracks)
  99528. free(block.data.cue_sheet.tracks);
  99529. break;
  99530. case FLAC__METADATA_TYPE_PICTURE:
  99531. if(0 != block.data.picture.mime_type)
  99532. free(block.data.picture.mime_type);
  99533. if(0 != block.data.picture.description)
  99534. free(block.data.picture.description);
  99535. if(0 != block.data.picture.data)
  99536. free(block.data.picture.data);
  99537. break;
  99538. case FLAC__METADATA_TYPE_STREAMINFO:
  99539. case FLAC__METADATA_TYPE_SEEKTABLE:
  99540. FLAC__ASSERT(0);
  99541. default:
  99542. if(0 != block.data.unknown.data)
  99543. free(block.data.unknown.data);
  99544. break;
  99545. }
  99546. }
  99547. }
  99548. if(is_last) {
  99549. /* if this fails, it's OK, it's just a hint for the seek routine */
  99550. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  99551. decoder->private_->first_frame_offset = 0;
  99552. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  99553. }
  99554. return true;
  99555. }
  99556. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  99557. {
  99558. FLAC__uint32 x;
  99559. unsigned bits, used_bits = 0;
  99560. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99561. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  99562. decoder->private_->stream_info.is_last = is_last;
  99563. decoder->private_->stream_info.length = length;
  99564. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  99565. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  99566. return false; /* read_callback_ sets the state for us */
  99567. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  99568. used_bits += bits;
  99569. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  99570. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  99571. return false; /* read_callback_ sets the state for us */
  99572. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  99573. used_bits += bits;
  99574. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  99575. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  99576. return false; /* read_callback_ sets the state for us */
  99577. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  99578. used_bits += bits;
  99579. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  99580. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  99581. return false; /* read_callback_ sets the state for us */
  99582. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  99583. used_bits += bits;
  99584. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  99585. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  99586. return false; /* read_callback_ sets the state for us */
  99587. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  99588. used_bits += bits;
  99589. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  99590. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  99591. return false; /* read_callback_ sets the state for us */
  99592. decoder->private_->stream_info.data.stream_info.channels = x+1;
  99593. used_bits += bits;
  99594. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  99595. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  99596. return false; /* read_callback_ sets the state for us */
  99597. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  99598. used_bits += bits;
  99599. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  99600. 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))
  99601. return false; /* read_callback_ sets the state for us */
  99602. used_bits += bits;
  99603. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  99604. return false; /* read_callback_ sets the state for us */
  99605. used_bits += 16*8;
  99606. /* skip the rest of the block */
  99607. FLAC__ASSERT(used_bits % 8 == 0);
  99608. length -= (used_bits / 8);
  99609. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  99610. return false; /* read_callback_ sets the state for us */
  99611. return true;
  99612. }
  99613. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  99614. {
  99615. FLAC__uint32 i, x;
  99616. FLAC__uint64 xx;
  99617. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99618. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  99619. decoder->private_->seek_table.is_last = is_last;
  99620. decoder->private_->seek_table.length = length;
  99621. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  99622. /* use realloc since we may pass through here several times (e.g. after seeking) */
  99623. 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)))) {
  99624. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99625. return false;
  99626. }
  99627. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  99628. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  99629. return false; /* read_callback_ sets the state for us */
  99630. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  99631. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  99632. return false; /* read_callback_ sets the state for us */
  99633. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  99634. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  99635. return false; /* read_callback_ sets the state for us */
  99636. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  99637. }
  99638. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  99639. /* if there is a partial point left, skip over it */
  99640. if(length > 0) {
  99641. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  99642. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  99643. return false; /* read_callback_ sets the state for us */
  99644. }
  99645. return true;
  99646. }
  99647. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  99648. {
  99649. FLAC__uint32 i;
  99650. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99651. /* read vendor string */
  99652. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  99653. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  99654. return false; /* read_callback_ sets the state for us */
  99655. if(obj->vendor_string.length > 0) {
  99656. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  99657. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99658. return false;
  99659. }
  99660. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  99661. return false; /* read_callback_ sets the state for us */
  99662. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  99663. }
  99664. else
  99665. obj->vendor_string.entry = 0;
  99666. /* read num comments */
  99667. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  99668. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  99669. return false; /* read_callback_ sets the state for us */
  99670. /* read comments */
  99671. if(obj->num_comments > 0) {
  99672. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  99673. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99674. return false;
  99675. }
  99676. for(i = 0; i < obj->num_comments; i++) {
  99677. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  99678. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  99679. return false; /* read_callback_ sets the state for us */
  99680. if(obj->comments[i].length > 0) {
  99681. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  99682. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99683. return false;
  99684. }
  99685. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  99686. return false; /* read_callback_ sets the state for us */
  99687. obj->comments[i].entry[obj->comments[i].length] = '\0';
  99688. }
  99689. else
  99690. obj->comments[i].entry = 0;
  99691. }
  99692. }
  99693. else {
  99694. obj->comments = 0;
  99695. }
  99696. return true;
  99697. }
  99698. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  99699. {
  99700. FLAC__uint32 i, j, x;
  99701. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99702. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  99703. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  99704. 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))
  99705. return false; /* read_callback_ sets the state for us */
  99706. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  99707. return false; /* read_callback_ sets the state for us */
  99708. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  99709. return false; /* read_callback_ sets the state for us */
  99710. obj->is_cd = x? true : false;
  99711. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  99712. return false; /* read_callback_ sets the state for us */
  99713. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  99714. return false; /* read_callback_ sets the state for us */
  99715. obj->num_tracks = x;
  99716. if(obj->num_tracks > 0) {
  99717. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  99718. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99719. return false;
  99720. }
  99721. for(i = 0; i < obj->num_tracks; i++) {
  99722. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  99723. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  99724. return false; /* read_callback_ sets the state for us */
  99725. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  99726. return false; /* read_callback_ sets the state for us */
  99727. track->number = (FLAC__byte)x;
  99728. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  99729. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  99730. return false; /* read_callback_ sets the state for us */
  99731. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  99732. return false; /* read_callback_ sets the state for us */
  99733. track->type = x;
  99734. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  99735. return false; /* read_callback_ sets the state for us */
  99736. track->pre_emphasis = x;
  99737. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  99738. return false; /* read_callback_ sets the state for us */
  99739. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  99740. return false; /* read_callback_ sets the state for us */
  99741. track->num_indices = (FLAC__byte)x;
  99742. if(track->num_indices > 0) {
  99743. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  99744. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99745. return false;
  99746. }
  99747. for(j = 0; j < track->num_indices; j++) {
  99748. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  99749. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  99750. return false; /* read_callback_ sets the state for us */
  99751. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  99752. return false; /* read_callback_ sets the state for us */
  99753. index->number = (FLAC__byte)x;
  99754. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  99755. return false; /* read_callback_ sets the state for us */
  99756. }
  99757. }
  99758. }
  99759. }
  99760. return true;
  99761. }
  99762. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  99763. {
  99764. FLAC__uint32 x;
  99765. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99766. /* read type */
  99767. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  99768. return false; /* read_callback_ sets the state for us */
  99769. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  99770. /* read MIME type */
  99771. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  99772. return false; /* read_callback_ sets the state for us */
  99773. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  99774. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99775. return false;
  99776. }
  99777. if(x > 0) {
  99778. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  99779. return false; /* read_callback_ sets the state for us */
  99780. }
  99781. obj->mime_type[x] = '\0';
  99782. /* read description */
  99783. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  99784. return false; /* read_callback_ sets the state for us */
  99785. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  99786. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99787. return false;
  99788. }
  99789. if(x > 0) {
  99790. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  99791. return false; /* read_callback_ sets the state for us */
  99792. }
  99793. obj->description[x] = '\0';
  99794. /* read width */
  99795. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  99796. return false; /* read_callback_ sets the state for us */
  99797. /* read height */
  99798. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  99799. return false; /* read_callback_ sets the state for us */
  99800. /* read depth */
  99801. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  99802. return false; /* read_callback_ sets the state for us */
  99803. /* read colors */
  99804. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  99805. return false; /* read_callback_ sets the state for us */
  99806. /* read data */
  99807. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  99808. return false; /* read_callback_ sets the state for us */
  99809. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  99810. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99811. return false;
  99812. }
  99813. if(obj->data_length > 0) {
  99814. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  99815. return false; /* read_callback_ sets the state for us */
  99816. }
  99817. return true;
  99818. }
  99819. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  99820. {
  99821. FLAC__uint32 x;
  99822. unsigned i, skip;
  99823. /* skip the version and flags bytes */
  99824. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  99825. return false; /* read_callback_ sets the state for us */
  99826. /* get the size (in bytes) to skip */
  99827. skip = 0;
  99828. for(i = 0; i < 4; i++) {
  99829. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  99830. return false; /* read_callback_ sets the state for us */
  99831. skip <<= 7;
  99832. skip |= (x & 0x7f);
  99833. }
  99834. /* skip the rest of the tag */
  99835. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  99836. return false; /* read_callback_ sets the state for us */
  99837. return true;
  99838. }
  99839. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  99840. {
  99841. FLAC__uint32 x;
  99842. FLAC__bool first = true;
  99843. /* If we know the total number of samples in the stream, stop if we've read that many. */
  99844. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  99845. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  99846. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  99847. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  99848. return true;
  99849. }
  99850. }
  99851. /* make sure we're byte aligned */
  99852. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  99853. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  99854. return false; /* read_callback_ sets the state for us */
  99855. }
  99856. while(1) {
  99857. if(decoder->private_->cached) {
  99858. x = (FLAC__uint32)decoder->private_->lookahead;
  99859. decoder->private_->cached = false;
  99860. }
  99861. else {
  99862. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  99863. return false; /* read_callback_ sets the state for us */
  99864. }
  99865. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  99866. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  99867. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  99868. return false; /* read_callback_ sets the state for us */
  99869. /* 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 */
  99870. /* else we have to check if the second byte is the end of a sync code */
  99871. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  99872. decoder->private_->lookahead = (FLAC__byte)x;
  99873. decoder->private_->cached = true;
  99874. }
  99875. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  99876. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  99877. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  99878. return true;
  99879. }
  99880. }
  99881. if(first) {
  99882. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  99883. first = false;
  99884. }
  99885. }
  99886. return true;
  99887. }
  99888. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  99889. {
  99890. unsigned channel;
  99891. unsigned i;
  99892. FLAC__int32 mid, side;
  99893. unsigned frame_crc; /* the one we calculate from the input stream */
  99894. FLAC__uint32 x;
  99895. *got_a_frame = false;
  99896. /* init the CRC */
  99897. frame_crc = 0;
  99898. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  99899. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  99900. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  99901. if(!read_frame_header_(decoder))
  99902. return false;
  99903. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  99904. return true;
  99905. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  99906. return false;
  99907. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  99908. /*
  99909. * first figure the correct bits-per-sample of the subframe
  99910. */
  99911. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  99912. switch(decoder->private_->frame.header.channel_assignment) {
  99913. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  99914. /* no adjustment needed */
  99915. break;
  99916. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  99917. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  99918. if(channel == 1)
  99919. bps++;
  99920. break;
  99921. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  99922. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  99923. if(channel == 0)
  99924. bps++;
  99925. break;
  99926. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  99927. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  99928. if(channel == 1)
  99929. bps++;
  99930. break;
  99931. default:
  99932. FLAC__ASSERT(0);
  99933. }
  99934. /*
  99935. * now read it
  99936. */
  99937. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  99938. return false;
  99939. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  99940. return true;
  99941. }
  99942. if(!read_zero_padding_(decoder))
  99943. return false;
  99944. 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) */
  99945. return true;
  99946. /*
  99947. * Read the frame CRC-16 from the footer and check
  99948. */
  99949. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  99950. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  99951. return false; /* read_callback_ sets the state for us */
  99952. if(frame_crc == x) {
  99953. if(do_full_decode) {
  99954. /* Undo any special channel coding */
  99955. switch(decoder->private_->frame.header.channel_assignment) {
  99956. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  99957. /* do nothing */
  99958. break;
  99959. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  99960. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  99961. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  99962. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  99963. break;
  99964. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  99965. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  99966. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  99967. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  99968. break;
  99969. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  99970. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  99971. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  99972. #if 1
  99973. mid = decoder->private_->output[0][i];
  99974. side = decoder->private_->output[1][i];
  99975. mid <<= 1;
  99976. mid |= (side & 1); /* i.e. if 'side' is odd... */
  99977. decoder->private_->output[0][i] = (mid + side) >> 1;
  99978. decoder->private_->output[1][i] = (mid - side) >> 1;
  99979. #else
  99980. /* OPT: without 'side' temp variable */
  99981. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  99982. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  99983. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  99984. #endif
  99985. }
  99986. break;
  99987. default:
  99988. FLAC__ASSERT(0);
  99989. break;
  99990. }
  99991. }
  99992. }
  99993. else {
  99994. /* Bad frame, emit error and zero the output signal */
  99995. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  99996. if(do_full_decode) {
  99997. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  99998. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  99999. }
  100000. }
  100001. }
  100002. *got_a_frame = true;
  100003. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  100004. if(decoder->private_->next_fixed_block_size)
  100005. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  100006. /* put the latest values into the public section of the decoder instance */
  100007. decoder->protected_->channels = decoder->private_->frame.header.channels;
  100008. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  100009. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  100010. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  100011. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  100012. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  100013. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  100014. /* write it */
  100015. if(do_full_decode) {
  100016. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  100017. return false;
  100018. }
  100019. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100020. return true;
  100021. }
  100022. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  100023. {
  100024. FLAC__uint32 x;
  100025. FLAC__uint64 xx;
  100026. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  100027. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  100028. unsigned raw_header_len;
  100029. FLAC__bool is_unparseable = false;
  100030. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100031. /* init the raw header with the saved bits from synchronization */
  100032. raw_header[0] = decoder->private_->header_warmup[0];
  100033. raw_header[1] = decoder->private_->header_warmup[1];
  100034. raw_header_len = 2;
  100035. /* check to make sure that reserved bit is 0 */
  100036. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  100037. is_unparseable = true;
  100038. /*
  100039. * Note that along the way as we read the header, we look for a sync
  100040. * code inside. If we find one it would indicate that our original
  100041. * sync was bad since there cannot be a sync code in a valid header.
  100042. *
  100043. * Three kinds of things can go wrong when reading the frame header:
  100044. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  100045. * If we don't find a sync code, it can end up looking like we read
  100046. * a valid but unparseable header, until getting to the frame header
  100047. * CRC. Even then we could get a false positive on the CRC.
  100048. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  100049. * future encoder).
  100050. * 3) We may be on a damaged frame which appears valid but unparseable.
  100051. *
  100052. * For all these reasons, we try and read a complete frame header as
  100053. * long as it seems valid, even if unparseable, up until the frame
  100054. * header CRC.
  100055. */
  100056. /*
  100057. * read in the raw header as bytes so we can CRC it, and parse it on the way
  100058. */
  100059. for(i = 0; i < 2; i++) {
  100060. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100061. return false; /* read_callback_ sets the state for us */
  100062. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100063. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  100064. decoder->private_->lookahead = (FLAC__byte)x;
  100065. decoder->private_->cached = true;
  100066. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100067. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100068. return true;
  100069. }
  100070. raw_header[raw_header_len++] = (FLAC__byte)x;
  100071. }
  100072. switch(x = raw_header[2] >> 4) {
  100073. case 0:
  100074. is_unparseable = true;
  100075. break;
  100076. case 1:
  100077. decoder->private_->frame.header.blocksize = 192;
  100078. break;
  100079. case 2:
  100080. case 3:
  100081. case 4:
  100082. case 5:
  100083. decoder->private_->frame.header.blocksize = 576 << (x-2);
  100084. break;
  100085. case 6:
  100086. case 7:
  100087. blocksize_hint = x;
  100088. break;
  100089. case 8:
  100090. case 9:
  100091. case 10:
  100092. case 11:
  100093. case 12:
  100094. case 13:
  100095. case 14:
  100096. case 15:
  100097. decoder->private_->frame.header.blocksize = 256 << (x-8);
  100098. break;
  100099. default:
  100100. FLAC__ASSERT(0);
  100101. break;
  100102. }
  100103. switch(x = raw_header[2] & 0x0f) {
  100104. case 0:
  100105. if(decoder->private_->has_stream_info)
  100106. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  100107. else
  100108. is_unparseable = true;
  100109. break;
  100110. case 1:
  100111. decoder->private_->frame.header.sample_rate = 88200;
  100112. break;
  100113. case 2:
  100114. decoder->private_->frame.header.sample_rate = 176400;
  100115. break;
  100116. case 3:
  100117. decoder->private_->frame.header.sample_rate = 192000;
  100118. break;
  100119. case 4:
  100120. decoder->private_->frame.header.sample_rate = 8000;
  100121. break;
  100122. case 5:
  100123. decoder->private_->frame.header.sample_rate = 16000;
  100124. break;
  100125. case 6:
  100126. decoder->private_->frame.header.sample_rate = 22050;
  100127. break;
  100128. case 7:
  100129. decoder->private_->frame.header.sample_rate = 24000;
  100130. break;
  100131. case 8:
  100132. decoder->private_->frame.header.sample_rate = 32000;
  100133. break;
  100134. case 9:
  100135. decoder->private_->frame.header.sample_rate = 44100;
  100136. break;
  100137. case 10:
  100138. decoder->private_->frame.header.sample_rate = 48000;
  100139. break;
  100140. case 11:
  100141. decoder->private_->frame.header.sample_rate = 96000;
  100142. break;
  100143. case 12:
  100144. case 13:
  100145. case 14:
  100146. sample_rate_hint = x;
  100147. break;
  100148. case 15:
  100149. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100150. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100151. return true;
  100152. default:
  100153. FLAC__ASSERT(0);
  100154. }
  100155. x = (unsigned)(raw_header[3] >> 4);
  100156. if(x & 8) {
  100157. decoder->private_->frame.header.channels = 2;
  100158. switch(x & 7) {
  100159. case 0:
  100160. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  100161. break;
  100162. case 1:
  100163. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  100164. break;
  100165. case 2:
  100166. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  100167. break;
  100168. default:
  100169. is_unparseable = true;
  100170. break;
  100171. }
  100172. }
  100173. else {
  100174. decoder->private_->frame.header.channels = (unsigned)x + 1;
  100175. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  100176. }
  100177. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  100178. case 0:
  100179. if(decoder->private_->has_stream_info)
  100180. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  100181. else
  100182. is_unparseable = true;
  100183. break;
  100184. case 1:
  100185. decoder->private_->frame.header.bits_per_sample = 8;
  100186. break;
  100187. case 2:
  100188. decoder->private_->frame.header.bits_per_sample = 12;
  100189. break;
  100190. case 4:
  100191. decoder->private_->frame.header.bits_per_sample = 16;
  100192. break;
  100193. case 5:
  100194. decoder->private_->frame.header.bits_per_sample = 20;
  100195. break;
  100196. case 6:
  100197. decoder->private_->frame.header.bits_per_sample = 24;
  100198. break;
  100199. case 3:
  100200. case 7:
  100201. is_unparseable = true;
  100202. break;
  100203. default:
  100204. FLAC__ASSERT(0);
  100205. break;
  100206. }
  100207. /* check to make sure that reserved bit is 0 */
  100208. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  100209. is_unparseable = true;
  100210. /* read the frame's starting sample number (or frame number as the case may be) */
  100211. if(
  100212. raw_header[1] & 0x01 ||
  100213. /*@@@ 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 */
  100214. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  100215. ) { /* variable blocksize */
  100216. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  100217. return false; /* read_callback_ sets the state for us */
  100218. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  100219. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  100220. decoder->private_->cached = true;
  100221. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100222. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100223. return true;
  100224. }
  100225. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  100226. decoder->private_->frame.header.number.sample_number = xx;
  100227. }
  100228. else { /* fixed blocksize */
  100229. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  100230. return false; /* read_callback_ sets the state for us */
  100231. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  100232. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  100233. decoder->private_->cached = true;
  100234. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100235. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100236. return true;
  100237. }
  100238. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  100239. decoder->private_->frame.header.number.frame_number = x;
  100240. }
  100241. if(blocksize_hint) {
  100242. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100243. return false; /* read_callback_ sets the state for us */
  100244. raw_header[raw_header_len++] = (FLAC__byte)x;
  100245. if(blocksize_hint == 7) {
  100246. FLAC__uint32 _x;
  100247. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  100248. return false; /* read_callback_ sets the state for us */
  100249. raw_header[raw_header_len++] = (FLAC__byte)_x;
  100250. x = (x << 8) | _x;
  100251. }
  100252. decoder->private_->frame.header.blocksize = x+1;
  100253. }
  100254. if(sample_rate_hint) {
  100255. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100256. return false; /* read_callback_ sets the state for us */
  100257. raw_header[raw_header_len++] = (FLAC__byte)x;
  100258. if(sample_rate_hint != 12) {
  100259. FLAC__uint32 _x;
  100260. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  100261. return false; /* read_callback_ sets the state for us */
  100262. raw_header[raw_header_len++] = (FLAC__byte)_x;
  100263. x = (x << 8) | _x;
  100264. }
  100265. if(sample_rate_hint == 12)
  100266. decoder->private_->frame.header.sample_rate = x*1000;
  100267. else if(sample_rate_hint == 13)
  100268. decoder->private_->frame.header.sample_rate = x;
  100269. else
  100270. decoder->private_->frame.header.sample_rate = x*10;
  100271. }
  100272. /* read the CRC-8 byte */
  100273. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100274. return false; /* read_callback_ sets the state for us */
  100275. crc8 = (FLAC__byte)x;
  100276. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  100277. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100278. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100279. return true;
  100280. }
  100281. /* calculate the sample number from the frame number if needed */
  100282. decoder->private_->next_fixed_block_size = 0;
  100283. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  100284. x = decoder->private_->frame.header.number.frame_number;
  100285. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  100286. if(decoder->private_->fixed_block_size)
  100287. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  100288. else if(decoder->private_->has_stream_info) {
  100289. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  100290. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  100291. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  100292. }
  100293. else
  100294. is_unparseable = true;
  100295. }
  100296. else if(x == 0) {
  100297. decoder->private_->frame.header.number.sample_number = 0;
  100298. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  100299. }
  100300. else {
  100301. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  100302. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  100303. }
  100304. }
  100305. if(is_unparseable) {
  100306. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100307. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100308. return true;
  100309. }
  100310. return true;
  100311. }
  100312. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  100313. {
  100314. FLAC__uint32 x;
  100315. FLAC__bool wasted_bits;
  100316. unsigned i;
  100317. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  100318. return false; /* read_callback_ sets the state for us */
  100319. wasted_bits = (x & 1);
  100320. x &= 0xfe;
  100321. if(wasted_bits) {
  100322. unsigned u;
  100323. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  100324. return false; /* read_callback_ sets the state for us */
  100325. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  100326. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  100327. }
  100328. else
  100329. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  100330. /*
  100331. * Lots of magic numbers here
  100332. */
  100333. if(x & 0x80) {
  100334. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100335. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100336. return true;
  100337. }
  100338. else if(x == 0) {
  100339. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  100340. return false;
  100341. }
  100342. else if(x == 2) {
  100343. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  100344. return false;
  100345. }
  100346. else if(x < 16) {
  100347. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100348. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100349. return true;
  100350. }
  100351. else if(x <= 24) {
  100352. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  100353. return false;
  100354. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  100355. return true;
  100356. }
  100357. else if(x < 64) {
  100358. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100359. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100360. return true;
  100361. }
  100362. else {
  100363. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  100364. return false;
  100365. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  100366. return true;
  100367. }
  100368. if(wasted_bits && do_full_decode) {
  100369. x = decoder->private_->frame.subframes[channel].wasted_bits;
  100370. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100371. decoder->private_->output[channel][i] <<= x;
  100372. }
  100373. return true;
  100374. }
  100375. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  100376. {
  100377. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  100378. FLAC__int32 x;
  100379. unsigned i;
  100380. FLAC__int32 *output = decoder->private_->output[channel];
  100381. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  100382. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  100383. return false; /* read_callback_ sets the state for us */
  100384. subframe->value = x;
  100385. /* decode the subframe */
  100386. if(do_full_decode) {
  100387. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100388. output[i] = x;
  100389. }
  100390. return true;
  100391. }
  100392. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  100393. {
  100394. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  100395. FLAC__int32 i32;
  100396. FLAC__uint32 u32;
  100397. unsigned u;
  100398. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  100399. subframe->residual = decoder->private_->residual[channel];
  100400. subframe->order = order;
  100401. /* read warm-up samples */
  100402. for(u = 0; u < order; u++) {
  100403. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  100404. return false; /* read_callback_ sets the state for us */
  100405. subframe->warmup[u] = i32;
  100406. }
  100407. /* read entropy coding method info */
  100408. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  100409. return false; /* read_callback_ sets the state for us */
  100410. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  100411. switch(subframe->entropy_coding_method.type) {
  100412. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  100413. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  100414. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  100415. return false; /* read_callback_ sets the state for us */
  100416. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  100417. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  100418. break;
  100419. default:
  100420. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100421. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100422. return true;
  100423. }
  100424. /* read residual */
  100425. switch(subframe->entropy_coding_method.type) {
  100426. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  100427. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  100428. 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))
  100429. return false;
  100430. break;
  100431. default:
  100432. FLAC__ASSERT(0);
  100433. }
  100434. /* decode the subframe */
  100435. if(do_full_decode) {
  100436. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  100437. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  100438. }
  100439. return true;
  100440. }
  100441. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  100442. {
  100443. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  100444. FLAC__int32 i32;
  100445. FLAC__uint32 u32;
  100446. unsigned u;
  100447. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  100448. subframe->residual = decoder->private_->residual[channel];
  100449. subframe->order = order;
  100450. /* read warm-up samples */
  100451. for(u = 0; u < order; u++) {
  100452. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  100453. return false; /* read_callback_ sets the state for us */
  100454. subframe->warmup[u] = i32;
  100455. }
  100456. /* read qlp coeff precision */
  100457. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  100458. return false; /* read_callback_ sets the state for us */
  100459. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  100460. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100461. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100462. return true;
  100463. }
  100464. subframe->qlp_coeff_precision = u32+1;
  100465. /* read qlp shift */
  100466. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  100467. return false; /* read_callback_ sets the state for us */
  100468. subframe->quantization_level = i32;
  100469. /* read quantized lp coefficiencts */
  100470. for(u = 0; u < order; u++) {
  100471. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  100472. return false; /* read_callback_ sets the state for us */
  100473. subframe->qlp_coeff[u] = i32;
  100474. }
  100475. /* read entropy coding method info */
  100476. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  100477. return false; /* read_callback_ sets the state for us */
  100478. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  100479. switch(subframe->entropy_coding_method.type) {
  100480. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  100481. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  100482. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  100483. return false; /* read_callback_ sets the state for us */
  100484. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  100485. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  100486. break;
  100487. default:
  100488. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100489. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100490. return true;
  100491. }
  100492. /* read residual */
  100493. switch(subframe->entropy_coding_method.type) {
  100494. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  100495. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  100496. 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))
  100497. return false;
  100498. break;
  100499. default:
  100500. FLAC__ASSERT(0);
  100501. }
  100502. /* decode the subframe */
  100503. if(do_full_decode) {
  100504. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  100505. /*@@@@@@ technically not pessimistic enough, should be more like
  100506. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  100507. */
  100508. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  100509. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  100510. if(order <= 8)
  100511. 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);
  100512. else
  100513. 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);
  100514. }
  100515. else
  100516. 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);
  100517. else
  100518. 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);
  100519. }
  100520. return true;
  100521. }
  100522. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  100523. {
  100524. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  100525. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  100526. unsigned i;
  100527. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  100528. subframe->data = residual;
  100529. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  100530. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  100531. return false; /* read_callback_ sets the state for us */
  100532. residual[i] = x;
  100533. }
  100534. /* decode the subframe */
  100535. if(do_full_decode)
  100536. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  100537. return true;
  100538. }
  100539. 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)
  100540. {
  100541. FLAC__uint32 rice_parameter;
  100542. int i;
  100543. unsigned partition, sample, u;
  100544. const unsigned partitions = 1u << partition_order;
  100545. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  100546. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  100547. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  100548. /* sanity checks */
  100549. if(partition_order == 0) {
  100550. if(decoder->private_->frame.header.blocksize < predictor_order) {
  100551. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100552. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100553. return true;
  100554. }
  100555. }
  100556. else {
  100557. if(partition_samples < predictor_order) {
  100558. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100559. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100560. return true;
  100561. }
  100562. }
  100563. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  100564. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100565. return false;
  100566. }
  100567. sample = 0;
  100568. for(partition = 0; partition < partitions; partition++) {
  100569. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  100570. return false; /* read_callback_ sets the state for us */
  100571. partitioned_rice_contents->parameters[partition] = rice_parameter;
  100572. if(rice_parameter < pesc) {
  100573. partitioned_rice_contents->raw_bits[partition] = 0;
  100574. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  100575. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  100576. return false; /* read_callback_ sets the state for us */
  100577. sample += u;
  100578. }
  100579. else {
  100580. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  100581. return false; /* read_callback_ sets the state for us */
  100582. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  100583. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  100584. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  100585. return false; /* read_callback_ sets the state for us */
  100586. residual[sample] = i;
  100587. }
  100588. }
  100589. }
  100590. return true;
  100591. }
  100592. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  100593. {
  100594. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  100595. FLAC__uint32 zero = 0;
  100596. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  100597. return false; /* read_callback_ sets the state for us */
  100598. if(zero != 0) {
  100599. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100600. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100601. }
  100602. }
  100603. return true;
  100604. }
  100605. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  100606. {
  100607. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  100608. if(
  100609. #if FLAC__HAS_OGG
  100610. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  100611. !decoder->private_->is_ogg &&
  100612. #endif
  100613. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  100614. ) {
  100615. *bytes = 0;
  100616. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  100617. return false;
  100618. }
  100619. else if(*bytes > 0) {
  100620. /* While seeking, it is possible for our seek to land in the
  100621. * middle of audio data that looks exactly like a frame header
  100622. * from a future version of an encoder. When that happens, our
  100623. * error callback will get an
  100624. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  100625. * unparseable_frame_count. But there is a remote possibility
  100626. * that it is properly synced at such a "future-codec frame",
  100627. * so to make sure, we wait to see many "unparseable" errors in
  100628. * a row before bailing out.
  100629. */
  100630. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  100631. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  100632. return false;
  100633. }
  100634. else {
  100635. const FLAC__StreamDecoderReadStatus status =
  100636. #if FLAC__HAS_OGG
  100637. decoder->private_->is_ogg?
  100638. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  100639. #endif
  100640. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  100641. ;
  100642. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  100643. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  100644. return false;
  100645. }
  100646. else if(*bytes == 0) {
  100647. if(
  100648. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  100649. (
  100650. #if FLAC__HAS_OGG
  100651. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  100652. !decoder->private_->is_ogg &&
  100653. #endif
  100654. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  100655. )
  100656. ) {
  100657. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  100658. return false;
  100659. }
  100660. else
  100661. return true;
  100662. }
  100663. else
  100664. return true;
  100665. }
  100666. }
  100667. else {
  100668. /* abort to avoid a deadlock */
  100669. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  100670. return false;
  100671. }
  100672. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  100673. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  100674. * and at the same time hit the end of the stream (for example, seeking
  100675. * to a point that is after the beginning of the last Ogg page). There
  100676. * is no way to report an Ogg sync loss through the callbacks (see note
  100677. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  100678. * So to keep the decoder from stopping at this point we gate the call
  100679. * to the eof_callback and let the Ogg decoder aspect set the
  100680. * end-of-stream state when it is needed.
  100681. */
  100682. }
  100683. #if FLAC__HAS_OGG
  100684. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  100685. {
  100686. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  100687. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  100688. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  100689. /* we don't really have a way to handle lost sync via read
  100690. * callback so we'll let it pass and let the underlying
  100691. * FLAC decoder catch the error
  100692. */
  100693. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  100694. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  100695. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  100696. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  100697. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  100698. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  100699. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  100700. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  100701. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  100702. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  100703. default:
  100704. FLAC__ASSERT(0);
  100705. /* double protection */
  100706. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  100707. }
  100708. }
  100709. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  100710. {
  100711. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  100712. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  100713. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  100714. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  100715. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  100716. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  100717. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  100718. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  100719. default:
  100720. /* double protection: */
  100721. FLAC__ASSERT(0);
  100722. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  100723. }
  100724. }
  100725. #endif
  100726. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  100727. {
  100728. if(decoder->private_->is_seeking) {
  100729. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  100730. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  100731. FLAC__uint64 target_sample = decoder->private_->target_sample;
  100732. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  100733. #if FLAC__HAS_OGG
  100734. decoder->private_->got_a_frame = true;
  100735. #endif
  100736. decoder->private_->last_frame = *frame; /* save the frame */
  100737. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  100738. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  100739. /* kick out of seek mode */
  100740. decoder->private_->is_seeking = false;
  100741. /* shift out the samples before target_sample */
  100742. if(delta > 0) {
  100743. unsigned channel;
  100744. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  100745. for(channel = 0; channel < frame->header.channels; channel++)
  100746. newbuffer[channel] = buffer[channel] + delta;
  100747. decoder->private_->last_frame.header.blocksize -= delta;
  100748. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  100749. /* write the relevant samples */
  100750. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  100751. }
  100752. else {
  100753. /* write the relevant samples */
  100754. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  100755. }
  100756. }
  100757. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  100758. }
  100759. /*
  100760. * If we never got STREAMINFO, turn off MD5 checking to save
  100761. * cycles since we don't have a sum to compare to anyway
  100762. */
  100763. if(!decoder->private_->has_stream_info)
  100764. decoder->private_->do_md5_checking = false;
  100765. if(decoder->private_->do_md5_checking) {
  100766. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  100767. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  100768. }
  100769. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  100770. }
  100771. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  100772. {
  100773. if(!decoder->private_->is_seeking)
  100774. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  100775. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  100776. decoder->private_->unparseable_frame_count++;
  100777. }
  100778. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  100779. {
  100780. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  100781. FLAC__int64 pos = -1;
  100782. int i;
  100783. unsigned approx_bytes_per_frame;
  100784. FLAC__bool first_seek = true;
  100785. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  100786. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  100787. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  100788. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  100789. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  100790. /* take these from the current frame in case they've changed mid-stream */
  100791. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  100792. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  100793. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  100794. /* use values from stream info if we didn't decode a frame */
  100795. if(channels == 0)
  100796. channels = decoder->private_->stream_info.data.stream_info.channels;
  100797. if(bps == 0)
  100798. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  100799. /* we are just guessing here */
  100800. if(max_framesize > 0)
  100801. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  100802. /*
  100803. * Check if it's a known fixed-blocksize stream. Note that though
  100804. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  100805. * never get a STREAMINFO block when decoding so the value of
  100806. * min_blocksize might be zero.
  100807. */
  100808. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  100809. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  100810. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  100811. }
  100812. else
  100813. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  100814. /*
  100815. * First, we set an upper and lower bound on where in the
  100816. * stream we will search. For now we assume the worst case
  100817. * scenario, which is our best guess at the beginning of
  100818. * the first frame and end of the stream.
  100819. */
  100820. lower_bound = first_frame_offset;
  100821. lower_bound_sample = 0;
  100822. upper_bound = stream_length;
  100823. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  100824. /*
  100825. * Now we refine the bounds if we have a seektable with
  100826. * suitable points. Note that according to the spec they
  100827. * must be ordered by ascending sample number.
  100828. *
  100829. * Note: to protect against invalid seek tables we will ignore points
  100830. * that have frame_samples==0 or sample_number>=total_samples
  100831. */
  100832. if(seek_table) {
  100833. FLAC__uint64 new_lower_bound = lower_bound;
  100834. FLAC__uint64 new_upper_bound = upper_bound;
  100835. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  100836. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  100837. /* find the closest seek point <= target_sample, if it exists */
  100838. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  100839. if(
  100840. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  100841. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  100842. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  100843. seek_table->points[i].sample_number <= target_sample
  100844. )
  100845. break;
  100846. }
  100847. if(i >= 0) { /* i.e. we found a suitable seek point... */
  100848. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  100849. new_lower_bound_sample = seek_table->points[i].sample_number;
  100850. }
  100851. /* find the closest seek point > target_sample, if it exists */
  100852. for(i = 0; i < (int)seek_table->num_points; i++) {
  100853. if(
  100854. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  100855. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  100856. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  100857. seek_table->points[i].sample_number > target_sample
  100858. )
  100859. break;
  100860. }
  100861. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  100862. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  100863. new_upper_bound_sample = seek_table->points[i].sample_number;
  100864. }
  100865. /* final protection against unsorted seek tables; keep original values if bogus */
  100866. if(new_upper_bound >= new_lower_bound) {
  100867. lower_bound = new_lower_bound;
  100868. upper_bound = new_upper_bound;
  100869. lower_bound_sample = new_lower_bound_sample;
  100870. upper_bound_sample = new_upper_bound_sample;
  100871. }
  100872. }
  100873. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  100874. /* there are 2 insidious ways that the following equality occurs, which
  100875. * we need to fix:
  100876. * 1) total_samples is 0 (unknown) and target_sample is 0
  100877. * 2) total_samples is 0 (unknown) and target_sample happens to be
  100878. * exactly equal to the last seek point in the seek table; this
  100879. * means there is no seek point above it, and upper_bound_samples
  100880. * remains equal to the estimate (of target_samples) we made above
  100881. * in either case it does not hurt to move upper_bound_sample up by 1
  100882. */
  100883. if(upper_bound_sample == lower_bound_sample)
  100884. upper_bound_sample++;
  100885. decoder->private_->target_sample = target_sample;
  100886. while(1) {
  100887. /* check if the bounds are still ok */
  100888. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  100889. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  100890. return false;
  100891. }
  100892. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100893. #if defined _MSC_VER || defined __MINGW32__
  100894. /* with VC++ you have to spoon feed it the casting */
  100895. 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;
  100896. #else
  100897. 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;
  100898. #endif
  100899. #else
  100900. /* a little less accurate: */
  100901. if(upper_bound - lower_bound < 0xffffffff)
  100902. 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;
  100903. else /* @@@ WATCHOUT, ~2TB limit */
  100904. 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;
  100905. #endif
  100906. if(pos >= (FLAC__int64)upper_bound)
  100907. pos = (FLAC__int64)upper_bound - 1;
  100908. if(pos < (FLAC__int64)lower_bound)
  100909. pos = (FLAC__int64)lower_bound;
  100910. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  100911. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  100912. return false;
  100913. }
  100914. if(!FLAC__stream_decoder_flush(decoder)) {
  100915. /* above call sets the state for us */
  100916. return false;
  100917. }
  100918. /* Now we need to get a frame. First we need to reset our
  100919. * unparseable_frame_count; if we get too many unparseable
  100920. * frames in a row, the read callback will return
  100921. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  100922. * FLAC__stream_decoder_process_single() to return false.
  100923. */
  100924. decoder->private_->unparseable_frame_count = 0;
  100925. if(!FLAC__stream_decoder_process_single(decoder)) {
  100926. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  100927. return false;
  100928. }
  100929. /* our write callback will change the state when it gets to the target frame */
  100930. /* 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 */
  100931. #if 0
  100932. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  100933. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  100934. break;
  100935. #endif
  100936. if(!decoder->private_->is_seeking)
  100937. break;
  100938. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  100939. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  100940. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  100941. if (pos == (FLAC__int64)lower_bound) {
  100942. /* can't move back any more than the first frame, something is fatally wrong */
  100943. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  100944. return false;
  100945. }
  100946. /* our last move backwards wasn't big enough, try again */
  100947. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  100948. continue;
  100949. }
  100950. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  100951. first_seek = false;
  100952. /* make sure we are not seeking in corrupted stream */
  100953. if (this_frame_sample < lower_bound_sample) {
  100954. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  100955. return false;
  100956. }
  100957. /* we need to narrow the search */
  100958. if(target_sample < this_frame_sample) {
  100959. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  100960. /*@@@@@@ what will decode position be if at end of stream? */
  100961. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  100962. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  100963. return false;
  100964. }
  100965. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  100966. }
  100967. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  100968. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  100969. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  100970. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  100971. return false;
  100972. }
  100973. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  100974. }
  100975. }
  100976. return true;
  100977. }
  100978. #if FLAC__HAS_OGG
  100979. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  100980. {
  100981. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  100982. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  100983. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  100984. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  100985. FLAC__bool did_a_seek;
  100986. unsigned iteration = 0;
  100987. /* In the first iterations, we will calculate the target byte position
  100988. * by the distance from the target sample to left_sample and
  100989. * right_sample (let's call it "proportional search"). After that, we
  100990. * will switch to binary search.
  100991. */
  100992. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  100993. /* We will switch to a linear search once our current sample is less
  100994. * than this number of samples ahead of the target sample
  100995. */
  100996. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  100997. /* If the total number of samples is unknown, use a large value, and
  100998. * force binary search immediately.
  100999. */
  101000. if(right_sample == 0) {
  101001. right_sample = (FLAC__uint64)(-1);
  101002. BINARY_SEARCH_AFTER_ITERATION = 0;
  101003. }
  101004. decoder->private_->target_sample = target_sample;
  101005. for( ; ; iteration++) {
  101006. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  101007. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  101008. pos = (right_pos + left_pos) / 2;
  101009. }
  101010. else {
  101011. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101012. #if defined _MSC_VER || defined __MINGW32__
  101013. /* with MSVC you have to spoon feed it the casting */
  101014. 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));
  101015. #else
  101016. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  101017. #endif
  101018. #else
  101019. /* a little less accurate: */
  101020. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  101021. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  101022. else /* @@@ WATCHOUT, ~2TB limit */
  101023. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  101024. #endif
  101025. /* @@@ TODO: might want to limit pos to some distance
  101026. * before EOF, to make sure we land before the last frame,
  101027. * thereby getting a this_frame_sample and so having a better
  101028. * estimate.
  101029. */
  101030. }
  101031. /* physical seek */
  101032. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  101033. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101034. return false;
  101035. }
  101036. if(!FLAC__stream_decoder_flush(decoder)) {
  101037. /* above call sets the state for us */
  101038. return false;
  101039. }
  101040. did_a_seek = true;
  101041. }
  101042. else
  101043. did_a_seek = false;
  101044. decoder->private_->got_a_frame = false;
  101045. if(!FLAC__stream_decoder_process_single(decoder)) {
  101046. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101047. return false;
  101048. }
  101049. if(!decoder->private_->got_a_frame) {
  101050. if(did_a_seek) {
  101051. /* this can happen if we seek to a point after the last frame; we drop
  101052. * to binary search right away in this case to avoid any wasted
  101053. * iterations of proportional search.
  101054. */
  101055. right_pos = pos;
  101056. BINARY_SEARCH_AFTER_ITERATION = 0;
  101057. }
  101058. else {
  101059. /* this can probably only happen if total_samples is unknown and the
  101060. * target_sample is past the end of the stream
  101061. */
  101062. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101063. return false;
  101064. }
  101065. }
  101066. /* our write callback will change the state when it gets to the target frame */
  101067. else if(!decoder->private_->is_seeking) {
  101068. break;
  101069. }
  101070. else {
  101071. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  101072. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101073. if (did_a_seek) {
  101074. if (this_frame_sample <= target_sample) {
  101075. /* The 'equal' case should not happen, since
  101076. * FLAC__stream_decoder_process_single()
  101077. * should recognize that it has hit the
  101078. * target sample and we would exit through
  101079. * the 'break' above.
  101080. */
  101081. FLAC__ASSERT(this_frame_sample != target_sample);
  101082. left_sample = this_frame_sample;
  101083. /* sanity check to avoid infinite loop */
  101084. if (left_pos == pos) {
  101085. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101086. return false;
  101087. }
  101088. left_pos = pos;
  101089. }
  101090. else if(this_frame_sample > target_sample) {
  101091. right_sample = this_frame_sample;
  101092. /* sanity check to avoid infinite loop */
  101093. if (right_pos == pos) {
  101094. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101095. return false;
  101096. }
  101097. right_pos = pos;
  101098. }
  101099. }
  101100. }
  101101. }
  101102. return true;
  101103. }
  101104. #endif
  101105. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101106. {
  101107. (void)client_data;
  101108. if(*bytes > 0) {
  101109. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  101110. if(ferror(decoder->private_->file))
  101111. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101112. else if(*bytes == 0)
  101113. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  101114. else
  101115. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101116. }
  101117. else
  101118. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  101119. }
  101120. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  101121. {
  101122. (void)client_data;
  101123. if(decoder->private_->file == stdin)
  101124. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  101125. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  101126. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  101127. else
  101128. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  101129. }
  101130. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  101131. {
  101132. off_t pos;
  101133. (void)client_data;
  101134. if(decoder->private_->file == stdin)
  101135. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  101136. else if((pos = ftello(decoder->private_->file)) < 0)
  101137. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  101138. else {
  101139. *absolute_byte_offset = (FLAC__uint64)pos;
  101140. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  101141. }
  101142. }
  101143. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  101144. {
  101145. struct stat filestats;
  101146. (void)client_data;
  101147. if(decoder->private_->file == stdin)
  101148. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  101149. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  101150. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  101151. else {
  101152. *stream_length = (FLAC__uint64)filestats.st_size;
  101153. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  101154. }
  101155. }
  101156. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  101157. {
  101158. (void)client_data;
  101159. return feof(decoder->private_->file)? true : false;
  101160. }
  101161. #endif
  101162. /*** End of inlined file: stream_decoder.c ***/
  101163. /*** Start of inlined file: stream_encoder.c ***/
  101164. /*** Start of inlined file: juce_FlacHeader.h ***/
  101165. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  101166. // tasks..
  101167. #define VERSION "1.2.1"
  101168. #define FLAC__NO_DLL 1
  101169. #if JUCE_MSVC
  101170. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  101171. #endif
  101172. #if JUCE_MAC
  101173. #define FLAC__SYS_DARWIN 1
  101174. #endif
  101175. /*** End of inlined file: juce_FlacHeader.h ***/
  101176. #if JUCE_USE_FLAC
  101177. #if HAVE_CONFIG_H
  101178. # include <config.h>
  101179. #endif
  101180. #if defined _MSC_VER || defined __MINGW32__
  101181. #include <io.h> /* for _setmode() */
  101182. #include <fcntl.h> /* for _O_BINARY */
  101183. #endif
  101184. #if defined __CYGWIN__ || defined __EMX__
  101185. #include <io.h> /* for setmode(), O_BINARY */
  101186. #include <fcntl.h> /* for _O_BINARY */
  101187. #endif
  101188. #include <limits.h>
  101189. #include <stdio.h>
  101190. #include <stdlib.h> /* for malloc() */
  101191. #include <string.h> /* for memcpy() */
  101192. #include <sys/types.h> /* for off_t */
  101193. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  101194. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  101195. #define fseeko fseek
  101196. #define ftello ftell
  101197. #endif
  101198. #endif
  101199. /*** Start of inlined file: stream_encoder.h ***/
  101200. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  101201. #define FLAC__PROTECTED__STREAM_ENCODER_H
  101202. #if FLAC__HAS_OGG
  101203. #include "private/ogg_encoder_aspect.h"
  101204. #endif
  101205. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101206. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  101207. typedef enum {
  101208. FLAC__APODIZATION_BARTLETT,
  101209. FLAC__APODIZATION_BARTLETT_HANN,
  101210. FLAC__APODIZATION_BLACKMAN,
  101211. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  101212. FLAC__APODIZATION_CONNES,
  101213. FLAC__APODIZATION_FLATTOP,
  101214. FLAC__APODIZATION_GAUSS,
  101215. FLAC__APODIZATION_HAMMING,
  101216. FLAC__APODIZATION_HANN,
  101217. FLAC__APODIZATION_KAISER_BESSEL,
  101218. FLAC__APODIZATION_NUTTALL,
  101219. FLAC__APODIZATION_RECTANGLE,
  101220. FLAC__APODIZATION_TRIANGLE,
  101221. FLAC__APODIZATION_TUKEY,
  101222. FLAC__APODIZATION_WELCH
  101223. } FLAC__ApodizationFunction;
  101224. typedef struct {
  101225. FLAC__ApodizationFunction type;
  101226. union {
  101227. struct {
  101228. FLAC__real stddev;
  101229. } gauss;
  101230. struct {
  101231. FLAC__real p;
  101232. } tukey;
  101233. } parameters;
  101234. } FLAC__ApodizationSpecification;
  101235. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101236. typedef struct FLAC__StreamEncoderProtected {
  101237. FLAC__StreamEncoderState state;
  101238. FLAC__bool verify;
  101239. FLAC__bool streamable_subset;
  101240. FLAC__bool do_md5;
  101241. FLAC__bool do_mid_side_stereo;
  101242. FLAC__bool loose_mid_side_stereo;
  101243. unsigned channels;
  101244. unsigned bits_per_sample;
  101245. unsigned sample_rate;
  101246. unsigned blocksize;
  101247. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101248. unsigned num_apodizations;
  101249. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  101250. #endif
  101251. unsigned max_lpc_order;
  101252. unsigned qlp_coeff_precision;
  101253. FLAC__bool do_qlp_coeff_prec_search;
  101254. FLAC__bool do_exhaustive_model_search;
  101255. FLAC__bool do_escape_coding;
  101256. unsigned min_residual_partition_order;
  101257. unsigned max_residual_partition_order;
  101258. unsigned rice_parameter_search_dist;
  101259. FLAC__uint64 total_samples_estimate;
  101260. FLAC__StreamMetadata **metadata;
  101261. unsigned num_metadata_blocks;
  101262. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  101263. #if FLAC__HAS_OGG
  101264. FLAC__OggEncoderAspect ogg_encoder_aspect;
  101265. #endif
  101266. } FLAC__StreamEncoderProtected;
  101267. #endif
  101268. /*** End of inlined file: stream_encoder.h ***/
  101269. #if FLAC__HAS_OGG
  101270. #include "include/private/ogg_helper.h"
  101271. #include "include/private/ogg_mapping.h"
  101272. #endif
  101273. /*** Start of inlined file: stream_encoder_framing.h ***/
  101274. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  101275. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  101276. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  101277. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  101278. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101279. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101280. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101281. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101282. #endif
  101283. /*** End of inlined file: stream_encoder_framing.h ***/
  101284. /*** Start of inlined file: window.h ***/
  101285. #ifndef FLAC__PRIVATE__WINDOW_H
  101286. #define FLAC__PRIVATE__WINDOW_H
  101287. #ifdef HAVE_CONFIG_H
  101288. #include <config.h>
  101289. #endif
  101290. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101291. /*
  101292. * FLAC__window_*()
  101293. * --------------------------------------------------------------------
  101294. * Calculates window coefficients according to different apodization
  101295. * functions.
  101296. *
  101297. * OUT window[0,L-1]
  101298. * IN L (number of points in window)
  101299. */
  101300. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  101301. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  101302. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  101303. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  101304. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  101305. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  101306. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  101307. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  101308. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  101309. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  101310. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  101311. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  101312. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  101313. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  101314. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  101315. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  101316. #endif
  101317. /*** End of inlined file: window.h ***/
  101318. #ifndef FLaC__INLINE
  101319. #define FLaC__INLINE
  101320. #endif
  101321. #ifdef min
  101322. #undef min
  101323. #endif
  101324. #define min(x,y) ((x)<(y)?(x):(y))
  101325. #ifdef max
  101326. #undef max
  101327. #endif
  101328. #define max(x,y) ((x)>(y)?(x):(y))
  101329. /* Exact Rice codeword length calculation is off by default. The simple
  101330. * (and fast) estimation (of how many bits a residual value will be
  101331. * encoded with) in this encoder is very good, almost always yielding
  101332. * compression within 0.1% of exact calculation.
  101333. */
  101334. #undef EXACT_RICE_BITS_CALCULATION
  101335. /* Rice parameter searching is off by default. The simple (and fast)
  101336. * parameter estimation in this encoder is very good, almost always
  101337. * yielding compression within 0.1% of the optimal parameters.
  101338. */
  101339. #undef ENABLE_RICE_PARAMETER_SEARCH
  101340. typedef struct {
  101341. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  101342. unsigned size; /* of each data[] in samples */
  101343. unsigned tail;
  101344. } verify_input_fifo;
  101345. typedef struct {
  101346. const FLAC__byte *data;
  101347. unsigned capacity;
  101348. unsigned bytes;
  101349. } verify_output;
  101350. typedef enum {
  101351. ENCODER_IN_MAGIC = 0,
  101352. ENCODER_IN_METADATA = 1,
  101353. ENCODER_IN_AUDIO = 2
  101354. } EncoderStateHint;
  101355. static struct CompressionLevels {
  101356. FLAC__bool do_mid_side_stereo;
  101357. FLAC__bool loose_mid_side_stereo;
  101358. unsigned max_lpc_order;
  101359. unsigned qlp_coeff_precision;
  101360. FLAC__bool do_qlp_coeff_prec_search;
  101361. FLAC__bool do_escape_coding;
  101362. FLAC__bool do_exhaustive_model_search;
  101363. unsigned min_residual_partition_order;
  101364. unsigned max_residual_partition_order;
  101365. unsigned rice_parameter_search_dist;
  101366. } compression_levels_[] = {
  101367. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  101368. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  101369. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  101370. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  101371. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  101372. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  101373. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  101374. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  101375. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  101376. };
  101377. /***********************************************************************
  101378. *
  101379. * Private class method prototypes
  101380. *
  101381. ***********************************************************************/
  101382. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  101383. static void free_(FLAC__StreamEncoder *encoder);
  101384. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  101385. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  101386. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  101387. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  101388. #if FLAC__HAS_OGG
  101389. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  101390. #endif
  101391. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  101392. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  101393. static FLAC__bool process_subframe_(
  101394. FLAC__StreamEncoder *encoder,
  101395. unsigned min_partition_order,
  101396. unsigned max_partition_order,
  101397. const FLAC__FrameHeader *frame_header,
  101398. unsigned subframe_bps,
  101399. const FLAC__int32 integer_signal[],
  101400. FLAC__Subframe *subframe[2],
  101401. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  101402. FLAC__int32 *residual[2],
  101403. unsigned *best_subframe,
  101404. unsigned *best_bits
  101405. );
  101406. static FLAC__bool add_subframe_(
  101407. FLAC__StreamEncoder *encoder,
  101408. unsigned blocksize,
  101409. unsigned subframe_bps,
  101410. const FLAC__Subframe *subframe,
  101411. FLAC__BitWriter *frame
  101412. );
  101413. static unsigned evaluate_constant_subframe_(
  101414. FLAC__StreamEncoder *encoder,
  101415. const FLAC__int32 signal,
  101416. unsigned blocksize,
  101417. unsigned subframe_bps,
  101418. FLAC__Subframe *subframe
  101419. );
  101420. static unsigned evaluate_fixed_subframe_(
  101421. FLAC__StreamEncoder *encoder,
  101422. const FLAC__int32 signal[],
  101423. FLAC__int32 residual[],
  101424. FLAC__uint64 abs_residual_partition_sums[],
  101425. unsigned raw_bits_per_partition[],
  101426. unsigned blocksize,
  101427. unsigned subframe_bps,
  101428. unsigned order,
  101429. unsigned rice_parameter,
  101430. unsigned rice_parameter_limit,
  101431. unsigned min_partition_order,
  101432. unsigned max_partition_order,
  101433. FLAC__bool do_escape_coding,
  101434. unsigned rice_parameter_search_dist,
  101435. FLAC__Subframe *subframe,
  101436. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  101437. );
  101438. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101439. static unsigned evaluate_lpc_subframe_(
  101440. FLAC__StreamEncoder *encoder,
  101441. const FLAC__int32 signal[],
  101442. FLAC__int32 residual[],
  101443. FLAC__uint64 abs_residual_partition_sums[],
  101444. unsigned raw_bits_per_partition[],
  101445. const FLAC__real lp_coeff[],
  101446. unsigned blocksize,
  101447. unsigned subframe_bps,
  101448. unsigned order,
  101449. unsigned qlp_coeff_precision,
  101450. unsigned rice_parameter,
  101451. unsigned rice_parameter_limit,
  101452. unsigned min_partition_order,
  101453. unsigned max_partition_order,
  101454. FLAC__bool do_escape_coding,
  101455. unsigned rice_parameter_search_dist,
  101456. FLAC__Subframe *subframe,
  101457. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  101458. );
  101459. #endif
  101460. static unsigned evaluate_verbatim_subframe_(
  101461. FLAC__StreamEncoder *encoder,
  101462. const FLAC__int32 signal[],
  101463. unsigned blocksize,
  101464. unsigned subframe_bps,
  101465. FLAC__Subframe *subframe
  101466. );
  101467. static unsigned find_best_partition_order_(
  101468. struct FLAC__StreamEncoderPrivate *private_,
  101469. const FLAC__int32 residual[],
  101470. FLAC__uint64 abs_residual_partition_sums[],
  101471. unsigned raw_bits_per_partition[],
  101472. unsigned residual_samples,
  101473. unsigned predictor_order,
  101474. unsigned rice_parameter,
  101475. unsigned rice_parameter_limit,
  101476. unsigned min_partition_order,
  101477. unsigned max_partition_order,
  101478. unsigned bps,
  101479. FLAC__bool do_escape_coding,
  101480. unsigned rice_parameter_search_dist,
  101481. FLAC__EntropyCodingMethod *best_ecm
  101482. );
  101483. static void precompute_partition_info_sums_(
  101484. const FLAC__int32 residual[],
  101485. FLAC__uint64 abs_residual_partition_sums[],
  101486. unsigned residual_samples,
  101487. unsigned predictor_order,
  101488. unsigned min_partition_order,
  101489. unsigned max_partition_order,
  101490. unsigned bps
  101491. );
  101492. static void precompute_partition_info_escapes_(
  101493. const FLAC__int32 residual[],
  101494. unsigned raw_bits_per_partition[],
  101495. unsigned residual_samples,
  101496. unsigned predictor_order,
  101497. unsigned min_partition_order,
  101498. unsigned max_partition_order
  101499. );
  101500. static FLAC__bool set_partitioned_rice_(
  101501. #ifdef EXACT_RICE_BITS_CALCULATION
  101502. const FLAC__int32 residual[],
  101503. #endif
  101504. const FLAC__uint64 abs_residual_partition_sums[],
  101505. const unsigned raw_bits_per_partition[],
  101506. const unsigned residual_samples,
  101507. const unsigned predictor_order,
  101508. const unsigned suggested_rice_parameter,
  101509. const unsigned rice_parameter_limit,
  101510. const unsigned rice_parameter_search_dist,
  101511. const unsigned partition_order,
  101512. const FLAC__bool search_for_escapes,
  101513. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  101514. unsigned *bits
  101515. );
  101516. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  101517. /* verify-related routines: */
  101518. static void append_to_verify_fifo_(
  101519. verify_input_fifo *fifo,
  101520. const FLAC__int32 * const input[],
  101521. unsigned input_offset,
  101522. unsigned channels,
  101523. unsigned wide_samples
  101524. );
  101525. static void append_to_verify_fifo_interleaved_(
  101526. verify_input_fifo *fifo,
  101527. const FLAC__int32 input[],
  101528. unsigned input_offset,
  101529. unsigned channels,
  101530. unsigned wide_samples
  101531. );
  101532. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  101533. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  101534. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  101535. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  101536. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  101537. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  101538. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  101539. 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);
  101540. static FILE *get_binary_stdout_(void);
  101541. /***********************************************************************
  101542. *
  101543. * Private class data
  101544. *
  101545. ***********************************************************************/
  101546. typedef struct FLAC__StreamEncoderPrivate {
  101547. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  101548. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  101549. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  101550. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101551. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  101552. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  101553. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  101554. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  101555. #endif
  101556. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  101557. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  101558. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  101559. FLAC__int32 *residual_workspace_mid_side[2][2];
  101560. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  101561. FLAC__Subframe subframe_workspace_mid_side[2][2];
  101562. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  101563. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  101564. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  101565. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  101566. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  101567. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  101568. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  101569. unsigned best_subframe_mid_side[2];
  101570. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  101571. unsigned best_subframe_bits_mid_side[2];
  101572. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  101573. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  101574. FLAC__BitWriter *frame; /* the current frame being worked on */
  101575. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  101576. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  101577. FLAC__ChannelAssignment last_channel_assignment;
  101578. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  101579. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  101580. unsigned current_sample_number;
  101581. unsigned current_frame_number;
  101582. FLAC__MD5Context md5context;
  101583. FLAC__CPUInfo cpuinfo;
  101584. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101585. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  101586. #else
  101587. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  101588. #endif
  101589. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101590. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  101591. 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[]);
  101592. 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[]);
  101593. 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[]);
  101594. #endif
  101595. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  101596. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  101597. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  101598. FLAC__bool disable_constant_subframes;
  101599. FLAC__bool disable_fixed_subframes;
  101600. FLAC__bool disable_verbatim_subframes;
  101601. #if FLAC__HAS_OGG
  101602. FLAC__bool is_ogg;
  101603. #endif
  101604. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  101605. FLAC__StreamEncoderSeekCallback seek_callback;
  101606. FLAC__StreamEncoderTellCallback tell_callback;
  101607. FLAC__StreamEncoderWriteCallback write_callback;
  101608. FLAC__StreamEncoderMetadataCallback metadata_callback;
  101609. FLAC__StreamEncoderProgressCallback progress_callback;
  101610. void *client_data;
  101611. unsigned first_seekpoint_to_check;
  101612. FILE *file; /* only used when encoding to a file */
  101613. FLAC__uint64 bytes_written;
  101614. FLAC__uint64 samples_written;
  101615. unsigned frames_written;
  101616. unsigned total_frames_estimate;
  101617. /* unaligned (original) pointers to allocated data */
  101618. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  101619. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  101620. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101621. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  101622. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  101623. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  101624. FLAC__real *windowed_signal_unaligned;
  101625. #endif
  101626. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  101627. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  101628. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  101629. unsigned *raw_bits_per_partition_unaligned;
  101630. /*
  101631. * These fields have been moved here from private function local
  101632. * declarations merely to save stack space during encoding.
  101633. */
  101634. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101635. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  101636. #endif
  101637. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  101638. /*
  101639. * The data for the verify section
  101640. */
  101641. struct {
  101642. FLAC__StreamDecoder *decoder;
  101643. EncoderStateHint state_hint;
  101644. FLAC__bool needs_magic_hack;
  101645. verify_input_fifo input_fifo;
  101646. verify_output output;
  101647. struct {
  101648. FLAC__uint64 absolute_sample;
  101649. unsigned frame_number;
  101650. unsigned channel;
  101651. unsigned sample;
  101652. FLAC__int32 expected;
  101653. FLAC__int32 got;
  101654. } error_stats;
  101655. } verify;
  101656. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  101657. } FLAC__StreamEncoderPrivate;
  101658. /***********************************************************************
  101659. *
  101660. * Public static class data
  101661. *
  101662. ***********************************************************************/
  101663. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  101664. "FLAC__STREAM_ENCODER_OK",
  101665. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  101666. "FLAC__STREAM_ENCODER_OGG_ERROR",
  101667. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  101668. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  101669. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  101670. "FLAC__STREAM_ENCODER_IO_ERROR",
  101671. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  101672. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  101673. };
  101674. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  101675. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  101676. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  101677. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  101678. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  101679. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  101680. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  101681. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  101682. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  101683. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  101684. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  101685. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  101686. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  101687. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  101688. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  101689. };
  101690. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  101691. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  101692. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  101693. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  101694. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  101695. };
  101696. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  101697. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  101698. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  101699. };
  101700. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  101701. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  101702. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  101703. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  101704. };
  101705. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  101706. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  101707. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  101708. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  101709. };
  101710. /* Number of samples that will be overread to watch for end of stream. By
  101711. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  101712. * always try to read blocksize+1 samples before encoding a block, so that
  101713. * even if the stream has a total sample count that is an integral multiple
  101714. * of the blocksize, we will still notice when we are encoding the last
  101715. * block. This is needed, for example, to correctly set the end-of-stream
  101716. * marker in Ogg FLAC.
  101717. *
  101718. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  101719. * not really any reason to change it.
  101720. */
  101721. static const unsigned OVERREAD_ = 1;
  101722. /***********************************************************************
  101723. *
  101724. * Class constructor/destructor
  101725. *
  101726. */
  101727. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  101728. {
  101729. FLAC__StreamEncoder *encoder;
  101730. unsigned i;
  101731. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  101732. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  101733. if(encoder == 0) {
  101734. return 0;
  101735. }
  101736. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  101737. if(encoder->protected_ == 0) {
  101738. free(encoder);
  101739. return 0;
  101740. }
  101741. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  101742. if(encoder->private_ == 0) {
  101743. free(encoder->protected_);
  101744. free(encoder);
  101745. return 0;
  101746. }
  101747. encoder->private_->frame = FLAC__bitwriter_new();
  101748. if(encoder->private_->frame == 0) {
  101749. free(encoder->private_);
  101750. free(encoder->protected_);
  101751. free(encoder);
  101752. return 0;
  101753. }
  101754. encoder->private_->file = 0;
  101755. set_defaults_enc(encoder);
  101756. encoder->private_->is_being_deleted = false;
  101757. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  101758. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  101759. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  101760. }
  101761. for(i = 0; i < 2; i++) {
  101762. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  101763. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  101764. }
  101765. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  101766. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  101767. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  101768. }
  101769. for(i = 0; i < 2; i++) {
  101770. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  101771. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  101772. }
  101773. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  101774. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  101775. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  101776. }
  101777. for(i = 0; i < 2; i++) {
  101778. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  101779. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  101780. }
  101781. for(i = 0; i < 2; i++)
  101782. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  101783. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  101784. return encoder;
  101785. }
  101786. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  101787. {
  101788. unsigned i;
  101789. FLAC__ASSERT(0 != encoder);
  101790. FLAC__ASSERT(0 != encoder->protected_);
  101791. FLAC__ASSERT(0 != encoder->private_);
  101792. FLAC__ASSERT(0 != encoder->private_->frame);
  101793. encoder->private_->is_being_deleted = true;
  101794. (void)FLAC__stream_encoder_finish(encoder);
  101795. if(0 != encoder->private_->verify.decoder)
  101796. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  101797. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  101798. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  101799. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  101800. }
  101801. for(i = 0; i < 2; i++) {
  101802. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  101803. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  101804. }
  101805. for(i = 0; i < 2; i++)
  101806. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  101807. FLAC__bitwriter_delete(encoder->private_->frame);
  101808. free(encoder->private_);
  101809. free(encoder->protected_);
  101810. free(encoder);
  101811. }
  101812. /***********************************************************************
  101813. *
  101814. * Public class methods
  101815. *
  101816. ***********************************************************************/
  101817. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  101818. FLAC__StreamEncoder *encoder,
  101819. FLAC__StreamEncoderReadCallback read_callback,
  101820. FLAC__StreamEncoderWriteCallback write_callback,
  101821. FLAC__StreamEncoderSeekCallback seek_callback,
  101822. FLAC__StreamEncoderTellCallback tell_callback,
  101823. FLAC__StreamEncoderMetadataCallback metadata_callback,
  101824. void *client_data,
  101825. FLAC__bool is_ogg
  101826. )
  101827. {
  101828. unsigned i;
  101829. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  101830. FLAC__ASSERT(0 != encoder);
  101831. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  101832. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  101833. #if !FLAC__HAS_OGG
  101834. if(is_ogg)
  101835. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  101836. #endif
  101837. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  101838. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  101839. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  101840. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  101841. if(encoder->protected_->channels != 2) {
  101842. encoder->protected_->do_mid_side_stereo = false;
  101843. encoder->protected_->loose_mid_side_stereo = false;
  101844. }
  101845. else if(!encoder->protected_->do_mid_side_stereo)
  101846. encoder->protected_->loose_mid_side_stereo = false;
  101847. if(encoder->protected_->bits_per_sample >= 32)
  101848. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  101849. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  101850. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  101851. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  101852. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  101853. if(encoder->protected_->blocksize == 0) {
  101854. if(encoder->protected_->max_lpc_order == 0)
  101855. encoder->protected_->blocksize = 1152;
  101856. else
  101857. encoder->protected_->blocksize = 4096;
  101858. }
  101859. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  101860. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  101861. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  101862. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  101863. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  101864. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  101865. if(encoder->protected_->qlp_coeff_precision == 0) {
  101866. if(encoder->protected_->bits_per_sample < 16) {
  101867. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  101868. /* @@@ until then we'll make a guess */
  101869. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  101870. }
  101871. else if(encoder->protected_->bits_per_sample == 16) {
  101872. if(encoder->protected_->blocksize <= 192)
  101873. encoder->protected_->qlp_coeff_precision = 7;
  101874. else if(encoder->protected_->blocksize <= 384)
  101875. encoder->protected_->qlp_coeff_precision = 8;
  101876. else if(encoder->protected_->blocksize <= 576)
  101877. encoder->protected_->qlp_coeff_precision = 9;
  101878. else if(encoder->protected_->blocksize <= 1152)
  101879. encoder->protected_->qlp_coeff_precision = 10;
  101880. else if(encoder->protected_->blocksize <= 2304)
  101881. encoder->protected_->qlp_coeff_precision = 11;
  101882. else if(encoder->protected_->blocksize <= 4608)
  101883. encoder->protected_->qlp_coeff_precision = 12;
  101884. else
  101885. encoder->protected_->qlp_coeff_precision = 13;
  101886. }
  101887. else {
  101888. if(encoder->protected_->blocksize <= 384)
  101889. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  101890. else if(encoder->protected_->blocksize <= 1152)
  101891. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  101892. else
  101893. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  101894. }
  101895. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  101896. }
  101897. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  101898. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  101899. if(encoder->protected_->streamable_subset) {
  101900. if(
  101901. encoder->protected_->blocksize != 192 &&
  101902. encoder->protected_->blocksize != 576 &&
  101903. encoder->protected_->blocksize != 1152 &&
  101904. encoder->protected_->blocksize != 2304 &&
  101905. encoder->protected_->blocksize != 4608 &&
  101906. encoder->protected_->blocksize != 256 &&
  101907. encoder->protected_->blocksize != 512 &&
  101908. encoder->protected_->blocksize != 1024 &&
  101909. encoder->protected_->blocksize != 2048 &&
  101910. encoder->protected_->blocksize != 4096 &&
  101911. encoder->protected_->blocksize != 8192 &&
  101912. encoder->protected_->blocksize != 16384
  101913. )
  101914. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  101915. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  101916. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  101917. if(
  101918. encoder->protected_->bits_per_sample != 8 &&
  101919. encoder->protected_->bits_per_sample != 12 &&
  101920. encoder->protected_->bits_per_sample != 16 &&
  101921. encoder->protected_->bits_per_sample != 20 &&
  101922. encoder->protected_->bits_per_sample != 24
  101923. )
  101924. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  101925. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  101926. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  101927. if(
  101928. encoder->protected_->sample_rate <= 48000 &&
  101929. (
  101930. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  101931. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  101932. )
  101933. ) {
  101934. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  101935. }
  101936. }
  101937. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101938. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  101939. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  101940. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  101941. #if FLAC__HAS_OGG
  101942. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  101943. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  101944. unsigned i;
  101945. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  101946. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  101947. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  101948. for( ; i > 0; i--)
  101949. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  101950. encoder->protected_->metadata[0] = vc;
  101951. break;
  101952. }
  101953. }
  101954. }
  101955. #endif
  101956. /* keep track of any SEEKTABLE block */
  101957. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  101958. unsigned i;
  101959. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  101960. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  101961. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  101962. break; /* take only the first one */
  101963. }
  101964. }
  101965. }
  101966. /* validate metadata */
  101967. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  101968. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  101969. metadata_has_seektable = false;
  101970. metadata_has_vorbis_comment = false;
  101971. metadata_picture_has_type1 = false;
  101972. metadata_picture_has_type2 = false;
  101973. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  101974. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  101975. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  101976. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  101977. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  101978. if(metadata_has_seektable) /* only one is allowed */
  101979. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  101980. metadata_has_seektable = true;
  101981. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  101982. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  101983. }
  101984. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  101985. if(metadata_has_vorbis_comment) /* only one is allowed */
  101986. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  101987. metadata_has_vorbis_comment = true;
  101988. }
  101989. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  101990. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  101991. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  101992. }
  101993. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  101994. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  101995. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  101996. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  101997. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  101998. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  101999. metadata_picture_has_type1 = true;
  102000. /* standard icon must be 32x32 pixel PNG */
  102001. if(
  102002. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  102003. (
  102004. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  102005. m->data.picture.width != 32 ||
  102006. m->data.picture.height != 32
  102007. )
  102008. )
  102009. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102010. }
  102011. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  102012. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  102013. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102014. metadata_picture_has_type2 = true;
  102015. }
  102016. }
  102017. }
  102018. encoder->private_->input_capacity = 0;
  102019. for(i = 0; i < encoder->protected_->channels; i++) {
  102020. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  102021. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102022. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  102023. #endif
  102024. }
  102025. for(i = 0; i < 2; i++) {
  102026. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  102027. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102028. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  102029. #endif
  102030. }
  102031. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102032. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  102033. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  102034. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  102035. #endif
  102036. for(i = 0; i < encoder->protected_->channels; i++) {
  102037. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  102038. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  102039. encoder->private_->best_subframe[i] = 0;
  102040. }
  102041. for(i = 0; i < 2; i++) {
  102042. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  102043. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  102044. encoder->private_->best_subframe_mid_side[i] = 0;
  102045. }
  102046. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  102047. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  102048. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102049. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  102050. #else
  102051. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  102052. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  102053. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  102054. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  102055. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  102056. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  102057. 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);
  102058. #endif
  102059. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  102060. encoder->private_->loose_mid_side_stereo_frames = 1;
  102061. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  102062. encoder->private_->current_sample_number = 0;
  102063. encoder->private_->current_frame_number = 0;
  102064. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  102065. 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? */
  102066. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  102067. /*
  102068. * get the CPU info and set the function pointers
  102069. */
  102070. FLAC__cpu_info(&encoder->private_->cpuinfo);
  102071. /* first default to the non-asm routines */
  102072. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102073. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  102074. #endif
  102075. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  102076. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102077. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  102078. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  102079. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  102080. #endif
  102081. /* now override with asm where appropriate */
  102082. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102083. # ifndef FLAC__NO_ASM
  102084. if(encoder->private_->cpuinfo.use_asm) {
  102085. # ifdef FLAC__CPU_IA32
  102086. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  102087. # ifdef FLAC__HAS_NASM
  102088. if(encoder->private_->cpuinfo.data.ia32.sse) {
  102089. if(encoder->protected_->max_lpc_order < 4)
  102090. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  102091. else if(encoder->protected_->max_lpc_order < 8)
  102092. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  102093. else if(encoder->protected_->max_lpc_order < 12)
  102094. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  102095. else
  102096. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  102097. }
  102098. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  102099. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  102100. else
  102101. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  102102. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  102103. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102104. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  102105. }
  102106. else {
  102107. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102108. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102109. }
  102110. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  102111. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  102112. # endif /* FLAC__HAS_NASM */
  102113. # endif /* FLAC__CPU_IA32 */
  102114. }
  102115. # endif /* !FLAC__NO_ASM */
  102116. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  102117. /* finally override based on wide-ness if necessary */
  102118. if(encoder->private_->use_wide_by_block) {
  102119. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  102120. }
  102121. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  102122. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  102123. #if FLAC__HAS_OGG
  102124. encoder->private_->is_ogg = is_ogg;
  102125. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  102126. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  102127. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102128. }
  102129. #endif
  102130. encoder->private_->read_callback = read_callback;
  102131. encoder->private_->write_callback = write_callback;
  102132. encoder->private_->seek_callback = seek_callback;
  102133. encoder->private_->tell_callback = tell_callback;
  102134. encoder->private_->metadata_callback = metadata_callback;
  102135. encoder->private_->client_data = client_data;
  102136. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  102137. /* the above function sets the state for us in case of an error */
  102138. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102139. }
  102140. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  102141. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  102142. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102143. }
  102144. /*
  102145. * Set up the verify stuff if necessary
  102146. */
  102147. if(encoder->protected_->verify) {
  102148. /*
  102149. * First, set up the fifo which will hold the
  102150. * original signal to compare against
  102151. */
  102152. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  102153. for(i = 0; i < encoder->protected_->channels; i++) {
  102154. 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))) {
  102155. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  102156. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102157. }
  102158. }
  102159. encoder->private_->verify.input_fifo.tail = 0;
  102160. /*
  102161. * Now set up a stream decoder for verification
  102162. */
  102163. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  102164. if(0 == encoder->private_->verify.decoder) {
  102165. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  102166. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102167. }
  102168. 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) {
  102169. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  102170. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102171. }
  102172. }
  102173. encoder->private_->verify.error_stats.absolute_sample = 0;
  102174. encoder->private_->verify.error_stats.frame_number = 0;
  102175. encoder->private_->verify.error_stats.channel = 0;
  102176. encoder->private_->verify.error_stats.sample = 0;
  102177. encoder->private_->verify.error_stats.expected = 0;
  102178. encoder->private_->verify.error_stats.got = 0;
  102179. /*
  102180. * These must be done before we write any metadata, because that
  102181. * calls the write_callback, which uses these values.
  102182. */
  102183. encoder->private_->first_seekpoint_to_check = 0;
  102184. encoder->private_->samples_written = 0;
  102185. encoder->protected_->streaminfo_offset = 0;
  102186. encoder->protected_->seektable_offset = 0;
  102187. encoder->protected_->audio_offset = 0;
  102188. /*
  102189. * write the stream header
  102190. */
  102191. if(encoder->protected_->verify)
  102192. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  102193. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  102194. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102195. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102196. }
  102197. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102198. /* the above function sets the state for us in case of an error */
  102199. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102200. }
  102201. /*
  102202. * write the STREAMINFO metadata block
  102203. */
  102204. if(encoder->protected_->verify)
  102205. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  102206. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  102207. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  102208. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  102209. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  102210. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  102211. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  102212. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  102213. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  102214. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  102215. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  102216. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  102217. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  102218. if(encoder->protected_->do_md5)
  102219. FLAC__MD5Init(&encoder->private_->md5context);
  102220. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  102221. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102222. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102223. }
  102224. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102225. /* the above function sets the state for us in case of an error */
  102226. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102227. }
  102228. /*
  102229. * Now that the STREAMINFO block is written, we can init this to an
  102230. * absurdly-high value...
  102231. */
  102232. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  102233. /* ... and clear this to 0 */
  102234. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  102235. /*
  102236. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  102237. * if not, we will write an empty one (FLAC__add_metadata_block()
  102238. * automatically supplies the vendor string).
  102239. *
  102240. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  102241. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  102242. * true it will have already insured that the metadata list is properly
  102243. * ordered.)
  102244. */
  102245. if(!metadata_has_vorbis_comment) {
  102246. FLAC__StreamMetadata vorbis_comment;
  102247. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  102248. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  102249. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  102250. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  102251. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  102252. vorbis_comment.data.vorbis_comment.num_comments = 0;
  102253. vorbis_comment.data.vorbis_comment.comments = 0;
  102254. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  102255. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102256. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102257. }
  102258. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102259. /* the above function sets the state for us in case of an error */
  102260. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102261. }
  102262. }
  102263. /*
  102264. * write the user's metadata blocks
  102265. */
  102266. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102267. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  102268. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  102269. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102270. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102271. }
  102272. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102273. /* the above function sets the state for us in case of an error */
  102274. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102275. }
  102276. }
  102277. /* now that all the metadata is written, we save the stream offset */
  102278. 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 */
  102279. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  102280. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102281. }
  102282. if(encoder->protected_->verify)
  102283. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  102284. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  102285. }
  102286. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  102287. FLAC__StreamEncoder *encoder,
  102288. FLAC__StreamEncoderWriteCallback write_callback,
  102289. FLAC__StreamEncoderSeekCallback seek_callback,
  102290. FLAC__StreamEncoderTellCallback tell_callback,
  102291. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102292. void *client_data
  102293. )
  102294. {
  102295. return init_stream_internal_enc(
  102296. encoder,
  102297. /*read_callback=*/0,
  102298. write_callback,
  102299. seek_callback,
  102300. tell_callback,
  102301. metadata_callback,
  102302. client_data,
  102303. /*is_ogg=*/false
  102304. );
  102305. }
  102306. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  102307. FLAC__StreamEncoder *encoder,
  102308. FLAC__StreamEncoderReadCallback read_callback,
  102309. FLAC__StreamEncoderWriteCallback write_callback,
  102310. FLAC__StreamEncoderSeekCallback seek_callback,
  102311. FLAC__StreamEncoderTellCallback tell_callback,
  102312. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102313. void *client_data
  102314. )
  102315. {
  102316. return init_stream_internal_enc(
  102317. encoder,
  102318. read_callback,
  102319. write_callback,
  102320. seek_callback,
  102321. tell_callback,
  102322. metadata_callback,
  102323. client_data,
  102324. /*is_ogg=*/true
  102325. );
  102326. }
  102327. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  102328. FLAC__StreamEncoder *encoder,
  102329. FILE *file,
  102330. FLAC__StreamEncoderProgressCallback progress_callback,
  102331. void *client_data,
  102332. FLAC__bool is_ogg
  102333. )
  102334. {
  102335. FLAC__StreamEncoderInitStatus init_status;
  102336. FLAC__ASSERT(0 != encoder);
  102337. FLAC__ASSERT(0 != file);
  102338. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102339. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102340. /* double protection */
  102341. if(file == 0) {
  102342. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  102343. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102344. }
  102345. /*
  102346. * To make sure that our file does not go unclosed after an error, we
  102347. * must assign the FILE pointer before any further error can occur in
  102348. * this routine.
  102349. */
  102350. if(file == stdout)
  102351. file = get_binary_stdout_(); /* just to be safe */
  102352. encoder->private_->file = file;
  102353. encoder->private_->progress_callback = progress_callback;
  102354. encoder->private_->bytes_written = 0;
  102355. encoder->private_->samples_written = 0;
  102356. encoder->private_->frames_written = 0;
  102357. init_status = init_stream_internal_enc(
  102358. encoder,
  102359. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  102360. file_write_callback_,
  102361. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  102362. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  102363. /*metadata_callback=*/0,
  102364. client_data,
  102365. is_ogg
  102366. );
  102367. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  102368. /* the above function sets the state for us in case of an error */
  102369. return init_status;
  102370. }
  102371. {
  102372. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  102373. FLAC__ASSERT(blocksize != 0);
  102374. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  102375. }
  102376. return init_status;
  102377. }
  102378. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  102379. FLAC__StreamEncoder *encoder,
  102380. FILE *file,
  102381. FLAC__StreamEncoderProgressCallback progress_callback,
  102382. void *client_data
  102383. )
  102384. {
  102385. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  102386. }
  102387. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  102388. FLAC__StreamEncoder *encoder,
  102389. FILE *file,
  102390. FLAC__StreamEncoderProgressCallback progress_callback,
  102391. void *client_data
  102392. )
  102393. {
  102394. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  102395. }
  102396. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  102397. FLAC__StreamEncoder *encoder,
  102398. const char *filename,
  102399. FLAC__StreamEncoderProgressCallback progress_callback,
  102400. void *client_data,
  102401. FLAC__bool is_ogg
  102402. )
  102403. {
  102404. FILE *file;
  102405. FLAC__ASSERT(0 != encoder);
  102406. /*
  102407. * To make sure that our file does not go unclosed after an error, we
  102408. * have to do the same entrance checks here that are later performed
  102409. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  102410. */
  102411. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102412. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102413. file = filename? fopen(filename, "w+b") : stdout;
  102414. if(file == 0) {
  102415. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  102416. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102417. }
  102418. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  102419. }
  102420. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  102421. FLAC__StreamEncoder *encoder,
  102422. const char *filename,
  102423. FLAC__StreamEncoderProgressCallback progress_callback,
  102424. void *client_data
  102425. )
  102426. {
  102427. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  102428. }
  102429. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  102430. FLAC__StreamEncoder *encoder,
  102431. const char *filename,
  102432. FLAC__StreamEncoderProgressCallback progress_callback,
  102433. void *client_data
  102434. )
  102435. {
  102436. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  102437. }
  102438. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  102439. {
  102440. FLAC__bool error = false;
  102441. FLAC__ASSERT(0 != encoder);
  102442. FLAC__ASSERT(0 != encoder->private_);
  102443. FLAC__ASSERT(0 != encoder->protected_);
  102444. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  102445. return true;
  102446. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  102447. if(encoder->private_->current_sample_number != 0) {
  102448. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  102449. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  102450. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  102451. error = true;
  102452. }
  102453. }
  102454. if(encoder->protected_->do_md5)
  102455. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  102456. if(!encoder->private_->is_being_deleted) {
  102457. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  102458. if(encoder->private_->seek_callback) {
  102459. #if FLAC__HAS_OGG
  102460. if(encoder->private_->is_ogg)
  102461. update_ogg_metadata_(encoder);
  102462. else
  102463. #endif
  102464. update_metadata_(encoder);
  102465. /* check if an error occurred while updating metadata */
  102466. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  102467. error = true;
  102468. }
  102469. if(encoder->private_->metadata_callback)
  102470. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  102471. }
  102472. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  102473. if(!error)
  102474. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  102475. error = true;
  102476. }
  102477. }
  102478. if(0 != encoder->private_->file) {
  102479. if(encoder->private_->file != stdout)
  102480. fclose(encoder->private_->file);
  102481. encoder->private_->file = 0;
  102482. }
  102483. #if FLAC__HAS_OGG
  102484. if(encoder->private_->is_ogg)
  102485. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  102486. #endif
  102487. free_(encoder);
  102488. set_defaults_enc(encoder);
  102489. if(!error)
  102490. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  102491. return !error;
  102492. }
  102493. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  102494. {
  102495. FLAC__ASSERT(0 != encoder);
  102496. FLAC__ASSERT(0 != encoder->private_);
  102497. FLAC__ASSERT(0 != encoder->protected_);
  102498. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102499. return false;
  102500. #if FLAC__HAS_OGG
  102501. /* can't check encoder->private_->is_ogg since that's not set until init time */
  102502. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  102503. return true;
  102504. #else
  102505. (void)value;
  102506. return false;
  102507. #endif
  102508. }
  102509. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102510. {
  102511. FLAC__ASSERT(0 != encoder);
  102512. FLAC__ASSERT(0 != encoder->private_);
  102513. FLAC__ASSERT(0 != encoder->protected_);
  102514. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102515. return false;
  102516. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  102517. encoder->protected_->verify = value;
  102518. #endif
  102519. return true;
  102520. }
  102521. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102522. {
  102523. FLAC__ASSERT(0 != encoder);
  102524. FLAC__ASSERT(0 != encoder->private_);
  102525. FLAC__ASSERT(0 != encoder->protected_);
  102526. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102527. return false;
  102528. encoder->protected_->streamable_subset = value;
  102529. return true;
  102530. }
  102531. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102532. {
  102533. FLAC__ASSERT(0 != encoder);
  102534. FLAC__ASSERT(0 != encoder->private_);
  102535. FLAC__ASSERT(0 != encoder->protected_);
  102536. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102537. return false;
  102538. encoder->protected_->do_md5 = value;
  102539. return true;
  102540. }
  102541. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  102542. {
  102543. FLAC__ASSERT(0 != encoder);
  102544. FLAC__ASSERT(0 != encoder->private_);
  102545. FLAC__ASSERT(0 != encoder->protected_);
  102546. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102547. return false;
  102548. encoder->protected_->channels = value;
  102549. return true;
  102550. }
  102551. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  102552. {
  102553. FLAC__ASSERT(0 != encoder);
  102554. FLAC__ASSERT(0 != encoder->private_);
  102555. FLAC__ASSERT(0 != encoder->protected_);
  102556. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102557. return false;
  102558. encoder->protected_->bits_per_sample = value;
  102559. return true;
  102560. }
  102561. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  102562. {
  102563. FLAC__ASSERT(0 != encoder);
  102564. FLAC__ASSERT(0 != encoder->private_);
  102565. FLAC__ASSERT(0 != encoder->protected_);
  102566. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102567. return false;
  102568. encoder->protected_->sample_rate = value;
  102569. return true;
  102570. }
  102571. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  102572. {
  102573. FLAC__bool ok = true;
  102574. FLAC__ASSERT(0 != encoder);
  102575. FLAC__ASSERT(0 != encoder->private_);
  102576. FLAC__ASSERT(0 != encoder->protected_);
  102577. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102578. return false;
  102579. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  102580. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  102581. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  102582. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  102583. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102584. #if 0
  102585. /* was: */
  102586. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  102587. /* but it's too hard to specify the string in a locale-specific way */
  102588. #else
  102589. encoder->protected_->num_apodizations = 1;
  102590. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  102591. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  102592. #endif
  102593. #endif
  102594. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  102595. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  102596. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  102597. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  102598. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  102599. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  102600. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  102601. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  102602. return ok;
  102603. }
  102604. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  102605. {
  102606. FLAC__ASSERT(0 != encoder);
  102607. FLAC__ASSERT(0 != encoder->private_);
  102608. FLAC__ASSERT(0 != encoder->protected_);
  102609. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102610. return false;
  102611. encoder->protected_->blocksize = value;
  102612. return true;
  102613. }
  102614. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102615. {
  102616. FLAC__ASSERT(0 != encoder);
  102617. FLAC__ASSERT(0 != encoder->private_);
  102618. FLAC__ASSERT(0 != encoder->protected_);
  102619. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102620. return false;
  102621. encoder->protected_->do_mid_side_stereo = value;
  102622. return true;
  102623. }
  102624. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102625. {
  102626. FLAC__ASSERT(0 != encoder);
  102627. FLAC__ASSERT(0 != encoder->private_);
  102628. FLAC__ASSERT(0 != encoder->protected_);
  102629. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102630. return false;
  102631. encoder->protected_->loose_mid_side_stereo = value;
  102632. return true;
  102633. }
  102634. /*@@@@add to tests*/
  102635. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  102636. {
  102637. FLAC__ASSERT(0 != encoder);
  102638. FLAC__ASSERT(0 != encoder->private_);
  102639. FLAC__ASSERT(0 != encoder->protected_);
  102640. FLAC__ASSERT(0 != specification);
  102641. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102642. return false;
  102643. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  102644. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  102645. #else
  102646. encoder->protected_->num_apodizations = 0;
  102647. while(1) {
  102648. const char *s = strchr(specification, ';');
  102649. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  102650. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  102651. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  102652. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  102653. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  102654. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  102655. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  102656. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  102657. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  102658. else if(n==6 && 0 == strncmp("connes" , specification, n))
  102659. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  102660. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  102661. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  102662. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  102663. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  102664. if (stddev > 0.0 && stddev <= 0.5) {
  102665. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  102666. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  102667. }
  102668. }
  102669. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  102670. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  102671. else if(n==4 && 0 == strncmp("hann" , specification, n))
  102672. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  102673. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  102674. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  102675. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  102676. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  102677. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  102678. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  102679. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  102680. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  102681. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  102682. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  102683. if (p >= 0.0 && p <= 1.0) {
  102684. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  102685. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  102686. }
  102687. }
  102688. else if(n==5 && 0 == strncmp("welch" , specification, n))
  102689. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  102690. if (encoder->protected_->num_apodizations == 32)
  102691. break;
  102692. if (s)
  102693. specification = s+1;
  102694. else
  102695. break;
  102696. }
  102697. if(encoder->protected_->num_apodizations == 0) {
  102698. encoder->protected_->num_apodizations = 1;
  102699. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  102700. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  102701. }
  102702. #endif
  102703. return true;
  102704. }
  102705. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  102706. {
  102707. FLAC__ASSERT(0 != encoder);
  102708. FLAC__ASSERT(0 != encoder->private_);
  102709. FLAC__ASSERT(0 != encoder->protected_);
  102710. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102711. return false;
  102712. encoder->protected_->max_lpc_order = value;
  102713. return true;
  102714. }
  102715. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  102716. {
  102717. FLAC__ASSERT(0 != encoder);
  102718. FLAC__ASSERT(0 != encoder->private_);
  102719. FLAC__ASSERT(0 != encoder->protected_);
  102720. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102721. return false;
  102722. encoder->protected_->qlp_coeff_precision = value;
  102723. return true;
  102724. }
  102725. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102726. {
  102727. FLAC__ASSERT(0 != encoder);
  102728. FLAC__ASSERT(0 != encoder->private_);
  102729. FLAC__ASSERT(0 != encoder->protected_);
  102730. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102731. return false;
  102732. encoder->protected_->do_qlp_coeff_prec_search = value;
  102733. return true;
  102734. }
  102735. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102736. {
  102737. FLAC__ASSERT(0 != encoder);
  102738. FLAC__ASSERT(0 != encoder->private_);
  102739. FLAC__ASSERT(0 != encoder->protected_);
  102740. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102741. return false;
  102742. #if 0
  102743. /*@@@ deprecated: */
  102744. encoder->protected_->do_escape_coding = value;
  102745. #else
  102746. (void)value;
  102747. #endif
  102748. return true;
  102749. }
  102750. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102751. {
  102752. FLAC__ASSERT(0 != encoder);
  102753. FLAC__ASSERT(0 != encoder->private_);
  102754. FLAC__ASSERT(0 != encoder->protected_);
  102755. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102756. return false;
  102757. encoder->protected_->do_exhaustive_model_search = value;
  102758. return true;
  102759. }
  102760. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  102761. {
  102762. FLAC__ASSERT(0 != encoder);
  102763. FLAC__ASSERT(0 != encoder->private_);
  102764. FLAC__ASSERT(0 != encoder->protected_);
  102765. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102766. return false;
  102767. encoder->protected_->min_residual_partition_order = value;
  102768. return true;
  102769. }
  102770. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  102771. {
  102772. FLAC__ASSERT(0 != encoder);
  102773. FLAC__ASSERT(0 != encoder->private_);
  102774. FLAC__ASSERT(0 != encoder->protected_);
  102775. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102776. return false;
  102777. encoder->protected_->max_residual_partition_order = value;
  102778. return true;
  102779. }
  102780. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  102781. {
  102782. FLAC__ASSERT(0 != encoder);
  102783. FLAC__ASSERT(0 != encoder->private_);
  102784. FLAC__ASSERT(0 != encoder->protected_);
  102785. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102786. return false;
  102787. #if 0
  102788. /*@@@ deprecated: */
  102789. encoder->protected_->rice_parameter_search_dist = value;
  102790. #else
  102791. (void)value;
  102792. #endif
  102793. return true;
  102794. }
  102795. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  102796. {
  102797. FLAC__ASSERT(0 != encoder);
  102798. FLAC__ASSERT(0 != encoder->private_);
  102799. FLAC__ASSERT(0 != encoder->protected_);
  102800. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102801. return false;
  102802. encoder->protected_->total_samples_estimate = value;
  102803. return true;
  102804. }
  102805. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  102806. {
  102807. FLAC__ASSERT(0 != encoder);
  102808. FLAC__ASSERT(0 != encoder->private_);
  102809. FLAC__ASSERT(0 != encoder->protected_);
  102810. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102811. return false;
  102812. if(0 == metadata)
  102813. num_blocks = 0;
  102814. if(0 == num_blocks)
  102815. metadata = 0;
  102816. /* realloc() does not do exactly what we want so... */
  102817. if(encoder->protected_->metadata) {
  102818. free(encoder->protected_->metadata);
  102819. encoder->protected_->metadata = 0;
  102820. encoder->protected_->num_metadata_blocks = 0;
  102821. }
  102822. if(num_blocks) {
  102823. FLAC__StreamMetadata **m;
  102824. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  102825. return false;
  102826. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  102827. encoder->protected_->metadata = m;
  102828. encoder->protected_->num_metadata_blocks = num_blocks;
  102829. }
  102830. #if FLAC__HAS_OGG
  102831. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  102832. return false;
  102833. #endif
  102834. return true;
  102835. }
  102836. /*
  102837. * These three functions are not static, but not publically exposed in
  102838. * include/FLAC/ either. They are used by the test suite.
  102839. */
  102840. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102841. {
  102842. FLAC__ASSERT(0 != encoder);
  102843. FLAC__ASSERT(0 != encoder->private_);
  102844. FLAC__ASSERT(0 != encoder->protected_);
  102845. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102846. return false;
  102847. encoder->private_->disable_constant_subframes = value;
  102848. return true;
  102849. }
  102850. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102851. {
  102852. FLAC__ASSERT(0 != encoder);
  102853. FLAC__ASSERT(0 != encoder->private_);
  102854. FLAC__ASSERT(0 != encoder->protected_);
  102855. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102856. return false;
  102857. encoder->private_->disable_fixed_subframes = value;
  102858. return true;
  102859. }
  102860. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  102861. {
  102862. FLAC__ASSERT(0 != encoder);
  102863. FLAC__ASSERT(0 != encoder->private_);
  102864. FLAC__ASSERT(0 != encoder->protected_);
  102865. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102866. return false;
  102867. encoder->private_->disable_verbatim_subframes = value;
  102868. return true;
  102869. }
  102870. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  102871. {
  102872. FLAC__ASSERT(0 != encoder);
  102873. FLAC__ASSERT(0 != encoder->private_);
  102874. FLAC__ASSERT(0 != encoder->protected_);
  102875. return encoder->protected_->state;
  102876. }
  102877. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  102878. {
  102879. FLAC__ASSERT(0 != encoder);
  102880. FLAC__ASSERT(0 != encoder->private_);
  102881. FLAC__ASSERT(0 != encoder->protected_);
  102882. if(encoder->protected_->verify)
  102883. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  102884. else
  102885. return FLAC__STREAM_DECODER_UNINITIALIZED;
  102886. }
  102887. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  102888. {
  102889. FLAC__ASSERT(0 != encoder);
  102890. FLAC__ASSERT(0 != encoder->private_);
  102891. FLAC__ASSERT(0 != encoder->protected_);
  102892. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  102893. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  102894. else
  102895. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  102896. }
  102897. 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)
  102898. {
  102899. FLAC__ASSERT(0 != encoder);
  102900. FLAC__ASSERT(0 != encoder->private_);
  102901. FLAC__ASSERT(0 != encoder->protected_);
  102902. if(0 != absolute_sample)
  102903. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  102904. if(0 != frame_number)
  102905. *frame_number = encoder->private_->verify.error_stats.frame_number;
  102906. if(0 != channel)
  102907. *channel = encoder->private_->verify.error_stats.channel;
  102908. if(0 != sample)
  102909. *sample = encoder->private_->verify.error_stats.sample;
  102910. if(0 != expected)
  102911. *expected = encoder->private_->verify.error_stats.expected;
  102912. if(0 != got)
  102913. *got = encoder->private_->verify.error_stats.got;
  102914. }
  102915. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
  102916. {
  102917. FLAC__ASSERT(0 != encoder);
  102918. FLAC__ASSERT(0 != encoder->private_);
  102919. FLAC__ASSERT(0 != encoder->protected_);
  102920. return encoder->protected_->verify;
  102921. }
  102922. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
  102923. {
  102924. FLAC__ASSERT(0 != encoder);
  102925. FLAC__ASSERT(0 != encoder->private_);
  102926. FLAC__ASSERT(0 != encoder->protected_);
  102927. return encoder->protected_->streamable_subset;
  102928. }
  102929. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
  102930. {
  102931. FLAC__ASSERT(0 != encoder);
  102932. FLAC__ASSERT(0 != encoder->private_);
  102933. FLAC__ASSERT(0 != encoder->protected_);
  102934. return encoder->protected_->do_md5;
  102935. }
  102936. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
  102937. {
  102938. FLAC__ASSERT(0 != encoder);
  102939. FLAC__ASSERT(0 != encoder->private_);
  102940. FLAC__ASSERT(0 != encoder->protected_);
  102941. return encoder->protected_->channels;
  102942. }
  102943. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
  102944. {
  102945. FLAC__ASSERT(0 != encoder);
  102946. FLAC__ASSERT(0 != encoder->private_);
  102947. FLAC__ASSERT(0 != encoder->protected_);
  102948. return encoder->protected_->bits_per_sample;
  102949. }
  102950. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
  102951. {
  102952. FLAC__ASSERT(0 != encoder);
  102953. FLAC__ASSERT(0 != encoder->private_);
  102954. FLAC__ASSERT(0 != encoder->protected_);
  102955. return encoder->protected_->sample_rate;
  102956. }
  102957. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
  102958. {
  102959. FLAC__ASSERT(0 != encoder);
  102960. FLAC__ASSERT(0 != encoder->private_);
  102961. FLAC__ASSERT(0 != encoder->protected_);
  102962. return encoder->protected_->blocksize;
  102963. }
  102964. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  102965. {
  102966. FLAC__ASSERT(0 != encoder);
  102967. FLAC__ASSERT(0 != encoder->private_);
  102968. FLAC__ASSERT(0 != encoder->protected_);
  102969. return encoder->protected_->do_mid_side_stereo;
  102970. }
  102971. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  102972. {
  102973. FLAC__ASSERT(0 != encoder);
  102974. FLAC__ASSERT(0 != encoder->private_);
  102975. FLAC__ASSERT(0 != encoder->protected_);
  102976. return encoder->protected_->loose_mid_side_stereo;
  102977. }
  102978. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
  102979. {
  102980. FLAC__ASSERT(0 != encoder);
  102981. FLAC__ASSERT(0 != encoder->private_);
  102982. FLAC__ASSERT(0 != encoder->protected_);
  102983. return encoder->protected_->max_lpc_order;
  102984. }
  102985. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
  102986. {
  102987. FLAC__ASSERT(0 != encoder);
  102988. FLAC__ASSERT(0 != encoder->private_);
  102989. FLAC__ASSERT(0 != encoder->protected_);
  102990. return encoder->protected_->qlp_coeff_precision;
  102991. }
  102992. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
  102993. {
  102994. FLAC__ASSERT(0 != encoder);
  102995. FLAC__ASSERT(0 != encoder->private_);
  102996. FLAC__ASSERT(0 != encoder->protected_);
  102997. return encoder->protected_->do_qlp_coeff_prec_search;
  102998. }
  102999. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  103000. {
  103001. FLAC__ASSERT(0 != encoder);
  103002. FLAC__ASSERT(0 != encoder->private_);
  103003. FLAC__ASSERT(0 != encoder->protected_);
  103004. return encoder->protected_->do_escape_coding;
  103005. }
  103006. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  103007. {
  103008. FLAC__ASSERT(0 != encoder);
  103009. FLAC__ASSERT(0 != encoder->private_);
  103010. FLAC__ASSERT(0 != encoder->protected_);
  103011. return encoder->protected_->do_exhaustive_model_search;
  103012. }
  103013. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  103014. {
  103015. FLAC__ASSERT(0 != encoder);
  103016. FLAC__ASSERT(0 != encoder->private_);
  103017. FLAC__ASSERT(0 != encoder->protected_);
  103018. return encoder->protected_->min_residual_partition_order;
  103019. }
  103020. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  103021. {
  103022. FLAC__ASSERT(0 != encoder);
  103023. FLAC__ASSERT(0 != encoder->private_);
  103024. FLAC__ASSERT(0 != encoder->protected_);
  103025. return encoder->protected_->max_residual_partition_order;
  103026. }
  103027. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  103028. {
  103029. FLAC__ASSERT(0 != encoder);
  103030. FLAC__ASSERT(0 != encoder->private_);
  103031. FLAC__ASSERT(0 != encoder->protected_);
  103032. return encoder->protected_->rice_parameter_search_dist;
  103033. }
  103034. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  103035. {
  103036. FLAC__ASSERT(0 != encoder);
  103037. FLAC__ASSERT(0 != encoder->private_);
  103038. FLAC__ASSERT(0 != encoder->protected_);
  103039. return encoder->protected_->total_samples_estimate;
  103040. }
  103041. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  103042. {
  103043. unsigned i, j = 0, channel;
  103044. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  103045. FLAC__ASSERT(0 != encoder);
  103046. FLAC__ASSERT(0 != encoder->private_);
  103047. FLAC__ASSERT(0 != encoder->protected_);
  103048. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103049. do {
  103050. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  103051. if(encoder->protected_->verify)
  103052. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  103053. for(channel = 0; channel < channels; channel++)
  103054. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  103055. if(encoder->protected_->do_mid_side_stereo) {
  103056. FLAC__ASSERT(channels == 2);
  103057. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103058. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103059. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  103060. 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' ! */
  103061. }
  103062. }
  103063. else
  103064. j += n;
  103065. encoder->private_->current_sample_number += n;
  103066. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103067. if(encoder->private_->current_sample_number > blocksize) {
  103068. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  103069. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103070. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103071. return false;
  103072. /* move unprocessed overread samples to beginnings of arrays */
  103073. for(channel = 0; channel < channels; channel++)
  103074. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  103075. if(encoder->protected_->do_mid_side_stereo) {
  103076. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  103077. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  103078. }
  103079. encoder->private_->current_sample_number = 1;
  103080. }
  103081. } while(j < samples);
  103082. return true;
  103083. }
  103084. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  103085. {
  103086. unsigned i, j, k, channel;
  103087. FLAC__int32 x, mid, side;
  103088. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  103089. FLAC__ASSERT(0 != encoder);
  103090. FLAC__ASSERT(0 != encoder->private_);
  103091. FLAC__ASSERT(0 != encoder->protected_);
  103092. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103093. j = k = 0;
  103094. /*
  103095. * we have several flavors of the same basic loop, optimized for
  103096. * different conditions:
  103097. */
  103098. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  103099. /*
  103100. * stereo coding: unroll channel loop
  103101. */
  103102. do {
  103103. if(encoder->protected_->verify)
  103104. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  103105. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103106. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103107. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  103108. x = buffer[k++];
  103109. encoder->private_->integer_signal[1][i] = x;
  103110. mid += x;
  103111. side -= x;
  103112. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  103113. encoder->private_->integer_signal_mid_side[1][i] = side;
  103114. encoder->private_->integer_signal_mid_side[0][i] = mid;
  103115. }
  103116. encoder->private_->current_sample_number = i;
  103117. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103118. if(i > blocksize) {
  103119. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103120. return false;
  103121. /* move unprocessed overread samples to beginnings of arrays */
  103122. FLAC__ASSERT(i == blocksize+OVERREAD_);
  103123. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103124. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  103125. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  103126. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  103127. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  103128. encoder->private_->current_sample_number = 1;
  103129. }
  103130. } while(j < samples);
  103131. }
  103132. else {
  103133. /*
  103134. * independent channel coding: buffer each channel in inner loop
  103135. */
  103136. do {
  103137. if(encoder->protected_->verify)
  103138. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  103139. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103140. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103141. for(channel = 0; channel < channels; channel++)
  103142. encoder->private_->integer_signal[channel][i] = buffer[k++];
  103143. }
  103144. encoder->private_->current_sample_number = i;
  103145. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103146. if(i > blocksize) {
  103147. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103148. return false;
  103149. /* move unprocessed overread samples to beginnings of arrays */
  103150. FLAC__ASSERT(i == blocksize+OVERREAD_);
  103151. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103152. for(channel = 0; channel < channels; channel++)
  103153. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  103154. encoder->private_->current_sample_number = 1;
  103155. }
  103156. } while(j < samples);
  103157. }
  103158. return true;
  103159. }
  103160. /***********************************************************************
  103161. *
  103162. * Private class methods
  103163. *
  103164. ***********************************************************************/
  103165. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  103166. {
  103167. FLAC__ASSERT(0 != encoder);
  103168. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  103169. encoder->protected_->verify = true;
  103170. #else
  103171. encoder->protected_->verify = false;
  103172. #endif
  103173. encoder->protected_->streamable_subset = true;
  103174. encoder->protected_->do_md5 = true;
  103175. encoder->protected_->do_mid_side_stereo = false;
  103176. encoder->protected_->loose_mid_side_stereo = false;
  103177. encoder->protected_->channels = 2;
  103178. encoder->protected_->bits_per_sample = 16;
  103179. encoder->protected_->sample_rate = 44100;
  103180. encoder->protected_->blocksize = 0;
  103181. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103182. encoder->protected_->num_apodizations = 1;
  103183. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103184. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103185. #endif
  103186. encoder->protected_->max_lpc_order = 0;
  103187. encoder->protected_->qlp_coeff_precision = 0;
  103188. encoder->protected_->do_qlp_coeff_prec_search = false;
  103189. encoder->protected_->do_exhaustive_model_search = false;
  103190. encoder->protected_->do_escape_coding = false;
  103191. encoder->protected_->min_residual_partition_order = 0;
  103192. encoder->protected_->max_residual_partition_order = 0;
  103193. encoder->protected_->rice_parameter_search_dist = 0;
  103194. encoder->protected_->total_samples_estimate = 0;
  103195. encoder->protected_->metadata = 0;
  103196. encoder->protected_->num_metadata_blocks = 0;
  103197. encoder->private_->seek_table = 0;
  103198. encoder->private_->disable_constant_subframes = false;
  103199. encoder->private_->disable_fixed_subframes = false;
  103200. encoder->private_->disable_verbatim_subframes = false;
  103201. #if FLAC__HAS_OGG
  103202. encoder->private_->is_ogg = false;
  103203. #endif
  103204. encoder->private_->read_callback = 0;
  103205. encoder->private_->write_callback = 0;
  103206. encoder->private_->seek_callback = 0;
  103207. encoder->private_->tell_callback = 0;
  103208. encoder->private_->metadata_callback = 0;
  103209. encoder->private_->progress_callback = 0;
  103210. encoder->private_->client_data = 0;
  103211. #if FLAC__HAS_OGG
  103212. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  103213. #endif
  103214. }
  103215. void free_(FLAC__StreamEncoder *encoder)
  103216. {
  103217. unsigned i, channel;
  103218. FLAC__ASSERT(0 != encoder);
  103219. if(encoder->protected_->metadata) {
  103220. free(encoder->protected_->metadata);
  103221. encoder->protected_->metadata = 0;
  103222. encoder->protected_->num_metadata_blocks = 0;
  103223. }
  103224. for(i = 0; i < encoder->protected_->channels; i++) {
  103225. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  103226. free(encoder->private_->integer_signal_unaligned[i]);
  103227. encoder->private_->integer_signal_unaligned[i] = 0;
  103228. }
  103229. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103230. if(0 != encoder->private_->real_signal_unaligned[i]) {
  103231. free(encoder->private_->real_signal_unaligned[i]);
  103232. encoder->private_->real_signal_unaligned[i] = 0;
  103233. }
  103234. #endif
  103235. }
  103236. for(i = 0; i < 2; i++) {
  103237. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  103238. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  103239. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  103240. }
  103241. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103242. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  103243. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  103244. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  103245. }
  103246. #endif
  103247. }
  103248. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103249. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  103250. if(0 != encoder->private_->window_unaligned[i]) {
  103251. free(encoder->private_->window_unaligned[i]);
  103252. encoder->private_->window_unaligned[i] = 0;
  103253. }
  103254. }
  103255. if(0 != encoder->private_->windowed_signal_unaligned) {
  103256. free(encoder->private_->windowed_signal_unaligned);
  103257. encoder->private_->windowed_signal_unaligned = 0;
  103258. }
  103259. #endif
  103260. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  103261. for(i = 0; i < 2; i++) {
  103262. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  103263. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  103264. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  103265. }
  103266. }
  103267. }
  103268. for(channel = 0; channel < 2; channel++) {
  103269. for(i = 0; i < 2; i++) {
  103270. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  103271. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  103272. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  103273. }
  103274. }
  103275. }
  103276. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  103277. free(encoder->private_->abs_residual_partition_sums_unaligned);
  103278. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  103279. }
  103280. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  103281. free(encoder->private_->raw_bits_per_partition_unaligned);
  103282. encoder->private_->raw_bits_per_partition_unaligned = 0;
  103283. }
  103284. if(encoder->protected_->verify) {
  103285. for(i = 0; i < encoder->protected_->channels; i++) {
  103286. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  103287. free(encoder->private_->verify.input_fifo.data[i]);
  103288. encoder->private_->verify.input_fifo.data[i] = 0;
  103289. }
  103290. }
  103291. }
  103292. FLAC__bitwriter_free(encoder->private_->frame);
  103293. }
  103294. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  103295. {
  103296. FLAC__bool ok;
  103297. unsigned i, channel;
  103298. FLAC__ASSERT(new_blocksize > 0);
  103299. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103300. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  103301. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  103302. if(new_blocksize <= encoder->private_->input_capacity)
  103303. return true;
  103304. ok = true;
  103305. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  103306. * requires that the input arrays (in our case the integer signals)
  103307. * have a buffer of up to 3 zeroes in front (at negative indices) for
  103308. * alignment purposes; we use 4 in front to keep the data well-aligned.
  103309. */
  103310. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  103311. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  103312. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  103313. encoder->private_->integer_signal[i] += 4;
  103314. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103315. #if 0 /* @@@ currently unused */
  103316. if(encoder->protected_->max_lpc_order > 0)
  103317. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  103318. #endif
  103319. #endif
  103320. }
  103321. for(i = 0; ok && i < 2; i++) {
  103322. 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]);
  103323. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  103324. encoder->private_->integer_signal_mid_side[i] += 4;
  103325. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103326. #if 0 /* @@@ currently unused */
  103327. if(encoder->protected_->max_lpc_order > 0)
  103328. 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]);
  103329. #endif
  103330. #endif
  103331. }
  103332. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103333. if(ok && encoder->protected_->max_lpc_order > 0) {
  103334. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  103335. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  103336. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  103337. }
  103338. #endif
  103339. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  103340. for(i = 0; ok && i < 2; i++) {
  103341. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  103342. }
  103343. }
  103344. for(channel = 0; ok && channel < 2; channel++) {
  103345. for(i = 0; ok && i < 2; i++) {
  103346. 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]);
  103347. }
  103348. }
  103349. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  103350. /*@@@ 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) */
  103351. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  103352. if(encoder->protected_->do_escape_coding)
  103353. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  103354. /* now adjust the windows if the blocksize has changed */
  103355. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103356. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  103357. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  103358. switch(encoder->protected_->apodizations[i].type) {
  103359. case FLAC__APODIZATION_BARTLETT:
  103360. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  103361. break;
  103362. case FLAC__APODIZATION_BARTLETT_HANN:
  103363. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  103364. break;
  103365. case FLAC__APODIZATION_BLACKMAN:
  103366. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  103367. break;
  103368. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  103369. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  103370. break;
  103371. case FLAC__APODIZATION_CONNES:
  103372. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  103373. break;
  103374. case FLAC__APODIZATION_FLATTOP:
  103375. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  103376. break;
  103377. case FLAC__APODIZATION_GAUSS:
  103378. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  103379. break;
  103380. case FLAC__APODIZATION_HAMMING:
  103381. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  103382. break;
  103383. case FLAC__APODIZATION_HANN:
  103384. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  103385. break;
  103386. case FLAC__APODIZATION_KAISER_BESSEL:
  103387. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  103388. break;
  103389. case FLAC__APODIZATION_NUTTALL:
  103390. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  103391. break;
  103392. case FLAC__APODIZATION_RECTANGLE:
  103393. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  103394. break;
  103395. case FLAC__APODIZATION_TRIANGLE:
  103396. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  103397. break;
  103398. case FLAC__APODIZATION_TUKEY:
  103399. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  103400. break;
  103401. case FLAC__APODIZATION_WELCH:
  103402. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  103403. break;
  103404. default:
  103405. FLAC__ASSERT(0);
  103406. /* double protection */
  103407. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  103408. break;
  103409. }
  103410. }
  103411. }
  103412. #endif
  103413. if(ok)
  103414. encoder->private_->input_capacity = new_blocksize;
  103415. else
  103416. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103417. return ok;
  103418. }
  103419. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  103420. {
  103421. const FLAC__byte *buffer;
  103422. size_t bytes;
  103423. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  103424. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  103425. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103426. return false;
  103427. }
  103428. if(encoder->protected_->verify) {
  103429. encoder->private_->verify.output.data = buffer;
  103430. encoder->private_->verify.output.bytes = bytes;
  103431. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  103432. encoder->private_->verify.needs_magic_hack = true;
  103433. }
  103434. else {
  103435. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  103436. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  103437. FLAC__bitwriter_clear(encoder->private_->frame);
  103438. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  103439. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  103440. return false;
  103441. }
  103442. }
  103443. }
  103444. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103445. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  103446. FLAC__bitwriter_clear(encoder->private_->frame);
  103447. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103448. return false;
  103449. }
  103450. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  103451. FLAC__bitwriter_clear(encoder->private_->frame);
  103452. if(samples > 0) {
  103453. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  103454. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  103455. }
  103456. return true;
  103457. }
  103458. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  103459. {
  103460. FLAC__StreamEncoderWriteStatus status;
  103461. FLAC__uint64 output_position = 0;
  103462. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  103463. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  103464. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103465. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  103466. }
  103467. /*
  103468. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  103469. */
  103470. if(samples == 0) {
  103471. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  103472. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  103473. encoder->protected_->streaminfo_offset = output_position;
  103474. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  103475. encoder->protected_->seektable_offset = output_position;
  103476. }
  103477. /*
  103478. * Mark the current seek point if hit (if audio_offset == 0 that
  103479. * means we're still writing metadata and haven't hit the first
  103480. * frame yet)
  103481. */
  103482. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  103483. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  103484. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  103485. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  103486. FLAC__uint64 test_sample;
  103487. unsigned i;
  103488. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  103489. test_sample = encoder->private_->seek_table->points[i].sample_number;
  103490. if(test_sample > frame_last_sample) {
  103491. break;
  103492. }
  103493. else if(test_sample >= frame_first_sample) {
  103494. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  103495. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  103496. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  103497. encoder->private_->first_seekpoint_to_check++;
  103498. /* DO NOT: "break;" and here's why:
  103499. * The seektable template may contain more than one target
  103500. * sample for any given frame; we will keep looping, generating
  103501. * duplicate seekpoints for them, and we'll clean it up later,
  103502. * just before writing the seektable back to the metadata.
  103503. */
  103504. }
  103505. else {
  103506. encoder->private_->first_seekpoint_to_check++;
  103507. }
  103508. }
  103509. }
  103510. #if FLAC__HAS_OGG
  103511. if(encoder->private_->is_ogg) {
  103512. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  103513. &encoder->protected_->ogg_encoder_aspect,
  103514. buffer,
  103515. bytes,
  103516. samples,
  103517. encoder->private_->current_frame_number,
  103518. is_last_block,
  103519. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  103520. encoder,
  103521. encoder->private_->client_data
  103522. );
  103523. }
  103524. else
  103525. #endif
  103526. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  103527. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103528. encoder->private_->bytes_written += bytes;
  103529. encoder->private_->samples_written += samples;
  103530. /* we keep a high watermark on the number of frames written because
  103531. * when the encoder goes back to write metadata, 'current_frame'
  103532. * will drop back to 0.
  103533. */
  103534. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  103535. }
  103536. else
  103537. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103538. return status;
  103539. }
  103540. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  103541. void update_metadata_(const FLAC__StreamEncoder *encoder)
  103542. {
  103543. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  103544. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  103545. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  103546. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  103547. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  103548. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  103549. FLAC__StreamEncoderSeekStatus seek_status;
  103550. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  103551. /* All this is based on intimate knowledge of the stream header
  103552. * layout, but a change to the header format that would break this
  103553. * would also break all streams encoded in the previous format.
  103554. */
  103555. /*
  103556. * Write MD5 signature
  103557. */
  103558. {
  103559. const unsigned md5_offset =
  103560. FLAC__STREAM_METADATA_HEADER_LENGTH +
  103561. (
  103562. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  103563. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  103564. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  103565. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  103566. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  103567. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  103568. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  103569. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  103570. ) / 8;
  103571. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  103572. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  103573. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103574. return;
  103575. }
  103576. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103577. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103578. return;
  103579. }
  103580. }
  103581. /*
  103582. * Write total samples
  103583. */
  103584. {
  103585. const unsigned total_samples_byte_offset =
  103586. FLAC__STREAM_METADATA_HEADER_LENGTH +
  103587. (
  103588. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  103589. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  103590. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  103591. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  103592. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  103593. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  103594. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  103595. - 4
  103596. ) / 8;
  103597. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  103598. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  103599. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  103600. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  103601. b[4] = (FLAC__byte)(samples & 0xFF);
  103602. 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) {
  103603. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  103604. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103605. return;
  103606. }
  103607. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103608. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103609. return;
  103610. }
  103611. }
  103612. /*
  103613. * Write min/max framesize
  103614. */
  103615. {
  103616. const unsigned min_framesize_offset =
  103617. FLAC__STREAM_METADATA_HEADER_LENGTH +
  103618. (
  103619. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  103620. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  103621. ) / 8;
  103622. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  103623. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  103624. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  103625. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  103626. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  103627. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  103628. 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) {
  103629. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  103630. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103631. return;
  103632. }
  103633. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103634. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103635. return;
  103636. }
  103637. }
  103638. /*
  103639. * Write seektable
  103640. */
  103641. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  103642. unsigned i;
  103643. FLAC__format_seektable_sort(encoder->private_->seek_table);
  103644. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  103645. 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) {
  103646. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  103647. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103648. return;
  103649. }
  103650. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  103651. FLAC__uint64 xx;
  103652. unsigned x;
  103653. xx = encoder->private_->seek_table->points[i].sample_number;
  103654. b[7] = (FLAC__byte)xx; xx >>= 8;
  103655. b[6] = (FLAC__byte)xx; xx >>= 8;
  103656. b[5] = (FLAC__byte)xx; xx >>= 8;
  103657. b[4] = (FLAC__byte)xx; xx >>= 8;
  103658. b[3] = (FLAC__byte)xx; xx >>= 8;
  103659. b[2] = (FLAC__byte)xx; xx >>= 8;
  103660. b[1] = (FLAC__byte)xx; xx >>= 8;
  103661. b[0] = (FLAC__byte)xx; xx >>= 8;
  103662. xx = encoder->private_->seek_table->points[i].stream_offset;
  103663. b[15] = (FLAC__byte)xx; xx >>= 8;
  103664. b[14] = (FLAC__byte)xx; xx >>= 8;
  103665. b[13] = (FLAC__byte)xx; xx >>= 8;
  103666. b[12] = (FLAC__byte)xx; xx >>= 8;
  103667. b[11] = (FLAC__byte)xx; xx >>= 8;
  103668. b[10] = (FLAC__byte)xx; xx >>= 8;
  103669. b[9] = (FLAC__byte)xx; xx >>= 8;
  103670. b[8] = (FLAC__byte)xx; xx >>= 8;
  103671. x = encoder->private_->seek_table->points[i].frame_samples;
  103672. b[17] = (FLAC__byte)x; x >>= 8;
  103673. b[16] = (FLAC__byte)x; x >>= 8;
  103674. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  103675. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103676. return;
  103677. }
  103678. }
  103679. }
  103680. }
  103681. #if FLAC__HAS_OGG
  103682. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  103683. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  103684. {
  103685. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  103686. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  103687. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  103688. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  103689. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  103690. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  103691. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  103692. FLAC__STREAM_SYNC_LENGTH
  103693. ;
  103694. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  103695. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  103696. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  103697. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  103698. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  103699. ogg_page page;
  103700. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  103701. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  103702. /* Pre-check that client supports seeking, since we don't want the
  103703. * ogg_helper code to ever have to deal with this condition.
  103704. */
  103705. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  103706. return;
  103707. /* All this is based on intimate knowledge of the stream header
  103708. * layout, but a change to the header format that would break this
  103709. * would also break all streams encoded in the previous format.
  103710. */
  103711. /**
  103712. ** Write STREAMINFO stats
  103713. **/
  103714. simple_ogg_page__init(&page);
  103715. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  103716. simple_ogg_page__clear(&page);
  103717. return; /* state already set */
  103718. }
  103719. /*
  103720. * Write MD5 signature
  103721. */
  103722. {
  103723. const unsigned md5_offset =
  103724. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  103725. FLAC__STREAM_METADATA_HEADER_LENGTH +
  103726. (
  103727. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  103728. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  103729. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  103730. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  103731. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  103732. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  103733. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  103734. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  103735. ) / 8;
  103736. if(md5_offset + 16 > (unsigned)page.body_len) {
  103737. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  103738. simple_ogg_page__clear(&page);
  103739. return;
  103740. }
  103741. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  103742. }
  103743. /*
  103744. * Write total samples
  103745. */
  103746. {
  103747. const unsigned total_samples_byte_offset =
  103748. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  103749. FLAC__STREAM_METADATA_HEADER_LENGTH +
  103750. (
  103751. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  103752. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  103753. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  103754. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  103755. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  103756. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  103757. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  103758. - 4
  103759. ) / 8;
  103760. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  103761. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  103762. simple_ogg_page__clear(&page);
  103763. return;
  103764. }
  103765. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  103766. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  103767. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  103768. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  103769. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  103770. b[4] = (FLAC__byte)(samples & 0xFF);
  103771. memcpy(page.body + total_samples_byte_offset, b, 5);
  103772. }
  103773. /*
  103774. * Write min/max framesize
  103775. */
  103776. {
  103777. const unsigned min_framesize_offset =
  103778. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  103779. FLAC__STREAM_METADATA_HEADER_LENGTH +
  103780. (
  103781. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  103782. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  103783. ) / 8;
  103784. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  103785. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  103786. simple_ogg_page__clear(&page);
  103787. return;
  103788. }
  103789. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  103790. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  103791. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  103792. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  103793. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  103794. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  103795. memcpy(page.body + min_framesize_offset, b, 6);
  103796. }
  103797. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  103798. simple_ogg_page__clear(&page);
  103799. return; /* state already set */
  103800. }
  103801. simple_ogg_page__clear(&page);
  103802. /*
  103803. * Write seektable
  103804. */
  103805. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  103806. unsigned i;
  103807. FLAC__byte *p;
  103808. FLAC__format_seektable_sort(encoder->private_->seek_table);
  103809. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  103810. simple_ogg_page__init(&page);
  103811. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  103812. simple_ogg_page__clear(&page);
  103813. return; /* state already set */
  103814. }
  103815. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  103816. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  103817. simple_ogg_page__clear(&page);
  103818. return;
  103819. }
  103820. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  103821. FLAC__uint64 xx;
  103822. unsigned x;
  103823. xx = encoder->private_->seek_table->points[i].sample_number;
  103824. b[7] = (FLAC__byte)xx; xx >>= 8;
  103825. b[6] = (FLAC__byte)xx; xx >>= 8;
  103826. b[5] = (FLAC__byte)xx; xx >>= 8;
  103827. b[4] = (FLAC__byte)xx; xx >>= 8;
  103828. b[3] = (FLAC__byte)xx; xx >>= 8;
  103829. b[2] = (FLAC__byte)xx; xx >>= 8;
  103830. b[1] = (FLAC__byte)xx; xx >>= 8;
  103831. b[0] = (FLAC__byte)xx; xx >>= 8;
  103832. xx = encoder->private_->seek_table->points[i].stream_offset;
  103833. b[15] = (FLAC__byte)xx; xx >>= 8;
  103834. b[14] = (FLAC__byte)xx; xx >>= 8;
  103835. b[13] = (FLAC__byte)xx; xx >>= 8;
  103836. b[12] = (FLAC__byte)xx; xx >>= 8;
  103837. b[11] = (FLAC__byte)xx; xx >>= 8;
  103838. b[10] = (FLAC__byte)xx; xx >>= 8;
  103839. b[9] = (FLAC__byte)xx; xx >>= 8;
  103840. b[8] = (FLAC__byte)xx; xx >>= 8;
  103841. x = encoder->private_->seek_table->points[i].frame_samples;
  103842. b[17] = (FLAC__byte)x; x >>= 8;
  103843. b[16] = (FLAC__byte)x; x >>= 8;
  103844. memcpy(p, b, 18);
  103845. }
  103846. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  103847. simple_ogg_page__clear(&page);
  103848. return; /* state already set */
  103849. }
  103850. simple_ogg_page__clear(&page);
  103851. }
  103852. }
  103853. #endif
  103854. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  103855. {
  103856. FLAC__uint16 crc;
  103857. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103858. /*
  103859. * Accumulate raw signal to the MD5 signature
  103860. */
  103861. 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)) {
  103862. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103863. return false;
  103864. }
  103865. /*
  103866. * Process the frame header and subframes into the frame bitbuffer
  103867. */
  103868. if(!process_subframes_(encoder, is_fractional_block)) {
  103869. /* the above function sets the state for us in case of an error */
  103870. return false;
  103871. }
  103872. /*
  103873. * Zero-pad the frame to a byte_boundary
  103874. */
  103875. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  103876. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103877. return false;
  103878. }
  103879. /*
  103880. * CRC-16 the whole thing
  103881. */
  103882. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  103883. if(
  103884. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  103885. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  103886. ) {
  103887. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103888. return false;
  103889. }
  103890. /*
  103891. * Write it
  103892. */
  103893. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  103894. /* the above function sets the state for us in case of an error */
  103895. return false;
  103896. }
  103897. /*
  103898. * Get ready for the next frame
  103899. */
  103900. encoder->private_->current_sample_number = 0;
  103901. encoder->private_->current_frame_number++;
  103902. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  103903. return true;
  103904. }
  103905. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  103906. {
  103907. FLAC__FrameHeader frame_header;
  103908. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  103909. FLAC__bool do_independent, do_mid_side;
  103910. /*
  103911. * Calculate the min,max Rice partition orders
  103912. */
  103913. if(is_fractional_block) {
  103914. max_partition_order = 0;
  103915. }
  103916. else {
  103917. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  103918. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  103919. }
  103920. min_partition_order = min(min_partition_order, max_partition_order);
  103921. /*
  103922. * Setup the frame
  103923. */
  103924. frame_header.blocksize = encoder->protected_->blocksize;
  103925. frame_header.sample_rate = encoder->protected_->sample_rate;
  103926. frame_header.channels = encoder->protected_->channels;
  103927. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  103928. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  103929. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  103930. frame_header.number.frame_number = encoder->private_->current_frame_number;
  103931. /*
  103932. * Figure out what channel assignments to try
  103933. */
  103934. if(encoder->protected_->do_mid_side_stereo) {
  103935. if(encoder->protected_->loose_mid_side_stereo) {
  103936. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  103937. do_independent = true;
  103938. do_mid_side = true;
  103939. }
  103940. else {
  103941. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  103942. do_mid_side = !do_independent;
  103943. }
  103944. }
  103945. else {
  103946. do_independent = true;
  103947. do_mid_side = true;
  103948. }
  103949. }
  103950. else {
  103951. do_independent = true;
  103952. do_mid_side = false;
  103953. }
  103954. FLAC__ASSERT(do_independent || do_mid_side);
  103955. /*
  103956. * Check for wasted bits; set effective bps for each subframe
  103957. */
  103958. if(do_independent) {
  103959. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  103960. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  103961. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  103962. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  103963. }
  103964. }
  103965. if(do_mid_side) {
  103966. FLAC__ASSERT(encoder->protected_->channels == 2);
  103967. for(channel = 0; channel < 2; channel++) {
  103968. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  103969. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  103970. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  103971. }
  103972. }
  103973. /*
  103974. * First do a normal encoding pass of each independent channel
  103975. */
  103976. if(do_independent) {
  103977. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  103978. if(!
  103979. process_subframe_(
  103980. encoder,
  103981. min_partition_order,
  103982. max_partition_order,
  103983. &frame_header,
  103984. encoder->private_->subframe_bps[channel],
  103985. encoder->private_->integer_signal[channel],
  103986. encoder->private_->subframe_workspace_ptr[channel],
  103987. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  103988. encoder->private_->residual_workspace[channel],
  103989. encoder->private_->best_subframe+channel,
  103990. encoder->private_->best_subframe_bits+channel
  103991. )
  103992. )
  103993. return false;
  103994. }
  103995. }
  103996. /*
  103997. * Now do mid and side channels if requested
  103998. */
  103999. if(do_mid_side) {
  104000. FLAC__ASSERT(encoder->protected_->channels == 2);
  104001. for(channel = 0; channel < 2; channel++) {
  104002. if(!
  104003. process_subframe_(
  104004. encoder,
  104005. min_partition_order,
  104006. max_partition_order,
  104007. &frame_header,
  104008. encoder->private_->subframe_bps_mid_side[channel],
  104009. encoder->private_->integer_signal_mid_side[channel],
  104010. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  104011. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  104012. encoder->private_->residual_workspace_mid_side[channel],
  104013. encoder->private_->best_subframe_mid_side+channel,
  104014. encoder->private_->best_subframe_bits_mid_side+channel
  104015. )
  104016. )
  104017. return false;
  104018. }
  104019. }
  104020. /*
  104021. * Compose the frame bitbuffer
  104022. */
  104023. if(do_mid_side) {
  104024. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  104025. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  104026. FLAC__ChannelAssignment channel_assignment;
  104027. FLAC__ASSERT(encoder->protected_->channels == 2);
  104028. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  104029. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  104030. }
  104031. else {
  104032. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  104033. unsigned min_bits;
  104034. int ca;
  104035. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  104036. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  104037. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  104038. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  104039. FLAC__ASSERT(do_independent && do_mid_side);
  104040. /* We have to figure out which channel assignent results in the smallest frame */
  104041. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  104042. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  104043. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  104044. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  104045. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  104046. min_bits = bits[channel_assignment];
  104047. for(ca = 1; ca <= 3; ca++) {
  104048. if(bits[ca] < min_bits) {
  104049. min_bits = bits[ca];
  104050. channel_assignment = (FLAC__ChannelAssignment)ca;
  104051. }
  104052. }
  104053. }
  104054. frame_header.channel_assignment = channel_assignment;
  104055. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  104056. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104057. return false;
  104058. }
  104059. switch(channel_assignment) {
  104060. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  104061. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  104062. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  104063. break;
  104064. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  104065. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  104066. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104067. break;
  104068. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  104069. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104070. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  104071. break;
  104072. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  104073. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  104074. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104075. break;
  104076. default:
  104077. FLAC__ASSERT(0);
  104078. }
  104079. switch(channel_assignment) {
  104080. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  104081. left_bps = encoder->private_->subframe_bps [0];
  104082. right_bps = encoder->private_->subframe_bps [1];
  104083. break;
  104084. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  104085. left_bps = encoder->private_->subframe_bps [0];
  104086. right_bps = encoder->private_->subframe_bps_mid_side[1];
  104087. break;
  104088. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  104089. left_bps = encoder->private_->subframe_bps_mid_side[1];
  104090. right_bps = encoder->private_->subframe_bps [1];
  104091. break;
  104092. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  104093. left_bps = encoder->private_->subframe_bps_mid_side[0];
  104094. right_bps = encoder->private_->subframe_bps_mid_side[1];
  104095. break;
  104096. default:
  104097. FLAC__ASSERT(0);
  104098. }
  104099. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  104100. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  104101. return false;
  104102. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  104103. return false;
  104104. }
  104105. else {
  104106. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  104107. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104108. return false;
  104109. }
  104110. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104111. 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)) {
  104112. /* the above function sets the state for us in case of an error */
  104113. return false;
  104114. }
  104115. }
  104116. }
  104117. if(encoder->protected_->loose_mid_side_stereo) {
  104118. encoder->private_->loose_mid_side_stereo_frame_count++;
  104119. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  104120. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  104121. }
  104122. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  104123. return true;
  104124. }
  104125. FLAC__bool process_subframe_(
  104126. FLAC__StreamEncoder *encoder,
  104127. unsigned min_partition_order,
  104128. unsigned max_partition_order,
  104129. const FLAC__FrameHeader *frame_header,
  104130. unsigned subframe_bps,
  104131. const FLAC__int32 integer_signal[],
  104132. FLAC__Subframe *subframe[2],
  104133. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  104134. FLAC__int32 *residual[2],
  104135. unsigned *best_subframe,
  104136. unsigned *best_bits
  104137. )
  104138. {
  104139. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104140. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  104141. #else
  104142. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  104143. #endif
  104144. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104145. FLAC__double lpc_residual_bits_per_sample;
  104146. 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 */
  104147. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  104148. unsigned min_lpc_order, max_lpc_order, lpc_order;
  104149. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  104150. #endif
  104151. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  104152. unsigned rice_parameter;
  104153. unsigned _candidate_bits, _best_bits;
  104154. unsigned _best_subframe;
  104155. /* only use RICE2 partitions if stream bps > 16 */
  104156. 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;
  104157. FLAC__ASSERT(frame_header->blocksize > 0);
  104158. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  104159. _best_subframe = 0;
  104160. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  104161. _best_bits = UINT_MAX;
  104162. else
  104163. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  104164. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  104165. unsigned signal_is_constant = false;
  104166. 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);
  104167. /* check for constant subframe */
  104168. if(
  104169. !encoder->private_->disable_constant_subframes &&
  104170. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104171. fixed_residual_bits_per_sample[1] == 0.0
  104172. #else
  104173. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  104174. #endif
  104175. ) {
  104176. /* the above means it's possible all samples are the same value; now double-check it: */
  104177. unsigned i;
  104178. signal_is_constant = true;
  104179. for(i = 1; i < frame_header->blocksize; i++) {
  104180. if(integer_signal[0] != integer_signal[i]) {
  104181. signal_is_constant = false;
  104182. break;
  104183. }
  104184. }
  104185. }
  104186. if(signal_is_constant) {
  104187. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  104188. if(_candidate_bits < _best_bits) {
  104189. _best_subframe = !_best_subframe;
  104190. _best_bits = _candidate_bits;
  104191. }
  104192. }
  104193. else {
  104194. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  104195. /* encode fixed */
  104196. if(encoder->protected_->do_exhaustive_model_search) {
  104197. min_fixed_order = 0;
  104198. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  104199. }
  104200. else {
  104201. min_fixed_order = max_fixed_order = guess_fixed_order;
  104202. }
  104203. if(max_fixed_order >= frame_header->blocksize)
  104204. max_fixed_order = frame_header->blocksize - 1;
  104205. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  104206. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104207. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  104208. continue; /* don't even try */
  104209. 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 */
  104210. #else
  104211. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  104212. continue; /* don't even try */
  104213. 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 */
  104214. #endif
  104215. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  104216. if(rice_parameter >= rice_parameter_limit) {
  104217. #ifdef DEBUG_VERBOSE
  104218. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  104219. #endif
  104220. rice_parameter = rice_parameter_limit - 1;
  104221. }
  104222. _candidate_bits =
  104223. evaluate_fixed_subframe_(
  104224. encoder,
  104225. integer_signal,
  104226. residual[!_best_subframe],
  104227. encoder->private_->abs_residual_partition_sums,
  104228. encoder->private_->raw_bits_per_partition,
  104229. frame_header->blocksize,
  104230. subframe_bps,
  104231. fixed_order,
  104232. rice_parameter,
  104233. rice_parameter_limit,
  104234. min_partition_order,
  104235. max_partition_order,
  104236. encoder->protected_->do_escape_coding,
  104237. encoder->protected_->rice_parameter_search_dist,
  104238. subframe[!_best_subframe],
  104239. partitioned_rice_contents[!_best_subframe]
  104240. );
  104241. if(_candidate_bits < _best_bits) {
  104242. _best_subframe = !_best_subframe;
  104243. _best_bits = _candidate_bits;
  104244. }
  104245. }
  104246. }
  104247. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104248. /* encode lpc */
  104249. if(encoder->protected_->max_lpc_order > 0) {
  104250. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  104251. max_lpc_order = frame_header->blocksize-1;
  104252. else
  104253. max_lpc_order = encoder->protected_->max_lpc_order;
  104254. if(max_lpc_order > 0) {
  104255. unsigned a;
  104256. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  104257. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  104258. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  104259. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  104260. if(autoc[0] != 0.0) {
  104261. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  104262. if(encoder->protected_->do_exhaustive_model_search) {
  104263. min_lpc_order = 1;
  104264. }
  104265. else {
  104266. const unsigned guess_lpc_order =
  104267. FLAC__lpc_compute_best_order(
  104268. lpc_error,
  104269. max_lpc_order,
  104270. frame_header->blocksize,
  104271. subframe_bps + (
  104272. encoder->protected_->do_qlp_coeff_prec_search?
  104273. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  104274. encoder->protected_->qlp_coeff_precision
  104275. )
  104276. );
  104277. min_lpc_order = max_lpc_order = guess_lpc_order;
  104278. }
  104279. if(max_lpc_order >= frame_header->blocksize)
  104280. max_lpc_order = frame_header->blocksize - 1;
  104281. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  104282. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  104283. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  104284. continue; /* don't even try */
  104285. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  104286. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  104287. if(rice_parameter >= rice_parameter_limit) {
  104288. #ifdef DEBUG_VERBOSE
  104289. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  104290. #endif
  104291. rice_parameter = rice_parameter_limit - 1;
  104292. }
  104293. if(encoder->protected_->do_qlp_coeff_prec_search) {
  104294. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  104295. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  104296. if(subframe_bps <= 17) {
  104297. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  104298. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  104299. }
  104300. else
  104301. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  104302. }
  104303. else {
  104304. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  104305. }
  104306. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  104307. _candidate_bits =
  104308. evaluate_lpc_subframe_(
  104309. encoder,
  104310. integer_signal,
  104311. residual[!_best_subframe],
  104312. encoder->private_->abs_residual_partition_sums,
  104313. encoder->private_->raw_bits_per_partition,
  104314. encoder->private_->lp_coeff[lpc_order-1],
  104315. frame_header->blocksize,
  104316. subframe_bps,
  104317. lpc_order,
  104318. qlp_coeff_precision,
  104319. rice_parameter,
  104320. rice_parameter_limit,
  104321. min_partition_order,
  104322. max_partition_order,
  104323. encoder->protected_->do_escape_coding,
  104324. encoder->protected_->rice_parameter_search_dist,
  104325. subframe[!_best_subframe],
  104326. partitioned_rice_contents[!_best_subframe]
  104327. );
  104328. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  104329. if(_candidate_bits < _best_bits) {
  104330. _best_subframe = !_best_subframe;
  104331. _best_bits = _candidate_bits;
  104332. }
  104333. }
  104334. }
  104335. }
  104336. }
  104337. }
  104338. }
  104339. }
  104340. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  104341. }
  104342. }
  104343. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  104344. if(_best_bits == UINT_MAX) {
  104345. FLAC__ASSERT(_best_subframe == 0);
  104346. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  104347. }
  104348. *best_subframe = _best_subframe;
  104349. *best_bits = _best_bits;
  104350. return true;
  104351. }
  104352. FLAC__bool add_subframe_(
  104353. FLAC__StreamEncoder *encoder,
  104354. unsigned blocksize,
  104355. unsigned subframe_bps,
  104356. const FLAC__Subframe *subframe,
  104357. FLAC__BitWriter *frame
  104358. )
  104359. {
  104360. switch(subframe->type) {
  104361. case FLAC__SUBFRAME_TYPE_CONSTANT:
  104362. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  104363. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104364. return false;
  104365. }
  104366. break;
  104367. case FLAC__SUBFRAME_TYPE_FIXED:
  104368. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  104369. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104370. return false;
  104371. }
  104372. break;
  104373. case FLAC__SUBFRAME_TYPE_LPC:
  104374. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  104375. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104376. return false;
  104377. }
  104378. break;
  104379. case FLAC__SUBFRAME_TYPE_VERBATIM:
  104380. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  104381. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104382. return false;
  104383. }
  104384. break;
  104385. default:
  104386. FLAC__ASSERT(0);
  104387. }
  104388. return true;
  104389. }
  104390. #define SPOTCHECK_ESTIMATE 0
  104391. #if SPOTCHECK_ESTIMATE
  104392. static void spotcheck_subframe_estimate_(
  104393. FLAC__StreamEncoder *encoder,
  104394. unsigned blocksize,
  104395. unsigned subframe_bps,
  104396. const FLAC__Subframe *subframe,
  104397. unsigned estimate
  104398. )
  104399. {
  104400. FLAC__bool ret;
  104401. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  104402. if(frame == 0) {
  104403. fprintf(stderr, "EST: can't allocate frame\n");
  104404. return;
  104405. }
  104406. if(!FLAC__bitwriter_init(frame)) {
  104407. fprintf(stderr, "EST: can't init frame\n");
  104408. return;
  104409. }
  104410. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  104411. FLAC__ASSERT(ret);
  104412. {
  104413. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  104414. if(estimate != actual)
  104415. 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);
  104416. }
  104417. FLAC__bitwriter_delete(frame);
  104418. }
  104419. #endif
  104420. unsigned evaluate_constant_subframe_(
  104421. FLAC__StreamEncoder *encoder,
  104422. const FLAC__int32 signal,
  104423. unsigned blocksize,
  104424. unsigned subframe_bps,
  104425. FLAC__Subframe *subframe
  104426. )
  104427. {
  104428. unsigned estimate;
  104429. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  104430. subframe->data.constant.value = signal;
  104431. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  104432. #if SPOTCHECK_ESTIMATE
  104433. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  104434. #else
  104435. (void)encoder, (void)blocksize;
  104436. #endif
  104437. return estimate;
  104438. }
  104439. unsigned evaluate_fixed_subframe_(
  104440. FLAC__StreamEncoder *encoder,
  104441. const FLAC__int32 signal[],
  104442. FLAC__int32 residual[],
  104443. FLAC__uint64 abs_residual_partition_sums[],
  104444. unsigned raw_bits_per_partition[],
  104445. unsigned blocksize,
  104446. unsigned subframe_bps,
  104447. unsigned order,
  104448. unsigned rice_parameter,
  104449. unsigned rice_parameter_limit,
  104450. unsigned min_partition_order,
  104451. unsigned max_partition_order,
  104452. FLAC__bool do_escape_coding,
  104453. unsigned rice_parameter_search_dist,
  104454. FLAC__Subframe *subframe,
  104455. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  104456. )
  104457. {
  104458. unsigned i, residual_bits, estimate;
  104459. const unsigned residual_samples = blocksize - order;
  104460. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  104461. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  104462. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  104463. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  104464. subframe->data.fixed.residual = residual;
  104465. residual_bits =
  104466. find_best_partition_order_(
  104467. encoder->private_,
  104468. residual,
  104469. abs_residual_partition_sums,
  104470. raw_bits_per_partition,
  104471. residual_samples,
  104472. order,
  104473. rice_parameter,
  104474. rice_parameter_limit,
  104475. min_partition_order,
  104476. max_partition_order,
  104477. subframe_bps,
  104478. do_escape_coding,
  104479. rice_parameter_search_dist,
  104480. &subframe->data.fixed.entropy_coding_method
  104481. );
  104482. subframe->data.fixed.order = order;
  104483. for(i = 0; i < order; i++)
  104484. subframe->data.fixed.warmup[i] = signal[i];
  104485. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  104486. #if SPOTCHECK_ESTIMATE
  104487. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  104488. #endif
  104489. return estimate;
  104490. }
  104491. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104492. unsigned evaluate_lpc_subframe_(
  104493. FLAC__StreamEncoder *encoder,
  104494. const FLAC__int32 signal[],
  104495. FLAC__int32 residual[],
  104496. FLAC__uint64 abs_residual_partition_sums[],
  104497. unsigned raw_bits_per_partition[],
  104498. const FLAC__real lp_coeff[],
  104499. unsigned blocksize,
  104500. unsigned subframe_bps,
  104501. unsigned order,
  104502. unsigned qlp_coeff_precision,
  104503. unsigned rice_parameter,
  104504. unsigned rice_parameter_limit,
  104505. unsigned min_partition_order,
  104506. unsigned max_partition_order,
  104507. FLAC__bool do_escape_coding,
  104508. unsigned rice_parameter_search_dist,
  104509. FLAC__Subframe *subframe,
  104510. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  104511. )
  104512. {
  104513. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  104514. unsigned i, residual_bits, estimate;
  104515. int quantization, ret;
  104516. const unsigned residual_samples = blocksize - order;
  104517. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  104518. if(subframe_bps <= 16) {
  104519. FLAC__ASSERT(order > 0);
  104520. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  104521. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  104522. }
  104523. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  104524. if(ret != 0)
  104525. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  104526. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  104527. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  104528. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  104529. else
  104530. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  104531. else
  104532. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  104533. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  104534. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  104535. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  104536. subframe->data.lpc.residual = residual;
  104537. residual_bits =
  104538. find_best_partition_order_(
  104539. encoder->private_,
  104540. residual,
  104541. abs_residual_partition_sums,
  104542. raw_bits_per_partition,
  104543. residual_samples,
  104544. order,
  104545. rice_parameter,
  104546. rice_parameter_limit,
  104547. min_partition_order,
  104548. max_partition_order,
  104549. subframe_bps,
  104550. do_escape_coding,
  104551. rice_parameter_search_dist,
  104552. &subframe->data.lpc.entropy_coding_method
  104553. );
  104554. subframe->data.lpc.order = order;
  104555. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  104556. subframe->data.lpc.quantization_level = quantization;
  104557. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  104558. for(i = 0; i < order; i++)
  104559. subframe->data.lpc.warmup[i] = signal[i];
  104560. 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;
  104561. #if SPOTCHECK_ESTIMATE
  104562. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  104563. #endif
  104564. return estimate;
  104565. }
  104566. #endif
  104567. unsigned evaluate_verbatim_subframe_(
  104568. FLAC__StreamEncoder *encoder,
  104569. const FLAC__int32 signal[],
  104570. unsigned blocksize,
  104571. unsigned subframe_bps,
  104572. FLAC__Subframe *subframe
  104573. )
  104574. {
  104575. unsigned estimate;
  104576. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  104577. subframe->data.verbatim.data = signal;
  104578. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  104579. #if SPOTCHECK_ESTIMATE
  104580. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  104581. #else
  104582. (void)encoder;
  104583. #endif
  104584. return estimate;
  104585. }
  104586. unsigned find_best_partition_order_(
  104587. FLAC__StreamEncoderPrivate *private_,
  104588. const FLAC__int32 residual[],
  104589. FLAC__uint64 abs_residual_partition_sums[],
  104590. unsigned raw_bits_per_partition[],
  104591. unsigned residual_samples,
  104592. unsigned predictor_order,
  104593. unsigned rice_parameter,
  104594. unsigned rice_parameter_limit,
  104595. unsigned min_partition_order,
  104596. unsigned max_partition_order,
  104597. unsigned bps,
  104598. FLAC__bool do_escape_coding,
  104599. unsigned rice_parameter_search_dist,
  104600. FLAC__EntropyCodingMethod *best_ecm
  104601. )
  104602. {
  104603. unsigned residual_bits, best_residual_bits = 0;
  104604. unsigned best_parameters_index = 0;
  104605. unsigned best_partition_order = 0;
  104606. const unsigned blocksize = residual_samples + predictor_order;
  104607. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  104608. min_partition_order = min(min_partition_order, max_partition_order);
  104609. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  104610. if(do_escape_coding)
  104611. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  104612. {
  104613. int partition_order;
  104614. unsigned sum;
  104615. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  104616. if(!
  104617. set_partitioned_rice_(
  104618. #ifdef EXACT_RICE_BITS_CALCULATION
  104619. residual,
  104620. #endif
  104621. abs_residual_partition_sums+sum,
  104622. raw_bits_per_partition+sum,
  104623. residual_samples,
  104624. predictor_order,
  104625. rice_parameter,
  104626. rice_parameter_limit,
  104627. rice_parameter_search_dist,
  104628. (unsigned)partition_order,
  104629. do_escape_coding,
  104630. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  104631. &residual_bits
  104632. )
  104633. )
  104634. {
  104635. FLAC__ASSERT(best_residual_bits != 0);
  104636. break;
  104637. }
  104638. sum += 1u << partition_order;
  104639. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  104640. best_residual_bits = residual_bits;
  104641. best_parameters_index = !best_parameters_index;
  104642. best_partition_order = partition_order;
  104643. }
  104644. }
  104645. }
  104646. best_ecm->data.partitioned_rice.order = best_partition_order;
  104647. {
  104648. /*
  104649. * We are allowed to de-const the pointer based on our special
  104650. * knowledge; it is const to the outside world.
  104651. */
  104652. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  104653. unsigned partition;
  104654. /* save best parameters and raw_bits */
  104655. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  104656. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  104657. if(do_escape_coding)
  104658. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  104659. /*
  104660. * Now need to check if the type should be changed to
  104661. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  104662. * size of the rice parameters.
  104663. */
  104664. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  104665. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  104666. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  104667. break;
  104668. }
  104669. }
  104670. }
  104671. return best_residual_bits;
  104672. }
  104673. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  104674. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  104675. const FLAC__int32 residual[],
  104676. FLAC__uint64 abs_residual_partition_sums[],
  104677. unsigned blocksize,
  104678. unsigned predictor_order,
  104679. unsigned min_partition_order,
  104680. unsigned max_partition_order
  104681. );
  104682. #endif
  104683. void precompute_partition_info_sums_(
  104684. const FLAC__int32 residual[],
  104685. FLAC__uint64 abs_residual_partition_sums[],
  104686. unsigned residual_samples,
  104687. unsigned predictor_order,
  104688. unsigned min_partition_order,
  104689. unsigned max_partition_order,
  104690. unsigned bps
  104691. )
  104692. {
  104693. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  104694. unsigned partitions = 1u << max_partition_order;
  104695. FLAC__ASSERT(default_partition_samples > predictor_order);
  104696. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  104697. /* slightly pessimistic but still catches all common cases */
  104698. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  104699. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  104700. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  104701. return;
  104702. }
  104703. #endif
  104704. /* first do max_partition_order */
  104705. {
  104706. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  104707. /* slightly pessimistic but still catches all common cases */
  104708. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  104709. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  104710. FLAC__uint32 abs_residual_partition_sum;
  104711. for(partition = residual_sample = 0; partition < partitions; partition++) {
  104712. end += default_partition_samples;
  104713. abs_residual_partition_sum = 0;
  104714. for( ; residual_sample < end; residual_sample++)
  104715. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  104716. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  104717. }
  104718. }
  104719. else { /* have to pessimistically use 64 bits for accumulator */
  104720. FLAC__uint64 abs_residual_partition_sum;
  104721. for(partition = residual_sample = 0; partition < partitions; partition++) {
  104722. end += default_partition_samples;
  104723. abs_residual_partition_sum = 0;
  104724. for( ; residual_sample < end; residual_sample++)
  104725. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  104726. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  104727. }
  104728. }
  104729. }
  104730. /* now merge partitions for lower orders */
  104731. {
  104732. unsigned from_partition = 0, to_partition = partitions;
  104733. int partition_order;
  104734. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  104735. unsigned i;
  104736. partitions >>= 1;
  104737. for(i = 0; i < partitions; i++) {
  104738. abs_residual_partition_sums[to_partition++] =
  104739. abs_residual_partition_sums[from_partition ] +
  104740. abs_residual_partition_sums[from_partition+1];
  104741. from_partition += 2;
  104742. }
  104743. }
  104744. }
  104745. }
  104746. void precompute_partition_info_escapes_(
  104747. const FLAC__int32 residual[],
  104748. unsigned raw_bits_per_partition[],
  104749. unsigned residual_samples,
  104750. unsigned predictor_order,
  104751. unsigned min_partition_order,
  104752. unsigned max_partition_order
  104753. )
  104754. {
  104755. int partition_order;
  104756. unsigned from_partition, to_partition = 0;
  104757. const unsigned blocksize = residual_samples + predictor_order;
  104758. /* first do max_partition_order */
  104759. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  104760. FLAC__int32 r;
  104761. FLAC__uint32 rmax;
  104762. unsigned partition, partition_sample, partition_samples, residual_sample;
  104763. const unsigned partitions = 1u << partition_order;
  104764. const unsigned default_partition_samples = blocksize >> partition_order;
  104765. FLAC__ASSERT(default_partition_samples > predictor_order);
  104766. for(partition = residual_sample = 0; partition < partitions; partition++) {
  104767. partition_samples = default_partition_samples;
  104768. if(partition == 0)
  104769. partition_samples -= predictor_order;
  104770. rmax = 0;
  104771. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  104772. r = residual[residual_sample++];
  104773. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  104774. if(r < 0)
  104775. rmax |= ~r;
  104776. else
  104777. rmax |= r;
  104778. }
  104779. /* now we know all residual values are in the range [-rmax-1,rmax] */
  104780. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  104781. }
  104782. to_partition = partitions;
  104783. break; /*@@@ yuck, should remove the 'for' loop instead */
  104784. }
  104785. /* now merge partitions for lower orders */
  104786. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  104787. unsigned m;
  104788. unsigned i;
  104789. const unsigned partitions = 1u << partition_order;
  104790. for(i = 0; i < partitions; i++) {
  104791. m = raw_bits_per_partition[from_partition];
  104792. from_partition++;
  104793. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  104794. from_partition++;
  104795. to_partition++;
  104796. }
  104797. }
  104798. }
  104799. #ifdef EXACT_RICE_BITS_CALCULATION
  104800. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  104801. const unsigned rice_parameter,
  104802. const unsigned partition_samples,
  104803. const FLAC__int32 *residual
  104804. )
  104805. {
  104806. unsigned i, partition_bits =
  104807. 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 */
  104808. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  104809. ;
  104810. for(i = 0; i < partition_samples; i++)
  104811. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  104812. return partition_bits;
  104813. }
  104814. #else
  104815. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  104816. const unsigned rice_parameter,
  104817. const unsigned partition_samples,
  104818. const FLAC__uint64 abs_residual_partition_sum
  104819. )
  104820. {
  104821. return
  104822. 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 */
  104823. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  104824. (
  104825. rice_parameter?
  104826. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  104827. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  104828. )
  104829. - (partition_samples >> 1)
  104830. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  104831. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  104832. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  104833. * So the subtraction term tries to guess how many extra bits were contributed.
  104834. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  104835. */
  104836. ;
  104837. }
  104838. #endif
  104839. FLAC__bool set_partitioned_rice_(
  104840. #ifdef EXACT_RICE_BITS_CALCULATION
  104841. const FLAC__int32 residual[],
  104842. #endif
  104843. const FLAC__uint64 abs_residual_partition_sums[],
  104844. const unsigned raw_bits_per_partition[],
  104845. const unsigned residual_samples,
  104846. const unsigned predictor_order,
  104847. const unsigned suggested_rice_parameter,
  104848. const unsigned rice_parameter_limit,
  104849. const unsigned rice_parameter_search_dist,
  104850. const unsigned partition_order,
  104851. const FLAC__bool search_for_escapes,
  104852. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  104853. unsigned *bits
  104854. )
  104855. {
  104856. unsigned rice_parameter, partition_bits;
  104857. unsigned best_partition_bits, best_rice_parameter = 0;
  104858. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  104859. unsigned *parameters, *raw_bits;
  104860. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  104861. unsigned min_rice_parameter, max_rice_parameter;
  104862. #else
  104863. (void)rice_parameter_search_dist;
  104864. #endif
  104865. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  104866. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  104867. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  104868. parameters = partitioned_rice_contents->parameters;
  104869. raw_bits = partitioned_rice_contents->raw_bits;
  104870. if(partition_order == 0) {
  104871. best_partition_bits = (unsigned)(-1);
  104872. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  104873. if(rice_parameter_search_dist) {
  104874. if(suggested_rice_parameter < rice_parameter_search_dist)
  104875. min_rice_parameter = 0;
  104876. else
  104877. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  104878. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  104879. if(max_rice_parameter >= rice_parameter_limit) {
  104880. #ifdef DEBUG_VERBOSE
  104881. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  104882. #endif
  104883. max_rice_parameter = rice_parameter_limit - 1;
  104884. }
  104885. }
  104886. else
  104887. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  104888. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  104889. #else
  104890. rice_parameter = suggested_rice_parameter;
  104891. #endif
  104892. #ifdef EXACT_RICE_BITS_CALCULATION
  104893. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  104894. #else
  104895. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  104896. #endif
  104897. if(partition_bits < best_partition_bits) {
  104898. best_rice_parameter = rice_parameter;
  104899. best_partition_bits = partition_bits;
  104900. }
  104901. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  104902. }
  104903. #endif
  104904. if(search_for_escapes) {
  104905. 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;
  104906. if(partition_bits <= best_partition_bits) {
  104907. raw_bits[0] = raw_bits_per_partition[0];
  104908. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  104909. best_partition_bits = partition_bits;
  104910. }
  104911. else
  104912. raw_bits[0] = 0;
  104913. }
  104914. parameters[0] = best_rice_parameter;
  104915. bits_ += best_partition_bits;
  104916. }
  104917. else {
  104918. unsigned partition, residual_sample;
  104919. unsigned partition_samples;
  104920. FLAC__uint64 mean, k;
  104921. const unsigned partitions = 1u << partition_order;
  104922. for(partition = residual_sample = 0; partition < partitions; partition++) {
  104923. partition_samples = (residual_samples+predictor_order) >> partition_order;
  104924. if(partition == 0) {
  104925. if(partition_samples <= predictor_order)
  104926. return false;
  104927. else
  104928. partition_samples -= predictor_order;
  104929. }
  104930. mean = abs_residual_partition_sums[partition];
  104931. /* we are basically calculating the size in bits of the
  104932. * average residual magnitude in the partition:
  104933. * rice_parameter = floor(log2(mean/partition_samples))
  104934. * 'mean' is not a good name for the variable, it is
  104935. * actually the sum of magnitudes of all residual values
  104936. * in the partition, so the actual mean is
  104937. * mean/partition_samples
  104938. */
  104939. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  104940. ;
  104941. if(rice_parameter >= rice_parameter_limit) {
  104942. #ifdef DEBUG_VERBOSE
  104943. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  104944. #endif
  104945. rice_parameter = rice_parameter_limit - 1;
  104946. }
  104947. best_partition_bits = (unsigned)(-1);
  104948. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  104949. if(rice_parameter_search_dist) {
  104950. if(rice_parameter < rice_parameter_search_dist)
  104951. min_rice_parameter = 0;
  104952. else
  104953. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  104954. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  104955. if(max_rice_parameter >= rice_parameter_limit) {
  104956. #ifdef DEBUG_VERBOSE
  104957. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  104958. #endif
  104959. max_rice_parameter = rice_parameter_limit - 1;
  104960. }
  104961. }
  104962. else
  104963. min_rice_parameter = max_rice_parameter = rice_parameter;
  104964. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  104965. #endif
  104966. #ifdef EXACT_RICE_BITS_CALCULATION
  104967. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  104968. #else
  104969. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  104970. #endif
  104971. if(partition_bits < best_partition_bits) {
  104972. best_rice_parameter = rice_parameter;
  104973. best_partition_bits = partition_bits;
  104974. }
  104975. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  104976. }
  104977. #endif
  104978. if(search_for_escapes) {
  104979. 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;
  104980. if(partition_bits <= best_partition_bits) {
  104981. raw_bits[partition] = raw_bits_per_partition[partition];
  104982. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  104983. best_partition_bits = partition_bits;
  104984. }
  104985. else
  104986. raw_bits[partition] = 0;
  104987. }
  104988. parameters[partition] = best_rice_parameter;
  104989. bits_ += best_partition_bits;
  104990. residual_sample += partition_samples;
  104991. }
  104992. }
  104993. *bits = bits_;
  104994. return true;
  104995. }
  104996. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  104997. {
  104998. unsigned i, shift;
  104999. FLAC__int32 x = 0;
  105000. for(i = 0; i < samples && !(x&1); i++)
  105001. x |= signal[i];
  105002. if(x == 0) {
  105003. shift = 0;
  105004. }
  105005. else {
  105006. for(shift = 0; !(x&1); shift++)
  105007. x >>= 1;
  105008. }
  105009. if(shift > 0) {
  105010. for(i = 0; i < samples; i++)
  105011. signal[i] >>= shift;
  105012. }
  105013. return shift;
  105014. }
  105015. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  105016. {
  105017. unsigned channel;
  105018. for(channel = 0; channel < channels; channel++)
  105019. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  105020. fifo->tail += wide_samples;
  105021. FLAC__ASSERT(fifo->tail <= fifo->size);
  105022. }
  105023. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  105024. {
  105025. unsigned channel;
  105026. unsigned sample, wide_sample;
  105027. unsigned tail = fifo->tail;
  105028. sample = input_offset * channels;
  105029. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  105030. for(channel = 0; channel < channels; channel++)
  105031. fifo->data[channel][tail] = input[sample++];
  105032. tail++;
  105033. }
  105034. fifo->tail = tail;
  105035. FLAC__ASSERT(fifo->tail <= fifo->size);
  105036. }
  105037. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  105038. {
  105039. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  105040. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  105041. (void)decoder;
  105042. if(encoder->private_->verify.needs_magic_hack) {
  105043. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  105044. *bytes = FLAC__STREAM_SYNC_LENGTH;
  105045. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  105046. encoder->private_->verify.needs_magic_hack = false;
  105047. }
  105048. else {
  105049. if(encoded_bytes == 0) {
  105050. /*
  105051. * If we get here, a FIFO underflow has occurred,
  105052. * which means there is a bug somewhere.
  105053. */
  105054. FLAC__ASSERT(0);
  105055. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  105056. }
  105057. else if(encoded_bytes < *bytes)
  105058. *bytes = encoded_bytes;
  105059. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  105060. encoder->private_->verify.output.data += *bytes;
  105061. encoder->private_->verify.output.bytes -= *bytes;
  105062. }
  105063. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  105064. }
  105065. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  105066. {
  105067. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  105068. unsigned channel;
  105069. const unsigned channels = frame->header.channels;
  105070. const unsigned blocksize = frame->header.blocksize;
  105071. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  105072. (void)decoder;
  105073. for(channel = 0; channel < channels; channel++) {
  105074. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  105075. unsigned i, sample = 0;
  105076. FLAC__int32 expect = 0, got = 0;
  105077. for(i = 0; i < blocksize; i++) {
  105078. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  105079. sample = i;
  105080. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  105081. got = (FLAC__int32)buffer[channel][i];
  105082. break;
  105083. }
  105084. }
  105085. FLAC__ASSERT(i < blocksize);
  105086. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  105087. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  105088. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  105089. encoder->private_->verify.error_stats.channel = channel;
  105090. encoder->private_->verify.error_stats.sample = sample;
  105091. encoder->private_->verify.error_stats.expected = expect;
  105092. encoder->private_->verify.error_stats.got = got;
  105093. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  105094. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  105095. }
  105096. }
  105097. /* dequeue the frame from the fifo */
  105098. encoder->private_->verify.input_fifo.tail -= blocksize;
  105099. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  105100. for(channel = 0; channel < channels; channel++)
  105101. 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]));
  105102. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  105103. }
  105104. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  105105. {
  105106. (void)decoder, (void)metadata, (void)client_data;
  105107. }
  105108. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  105109. {
  105110. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  105111. (void)decoder, (void)status;
  105112. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  105113. }
  105114. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  105115. {
  105116. (void)client_data;
  105117. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  105118. if (*bytes == 0) {
  105119. if (feof(encoder->private_->file))
  105120. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  105121. else if (ferror(encoder->private_->file))
  105122. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  105123. }
  105124. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  105125. }
  105126. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  105127. {
  105128. (void)client_data;
  105129. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  105130. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  105131. else
  105132. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  105133. }
  105134. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  105135. {
  105136. off_t offset;
  105137. (void)client_data;
  105138. offset = ftello(encoder->private_->file);
  105139. if(offset < 0) {
  105140. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  105141. }
  105142. else {
  105143. *absolute_byte_offset = (FLAC__uint64)offset;
  105144. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  105145. }
  105146. }
  105147. #ifdef FLAC__VALGRIND_TESTING
  105148. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  105149. {
  105150. size_t ret = fwrite(ptr, size, nmemb, stream);
  105151. if(!ferror(stream))
  105152. fflush(stream);
  105153. return ret;
  105154. }
  105155. #else
  105156. #define local__fwrite fwrite
  105157. #endif
  105158. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  105159. {
  105160. (void)client_data, (void)current_frame;
  105161. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  105162. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  105163. #if FLAC__HAS_OGG
  105164. /* We would like to be able to use 'samples > 0' in the
  105165. * clause here but currently because of the nature of our
  105166. * Ogg writing implementation, 'samples' is always 0 (see
  105167. * ogg_encoder_aspect.c). The downside is extra progress
  105168. * callbacks.
  105169. */
  105170. encoder->private_->is_ogg? true :
  105171. #endif
  105172. samples > 0
  105173. );
  105174. if(call_it) {
  105175. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  105176. * because at this point in the callback chain, the stats
  105177. * have not been updated. Only after we return and control
  105178. * gets back to write_frame_() are the stats updated
  105179. */
  105180. 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);
  105181. }
  105182. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  105183. }
  105184. else
  105185. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  105186. }
  105187. /*
  105188. * This will forcibly set stdout to binary mode (for OSes that require it)
  105189. */
  105190. FILE *get_binary_stdout_(void)
  105191. {
  105192. /* if something breaks here it is probably due to the presence or
  105193. * absence of an underscore before the identifiers 'setmode',
  105194. * 'fileno', and/or 'O_BINARY'; check your system header files.
  105195. */
  105196. #if defined _MSC_VER || defined __MINGW32__
  105197. _setmode(_fileno(stdout), _O_BINARY);
  105198. #elif defined __CYGWIN__
  105199. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  105200. setmode(_fileno(stdout), _O_BINARY);
  105201. #elif defined __EMX__
  105202. setmode(fileno(stdout), O_BINARY);
  105203. #endif
  105204. return stdout;
  105205. }
  105206. #endif
  105207. /*** End of inlined file: stream_encoder.c ***/
  105208. /*** Start of inlined file: stream_encoder_framing.c ***/
  105209. /*** Start of inlined file: juce_FlacHeader.h ***/
  105210. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  105211. // tasks..
  105212. #define VERSION "1.2.1"
  105213. #define FLAC__NO_DLL 1
  105214. #if JUCE_MSVC
  105215. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  105216. #endif
  105217. #if JUCE_MAC
  105218. #define FLAC__SYS_DARWIN 1
  105219. #endif
  105220. /*** End of inlined file: juce_FlacHeader.h ***/
  105221. #if JUCE_USE_FLAC
  105222. #if HAVE_CONFIG_H
  105223. # include <config.h>
  105224. #endif
  105225. #include <stdio.h>
  105226. #include <string.h> /* for strlen() */
  105227. #ifdef max
  105228. #undef max
  105229. #endif
  105230. #define max(x,y) ((x)>(y)?(x):(y))
  105231. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  105232. 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);
  105233. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  105234. {
  105235. unsigned i, j;
  105236. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  105237. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  105238. return false;
  105239. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  105240. return false;
  105241. /*
  105242. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  105243. */
  105244. i = metadata->length;
  105245. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  105246. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  105247. i -= metadata->data.vorbis_comment.vendor_string.length;
  105248. i += vendor_string_length;
  105249. }
  105250. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  105251. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  105252. return false;
  105253. switch(metadata->type) {
  105254. case FLAC__METADATA_TYPE_STREAMINFO:
  105255. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  105256. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  105257. return false;
  105258. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  105259. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  105260. return false;
  105261. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  105262. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  105263. return false;
  105264. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  105265. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  105266. return false;
  105267. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  105268. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  105269. return false;
  105270. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  105271. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  105272. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  105273. return false;
  105274. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  105275. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  105276. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  105277. return false;
  105278. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  105279. return false;
  105280. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  105281. return false;
  105282. break;
  105283. case FLAC__METADATA_TYPE_PADDING:
  105284. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  105285. return false;
  105286. break;
  105287. case FLAC__METADATA_TYPE_APPLICATION:
  105288. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  105289. return false;
  105290. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  105291. return false;
  105292. break;
  105293. case FLAC__METADATA_TYPE_SEEKTABLE:
  105294. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  105295. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  105296. return false;
  105297. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  105298. return false;
  105299. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  105300. return false;
  105301. }
  105302. break;
  105303. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  105304. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  105305. return false;
  105306. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  105307. return false;
  105308. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  105309. return false;
  105310. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  105311. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  105312. return false;
  105313. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  105314. return false;
  105315. }
  105316. break;
  105317. case FLAC__METADATA_TYPE_CUESHEET:
  105318. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  105319. 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))
  105320. return false;
  105321. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  105322. return false;
  105323. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  105324. return false;
  105325. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  105326. return false;
  105327. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  105328. return false;
  105329. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  105330. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  105331. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  105332. return false;
  105333. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  105334. return false;
  105335. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  105336. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  105337. return false;
  105338. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  105339. return false;
  105340. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  105341. return false;
  105342. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  105343. return false;
  105344. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  105345. return false;
  105346. for(j = 0; j < track->num_indices; j++) {
  105347. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  105348. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  105349. return false;
  105350. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  105351. return false;
  105352. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  105353. return false;
  105354. }
  105355. }
  105356. break;
  105357. case FLAC__METADATA_TYPE_PICTURE:
  105358. {
  105359. size_t len;
  105360. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  105361. return false;
  105362. len = strlen(metadata->data.picture.mime_type);
  105363. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  105364. return false;
  105365. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  105366. return false;
  105367. len = strlen((const char *)metadata->data.picture.description);
  105368. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  105369. return false;
  105370. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  105371. return false;
  105372. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  105373. return false;
  105374. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  105375. return false;
  105376. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  105377. return false;
  105378. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  105379. return false;
  105380. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  105381. return false;
  105382. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  105383. return false;
  105384. }
  105385. break;
  105386. default:
  105387. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  105388. return false;
  105389. break;
  105390. }
  105391. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  105392. return true;
  105393. }
  105394. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  105395. {
  105396. unsigned u, blocksize_hint, sample_rate_hint;
  105397. FLAC__byte crc;
  105398. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  105399. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  105400. return false;
  105401. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  105402. return false;
  105403. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  105404. return false;
  105405. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  105406. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  105407. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  105408. blocksize_hint = 0;
  105409. switch(header->blocksize) {
  105410. case 192: u = 1; break;
  105411. case 576: u = 2; break;
  105412. case 1152: u = 3; break;
  105413. case 2304: u = 4; break;
  105414. case 4608: u = 5; break;
  105415. case 256: u = 8; break;
  105416. case 512: u = 9; break;
  105417. case 1024: u = 10; break;
  105418. case 2048: u = 11; break;
  105419. case 4096: u = 12; break;
  105420. case 8192: u = 13; break;
  105421. case 16384: u = 14; break;
  105422. case 32768: u = 15; break;
  105423. default:
  105424. if(header->blocksize <= 0x100)
  105425. blocksize_hint = u = 6;
  105426. else
  105427. blocksize_hint = u = 7;
  105428. break;
  105429. }
  105430. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  105431. return false;
  105432. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  105433. sample_rate_hint = 0;
  105434. switch(header->sample_rate) {
  105435. case 88200: u = 1; break;
  105436. case 176400: u = 2; break;
  105437. case 192000: u = 3; break;
  105438. case 8000: u = 4; break;
  105439. case 16000: u = 5; break;
  105440. case 22050: u = 6; break;
  105441. case 24000: u = 7; break;
  105442. case 32000: u = 8; break;
  105443. case 44100: u = 9; break;
  105444. case 48000: u = 10; break;
  105445. case 96000: u = 11; break;
  105446. default:
  105447. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  105448. sample_rate_hint = u = 12;
  105449. else if(header->sample_rate % 10 == 0)
  105450. sample_rate_hint = u = 14;
  105451. else if(header->sample_rate <= 0xffff)
  105452. sample_rate_hint = u = 13;
  105453. else
  105454. u = 0;
  105455. break;
  105456. }
  105457. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  105458. return false;
  105459. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  105460. switch(header->channel_assignment) {
  105461. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  105462. u = header->channels - 1;
  105463. break;
  105464. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  105465. FLAC__ASSERT(header->channels == 2);
  105466. u = 8;
  105467. break;
  105468. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  105469. FLAC__ASSERT(header->channels == 2);
  105470. u = 9;
  105471. break;
  105472. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  105473. FLAC__ASSERT(header->channels == 2);
  105474. u = 10;
  105475. break;
  105476. default:
  105477. FLAC__ASSERT(0);
  105478. }
  105479. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  105480. return false;
  105481. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  105482. switch(header->bits_per_sample) {
  105483. case 8 : u = 1; break;
  105484. case 12: u = 2; break;
  105485. case 16: u = 4; break;
  105486. case 20: u = 5; break;
  105487. case 24: u = 6; break;
  105488. default: u = 0; break;
  105489. }
  105490. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  105491. return false;
  105492. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  105493. return false;
  105494. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  105495. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  105496. return false;
  105497. }
  105498. else {
  105499. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  105500. return false;
  105501. }
  105502. if(blocksize_hint)
  105503. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  105504. return false;
  105505. switch(sample_rate_hint) {
  105506. case 12:
  105507. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  105508. return false;
  105509. break;
  105510. case 13:
  105511. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  105512. return false;
  105513. break;
  105514. case 14:
  105515. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  105516. return false;
  105517. break;
  105518. }
  105519. /* write the CRC */
  105520. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  105521. return false;
  105522. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  105523. return false;
  105524. return true;
  105525. }
  105526. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  105527. {
  105528. FLAC__bool ok;
  105529. ok =
  105530. 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) &&
  105531. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  105532. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  105533. ;
  105534. return ok;
  105535. }
  105536. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  105537. {
  105538. unsigned i;
  105539. 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))
  105540. return false;
  105541. if(wasted_bits)
  105542. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  105543. return false;
  105544. for(i = 0; i < subframe->order; i++)
  105545. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  105546. return false;
  105547. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  105548. return false;
  105549. switch(subframe->entropy_coding_method.type) {
  105550. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  105551. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  105552. if(!add_residual_partitioned_rice_(
  105553. bw,
  105554. subframe->residual,
  105555. residual_samples,
  105556. subframe->order,
  105557. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  105558. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  105559. subframe->entropy_coding_method.data.partitioned_rice.order,
  105560. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  105561. ))
  105562. return false;
  105563. break;
  105564. default:
  105565. FLAC__ASSERT(0);
  105566. }
  105567. return true;
  105568. }
  105569. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  105570. {
  105571. unsigned i;
  105572. 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))
  105573. return false;
  105574. if(wasted_bits)
  105575. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  105576. return false;
  105577. for(i = 0; i < subframe->order; i++)
  105578. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  105579. return false;
  105580. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  105581. return false;
  105582. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  105583. return false;
  105584. for(i = 0; i < subframe->order; i++)
  105585. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  105586. return false;
  105587. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  105588. return false;
  105589. switch(subframe->entropy_coding_method.type) {
  105590. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  105591. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  105592. if(!add_residual_partitioned_rice_(
  105593. bw,
  105594. subframe->residual,
  105595. residual_samples,
  105596. subframe->order,
  105597. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  105598. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  105599. subframe->entropy_coding_method.data.partitioned_rice.order,
  105600. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  105601. ))
  105602. return false;
  105603. break;
  105604. default:
  105605. FLAC__ASSERT(0);
  105606. }
  105607. return true;
  105608. }
  105609. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  105610. {
  105611. unsigned i;
  105612. const FLAC__int32 *signal = subframe->data;
  105613. 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))
  105614. return false;
  105615. if(wasted_bits)
  105616. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  105617. return false;
  105618. for(i = 0; i < samples; i++)
  105619. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  105620. return false;
  105621. return true;
  105622. }
  105623. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  105624. {
  105625. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  105626. return false;
  105627. switch(method->type) {
  105628. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  105629. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  105630. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  105631. return false;
  105632. break;
  105633. default:
  105634. FLAC__ASSERT(0);
  105635. }
  105636. return true;
  105637. }
  105638. 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)
  105639. {
  105640. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  105641. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  105642. if(partition_order == 0) {
  105643. unsigned i;
  105644. if(raw_bits[0] == 0) {
  105645. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  105646. return false;
  105647. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  105648. return false;
  105649. }
  105650. else {
  105651. FLAC__ASSERT(rice_parameters[0] == 0);
  105652. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  105653. return false;
  105654. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  105655. return false;
  105656. for(i = 0; i < residual_samples; i++) {
  105657. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  105658. return false;
  105659. }
  105660. }
  105661. return true;
  105662. }
  105663. else {
  105664. unsigned i, j, k = 0, k_last = 0;
  105665. unsigned partition_samples;
  105666. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  105667. for(i = 0; i < (1u<<partition_order); i++) {
  105668. partition_samples = default_partition_samples;
  105669. if(i == 0)
  105670. partition_samples -= predictor_order;
  105671. k += partition_samples;
  105672. if(raw_bits[i] == 0) {
  105673. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  105674. return false;
  105675. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  105676. return false;
  105677. }
  105678. else {
  105679. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  105680. return false;
  105681. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  105682. return false;
  105683. for(j = k_last; j < k; j++) {
  105684. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  105685. return false;
  105686. }
  105687. }
  105688. k_last = k;
  105689. }
  105690. return true;
  105691. }
  105692. }
  105693. #endif
  105694. /*** End of inlined file: stream_encoder_framing.c ***/
  105695. /*** Start of inlined file: window_flac.c ***/
  105696. /*** Start of inlined file: juce_FlacHeader.h ***/
  105697. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  105698. // tasks..
  105699. #define VERSION "1.2.1"
  105700. #define FLAC__NO_DLL 1
  105701. #if JUCE_MSVC
  105702. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  105703. #endif
  105704. #if JUCE_MAC
  105705. #define FLAC__SYS_DARWIN 1
  105706. #endif
  105707. /*** End of inlined file: juce_FlacHeader.h ***/
  105708. #if JUCE_USE_FLAC
  105709. #if HAVE_CONFIG_H
  105710. # include <config.h>
  105711. #endif
  105712. #include <math.h>
  105713. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105714. #ifndef M_PI
  105715. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  105716. #define M_PI 3.14159265358979323846
  105717. #endif
  105718. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  105719. {
  105720. const FLAC__int32 N = L - 1;
  105721. FLAC__int32 n;
  105722. if (L & 1) {
  105723. for (n = 0; n <= N/2; n++)
  105724. window[n] = 2.0f * n / (float)N;
  105725. for (; n <= N; n++)
  105726. window[n] = 2.0f - 2.0f * n / (float)N;
  105727. }
  105728. else {
  105729. for (n = 0; n <= L/2-1; n++)
  105730. window[n] = 2.0f * n / (float)N;
  105731. for (; n <= N; n++)
  105732. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  105733. }
  105734. }
  105735. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  105736. {
  105737. const FLAC__int32 N = L - 1;
  105738. FLAC__int32 n;
  105739. for (n = 0; n < L; n++)
  105740. 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)));
  105741. }
  105742. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  105743. {
  105744. const FLAC__int32 N = L - 1;
  105745. FLAC__int32 n;
  105746. for (n = 0; n < L; n++)
  105747. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  105748. }
  105749. /* 4-term -92dB side-lobe */
  105750. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  105751. {
  105752. const FLAC__int32 N = L - 1;
  105753. FLAC__int32 n;
  105754. for (n = 0; n <= N; n++)
  105755. 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));
  105756. }
  105757. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  105758. {
  105759. const FLAC__int32 N = L - 1;
  105760. const double N2 = (double)N / 2.;
  105761. FLAC__int32 n;
  105762. for (n = 0; n <= N; n++) {
  105763. double k = ((double)n - N2) / N2;
  105764. k = 1.0f - k * k;
  105765. window[n] = (FLAC__real)(k * k);
  105766. }
  105767. }
  105768. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  105769. {
  105770. const FLAC__int32 N = L - 1;
  105771. FLAC__int32 n;
  105772. for (n = 0; n < L; n++)
  105773. 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));
  105774. }
  105775. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  105776. {
  105777. const FLAC__int32 N = L - 1;
  105778. const double N2 = (double)N / 2.;
  105779. FLAC__int32 n;
  105780. for (n = 0; n <= N; n++) {
  105781. const double k = ((double)n - N2) / (stddev * N2);
  105782. window[n] = (FLAC__real)exp(-0.5f * k * k);
  105783. }
  105784. }
  105785. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
  105786. {
  105787. const FLAC__int32 N = L - 1;
  105788. FLAC__int32 n;
  105789. for (n = 0; n < L; n++)
  105790. window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  105791. }
  105792. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
  105793. {
  105794. const FLAC__int32 N = L - 1;
  105795. FLAC__int32 n;
  105796. for (n = 0; n < L; n++)
  105797. window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  105798. }
  105799. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  105800. {
  105801. const FLAC__int32 N = L - 1;
  105802. FLAC__int32 n;
  105803. for (n = 0; n < L; n++)
  105804. 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));
  105805. }
  105806. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  105807. {
  105808. const FLAC__int32 N = L - 1;
  105809. FLAC__int32 n;
  105810. for (n = 0; n < L; n++)
  105811. 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));
  105812. }
  105813. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  105814. {
  105815. FLAC__int32 n;
  105816. for (n = 0; n < L; n++)
  105817. window[n] = 1.0f;
  105818. }
  105819. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  105820. {
  105821. FLAC__int32 n;
  105822. if (L & 1) {
  105823. for (n = 1; n <= L+1/2; n++)
  105824. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  105825. for (; n <= L; n++)
  105826. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  105827. }
  105828. else {
  105829. for (n = 1; n <= L/2; n++)
  105830. window[n-1] = 2.0f * n / (float)L;
  105831. for (; n <= L; n++)
  105832. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  105833. }
  105834. }
  105835. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  105836. {
  105837. if (p <= 0.0)
  105838. FLAC__window_rectangle(window, L);
  105839. else if (p >= 1.0)
  105840. FLAC__window_hann(window, L);
  105841. else {
  105842. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  105843. FLAC__int32 n;
  105844. /* start with rectangle... */
  105845. FLAC__window_rectangle(window, L);
  105846. /* ...replace ends with hann */
  105847. if (Np > 0) {
  105848. for (n = 0; n <= Np; n++) {
  105849. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  105850. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  105851. }
  105852. }
  105853. }
  105854. }
  105855. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  105856. {
  105857. const FLAC__int32 N = L - 1;
  105858. const double N2 = (double)N / 2.;
  105859. FLAC__int32 n;
  105860. for (n = 0; n <= N; n++) {
  105861. const double k = ((double)n - N2) / N2;
  105862. window[n] = (FLAC__real)(1.0f - k * k);
  105863. }
  105864. }
  105865. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  105866. #endif
  105867. /*** End of inlined file: window_flac.c ***/
  105868. #else
  105869. #include <FLAC/all.h>
  105870. #endif
  105871. }
  105872. #undef max
  105873. #undef min
  105874. BEGIN_JUCE_NAMESPACE
  105875. static const char* const flacFormatName = "FLAC file";
  105876. static const char* const flacExtensions[] = { ".flac", 0 };
  105877. class FlacReader : public AudioFormatReader
  105878. {
  105879. public:
  105880. FlacReader (InputStream* const in)
  105881. : AudioFormatReader (in, TRANS (flacFormatName)),
  105882. reservoir (2, 0),
  105883. reservoirStart (0),
  105884. samplesInReservoir (0),
  105885. scanningForLength (false)
  105886. {
  105887. using namespace FlacNamespace;
  105888. lengthInSamples = 0;
  105889. decoder = FLAC__stream_decoder_new();
  105890. ok = FLAC__stream_decoder_init_stream (decoder,
  105891. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  105892. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  105893. this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  105894. if (ok)
  105895. {
  105896. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  105897. if (lengthInSamples == 0 && sampleRate > 0)
  105898. {
  105899. // the length hasn't been stored in the metadata, so we'll need to
  105900. // work it out the length the hard way, by scanning the whole file..
  105901. scanningForLength = true;
  105902. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  105903. scanningForLength = false;
  105904. const int64 tempLength = lengthInSamples;
  105905. FLAC__stream_decoder_reset (decoder);
  105906. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  105907. lengthInSamples = tempLength;
  105908. }
  105909. }
  105910. }
  105911. ~FlacReader()
  105912. {
  105913. FlacNamespace::FLAC__stream_decoder_delete (decoder);
  105914. }
  105915. void useMetadata (const FlacNamespace::FLAC__StreamMetadata_StreamInfo& info)
  105916. {
  105917. sampleRate = info.sample_rate;
  105918. bitsPerSample = info.bits_per_sample;
  105919. lengthInSamples = (unsigned int) info.total_samples;
  105920. numChannels = info.channels;
  105921. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  105922. }
  105923. // returns the number of samples read
  105924. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  105925. int64 startSampleInFile, int numSamples)
  105926. {
  105927. using namespace FlacNamespace;
  105928. if (! ok)
  105929. return false;
  105930. while (numSamples > 0)
  105931. {
  105932. if (startSampleInFile >= reservoirStart
  105933. && startSampleInFile < reservoirStart + samplesInReservoir)
  105934. {
  105935. const int num = (int) jmin ((int64) numSamples,
  105936. reservoirStart + samplesInReservoir - startSampleInFile);
  105937. jassert (num > 0);
  105938. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  105939. if (destSamples[i] != 0)
  105940. memcpy (destSamples[i] + startOffsetInDestBuffer,
  105941. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  105942. sizeof (int) * num);
  105943. startOffsetInDestBuffer += num;
  105944. startSampleInFile += num;
  105945. numSamples -= num;
  105946. }
  105947. else
  105948. {
  105949. if (startSampleInFile >= (int) lengthInSamples)
  105950. {
  105951. samplesInReservoir = 0;
  105952. }
  105953. else if (startSampleInFile < reservoirStart
  105954. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  105955. {
  105956. // had some problems with flac crashing if the read pos is aligned more
  105957. // accurately than this. Probably fixed in newer versions of the library, though.
  105958. reservoirStart = (int) (startSampleInFile & ~511);
  105959. samplesInReservoir = 0;
  105960. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  105961. }
  105962. else
  105963. {
  105964. reservoirStart += samplesInReservoir;
  105965. samplesInReservoir = 0;
  105966. FLAC__stream_decoder_process_single (decoder);
  105967. }
  105968. if (samplesInReservoir == 0)
  105969. break;
  105970. }
  105971. }
  105972. if (numSamples > 0)
  105973. {
  105974. for (int i = numDestChannels; --i >= 0;)
  105975. if (destSamples[i] != 0)
  105976. zeromem (destSamples[i] + startOffsetInDestBuffer,
  105977. sizeof (int) * numSamples);
  105978. }
  105979. return true;
  105980. }
  105981. void useSamples (const FlacNamespace::FLAC__int32* const buffer[], int numSamples)
  105982. {
  105983. if (scanningForLength)
  105984. {
  105985. lengthInSamples += numSamples;
  105986. }
  105987. else
  105988. {
  105989. if (numSamples > reservoir.getNumSamples())
  105990. reservoir.setSize (numChannels, numSamples, false, false, true);
  105991. const int bitsToShift = 32 - bitsPerSample;
  105992. for (int i = 0; i < (int) numChannels; ++i)
  105993. {
  105994. const FlacNamespace::FLAC__int32* src = buffer[i];
  105995. int n = i;
  105996. while (src == 0 && n > 0)
  105997. src = buffer [--n];
  105998. if (src != 0)
  105999. {
  106000. int* dest = (int*) reservoir.getSampleData(i);
  106001. for (int j = 0; j < numSamples; ++j)
  106002. dest[j] = src[j] << bitsToShift;
  106003. }
  106004. }
  106005. samplesInReservoir = numSamples;
  106006. }
  106007. }
  106008. static FlacNamespace::FLAC__StreamDecoderReadStatus readCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__byte buffer[], size_t* bytes, void* client_data)
  106009. {
  106010. using namespace FlacNamespace;
  106011. *bytes = (size_t) static_cast <const FlacReader*> (client_data)->input->read (buffer, (int) *bytes);
  106012. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  106013. }
  106014. static FlacNamespace::FLAC__StreamDecoderSeekStatus seekCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64 absolute_byte_offset, void* client_data)
  106015. {
  106016. using namespace FlacNamespace;
  106017. static_cast <const FlacReader*> (client_data)->input->setPosition ((int) absolute_byte_offset);
  106018. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  106019. }
  106020. static FlacNamespace::FLAC__StreamDecoderTellStatus tellCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  106021. {
  106022. using namespace FlacNamespace;
  106023. *absolute_byte_offset = static_cast <const FlacReader*> (client_data)->input->getPosition();
  106024. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  106025. }
  106026. static FlacNamespace::FLAC__StreamDecoderLengthStatus lengthCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* stream_length, void* client_data)
  106027. {
  106028. using namespace FlacNamespace;
  106029. *stream_length = static_cast <const FlacReader*> (client_data)->input->getTotalLength();
  106030. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  106031. }
  106032. static FlacNamespace::FLAC__bool eofCallback_ (const FlacNamespace::FLAC__StreamDecoder*, void* client_data)
  106033. {
  106034. return static_cast <const FlacReader*> (client_data)->input->isExhausted();
  106035. }
  106036. static FlacNamespace::FLAC__StreamDecoderWriteStatus writeCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  106037. const FlacNamespace::FLAC__Frame* frame,
  106038. const FlacNamespace::FLAC__int32* const buffer[],
  106039. void* client_data)
  106040. {
  106041. using namespace FlacNamespace;
  106042. static_cast <FlacReader*> (client_data)->useSamples (buffer, frame->header.blocksize);
  106043. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  106044. }
  106045. static void metadataCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  106046. const FlacNamespace::FLAC__StreamMetadata* metadata,
  106047. void* client_data)
  106048. {
  106049. static_cast <FlacReader*> (client_data)->useMetadata (metadata->data.stream_info);
  106050. }
  106051. static void errorCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__StreamDecoderErrorStatus, void*)
  106052. {
  106053. }
  106054. juce_UseDebuggingNewOperator
  106055. private:
  106056. FlacNamespace::FLAC__StreamDecoder* decoder;
  106057. AudioSampleBuffer reservoir;
  106058. int reservoirStart, samplesInReservoir;
  106059. bool ok, scanningForLength;
  106060. FlacReader (const FlacReader&);
  106061. FlacReader& operator= (const FlacReader&);
  106062. };
  106063. class FlacWriter : public AudioFormatWriter
  106064. {
  106065. public:
  106066. FlacWriter (OutputStream* const out,
  106067. const double sampleRate_,
  106068. const int numChannels_,
  106069. const int bitsPerSample_)
  106070. : AudioFormatWriter (out, TRANS (flacFormatName),
  106071. sampleRate_,
  106072. numChannels_,
  106073. bitsPerSample_)
  106074. {
  106075. using namespace FlacNamespace;
  106076. encoder = FLAC__stream_encoder_new();
  106077. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  106078. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  106079. FLAC__stream_encoder_set_channels (encoder, numChannels);
  106080. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin ((unsigned int) 24, bitsPerSample));
  106081. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  106082. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  106083. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  106084. ok = FLAC__stream_encoder_init_stream (encoder,
  106085. encodeWriteCallback, encodeSeekCallback,
  106086. encodeTellCallback, encodeMetadataCallback,
  106087. this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  106088. }
  106089. ~FlacWriter()
  106090. {
  106091. if (ok)
  106092. {
  106093. FlacNamespace::FLAC__stream_encoder_finish (encoder);
  106094. output->flush();
  106095. }
  106096. else
  106097. {
  106098. output = 0; // to stop the base class deleting this, as it needs to be returned
  106099. // to the caller of createWriter()
  106100. }
  106101. FlacNamespace::FLAC__stream_encoder_delete (encoder);
  106102. }
  106103. bool write (const int** samplesToWrite, int numSamples)
  106104. {
  106105. using namespace FlacNamespace;
  106106. if (! ok)
  106107. return false;
  106108. int* buf[3];
  106109. const int bitsToShift = 32 - bitsPerSample;
  106110. if (bitsToShift > 0)
  106111. {
  106112. const int numChannelsToWrite = (samplesToWrite[1] == 0) ? 1 : 2;
  106113. temp.setSize (sizeof (int) * numSamples * numChannelsToWrite);
  106114. buf[0] = (int*) temp.getData();
  106115. buf[1] = buf[0] + numSamples;
  106116. buf[2] = 0;
  106117. for (int i = numChannelsToWrite; --i >= 0;)
  106118. {
  106119. if (samplesToWrite[i] != 0)
  106120. {
  106121. for (int j = 0; j < numSamples; ++j)
  106122. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  106123. }
  106124. }
  106125. samplesToWrite = (const int**) buf;
  106126. }
  106127. return FLAC__stream_encoder_process (encoder,
  106128. (const FLAC__int32**) samplesToWrite,
  106129. numSamples) != 0;
  106130. }
  106131. bool writeData (const void* const data, const int size) const
  106132. {
  106133. return output->write (data, size);
  106134. }
  106135. static void packUint32 (FlacNamespace::FLAC__uint32 val, FlacNamespace::FLAC__byte* b, const int bytes)
  106136. {
  106137. using namespace FlacNamespace;
  106138. b += bytes;
  106139. for (int i = 0; i < bytes; ++i)
  106140. {
  106141. *(--b) = (FLAC__byte) (val & 0xff);
  106142. val >>= 8;
  106143. }
  106144. }
  106145. void writeMetaData (const FlacNamespace::FLAC__StreamMetadata* metadata)
  106146. {
  106147. using namespace FlacNamespace;
  106148. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  106149. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  106150. const unsigned int channelsMinus1 = info.channels - 1;
  106151. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  106152. packUint32 (info.min_blocksize, buffer, 2);
  106153. packUint32 (info.max_blocksize, buffer + 2, 2);
  106154. packUint32 (info.min_framesize, buffer + 4, 3);
  106155. packUint32 (info.max_framesize, buffer + 7, 3);
  106156. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  106157. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  106158. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  106159. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  106160. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  106161. memcpy (buffer + 18, info.md5sum, 16);
  106162. const bool seekOk = output->setPosition (4);
  106163. (void) seekOk;
  106164. // if this fails, you've given it an output stream that can't seek! It needs
  106165. // to be able to seek back to write the header
  106166. jassert (seekOk);
  106167. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  106168. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  106169. }
  106170. static FlacNamespace::FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FlacNamespace::FLAC__StreamEncoder*,
  106171. const FlacNamespace::FLAC__byte buffer[],
  106172. size_t bytes,
  106173. unsigned int /*samples*/,
  106174. unsigned int /*current_frame*/,
  106175. void* client_data)
  106176. {
  106177. using namespace FlacNamespace;
  106178. return static_cast <FlacWriter*> (client_data)->writeData (buffer, (int) bytes)
  106179. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  106180. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  106181. }
  106182. static FlacNamespace::FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64, void*)
  106183. {
  106184. using namespace FlacNamespace;
  106185. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  106186. }
  106187. static FlacNamespace::FLAC__StreamEncoderTellStatus encodeTellCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  106188. {
  106189. using namespace FlacNamespace;
  106190. if (client_data == 0)
  106191. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  106192. *absolute_byte_offset = (FLAC__uint64) static_cast <FlacWriter*> (client_data)->output->getPosition();
  106193. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  106194. }
  106195. static void encodeMetadataCallback (const FlacNamespace::FLAC__StreamEncoder*, const FlacNamespace::FLAC__StreamMetadata* metadata, void* client_data)
  106196. {
  106197. static_cast <FlacWriter*> (client_data)->writeMetaData (metadata);
  106198. }
  106199. juce_UseDebuggingNewOperator
  106200. bool ok;
  106201. private:
  106202. FlacNamespace::FLAC__StreamEncoder* encoder;
  106203. MemoryBlock temp;
  106204. FlacWriter (const FlacWriter&);
  106205. FlacWriter& operator= (const FlacWriter&);
  106206. };
  106207. FlacAudioFormat::FlacAudioFormat()
  106208. : AudioFormat (TRANS (flacFormatName), StringArray (flacExtensions))
  106209. {
  106210. }
  106211. FlacAudioFormat::~FlacAudioFormat()
  106212. {
  106213. }
  106214. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  106215. {
  106216. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  106217. return Array <int> (rates);
  106218. }
  106219. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  106220. {
  106221. const int depths[] = { 16, 24, 0 };
  106222. return Array <int> (depths);
  106223. }
  106224. bool FlacAudioFormat::canDoStereo()
  106225. {
  106226. return true;
  106227. }
  106228. bool FlacAudioFormat::canDoMono()
  106229. {
  106230. return true;
  106231. }
  106232. bool FlacAudioFormat::isCompressed()
  106233. {
  106234. return true;
  106235. }
  106236. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  106237. const bool deleteStreamIfOpeningFails)
  106238. {
  106239. ScopedPointer<FlacReader> r (new FlacReader (in));
  106240. if (r->sampleRate != 0)
  106241. return r.release();
  106242. if (! deleteStreamIfOpeningFails)
  106243. r->input = 0;
  106244. return 0;
  106245. }
  106246. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  106247. double sampleRate,
  106248. unsigned int numberOfChannels,
  106249. int bitsPerSample,
  106250. const StringPairArray& /*metadataValues*/,
  106251. int /*qualityOptionIndex*/)
  106252. {
  106253. if (getPossibleBitDepths().contains (bitsPerSample))
  106254. {
  106255. ScopedPointer<FlacWriter> w (new FlacWriter (out, sampleRate, numberOfChannels, bitsPerSample));
  106256. if (w->ok)
  106257. return w.release();
  106258. }
  106259. return 0;
  106260. }
  106261. END_JUCE_NAMESPACE
  106262. #endif
  106263. /*** End of inlined file: juce_FlacAudioFormat.cpp ***/
  106264. /*** Start of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  106265. #if JUCE_USE_OGGVORBIS
  106266. #if JUCE_MAC
  106267. #define __MACOSX__ 1
  106268. #endif
  106269. namespace OggVorbisNamespace
  106270. {
  106271. #if JUCE_INCLUDE_OGGVORBIS_CODE
  106272. /*** Start of inlined file: vorbisenc.h ***/
  106273. #ifndef _OV_ENC_H_
  106274. #define _OV_ENC_H_
  106275. #ifdef __cplusplus
  106276. extern "C"
  106277. {
  106278. #endif /* __cplusplus */
  106279. /*** Start of inlined file: codec.h ***/
  106280. #ifndef _vorbis_codec_h_
  106281. #define _vorbis_codec_h_
  106282. #ifdef __cplusplus
  106283. extern "C"
  106284. {
  106285. #endif /* __cplusplus */
  106286. /*** Start of inlined file: ogg.h ***/
  106287. #ifndef _OGG_H
  106288. #define _OGG_H
  106289. #ifdef __cplusplus
  106290. extern "C" {
  106291. #endif
  106292. /*** Start of inlined file: os_types.h ***/
  106293. #ifndef _OS_TYPES_H
  106294. #define _OS_TYPES_H
  106295. /* make it easy on the folks that want to compile the libs with a
  106296. different malloc than stdlib */
  106297. #define _ogg_malloc malloc
  106298. #define _ogg_calloc calloc
  106299. #define _ogg_realloc realloc
  106300. #define _ogg_free free
  106301. #if defined(_WIN32)
  106302. # if defined(__CYGWIN__)
  106303. # include <_G_config.h>
  106304. typedef _G_int64_t ogg_int64_t;
  106305. typedef _G_int32_t ogg_int32_t;
  106306. typedef _G_uint32_t ogg_uint32_t;
  106307. typedef _G_int16_t ogg_int16_t;
  106308. typedef _G_uint16_t ogg_uint16_t;
  106309. # elif defined(__MINGW32__)
  106310. typedef short ogg_int16_t;
  106311. typedef unsigned short ogg_uint16_t;
  106312. typedef int ogg_int32_t;
  106313. typedef unsigned int ogg_uint32_t;
  106314. typedef long long ogg_int64_t;
  106315. typedef unsigned long long ogg_uint64_t;
  106316. # elif defined(__MWERKS__)
  106317. typedef long long ogg_int64_t;
  106318. typedef int ogg_int32_t;
  106319. typedef unsigned int ogg_uint32_t;
  106320. typedef short ogg_int16_t;
  106321. typedef unsigned short ogg_uint16_t;
  106322. # else
  106323. /* MSVC/Borland */
  106324. typedef __int64 ogg_int64_t;
  106325. typedef __int32 ogg_int32_t;
  106326. typedef unsigned __int32 ogg_uint32_t;
  106327. typedef __int16 ogg_int16_t;
  106328. typedef unsigned __int16 ogg_uint16_t;
  106329. # endif
  106330. #elif defined(__MACOS__)
  106331. # include <sys/types.h>
  106332. typedef SInt16 ogg_int16_t;
  106333. typedef UInt16 ogg_uint16_t;
  106334. typedef SInt32 ogg_int32_t;
  106335. typedef UInt32 ogg_uint32_t;
  106336. typedef SInt64 ogg_int64_t;
  106337. #elif defined(__MACOSX__) /* MacOS X Framework build */
  106338. # include <sys/types.h>
  106339. typedef int16_t ogg_int16_t;
  106340. typedef u_int16_t ogg_uint16_t;
  106341. typedef int32_t ogg_int32_t;
  106342. typedef u_int32_t ogg_uint32_t;
  106343. typedef int64_t ogg_int64_t;
  106344. #elif defined(__BEOS__)
  106345. /* Be */
  106346. # include <inttypes.h>
  106347. typedef int16_t ogg_int16_t;
  106348. typedef u_int16_t ogg_uint16_t;
  106349. typedef int32_t ogg_int32_t;
  106350. typedef u_int32_t ogg_uint32_t;
  106351. typedef int64_t ogg_int64_t;
  106352. #elif defined (__EMX__)
  106353. /* OS/2 GCC */
  106354. typedef short ogg_int16_t;
  106355. typedef unsigned short ogg_uint16_t;
  106356. typedef int ogg_int32_t;
  106357. typedef unsigned int ogg_uint32_t;
  106358. typedef long long ogg_int64_t;
  106359. #elif defined (DJGPP)
  106360. /* DJGPP */
  106361. typedef short ogg_int16_t;
  106362. typedef int ogg_int32_t;
  106363. typedef unsigned int ogg_uint32_t;
  106364. typedef long long ogg_int64_t;
  106365. #elif defined(R5900)
  106366. /* PS2 EE */
  106367. typedef long ogg_int64_t;
  106368. typedef int ogg_int32_t;
  106369. typedef unsigned ogg_uint32_t;
  106370. typedef short ogg_int16_t;
  106371. #elif defined(__SYMBIAN32__)
  106372. /* Symbian GCC */
  106373. typedef signed short ogg_int16_t;
  106374. typedef unsigned short ogg_uint16_t;
  106375. typedef signed int ogg_int32_t;
  106376. typedef unsigned int ogg_uint32_t;
  106377. typedef long long int ogg_int64_t;
  106378. #else
  106379. # include <sys/types.h>
  106380. /*** Start of inlined file: config_types.h ***/
  106381. #ifndef __CONFIG_TYPES_H__
  106382. #define __CONFIG_TYPES_H__
  106383. typedef int16_t ogg_int16_t;
  106384. typedef unsigned short ogg_uint16_t;
  106385. typedef int32_t ogg_int32_t;
  106386. typedef unsigned int ogg_uint32_t;
  106387. typedef int64_t ogg_int64_t;
  106388. #endif
  106389. /*** End of inlined file: config_types.h ***/
  106390. #endif
  106391. #endif /* _OS_TYPES_H */
  106392. /*** End of inlined file: os_types.h ***/
  106393. typedef struct {
  106394. long endbyte;
  106395. int endbit;
  106396. unsigned char *buffer;
  106397. unsigned char *ptr;
  106398. long storage;
  106399. } oggpack_buffer;
  106400. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  106401. typedef struct {
  106402. unsigned char *header;
  106403. long header_len;
  106404. unsigned char *body;
  106405. long body_len;
  106406. } ogg_page;
  106407. ogg_uint32_t ogg_bitreverse(ogg_uint32_t x){
  106408. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  106409. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  106410. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  106411. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  106412. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  106413. }
  106414. /* ogg_stream_state contains the current encode/decode state of a logical
  106415. Ogg bitstream **********************************************************/
  106416. typedef struct {
  106417. unsigned char *body_data; /* bytes from packet bodies */
  106418. long body_storage; /* storage elements allocated */
  106419. long body_fill; /* elements stored; fill mark */
  106420. long body_returned; /* elements of fill returned */
  106421. int *lacing_vals; /* The values that will go to the segment table */
  106422. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  106423. this way, but it is simple coupled to the
  106424. lacing fifo */
  106425. long lacing_storage;
  106426. long lacing_fill;
  106427. long lacing_packet;
  106428. long lacing_returned;
  106429. unsigned char header[282]; /* working space for header encode */
  106430. int header_fill;
  106431. int e_o_s; /* set when we have buffered the last packet in the
  106432. logical bitstream */
  106433. int b_o_s; /* set after we've written the initial page
  106434. of a logical bitstream */
  106435. long serialno;
  106436. long pageno;
  106437. ogg_int64_t packetno; /* sequence number for decode; the framing
  106438. knows where there's a hole in the data,
  106439. but we need coupling so that the codec
  106440. (which is in a seperate abstraction
  106441. layer) also knows about the gap */
  106442. ogg_int64_t granulepos;
  106443. } ogg_stream_state;
  106444. /* ogg_packet is used to encapsulate the data and metadata belonging
  106445. to a single raw Ogg/Vorbis packet *************************************/
  106446. typedef struct {
  106447. unsigned char *packet;
  106448. long bytes;
  106449. long b_o_s;
  106450. long e_o_s;
  106451. ogg_int64_t granulepos;
  106452. ogg_int64_t packetno; /* sequence number for decode; the framing
  106453. knows where there's a hole in the data,
  106454. but we need coupling so that the codec
  106455. (which is in a seperate abstraction
  106456. layer) also knows about the gap */
  106457. } ogg_packet;
  106458. typedef struct {
  106459. unsigned char *data;
  106460. int storage;
  106461. int fill;
  106462. int returned;
  106463. int unsynced;
  106464. int headerbytes;
  106465. int bodybytes;
  106466. } ogg_sync_state;
  106467. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  106468. extern void oggpack_writeinit(oggpack_buffer *b);
  106469. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  106470. extern void oggpack_writealign(oggpack_buffer *b);
  106471. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  106472. extern void oggpack_reset(oggpack_buffer *b);
  106473. extern void oggpack_writeclear(oggpack_buffer *b);
  106474. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  106475. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  106476. extern long oggpack_look(oggpack_buffer *b,int bits);
  106477. extern long oggpack_look1(oggpack_buffer *b);
  106478. extern void oggpack_adv(oggpack_buffer *b,int bits);
  106479. extern void oggpack_adv1(oggpack_buffer *b);
  106480. extern long oggpack_read(oggpack_buffer *b,int bits);
  106481. extern long oggpack_read1(oggpack_buffer *b);
  106482. extern long oggpack_bytes(oggpack_buffer *b);
  106483. extern long oggpack_bits(oggpack_buffer *b);
  106484. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  106485. extern void oggpackB_writeinit(oggpack_buffer *b);
  106486. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  106487. extern void oggpackB_writealign(oggpack_buffer *b);
  106488. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  106489. extern void oggpackB_reset(oggpack_buffer *b);
  106490. extern void oggpackB_writeclear(oggpack_buffer *b);
  106491. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  106492. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  106493. extern long oggpackB_look(oggpack_buffer *b,int bits);
  106494. extern long oggpackB_look1(oggpack_buffer *b);
  106495. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  106496. extern void oggpackB_adv1(oggpack_buffer *b);
  106497. extern long oggpackB_read(oggpack_buffer *b,int bits);
  106498. extern long oggpackB_read1(oggpack_buffer *b);
  106499. extern long oggpackB_bytes(oggpack_buffer *b);
  106500. extern long oggpackB_bits(oggpack_buffer *b);
  106501. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  106502. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  106503. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  106504. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  106505. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  106506. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  106507. extern int ogg_sync_init(ogg_sync_state *oy);
  106508. extern int ogg_sync_clear(ogg_sync_state *oy);
  106509. extern int ogg_sync_reset(ogg_sync_state *oy);
  106510. extern int ogg_sync_destroy(ogg_sync_state *oy);
  106511. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  106512. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  106513. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  106514. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  106515. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  106516. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  106517. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  106518. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  106519. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  106520. extern int ogg_stream_clear(ogg_stream_state *os);
  106521. extern int ogg_stream_reset(ogg_stream_state *os);
  106522. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  106523. extern int ogg_stream_destroy(ogg_stream_state *os);
  106524. extern int ogg_stream_eos(ogg_stream_state *os);
  106525. extern void ogg_page_checksum_set(ogg_page *og);
  106526. extern int ogg_page_version(ogg_page *og);
  106527. extern int ogg_page_continued(ogg_page *og);
  106528. extern int ogg_page_bos(ogg_page *og);
  106529. extern int ogg_page_eos(ogg_page *og);
  106530. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  106531. extern int ogg_page_serialno(ogg_page *og);
  106532. extern long ogg_page_pageno(ogg_page *og);
  106533. extern int ogg_page_packets(ogg_page *og);
  106534. extern void ogg_packet_clear(ogg_packet *op);
  106535. #ifdef __cplusplus
  106536. }
  106537. #endif
  106538. #endif /* _OGG_H */
  106539. /*** End of inlined file: ogg.h ***/
  106540. typedef struct vorbis_info{
  106541. int version;
  106542. int channels;
  106543. long rate;
  106544. /* The below bitrate declarations are *hints*.
  106545. Combinations of the three values carry the following implications:
  106546. all three set to the same value:
  106547. implies a fixed rate bitstream
  106548. only nominal set:
  106549. implies a VBR stream that averages the nominal bitrate. No hard
  106550. upper/lower limit
  106551. upper and or lower set:
  106552. implies a VBR bitstream that obeys the bitrate limits. nominal
  106553. may also be set to give a nominal rate.
  106554. none set:
  106555. the coder does not care to speculate.
  106556. */
  106557. long bitrate_upper;
  106558. long bitrate_nominal;
  106559. long bitrate_lower;
  106560. long bitrate_window;
  106561. void *codec_setup;
  106562. } vorbis_info;
  106563. /* vorbis_dsp_state buffers the current vorbis audio
  106564. analysis/synthesis state. The DSP state belongs to a specific
  106565. logical bitstream ****************************************************/
  106566. typedef struct vorbis_dsp_state{
  106567. int analysisp;
  106568. vorbis_info *vi;
  106569. float **pcm;
  106570. float **pcmret;
  106571. int pcm_storage;
  106572. int pcm_current;
  106573. int pcm_returned;
  106574. int preextrapolate;
  106575. int eofflag;
  106576. long lW;
  106577. long W;
  106578. long nW;
  106579. long centerW;
  106580. ogg_int64_t granulepos;
  106581. ogg_int64_t sequence;
  106582. ogg_int64_t glue_bits;
  106583. ogg_int64_t time_bits;
  106584. ogg_int64_t floor_bits;
  106585. ogg_int64_t res_bits;
  106586. void *backend_state;
  106587. } vorbis_dsp_state;
  106588. typedef struct vorbis_block{
  106589. /* necessary stream state for linking to the framing abstraction */
  106590. float **pcm; /* this is a pointer into local storage */
  106591. oggpack_buffer opb;
  106592. long lW;
  106593. long W;
  106594. long nW;
  106595. int pcmend;
  106596. int mode;
  106597. int eofflag;
  106598. ogg_int64_t granulepos;
  106599. ogg_int64_t sequence;
  106600. vorbis_dsp_state *vd; /* For read-only access of configuration */
  106601. /* local storage to avoid remallocing; it's up to the mapping to
  106602. structure it */
  106603. void *localstore;
  106604. long localtop;
  106605. long localalloc;
  106606. long totaluse;
  106607. struct alloc_chain *reap;
  106608. /* bitmetrics for the frame */
  106609. long glue_bits;
  106610. long time_bits;
  106611. long floor_bits;
  106612. long res_bits;
  106613. void *internal;
  106614. } vorbis_block;
  106615. /* vorbis_block is a single block of data to be processed as part of
  106616. the analysis/synthesis stream; it belongs to a specific logical
  106617. bitstream, but is independant from other vorbis_blocks belonging to
  106618. that logical bitstream. *************************************************/
  106619. struct alloc_chain{
  106620. void *ptr;
  106621. struct alloc_chain *next;
  106622. };
  106623. /* vorbis_info contains all the setup information specific to the
  106624. specific compression/decompression mode in progress (eg,
  106625. psychoacoustic settings, channel setup, options, codebook
  106626. etc). vorbis_info and substructures are in backends.h.
  106627. *********************************************************************/
  106628. /* the comments are not part of vorbis_info so that vorbis_info can be
  106629. static storage */
  106630. typedef struct vorbis_comment{
  106631. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  106632. whatever vendor is set to in encode */
  106633. char **user_comments;
  106634. int *comment_lengths;
  106635. int comments;
  106636. char *vendor;
  106637. } vorbis_comment;
  106638. /* libvorbis encodes in two abstraction layers; first we perform DSP
  106639. and produce a packet (see docs/analysis.txt). The packet is then
  106640. coded into a framed OggSquish bitstream by the second layer (see
  106641. docs/framing.txt). Decode is the reverse process; we sync/frame
  106642. the bitstream and extract individual packets, then decode the
  106643. packet back into PCM audio.
  106644. The extra framing/packetizing is used in streaming formats, such as
  106645. files. Over the net (such as with UDP), the framing and
  106646. packetization aren't necessary as they're provided by the transport
  106647. and the streaming layer is not used */
  106648. /* Vorbis PRIMITIVES: general ***************************************/
  106649. extern void vorbis_info_init(vorbis_info *vi);
  106650. extern void vorbis_info_clear(vorbis_info *vi);
  106651. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  106652. extern void vorbis_comment_init(vorbis_comment *vc);
  106653. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  106654. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  106655. const char *tag, char *contents);
  106656. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  106657. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  106658. extern void vorbis_comment_clear(vorbis_comment *vc);
  106659. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  106660. extern int vorbis_block_clear(vorbis_block *vb);
  106661. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  106662. extern double vorbis_granule_time(vorbis_dsp_state *v,
  106663. ogg_int64_t granulepos);
  106664. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  106665. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  106666. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  106667. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  106668. vorbis_comment *vc,
  106669. ogg_packet *op,
  106670. ogg_packet *op_comm,
  106671. ogg_packet *op_code);
  106672. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  106673. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  106674. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  106675. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  106676. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  106677. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  106678. ogg_packet *op);
  106679. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  106680. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  106681. ogg_packet *op);
  106682. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  106683. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  106684. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  106685. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  106686. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  106687. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  106688. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  106689. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  106690. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  106691. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  106692. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  106693. /* Vorbis ERRORS and return codes ***********************************/
  106694. #define OV_FALSE -1
  106695. #define OV_EOF -2
  106696. #define OV_HOLE -3
  106697. #define OV_EREAD -128
  106698. #define OV_EFAULT -129
  106699. #define OV_EIMPL -130
  106700. #define OV_EINVAL -131
  106701. #define OV_ENOTVORBIS -132
  106702. #define OV_EBADHEADER -133
  106703. #define OV_EVERSION -134
  106704. #define OV_ENOTAUDIO -135
  106705. #define OV_EBADPACKET -136
  106706. #define OV_EBADLINK -137
  106707. #define OV_ENOSEEK -138
  106708. #ifdef __cplusplus
  106709. }
  106710. #endif /* __cplusplus */
  106711. #endif
  106712. /*** End of inlined file: codec.h ***/
  106713. extern int vorbis_encode_init(vorbis_info *vi,
  106714. long channels,
  106715. long rate,
  106716. long max_bitrate,
  106717. long nominal_bitrate,
  106718. long min_bitrate);
  106719. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  106720. long channels,
  106721. long rate,
  106722. long max_bitrate,
  106723. long nominal_bitrate,
  106724. long min_bitrate);
  106725. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  106726. long channels,
  106727. long rate,
  106728. float quality /* quality level from 0. (lo) to 1. (hi) */
  106729. );
  106730. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  106731. long channels,
  106732. long rate,
  106733. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  106734. );
  106735. extern int vorbis_encode_setup_init(vorbis_info *vi);
  106736. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  106737. /* deprecated rate management supported only for compatability */
  106738. #define OV_ECTL_RATEMANAGE_GET 0x10
  106739. #define OV_ECTL_RATEMANAGE_SET 0x11
  106740. #define OV_ECTL_RATEMANAGE_AVG 0x12
  106741. #define OV_ECTL_RATEMANAGE_HARD 0x13
  106742. struct ovectl_ratemanage_arg {
  106743. int management_active;
  106744. long bitrate_hard_min;
  106745. long bitrate_hard_max;
  106746. double bitrate_hard_window;
  106747. long bitrate_av_lo;
  106748. long bitrate_av_hi;
  106749. double bitrate_av_window;
  106750. double bitrate_av_window_center;
  106751. };
  106752. /* new rate setup */
  106753. #define OV_ECTL_RATEMANAGE2_GET 0x14
  106754. #define OV_ECTL_RATEMANAGE2_SET 0x15
  106755. struct ovectl_ratemanage2_arg {
  106756. int management_active;
  106757. long bitrate_limit_min_kbps;
  106758. long bitrate_limit_max_kbps;
  106759. long bitrate_limit_reservoir_bits;
  106760. double bitrate_limit_reservoir_bias;
  106761. long bitrate_average_kbps;
  106762. double bitrate_average_damping;
  106763. };
  106764. #define OV_ECTL_LOWPASS_GET 0x20
  106765. #define OV_ECTL_LOWPASS_SET 0x21
  106766. #define OV_ECTL_IBLOCK_GET 0x30
  106767. #define OV_ECTL_IBLOCK_SET 0x31
  106768. #ifdef __cplusplus
  106769. }
  106770. #endif /* __cplusplus */
  106771. #endif
  106772. /*** End of inlined file: vorbisenc.h ***/
  106773. /*** Start of inlined file: vorbisfile.h ***/
  106774. #ifndef _OV_FILE_H_
  106775. #define _OV_FILE_H_
  106776. #ifdef __cplusplus
  106777. extern "C"
  106778. {
  106779. #endif /* __cplusplus */
  106780. #include <stdio.h>
  106781. /* The function prototypes for the callbacks are basically the same as for
  106782. * the stdio functions fread, fseek, fclose, ftell.
  106783. * The one difference is that the FILE * arguments have been replaced with
  106784. * a void * - this is to be used as a pointer to whatever internal data these
  106785. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  106786. *
  106787. * If you use other functions, check the docs for these functions and return
  106788. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  106789. * unseekable
  106790. */
  106791. typedef struct {
  106792. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  106793. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  106794. int (*close_func) (void *datasource);
  106795. long (*tell_func) (void *datasource);
  106796. } ov_callbacks;
  106797. #define NOTOPEN 0
  106798. #define PARTOPEN 1
  106799. #define OPENED 2
  106800. #define STREAMSET 3
  106801. #define INITSET 4
  106802. typedef struct OggVorbis_File {
  106803. void *datasource; /* Pointer to a FILE *, etc. */
  106804. int seekable;
  106805. ogg_int64_t offset;
  106806. ogg_int64_t end;
  106807. ogg_sync_state oy;
  106808. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  106809. stream appears */
  106810. int links;
  106811. ogg_int64_t *offsets;
  106812. ogg_int64_t *dataoffsets;
  106813. long *serialnos;
  106814. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  106815. compatability; x2 size, stores both
  106816. beginning and end values */
  106817. vorbis_info *vi;
  106818. vorbis_comment *vc;
  106819. /* Decoding working state local storage */
  106820. ogg_int64_t pcm_offset;
  106821. int ready_state;
  106822. long current_serialno;
  106823. int current_link;
  106824. double bittrack;
  106825. double samptrack;
  106826. ogg_stream_state os; /* take physical pages, weld into a logical
  106827. stream of packets */
  106828. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  106829. vorbis_block vb; /* local working space for packet->PCM decode */
  106830. ov_callbacks callbacks;
  106831. } OggVorbis_File;
  106832. extern int ov_clear(OggVorbis_File *vf);
  106833. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  106834. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  106835. char *initial, long ibytes, ov_callbacks callbacks);
  106836. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  106837. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  106838. char *initial, long ibytes, ov_callbacks callbacks);
  106839. extern int ov_test_open(OggVorbis_File *vf);
  106840. extern long ov_bitrate(OggVorbis_File *vf,int i);
  106841. extern long ov_bitrate_instant(OggVorbis_File *vf);
  106842. extern long ov_streams(OggVorbis_File *vf);
  106843. extern long ov_seekable(OggVorbis_File *vf);
  106844. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  106845. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  106846. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  106847. extern double ov_time_total(OggVorbis_File *vf,int i);
  106848. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  106849. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  106850. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  106851. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  106852. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  106853. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  106854. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  106855. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  106856. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  106857. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  106858. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  106859. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  106860. extern double ov_time_tell(OggVorbis_File *vf);
  106861. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  106862. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  106863. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  106864. int *bitstream);
  106865. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  106866. int bigendianp,int word,int sgned,int *bitstream);
  106867. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  106868. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  106869. extern int ov_halfrate_p(OggVorbis_File *vf);
  106870. #ifdef __cplusplus
  106871. }
  106872. #endif /* __cplusplus */
  106873. #endif
  106874. /*** End of inlined file: vorbisfile.h ***/
  106875. /*** Start of inlined file: bitwise.c ***/
  106876. /* We're 'LSb' endian; if we write a word but read individual bits,
  106877. then we'll read the lsb first */
  106878. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  106879. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  106880. // tasks..
  106881. #if JUCE_MSVC
  106882. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  106883. #endif
  106884. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  106885. #if JUCE_USE_OGGVORBIS
  106886. #include <string.h>
  106887. #include <stdlib.h>
  106888. #define BUFFER_INCREMENT 256
  106889. static const unsigned long mask[]=
  106890. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  106891. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  106892. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  106893. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  106894. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  106895. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  106896. 0x3fffffff,0x7fffffff,0xffffffff };
  106897. static const unsigned int mask8B[]=
  106898. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  106899. void oggpack_writeinit(oggpack_buffer *b){
  106900. memset(b,0,sizeof(*b));
  106901. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  106902. b->buffer[0]='\0';
  106903. b->storage=BUFFER_INCREMENT;
  106904. }
  106905. void oggpackB_writeinit(oggpack_buffer *b){
  106906. oggpack_writeinit(b);
  106907. }
  106908. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  106909. long bytes=bits>>3;
  106910. bits-=bytes*8;
  106911. b->ptr=b->buffer+bytes;
  106912. b->endbit=bits;
  106913. b->endbyte=bytes;
  106914. *b->ptr&=mask[bits];
  106915. }
  106916. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  106917. long bytes=bits>>3;
  106918. bits-=bytes*8;
  106919. b->ptr=b->buffer+bytes;
  106920. b->endbit=bits;
  106921. b->endbyte=bytes;
  106922. *b->ptr&=mask8B[bits];
  106923. }
  106924. /* Takes only up to 32 bits. */
  106925. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  106926. if(b->endbyte+4>=b->storage){
  106927. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  106928. b->storage+=BUFFER_INCREMENT;
  106929. b->ptr=b->buffer+b->endbyte;
  106930. }
  106931. value&=mask[bits];
  106932. bits+=b->endbit;
  106933. b->ptr[0]|=value<<b->endbit;
  106934. if(bits>=8){
  106935. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  106936. if(bits>=16){
  106937. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  106938. if(bits>=24){
  106939. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  106940. if(bits>=32){
  106941. if(b->endbit)
  106942. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  106943. else
  106944. b->ptr[4]=0;
  106945. }
  106946. }
  106947. }
  106948. }
  106949. b->endbyte+=bits/8;
  106950. b->ptr+=bits/8;
  106951. b->endbit=bits&7;
  106952. }
  106953. /* Takes only up to 32 bits. */
  106954. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  106955. if(b->endbyte+4>=b->storage){
  106956. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  106957. b->storage+=BUFFER_INCREMENT;
  106958. b->ptr=b->buffer+b->endbyte;
  106959. }
  106960. value=(value&mask[bits])<<(32-bits);
  106961. bits+=b->endbit;
  106962. b->ptr[0]|=value>>(24+b->endbit);
  106963. if(bits>=8){
  106964. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  106965. if(bits>=16){
  106966. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  106967. if(bits>=24){
  106968. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  106969. if(bits>=32){
  106970. if(b->endbit)
  106971. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  106972. else
  106973. b->ptr[4]=0;
  106974. }
  106975. }
  106976. }
  106977. }
  106978. b->endbyte+=bits/8;
  106979. b->ptr+=bits/8;
  106980. b->endbit=bits&7;
  106981. }
  106982. void oggpack_writealign(oggpack_buffer *b){
  106983. int bits=8-b->endbit;
  106984. if(bits<8)
  106985. oggpack_write(b,0,bits);
  106986. }
  106987. void oggpackB_writealign(oggpack_buffer *b){
  106988. int bits=8-b->endbit;
  106989. if(bits<8)
  106990. oggpackB_write(b,0,bits);
  106991. }
  106992. static void oggpack_writecopy_helper(oggpack_buffer *b,
  106993. void *source,
  106994. long bits,
  106995. void (*w)(oggpack_buffer *,
  106996. unsigned long,
  106997. int),
  106998. int msb){
  106999. unsigned char *ptr=(unsigned char *)source;
  107000. long bytes=bits/8;
  107001. bits-=bytes*8;
  107002. if(b->endbit){
  107003. int i;
  107004. /* unaligned copy. Do it the hard way. */
  107005. for(i=0;i<bytes;i++)
  107006. w(b,(unsigned long)(ptr[i]),8);
  107007. }else{
  107008. /* aligned block copy */
  107009. if(b->endbyte+bytes+1>=b->storage){
  107010. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  107011. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  107012. b->ptr=b->buffer+b->endbyte;
  107013. }
  107014. memmove(b->ptr,source,bytes);
  107015. b->ptr+=bytes;
  107016. b->endbyte+=bytes;
  107017. *b->ptr=0;
  107018. }
  107019. if(bits){
  107020. if(msb)
  107021. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  107022. else
  107023. w(b,(unsigned long)(ptr[bytes]),bits);
  107024. }
  107025. }
  107026. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  107027. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  107028. }
  107029. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  107030. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  107031. }
  107032. void oggpack_reset(oggpack_buffer *b){
  107033. b->ptr=b->buffer;
  107034. b->buffer[0]=0;
  107035. b->endbit=b->endbyte=0;
  107036. }
  107037. void oggpackB_reset(oggpack_buffer *b){
  107038. oggpack_reset(b);
  107039. }
  107040. void oggpack_writeclear(oggpack_buffer *b){
  107041. _ogg_free(b->buffer);
  107042. memset(b,0,sizeof(*b));
  107043. }
  107044. void oggpackB_writeclear(oggpack_buffer *b){
  107045. oggpack_writeclear(b);
  107046. }
  107047. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  107048. memset(b,0,sizeof(*b));
  107049. b->buffer=b->ptr=buf;
  107050. b->storage=bytes;
  107051. }
  107052. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  107053. oggpack_readinit(b,buf,bytes);
  107054. }
  107055. /* Read in bits without advancing the bitptr; bits <= 32 */
  107056. long oggpack_look(oggpack_buffer *b,int bits){
  107057. unsigned long ret;
  107058. unsigned long m=mask[bits];
  107059. bits+=b->endbit;
  107060. if(b->endbyte+4>=b->storage){
  107061. /* not the main path */
  107062. if(b->endbyte*8+bits>b->storage*8)return(-1);
  107063. }
  107064. ret=b->ptr[0]>>b->endbit;
  107065. if(bits>8){
  107066. ret|=b->ptr[1]<<(8-b->endbit);
  107067. if(bits>16){
  107068. ret|=b->ptr[2]<<(16-b->endbit);
  107069. if(bits>24){
  107070. ret|=b->ptr[3]<<(24-b->endbit);
  107071. if(bits>32 && b->endbit)
  107072. ret|=b->ptr[4]<<(32-b->endbit);
  107073. }
  107074. }
  107075. }
  107076. return(m&ret);
  107077. }
  107078. /* Read in bits without advancing the bitptr; bits <= 32 */
  107079. long oggpackB_look(oggpack_buffer *b,int bits){
  107080. unsigned long ret;
  107081. int m=32-bits;
  107082. bits+=b->endbit;
  107083. if(b->endbyte+4>=b->storage){
  107084. /* not the main path */
  107085. if(b->endbyte*8+bits>b->storage*8)return(-1);
  107086. }
  107087. ret=b->ptr[0]<<(24+b->endbit);
  107088. if(bits>8){
  107089. ret|=b->ptr[1]<<(16+b->endbit);
  107090. if(bits>16){
  107091. ret|=b->ptr[2]<<(8+b->endbit);
  107092. if(bits>24){
  107093. ret|=b->ptr[3]<<(b->endbit);
  107094. if(bits>32 && b->endbit)
  107095. ret|=b->ptr[4]>>(8-b->endbit);
  107096. }
  107097. }
  107098. }
  107099. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  107100. }
  107101. long oggpack_look1(oggpack_buffer *b){
  107102. if(b->endbyte>=b->storage)return(-1);
  107103. return((b->ptr[0]>>b->endbit)&1);
  107104. }
  107105. long oggpackB_look1(oggpack_buffer *b){
  107106. if(b->endbyte>=b->storage)return(-1);
  107107. return((b->ptr[0]>>(7-b->endbit))&1);
  107108. }
  107109. void oggpack_adv(oggpack_buffer *b,int bits){
  107110. bits+=b->endbit;
  107111. b->ptr+=bits/8;
  107112. b->endbyte+=bits/8;
  107113. b->endbit=bits&7;
  107114. }
  107115. void oggpackB_adv(oggpack_buffer *b,int bits){
  107116. oggpack_adv(b,bits);
  107117. }
  107118. void oggpack_adv1(oggpack_buffer *b){
  107119. if(++(b->endbit)>7){
  107120. b->endbit=0;
  107121. b->ptr++;
  107122. b->endbyte++;
  107123. }
  107124. }
  107125. void oggpackB_adv1(oggpack_buffer *b){
  107126. oggpack_adv1(b);
  107127. }
  107128. /* bits <= 32 */
  107129. long oggpack_read(oggpack_buffer *b,int bits){
  107130. long ret;
  107131. unsigned long m=mask[bits];
  107132. bits+=b->endbit;
  107133. if(b->endbyte+4>=b->storage){
  107134. /* not the main path */
  107135. ret=-1L;
  107136. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  107137. }
  107138. ret=b->ptr[0]>>b->endbit;
  107139. if(bits>8){
  107140. ret|=b->ptr[1]<<(8-b->endbit);
  107141. if(bits>16){
  107142. ret|=b->ptr[2]<<(16-b->endbit);
  107143. if(bits>24){
  107144. ret|=b->ptr[3]<<(24-b->endbit);
  107145. if(bits>32 && b->endbit){
  107146. ret|=b->ptr[4]<<(32-b->endbit);
  107147. }
  107148. }
  107149. }
  107150. }
  107151. ret&=m;
  107152. overflow:
  107153. b->ptr+=bits/8;
  107154. b->endbyte+=bits/8;
  107155. b->endbit=bits&7;
  107156. return(ret);
  107157. }
  107158. /* bits <= 32 */
  107159. long oggpackB_read(oggpack_buffer *b,int bits){
  107160. long ret;
  107161. long m=32-bits;
  107162. bits+=b->endbit;
  107163. if(b->endbyte+4>=b->storage){
  107164. /* not the main path */
  107165. ret=-1L;
  107166. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  107167. }
  107168. ret=b->ptr[0]<<(24+b->endbit);
  107169. if(bits>8){
  107170. ret|=b->ptr[1]<<(16+b->endbit);
  107171. if(bits>16){
  107172. ret|=b->ptr[2]<<(8+b->endbit);
  107173. if(bits>24){
  107174. ret|=b->ptr[3]<<(b->endbit);
  107175. if(bits>32 && b->endbit)
  107176. ret|=b->ptr[4]>>(8-b->endbit);
  107177. }
  107178. }
  107179. }
  107180. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  107181. overflow:
  107182. b->ptr+=bits/8;
  107183. b->endbyte+=bits/8;
  107184. b->endbit=bits&7;
  107185. return(ret);
  107186. }
  107187. long oggpack_read1(oggpack_buffer *b){
  107188. long ret;
  107189. if(b->endbyte>=b->storage){
  107190. /* not the main path */
  107191. ret=-1L;
  107192. goto overflow;
  107193. }
  107194. ret=(b->ptr[0]>>b->endbit)&1;
  107195. overflow:
  107196. b->endbit++;
  107197. if(b->endbit>7){
  107198. b->endbit=0;
  107199. b->ptr++;
  107200. b->endbyte++;
  107201. }
  107202. return(ret);
  107203. }
  107204. long oggpackB_read1(oggpack_buffer *b){
  107205. long ret;
  107206. if(b->endbyte>=b->storage){
  107207. /* not the main path */
  107208. ret=-1L;
  107209. goto overflow;
  107210. }
  107211. ret=(b->ptr[0]>>(7-b->endbit))&1;
  107212. overflow:
  107213. b->endbit++;
  107214. if(b->endbit>7){
  107215. b->endbit=0;
  107216. b->ptr++;
  107217. b->endbyte++;
  107218. }
  107219. return(ret);
  107220. }
  107221. long oggpack_bytes(oggpack_buffer *b){
  107222. return(b->endbyte+(b->endbit+7)/8);
  107223. }
  107224. long oggpack_bits(oggpack_buffer *b){
  107225. return(b->endbyte*8+b->endbit);
  107226. }
  107227. long oggpackB_bytes(oggpack_buffer *b){
  107228. return oggpack_bytes(b);
  107229. }
  107230. long oggpackB_bits(oggpack_buffer *b){
  107231. return oggpack_bits(b);
  107232. }
  107233. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  107234. return(b->buffer);
  107235. }
  107236. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  107237. return oggpack_get_buffer(b);
  107238. }
  107239. /* Self test of the bitwise routines; everything else is based on
  107240. them, so they damned well better be solid. */
  107241. #ifdef _V_SELFTEST
  107242. #include <stdio.h>
  107243. static int ilog(unsigned int v){
  107244. int ret=0;
  107245. while(v){
  107246. ret++;
  107247. v>>=1;
  107248. }
  107249. return(ret);
  107250. }
  107251. oggpack_buffer o;
  107252. oggpack_buffer r;
  107253. void report(char *in){
  107254. fprintf(stderr,"%s",in);
  107255. exit(1);
  107256. }
  107257. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  107258. long bytes,i;
  107259. unsigned char *buffer;
  107260. oggpack_reset(&o);
  107261. for(i=0;i<vals;i++)
  107262. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  107263. buffer=oggpack_get_buffer(&o);
  107264. bytes=oggpack_bytes(&o);
  107265. if(bytes!=compsize)report("wrong number of bytes!\n");
  107266. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  107267. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  107268. report("wrote incorrect value!\n");
  107269. }
  107270. oggpack_readinit(&r,buffer,bytes);
  107271. for(i=0;i<vals;i++){
  107272. int tbit=bits?bits:ilog(b[i]);
  107273. if(oggpack_look(&r,tbit)==-1)
  107274. report("out of data!\n");
  107275. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  107276. report("looked at incorrect value!\n");
  107277. if(tbit==1)
  107278. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  107279. report("looked at single bit incorrect value!\n");
  107280. if(tbit==1){
  107281. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  107282. report("read incorrect single bit value!\n");
  107283. }else{
  107284. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  107285. report("read incorrect value!\n");
  107286. }
  107287. }
  107288. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  107289. }
  107290. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  107291. long bytes,i;
  107292. unsigned char *buffer;
  107293. oggpackB_reset(&o);
  107294. for(i=0;i<vals;i++)
  107295. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  107296. buffer=oggpackB_get_buffer(&o);
  107297. bytes=oggpackB_bytes(&o);
  107298. if(bytes!=compsize)report("wrong number of bytes!\n");
  107299. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  107300. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  107301. report("wrote incorrect value!\n");
  107302. }
  107303. oggpackB_readinit(&r,buffer,bytes);
  107304. for(i=0;i<vals;i++){
  107305. int tbit=bits?bits:ilog(b[i]);
  107306. if(oggpackB_look(&r,tbit)==-1)
  107307. report("out of data!\n");
  107308. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  107309. report("looked at incorrect value!\n");
  107310. if(tbit==1)
  107311. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  107312. report("looked at single bit incorrect value!\n");
  107313. if(tbit==1){
  107314. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  107315. report("read incorrect single bit value!\n");
  107316. }else{
  107317. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  107318. report("read incorrect value!\n");
  107319. }
  107320. }
  107321. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  107322. }
  107323. int main(void){
  107324. unsigned char *buffer;
  107325. long bytes,i;
  107326. static unsigned long testbuffer1[]=
  107327. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  107328. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  107329. int test1size=43;
  107330. static unsigned long testbuffer2[]=
  107331. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  107332. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  107333. 85525151,0,12321,1,349528352};
  107334. int test2size=21;
  107335. static unsigned long testbuffer3[]=
  107336. {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,
  107337. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  107338. int test3size=56;
  107339. static unsigned long large[]=
  107340. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  107341. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  107342. 85525151,0,12321,1,2146528352};
  107343. int onesize=33;
  107344. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  107345. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  107346. 223,4};
  107347. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  107348. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  107349. 245,251,128};
  107350. int twosize=6;
  107351. static int two[6]={61,255,255,251,231,29};
  107352. static int twoB[6]={247,63,255,253,249,120};
  107353. int threesize=54;
  107354. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  107355. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  107356. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  107357. 100,52,4,14,18,86,77,1};
  107358. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  107359. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  107360. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  107361. 200,20,254,4,58,106,176,144,0};
  107362. int foursize=38;
  107363. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  107364. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  107365. 28,2,133,0,1};
  107366. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  107367. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  107368. 129,10,4,32};
  107369. int fivesize=45;
  107370. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  107371. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  107372. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  107373. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  107374. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  107375. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  107376. int sixsize=7;
  107377. static int six[7]={17,177,170,242,169,19,148};
  107378. static int sixB[7]={136,141,85,79,149,200,41};
  107379. /* Test read/write together */
  107380. /* Later we test against pregenerated bitstreams */
  107381. oggpack_writeinit(&o);
  107382. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  107383. cliptest(testbuffer1,test1size,0,one,onesize);
  107384. fprintf(stderr,"ok.");
  107385. fprintf(stderr,"\nNull bit call (LSb): ");
  107386. cliptest(testbuffer3,test3size,0,two,twosize);
  107387. fprintf(stderr,"ok.");
  107388. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  107389. cliptest(testbuffer2,test2size,0,three,threesize);
  107390. fprintf(stderr,"ok.");
  107391. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  107392. oggpack_reset(&o);
  107393. for(i=0;i<test2size;i++)
  107394. oggpack_write(&o,large[i],32);
  107395. buffer=oggpack_get_buffer(&o);
  107396. bytes=oggpack_bytes(&o);
  107397. oggpack_readinit(&r,buffer,bytes);
  107398. for(i=0;i<test2size;i++){
  107399. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  107400. if(oggpack_look(&r,32)!=large[i]){
  107401. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  107402. oggpack_look(&r,32),large[i]);
  107403. report("read incorrect value!\n");
  107404. }
  107405. oggpack_adv(&r,32);
  107406. }
  107407. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  107408. fprintf(stderr,"ok.");
  107409. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  107410. cliptest(testbuffer1,test1size,7,four,foursize);
  107411. fprintf(stderr,"ok.");
  107412. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  107413. cliptest(testbuffer2,test2size,17,five,fivesize);
  107414. fprintf(stderr,"ok.");
  107415. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  107416. cliptest(testbuffer3,test3size,1,six,sixsize);
  107417. fprintf(stderr,"ok.");
  107418. fprintf(stderr,"\nTesting read past end (LSb): ");
  107419. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  107420. for(i=0;i<64;i++){
  107421. if(oggpack_read(&r,1)!=0){
  107422. fprintf(stderr,"failed; got -1 prematurely.\n");
  107423. exit(1);
  107424. }
  107425. }
  107426. if(oggpack_look(&r,1)!=-1 ||
  107427. oggpack_read(&r,1)!=-1){
  107428. fprintf(stderr,"failed; read past end without -1.\n");
  107429. exit(1);
  107430. }
  107431. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  107432. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  107433. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  107434. exit(1);
  107435. }
  107436. if(oggpack_look(&r,18)!=0 ||
  107437. oggpack_look(&r,18)!=0){
  107438. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  107439. exit(1);
  107440. }
  107441. if(oggpack_look(&r,19)!=-1 ||
  107442. oggpack_look(&r,19)!=-1){
  107443. fprintf(stderr,"failed; read past end without -1.\n");
  107444. exit(1);
  107445. }
  107446. if(oggpack_look(&r,32)!=-1 ||
  107447. oggpack_look(&r,32)!=-1){
  107448. fprintf(stderr,"failed; read past end without -1.\n");
  107449. exit(1);
  107450. }
  107451. oggpack_writeclear(&o);
  107452. fprintf(stderr,"ok.\n");
  107453. /********** lazy, cut-n-paste retest with MSb packing ***********/
  107454. /* Test read/write together */
  107455. /* Later we test against pregenerated bitstreams */
  107456. oggpackB_writeinit(&o);
  107457. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  107458. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  107459. fprintf(stderr,"ok.");
  107460. fprintf(stderr,"\nNull bit call (MSb): ");
  107461. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  107462. fprintf(stderr,"ok.");
  107463. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  107464. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  107465. fprintf(stderr,"ok.");
  107466. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  107467. oggpackB_reset(&o);
  107468. for(i=0;i<test2size;i++)
  107469. oggpackB_write(&o,large[i],32);
  107470. buffer=oggpackB_get_buffer(&o);
  107471. bytes=oggpackB_bytes(&o);
  107472. oggpackB_readinit(&r,buffer,bytes);
  107473. for(i=0;i<test2size;i++){
  107474. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  107475. if(oggpackB_look(&r,32)!=large[i]){
  107476. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  107477. oggpackB_look(&r,32),large[i]);
  107478. report("read incorrect value!\n");
  107479. }
  107480. oggpackB_adv(&r,32);
  107481. }
  107482. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  107483. fprintf(stderr,"ok.");
  107484. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  107485. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  107486. fprintf(stderr,"ok.");
  107487. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  107488. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  107489. fprintf(stderr,"ok.");
  107490. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  107491. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  107492. fprintf(stderr,"ok.");
  107493. fprintf(stderr,"\nTesting read past end (MSb): ");
  107494. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  107495. for(i=0;i<64;i++){
  107496. if(oggpackB_read(&r,1)!=0){
  107497. fprintf(stderr,"failed; got -1 prematurely.\n");
  107498. exit(1);
  107499. }
  107500. }
  107501. if(oggpackB_look(&r,1)!=-1 ||
  107502. oggpackB_read(&r,1)!=-1){
  107503. fprintf(stderr,"failed; read past end without -1.\n");
  107504. exit(1);
  107505. }
  107506. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  107507. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  107508. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  107509. exit(1);
  107510. }
  107511. if(oggpackB_look(&r,18)!=0 ||
  107512. oggpackB_look(&r,18)!=0){
  107513. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  107514. exit(1);
  107515. }
  107516. if(oggpackB_look(&r,19)!=-1 ||
  107517. oggpackB_look(&r,19)!=-1){
  107518. fprintf(stderr,"failed; read past end without -1.\n");
  107519. exit(1);
  107520. }
  107521. if(oggpackB_look(&r,32)!=-1 ||
  107522. oggpackB_look(&r,32)!=-1){
  107523. fprintf(stderr,"failed; read past end without -1.\n");
  107524. exit(1);
  107525. }
  107526. oggpackB_writeclear(&o);
  107527. fprintf(stderr,"ok.\n\n");
  107528. return(0);
  107529. }
  107530. #endif /* _V_SELFTEST */
  107531. #undef BUFFER_INCREMENT
  107532. #endif
  107533. /*** End of inlined file: bitwise.c ***/
  107534. /*** Start of inlined file: framing.c ***/
  107535. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  107536. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107537. // tasks..
  107538. #if JUCE_MSVC
  107539. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107540. #endif
  107541. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  107542. #if JUCE_USE_OGGVORBIS
  107543. #include <stdlib.h>
  107544. #include <string.h>
  107545. /* A complete description of Ogg framing exists in docs/framing.html */
  107546. int ogg_page_version(ogg_page *og){
  107547. return((int)(og->header[4]));
  107548. }
  107549. int ogg_page_continued(ogg_page *og){
  107550. return((int)(og->header[5]&0x01));
  107551. }
  107552. int ogg_page_bos(ogg_page *og){
  107553. return((int)(og->header[5]&0x02));
  107554. }
  107555. int ogg_page_eos(ogg_page *og){
  107556. return((int)(og->header[5]&0x04));
  107557. }
  107558. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  107559. unsigned char *page=og->header;
  107560. ogg_int64_t granulepos=page[13]&(0xff);
  107561. granulepos= (granulepos<<8)|(page[12]&0xff);
  107562. granulepos= (granulepos<<8)|(page[11]&0xff);
  107563. granulepos= (granulepos<<8)|(page[10]&0xff);
  107564. granulepos= (granulepos<<8)|(page[9]&0xff);
  107565. granulepos= (granulepos<<8)|(page[8]&0xff);
  107566. granulepos= (granulepos<<8)|(page[7]&0xff);
  107567. granulepos= (granulepos<<8)|(page[6]&0xff);
  107568. return(granulepos);
  107569. }
  107570. int ogg_page_serialno(ogg_page *og){
  107571. return(og->header[14] |
  107572. (og->header[15]<<8) |
  107573. (og->header[16]<<16) |
  107574. (og->header[17]<<24));
  107575. }
  107576. long ogg_page_pageno(ogg_page *og){
  107577. return(og->header[18] |
  107578. (og->header[19]<<8) |
  107579. (og->header[20]<<16) |
  107580. (og->header[21]<<24));
  107581. }
  107582. /* returns the number of packets that are completed on this page (if
  107583. the leading packet is begun on a previous page, but ends on this
  107584. page, it's counted */
  107585. /* NOTE:
  107586. If a page consists of a packet begun on a previous page, and a new
  107587. packet begun (but not completed) on this page, the return will be:
  107588. ogg_page_packets(page) ==1,
  107589. ogg_page_continued(page) !=0
  107590. If a page happens to be a single packet that was begun on a
  107591. previous page, and spans to the next page (in the case of a three or
  107592. more page packet), the return will be:
  107593. ogg_page_packets(page) ==0,
  107594. ogg_page_continued(page) !=0
  107595. */
  107596. int ogg_page_packets(ogg_page *og){
  107597. int i,n=og->header[26],count=0;
  107598. for(i=0;i<n;i++)
  107599. if(og->header[27+i]<255)count++;
  107600. return(count);
  107601. }
  107602. #if 0
  107603. /* helper to initialize lookup for direct-table CRC (illustrative; we
  107604. use the static init below) */
  107605. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  107606. int i;
  107607. unsigned long r;
  107608. r = index << 24;
  107609. for (i=0; i<8; i++)
  107610. if (r & 0x80000000UL)
  107611. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  107612. polynomial, although we use an
  107613. unreflected alg and an init/final
  107614. of 0, not 0xffffffff */
  107615. else
  107616. r<<=1;
  107617. return (r & 0xffffffffUL);
  107618. }
  107619. #endif
  107620. static const ogg_uint32_t crc_lookup[256]={
  107621. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  107622. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  107623. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  107624. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  107625. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  107626. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  107627. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  107628. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  107629. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  107630. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  107631. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  107632. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  107633. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  107634. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  107635. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  107636. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  107637. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  107638. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  107639. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  107640. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  107641. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  107642. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  107643. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  107644. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  107645. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  107646. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  107647. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  107648. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  107649. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  107650. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  107651. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  107652. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  107653. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  107654. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  107655. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  107656. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  107657. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  107658. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  107659. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  107660. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  107661. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  107662. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  107663. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  107664. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  107665. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  107666. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  107667. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  107668. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  107669. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  107670. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  107671. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  107672. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  107673. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  107674. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  107675. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  107676. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  107677. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  107678. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  107679. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  107680. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  107681. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  107682. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  107683. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  107684. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  107685. /* init the encode/decode logical stream state */
  107686. int ogg_stream_init(ogg_stream_state *os,int serialno){
  107687. if(os){
  107688. memset(os,0,sizeof(*os));
  107689. os->body_storage=16*1024;
  107690. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  107691. os->lacing_storage=1024;
  107692. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  107693. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  107694. os->serialno=serialno;
  107695. return(0);
  107696. }
  107697. return(-1);
  107698. }
  107699. /* _clear does not free os, only the non-flat storage within */
  107700. int ogg_stream_clear(ogg_stream_state *os){
  107701. if(os){
  107702. if(os->body_data)_ogg_free(os->body_data);
  107703. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  107704. if(os->granule_vals)_ogg_free(os->granule_vals);
  107705. memset(os,0,sizeof(*os));
  107706. }
  107707. return(0);
  107708. }
  107709. int ogg_stream_destroy(ogg_stream_state *os){
  107710. if(os){
  107711. ogg_stream_clear(os);
  107712. _ogg_free(os);
  107713. }
  107714. return(0);
  107715. }
  107716. /* Helpers for ogg_stream_encode; this keeps the structure and
  107717. what's happening fairly clear */
  107718. static void _os_body_expand(ogg_stream_state *os,int needed){
  107719. if(os->body_storage<=os->body_fill+needed){
  107720. os->body_storage+=(needed+1024);
  107721. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  107722. }
  107723. }
  107724. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  107725. if(os->lacing_storage<=os->lacing_fill+needed){
  107726. os->lacing_storage+=(needed+32);
  107727. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  107728. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  107729. }
  107730. }
  107731. /* checksum the page */
  107732. /* Direct table CRC; note that this will be faster in the future if we
  107733. perform the checksum silmultaneously with other copies */
  107734. void ogg_page_checksum_set(ogg_page *og){
  107735. if(og){
  107736. ogg_uint32_t crc_reg=0;
  107737. int i;
  107738. /* safety; needed for API behavior, but not framing code */
  107739. og->header[22]=0;
  107740. og->header[23]=0;
  107741. og->header[24]=0;
  107742. og->header[25]=0;
  107743. for(i=0;i<og->header_len;i++)
  107744. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  107745. for(i=0;i<og->body_len;i++)
  107746. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  107747. og->header[22]=(unsigned char)(crc_reg&0xff);
  107748. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  107749. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  107750. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  107751. }
  107752. }
  107753. /* submit data to the internal buffer of the framing engine */
  107754. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  107755. int lacing_vals=op->bytes/255+1,i;
  107756. if(os->body_returned){
  107757. /* advance packet data according to the body_returned pointer. We
  107758. had to keep it around to return a pointer into the buffer last
  107759. call */
  107760. os->body_fill-=os->body_returned;
  107761. if(os->body_fill)
  107762. memmove(os->body_data,os->body_data+os->body_returned,
  107763. os->body_fill);
  107764. os->body_returned=0;
  107765. }
  107766. /* make sure we have the buffer storage */
  107767. _os_body_expand(os,op->bytes);
  107768. _os_lacing_expand(os,lacing_vals);
  107769. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  107770. the liability of overly clean abstraction for the time being. It
  107771. will actually be fairly easy to eliminate the extra copy in the
  107772. future */
  107773. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  107774. os->body_fill+=op->bytes;
  107775. /* Store lacing vals for this packet */
  107776. for(i=0;i<lacing_vals-1;i++){
  107777. os->lacing_vals[os->lacing_fill+i]=255;
  107778. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  107779. }
  107780. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  107781. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  107782. /* flag the first segment as the beginning of the packet */
  107783. os->lacing_vals[os->lacing_fill]|= 0x100;
  107784. os->lacing_fill+=lacing_vals;
  107785. /* for the sake of completeness */
  107786. os->packetno++;
  107787. if(op->e_o_s)os->e_o_s=1;
  107788. return(0);
  107789. }
  107790. /* This will flush remaining packets into a page (returning nonzero),
  107791. even if there is not enough data to trigger a flush normally
  107792. (undersized page). If there are no packets or partial packets to
  107793. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  107794. try to flush a normal sized page like ogg_stream_pageout; a call to
  107795. ogg_stream_flush does not guarantee that all packets have flushed.
  107796. Only a return value of 0 from ogg_stream_flush indicates all packet
  107797. data is flushed into pages.
  107798. since ogg_stream_flush will flush the last page in a stream even if
  107799. it's undersized, you almost certainly want to use ogg_stream_pageout
  107800. (and *not* ogg_stream_flush) unless you specifically need to flush
  107801. an page regardless of size in the middle of a stream. */
  107802. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  107803. int i;
  107804. int vals=0;
  107805. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  107806. int bytes=0;
  107807. long acc=0;
  107808. ogg_int64_t granule_pos=-1;
  107809. if(maxvals==0)return(0);
  107810. /* construct a page */
  107811. /* decide how many segments to include */
  107812. /* If this is the initial header case, the first page must only include
  107813. the initial header packet */
  107814. if(os->b_o_s==0){ /* 'initial header page' case */
  107815. granule_pos=0;
  107816. for(vals=0;vals<maxvals;vals++){
  107817. if((os->lacing_vals[vals]&0x0ff)<255){
  107818. vals++;
  107819. break;
  107820. }
  107821. }
  107822. }else{
  107823. for(vals=0;vals<maxvals;vals++){
  107824. if(acc>4096)break;
  107825. acc+=os->lacing_vals[vals]&0x0ff;
  107826. if((os->lacing_vals[vals]&0xff)<255)
  107827. granule_pos=os->granule_vals[vals];
  107828. }
  107829. }
  107830. /* construct the header in temp storage */
  107831. memcpy(os->header,"OggS",4);
  107832. /* stream structure version */
  107833. os->header[4]=0x00;
  107834. /* continued packet flag? */
  107835. os->header[5]=0x00;
  107836. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  107837. /* first page flag? */
  107838. if(os->b_o_s==0)os->header[5]|=0x02;
  107839. /* last page flag? */
  107840. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  107841. os->b_o_s=1;
  107842. /* 64 bits of PCM position */
  107843. for(i=6;i<14;i++){
  107844. os->header[i]=(unsigned char)(granule_pos&0xff);
  107845. granule_pos>>=8;
  107846. }
  107847. /* 32 bits of stream serial number */
  107848. {
  107849. long serialno=os->serialno;
  107850. for(i=14;i<18;i++){
  107851. os->header[i]=(unsigned char)(serialno&0xff);
  107852. serialno>>=8;
  107853. }
  107854. }
  107855. /* 32 bits of page counter (we have both counter and page header
  107856. because this val can roll over) */
  107857. if(os->pageno==-1)os->pageno=0; /* because someone called
  107858. stream_reset; this would be a
  107859. strange thing to do in an
  107860. encode stream, but it has
  107861. plausible uses */
  107862. {
  107863. long pageno=os->pageno++;
  107864. for(i=18;i<22;i++){
  107865. os->header[i]=(unsigned char)(pageno&0xff);
  107866. pageno>>=8;
  107867. }
  107868. }
  107869. /* zero for computation; filled in later */
  107870. os->header[22]=0;
  107871. os->header[23]=0;
  107872. os->header[24]=0;
  107873. os->header[25]=0;
  107874. /* segment table */
  107875. os->header[26]=(unsigned char)(vals&0xff);
  107876. for(i=0;i<vals;i++)
  107877. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  107878. /* set pointers in the ogg_page struct */
  107879. og->header=os->header;
  107880. og->header_len=os->header_fill=vals+27;
  107881. og->body=os->body_data+os->body_returned;
  107882. og->body_len=bytes;
  107883. /* advance the lacing data and set the body_returned pointer */
  107884. os->lacing_fill-=vals;
  107885. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  107886. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  107887. os->body_returned+=bytes;
  107888. /* calculate the checksum */
  107889. ogg_page_checksum_set(og);
  107890. /* done */
  107891. return(1);
  107892. }
  107893. /* This constructs pages from buffered packet segments. The pointers
  107894. returned are to static buffers; do not free. The returned buffers are
  107895. good only until the next call (using the same ogg_stream_state) */
  107896. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  107897. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  107898. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  107899. os->lacing_fill>=255 || /* 'segment table full' case */
  107900. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  107901. return(ogg_stream_flush(os,og));
  107902. }
  107903. /* not enough data to construct a page and not end of stream */
  107904. return(0);
  107905. }
  107906. int ogg_stream_eos(ogg_stream_state *os){
  107907. return os->e_o_s;
  107908. }
  107909. /* DECODING PRIMITIVES: packet streaming layer **********************/
  107910. /* This has two layers to place more of the multi-serialno and paging
  107911. control in the application's hands. First, we expose a data buffer
  107912. using ogg_sync_buffer(). The app either copies into the
  107913. buffer, or passes it directly to read(), etc. We then call
  107914. ogg_sync_wrote() to tell how many bytes we just added.
  107915. Pages are returned (pointers into the buffer in ogg_sync_state)
  107916. by ogg_sync_pageout(). The page is then submitted to
  107917. ogg_stream_pagein() along with the appropriate
  107918. ogg_stream_state* (ie, matching serialno). We then get raw
  107919. packets out calling ogg_stream_packetout() with a
  107920. ogg_stream_state. */
  107921. /* initialize the struct to a known state */
  107922. int ogg_sync_init(ogg_sync_state *oy){
  107923. if(oy){
  107924. memset(oy,0,sizeof(*oy));
  107925. }
  107926. return(0);
  107927. }
  107928. /* clear non-flat storage within */
  107929. int ogg_sync_clear(ogg_sync_state *oy){
  107930. if(oy){
  107931. if(oy->data)_ogg_free(oy->data);
  107932. ogg_sync_init(oy);
  107933. }
  107934. return(0);
  107935. }
  107936. int ogg_sync_destroy(ogg_sync_state *oy){
  107937. if(oy){
  107938. ogg_sync_clear(oy);
  107939. _ogg_free(oy);
  107940. }
  107941. return(0);
  107942. }
  107943. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  107944. /* first, clear out any space that has been previously returned */
  107945. if(oy->returned){
  107946. oy->fill-=oy->returned;
  107947. if(oy->fill>0)
  107948. memmove(oy->data,oy->data+oy->returned,oy->fill);
  107949. oy->returned=0;
  107950. }
  107951. if(size>oy->storage-oy->fill){
  107952. /* We need to extend the internal buffer */
  107953. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  107954. if(oy->data)
  107955. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  107956. else
  107957. oy->data=(unsigned char*) _ogg_malloc(newsize);
  107958. oy->storage=newsize;
  107959. }
  107960. /* expose a segment at least as large as requested at the fill mark */
  107961. return((char *)oy->data+oy->fill);
  107962. }
  107963. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  107964. if(oy->fill+bytes>oy->storage)return(-1);
  107965. oy->fill+=bytes;
  107966. return(0);
  107967. }
  107968. /* sync the stream. This is meant to be useful for finding page
  107969. boundaries.
  107970. return values for this:
  107971. -n) skipped n bytes
  107972. 0) page not ready; more data (no bytes skipped)
  107973. n) page synced at current location; page length n bytes
  107974. */
  107975. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  107976. unsigned char *page=oy->data+oy->returned;
  107977. unsigned char *next;
  107978. long bytes=oy->fill-oy->returned;
  107979. if(oy->headerbytes==0){
  107980. int headerbytes,i;
  107981. if(bytes<27)return(0); /* not enough for a header */
  107982. /* verify capture pattern */
  107983. if(memcmp(page,"OggS",4))goto sync_fail;
  107984. headerbytes=page[26]+27;
  107985. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  107986. /* count up body length in the segment table */
  107987. for(i=0;i<page[26];i++)
  107988. oy->bodybytes+=page[27+i];
  107989. oy->headerbytes=headerbytes;
  107990. }
  107991. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  107992. /* The whole test page is buffered. Verify the checksum */
  107993. {
  107994. /* Grab the checksum bytes, set the header field to zero */
  107995. char chksum[4];
  107996. ogg_page log;
  107997. memcpy(chksum,page+22,4);
  107998. memset(page+22,0,4);
  107999. /* set up a temp page struct and recompute the checksum */
  108000. log.header=page;
  108001. log.header_len=oy->headerbytes;
  108002. log.body=page+oy->headerbytes;
  108003. log.body_len=oy->bodybytes;
  108004. ogg_page_checksum_set(&log);
  108005. /* Compare */
  108006. if(memcmp(chksum,page+22,4)){
  108007. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  108008. at all) */
  108009. /* replace the computed checksum with the one actually read in */
  108010. memcpy(page+22,chksum,4);
  108011. /* Bad checksum. Lose sync */
  108012. goto sync_fail;
  108013. }
  108014. }
  108015. /* yes, have a whole page all ready to go */
  108016. {
  108017. unsigned char *page=oy->data+oy->returned;
  108018. long bytes;
  108019. if(og){
  108020. og->header=page;
  108021. og->header_len=oy->headerbytes;
  108022. og->body=page+oy->headerbytes;
  108023. og->body_len=oy->bodybytes;
  108024. }
  108025. oy->unsynced=0;
  108026. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  108027. oy->headerbytes=0;
  108028. oy->bodybytes=0;
  108029. return(bytes);
  108030. }
  108031. sync_fail:
  108032. oy->headerbytes=0;
  108033. oy->bodybytes=0;
  108034. /* search for possible capture */
  108035. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  108036. if(!next)
  108037. next=oy->data+oy->fill;
  108038. oy->returned=next-oy->data;
  108039. return(-(next-page));
  108040. }
  108041. /* sync the stream and get a page. Keep trying until we find a page.
  108042. Supress 'sync errors' after reporting the first.
  108043. return values:
  108044. -1) recapture (hole in data)
  108045. 0) need more data
  108046. 1) page returned
  108047. Returns pointers into buffered data; invalidated by next call to
  108048. _stream, _clear, _init, or _buffer */
  108049. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  108050. /* all we need to do is verify a page at the head of the stream
  108051. buffer. If it doesn't verify, we look for the next potential
  108052. frame */
  108053. for(;;){
  108054. long ret=ogg_sync_pageseek(oy,og);
  108055. if(ret>0){
  108056. /* have a page */
  108057. return(1);
  108058. }
  108059. if(ret==0){
  108060. /* need more data */
  108061. return(0);
  108062. }
  108063. /* head did not start a synced page... skipped some bytes */
  108064. if(!oy->unsynced){
  108065. oy->unsynced=1;
  108066. return(-1);
  108067. }
  108068. /* loop. keep looking */
  108069. }
  108070. }
  108071. /* add the incoming page to the stream state; we decompose the page
  108072. into packet segments here as well. */
  108073. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  108074. unsigned char *header=og->header;
  108075. unsigned char *body=og->body;
  108076. long bodysize=og->body_len;
  108077. int segptr=0;
  108078. int version=ogg_page_version(og);
  108079. int continued=ogg_page_continued(og);
  108080. int bos=ogg_page_bos(og);
  108081. int eos=ogg_page_eos(og);
  108082. ogg_int64_t granulepos=ogg_page_granulepos(og);
  108083. int serialno=ogg_page_serialno(og);
  108084. long pageno=ogg_page_pageno(og);
  108085. int segments=header[26];
  108086. /* clean up 'returned data' */
  108087. {
  108088. long lr=os->lacing_returned;
  108089. long br=os->body_returned;
  108090. /* body data */
  108091. if(br){
  108092. os->body_fill-=br;
  108093. if(os->body_fill)
  108094. memmove(os->body_data,os->body_data+br,os->body_fill);
  108095. os->body_returned=0;
  108096. }
  108097. if(lr){
  108098. /* segment table */
  108099. if(os->lacing_fill-lr){
  108100. memmove(os->lacing_vals,os->lacing_vals+lr,
  108101. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  108102. memmove(os->granule_vals,os->granule_vals+lr,
  108103. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  108104. }
  108105. os->lacing_fill-=lr;
  108106. os->lacing_packet-=lr;
  108107. os->lacing_returned=0;
  108108. }
  108109. }
  108110. /* check the serial number */
  108111. if(serialno!=os->serialno)return(-1);
  108112. if(version>0)return(-1);
  108113. _os_lacing_expand(os,segments+1);
  108114. /* are we in sequence? */
  108115. if(pageno!=os->pageno){
  108116. int i;
  108117. /* unroll previous partial packet (if any) */
  108118. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  108119. os->body_fill-=os->lacing_vals[i]&0xff;
  108120. os->lacing_fill=os->lacing_packet;
  108121. /* make a note of dropped data in segment table */
  108122. if(os->pageno!=-1){
  108123. os->lacing_vals[os->lacing_fill++]=0x400;
  108124. os->lacing_packet++;
  108125. }
  108126. }
  108127. /* are we a 'continued packet' page? If so, we may need to skip
  108128. some segments */
  108129. if(continued){
  108130. if(os->lacing_fill<1 ||
  108131. os->lacing_vals[os->lacing_fill-1]==0x400){
  108132. bos=0;
  108133. for(;segptr<segments;segptr++){
  108134. int val=header[27+segptr];
  108135. body+=val;
  108136. bodysize-=val;
  108137. if(val<255){
  108138. segptr++;
  108139. break;
  108140. }
  108141. }
  108142. }
  108143. }
  108144. if(bodysize){
  108145. _os_body_expand(os,bodysize);
  108146. memcpy(os->body_data+os->body_fill,body,bodysize);
  108147. os->body_fill+=bodysize;
  108148. }
  108149. {
  108150. int saved=-1;
  108151. while(segptr<segments){
  108152. int val=header[27+segptr];
  108153. os->lacing_vals[os->lacing_fill]=val;
  108154. os->granule_vals[os->lacing_fill]=-1;
  108155. if(bos){
  108156. os->lacing_vals[os->lacing_fill]|=0x100;
  108157. bos=0;
  108158. }
  108159. if(val<255)saved=os->lacing_fill;
  108160. os->lacing_fill++;
  108161. segptr++;
  108162. if(val<255)os->lacing_packet=os->lacing_fill;
  108163. }
  108164. /* set the granulepos on the last granuleval of the last full packet */
  108165. if(saved!=-1){
  108166. os->granule_vals[saved]=granulepos;
  108167. }
  108168. }
  108169. if(eos){
  108170. os->e_o_s=1;
  108171. if(os->lacing_fill>0)
  108172. os->lacing_vals[os->lacing_fill-1]|=0x200;
  108173. }
  108174. os->pageno=pageno+1;
  108175. return(0);
  108176. }
  108177. /* clear things to an initial state. Good to call, eg, before seeking */
  108178. int ogg_sync_reset(ogg_sync_state *oy){
  108179. oy->fill=0;
  108180. oy->returned=0;
  108181. oy->unsynced=0;
  108182. oy->headerbytes=0;
  108183. oy->bodybytes=0;
  108184. return(0);
  108185. }
  108186. int ogg_stream_reset(ogg_stream_state *os){
  108187. os->body_fill=0;
  108188. os->body_returned=0;
  108189. os->lacing_fill=0;
  108190. os->lacing_packet=0;
  108191. os->lacing_returned=0;
  108192. os->header_fill=0;
  108193. os->e_o_s=0;
  108194. os->b_o_s=0;
  108195. os->pageno=-1;
  108196. os->packetno=0;
  108197. os->granulepos=0;
  108198. return(0);
  108199. }
  108200. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  108201. ogg_stream_reset(os);
  108202. os->serialno=serialno;
  108203. return(0);
  108204. }
  108205. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  108206. /* The last part of decode. We have the stream broken into packet
  108207. segments. Now we need to group them into packets (or return the
  108208. out of sync markers) */
  108209. int ptr=os->lacing_returned;
  108210. if(os->lacing_packet<=ptr)return(0);
  108211. if(os->lacing_vals[ptr]&0x400){
  108212. /* we need to tell the codec there's a gap; it might need to
  108213. handle previous packet dependencies. */
  108214. os->lacing_returned++;
  108215. os->packetno++;
  108216. return(-1);
  108217. }
  108218. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  108219. to ask if there's a whole packet
  108220. waiting */
  108221. /* Gather the whole packet. We'll have no holes or a partial packet */
  108222. {
  108223. int size=os->lacing_vals[ptr]&0xff;
  108224. int bytes=size;
  108225. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  108226. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  108227. while(size==255){
  108228. int val=os->lacing_vals[++ptr];
  108229. size=val&0xff;
  108230. if(val&0x200)eos=0x200;
  108231. bytes+=size;
  108232. }
  108233. if(op){
  108234. op->e_o_s=eos;
  108235. op->b_o_s=bos;
  108236. op->packet=os->body_data+os->body_returned;
  108237. op->packetno=os->packetno;
  108238. op->granulepos=os->granule_vals[ptr];
  108239. op->bytes=bytes;
  108240. }
  108241. if(adv){
  108242. os->body_returned+=bytes;
  108243. os->lacing_returned=ptr+1;
  108244. os->packetno++;
  108245. }
  108246. }
  108247. return(1);
  108248. }
  108249. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  108250. return _packetout(os,op,1);
  108251. }
  108252. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  108253. return _packetout(os,op,0);
  108254. }
  108255. void ogg_packet_clear(ogg_packet *op) {
  108256. _ogg_free(op->packet);
  108257. memset(op, 0, sizeof(*op));
  108258. }
  108259. #ifdef _V_SELFTEST
  108260. #include <stdio.h>
  108261. ogg_stream_state os_en, os_de;
  108262. ogg_sync_state oy;
  108263. void checkpacket(ogg_packet *op,int len, int no, int pos){
  108264. long j;
  108265. static int sequence=0;
  108266. static int lastno=0;
  108267. if(op->bytes!=len){
  108268. fprintf(stderr,"incorrect packet length!\n");
  108269. exit(1);
  108270. }
  108271. if(op->granulepos!=pos){
  108272. fprintf(stderr,"incorrect packet position!\n");
  108273. exit(1);
  108274. }
  108275. /* packet number just follows sequence/gap; adjust the input number
  108276. for that */
  108277. if(no==0){
  108278. sequence=0;
  108279. }else{
  108280. sequence++;
  108281. if(no>lastno+1)
  108282. sequence++;
  108283. }
  108284. lastno=no;
  108285. if(op->packetno!=sequence){
  108286. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  108287. (long)(op->packetno),sequence);
  108288. exit(1);
  108289. }
  108290. /* Test data */
  108291. for(j=0;j<op->bytes;j++)
  108292. if(op->packet[j]!=((j+no)&0xff)){
  108293. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  108294. j,op->packet[j],(j+no)&0xff);
  108295. exit(1);
  108296. }
  108297. }
  108298. void check_page(unsigned char *data,const int *header,ogg_page *og){
  108299. long j;
  108300. /* Test data */
  108301. for(j=0;j<og->body_len;j++)
  108302. if(og->body[j]!=data[j]){
  108303. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  108304. j,data[j],og->body[j]);
  108305. exit(1);
  108306. }
  108307. /* Test header */
  108308. for(j=0;j<og->header_len;j++){
  108309. if(og->header[j]!=header[j]){
  108310. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  108311. for(j=0;j<header[26]+27;j++)
  108312. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  108313. fprintf(stderr,"\n");
  108314. exit(1);
  108315. }
  108316. }
  108317. if(og->header_len!=header[26]+27){
  108318. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  108319. og->header_len,header[26]+27);
  108320. exit(1);
  108321. }
  108322. }
  108323. void print_header(ogg_page *og){
  108324. int j;
  108325. fprintf(stderr,"\nHEADER:\n");
  108326. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  108327. og->header[0],og->header[1],og->header[2],og->header[3],
  108328. (int)og->header[4],(int)og->header[5]);
  108329. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  108330. (og->header[9]<<24)|(og->header[8]<<16)|
  108331. (og->header[7]<<8)|og->header[6],
  108332. (og->header[17]<<24)|(og->header[16]<<16)|
  108333. (og->header[15]<<8)|og->header[14],
  108334. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  108335. (og->header[19]<<8)|og->header[18]);
  108336. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  108337. (int)og->header[22],(int)og->header[23],
  108338. (int)og->header[24],(int)og->header[25],
  108339. (int)og->header[26]);
  108340. for(j=27;j<og->header_len;j++)
  108341. fprintf(stderr,"%d ",(int)og->header[j]);
  108342. fprintf(stderr,")\n\n");
  108343. }
  108344. void copy_page(ogg_page *og){
  108345. unsigned char *temp=_ogg_malloc(og->header_len);
  108346. memcpy(temp,og->header,og->header_len);
  108347. og->header=temp;
  108348. temp=_ogg_malloc(og->body_len);
  108349. memcpy(temp,og->body,og->body_len);
  108350. og->body=temp;
  108351. }
  108352. void free_page(ogg_page *og){
  108353. _ogg_free (og->header);
  108354. _ogg_free (og->body);
  108355. }
  108356. void error(void){
  108357. fprintf(stderr,"error!\n");
  108358. exit(1);
  108359. }
  108360. /* 17 only */
  108361. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  108362. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108363. 0x01,0x02,0x03,0x04,0,0,0,0,
  108364. 0x15,0xed,0xec,0x91,
  108365. 1,
  108366. 17};
  108367. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  108368. const int head1_1[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108369. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108370. 0x01,0x02,0x03,0x04,0,0,0,0,
  108371. 0x59,0x10,0x6c,0x2c,
  108372. 1,
  108373. 17};
  108374. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  108375. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  108376. 0x01,0x02,0x03,0x04,1,0,0,0,
  108377. 0x89,0x33,0x85,0xce,
  108378. 13,
  108379. 254,255,0,255,1,255,245,255,255,0,
  108380. 255,255,90};
  108381. /* nil packets; beginning,middle,end */
  108382. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108383. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108384. 0x01,0x02,0x03,0x04,0,0,0,0,
  108385. 0xff,0x7b,0x23,0x17,
  108386. 1,
  108387. 0};
  108388. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  108389. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  108390. 0x01,0x02,0x03,0x04,1,0,0,0,
  108391. 0x5c,0x3f,0x66,0xcb,
  108392. 17,
  108393. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  108394. 255,255,90,0};
  108395. /* large initial packet */
  108396. const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108397. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108398. 0x01,0x02,0x03,0x04,0,0,0,0,
  108399. 0x01,0x27,0x31,0xaa,
  108400. 18,
  108401. 255,255,255,255,255,255,255,255,
  108402. 255,255,255,255,255,255,255,255,255,10};
  108403. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  108404. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  108405. 0x01,0x02,0x03,0x04,1,0,0,0,
  108406. 0x7f,0x4e,0x8a,0xd2,
  108407. 4,
  108408. 255,4,255,0};
  108409. /* continuing packet test */
  108410. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108411. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108412. 0x01,0x02,0x03,0x04,0,0,0,0,
  108413. 0xff,0x7b,0x23,0x17,
  108414. 1,
  108415. 0};
  108416. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  108417. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  108418. 0x01,0x02,0x03,0x04,1,0,0,0,
  108419. 0x54,0x05,0x51,0xc8,
  108420. 17,
  108421. 255,255,255,255,255,255,255,255,
  108422. 255,255,255,255,255,255,255,255,255};
  108423. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  108424. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  108425. 0x01,0x02,0x03,0x04,2,0,0,0,
  108426. 0xc8,0xc3,0xcb,0xed,
  108427. 5,
  108428. 10,255,4,255,0};
  108429. /* page with the 255 segment limit */
  108430. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108431. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108432. 0x01,0x02,0x03,0x04,0,0,0,0,
  108433. 0xff,0x7b,0x23,0x17,
  108434. 1,
  108435. 0};
  108436. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  108437. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  108438. 0x01,0x02,0x03,0x04,1,0,0,0,
  108439. 0xed,0x2a,0x2e,0xa7,
  108440. 255,
  108441. 10,10,10,10,10,10,10,10,
  108442. 10,10,10,10,10,10,10,10,
  108443. 10,10,10,10,10,10,10,10,
  108444. 10,10,10,10,10,10,10,10,
  108445. 10,10,10,10,10,10,10,10,
  108446. 10,10,10,10,10,10,10,10,
  108447. 10,10,10,10,10,10,10,10,
  108448. 10,10,10,10,10,10,10,10,
  108449. 10,10,10,10,10,10,10,10,
  108450. 10,10,10,10,10,10,10,10,
  108451. 10,10,10,10,10,10,10,10,
  108452. 10,10,10,10,10,10,10,10,
  108453. 10,10,10,10,10,10,10,10,
  108454. 10,10,10,10,10,10,10,10,
  108455. 10,10,10,10,10,10,10,10,
  108456. 10,10,10,10,10,10,10,10,
  108457. 10,10,10,10,10,10,10,10,
  108458. 10,10,10,10,10,10,10,10,
  108459. 10,10,10,10,10,10,10,10,
  108460. 10,10,10,10,10,10,10,10,
  108461. 10,10,10,10,10,10,10,10,
  108462. 10,10,10,10,10,10,10,10,
  108463. 10,10,10,10,10,10,10,10,
  108464. 10,10,10,10,10,10,10,10,
  108465. 10,10,10,10,10,10,10,10,
  108466. 10,10,10,10,10,10,10,10,
  108467. 10,10,10,10,10,10,10,10,
  108468. 10,10,10,10,10,10,10,10,
  108469. 10,10,10,10,10,10,10,10,
  108470. 10,10,10,10,10,10,10,10,
  108471. 10,10,10,10,10,10,10,10,
  108472. 10,10,10,10,10,10,10};
  108473. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  108474. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  108475. 0x01,0x02,0x03,0x04,2,0,0,0,
  108476. 0x6c,0x3b,0x82,0x3d,
  108477. 1,
  108478. 50};
  108479. /* packet that overspans over an entire page */
  108480. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108481. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108482. 0x01,0x02,0x03,0x04,0,0,0,0,
  108483. 0xff,0x7b,0x23,0x17,
  108484. 1,
  108485. 0};
  108486. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  108487. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  108488. 0x01,0x02,0x03,0x04,1,0,0,0,
  108489. 0x3c,0xd9,0x4d,0x3f,
  108490. 17,
  108491. 100,255,255,255,255,255,255,255,255,
  108492. 255,255,255,255,255,255,255,255};
  108493. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  108494. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  108495. 0x01,0x02,0x03,0x04,2,0,0,0,
  108496. 0x01,0xd2,0xe5,0xe5,
  108497. 17,
  108498. 255,255,255,255,255,255,255,255,
  108499. 255,255,255,255,255,255,255,255,255};
  108500. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  108501. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  108502. 0x01,0x02,0x03,0x04,3,0,0,0,
  108503. 0xef,0xdd,0x88,0xde,
  108504. 7,
  108505. 255,255,75,255,4,255,0};
  108506. /* packet that overspans over an entire page */
  108507. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108508. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108509. 0x01,0x02,0x03,0x04,0,0,0,0,
  108510. 0xff,0x7b,0x23,0x17,
  108511. 1,
  108512. 0};
  108513. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  108514. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  108515. 0x01,0x02,0x03,0x04,1,0,0,0,
  108516. 0x3c,0xd9,0x4d,0x3f,
  108517. 17,
  108518. 100,255,255,255,255,255,255,255,255,
  108519. 255,255,255,255,255,255,255,255};
  108520. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  108521. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  108522. 0x01,0x02,0x03,0x04,2,0,0,0,
  108523. 0xd4,0xe0,0x60,0xe5,
  108524. 1,0};
  108525. void test_pack(const int *pl, const int **headers, int byteskip,
  108526. int pageskip, int packetskip){
  108527. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  108528. long inptr=0;
  108529. long outptr=0;
  108530. long deptr=0;
  108531. long depacket=0;
  108532. long granule_pos=7,pageno=0;
  108533. int i,j,packets,pageout=pageskip;
  108534. int eosflag=0;
  108535. int bosflag=0;
  108536. int byteskipcount=0;
  108537. ogg_stream_reset(&os_en);
  108538. ogg_stream_reset(&os_de);
  108539. ogg_sync_reset(&oy);
  108540. for(packets=0;packets<packetskip;packets++)
  108541. depacket+=pl[packets];
  108542. for(packets=0;;packets++)if(pl[packets]==-1)break;
  108543. for(i=0;i<packets;i++){
  108544. /* construct a test packet */
  108545. ogg_packet op;
  108546. int len=pl[i];
  108547. op.packet=data+inptr;
  108548. op.bytes=len;
  108549. op.e_o_s=(pl[i+1]<0?1:0);
  108550. op.granulepos=granule_pos;
  108551. granule_pos+=1024;
  108552. for(j=0;j<len;j++)data[inptr++]=i+j;
  108553. /* submit the test packet */
  108554. ogg_stream_packetin(&os_en,&op);
  108555. /* retrieve any finished pages */
  108556. {
  108557. ogg_page og;
  108558. while(ogg_stream_pageout(&os_en,&og)){
  108559. /* We have a page. Check it carefully */
  108560. fprintf(stderr,"%ld, ",pageno);
  108561. if(headers[pageno]==NULL){
  108562. fprintf(stderr,"coded too many pages!\n");
  108563. exit(1);
  108564. }
  108565. check_page(data+outptr,headers[pageno],&og);
  108566. outptr+=og.body_len;
  108567. pageno++;
  108568. if(pageskip){
  108569. bosflag=1;
  108570. pageskip--;
  108571. deptr+=og.body_len;
  108572. }
  108573. /* have a complete page; submit it to sync/decode */
  108574. {
  108575. ogg_page og_de;
  108576. ogg_packet op_de,op_de2;
  108577. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  108578. char *next=buf;
  108579. byteskipcount+=og.header_len;
  108580. if(byteskipcount>byteskip){
  108581. memcpy(next,og.header,byteskipcount-byteskip);
  108582. next+=byteskipcount-byteskip;
  108583. byteskipcount=byteskip;
  108584. }
  108585. byteskipcount+=og.body_len;
  108586. if(byteskipcount>byteskip){
  108587. memcpy(next,og.body,byteskipcount-byteskip);
  108588. next+=byteskipcount-byteskip;
  108589. byteskipcount=byteskip;
  108590. }
  108591. ogg_sync_wrote(&oy,next-buf);
  108592. while(1){
  108593. int ret=ogg_sync_pageout(&oy,&og_de);
  108594. if(ret==0)break;
  108595. if(ret<0)continue;
  108596. /* got a page. Happy happy. Verify that it's good. */
  108597. fprintf(stderr,"(%ld), ",pageout);
  108598. check_page(data+deptr,headers[pageout],&og_de);
  108599. deptr+=og_de.body_len;
  108600. pageout++;
  108601. /* submit it to deconstitution */
  108602. ogg_stream_pagein(&os_de,&og_de);
  108603. /* packets out? */
  108604. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  108605. ogg_stream_packetpeek(&os_de,NULL);
  108606. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  108607. /* verify peek and out match */
  108608. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  108609. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  108610. depacket);
  108611. exit(1);
  108612. }
  108613. /* verify the packet! */
  108614. /* check data */
  108615. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  108616. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  108617. depacket);
  108618. exit(1);
  108619. }
  108620. /* check bos flag */
  108621. if(bosflag==0 && op_de.b_o_s==0){
  108622. fprintf(stderr,"b_o_s flag not set on packet!\n");
  108623. exit(1);
  108624. }
  108625. if(bosflag && op_de.b_o_s){
  108626. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  108627. exit(1);
  108628. }
  108629. bosflag=1;
  108630. depacket+=op_de.bytes;
  108631. /* check eos flag */
  108632. if(eosflag){
  108633. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  108634. exit(1);
  108635. }
  108636. if(op_de.e_o_s)eosflag=1;
  108637. /* check granulepos flag */
  108638. if(op_de.granulepos!=-1){
  108639. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  108640. }
  108641. }
  108642. }
  108643. }
  108644. }
  108645. }
  108646. }
  108647. _ogg_free(data);
  108648. if(headers[pageno]!=NULL){
  108649. fprintf(stderr,"did not write last page!\n");
  108650. exit(1);
  108651. }
  108652. if(headers[pageout]!=NULL){
  108653. fprintf(stderr,"did not decode last page!\n");
  108654. exit(1);
  108655. }
  108656. if(inptr!=outptr){
  108657. fprintf(stderr,"encoded page data incomplete!\n");
  108658. exit(1);
  108659. }
  108660. if(inptr!=deptr){
  108661. fprintf(stderr,"decoded page data incomplete!\n");
  108662. exit(1);
  108663. }
  108664. if(inptr!=depacket){
  108665. fprintf(stderr,"decoded packet data incomplete!\n");
  108666. exit(1);
  108667. }
  108668. if(!eosflag){
  108669. fprintf(stderr,"Never got a packet with EOS set!\n");
  108670. exit(1);
  108671. }
  108672. fprintf(stderr,"ok.\n");
  108673. }
  108674. int main(void){
  108675. ogg_stream_init(&os_en,0x04030201);
  108676. ogg_stream_init(&os_de,0x04030201);
  108677. ogg_sync_init(&oy);
  108678. /* Exercise each code path in the framing code. Also verify that
  108679. the checksums are working. */
  108680. {
  108681. /* 17 only */
  108682. const int packets[]={17, -1};
  108683. const int *headret[]={head1_0,NULL};
  108684. fprintf(stderr,"testing single page encoding... ");
  108685. test_pack(packets,headret,0,0,0);
  108686. }
  108687. {
  108688. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  108689. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  108690. const int *headret[]={head1_1,head2_1,NULL};
  108691. fprintf(stderr,"testing basic page encoding... ");
  108692. test_pack(packets,headret,0,0,0);
  108693. }
  108694. {
  108695. /* nil packets; beginning,middle,end */
  108696. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  108697. const int *headret[]={head1_2,head2_2,NULL};
  108698. fprintf(stderr,"testing basic nil packets... ");
  108699. test_pack(packets,headret,0,0,0);
  108700. }
  108701. {
  108702. /* large initial packet */
  108703. const int packets[]={4345,259,255,-1};
  108704. const int *headret[]={head1_3,head2_3,NULL};
  108705. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  108706. test_pack(packets,headret,0,0,0);
  108707. }
  108708. {
  108709. /* continuing packet test */
  108710. const int packets[]={0,4345,259,255,-1};
  108711. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  108712. fprintf(stderr,"testing single packet page span... ");
  108713. test_pack(packets,headret,0,0,0);
  108714. }
  108715. /* page with the 255 segment limit */
  108716. {
  108717. const int packets[]={0,10,10,10,10,10,10,10,10,
  108718. 10,10,10,10,10,10,10,10,
  108719. 10,10,10,10,10,10,10,10,
  108720. 10,10,10,10,10,10,10,10,
  108721. 10,10,10,10,10,10,10,10,
  108722. 10,10,10,10,10,10,10,10,
  108723. 10,10,10,10,10,10,10,10,
  108724. 10,10,10,10,10,10,10,10,
  108725. 10,10,10,10,10,10,10,10,
  108726. 10,10,10,10,10,10,10,10,
  108727. 10,10,10,10,10,10,10,10,
  108728. 10,10,10,10,10,10,10,10,
  108729. 10,10,10,10,10,10,10,10,
  108730. 10,10,10,10,10,10,10,10,
  108731. 10,10,10,10,10,10,10,10,
  108732. 10,10,10,10,10,10,10,10,
  108733. 10,10,10,10,10,10,10,10,
  108734. 10,10,10,10,10,10,10,10,
  108735. 10,10,10,10,10,10,10,10,
  108736. 10,10,10,10,10,10,10,10,
  108737. 10,10,10,10,10,10,10,10,
  108738. 10,10,10,10,10,10,10,10,
  108739. 10,10,10,10,10,10,10,10,
  108740. 10,10,10,10,10,10,10,10,
  108741. 10,10,10,10,10,10,10,10,
  108742. 10,10,10,10,10,10,10,10,
  108743. 10,10,10,10,10,10,10,10,
  108744. 10,10,10,10,10,10,10,10,
  108745. 10,10,10,10,10,10,10,10,
  108746. 10,10,10,10,10,10,10,10,
  108747. 10,10,10,10,10,10,10,10,
  108748. 10,10,10,10,10,10,10,50,-1};
  108749. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  108750. fprintf(stderr,"testing max packet segments... ");
  108751. test_pack(packets,headret,0,0,0);
  108752. }
  108753. {
  108754. /* packet that overspans over an entire page */
  108755. const int packets[]={0,100,9000,259,255,-1};
  108756. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  108757. fprintf(stderr,"testing very large packets... ");
  108758. test_pack(packets,headret,0,0,0);
  108759. }
  108760. {
  108761. /* test for the libogg 1.1.1 resync in large continuation bug
  108762. found by Josh Coalson) */
  108763. const int packets[]={0,100,9000,259,255,-1};
  108764. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  108765. fprintf(stderr,"testing continuation resync in very large packets... ");
  108766. test_pack(packets,headret,100,2,3);
  108767. }
  108768. {
  108769. /* term only page. why not? */
  108770. const int packets[]={0,100,4080,-1};
  108771. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  108772. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  108773. test_pack(packets,headret,0,0,0);
  108774. }
  108775. {
  108776. /* build a bunch of pages for testing */
  108777. unsigned char *data=_ogg_malloc(1024*1024);
  108778. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  108779. int inptr=0,i,j;
  108780. ogg_page og[5];
  108781. ogg_stream_reset(&os_en);
  108782. for(i=0;pl[i]!=-1;i++){
  108783. ogg_packet op;
  108784. int len=pl[i];
  108785. op.packet=data+inptr;
  108786. op.bytes=len;
  108787. op.e_o_s=(pl[i+1]<0?1:0);
  108788. op.granulepos=(i+1)*1000;
  108789. for(j=0;j<len;j++)data[inptr++]=i+j;
  108790. ogg_stream_packetin(&os_en,&op);
  108791. }
  108792. _ogg_free(data);
  108793. /* retrieve finished pages */
  108794. for(i=0;i<5;i++){
  108795. if(ogg_stream_pageout(&os_en,&og[i])==0){
  108796. fprintf(stderr,"Too few pages output building sync tests!\n");
  108797. exit(1);
  108798. }
  108799. copy_page(&og[i]);
  108800. }
  108801. /* Test lost pages on pagein/packetout: no rollback */
  108802. {
  108803. ogg_page temp;
  108804. ogg_packet test;
  108805. fprintf(stderr,"Testing loss of pages... ");
  108806. ogg_sync_reset(&oy);
  108807. ogg_stream_reset(&os_de);
  108808. for(i=0;i<5;i++){
  108809. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  108810. og[i].header_len);
  108811. ogg_sync_wrote(&oy,og[i].header_len);
  108812. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  108813. ogg_sync_wrote(&oy,og[i].body_len);
  108814. }
  108815. ogg_sync_pageout(&oy,&temp);
  108816. ogg_stream_pagein(&os_de,&temp);
  108817. ogg_sync_pageout(&oy,&temp);
  108818. ogg_stream_pagein(&os_de,&temp);
  108819. ogg_sync_pageout(&oy,&temp);
  108820. /* skip */
  108821. ogg_sync_pageout(&oy,&temp);
  108822. ogg_stream_pagein(&os_de,&temp);
  108823. /* do we get the expected results/packets? */
  108824. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108825. checkpacket(&test,0,0,0);
  108826. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108827. checkpacket(&test,100,1,-1);
  108828. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108829. checkpacket(&test,4079,2,3000);
  108830. if(ogg_stream_packetout(&os_de,&test)!=-1){
  108831. fprintf(stderr,"Error: loss of page did not return error\n");
  108832. exit(1);
  108833. }
  108834. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108835. checkpacket(&test,76,5,-1);
  108836. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108837. checkpacket(&test,34,6,-1);
  108838. fprintf(stderr,"ok.\n");
  108839. }
  108840. /* Test lost pages on pagein/packetout: rollback with continuation */
  108841. {
  108842. ogg_page temp;
  108843. ogg_packet test;
  108844. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  108845. ogg_sync_reset(&oy);
  108846. ogg_stream_reset(&os_de);
  108847. for(i=0;i<5;i++){
  108848. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  108849. og[i].header_len);
  108850. ogg_sync_wrote(&oy,og[i].header_len);
  108851. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  108852. ogg_sync_wrote(&oy,og[i].body_len);
  108853. }
  108854. ogg_sync_pageout(&oy,&temp);
  108855. ogg_stream_pagein(&os_de,&temp);
  108856. ogg_sync_pageout(&oy,&temp);
  108857. ogg_stream_pagein(&os_de,&temp);
  108858. ogg_sync_pageout(&oy,&temp);
  108859. ogg_stream_pagein(&os_de,&temp);
  108860. ogg_sync_pageout(&oy,&temp);
  108861. /* skip */
  108862. ogg_sync_pageout(&oy,&temp);
  108863. ogg_stream_pagein(&os_de,&temp);
  108864. /* do we get the expected results/packets? */
  108865. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108866. checkpacket(&test,0,0,0);
  108867. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108868. checkpacket(&test,100,1,-1);
  108869. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108870. checkpacket(&test,4079,2,3000);
  108871. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108872. checkpacket(&test,2956,3,4000);
  108873. if(ogg_stream_packetout(&os_de,&test)!=-1){
  108874. fprintf(stderr,"Error: loss of page did not return error\n");
  108875. exit(1);
  108876. }
  108877. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  108878. checkpacket(&test,300,13,14000);
  108879. fprintf(stderr,"ok.\n");
  108880. }
  108881. /* the rest only test sync */
  108882. {
  108883. ogg_page og_de;
  108884. /* Test fractional page inputs: incomplete capture */
  108885. fprintf(stderr,"Testing sync on partial inputs... ");
  108886. ogg_sync_reset(&oy);
  108887. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  108888. 3);
  108889. ogg_sync_wrote(&oy,3);
  108890. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  108891. /* Test fractional page inputs: incomplete fixed header */
  108892. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  108893. 20);
  108894. ogg_sync_wrote(&oy,20);
  108895. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  108896. /* Test fractional page inputs: incomplete header */
  108897. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  108898. 5);
  108899. ogg_sync_wrote(&oy,5);
  108900. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  108901. /* Test fractional page inputs: incomplete body */
  108902. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  108903. og[1].header_len-28);
  108904. ogg_sync_wrote(&oy,og[1].header_len-28);
  108905. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  108906. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  108907. ogg_sync_wrote(&oy,1000);
  108908. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  108909. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  108910. og[1].body_len-1000);
  108911. ogg_sync_wrote(&oy,og[1].body_len-1000);
  108912. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  108913. fprintf(stderr,"ok.\n");
  108914. }
  108915. /* Test fractional page inputs: page + incomplete capture */
  108916. {
  108917. ogg_page og_de;
  108918. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  108919. ogg_sync_reset(&oy);
  108920. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  108921. og[1].header_len);
  108922. ogg_sync_wrote(&oy,og[1].header_len);
  108923. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  108924. og[1].body_len);
  108925. ogg_sync_wrote(&oy,og[1].body_len);
  108926. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  108927. 20);
  108928. ogg_sync_wrote(&oy,20);
  108929. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  108930. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  108931. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  108932. og[1].header_len-20);
  108933. ogg_sync_wrote(&oy,og[1].header_len-20);
  108934. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  108935. og[1].body_len);
  108936. ogg_sync_wrote(&oy,og[1].body_len);
  108937. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  108938. fprintf(stderr,"ok.\n");
  108939. }
  108940. /* Test recapture: garbage + page */
  108941. {
  108942. ogg_page og_de;
  108943. fprintf(stderr,"Testing search for capture... ");
  108944. ogg_sync_reset(&oy);
  108945. /* 'garbage' */
  108946. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  108947. og[1].body_len);
  108948. ogg_sync_wrote(&oy,og[1].body_len);
  108949. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  108950. og[1].header_len);
  108951. ogg_sync_wrote(&oy,og[1].header_len);
  108952. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  108953. og[1].body_len);
  108954. ogg_sync_wrote(&oy,og[1].body_len);
  108955. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  108956. 20);
  108957. ogg_sync_wrote(&oy,20);
  108958. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  108959. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  108960. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  108961. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  108962. og[2].header_len-20);
  108963. ogg_sync_wrote(&oy,og[2].header_len-20);
  108964. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  108965. og[2].body_len);
  108966. ogg_sync_wrote(&oy,og[2].body_len);
  108967. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  108968. fprintf(stderr,"ok.\n");
  108969. }
  108970. /* Test recapture: page + garbage + page */
  108971. {
  108972. ogg_page og_de;
  108973. fprintf(stderr,"Testing recapture... ");
  108974. ogg_sync_reset(&oy);
  108975. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  108976. og[1].header_len);
  108977. ogg_sync_wrote(&oy,og[1].header_len);
  108978. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  108979. og[1].body_len);
  108980. ogg_sync_wrote(&oy,og[1].body_len);
  108981. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  108982. og[2].header_len);
  108983. ogg_sync_wrote(&oy,og[2].header_len);
  108984. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  108985. og[2].header_len);
  108986. ogg_sync_wrote(&oy,og[2].header_len);
  108987. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  108988. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  108989. og[2].body_len-5);
  108990. ogg_sync_wrote(&oy,og[2].body_len-5);
  108991. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  108992. og[3].header_len);
  108993. ogg_sync_wrote(&oy,og[3].header_len);
  108994. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  108995. og[3].body_len);
  108996. ogg_sync_wrote(&oy,og[3].body_len);
  108997. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  108998. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  108999. fprintf(stderr,"ok.\n");
  109000. }
  109001. /* Free page data that was previously copied */
  109002. {
  109003. for(i=0;i<5;i++){
  109004. free_page(&og[i]);
  109005. }
  109006. }
  109007. }
  109008. return(0);
  109009. }
  109010. #endif
  109011. #endif
  109012. /*** End of inlined file: framing.c ***/
  109013. /*** Start of inlined file: analysis.c ***/
  109014. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  109015. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109016. // tasks..
  109017. #if JUCE_MSVC
  109018. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109019. #endif
  109020. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  109021. #if JUCE_USE_OGGVORBIS
  109022. #include <stdio.h>
  109023. #include <string.h>
  109024. #include <math.h>
  109025. /*** Start of inlined file: codec_internal.h ***/
  109026. #ifndef _V_CODECI_H_
  109027. #define _V_CODECI_H_
  109028. /*** Start of inlined file: envelope.h ***/
  109029. #ifndef _V_ENVELOPE_
  109030. #define _V_ENVELOPE_
  109031. /*** Start of inlined file: mdct.h ***/
  109032. #ifndef _OGG_mdct_H_
  109033. #define _OGG_mdct_H_
  109034. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  109035. #ifdef MDCT_INTEGERIZED
  109036. #define DATA_TYPE int
  109037. #define REG_TYPE register int
  109038. #define TRIGBITS 14
  109039. #define cPI3_8 6270
  109040. #define cPI2_8 11585
  109041. #define cPI1_8 15137
  109042. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  109043. #define MULT_NORM(x) ((x)>>TRIGBITS)
  109044. #define HALVE(x) ((x)>>1)
  109045. #else
  109046. #define DATA_TYPE float
  109047. #define REG_TYPE float
  109048. #define cPI3_8 .38268343236508977175F
  109049. #define cPI2_8 .70710678118654752441F
  109050. #define cPI1_8 .92387953251128675613F
  109051. #define FLOAT_CONV(x) (x)
  109052. #define MULT_NORM(x) (x)
  109053. #define HALVE(x) ((x)*.5f)
  109054. #endif
  109055. typedef struct {
  109056. int n;
  109057. int log2n;
  109058. DATA_TYPE *trig;
  109059. int *bitrev;
  109060. DATA_TYPE scale;
  109061. } mdct_lookup;
  109062. extern void mdct_init(mdct_lookup *lookup,int n);
  109063. extern void mdct_clear(mdct_lookup *l);
  109064. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  109065. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  109066. #endif
  109067. /*** End of inlined file: mdct.h ***/
  109068. #define VE_PRE 16
  109069. #define VE_WIN 4
  109070. #define VE_POST 2
  109071. #define VE_AMP (VE_PRE+VE_POST-1)
  109072. #define VE_BANDS 7
  109073. #define VE_NEARDC 15
  109074. #define VE_MINSTRETCH 2 /* a bit less than short block */
  109075. #define VE_MAXSTRETCH 12 /* one-third full block */
  109076. typedef struct {
  109077. float ampbuf[VE_AMP];
  109078. int ampptr;
  109079. float nearDC[VE_NEARDC];
  109080. float nearDC_acc;
  109081. float nearDC_partialacc;
  109082. int nearptr;
  109083. } envelope_filter_state;
  109084. typedef struct {
  109085. int begin;
  109086. int end;
  109087. float *window;
  109088. float total;
  109089. } envelope_band;
  109090. typedef struct {
  109091. int ch;
  109092. int winlength;
  109093. int searchstep;
  109094. float minenergy;
  109095. mdct_lookup mdct;
  109096. float *mdct_win;
  109097. envelope_band band[VE_BANDS];
  109098. envelope_filter_state *filter;
  109099. int stretch;
  109100. int *mark;
  109101. long storage;
  109102. long current;
  109103. long curmark;
  109104. long cursor;
  109105. } envelope_lookup;
  109106. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  109107. extern void _ve_envelope_clear(envelope_lookup *e);
  109108. extern long _ve_envelope_search(vorbis_dsp_state *v);
  109109. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  109110. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  109111. #endif
  109112. /*** End of inlined file: envelope.h ***/
  109113. /*** Start of inlined file: codebook.h ***/
  109114. #ifndef _V_CODEBOOK_H_
  109115. #define _V_CODEBOOK_H_
  109116. /* This structure encapsulates huffman and VQ style encoding books; it
  109117. doesn't do anything specific to either.
  109118. valuelist/quantlist are nonNULL (and q_* significant) only if
  109119. there's entry->value mapping to be done.
  109120. If encode-side mapping must be done (and thus the entry needs to be
  109121. hunted), the auxiliary encode pointer will point to a decision
  109122. tree. This is true of both VQ and huffman, but is mostly useful
  109123. with VQ.
  109124. */
  109125. typedef struct static_codebook{
  109126. long dim; /* codebook dimensions (elements per vector) */
  109127. long entries; /* codebook entries */
  109128. long *lengthlist; /* codeword lengths in bits */
  109129. /* mapping ***************************************************************/
  109130. int maptype; /* 0=none
  109131. 1=implicitly populated values from map column
  109132. 2=listed arbitrary values */
  109133. /* The below does a linear, single monotonic sequence mapping. */
  109134. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  109135. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  109136. int q_quant; /* bits: 0 < quant <= 16 */
  109137. int q_sequencep; /* bitflag */
  109138. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  109139. map == 2: list of dim*entries quantized entry vals
  109140. */
  109141. /* encode helpers ********************************************************/
  109142. struct encode_aux_nearestmatch *nearest_tree;
  109143. struct encode_aux_threshmatch *thresh_tree;
  109144. struct encode_aux_pigeonhole *pigeon_tree;
  109145. int allocedp;
  109146. } static_codebook;
  109147. /* this structures an arbitrary trained book to quickly find the
  109148. nearest cell match */
  109149. typedef struct encode_aux_nearestmatch{
  109150. /* pre-calculated partitioning tree */
  109151. long *ptr0;
  109152. long *ptr1;
  109153. long *p; /* decision points (each is an entry) */
  109154. long *q; /* decision points (each is an entry) */
  109155. long aux; /* number of tree entries */
  109156. long alloc;
  109157. } encode_aux_nearestmatch;
  109158. /* assumes a maptype of 1; encode side only, so that's OK */
  109159. typedef struct encode_aux_threshmatch{
  109160. float *quantthresh;
  109161. long *quantmap;
  109162. int quantvals;
  109163. int threshvals;
  109164. } encode_aux_threshmatch;
  109165. typedef struct encode_aux_pigeonhole{
  109166. float min;
  109167. float del;
  109168. int mapentries;
  109169. int quantvals;
  109170. long *pigeonmap;
  109171. long fittotal;
  109172. long *fitlist;
  109173. long *fitmap;
  109174. long *fitlength;
  109175. } encode_aux_pigeonhole;
  109176. typedef struct codebook{
  109177. long dim; /* codebook dimensions (elements per vector) */
  109178. long entries; /* codebook entries */
  109179. long used_entries; /* populated codebook entries */
  109180. const static_codebook *c;
  109181. /* for encode, the below are entry-ordered, fully populated */
  109182. /* for decode, the below are ordered by bitreversed codeword and only
  109183. used entries are populated */
  109184. float *valuelist; /* list of dim*entries actual entry values */
  109185. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  109186. int *dec_index; /* only used if sparseness collapsed */
  109187. char *dec_codelengths;
  109188. ogg_uint32_t *dec_firsttable;
  109189. int dec_firsttablen;
  109190. int dec_maxlength;
  109191. } codebook;
  109192. extern void vorbis_staticbook_clear(static_codebook *b);
  109193. extern void vorbis_staticbook_destroy(static_codebook *b);
  109194. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  109195. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  109196. extern void vorbis_book_clear(codebook *b);
  109197. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  109198. extern float *_book_logdist(const static_codebook *b,float *vals);
  109199. extern float _float32_unpack(long val);
  109200. extern long _float32_pack(float val);
  109201. extern int _best(codebook *book, float *a, int step);
  109202. extern int _ilog(unsigned int v);
  109203. extern long _book_maptype1_quantvals(const static_codebook *b);
  109204. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  109205. extern long vorbis_book_codeword(codebook *book,int entry);
  109206. extern long vorbis_book_codelen(codebook *book,int entry);
  109207. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  109208. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  109209. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  109210. extern int vorbis_book_errorv(codebook *book, float *a);
  109211. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  109212. oggpack_buffer *b);
  109213. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  109214. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  109215. oggpack_buffer *b,int n);
  109216. extern long vorbis_book_decodev_set(codebook *book, float *a,
  109217. oggpack_buffer *b,int n);
  109218. extern long vorbis_book_decodev_add(codebook *book, float *a,
  109219. oggpack_buffer *b,int n);
  109220. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  109221. long off,int ch,
  109222. oggpack_buffer *b,int n);
  109223. #endif
  109224. /*** End of inlined file: codebook.h ***/
  109225. #define BLOCKTYPE_IMPULSE 0
  109226. #define BLOCKTYPE_PADDING 1
  109227. #define BLOCKTYPE_TRANSITION 0
  109228. #define BLOCKTYPE_LONG 1
  109229. #define PACKETBLOBS 15
  109230. typedef struct vorbis_block_internal{
  109231. float **pcmdelay; /* this is a pointer into local storage */
  109232. float ampmax;
  109233. int blocktype;
  109234. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  109235. blob [PACKETBLOBS/2] points to
  109236. the oggpack_buffer in the
  109237. main vorbis_block */
  109238. } vorbis_block_internal;
  109239. typedef void vorbis_look_floor;
  109240. typedef void vorbis_look_residue;
  109241. typedef void vorbis_look_transform;
  109242. /* mode ************************************************************/
  109243. typedef struct {
  109244. int blockflag;
  109245. int windowtype;
  109246. int transformtype;
  109247. int mapping;
  109248. } vorbis_info_mode;
  109249. typedef void vorbis_info_floor;
  109250. typedef void vorbis_info_residue;
  109251. typedef void vorbis_info_mapping;
  109252. /*** Start of inlined file: psy.h ***/
  109253. #ifndef _V_PSY_H_
  109254. #define _V_PSY_H_
  109255. /*** Start of inlined file: smallft.h ***/
  109256. #ifndef _V_SMFT_H_
  109257. #define _V_SMFT_H_
  109258. typedef struct {
  109259. int n;
  109260. float *trigcache;
  109261. int *splitcache;
  109262. } drft_lookup;
  109263. extern void drft_forward(drft_lookup *l,float *data);
  109264. extern void drft_backward(drft_lookup *l,float *data);
  109265. extern void drft_init(drft_lookup *l,int n);
  109266. extern void drft_clear(drft_lookup *l);
  109267. #endif
  109268. /*** End of inlined file: smallft.h ***/
  109269. /*** Start of inlined file: backends.h ***/
  109270. /* this is exposed up here because we need it for static modes.
  109271. Lookups for each backend aren't exposed because there's no reason
  109272. to do so */
  109273. #ifndef _vorbis_backend_h_
  109274. #define _vorbis_backend_h_
  109275. /* this would all be simpler/shorter with templates, but.... */
  109276. /* Floor backend generic *****************************************/
  109277. typedef struct{
  109278. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  109279. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  109280. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  109281. void (*free_info) (vorbis_info_floor *);
  109282. void (*free_look) (vorbis_look_floor *);
  109283. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  109284. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  109285. void *buffer,float *);
  109286. } vorbis_func_floor;
  109287. typedef struct{
  109288. int order;
  109289. long rate;
  109290. long barkmap;
  109291. int ampbits;
  109292. int ampdB;
  109293. int numbooks; /* <= 16 */
  109294. int books[16];
  109295. float lessthan; /* encode-only config setting hacks for libvorbis */
  109296. float greaterthan; /* encode-only config setting hacks for libvorbis */
  109297. } vorbis_info_floor0;
  109298. #define VIF_POSIT 63
  109299. #define VIF_CLASS 16
  109300. #define VIF_PARTS 31
  109301. typedef struct{
  109302. int partitions; /* 0 to 31 */
  109303. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  109304. int class_dim[VIF_CLASS]; /* 1 to 8 */
  109305. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  109306. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  109307. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  109308. int mult; /* 1 2 3 or 4 */
  109309. int postlist[VIF_POSIT+2]; /* first two implicit */
  109310. /* encode side analysis parameters */
  109311. float maxover;
  109312. float maxunder;
  109313. float maxerr;
  109314. float twofitweight;
  109315. float twofitatten;
  109316. int n;
  109317. } vorbis_info_floor1;
  109318. /* Residue backend generic *****************************************/
  109319. typedef struct{
  109320. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  109321. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  109322. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  109323. vorbis_info_residue *);
  109324. void (*free_info) (vorbis_info_residue *);
  109325. void (*free_look) (vorbis_look_residue *);
  109326. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  109327. float **,int *,int);
  109328. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  109329. vorbis_look_residue *,
  109330. float **,float **,int *,int,long **);
  109331. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  109332. float **,int *,int);
  109333. } vorbis_func_residue;
  109334. typedef struct vorbis_info_residue0{
  109335. /* block-partitioned VQ coded straight residue */
  109336. long begin;
  109337. long end;
  109338. /* first stage (lossless partitioning) */
  109339. int grouping; /* group n vectors per partition */
  109340. int partitions; /* possible codebooks for a partition */
  109341. int groupbook; /* huffbook for partitioning */
  109342. int secondstages[64]; /* expanded out to pointers in lookup */
  109343. int booklist[256]; /* list of second stage books */
  109344. float classmetric1[64];
  109345. float classmetric2[64];
  109346. } vorbis_info_residue0;
  109347. /* Mapping backend generic *****************************************/
  109348. typedef struct{
  109349. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  109350. oggpack_buffer *);
  109351. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  109352. void (*free_info) (vorbis_info_mapping *);
  109353. int (*forward) (struct vorbis_block *vb);
  109354. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  109355. } vorbis_func_mapping;
  109356. typedef struct vorbis_info_mapping0{
  109357. int submaps; /* <= 16 */
  109358. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  109359. int floorsubmap[16]; /* [mux] submap to floors */
  109360. int residuesubmap[16]; /* [mux] submap to residue */
  109361. int coupling_steps;
  109362. int coupling_mag[256];
  109363. int coupling_ang[256];
  109364. } vorbis_info_mapping0;
  109365. #endif
  109366. /*** End of inlined file: backends.h ***/
  109367. #ifndef EHMER_MAX
  109368. #define EHMER_MAX 56
  109369. #endif
  109370. /* psychoacoustic setup ********************************************/
  109371. #define P_BANDS 17 /* 62Hz to 16kHz */
  109372. #define P_LEVELS 8 /* 30dB to 100dB */
  109373. #define P_LEVEL_0 30. /* 30 dB */
  109374. #define P_NOISECURVES 3
  109375. #define NOISE_COMPAND_LEVELS 40
  109376. typedef struct vorbis_info_psy{
  109377. int blockflag;
  109378. float ath_adjatt;
  109379. float ath_maxatt;
  109380. float tone_masteratt[P_NOISECURVES];
  109381. float tone_centerboost;
  109382. float tone_decay;
  109383. float tone_abs_limit;
  109384. float toneatt[P_BANDS];
  109385. int noisemaskp;
  109386. float noisemaxsupp;
  109387. float noisewindowlo;
  109388. float noisewindowhi;
  109389. int noisewindowlomin;
  109390. int noisewindowhimin;
  109391. int noisewindowfixed;
  109392. float noiseoff[P_NOISECURVES][P_BANDS];
  109393. float noisecompand[NOISE_COMPAND_LEVELS];
  109394. float max_curve_dB;
  109395. int normal_channel_p;
  109396. int normal_point_p;
  109397. int normal_start;
  109398. int normal_partition;
  109399. double normal_thresh;
  109400. } vorbis_info_psy;
  109401. typedef struct{
  109402. int eighth_octave_lines;
  109403. /* for block long/short tuning; encode only */
  109404. float preecho_thresh[VE_BANDS];
  109405. float postecho_thresh[VE_BANDS];
  109406. float stretch_penalty;
  109407. float preecho_minenergy;
  109408. float ampmax_att_per_sec;
  109409. /* channel coupling config */
  109410. int coupling_pkHz[PACKETBLOBS];
  109411. int coupling_pointlimit[2][PACKETBLOBS];
  109412. int coupling_prepointamp[PACKETBLOBS];
  109413. int coupling_postpointamp[PACKETBLOBS];
  109414. int sliding_lowpass[2][PACKETBLOBS];
  109415. } vorbis_info_psy_global;
  109416. typedef struct {
  109417. float ampmax;
  109418. int channels;
  109419. vorbis_info_psy_global *gi;
  109420. int coupling_pointlimit[2][P_NOISECURVES];
  109421. } vorbis_look_psy_global;
  109422. typedef struct {
  109423. int n;
  109424. struct vorbis_info_psy *vi;
  109425. float ***tonecurves;
  109426. float **noiseoffset;
  109427. float *ath;
  109428. long *octave; /* in n.ocshift format */
  109429. long *bark;
  109430. long firstoc;
  109431. long shiftoc;
  109432. int eighth_octave_lines; /* power of two, please */
  109433. int total_octave_lines;
  109434. long rate; /* cache it */
  109435. float m_val; /* Masking compensation value */
  109436. } vorbis_look_psy;
  109437. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  109438. vorbis_info_psy_global *gi,int n,long rate);
  109439. extern void _vp_psy_clear(vorbis_look_psy *p);
  109440. extern void *_vi_psy_dup(void *source);
  109441. extern void _vi_psy_free(vorbis_info_psy *i);
  109442. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  109443. extern void _vp_remove_floor(vorbis_look_psy *p,
  109444. float *mdct,
  109445. int *icodedflr,
  109446. float *residue,
  109447. int sliding_lowpass);
  109448. extern void _vp_noisemask(vorbis_look_psy *p,
  109449. float *logmdct,
  109450. float *logmask);
  109451. extern void _vp_tonemask(vorbis_look_psy *p,
  109452. float *logfft,
  109453. float *logmask,
  109454. float global_specmax,
  109455. float local_specmax);
  109456. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  109457. float *noise,
  109458. float *tone,
  109459. int offset_select,
  109460. float *logmask,
  109461. float *mdct,
  109462. float *logmdct);
  109463. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  109464. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  109465. vorbis_info_psy_global *g,
  109466. vorbis_look_psy *p,
  109467. vorbis_info_mapping0 *vi,
  109468. float **mdct);
  109469. extern void _vp_couple(int blobno,
  109470. vorbis_info_psy_global *g,
  109471. vorbis_look_psy *p,
  109472. vorbis_info_mapping0 *vi,
  109473. float **res,
  109474. float **mag_memo,
  109475. int **mag_sort,
  109476. int **ifloor,
  109477. int *nonzero,
  109478. int sliding_lowpass);
  109479. extern void _vp_noise_normalize(vorbis_look_psy *p,
  109480. float *in,float *out,int *sortedindex);
  109481. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  109482. float *magnitudes,int *sortedindex);
  109483. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  109484. vorbis_look_psy *p,
  109485. vorbis_info_mapping0 *vi,
  109486. float **mags);
  109487. extern void hf_reduction(vorbis_info_psy_global *g,
  109488. vorbis_look_psy *p,
  109489. vorbis_info_mapping0 *vi,
  109490. float **mdct);
  109491. #endif
  109492. /*** End of inlined file: psy.h ***/
  109493. /*** Start of inlined file: bitrate.h ***/
  109494. #ifndef _V_BITRATE_H_
  109495. #define _V_BITRATE_H_
  109496. /*** Start of inlined file: os.h ***/
  109497. #ifndef _OS_H
  109498. #define _OS_H
  109499. /********************************************************************
  109500. * *
  109501. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  109502. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  109503. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  109504. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  109505. * *
  109506. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  109507. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  109508. * *
  109509. ********************************************************************
  109510. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  109511. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  109512. ********************************************************************/
  109513. #ifdef HAVE_CONFIG_H
  109514. #include "config.h"
  109515. #endif
  109516. #include <math.h>
  109517. /*** Start of inlined file: misc.h ***/
  109518. #ifndef _V_RANDOM_H_
  109519. #define _V_RANDOM_H_
  109520. extern int analysis_noisy;
  109521. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  109522. extern void _vorbis_block_ripcord(vorbis_block *vb);
  109523. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  109524. ogg_int64_t off);
  109525. #ifdef DEBUG_MALLOC
  109526. #define _VDBG_GRAPHFILE "malloc.m"
  109527. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  109528. extern void _VDBG_free(void *ptr,char *file,long line);
  109529. #ifndef MISC_C
  109530. #undef _ogg_malloc
  109531. #undef _ogg_calloc
  109532. #undef _ogg_realloc
  109533. #undef _ogg_free
  109534. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  109535. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  109536. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  109537. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  109538. #endif
  109539. #endif
  109540. #endif
  109541. /*** End of inlined file: misc.h ***/
  109542. #ifndef _V_IFDEFJAIL_H_
  109543. # define _V_IFDEFJAIL_H_
  109544. # ifdef __GNUC__
  109545. # define STIN static __inline__
  109546. # elif _WIN32
  109547. # define STIN static __inline
  109548. # else
  109549. # define STIN static
  109550. # endif
  109551. #ifdef DJGPP
  109552. # define rint(x) (floor((x)+0.5f))
  109553. #endif
  109554. #ifndef M_PI
  109555. # define M_PI (3.1415926536f)
  109556. #endif
  109557. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  109558. # include <malloc.h>
  109559. # define rint(x) (floor((x)+0.5f))
  109560. # define NO_FLOAT_MATH_LIB
  109561. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  109562. #endif
  109563. #if defined(__SYMBIAN32__) && defined(__WINS__)
  109564. void *_alloca(size_t size);
  109565. # define alloca _alloca
  109566. #endif
  109567. #ifndef FAST_HYPOT
  109568. # define FAST_HYPOT hypot
  109569. #endif
  109570. #endif
  109571. #ifdef HAVE_ALLOCA_H
  109572. # include <alloca.h>
  109573. #endif
  109574. #ifdef USE_MEMORY_H
  109575. # include <memory.h>
  109576. #endif
  109577. #ifndef min
  109578. # define min(x,y) ((x)>(y)?(y):(x))
  109579. #endif
  109580. #ifndef max
  109581. # define max(x,y) ((x)<(y)?(y):(x))
  109582. #endif
  109583. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  109584. # define VORBIS_FPU_CONTROL
  109585. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  109586. Because of encapsulation constraints (GCC can't see inside the asm
  109587. block and so we end up doing stupid things like a store/load that
  109588. is collectively a noop), we do it this way */
  109589. /* we must set up the fpu before this works!! */
  109590. typedef ogg_int16_t vorbis_fpu_control;
  109591. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  109592. ogg_int16_t ret;
  109593. ogg_int16_t temp;
  109594. __asm__ __volatile__("fnstcw %0\n\t"
  109595. "movw %0,%%dx\n\t"
  109596. "orw $62463,%%dx\n\t"
  109597. "movw %%dx,%1\n\t"
  109598. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  109599. *fpu=ret;
  109600. }
  109601. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  109602. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  109603. }
  109604. /* assumes the FPU is in round mode! */
  109605. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  109606. we get extra fst/fld to
  109607. truncate precision */
  109608. int i;
  109609. __asm__("fistl %0": "=m"(i) : "t"(f));
  109610. return(i);
  109611. }
  109612. #endif
  109613. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  109614. # define VORBIS_FPU_CONTROL
  109615. typedef ogg_int16_t vorbis_fpu_control;
  109616. static __inline int vorbis_ftoi(double f){
  109617. int i;
  109618. __asm{
  109619. fld f
  109620. fistp i
  109621. }
  109622. return i;
  109623. }
  109624. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  109625. }
  109626. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  109627. }
  109628. #endif
  109629. #ifndef VORBIS_FPU_CONTROL
  109630. typedef int vorbis_fpu_control;
  109631. static int vorbis_ftoi(double f){
  109632. return (int)(f+.5);
  109633. }
  109634. /* We don't have special code for this compiler/arch, so do it the slow way */
  109635. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  109636. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  109637. #endif
  109638. #endif /* _OS_H */
  109639. /*** End of inlined file: os.h ***/
  109640. /* encode side bitrate tracking */
  109641. typedef struct bitrate_manager_state {
  109642. int managed;
  109643. long avg_reservoir;
  109644. long minmax_reservoir;
  109645. long avg_bitsper;
  109646. long min_bitsper;
  109647. long max_bitsper;
  109648. long short_per_long;
  109649. double avgfloat;
  109650. vorbis_block *vb;
  109651. int choice;
  109652. } bitrate_manager_state;
  109653. typedef struct bitrate_manager_info{
  109654. long avg_rate;
  109655. long min_rate;
  109656. long max_rate;
  109657. long reservoir_bits;
  109658. double reservoir_bias;
  109659. double slew_damp;
  109660. } bitrate_manager_info;
  109661. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  109662. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  109663. extern int vorbis_bitrate_managed(vorbis_block *vb);
  109664. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  109665. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  109666. #endif
  109667. /*** End of inlined file: bitrate.h ***/
  109668. static int ilog(unsigned int v){
  109669. int ret=0;
  109670. while(v){
  109671. ret++;
  109672. v>>=1;
  109673. }
  109674. return(ret);
  109675. }
  109676. static int ilog2(unsigned int v){
  109677. int ret=0;
  109678. if(v)--v;
  109679. while(v){
  109680. ret++;
  109681. v>>=1;
  109682. }
  109683. return(ret);
  109684. }
  109685. typedef struct private_state {
  109686. /* local lookup storage */
  109687. envelope_lookup *ve; /* envelope lookup */
  109688. int window[2];
  109689. vorbis_look_transform **transform[2]; /* block, type */
  109690. drft_lookup fft_look[2];
  109691. int modebits;
  109692. vorbis_look_floor **flr;
  109693. vorbis_look_residue **residue;
  109694. vorbis_look_psy *psy;
  109695. vorbis_look_psy_global *psy_g_look;
  109696. /* local storage, only used on the encoding side. This way the
  109697. application does not need to worry about freeing some packets'
  109698. memory and not others'; packet storage is always tracked.
  109699. Cleared next call to a _dsp_ function */
  109700. unsigned char *header;
  109701. unsigned char *header1;
  109702. unsigned char *header2;
  109703. bitrate_manager_state bms;
  109704. ogg_int64_t sample_count;
  109705. } private_state;
  109706. /* codec_setup_info contains all the setup information specific to the
  109707. specific compression/decompression mode in progress (eg,
  109708. psychoacoustic settings, channel setup, options, codebook
  109709. etc).
  109710. *********************************************************************/
  109711. /*** Start of inlined file: highlevel.h ***/
  109712. typedef struct highlevel_byblocktype {
  109713. double tone_mask_setting;
  109714. double tone_peaklimit_setting;
  109715. double noise_bias_setting;
  109716. double noise_compand_setting;
  109717. } highlevel_byblocktype;
  109718. typedef struct highlevel_encode_setup {
  109719. void *setup;
  109720. int set_in_stone;
  109721. double base_setting;
  109722. double long_setting;
  109723. double short_setting;
  109724. double impulse_noisetune;
  109725. int managed;
  109726. long bitrate_min;
  109727. long bitrate_av;
  109728. double bitrate_av_damp;
  109729. long bitrate_max;
  109730. long bitrate_reservoir;
  109731. double bitrate_reservoir_bias;
  109732. int impulse_block_p;
  109733. int noise_normalize_p;
  109734. double stereo_point_setting;
  109735. double lowpass_kHz;
  109736. double ath_floating_dB;
  109737. double ath_absolute_dB;
  109738. double amplitude_track_dBpersec;
  109739. double trigger_setting;
  109740. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  109741. } highlevel_encode_setup;
  109742. /*** End of inlined file: highlevel.h ***/
  109743. typedef struct codec_setup_info {
  109744. /* Vorbis supports only short and long blocks, but allows the
  109745. encoder to choose the sizes */
  109746. long blocksizes[2];
  109747. /* modes are the primary means of supporting on-the-fly different
  109748. blocksizes, different channel mappings (LR or M/A),
  109749. different residue backends, etc. Each mode consists of a
  109750. blocksize flag and a mapping (along with the mapping setup */
  109751. int modes;
  109752. int maps;
  109753. int floors;
  109754. int residues;
  109755. int books;
  109756. int psys; /* encode only */
  109757. vorbis_info_mode *mode_param[64];
  109758. int map_type[64];
  109759. vorbis_info_mapping *map_param[64];
  109760. int floor_type[64];
  109761. vorbis_info_floor *floor_param[64];
  109762. int residue_type[64];
  109763. vorbis_info_residue *residue_param[64];
  109764. static_codebook *book_param[256];
  109765. codebook *fullbooks;
  109766. vorbis_info_psy *psy_param[4]; /* encode only */
  109767. vorbis_info_psy_global psy_g_param;
  109768. bitrate_manager_info bi;
  109769. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  109770. highly redundant structure, but
  109771. improves clarity of program flow. */
  109772. int halfrate_flag; /* painless downsample for decode */
  109773. } codec_setup_info;
  109774. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  109775. extern void _vp_global_free(vorbis_look_psy_global *look);
  109776. #endif
  109777. /*** End of inlined file: codec_internal.h ***/
  109778. /*** Start of inlined file: registry.h ***/
  109779. #ifndef _V_REG_H_
  109780. #define _V_REG_H_
  109781. #define VI_TRANSFORMB 1
  109782. #define VI_WINDOWB 1
  109783. #define VI_TIMEB 1
  109784. #define VI_FLOORB 2
  109785. #define VI_RESB 3
  109786. #define VI_MAPB 1
  109787. extern vorbis_func_floor *_floor_P[];
  109788. extern vorbis_func_residue *_residue_P[];
  109789. extern vorbis_func_mapping *_mapping_P[];
  109790. #endif
  109791. /*** End of inlined file: registry.h ***/
  109792. /*** Start of inlined file: scales.h ***/
  109793. #ifndef _V_SCALES_H_
  109794. #define _V_SCALES_H_
  109795. #include <math.h>
  109796. /* 20log10(x) */
  109797. #define VORBIS_IEEE_FLOAT32 1
  109798. #ifdef VORBIS_IEEE_FLOAT32
  109799. static float unitnorm(float x){
  109800. union {
  109801. ogg_uint32_t i;
  109802. float f;
  109803. } ix;
  109804. ix.f = x;
  109805. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  109806. return ix.f;
  109807. }
  109808. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  109809. static float todB(const float *x){
  109810. union {
  109811. ogg_uint32_t i;
  109812. float f;
  109813. } ix;
  109814. ix.f = *x;
  109815. ix.i = ix.i&0x7fffffff;
  109816. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  109817. }
  109818. #define todB_nn(x) todB(x)
  109819. #else
  109820. static float unitnorm(float x){
  109821. if(x<0)return(-1.f);
  109822. return(1.f);
  109823. }
  109824. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  109825. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  109826. #endif
  109827. #define fromdB(x) (exp((x)*.11512925f))
  109828. /* The bark scale equations are approximations, since the original
  109829. table was somewhat hand rolled. The below are chosen to have the
  109830. best possible fit to the rolled tables, thus their somewhat odd
  109831. appearance (these are more accurate and over a longer range than
  109832. the oft-quoted bark equations found in the texts I have). The
  109833. approximations are valid from 0 - 30kHz (nyquist) or so.
  109834. all f in Hz, z in Bark */
  109835. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  109836. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  109837. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  109838. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  109839. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  109840. 0.0 */
  109841. #define toOC(n) (log(n)*1.442695f-5.965784f)
  109842. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  109843. #endif
  109844. /*** End of inlined file: scales.h ***/
  109845. int analysis_noisy=1;
  109846. /* decides between modes, dispatches to the appropriate mapping. */
  109847. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  109848. int ret,i;
  109849. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  109850. vb->glue_bits=0;
  109851. vb->time_bits=0;
  109852. vb->floor_bits=0;
  109853. vb->res_bits=0;
  109854. /* first things first. Make sure encode is ready */
  109855. for(i=0;i<PACKETBLOBS;i++)
  109856. oggpack_reset(vbi->packetblob[i]);
  109857. /* we only have one mapping type (0), and we let the mapping code
  109858. itself figure out what soft mode to use. This allows easier
  109859. bitrate management */
  109860. if((ret=_mapping_P[0]->forward(vb)))
  109861. return(ret);
  109862. if(op){
  109863. if(vorbis_bitrate_managed(vb))
  109864. /* The app is using a bitmanaged mode... but not using the
  109865. bitrate management interface. */
  109866. return(OV_EINVAL);
  109867. op->packet=oggpack_get_buffer(&vb->opb);
  109868. op->bytes=oggpack_bytes(&vb->opb);
  109869. op->b_o_s=0;
  109870. op->e_o_s=vb->eofflag;
  109871. op->granulepos=vb->granulepos;
  109872. op->packetno=vb->sequence; /* for sake of completeness */
  109873. }
  109874. return(0);
  109875. }
  109876. /* there was no great place to put this.... */
  109877. void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  109878. int j;
  109879. FILE *of;
  109880. char buffer[80];
  109881. /* if(i==5870){*/
  109882. sprintf(buffer,"%s_%d.m",base,i);
  109883. of=fopen(buffer,"w");
  109884. if(!of)perror("failed to open data dump file");
  109885. for(j=0;j<n;j++){
  109886. if(bark){
  109887. float b=toBARK((4000.f*j/n)+.25);
  109888. fprintf(of,"%f ",b);
  109889. }else
  109890. if(off!=0)
  109891. fprintf(of,"%f ",(double)(j+off)/8000.);
  109892. else
  109893. fprintf(of,"%f ",(double)j);
  109894. if(dB){
  109895. float val;
  109896. if(v[j]==0.)
  109897. val=-140.;
  109898. else
  109899. val=todB(v+j);
  109900. fprintf(of,"%f\n",val);
  109901. }else{
  109902. fprintf(of,"%f\n",v[j]);
  109903. }
  109904. }
  109905. fclose(of);
  109906. /* } */
  109907. }
  109908. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  109909. ogg_int64_t off){
  109910. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  109911. }
  109912. #endif
  109913. /*** End of inlined file: analysis.c ***/
  109914. /*** Start of inlined file: bitrate.c ***/
  109915. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  109916. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109917. // tasks..
  109918. #if JUCE_MSVC
  109919. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109920. #endif
  109921. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  109922. #if JUCE_USE_OGGVORBIS
  109923. #include <stdlib.h>
  109924. #include <string.h>
  109925. #include <math.h>
  109926. /* compute bitrate tracking setup */
  109927. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  109928. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  109929. bitrate_manager_info *bi=&ci->bi;
  109930. memset(bm,0,sizeof(*bm));
  109931. if(bi && (bi->reservoir_bits>0)){
  109932. long ratesamples=vi->rate;
  109933. int halfsamples=ci->blocksizes[0]>>1;
  109934. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  109935. bm->managed=1;
  109936. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  109937. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  109938. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  109939. bm->avgfloat=PACKETBLOBS/2;
  109940. /* not a necessary fix, but one that leads to a more balanced
  109941. typical initialization */
  109942. {
  109943. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  109944. bm->minmax_reservoir=desired_fill;
  109945. bm->avg_reservoir=desired_fill;
  109946. }
  109947. }
  109948. }
  109949. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  109950. memset(bm,0,sizeof(*bm));
  109951. return;
  109952. }
  109953. int vorbis_bitrate_managed(vorbis_block *vb){
  109954. vorbis_dsp_state *vd=vb->vd;
  109955. private_state *b=(private_state*)vd->backend_state;
  109956. bitrate_manager_state *bm=&b->bms;
  109957. if(bm && bm->managed)return(1);
  109958. return(0);
  109959. }
  109960. /* finish taking in the block we just processed */
  109961. int vorbis_bitrate_addblock(vorbis_block *vb){
  109962. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  109963. vorbis_dsp_state *vd=vb->vd;
  109964. private_state *b=(private_state*)vd->backend_state;
  109965. bitrate_manager_state *bm=&b->bms;
  109966. vorbis_info *vi=vd->vi;
  109967. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109968. bitrate_manager_info *bi=&ci->bi;
  109969. int choice=rint(bm->avgfloat);
  109970. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  109971. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  109972. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  109973. int samples=ci->blocksizes[vb->W]>>1;
  109974. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  109975. if(!bm->managed){
  109976. /* not a bitrate managed stream, but for API simplicity, we'll
  109977. buffer the packet to keep the code path clean */
  109978. if(bm->vb)return(-1); /* one has been submitted without
  109979. being claimed */
  109980. bm->vb=vb;
  109981. return(0);
  109982. }
  109983. bm->vb=vb;
  109984. /* look ahead for avg floater */
  109985. if(bm->avg_bitsper>0){
  109986. double slew=0.;
  109987. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  109988. double slewlimit= 15./bi->slew_damp;
  109989. /* choosing a new floater:
  109990. if we're over target, we slew down
  109991. if we're under target, we slew up
  109992. choose slew as follows: look through packetblobs of this frame
  109993. and set slew as the first in the appropriate direction that
  109994. gives us the slew we want. This may mean no slew if delta is
  109995. already favorable.
  109996. Then limit slew to slew max */
  109997. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  109998. while(choice>0 && this_bits>avg_target_bits &&
  109999. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  110000. choice--;
  110001. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110002. }
  110003. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  110004. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  110005. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  110006. choice++;
  110007. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110008. }
  110009. }
  110010. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  110011. if(slew<-slewlimit)slew=-slewlimit;
  110012. if(slew>slewlimit)slew=slewlimit;
  110013. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  110014. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110015. }
  110016. /* enforce min(if used) on the current floater (if used) */
  110017. if(bm->min_bitsper>0){
  110018. /* do we need to force the bitrate up? */
  110019. if(this_bits<min_target_bits){
  110020. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  110021. choice++;
  110022. if(choice>=PACKETBLOBS)break;
  110023. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110024. }
  110025. }
  110026. }
  110027. /* enforce max (if used) on the current floater (if used) */
  110028. if(bm->max_bitsper>0){
  110029. /* do we need to force the bitrate down? */
  110030. if(this_bits>max_target_bits){
  110031. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  110032. choice--;
  110033. if(choice<0)break;
  110034. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110035. }
  110036. }
  110037. }
  110038. /* Choice of packetblobs now made based on floater, and min/max
  110039. requirements. Now boundary check extreme choices */
  110040. if(choice<0){
  110041. /* choosing a smaller packetblob is insufficient to trim bitrate.
  110042. frame will need to be truncated */
  110043. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  110044. bm->choice=choice=0;
  110045. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  110046. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  110047. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110048. }
  110049. }else{
  110050. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  110051. if(choice>=PACKETBLOBS)
  110052. choice=PACKETBLOBS-1;
  110053. bm->choice=choice;
  110054. /* prop up bitrate according to demand. pad this frame out with zeroes */
  110055. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  110056. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  110057. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110058. }
  110059. /* now we have the final packet and the final packet size. Update statistics */
  110060. /* min and max reservoir */
  110061. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  110062. if(max_target_bits>0 && this_bits>max_target_bits){
  110063. bm->minmax_reservoir+=(this_bits-max_target_bits);
  110064. }else if(min_target_bits>0 && this_bits<min_target_bits){
  110065. bm->minmax_reservoir+=(this_bits-min_target_bits);
  110066. }else{
  110067. /* inbetween; we want to take reservoir toward but not past desired_fill */
  110068. if(bm->minmax_reservoir>desired_fill){
  110069. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  110070. bm->minmax_reservoir+=(this_bits-max_target_bits);
  110071. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  110072. }else{
  110073. bm->minmax_reservoir=desired_fill;
  110074. }
  110075. }else{
  110076. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  110077. bm->minmax_reservoir+=(this_bits-min_target_bits);
  110078. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  110079. }else{
  110080. bm->minmax_reservoir=desired_fill;
  110081. }
  110082. }
  110083. }
  110084. }
  110085. /* avg reservoir */
  110086. if(bm->avg_bitsper>0){
  110087. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  110088. bm->avg_reservoir+=this_bits-avg_target_bits;
  110089. }
  110090. return(0);
  110091. }
  110092. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  110093. private_state *b=(private_state*)vd->backend_state;
  110094. bitrate_manager_state *bm=&b->bms;
  110095. vorbis_block *vb=bm->vb;
  110096. int choice=PACKETBLOBS/2;
  110097. if(!vb)return 0;
  110098. if(op){
  110099. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110100. if(vorbis_bitrate_managed(vb))
  110101. choice=bm->choice;
  110102. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  110103. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  110104. op->b_o_s=0;
  110105. op->e_o_s=vb->eofflag;
  110106. op->granulepos=vb->granulepos;
  110107. op->packetno=vb->sequence; /* for sake of completeness */
  110108. }
  110109. bm->vb=0;
  110110. return(1);
  110111. }
  110112. #endif
  110113. /*** End of inlined file: bitrate.c ***/
  110114. /*** Start of inlined file: block.c ***/
  110115. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110116. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110117. // tasks..
  110118. #if JUCE_MSVC
  110119. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110120. #endif
  110121. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110122. #if JUCE_USE_OGGVORBIS
  110123. #include <stdio.h>
  110124. #include <stdlib.h>
  110125. #include <string.h>
  110126. /*** Start of inlined file: window.h ***/
  110127. #ifndef _V_WINDOW_
  110128. #define _V_WINDOW_
  110129. extern float *_vorbis_window_get(int n);
  110130. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  110131. int lW,int W,int nW);
  110132. #endif
  110133. /*** End of inlined file: window.h ***/
  110134. /*** Start of inlined file: lpc.h ***/
  110135. #ifndef _V_LPC_H_
  110136. #define _V_LPC_H_
  110137. /* simple linear scale LPC code */
  110138. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  110139. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  110140. float *data,long n);
  110141. #endif
  110142. /*** End of inlined file: lpc.h ***/
  110143. /* pcm accumulator examples (not exhaustive):
  110144. <-------------- lW ---------------->
  110145. <--------------- W ---------------->
  110146. : .....|..... _______________ |
  110147. : .''' | '''_--- | |\ |
  110148. :.....''' |_____--- '''......| | \_______|
  110149. :.................|__________________|_______|__|______|
  110150. |<------ Sl ------>| > Sr < |endW
  110151. |beginSl |endSl | |endSr
  110152. |beginW |endlW |beginSr
  110153. |< lW >|
  110154. <--------------- W ---------------->
  110155. | | .. ______________ |
  110156. | | ' `/ | ---_ |
  110157. |___.'___/`. | ---_____|
  110158. |_______|__|_______|_________________|
  110159. | >|Sl|< |<------ Sr ----->|endW
  110160. | | |endSl |beginSr |endSr
  110161. |beginW | |endlW
  110162. mult[0] |beginSl mult[n]
  110163. <-------------- lW ----------------->
  110164. |<--W-->|
  110165. : .............. ___ | |
  110166. : .''' |`/ \ | |
  110167. :.....''' |/`....\|...|
  110168. :.........................|___|___|___|
  110169. |Sl |Sr |endW
  110170. | | |endSr
  110171. | |beginSr
  110172. | |endSl
  110173. |beginSl
  110174. |beginW
  110175. */
  110176. /* block abstraction setup *********************************************/
  110177. #ifndef WORD_ALIGN
  110178. #define WORD_ALIGN 8
  110179. #endif
  110180. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  110181. int i;
  110182. memset(vb,0,sizeof(*vb));
  110183. vb->vd=v;
  110184. vb->localalloc=0;
  110185. vb->localstore=NULL;
  110186. if(v->analysisp){
  110187. vorbis_block_internal *vbi=(vorbis_block_internal*)
  110188. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  110189. vbi->ampmax=-9999;
  110190. for(i=0;i<PACKETBLOBS;i++){
  110191. if(i==PACKETBLOBS/2){
  110192. vbi->packetblob[i]=&vb->opb;
  110193. }else{
  110194. vbi->packetblob[i]=
  110195. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  110196. }
  110197. oggpack_writeinit(vbi->packetblob[i]);
  110198. }
  110199. }
  110200. return(0);
  110201. }
  110202. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  110203. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  110204. if(bytes+vb->localtop>vb->localalloc){
  110205. /* can't just _ogg_realloc... there are outstanding pointers */
  110206. if(vb->localstore){
  110207. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  110208. vb->totaluse+=vb->localtop;
  110209. link->next=vb->reap;
  110210. link->ptr=vb->localstore;
  110211. vb->reap=link;
  110212. }
  110213. /* highly conservative */
  110214. vb->localalloc=bytes;
  110215. vb->localstore=_ogg_malloc(vb->localalloc);
  110216. vb->localtop=0;
  110217. }
  110218. {
  110219. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  110220. vb->localtop+=bytes;
  110221. return ret;
  110222. }
  110223. }
  110224. /* reap the chain, pull the ripcord */
  110225. void _vorbis_block_ripcord(vorbis_block *vb){
  110226. /* reap the chain */
  110227. struct alloc_chain *reap=vb->reap;
  110228. while(reap){
  110229. struct alloc_chain *next=reap->next;
  110230. _ogg_free(reap->ptr);
  110231. memset(reap,0,sizeof(*reap));
  110232. _ogg_free(reap);
  110233. reap=next;
  110234. }
  110235. /* consolidate storage */
  110236. if(vb->totaluse){
  110237. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  110238. vb->localalloc+=vb->totaluse;
  110239. vb->totaluse=0;
  110240. }
  110241. /* pull the ripcord */
  110242. vb->localtop=0;
  110243. vb->reap=NULL;
  110244. }
  110245. int vorbis_block_clear(vorbis_block *vb){
  110246. int i;
  110247. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110248. _vorbis_block_ripcord(vb);
  110249. if(vb->localstore)_ogg_free(vb->localstore);
  110250. if(vbi){
  110251. for(i=0;i<PACKETBLOBS;i++){
  110252. oggpack_writeclear(vbi->packetblob[i]);
  110253. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  110254. }
  110255. _ogg_free(vbi);
  110256. }
  110257. memset(vb,0,sizeof(*vb));
  110258. return(0);
  110259. }
  110260. /* Analysis side code, but directly related to blocking. Thus it's
  110261. here and not in analysis.c (which is for analysis transforms only).
  110262. The init is here because some of it is shared */
  110263. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  110264. int i;
  110265. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110266. private_state *b=NULL;
  110267. int hs;
  110268. if(ci==NULL) return 1;
  110269. hs=ci->halfrate_flag;
  110270. memset(v,0,sizeof(*v));
  110271. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  110272. v->vi=vi;
  110273. b->modebits=ilog2(ci->modes);
  110274. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  110275. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  110276. /* MDCT is tranform 0 */
  110277. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  110278. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  110279. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  110280. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  110281. /* Vorbis I uses only window type 0 */
  110282. b->window[0]=ilog2(ci->blocksizes[0])-6;
  110283. b->window[1]=ilog2(ci->blocksizes[1])-6;
  110284. if(encp){ /* encode/decode differ here */
  110285. /* analysis always needs an fft */
  110286. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  110287. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  110288. /* finish the codebooks */
  110289. if(!ci->fullbooks){
  110290. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  110291. for(i=0;i<ci->books;i++)
  110292. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  110293. }
  110294. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  110295. for(i=0;i<ci->psys;i++){
  110296. _vp_psy_init(b->psy+i,
  110297. ci->psy_param[i],
  110298. &ci->psy_g_param,
  110299. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  110300. vi->rate);
  110301. }
  110302. v->analysisp=1;
  110303. }else{
  110304. /* finish the codebooks */
  110305. if(!ci->fullbooks){
  110306. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  110307. for(i=0;i<ci->books;i++){
  110308. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  110309. /* decode codebooks are now standalone after init */
  110310. vorbis_staticbook_destroy(ci->book_param[i]);
  110311. ci->book_param[i]=NULL;
  110312. }
  110313. }
  110314. }
  110315. /* initialize the storage vectors. blocksize[1] is small for encode,
  110316. but the correct size for decode */
  110317. v->pcm_storage=ci->blocksizes[1];
  110318. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  110319. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  110320. {
  110321. int i;
  110322. for(i=0;i<vi->channels;i++)
  110323. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  110324. }
  110325. /* all 1 (large block) or 0 (small block) */
  110326. /* explicitly set for the sake of clarity */
  110327. v->lW=0; /* previous window size */
  110328. v->W=0; /* current window size */
  110329. /* all vector indexes */
  110330. v->centerW=ci->blocksizes[1]/2;
  110331. v->pcm_current=v->centerW;
  110332. /* initialize all the backend lookups */
  110333. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  110334. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  110335. for(i=0;i<ci->floors;i++)
  110336. b->flr[i]=_floor_P[ci->floor_type[i]]->
  110337. look(v,ci->floor_param[i]);
  110338. for(i=0;i<ci->residues;i++)
  110339. b->residue[i]=_residue_P[ci->residue_type[i]]->
  110340. look(v,ci->residue_param[i]);
  110341. return 0;
  110342. }
  110343. /* arbitrary settings and spec-mandated numbers get filled in here */
  110344. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  110345. private_state *b=NULL;
  110346. if(_vds_shared_init(v,vi,1))return 1;
  110347. b=(private_state*)v->backend_state;
  110348. b->psy_g_look=_vp_global_look(vi);
  110349. /* Initialize the envelope state storage */
  110350. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  110351. _ve_envelope_init(b->ve,vi);
  110352. vorbis_bitrate_init(vi,&b->bms);
  110353. /* compressed audio packets start after the headers
  110354. with sequence number 3 */
  110355. v->sequence=3;
  110356. return(0);
  110357. }
  110358. void vorbis_dsp_clear(vorbis_dsp_state *v){
  110359. int i;
  110360. if(v){
  110361. vorbis_info *vi=v->vi;
  110362. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  110363. private_state *b=(private_state*)v->backend_state;
  110364. if(b){
  110365. if(b->ve){
  110366. _ve_envelope_clear(b->ve);
  110367. _ogg_free(b->ve);
  110368. }
  110369. if(b->transform[0]){
  110370. mdct_clear((mdct_lookup*) b->transform[0][0]);
  110371. _ogg_free(b->transform[0][0]);
  110372. _ogg_free(b->transform[0]);
  110373. }
  110374. if(b->transform[1]){
  110375. mdct_clear((mdct_lookup*) b->transform[1][0]);
  110376. _ogg_free(b->transform[1][0]);
  110377. _ogg_free(b->transform[1]);
  110378. }
  110379. if(b->flr){
  110380. for(i=0;i<ci->floors;i++)
  110381. _floor_P[ci->floor_type[i]]->
  110382. free_look(b->flr[i]);
  110383. _ogg_free(b->flr);
  110384. }
  110385. if(b->residue){
  110386. for(i=0;i<ci->residues;i++)
  110387. _residue_P[ci->residue_type[i]]->
  110388. free_look(b->residue[i]);
  110389. _ogg_free(b->residue);
  110390. }
  110391. if(b->psy){
  110392. for(i=0;i<ci->psys;i++)
  110393. _vp_psy_clear(b->psy+i);
  110394. _ogg_free(b->psy);
  110395. }
  110396. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  110397. vorbis_bitrate_clear(&b->bms);
  110398. drft_clear(&b->fft_look[0]);
  110399. drft_clear(&b->fft_look[1]);
  110400. }
  110401. if(v->pcm){
  110402. for(i=0;i<vi->channels;i++)
  110403. if(v->pcm[i])_ogg_free(v->pcm[i]);
  110404. _ogg_free(v->pcm);
  110405. if(v->pcmret)_ogg_free(v->pcmret);
  110406. }
  110407. if(b){
  110408. /* free header, header1, header2 */
  110409. if(b->header)_ogg_free(b->header);
  110410. if(b->header1)_ogg_free(b->header1);
  110411. if(b->header2)_ogg_free(b->header2);
  110412. _ogg_free(b);
  110413. }
  110414. memset(v,0,sizeof(*v));
  110415. }
  110416. }
  110417. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  110418. int i;
  110419. vorbis_info *vi=v->vi;
  110420. private_state *b=(private_state*)v->backend_state;
  110421. /* free header, header1, header2 */
  110422. if(b->header)_ogg_free(b->header);b->header=NULL;
  110423. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  110424. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  110425. /* Do we have enough storage space for the requested buffer? If not,
  110426. expand the PCM (and envelope) storage */
  110427. if(v->pcm_current+vals>=v->pcm_storage){
  110428. v->pcm_storage=v->pcm_current+vals*2;
  110429. for(i=0;i<vi->channels;i++){
  110430. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  110431. }
  110432. }
  110433. for(i=0;i<vi->channels;i++)
  110434. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  110435. return(v->pcmret);
  110436. }
  110437. static void _preextrapolate_helper(vorbis_dsp_state *v){
  110438. int i;
  110439. int order=32;
  110440. float *lpc=(float*)alloca(order*sizeof(*lpc));
  110441. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  110442. long j;
  110443. v->preextrapolate=1;
  110444. if(v->pcm_current-v->centerW>order*2){ /* safety */
  110445. for(i=0;i<v->vi->channels;i++){
  110446. /* need to run the extrapolation in reverse! */
  110447. for(j=0;j<v->pcm_current;j++)
  110448. work[j]=v->pcm[i][v->pcm_current-j-1];
  110449. /* prime as above */
  110450. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  110451. /* run the predictor filter */
  110452. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  110453. order,
  110454. work+v->pcm_current-v->centerW,
  110455. v->centerW);
  110456. for(j=0;j<v->pcm_current;j++)
  110457. v->pcm[i][v->pcm_current-j-1]=work[j];
  110458. }
  110459. }
  110460. }
  110461. /* call with val<=0 to set eof */
  110462. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  110463. vorbis_info *vi=v->vi;
  110464. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110465. if(vals<=0){
  110466. int order=32;
  110467. int i;
  110468. float *lpc=(float*) alloca(order*sizeof(*lpc));
  110469. /* if it wasn't done earlier (very short sample) */
  110470. if(!v->preextrapolate)
  110471. _preextrapolate_helper(v);
  110472. /* We're encoding the end of the stream. Just make sure we have
  110473. [at least] a few full blocks of zeroes at the end. */
  110474. /* actually, we don't want zeroes; that could drop a large
  110475. amplitude off a cliff, creating spread spectrum noise that will
  110476. suck to encode. Extrapolate for the sake of cleanliness. */
  110477. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  110478. v->eofflag=v->pcm_current;
  110479. v->pcm_current+=ci->blocksizes[1]*3;
  110480. for(i=0;i<vi->channels;i++){
  110481. if(v->eofflag>order*2){
  110482. /* extrapolate with LPC to fill in */
  110483. long n;
  110484. /* make a predictor filter */
  110485. n=v->eofflag;
  110486. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  110487. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  110488. /* run the predictor filter */
  110489. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  110490. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  110491. }else{
  110492. /* not enough data to extrapolate (unlikely to happen due to
  110493. guarding the overlap, but bulletproof in case that
  110494. assumtion goes away). zeroes will do. */
  110495. memset(v->pcm[i]+v->eofflag,0,
  110496. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  110497. }
  110498. }
  110499. }else{
  110500. if(v->pcm_current+vals>v->pcm_storage)
  110501. return(OV_EINVAL);
  110502. v->pcm_current+=vals;
  110503. /* we may want to reverse extrapolate the beginning of a stream
  110504. too... in case we're beginning on a cliff! */
  110505. /* clumsy, but simple. It only runs once, so simple is good. */
  110506. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  110507. _preextrapolate_helper(v);
  110508. }
  110509. return(0);
  110510. }
  110511. /* do the deltas, envelope shaping, pre-echo and determine the size of
  110512. the next block on which to continue analysis */
  110513. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  110514. int i;
  110515. vorbis_info *vi=v->vi;
  110516. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110517. private_state *b=(private_state*)v->backend_state;
  110518. vorbis_look_psy_global *g=b->psy_g_look;
  110519. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  110520. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  110521. /* check to see if we're started... */
  110522. if(!v->preextrapolate)return(0);
  110523. /* check to see if we're done... */
  110524. if(v->eofflag==-1)return(0);
  110525. /* By our invariant, we have lW, W and centerW set. Search for
  110526. the next boundary so we can determine nW (the next window size)
  110527. which lets us compute the shape of the current block's window */
  110528. /* we do an envelope search even on a single blocksize; we may still
  110529. be throwing more bits at impulses, and envelope search handles
  110530. marking impulses too. */
  110531. {
  110532. long bp=_ve_envelope_search(v);
  110533. if(bp==-1){
  110534. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  110535. full long block */
  110536. v->nW=0;
  110537. }else{
  110538. if(ci->blocksizes[0]==ci->blocksizes[1])
  110539. v->nW=0;
  110540. else
  110541. v->nW=bp;
  110542. }
  110543. }
  110544. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  110545. {
  110546. /* center of next block + next block maximum right side. */
  110547. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  110548. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  110549. although this check is
  110550. less strict that the
  110551. _ve_envelope_search,
  110552. the search is not run
  110553. if we only use one
  110554. block size */
  110555. }
  110556. /* fill in the block. Note that for a short window, lW and nW are *short*
  110557. regardless of actual settings in the stream */
  110558. _vorbis_block_ripcord(vb);
  110559. vb->lW=v->lW;
  110560. vb->W=v->W;
  110561. vb->nW=v->nW;
  110562. if(v->W){
  110563. if(!v->lW || !v->nW){
  110564. vbi->blocktype=BLOCKTYPE_TRANSITION;
  110565. /*fprintf(stderr,"-");*/
  110566. }else{
  110567. vbi->blocktype=BLOCKTYPE_LONG;
  110568. /*fprintf(stderr,"_");*/
  110569. }
  110570. }else{
  110571. if(_ve_envelope_mark(v)){
  110572. vbi->blocktype=BLOCKTYPE_IMPULSE;
  110573. /*fprintf(stderr,"|");*/
  110574. }else{
  110575. vbi->blocktype=BLOCKTYPE_PADDING;
  110576. /*fprintf(stderr,".");*/
  110577. }
  110578. }
  110579. vb->vd=v;
  110580. vb->sequence=v->sequence++;
  110581. vb->granulepos=v->granulepos;
  110582. vb->pcmend=ci->blocksizes[v->W];
  110583. /* copy the vectors; this uses the local storage in vb */
  110584. /* this tracks 'strongest peak' for later psychoacoustics */
  110585. /* moved to the global psy state; clean this mess up */
  110586. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  110587. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  110588. vbi->ampmax=g->ampmax;
  110589. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  110590. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  110591. for(i=0;i<vi->channels;i++){
  110592. vbi->pcmdelay[i]=
  110593. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  110594. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  110595. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  110596. /* before we added the delay
  110597. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  110598. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  110599. */
  110600. }
  110601. /* handle eof detection: eof==0 means that we've not yet received EOF
  110602. eof>0 marks the last 'real' sample in pcm[]
  110603. eof<0 'no more to do'; doesn't get here */
  110604. if(v->eofflag){
  110605. if(v->centerW>=v->eofflag){
  110606. v->eofflag=-1;
  110607. vb->eofflag=1;
  110608. return(1);
  110609. }
  110610. }
  110611. /* advance storage vectors and clean up */
  110612. {
  110613. int new_centerNext=ci->blocksizes[1]/2;
  110614. int movementW=centerNext-new_centerNext;
  110615. if(movementW>0){
  110616. _ve_envelope_shift(b->ve,movementW);
  110617. v->pcm_current-=movementW;
  110618. for(i=0;i<vi->channels;i++)
  110619. memmove(v->pcm[i],v->pcm[i]+movementW,
  110620. v->pcm_current*sizeof(*v->pcm[i]));
  110621. v->lW=v->W;
  110622. v->W=v->nW;
  110623. v->centerW=new_centerNext;
  110624. if(v->eofflag){
  110625. v->eofflag-=movementW;
  110626. if(v->eofflag<=0)v->eofflag=-1;
  110627. /* do not add padding to end of stream! */
  110628. if(v->centerW>=v->eofflag){
  110629. v->granulepos+=movementW-(v->centerW-v->eofflag);
  110630. }else{
  110631. v->granulepos+=movementW;
  110632. }
  110633. }else{
  110634. v->granulepos+=movementW;
  110635. }
  110636. }
  110637. }
  110638. /* done */
  110639. return(1);
  110640. }
  110641. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  110642. vorbis_info *vi=v->vi;
  110643. codec_setup_info *ci;
  110644. int hs;
  110645. if(!v->backend_state)return -1;
  110646. if(!vi)return -1;
  110647. ci=(codec_setup_info*) vi->codec_setup;
  110648. if(!ci)return -1;
  110649. hs=ci->halfrate_flag;
  110650. v->centerW=ci->blocksizes[1]>>(hs+1);
  110651. v->pcm_current=v->centerW>>hs;
  110652. v->pcm_returned=-1;
  110653. v->granulepos=-1;
  110654. v->sequence=-1;
  110655. v->eofflag=0;
  110656. ((private_state *)(v->backend_state))->sample_count=-1;
  110657. return(0);
  110658. }
  110659. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  110660. if(_vds_shared_init(v,vi,0)) return 1;
  110661. vorbis_synthesis_restart(v);
  110662. return 0;
  110663. }
  110664. /* Unlike in analysis, the window is only partially applied for each
  110665. block. The time domain envelope is not yet handled at the point of
  110666. calling (as it relies on the previous block). */
  110667. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  110668. vorbis_info *vi=v->vi;
  110669. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110670. private_state *b=(private_state*)v->backend_state;
  110671. int hs=ci->halfrate_flag;
  110672. int i,j;
  110673. if(!vb)return(OV_EINVAL);
  110674. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  110675. v->lW=v->W;
  110676. v->W=vb->W;
  110677. v->nW=-1;
  110678. if((v->sequence==-1)||
  110679. (v->sequence+1 != vb->sequence)){
  110680. v->granulepos=-1; /* out of sequence; lose count */
  110681. b->sample_count=-1;
  110682. }
  110683. v->sequence=vb->sequence;
  110684. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  110685. was called on block */
  110686. int n=ci->blocksizes[v->W]>>(hs+1);
  110687. int n0=ci->blocksizes[0]>>(hs+1);
  110688. int n1=ci->blocksizes[1]>>(hs+1);
  110689. int thisCenter;
  110690. int prevCenter;
  110691. v->glue_bits+=vb->glue_bits;
  110692. v->time_bits+=vb->time_bits;
  110693. v->floor_bits+=vb->floor_bits;
  110694. v->res_bits+=vb->res_bits;
  110695. if(v->centerW){
  110696. thisCenter=n1;
  110697. prevCenter=0;
  110698. }else{
  110699. thisCenter=0;
  110700. prevCenter=n1;
  110701. }
  110702. /* v->pcm is now used like a two-stage double buffer. We don't want
  110703. to have to constantly shift *or* adjust memory usage. Don't
  110704. accept a new block until the old is shifted out */
  110705. for(j=0;j<vi->channels;j++){
  110706. /* the overlap/add section */
  110707. if(v->lW){
  110708. if(v->W){
  110709. /* large/large */
  110710. float *w=_vorbis_window_get(b->window[1]-hs);
  110711. float *pcm=v->pcm[j]+prevCenter;
  110712. float *p=vb->pcm[j];
  110713. for(i=0;i<n1;i++)
  110714. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  110715. }else{
  110716. /* large/small */
  110717. float *w=_vorbis_window_get(b->window[0]-hs);
  110718. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  110719. float *p=vb->pcm[j];
  110720. for(i=0;i<n0;i++)
  110721. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  110722. }
  110723. }else{
  110724. if(v->W){
  110725. /* small/large */
  110726. float *w=_vorbis_window_get(b->window[0]-hs);
  110727. float *pcm=v->pcm[j]+prevCenter;
  110728. float *p=vb->pcm[j]+n1/2-n0/2;
  110729. for(i=0;i<n0;i++)
  110730. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  110731. for(;i<n1/2+n0/2;i++)
  110732. pcm[i]=p[i];
  110733. }else{
  110734. /* small/small */
  110735. float *w=_vorbis_window_get(b->window[0]-hs);
  110736. float *pcm=v->pcm[j]+prevCenter;
  110737. float *p=vb->pcm[j];
  110738. for(i=0;i<n0;i++)
  110739. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  110740. }
  110741. }
  110742. /* the copy section */
  110743. {
  110744. float *pcm=v->pcm[j]+thisCenter;
  110745. float *p=vb->pcm[j]+n;
  110746. for(i=0;i<n;i++)
  110747. pcm[i]=p[i];
  110748. }
  110749. }
  110750. if(v->centerW)
  110751. v->centerW=0;
  110752. else
  110753. v->centerW=n1;
  110754. /* deal with initial packet state; we do this using the explicit
  110755. pcm_returned==-1 flag otherwise we're sensitive to first block
  110756. being short or long */
  110757. if(v->pcm_returned==-1){
  110758. v->pcm_returned=thisCenter;
  110759. v->pcm_current=thisCenter;
  110760. }else{
  110761. v->pcm_returned=prevCenter;
  110762. v->pcm_current=prevCenter+
  110763. ((ci->blocksizes[v->lW]/4+
  110764. ci->blocksizes[v->W]/4)>>hs);
  110765. }
  110766. }
  110767. /* track the frame number... This is for convenience, but also
  110768. making sure our last packet doesn't end with added padding. If
  110769. the last packet is partial, the number of samples we'll have to
  110770. return will be past the vb->granulepos.
  110771. This is not foolproof! It will be confused if we begin
  110772. decoding at the last page after a seek or hole. In that case,
  110773. we don't have a starting point to judge where the last frame
  110774. is. For this reason, vorbisfile will always try to make sure
  110775. it reads the last two marked pages in proper sequence */
  110776. if(b->sample_count==-1){
  110777. b->sample_count=0;
  110778. }else{
  110779. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  110780. }
  110781. if(v->granulepos==-1){
  110782. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  110783. v->granulepos=vb->granulepos;
  110784. /* is this a short page? */
  110785. if(b->sample_count>v->granulepos){
  110786. /* corner case; if this is both the first and last audio page,
  110787. then spec says the end is cut, not beginning */
  110788. if(vb->eofflag){
  110789. /* trim the end */
  110790. /* no preceeding granulepos; assume we started at zero (we'd
  110791. have to in a short single-page stream) */
  110792. /* granulepos could be -1 due to a seek, but that would result
  110793. in a long count, not short count */
  110794. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  110795. }else{
  110796. /* trim the beginning */
  110797. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  110798. if(v->pcm_returned>v->pcm_current)
  110799. v->pcm_returned=v->pcm_current;
  110800. }
  110801. }
  110802. }
  110803. }else{
  110804. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  110805. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  110806. if(v->granulepos>vb->granulepos){
  110807. long extra=v->granulepos-vb->granulepos;
  110808. if(extra)
  110809. if(vb->eofflag){
  110810. /* partial last frame. Strip the extra samples off */
  110811. v->pcm_current-=extra>>hs;
  110812. } /* else {Shouldn't happen *unless* the bitstream is out of
  110813. spec. Either way, believe the bitstream } */
  110814. } /* else {Shouldn't happen *unless* the bitstream is out of
  110815. spec. Either way, believe the bitstream } */
  110816. v->granulepos=vb->granulepos;
  110817. }
  110818. }
  110819. /* Update, cleanup */
  110820. if(vb->eofflag)v->eofflag=1;
  110821. return(0);
  110822. }
  110823. /* pcm==NULL indicates we just want the pending samples, no more */
  110824. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  110825. vorbis_info *vi=v->vi;
  110826. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  110827. if(pcm){
  110828. int i;
  110829. for(i=0;i<vi->channels;i++)
  110830. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  110831. *pcm=v->pcmret;
  110832. }
  110833. return(v->pcm_current-v->pcm_returned);
  110834. }
  110835. return(0);
  110836. }
  110837. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  110838. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  110839. v->pcm_returned+=n;
  110840. return(0);
  110841. }
  110842. /* intended for use with a specific vorbisfile feature; we want access
  110843. to the [usually synthetic/postextrapolated] buffer and lapping at
  110844. the end of a decode cycle, specifically, a half-short-block worth.
  110845. This funtion works like pcmout above, except it will also expose
  110846. this implicit buffer data not normally decoded. */
  110847. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  110848. vorbis_info *vi=v->vi;
  110849. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  110850. int hs=ci->halfrate_flag;
  110851. int n=ci->blocksizes[v->W]>>(hs+1);
  110852. int n0=ci->blocksizes[0]>>(hs+1);
  110853. int n1=ci->blocksizes[1]>>(hs+1);
  110854. int i,j;
  110855. if(v->pcm_returned<0)return 0;
  110856. /* our returned data ends at pcm_returned; because the synthesis pcm
  110857. buffer is a two-fragment ring, that means our data block may be
  110858. fragmented by buffering, wrapping or a short block not filling
  110859. out a buffer. To simplify things, we unfragment if it's at all
  110860. possibly needed. Otherwise, we'd need to call lapout more than
  110861. once as well as hold additional dsp state. Opt for
  110862. simplicity. */
  110863. /* centerW was advanced by blockin; it would be the center of the
  110864. *next* block */
  110865. if(v->centerW==n1){
  110866. /* the data buffer wraps; swap the halves */
  110867. /* slow, sure, small */
  110868. for(j=0;j<vi->channels;j++){
  110869. float *p=v->pcm[j];
  110870. for(i=0;i<n1;i++){
  110871. float temp=p[i];
  110872. p[i]=p[i+n1];
  110873. p[i+n1]=temp;
  110874. }
  110875. }
  110876. v->pcm_current-=n1;
  110877. v->pcm_returned-=n1;
  110878. v->centerW=0;
  110879. }
  110880. /* solidify buffer into contiguous space */
  110881. if((v->lW^v->W)==1){
  110882. /* long/short or short/long */
  110883. for(j=0;j<vi->channels;j++){
  110884. float *s=v->pcm[j];
  110885. float *d=v->pcm[j]+(n1-n0)/2;
  110886. for(i=(n1+n0)/2-1;i>=0;--i)
  110887. d[i]=s[i];
  110888. }
  110889. v->pcm_returned+=(n1-n0)/2;
  110890. v->pcm_current+=(n1-n0)/2;
  110891. }else{
  110892. if(v->lW==0){
  110893. /* short/short */
  110894. for(j=0;j<vi->channels;j++){
  110895. float *s=v->pcm[j];
  110896. float *d=v->pcm[j]+n1-n0;
  110897. for(i=n0-1;i>=0;--i)
  110898. d[i]=s[i];
  110899. }
  110900. v->pcm_returned+=n1-n0;
  110901. v->pcm_current+=n1-n0;
  110902. }
  110903. }
  110904. if(pcm){
  110905. int i;
  110906. for(i=0;i<vi->channels;i++)
  110907. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  110908. *pcm=v->pcmret;
  110909. }
  110910. return(n1+n-v->pcm_returned);
  110911. }
  110912. float *vorbis_window(vorbis_dsp_state *v,int W){
  110913. vorbis_info *vi=v->vi;
  110914. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  110915. int hs=ci->halfrate_flag;
  110916. private_state *b=(private_state*)v->backend_state;
  110917. if(b->window[W]-1<0)return NULL;
  110918. return _vorbis_window_get(b->window[W]-hs);
  110919. }
  110920. #endif
  110921. /*** End of inlined file: block.c ***/
  110922. /*** Start of inlined file: codebook.c ***/
  110923. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110924. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110925. // tasks..
  110926. #if JUCE_MSVC
  110927. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110928. #endif
  110929. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110930. #if JUCE_USE_OGGVORBIS
  110931. #include <stdlib.h>
  110932. #include <string.h>
  110933. #include <math.h>
  110934. /* packs the given codebook into the bitstream **************************/
  110935. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  110936. long i,j;
  110937. int ordered=0;
  110938. /* first the basic parameters */
  110939. oggpack_write(opb,0x564342,24);
  110940. oggpack_write(opb,c->dim,16);
  110941. oggpack_write(opb,c->entries,24);
  110942. /* pack the codewords. There are two packings; length ordered and
  110943. length random. Decide between the two now. */
  110944. for(i=1;i<c->entries;i++)
  110945. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  110946. if(i==c->entries)ordered=1;
  110947. if(ordered){
  110948. /* length ordered. We only need to say how many codewords of
  110949. each length. The actual codewords are generated
  110950. deterministically */
  110951. long count=0;
  110952. oggpack_write(opb,1,1); /* ordered */
  110953. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  110954. for(i=1;i<c->entries;i++){
  110955. long thisx=c->lengthlist[i];
  110956. long last=c->lengthlist[i-1];
  110957. if(thisx>last){
  110958. for(j=last;j<thisx;j++){
  110959. oggpack_write(opb,i-count,_ilog(c->entries-count));
  110960. count=i;
  110961. }
  110962. }
  110963. }
  110964. oggpack_write(opb,i-count,_ilog(c->entries-count));
  110965. }else{
  110966. /* length random. Again, we don't code the codeword itself, just
  110967. the length. This time, though, we have to encode each length */
  110968. oggpack_write(opb,0,1); /* unordered */
  110969. /* algortihmic mapping has use for 'unused entries', which we tag
  110970. here. The algorithmic mapping happens as usual, but the unused
  110971. entry has no codeword. */
  110972. for(i=0;i<c->entries;i++)
  110973. if(c->lengthlist[i]==0)break;
  110974. if(i==c->entries){
  110975. oggpack_write(opb,0,1); /* no unused entries */
  110976. for(i=0;i<c->entries;i++)
  110977. oggpack_write(opb,c->lengthlist[i]-1,5);
  110978. }else{
  110979. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  110980. for(i=0;i<c->entries;i++){
  110981. if(c->lengthlist[i]==0){
  110982. oggpack_write(opb,0,1);
  110983. }else{
  110984. oggpack_write(opb,1,1);
  110985. oggpack_write(opb,c->lengthlist[i]-1,5);
  110986. }
  110987. }
  110988. }
  110989. }
  110990. /* is the entry number the desired return value, or do we have a
  110991. mapping? If we have a mapping, what type? */
  110992. oggpack_write(opb,c->maptype,4);
  110993. switch(c->maptype){
  110994. case 0:
  110995. /* no mapping */
  110996. break;
  110997. case 1:case 2:
  110998. /* implicitly populated value mapping */
  110999. /* explicitly populated value mapping */
  111000. if(!c->quantlist){
  111001. /* no quantlist? error */
  111002. return(-1);
  111003. }
  111004. /* values that define the dequantization */
  111005. oggpack_write(opb,c->q_min,32);
  111006. oggpack_write(opb,c->q_delta,32);
  111007. oggpack_write(opb,c->q_quant-1,4);
  111008. oggpack_write(opb,c->q_sequencep,1);
  111009. {
  111010. int quantvals;
  111011. switch(c->maptype){
  111012. case 1:
  111013. /* a single column of (c->entries/c->dim) quantized values for
  111014. building a full value list algorithmically (square lattice) */
  111015. quantvals=_book_maptype1_quantvals(c);
  111016. break;
  111017. case 2:
  111018. /* every value (c->entries*c->dim total) specified explicitly */
  111019. quantvals=c->entries*c->dim;
  111020. break;
  111021. default: /* NOT_REACHABLE */
  111022. quantvals=-1;
  111023. }
  111024. /* quantized values */
  111025. for(i=0;i<quantvals;i++)
  111026. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  111027. }
  111028. break;
  111029. default:
  111030. /* error case; we don't have any other map types now */
  111031. return(-1);
  111032. }
  111033. return(0);
  111034. }
  111035. /* unpacks a codebook from the packet buffer into the codebook struct,
  111036. readies the codebook auxiliary structures for decode *************/
  111037. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  111038. long i,j;
  111039. memset(s,0,sizeof(*s));
  111040. s->allocedp=1;
  111041. /* make sure alignment is correct */
  111042. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  111043. /* first the basic parameters */
  111044. s->dim=oggpack_read(opb,16);
  111045. s->entries=oggpack_read(opb,24);
  111046. if(s->entries==-1)goto _eofout;
  111047. /* codeword ordering.... length ordered or unordered? */
  111048. switch((int)oggpack_read(opb,1)){
  111049. case 0:
  111050. /* unordered */
  111051. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  111052. /* allocated but unused entries? */
  111053. if(oggpack_read(opb,1)){
  111054. /* yes, unused entries */
  111055. for(i=0;i<s->entries;i++){
  111056. if(oggpack_read(opb,1)){
  111057. long num=oggpack_read(opb,5);
  111058. if(num==-1)goto _eofout;
  111059. s->lengthlist[i]=num+1;
  111060. }else
  111061. s->lengthlist[i]=0;
  111062. }
  111063. }else{
  111064. /* all entries used; no tagging */
  111065. for(i=0;i<s->entries;i++){
  111066. long num=oggpack_read(opb,5);
  111067. if(num==-1)goto _eofout;
  111068. s->lengthlist[i]=num+1;
  111069. }
  111070. }
  111071. break;
  111072. case 1:
  111073. /* ordered */
  111074. {
  111075. long length=oggpack_read(opb,5)+1;
  111076. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  111077. for(i=0;i<s->entries;){
  111078. long num=oggpack_read(opb,_ilog(s->entries-i));
  111079. if(num==-1)goto _eofout;
  111080. for(j=0;j<num && i<s->entries;j++,i++)
  111081. s->lengthlist[i]=length;
  111082. length++;
  111083. }
  111084. }
  111085. break;
  111086. default:
  111087. /* EOF */
  111088. return(-1);
  111089. }
  111090. /* Do we have a mapping to unpack? */
  111091. switch((s->maptype=oggpack_read(opb,4))){
  111092. case 0:
  111093. /* no mapping */
  111094. break;
  111095. case 1: case 2:
  111096. /* implicitly populated value mapping */
  111097. /* explicitly populated value mapping */
  111098. s->q_min=oggpack_read(opb,32);
  111099. s->q_delta=oggpack_read(opb,32);
  111100. s->q_quant=oggpack_read(opb,4)+1;
  111101. s->q_sequencep=oggpack_read(opb,1);
  111102. {
  111103. int quantvals=0;
  111104. switch(s->maptype){
  111105. case 1:
  111106. quantvals=_book_maptype1_quantvals(s);
  111107. break;
  111108. case 2:
  111109. quantvals=s->entries*s->dim;
  111110. break;
  111111. }
  111112. /* quantized values */
  111113. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  111114. for(i=0;i<quantvals;i++)
  111115. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  111116. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  111117. }
  111118. break;
  111119. default:
  111120. goto _errout;
  111121. }
  111122. /* all set */
  111123. return(0);
  111124. _errout:
  111125. _eofout:
  111126. vorbis_staticbook_clear(s);
  111127. return(-1);
  111128. }
  111129. /* returns the number of bits ************************************************/
  111130. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  111131. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  111132. return(book->c->lengthlist[a]);
  111133. }
  111134. /* One the encode side, our vector writers are each designed for a
  111135. specific purpose, and the encoder is not flexible without modification:
  111136. The LSP vector coder uses a single stage nearest-match with no
  111137. interleave, so no step and no error return. This is specced by floor0
  111138. and doesn't change.
  111139. Residue0 encoding interleaves, uses multiple stages, and each stage
  111140. peels of a specific amount of resolution from a lattice (thus we want
  111141. to match by threshold, not nearest match). Residue doesn't *have* to
  111142. be encoded that way, but to change it, one will need to add more
  111143. infrastructure on the encode side (decode side is specced and simpler) */
  111144. /* floor0 LSP (single stage, non interleaved, nearest match) */
  111145. /* returns entry number and *modifies a* to the quantization value *****/
  111146. int vorbis_book_errorv(codebook *book,float *a){
  111147. int dim=book->dim,k;
  111148. int best=_best(book,a,1);
  111149. for(k=0;k<dim;k++)
  111150. a[k]=(book->valuelist+best*dim)[k];
  111151. return(best);
  111152. }
  111153. /* returns the number of bits and *modifies a* to the quantization value *****/
  111154. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  111155. int k,dim=book->dim;
  111156. for(k=0;k<dim;k++)
  111157. a[k]=(book->valuelist+best*dim)[k];
  111158. return(vorbis_book_encode(book,best,b));
  111159. }
  111160. /* the 'eliminate the decode tree' optimization actually requires the
  111161. codewords to be MSb first, not LSb. This is an annoying inelegancy
  111162. (and one of the first places where carefully thought out design
  111163. turned out to be wrong; Vorbis II and future Ogg codecs should go
  111164. to an MSb bitpacker), but not actually the huge hit it appears to
  111165. be. The first-stage decode table catches most words so that
  111166. bitreverse is not in the main execution path. */
  111167. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  111168. int read=book->dec_maxlength;
  111169. long lo,hi;
  111170. long lok = oggpack_look(b,book->dec_firsttablen);
  111171. if (lok >= 0) {
  111172. long entry = book->dec_firsttable[lok];
  111173. if(entry&0x80000000UL){
  111174. lo=(entry>>15)&0x7fff;
  111175. hi=book->used_entries-(entry&0x7fff);
  111176. }else{
  111177. oggpack_adv(b, book->dec_codelengths[entry-1]);
  111178. return(entry-1);
  111179. }
  111180. }else{
  111181. lo=0;
  111182. hi=book->used_entries;
  111183. }
  111184. lok = oggpack_look(b, read);
  111185. while(lok<0 && read>1)
  111186. lok = oggpack_look(b, --read);
  111187. if(lok<0)return -1;
  111188. /* bisect search for the codeword in the ordered list */
  111189. {
  111190. ogg_uint32_t testword=ogg_bitreverse((ogg_uint32_t)lok);
  111191. while(hi-lo>1){
  111192. long p=(hi-lo)>>1;
  111193. long test=book->codelist[lo+p]>testword;
  111194. lo+=p&(test-1);
  111195. hi-=p&(-test);
  111196. }
  111197. if(book->dec_codelengths[lo]<=read){
  111198. oggpack_adv(b, book->dec_codelengths[lo]);
  111199. return(lo);
  111200. }
  111201. }
  111202. oggpack_adv(b, read);
  111203. return(-1);
  111204. }
  111205. /* Decode side is specced and easier, because we don't need to find
  111206. matches using different criteria; we simply read and map. There are
  111207. two things we need to do 'depending':
  111208. We may need to support interleave. We don't really, but it's
  111209. convenient to do it here rather than rebuild the vector later.
  111210. Cascades may be additive or multiplicitive; this is not inherent in
  111211. the codebook, but set in the code using the codebook. Like
  111212. interleaving, it's easiest to do it here.
  111213. addmul==0 -> declarative (set the value)
  111214. addmul==1 -> additive
  111215. addmul==2 -> multiplicitive */
  111216. /* returns the [original, not compacted] entry number or -1 on eof *********/
  111217. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  111218. long packed_entry=decode_packed_entry_number(book,b);
  111219. if(packed_entry>=0)
  111220. return(book->dec_index[packed_entry]);
  111221. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  111222. return(packed_entry);
  111223. }
  111224. /* returns 0 on OK or -1 on eof *************************************/
  111225. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  111226. int step=n/book->dim;
  111227. long *entry = (long*)alloca(sizeof(*entry)*step);
  111228. float **t = (float**)alloca(sizeof(*t)*step);
  111229. int i,j,o;
  111230. for (i = 0; i < step; i++) {
  111231. entry[i]=decode_packed_entry_number(book,b);
  111232. if(entry[i]==-1)return(-1);
  111233. t[i] = book->valuelist+entry[i]*book->dim;
  111234. }
  111235. for(i=0,o=0;i<book->dim;i++,o+=step)
  111236. for (j=0;j<step;j++)
  111237. a[o+j]+=t[j][i];
  111238. return(0);
  111239. }
  111240. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  111241. int i,j,entry;
  111242. float *t;
  111243. if(book->dim>8){
  111244. for(i=0;i<n;){
  111245. entry = decode_packed_entry_number(book,b);
  111246. if(entry==-1)return(-1);
  111247. t = book->valuelist+entry*book->dim;
  111248. for (j=0;j<book->dim;)
  111249. a[i++]+=t[j++];
  111250. }
  111251. }else{
  111252. for(i=0;i<n;){
  111253. entry = decode_packed_entry_number(book,b);
  111254. if(entry==-1)return(-1);
  111255. t = book->valuelist+entry*book->dim;
  111256. j=0;
  111257. switch((int)book->dim){
  111258. case 8:
  111259. a[i++]+=t[j++];
  111260. case 7:
  111261. a[i++]+=t[j++];
  111262. case 6:
  111263. a[i++]+=t[j++];
  111264. case 5:
  111265. a[i++]+=t[j++];
  111266. case 4:
  111267. a[i++]+=t[j++];
  111268. case 3:
  111269. a[i++]+=t[j++];
  111270. case 2:
  111271. a[i++]+=t[j++];
  111272. case 1:
  111273. a[i++]+=t[j++];
  111274. case 0:
  111275. break;
  111276. }
  111277. }
  111278. }
  111279. return(0);
  111280. }
  111281. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  111282. int i,j,entry;
  111283. float *t;
  111284. for(i=0;i<n;){
  111285. entry = decode_packed_entry_number(book,b);
  111286. if(entry==-1)return(-1);
  111287. t = book->valuelist+entry*book->dim;
  111288. for (j=0;j<book->dim;)
  111289. a[i++]=t[j++];
  111290. }
  111291. return(0);
  111292. }
  111293. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  111294. oggpack_buffer *b,int n){
  111295. long i,j,entry;
  111296. int chptr=0;
  111297. for(i=offset/ch;i<(offset+n)/ch;){
  111298. entry = decode_packed_entry_number(book,b);
  111299. if(entry==-1)return(-1);
  111300. {
  111301. const float *t = book->valuelist+entry*book->dim;
  111302. for (j=0;j<book->dim;j++){
  111303. a[chptr++][i]+=t[j];
  111304. if(chptr==ch){
  111305. chptr=0;
  111306. i++;
  111307. }
  111308. }
  111309. }
  111310. }
  111311. return(0);
  111312. }
  111313. #ifdef _V_SELFTEST
  111314. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  111315. number of vectors through (keeping track of the quantized values),
  111316. and decode using the unpacked book. quantized version of in should
  111317. exactly equal out */
  111318. #include <stdio.h>
  111319. #include "vorbis/book/lsp20_0.vqh"
  111320. #include "vorbis/book/res0a_13.vqh"
  111321. #define TESTSIZE 40
  111322. float test1[TESTSIZE]={
  111323. 0.105939f,
  111324. 0.215373f,
  111325. 0.429117f,
  111326. 0.587974f,
  111327. 0.181173f,
  111328. 0.296583f,
  111329. 0.515707f,
  111330. 0.715261f,
  111331. 0.162327f,
  111332. 0.263834f,
  111333. 0.342876f,
  111334. 0.406025f,
  111335. 0.103571f,
  111336. 0.223561f,
  111337. 0.368513f,
  111338. 0.540313f,
  111339. 0.136672f,
  111340. 0.395882f,
  111341. 0.587183f,
  111342. 0.652476f,
  111343. 0.114338f,
  111344. 0.417300f,
  111345. 0.525486f,
  111346. 0.698679f,
  111347. 0.147492f,
  111348. 0.324481f,
  111349. 0.643089f,
  111350. 0.757582f,
  111351. 0.139556f,
  111352. 0.215795f,
  111353. 0.324559f,
  111354. 0.399387f,
  111355. 0.120236f,
  111356. 0.267420f,
  111357. 0.446940f,
  111358. 0.608760f,
  111359. 0.115587f,
  111360. 0.287234f,
  111361. 0.571081f,
  111362. 0.708603f,
  111363. };
  111364. float test3[TESTSIZE]={
  111365. 0,1,-2,3,4,-5,6,7,8,9,
  111366. 8,-2,7,-1,4,6,8,3,1,-9,
  111367. 10,11,12,13,14,15,26,17,18,19,
  111368. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  111369. static_codebook *testlist[]={&_vq_book_lsp20_0,
  111370. &_vq_book_res0a_13,NULL};
  111371. float *testvec[]={test1,test3};
  111372. int main(){
  111373. oggpack_buffer write;
  111374. oggpack_buffer read;
  111375. long ptr=0,i;
  111376. oggpack_writeinit(&write);
  111377. fprintf(stderr,"Testing codebook abstraction...:\n");
  111378. while(testlist[ptr]){
  111379. codebook c;
  111380. static_codebook s;
  111381. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  111382. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  111383. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  111384. memset(iv,0,sizeof(*iv)*TESTSIZE);
  111385. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  111386. /* pack the codebook, write the testvector */
  111387. oggpack_reset(&write);
  111388. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  111389. we can write */
  111390. vorbis_staticbook_pack(testlist[ptr],&write);
  111391. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  111392. for(i=0;i<TESTSIZE;i+=c.dim){
  111393. int best=_best(&c,qv+i,1);
  111394. vorbis_book_encodev(&c,best,qv+i,&write);
  111395. }
  111396. vorbis_book_clear(&c);
  111397. fprintf(stderr,"OK.\n");
  111398. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  111399. /* transfer the write data to a read buffer and unpack/read */
  111400. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  111401. if(vorbis_staticbook_unpack(&read,&s)){
  111402. fprintf(stderr,"Error unpacking codebook.\n");
  111403. exit(1);
  111404. }
  111405. if(vorbis_book_init_decode(&c,&s)){
  111406. fprintf(stderr,"Error initializing codebook.\n");
  111407. exit(1);
  111408. }
  111409. for(i=0;i<TESTSIZE;i+=c.dim)
  111410. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  111411. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  111412. exit(1);
  111413. }
  111414. for(i=0;i<TESTSIZE;i++)
  111415. if(fabs(qv[i]-iv[i])>.000001){
  111416. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  111417. iv[i],qv[i],i);
  111418. exit(1);
  111419. }
  111420. fprintf(stderr,"OK\n");
  111421. ptr++;
  111422. }
  111423. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  111424. exit(0);
  111425. }
  111426. #endif
  111427. #endif
  111428. /*** End of inlined file: codebook.c ***/
  111429. /*** Start of inlined file: envelope.c ***/
  111430. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111431. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111432. // tasks..
  111433. #if JUCE_MSVC
  111434. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111435. #endif
  111436. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111437. #if JUCE_USE_OGGVORBIS
  111438. #include <stdlib.h>
  111439. #include <string.h>
  111440. #include <stdio.h>
  111441. #include <math.h>
  111442. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  111443. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111444. vorbis_info_psy_global *gi=&ci->psy_g_param;
  111445. int ch=vi->channels;
  111446. int i,j;
  111447. int n=e->winlength=128;
  111448. e->searchstep=64; /* not random */
  111449. e->minenergy=gi->preecho_minenergy;
  111450. e->ch=ch;
  111451. e->storage=128;
  111452. e->cursor=ci->blocksizes[1]/2;
  111453. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  111454. mdct_init(&e->mdct,n);
  111455. for(i=0;i<n;i++){
  111456. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  111457. e->mdct_win[i]*=e->mdct_win[i];
  111458. }
  111459. /* magic follows */
  111460. e->band[0].begin=2; e->band[0].end=4;
  111461. e->band[1].begin=4; e->band[1].end=5;
  111462. e->band[2].begin=6; e->band[2].end=6;
  111463. e->band[3].begin=9; e->band[3].end=8;
  111464. e->band[4].begin=13; e->band[4].end=8;
  111465. e->band[5].begin=17; e->band[5].end=8;
  111466. e->band[6].begin=22; e->band[6].end=8;
  111467. for(j=0;j<VE_BANDS;j++){
  111468. n=e->band[j].end;
  111469. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  111470. for(i=0;i<n;i++){
  111471. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  111472. e->band[j].total+=e->band[j].window[i];
  111473. }
  111474. e->band[j].total=1./e->band[j].total;
  111475. }
  111476. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  111477. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  111478. }
  111479. void _ve_envelope_clear(envelope_lookup *e){
  111480. int i;
  111481. mdct_clear(&e->mdct);
  111482. for(i=0;i<VE_BANDS;i++)
  111483. _ogg_free(e->band[i].window);
  111484. _ogg_free(e->mdct_win);
  111485. _ogg_free(e->filter);
  111486. _ogg_free(e->mark);
  111487. memset(e,0,sizeof(*e));
  111488. }
  111489. /* fairly straight threshhold-by-band based until we find something
  111490. that works better and isn't patented. */
  111491. static int _ve_amp(envelope_lookup *ve,
  111492. vorbis_info_psy_global *gi,
  111493. float *data,
  111494. envelope_band *bands,
  111495. envelope_filter_state *filters,
  111496. long pos){
  111497. long n=ve->winlength;
  111498. int ret=0;
  111499. long i,j;
  111500. float decay;
  111501. /* we want to have a 'minimum bar' for energy, else we're just
  111502. basing blocks on quantization noise that outweighs the signal
  111503. itself (for low power signals) */
  111504. float minV=ve->minenergy;
  111505. float *vec=(float*) alloca(n*sizeof(*vec));
  111506. /* stretch is used to gradually lengthen the number of windows
  111507. considered prevoius-to-potential-trigger */
  111508. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  111509. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  111510. if(penalty<0.f)penalty=0.f;
  111511. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  111512. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  111513. totalshift+pos*ve->searchstep);*/
  111514. /* window and transform */
  111515. for(i=0;i<n;i++)
  111516. vec[i]=data[i]*ve->mdct_win[i];
  111517. mdct_forward(&ve->mdct,vec,vec);
  111518. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  111519. /* near-DC spreading function; this has nothing to do with
  111520. psychoacoustics, just sidelobe leakage and window size */
  111521. {
  111522. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  111523. int ptr=filters->nearptr;
  111524. /* the accumulation is regularly refreshed from scratch to avoid
  111525. floating point creep */
  111526. if(ptr==0){
  111527. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  111528. filters->nearDC_partialacc=temp;
  111529. }else{
  111530. decay=filters->nearDC_acc+=temp;
  111531. filters->nearDC_partialacc+=temp;
  111532. }
  111533. filters->nearDC_acc-=filters->nearDC[ptr];
  111534. filters->nearDC[ptr]=temp;
  111535. decay*=(1./(VE_NEARDC+1));
  111536. filters->nearptr++;
  111537. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  111538. decay=todB(&decay)*.5-15.f;
  111539. }
  111540. /* perform spreading and limiting, also smooth the spectrum. yes,
  111541. the MDCT results in all real coefficients, but it still *behaves*
  111542. like real/imaginary pairs */
  111543. for(i=0;i<n/2;i+=2){
  111544. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  111545. val=todB(&val)*.5f;
  111546. if(val<decay)val=decay;
  111547. if(val<minV)val=minV;
  111548. vec[i>>1]=val;
  111549. decay-=8.;
  111550. }
  111551. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  111552. /* perform preecho/postecho triggering by band */
  111553. for(j=0;j<VE_BANDS;j++){
  111554. float acc=0.;
  111555. float valmax,valmin;
  111556. /* accumulate amplitude */
  111557. for(i=0;i<bands[j].end;i++)
  111558. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  111559. acc*=bands[j].total;
  111560. /* convert amplitude to delta */
  111561. {
  111562. int p,thisx=filters[j].ampptr;
  111563. float postmax,postmin,premax=-99999.f,premin=99999.f;
  111564. p=thisx;
  111565. p--;
  111566. if(p<0)p+=VE_AMP;
  111567. postmax=max(acc,filters[j].ampbuf[p]);
  111568. postmin=min(acc,filters[j].ampbuf[p]);
  111569. for(i=0;i<stretch;i++){
  111570. p--;
  111571. if(p<0)p+=VE_AMP;
  111572. premax=max(premax,filters[j].ampbuf[p]);
  111573. premin=min(premin,filters[j].ampbuf[p]);
  111574. }
  111575. valmin=postmin-premin;
  111576. valmax=postmax-premax;
  111577. /*filters[j].markers[pos]=valmax;*/
  111578. filters[j].ampbuf[thisx]=acc;
  111579. filters[j].ampptr++;
  111580. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  111581. }
  111582. /* look at min/max, decide trigger */
  111583. if(valmax>gi->preecho_thresh[j]+penalty){
  111584. ret|=1;
  111585. ret|=4;
  111586. }
  111587. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  111588. }
  111589. return(ret);
  111590. }
  111591. #if 0
  111592. static int seq=0;
  111593. static ogg_int64_t totalshift=-1024;
  111594. #endif
  111595. long _ve_envelope_search(vorbis_dsp_state *v){
  111596. vorbis_info *vi=v->vi;
  111597. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  111598. vorbis_info_psy_global *gi=&ci->psy_g_param;
  111599. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  111600. long i,j;
  111601. int first=ve->current/ve->searchstep;
  111602. int last=v->pcm_current/ve->searchstep-VE_WIN;
  111603. if(first<0)first=0;
  111604. /* make sure we have enough storage to match the PCM */
  111605. if(last+VE_WIN+VE_POST>ve->storage){
  111606. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  111607. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  111608. }
  111609. for(j=first;j<last;j++){
  111610. int ret=0;
  111611. ve->stretch++;
  111612. if(ve->stretch>VE_MAXSTRETCH*2)
  111613. ve->stretch=VE_MAXSTRETCH*2;
  111614. for(i=0;i<ve->ch;i++){
  111615. float *pcm=v->pcm[i]+ve->searchstep*(j);
  111616. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  111617. }
  111618. ve->mark[j+VE_POST]=0;
  111619. if(ret&1){
  111620. ve->mark[j]=1;
  111621. ve->mark[j+1]=1;
  111622. }
  111623. if(ret&2){
  111624. ve->mark[j]=1;
  111625. if(j>0)ve->mark[j-1]=1;
  111626. }
  111627. if(ret&4)ve->stretch=-1;
  111628. }
  111629. ve->current=last*ve->searchstep;
  111630. {
  111631. long centerW=v->centerW;
  111632. long testW=
  111633. centerW+
  111634. ci->blocksizes[v->W]/4+
  111635. ci->blocksizes[1]/2+
  111636. ci->blocksizes[0]/4;
  111637. j=ve->cursor;
  111638. while(j<ve->current-(ve->searchstep)){/* account for postecho
  111639. working back one window */
  111640. if(j>=testW)return(1);
  111641. ve->cursor=j;
  111642. if(ve->mark[j/ve->searchstep]){
  111643. if(j>centerW){
  111644. #if 0
  111645. if(j>ve->curmark){
  111646. float *marker=alloca(v->pcm_current*sizeof(*marker));
  111647. int l,m;
  111648. memset(marker,0,sizeof(*marker)*v->pcm_current);
  111649. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  111650. seq,
  111651. (totalshift+ve->cursor)/44100.,
  111652. (totalshift+j)/44100.);
  111653. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  111654. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  111655. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  111656. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  111657. for(m=0;m<VE_BANDS;m++){
  111658. char buf[80];
  111659. sprintf(buf,"delL%d",m);
  111660. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  111661. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  111662. }
  111663. for(m=0;m<VE_BANDS;m++){
  111664. char buf[80];
  111665. sprintf(buf,"delR%d",m);
  111666. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  111667. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  111668. }
  111669. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  111670. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  111671. seq++;
  111672. }
  111673. #endif
  111674. ve->curmark=j;
  111675. if(j>=testW)return(1);
  111676. return(0);
  111677. }
  111678. }
  111679. j+=ve->searchstep;
  111680. }
  111681. }
  111682. return(-1);
  111683. }
  111684. int _ve_envelope_mark(vorbis_dsp_state *v){
  111685. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  111686. vorbis_info *vi=v->vi;
  111687. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111688. long centerW=v->centerW;
  111689. long beginW=centerW-ci->blocksizes[v->W]/4;
  111690. long endW=centerW+ci->blocksizes[v->W]/4;
  111691. if(v->W){
  111692. beginW-=ci->blocksizes[v->lW]/4;
  111693. endW+=ci->blocksizes[v->nW]/4;
  111694. }else{
  111695. beginW-=ci->blocksizes[0]/4;
  111696. endW+=ci->blocksizes[0]/4;
  111697. }
  111698. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  111699. {
  111700. long first=beginW/ve->searchstep;
  111701. long last=endW/ve->searchstep;
  111702. long i;
  111703. for(i=first;i<last;i++)
  111704. if(ve->mark[i])return(1);
  111705. }
  111706. return(0);
  111707. }
  111708. void _ve_envelope_shift(envelope_lookup *e,long shift){
  111709. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  111710. ahead of ve->current */
  111711. int smallshift=shift/e->searchstep;
  111712. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  111713. #if 0
  111714. for(i=0;i<VE_BANDS*e->ch;i++)
  111715. memmove(e->filter[i].markers,
  111716. e->filter[i].markers+smallshift,
  111717. (1024-smallshift)*sizeof(*(*e->filter).markers));
  111718. totalshift+=shift;
  111719. #endif
  111720. e->current-=shift;
  111721. if(e->curmark>=0)
  111722. e->curmark-=shift;
  111723. e->cursor-=shift;
  111724. }
  111725. #endif
  111726. /*** End of inlined file: envelope.c ***/
  111727. /*** Start of inlined file: floor0.c ***/
  111728. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111729. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111730. // tasks..
  111731. #if JUCE_MSVC
  111732. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111733. #endif
  111734. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111735. #if JUCE_USE_OGGVORBIS
  111736. #include <stdlib.h>
  111737. #include <string.h>
  111738. #include <math.h>
  111739. /*** Start of inlined file: lsp.h ***/
  111740. #ifndef _V_LSP_H_
  111741. #define _V_LSP_H_
  111742. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  111743. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  111744. float *lsp,int m,
  111745. float amp,float ampoffset);
  111746. #endif
  111747. /*** End of inlined file: lsp.h ***/
  111748. #include <stdio.h>
  111749. typedef struct {
  111750. int ln;
  111751. int m;
  111752. int **linearmap;
  111753. int n[2];
  111754. vorbis_info_floor0 *vi;
  111755. long bits;
  111756. long frames;
  111757. } vorbis_look_floor0;
  111758. /***********************************************/
  111759. static void floor0_free_info(vorbis_info_floor *i){
  111760. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  111761. if(info){
  111762. memset(info,0,sizeof(*info));
  111763. _ogg_free(info);
  111764. }
  111765. }
  111766. static void floor0_free_look(vorbis_look_floor *i){
  111767. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  111768. if(look){
  111769. if(look->linearmap){
  111770. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  111771. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  111772. _ogg_free(look->linearmap);
  111773. }
  111774. memset(look,0,sizeof(*look));
  111775. _ogg_free(look);
  111776. }
  111777. }
  111778. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  111779. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111780. int j;
  111781. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  111782. info->order=oggpack_read(opb,8);
  111783. info->rate=oggpack_read(opb,16);
  111784. info->barkmap=oggpack_read(opb,16);
  111785. info->ampbits=oggpack_read(opb,6);
  111786. info->ampdB=oggpack_read(opb,8);
  111787. info->numbooks=oggpack_read(opb,4)+1;
  111788. if(info->order<1)goto err_out;
  111789. if(info->rate<1)goto err_out;
  111790. if(info->barkmap<1)goto err_out;
  111791. if(info->numbooks<1)goto err_out;
  111792. for(j=0;j<info->numbooks;j++){
  111793. info->books[j]=oggpack_read(opb,8);
  111794. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  111795. }
  111796. return(info);
  111797. err_out:
  111798. floor0_free_info(info);
  111799. return(NULL);
  111800. }
  111801. /* initialize Bark scale and normalization lookups. We could do this
  111802. with static tables, but Vorbis allows a number of possible
  111803. combinations, so it's best to do it computationally.
  111804. The below is authoritative in terms of defining scale mapping.
  111805. Note that the scale depends on the sampling rate as well as the
  111806. linear block and mapping sizes */
  111807. static void floor0_map_lazy_init(vorbis_block *vb,
  111808. vorbis_info_floor *infoX,
  111809. vorbis_look_floor0 *look){
  111810. if(!look->linearmap[vb->W]){
  111811. vorbis_dsp_state *vd=vb->vd;
  111812. vorbis_info *vi=vd->vi;
  111813. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111814. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  111815. int W=vb->W;
  111816. int n=ci->blocksizes[W]/2,j;
  111817. /* we choose a scaling constant so that:
  111818. floor(bark(rate/2-1)*C)=mapped-1
  111819. floor(bark(rate/2)*C)=mapped */
  111820. float scale=look->ln/toBARK(info->rate/2.f);
  111821. /* the mapping from a linear scale to a smaller bark scale is
  111822. straightforward. We do *not* make sure that the linear mapping
  111823. does not skip bark-scale bins; the decoder simply skips them and
  111824. the encoder may do what it wishes in filling them. They're
  111825. necessary in some mapping combinations to keep the scale spacing
  111826. accurate */
  111827. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  111828. for(j=0;j<n;j++){
  111829. int val=floor( toBARK((info->rate/2.f)/n*j)
  111830. *scale); /* bark numbers represent band edges */
  111831. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  111832. look->linearmap[W][j]=val;
  111833. }
  111834. look->linearmap[W][j]=-1;
  111835. look->n[W]=n;
  111836. }
  111837. }
  111838. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  111839. vorbis_info_floor *i){
  111840. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  111841. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  111842. look->m=info->order;
  111843. look->ln=info->barkmap;
  111844. look->vi=info;
  111845. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  111846. return look;
  111847. }
  111848. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  111849. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  111850. vorbis_info_floor0 *info=look->vi;
  111851. int j,k;
  111852. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  111853. if(ampraw>0){ /* also handles the -1 out of data case */
  111854. long maxval=(1<<info->ampbits)-1;
  111855. float amp=(float)ampraw/maxval*info->ampdB;
  111856. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  111857. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  111858. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  111859. codebook *b=ci->fullbooks+info->books[booknum];
  111860. float last=0.f;
  111861. /* the additional b->dim is a guard against any possible stack
  111862. smash; b->dim is provably more than we can overflow the
  111863. vector */
  111864. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  111865. for(j=0;j<look->m;j+=b->dim)
  111866. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  111867. for(j=0;j<look->m;){
  111868. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  111869. last=lsp[j-1];
  111870. }
  111871. lsp[look->m]=amp;
  111872. return(lsp);
  111873. }
  111874. }
  111875. eop:
  111876. return(NULL);
  111877. }
  111878. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  111879. void *memo,float *out){
  111880. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  111881. vorbis_info_floor0 *info=look->vi;
  111882. floor0_map_lazy_init(vb,info,look);
  111883. if(memo){
  111884. float *lsp=(float *)memo;
  111885. float amp=lsp[look->m];
  111886. /* take the coefficients back to a spectral envelope curve */
  111887. vorbis_lsp_to_curve(out,
  111888. look->linearmap[vb->W],
  111889. look->n[vb->W],
  111890. look->ln,
  111891. lsp,look->m,amp,(float)info->ampdB);
  111892. return(1);
  111893. }
  111894. memset(out,0,sizeof(*out)*look->n[vb->W]);
  111895. return(0);
  111896. }
  111897. /* export hooks */
  111898. vorbis_func_floor floor0_exportbundle={
  111899. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  111900. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  111901. };
  111902. #endif
  111903. /*** End of inlined file: floor0.c ***/
  111904. /*** Start of inlined file: floor1.c ***/
  111905. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111906. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111907. // tasks..
  111908. #if JUCE_MSVC
  111909. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111910. #endif
  111911. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111912. #if JUCE_USE_OGGVORBIS
  111913. #include <stdlib.h>
  111914. #include <string.h>
  111915. #include <math.h>
  111916. #include <stdio.h>
  111917. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  111918. typedef struct {
  111919. int sorted_index[VIF_POSIT+2];
  111920. int forward_index[VIF_POSIT+2];
  111921. int reverse_index[VIF_POSIT+2];
  111922. int hineighbor[VIF_POSIT];
  111923. int loneighbor[VIF_POSIT];
  111924. int posts;
  111925. int n;
  111926. int quant_q;
  111927. vorbis_info_floor1 *vi;
  111928. long phrasebits;
  111929. long postbits;
  111930. long frames;
  111931. } vorbis_look_floor1;
  111932. typedef struct lsfit_acc{
  111933. long x0;
  111934. long x1;
  111935. long xa;
  111936. long ya;
  111937. long x2a;
  111938. long y2a;
  111939. long xya;
  111940. long an;
  111941. } lsfit_acc;
  111942. /***********************************************/
  111943. static void floor1_free_info(vorbis_info_floor *i){
  111944. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  111945. if(info){
  111946. memset(info,0,sizeof(*info));
  111947. _ogg_free(info);
  111948. }
  111949. }
  111950. static void floor1_free_look(vorbis_look_floor *i){
  111951. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  111952. if(look){
  111953. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  111954. (float)look->phrasebits/look->frames,
  111955. (float)look->postbits/look->frames,
  111956. (float)(look->postbits+look->phrasebits)/look->frames);*/
  111957. memset(look,0,sizeof(*look));
  111958. _ogg_free(look);
  111959. }
  111960. }
  111961. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  111962. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  111963. int j,k;
  111964. int count=0;
  111965. int rangebits;
  111966. int maxposit=info->postlist[1];
  111967. int maxclass=-1;
  111968. /* save out partitions */
  111969. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  111970. for(j=0;j<info->partitions;j++){
  111971. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  111972. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  111973. }
  111974. /* save out partition classes */
  111975. for(j=0;j<maxclass+1;j++){
  111976. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  111977. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  111978. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  111979. for(k=0;k<(1<<info->class_subs[j]);k++)
  111980. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  111981. }
  111982. /* save out the post list */
  111983. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  111984. oggpack_write(opb,ilog2(maxposit),4);
  111985. rangebits=ilog2(maxposit);
  111986. for(j=0,k=0;j<info->partitions;j++){
  111987. count+=info->class_dim[info->partitionclass[j]];
  111988. for(;k<count;k++)
  111989. oggpack_write(opb,info->postlist[k+2],rangebits);
  111990. }
  111991. }
  111992. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  111993. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111994. int j,k,count=0,maxclass=-1,rangebits;
  111995. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  111996. /* read partitions */
  111997. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  111998. for(j=0;j<info->partitions;j++){
  111999. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  112000. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  112001. }
  112002. /* read partition classes */
  112003. for(j=0;j<maxclass+1;j++){
  112004. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  112005. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  112006. if(info->class_subs[j]<0)
  112007. goto err_out;
  112008. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  112009. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  112010. goto err_out;
  112011. for(k=0;k<(1<<info->class_subs[j]);k++){
  112012. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  112013. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  112014. goto err_out;
  112015. }
  112016. }
  112017. /* read the post list */
  112018. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  112019. rangebits=oggpack_read(opb,4);
  112020. for(j=0,k=0;j<info->partitions;j++){
  112021. count+=info->class_dim[info->partitionclass[j]];
  112022. for(;k<count;k++){
  112023. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  112024. if(t<0 || t>=(1<<rangebits))
  112025. goto err_out;
  112026. }
  112027. }
  112028. info->postlist[0]=0;
  112029. info->postlist[1]=1<<rangebits;
  112030. return(info);
  112031. err_out:
  112032. floor1_free_info(info);
  112033. return(NULL);
  112034. }
  112035. static int icomp(const void *a,const void *b){
  112036. return(**(int **)a-**(int **)b);
  112037. }
  112038. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  112039. vorbis_info_floor *in){
  112040. int *sortpointer[VIF_POSIT+2];
  112041. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  112042. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  112043. int i,j,n=0;
  112044. look->vi=info;
  112045. look->n=info->postlist[1];
  112046. /* we drop each position value in-between already decoded values,
  112047. and use linear interpolation to predict each new value past the
  112048. edges. The positions are read in the order of the position
  112049. list... we precompute the bounding positions in the lookup. Of
  112050. course, the neighbors can change (if a position is declined), but
  112051. this is an initial mapping */
  112052. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  112053. n+=2;
  112054. look->posts=n;
  112055. /* also store a sorted position index */
  112056. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  112057. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  112058. /* points from sort order back to range number */
  112059. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  112060. /* points from range order to sorted position */
  112061. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  112062. /* we actually need the post values too */
  112063. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  112064. /* quantize values to multiplier spec */
  112065. switch(info->mult){
  112066. case 1: /* 1024 -> 256 */
  112067. look->quant_q=256;
  112068. break;
  112069. case 2: /* 1024 -> 128 */
  112070. look->quant_q=128;
  112071. break;
  112072. case 3: /* 1024 -> 86 */
  112073. look->quant_q=86;
  112074. break;
  112075. case 4: /* 1024 -> 64 */
  112076. look->quant_q=64;
  112077. break;
  112078. }
  112079. /* discover our neighbors for decode where we don't use fit flags
  112080. (that would push the neighbors outward) */
  112081. for(i=0;i<n-2;i++){
  112082. int lo=0;
  112083. int hi=1;
  112084. int lx=0;
  112085. int hx=look->n;
  112086. int currentx=info->postlist[i+2];
  112087. for(j=0;j<i+2;j++){
  112088. int x=info->postlist[j];
  112089. if(x>lx && x<currentx){
  112090. lo=j;
  112091. lx=x;
  112092. }
  112093. if(x<hx && x>currentx){
  112094. hi=j;
  112095. hx=x;
  112096. }
  112097. }
  112098. look->loneighbor[i]=lo;
  112099. look->hineighbor[i]=hi;
  112100. }
  112101. return(look);
  112102. }
  112103. static int render_point(int x0,int x1,int y0,int y1,int x){
  112104. y0&=0x7fff; /* mask off flag */
  112105. y1&=0x7fff;
  112106. {
  112107. int dy=y1-y0;
  112108. int adx=x1-x0;
  112109. int ady=abs(dy);
  112110. int err=ady*(x-x0);
  112111. int off=err/adx;
  112112. if(dy<0)return(y0-off);
  112113. return(y0+off);
  112114. }
  112115. }
  112116. static int vorbis_dBquant(const float *x){
  112117. int i= *x*7.3142857f+1023.5f;
  112118. if(i>1023)return(1023);
  112119. if(i<0)return(0);
  112120. return i;
  112121. }
  112122. static float FLOOR1_fromdB_LOOKUP[256]={
  112123. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  112124. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  112125. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  112126. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  112127. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  112128. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  112129. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  112130. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  112131. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  112132. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  112133. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  112134. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  112135. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  112136. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  112137. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  112138. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  112139. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  112140. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  112141. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  112142. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  112143. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  112144. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  112145. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  112146. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  112147. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  112148. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  112149. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  112150. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  112151. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  112152. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  112153. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  112154. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  112155. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  112156. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  112157. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  112158. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  112159. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  112160. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  112161. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  112162. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  112163. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  112164. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  112165. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  112166. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  112167. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  112168. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  112169. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  112170. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  112171. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  112172. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  112173. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  112174. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  112175. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  112176. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  112177. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  112178. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  112179. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  112180. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  112181. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  112182. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  112183. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  112184. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  112185. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  112186. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  112187. };
  112188. static void render_line(int x0,int x1,int y0,int y1,float *d){
  112189. int dy=y1-y0;
  112190. int adx=x1-x0;
  112191. int ady=abs(dy);
  112192. int base=dy/adx;
  112193. int sy=(dy<0?base-1:base+1);
  112194. int x=x0;
  112195. int y=y0;
  112196. int err=0;
  112197. ady-=abs(base*adx);
  112198. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  112199. while(++x<x1){
  112200. err=err+ady;
  112201. if(err>=adx){
  112202. err-=adx;
  112203. y+=sy;
  112204. }else{
  112205. y+=base;
  112206. }
  112207. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  112208. }
  112209. }
  112210. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  112211. int dy=y1-y0;
  112212. int adx=x1-x0;
  112213. int ady=abs(dy);
  112214. int base=dy/adx;
  112215. int sy=(dy<0?base-1:base+1);
  112216. int x=x0;
  112217. int y=y0;
  112218. int err=0;
  112219. ady-=abs(base*adx);
  112220. d[x]=y;
  112221. while(++x<x1){
  112222. err=err+ady;
  112223. if(err>=adx){
  112224. err-=adx;
  112225. y+=sy;
  112226. }else{
  112227. y+=base;
  112228. }
  112229. d[x]=y;
  112230. }
  112231. }
  112232. /* the floor has already been filtered to only include relevant sections */
  112233. static int accumulate_fit(const float *flr,const float *mdct,
  112234. int x0, int x1,lsfit_acc *a,
  112235. int n,vorbis_info_floor1 *info){
  112236. long i;
  112237. 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;
  112238. memset(a,0,sizeof(*a));
  112239. a->x0=x0;
  112240. a->x1=x1;
  112241. if(x1>=n)x1=n-1;
  112242. for(i=x0;i<=x1;i++){
  112243. int quantized=vorbis_dBquant(flr+i);
  112244. if(quantized){
  112245. if(mdct[i]+info->twofitatten>=flr[i]){
  112246. xa += i;
  112247. ya += quantized;
  112248. x2a += i*i;
  112249. y2a += quantized*quantized;
  112250. xya += i*quantized;
  112251. na++;
  112252. }else{
  112253. xb += i;
  112254. yb += quantized;
  112255. x2b += i*i;
  112256. y2b += quantized*quantized;
  112257. xyb += i*quantized;
  112258. nb++;
  112259. }
  112260. }
  112261. }
  112262. xb+=xa;
  112263. yb+=ya;
  112264. x2b+=x2a;
  112265. y2b+=y2a;
  112266. xyb+=xya;
  112267. nb+=na;
  112268. /* weight toward the actually used frequencies if we meet the threshhold */
  112269. {
  112270. int weight=nb*info->twofitweight/(na+1);
  112271. a->xa=xa*weight+xb;
  112272. a->ya=ya*weight+yb;
  112273. a->x2a=x2a*weight+x2b;
  112274. a->y2a=y2a*weight+y2b;
  112275. a->xya=xya*weight+xyb;
  112276. a->an=na*weight+nb;
  112277. }
  112278. return(na);
  112279. }
  112280. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  112281. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  112282. long x0=a[0].x0;
  112283. long x1=a[fits-1].x1;
  112284. for(i=0;i<fits;i++){
  112285. x+=a[i].xa;
  112286. y+=a[i].ya;
  112287. x2+=a[i].x2a;
  112288. y2+=a[i].y2a;
  112289. xy+=a[i].xya;
  112290. an+=a[i].an;
  112291. }
  112292. if(*y0>=0){
  112293. x+= x0;
  112294. y+= *y0;
  112295. x2+= x0 * x0;
  112296. y2+= *y0 * *y0;
  112297. xy+= *y0 * x0;
  112298. an++;
  112299. }
  112300. if(*y1>=0){
  112301. x+= x1;
  112302. y+= *y1;
  112303. x2+= x1 * x1;
  112304. y2+= *y1 * *y1;
  112305. xy+= *y1 * x1;
  112306. an++;
  112307. }
  112308. if(an){
  112309. /* need 64 bit multiplies, which C doesn't give portably as int */
  112310. double fx=x;
  112311. double fy=y;
  112312. double fx2=x2;
  112313. double fxy=xy;
  112314. double denom=1./(an*fx2-fx*fx);
  112315. double a=(fy*fx2-fxy*fx)*denom;
  112316. double b=(an*fxy-fx*fy)*denom;
  112317. *y0=rint(a+b*x0);
  112318. *y1=rint(a+b*x1);
  112319. /* limit to our range! */
  112320. if(*y0>1023)*y0=1023;
  112321. if(*y1>1023)*y1=1023;
  112322. if(*y0<0)*y0=0;
  112323. if(*y1<0)*y1=0;
  112324. }else{
  112325. *y0=0;
  112326. *y1=0;
  112327. }
  112328. }
  112329. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  112330. long y=0;
  112331. int i;
  112332. for(i=0;i<fits && y==0;i++)
  112333. y+=a[i].ya;
  112334. *y0=*y1=y;
  112335. }*/
  112336. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  112337. const float *mdct,
  112338. vorbis_info_floor1 *info){
  112339. int dy=y1-y0;
  112340. int adx=x1-x0;
  112341. int ady=abs(dy);
  112342. int base=dy/adx;
  112343. int sy=(dy<0?base-1:base+1);
  112344. int x=x0;
  112345. int y=y0;
  112346. int err=0;
  112347. int val=vorbis_dBquant(mask+x);
  112348. int mse=0;
  112349. int n=0;
  112350. ady-=abs(base*adx);
  112351. mse=(y-val);
  112352. mse*=mse;
  112353. n++;
  112354. if(mdct[x]+info->twofitatten>=mask[x]){
  112355. if(y+info->maxover<val)return(1);
  112356. if(y-info->maxunder>val)return(1);
  112357. }
  112358. while(++x<x1){
  112359. err=err+ady;
  112360. if(err>=adx){
  112361. err-=adx;
  112362. y+=sy;
  112363. }else{
  112364. y+=base;
  112365. }
  112366. val=vorbis_dBquant(mask+x);
  112367. mse+=((y-val)*(y-val));
  112368. n++;
  112369. if(mdct[x]+info->twofitatten>=mask[x]){
  112370. if(val){
  112371. if(y+info->maxover<val)return(1);
  112372. if(y-info->maxunder>val)return(1);
  112373. }
  112374. }
  112375. }
  112376. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  112377. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  112378. if(mse/n>info->maxerr)return(1);
  112379. return(0);
  112380. }
  112381. static int post_Y(int *A,int *B,int pos){
  112382. if(A[pos]<0)
  112383. return B[pos];
  112384. if(B[pos]<0)
  112385. return A[pos];
  112386. return (A[pos]+B[pos])>>1;
  112387. }
  112388. int *floor1_fit(vorbis_block *vb,void *look_,
  112389. const float *logmdct, /* in */
  112390. const float *logmask){
  112391. long i,j;
  112392. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  112393. vorbis_info_floor1 *info=look->vi;
  112394. long n=look->n;
  112395. long posts=look->posts;
  112396. long nonzero=0;
  112397. lsfit_acc fits[VIF_POSIT+1];
  112398. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  112399. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  112400. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  112401. int hineighbor[VIF_POSIT+2];
  112402. int *output=NULL;
  112403. int memo[VIF_POSIT+2];
  112404. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  112405. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  112406. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  112407. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  112408. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  112409. /* quantize the relevant floor points and collect them into line fit
  112410. structures (one per minimal division) at the same time */
  112411. if(posts==0){
  112412. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  112413. }else{
  112414. for(i=0;i<posts-1;i++)
  112415. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  112416. look->sorted_index[i+1],fits+i,
  112417. n,info);
  112418. }
  112419. if(nonzero){
  112420. /* start by fitting the implicit base case.... */
  112421. int y0=-200;
  112422. int y1=-200;
  112423. fit_line(fits,posts-1,&y0,&y1);
  112424. fit_valueA[0]=y0;
  112425. fit_valueB[0]=y0;
  112426. fit_valueB[1]=y1;
  112427. fit_valueA[1]=y1;
  112428. /* Non degenerate case */
  112429. /* start progressive splitting. This is a greedy, non-optimal
  112430. algorithm, but simple and close enough to the best
  112431. answer. */
  112432. for(i=2;i<posts;i++){
  112433. int sortpos=look->reverse_index[i];
  112434. int ln=loneighbor[sortpos];
  112435. int hn=hineighbor[sortpos];
  112436. /* eliminate repeat searches of a particular range with a memo */
  112437. if(memo[ln]!=hn){
  112438. /* haven't performed this error search yet */
  112439. int lsortpos=look->reverse_index[ln];
  112440. int hsortpos=look->reverse_index[hn];
  112441. memo[ln]=hn;
  112442. {
  112443. /* A note: we want to bound/minimize *local*, not global, error */
  112444. int lx=info->postlist[ln];
  112445. int hx=info->postlist[hn];
  112446. int ly=post_Y(fit_valueA,fit_valueB,ln);
  112447. int hy=post_Y(fit_valueA,fit_valueB,hn);
  112448. if(ly==-1 || hy==-1){
  112449. exit(1);
  112450. }
  112451. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  112452. /* outside error bounds/begin search area. Split it. */
  112453. int ly0=-200;
  112454. int ly1=-200;
  112455. int hy0=-200;
  112456. int hy1=-200;
  112457. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  112458. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  112459. /* store new edge values */
  112460. fit_valueB[ln]=ly0;
  112461. if(ln==0)fit_valueA[ln]=ly0;
  112462. fit_valueA[i]=ly1;
  112463. fit_valueB[i]=hy0;
  112464. fit_valueA[hn]=hy1;
  112465. if(hn==1)fit_valueB[hn]=hy1;
  112466. if(ly1>=0 || hy0>=0){
  112467. /* store new neighbor values */
  112468. for(j=sortpos-1;j>=0;j--)
  112469. if(hineighbor[j]==hn)
  112470. hineighbor[j]=i;
  112471. else
  112472. break;
  112473. for(j=sortpos+1;j<posts;j++)
  112474. if(loneighbor[j]==ln)
  112475. loneighbor[j]=i;
  112476. else
  112477. break;
  112478. }
  112479. }else{
  112480. fit_valueA[i]=-200;
  112481. fit_valueB[i]=-200;
  112482. }
  112483. }
  112484. }
  112485. }
  112486. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  112487. output[0]=post_Y(fit_valueA,fit_valueB,0);
  112488. output[1]=post_Y(fit_valueA,fit_valueB,1);
  112489. /* fill in posts marked as not using a fit; we will zero
  112490. back out to 'unused' when encoding them so long as curve
  112491. interpolation doesn't force them into use */
  112492. for(i=2;i<posts;i++){
  112493. int ln=look->loneighbor[i-2];
  112494. int hn=look->hineighbor[i-2];
  112495. int x0=info->postlist[ln];
  112496. int x1=info->postlist[hn];
  112497. int y0=output[ln];
  112498. int y1=output[hn];
  112499. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  112500. int vx=post_Y(fit_valueA,fit_valueB,i);
  112501. if(vx>=0 && predicted!=vx){
  112502. output[i]=vx;
  112503. }else{
  112504. output[i]= predicted|0x8000;
  112505. }
  112506. }
  112507. }
  112508. return(output);
  112509. }
  112510. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  112511. int *A,int *B,
  112512. int del){
  112513. long i;
  112514. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  112515. long posts=look->posts;
  112516. int *output=NULL;
  112517. if(A && B){
  112518. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  112519. for(i=0;i<posts;i++){
  112520. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  112521. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  112522. }
  112523. }
  112524. return(output);
  112525. }
  112526. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  112527. void*look_,
  112528. int *post,int *ilogmask){
  112529. long i,j;
  112530. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  112531. vorbis_info_floor1 *info=look->vi;
  112532. long posts=look->posts;
  112533. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  112534. int out[VIF_POSIT+2];
  112535. static_codebook **sbooks=ci->book_param;
  112536. codebook *books=ci->fullbooks;
  112537. static long seq=0;
  112538. /* quantize values to multiplier spec */
  112539. if(post){
  112540. for(i=0;i<posts;i++){
  112541. int val=post[i]&0x7fff;
  112542. switch(info->mult){
  112543. case 1: /* 1024 -> 256 */
  112544. val>>=2;
  112545. break;
  112546. case 2: /* 1024 -> 128 */
  112547. val>>=3;
  112548. break;
  112549. case 3: /* 1024 -> 86 */
  112550. val/=12;
  112551. break;
  112552. case 4: /* 1024 -> 64 */
  112553. val>>=4;
  112554. break;
  112555. }
  112556. post[i]=val | (post[i]&0x8000);
  112557. }
  112558. out[0]=post[0];
  112559. out[1]=post[1];
  112560. /* find prediction values for each post and subtract them */
  112561. for(i=2;i<posts;i++){
  112562. int ln=look->loneighbor[i-2];
  112563. int hn=look->hineighbor[i-2];
  112564. int x0=info->postlist[ln];
  112565. int x1=info->postlist[hn];
  112566. int y0=post[ln];
  112567. int y1=post[hn];
  112568. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  112569. if((post[i]&0x8000) || (predicted==post[i])){
  112570. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  112571. in interpolation */
  112572. out[i]=0;
  112573. }else{
  112574. int headroom=(look->quant_q-predicted<predicted?
  112575. look->quant_q-predicted:predicted);
  112576. int val=post[i]-predicted;
  112577. /* at this point the 'deviation' value is in the range +/- max
  112578. range, but the real, unique range can always be mapped to
  112579. only [0-maxrange). So we want to wrap the deviation into
  112580. this limited range, but do it in the way that least screws
  112581. an essentially gaussian probability distribution. */
  112582. if(val<0)
  112583. if(val<-headroom)
  112584. val=headroom-val-1;
  112585. else
  112586. val=-1-(val<<1);
  112587. else
  112588. if(val>=headroom)
  112589. val= val+headroom;
  112590. else
  112591. val<<=1;
  112592. out[i]=val;
  112593. post[ln]&=0x7fff;
  112594. post[hn]&=0x7fff;
  112595. }
  112596. }
  112597. /* we have everything we need. pack it out */
  112598. /* mark nontrivial floor */
  112599. oggpack_write(opb,1,1);
  112600. /* beginning/end post */
  112601. look->frames++;
  112602. look->postbits+=ilog(look->quant_q-1)*2;
  112603. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  112604. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  112605. /* partition by partition */
  112606. for(i=0,j=2;i<info->partitions;i++){
  112607. int classx=info->partitionclass[i];
  112608. int cdim=info->class_dim[classx];
  112609. int csubbits=info->class_subs[classx];
  112610. int csub=1<<csubbits;
  112611. int bookas[8]={0,0,0,0,0,0,0,0};
  112612. int cval=0;
  112613. int cshift=0;
  112614. int k,l;
  112615. /* generate the partition's first stage cascade value */
  112616. if(csubbits){
  112617. int maxval[8];
  112618. for(k=0;k<csub;k++){
  112619. int booknum=info->class_subbook[classx][k];
  112620. if(booknum<0){
  112621. maxval[k]=1;
  112622. }else{
  112623. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  112624. }
  112625. }
  112626. for(k=0;k<cdim;k++){
  112627. for(l=0;l<csub;l++){
  112628. int val=out[j+k];
  112629. if(val<maxval[l]){
  112630. bookas[k]=l;
  112631. break;
  112632. }
  112633. }
  112634. cval|= bookas[k]<<cshift;
  112635. cshift+=csubbits;
  112636. }
  112637. /* write it */
  112638. look->phrasebits+=
  112639. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  112640. #ifdef TRAIN_FLOOR1
  112641. {
  112642. FILE *of;
  112643. char buffer[80];
  112644. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  112645. vb->pcmend/2,posts-2,class);
  112646. of=fopen(buffer,"a");
  112647. fprintf(of,"%d\n",cval);
  112648. fclose(of);
  112649. }
  112650. #endif
  112651. }
  112652. /* write post values */
  112653. for(k=0;k<cdim;k++){
  112654. int book=info->class_subbook[classx][bookas[k]];
  112655. if(book>=0){
  112656. /* hack to allow training with 'bad' books */
  112657. if(out[j+k]<(books+book)->entries)
  112658. look->postbits+=vorbis_book_encode(books+book,
  112659. out[j+k],opb);
  112660. /*else
  112661. fprintf(stderr,"+!");*/
  112662. #ifdef TRAIN_FLOOR1
  112663. {
  112664. FILE *of;
  112665. char buffer[80];
  112666. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  112667. vb->pcmend/2,posts-2,class,bookas[k]);
  112668. of=fopen(buffer,"a");
  112669. fprintf(of,"%d\n",out[j+k]);
  112670. fclose(of);
  112671. }
  112672. #endif
  112673. }
  112674. }
  112675. j+=cdim;
  112676. }
  112677. {
  112678. /* generate quantized floor equivalent to what we'd unpack in decode */
  112679. /* render the lines */
  112680. int hx=0;
  112681. int lx=0;
  112682. int ly=post[0]*info->mult;
  112683. for(j=1;j<look->posts;j++){
  112684. int current=look->forward_index[j];
  112685. int hy=post[current]&0x7fff;
  112686. if(hy==post[current]){
  112687. hy*=info->mult;
  112688. hx=info->postlist[current];
  112689. render_line0(lx,hx,ly,hy,ilogmask);
  112690. lx=hx;
  112691. ly=hy;
  112692. }
  112693. }
  112694. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  112695. seq++;
  112696. return(1);
  112697. }
  112698. }else{
  112699. oggpack_write(opb,0,1);
  112700. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  112701. seq++;
  112702. return(0);
  112703. }
  112704. }
  112705. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  112706. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  112707. vorbis_info_floor1 *info=look->vi;
  112708. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  112709. int i,j,k;
  112710. codebook *books=ci->fullbooks;
  112711. /* unpack wrapped/predicted values from stream */
  112712. if(oggpack_read(&vb->opb,1)==1){
  112713. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  112714. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  112715. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  112716. /* partition by partition */
  112717. for(i=0,j=2;i<info->partitions;i++){
  112718. int classx=info->partitionclass[i];
  112719. int cdim=info->class_dim[classx];
  112720. int csubbits=info->class_subs[classx];
  112721. int csub=1<<csubbits;
  112722. int cval=0;
  112723. /* decode the partition's first stage cascade value */
  112724. if(csubbits){
  112725. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  112726. if(cval==-1)goto eop;
  112727. }
  112728. for(k=0;k<cdim;k++){
  112729. int book=info->class_subbook[classx][cval&(csub-1)];
  112730. cval>>=csubbits;
  112731. if(book>=0){
  112732. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  112733. goto eop;
  112734. }else{
  112735. fit_value[j+k]=0;
  112736. }
  112737. }
  112738. j+=cdim;
  112739. }
  112740. /* unwrap positive values and reconsitute via linear interpolation */
  112741. for(i=2;i<look->posts;i++){
  112742. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  112743. info->postlist[look->hineighbor[i-2]],
  112744. fit_value[look->loneighbor[i-2]],
  112745. fit_value[look->hineighbor[i-2]],
  112746. info->postlist[i]);
  112747. int hiroom=look->quant_q-predicted;
  112748. int loroom=predicted;
  112749. int room=(hiroom<loroom?hiroom:loroom)<<1;
  112750. int val=fit_value[i];
  112751. if(val){
  112752. if(val>=room){
  112753. if(hiroom>loroom){
  112754. val = val-loroom;
  112755. }else{
  112756. val = -1-(val-hiroom);
  112757. }
  112758. }else{
  112759. if(val&1){
  112760. val= -((val+1)>>1);
  112761. }else{
  112762. val>>=1;
  112763. }
  112764. }
  112765. fit_value[i]=val+predicted;
  112766. fit_value[look->loneighbor[i-2]]&=0x7fff;
  112767. fit_value[look->hineighbor[i-2]]&=0x7fff;
  112768. }else{
  112769. fit_value[i]=predicted|0x8000;
  112770. }
  112771. }
  112772. return(fit_value);
  112773. }
  112774. eop:
  112775. return(NULL);
  112776. }
  112777. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  112778. float *out){
  112779. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  112780. vorbis_info_floor1 *info=look->vi;
  112781. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  112782. int n=ci->blocksizes[vb->W]/2;
  112783. int j;
  112784. if(memo){
  112785. /* render the lines */
  112786. int *fit_value=(int *)memo;
  112787. int hx=0;
  112788. int lx=0;
  112789. int ly=fit_value[0]*info->mult;
  112790. for(j=1;j<look->posts;j++){
  112791. int current=look->forward_index[j];
  112792. int hy=fit_value[current]&0x7fff;
  112793. if(hy==fit_value[current]){
  112794. hy*=info->mult;
  112795. hx=info->postlist[current];
  112796. render_line(lx,hx,ly,hy,out);
  112797. lx=hx;
  112798. ly=hy;
  112799. }
  112800. }
  112801. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  112802. return(1);
  112803. }
  112804. memset(out,0,sizeof(*out)*n);
  112805. return(0);
  112806. }
  112807. /* export hooks */
  112808. vorbis_func_floor floor1_exportbundle={
  112809. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  112810. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  112811. };
  112812. #endif
  112813. /*** End of inlined file: floor1.c ***/
  112814. /*** Start of inlined file: info.c ***/
  112815. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112816. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112817. // tasks..
  112818. #if JUCE_MSVC
  112819. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112820. #endif
  112821. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112822. #if JUCE_USE_OGGVORBIS
  112823. /* general handling of the header and the vorbis_info structure (and
  112824. substructures) */
  112825. #include <stdlib.h>
  112826. #include <string.h>
  112827. #include <ctype.h>
  112828. static void _v_writestring(oggpack_buffer *o, const char *s, int bytes){
  112829. while(bytes--){
  112830. oggpack_write(o,*s++,8);
  112831. }
  112832. }
  112833. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  112834. while(bytes--){
  112835. *buf++=oggpack_read(o,8);
  112836. }
  112837. }
  112838. void vorbis_comment_init(vorbis_comment *vc){
  112839. memset(vc,0,sizeof(*vc));
  112840. }
  112841. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  112842. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  112843. (vc->comments+2)*sizeof(*vc->user_comments));
  112844. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  112845. (vc->comments+2)*sizeof(*vc->comment_lengths));
  112846. vc->comment_lengths[vc->comments]=strlen(comment);
  112847. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  112848. strcpy(vc->user_comments[vc->comments], comment);
  112849. vc->comments++;
  112850. vc->user_comments[vc->comments]=NULL;
  112851. }
  112852. void vorbis_comment_add_tag(vorbis_comment *vc, const char *tag, char *contents){
  112853. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  112854. strcpy(comment, tag);
  112855. strcat(comment, "=");
  112856. strcat(comment, contents);
  112857. vorbis_comment_add(vc, comment);
  112858. }
  112859. /* This is more or less the same as strncasecmp - but that doesn't exist
  112860. * everywhere, and this is a fairly trivial function, so we include it */
  112861. static int tagcompare(const char *s1, const char *s2, int n){
  112862. int c=0;
  112863. while(c < n){
  112864. if(toupper(s1[c]) != toupper(s2[c]))
  112865. return !0;
  112866. c++;
  112867. }
  112868. return 0;
  112869. }
  112870. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  112871. long i;
  112872. int found = 0;
  112873. int taglen = strlen(tag)+1; /* +1 for the = we append */
  112874. char *fulltag = (char*)alloca(taglen+ 1);
  112875. strcpy(fulltag, tag);
  112876. strcat(fulltag, "=");
  112877. for(i=0;i<vc->comments;i++){
  112878. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  112879. if(count == found)
  112880. /* We return a pointer to the data, not a copy */
  112881. return vc->user_comments[i] + taglen;
  112882. else
  112883. found++;
  112884. }
  112885. }
  112886. return NULL; /* didn't find anything */
  112887. }
  112888. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  112889. int i,count=0;
  112890. int taglen = strlen(tag)+1; /* +1 for the = we append */
  112891. char *fulltag = (char*)alloca(taglen+1);
  112892. strcpy(fulltag,tag);
  112893. strcat(fulltag, "=");
  112894. for(i=0;i<vc->comments;i++){
  112895. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  112896. count++;
  112897. }
  112898. return count;
  112899. }
  112900. void vorbis_comment_clear(vorbis_comment *vc){
  112901. if(vc){
  112902. long i;
  112903. for(i=0;i<vc->comments;i++)
  112904. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  112905. if(vc->user_comments)_ogg_free(vc->user_comments);
  112906. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  112907. if(vc->vendor)_ogg_free(vc->vendor);
  112908. }
  112909. memset(vc,0,sizeof(*vc));
  112910. }
  112911. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  112912. They may be equal, but short will never ge greater than long */
  112913. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  112914. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  112915. return ci ? ci->blocksizes[zo] : -1;
  112916. }
  112917. /* used by synthesis, which has a full, alloced vi */
  112918. void vorbis_info_init(vorbis_info *vi){
  112919. memset(vi,0,sizeof(*vi));
  112920. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  112921. }
  112922. void vorbis_info_clear(vorbis_info *vi){
  112923. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112924. int i;
  112925. if(ci){
  112926. for(i=0;i<ci->modes;i++)
  112927. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  112928. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  112929. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  112930. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  112931. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  112932. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  112933. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  112934. for(i=0;i<ci->books;i++){
  112935. if(ci->book_param[i]){
  112936. /* knows if the book was not alloced */
  112937. vorbis_staticbook_destroy(ci->book_param[i]);
  112938. }
  112939. if(ci->fullbooks)
  112940. vorbis_book_clear(ci->fullbooks+i);
  112941. }
  112942. if(ci->fullbooks)
  112943. _ogg_free(ci->fullbooks);
  112944. for(i=0;i<ci->psys;i++)
  112945. _vi_psy_free(ci->psy_param[i]);
  112946. _ogg_free(ci);
  112947. }
  112948. memset(vi,0,sizeof(*vi));
  112949. }
  112950. /* Header packing/unpacking ********************************************/
  112951. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  112952. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112953. if(!ci)return(OV_EFAULT);
  112954. vi->version=oggpack_read(opb,32);
  112955. if(vi->version!=0)return(OV_EVERSION);
  112956. vi->channels=oggpack_read(opb,8);
  112957. vi->rate=oggpack_read(opb,32);
  112958. vi->bitrate_upper=oggpack_read(opb,32);
  112959. vi->bitrate_nominal=oggpack_read(opb,32);
  112960. vi->bitrate_lower=oggpack_read(opb,32);
  112961. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  112962. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  112963. if(vi->rate<1)goto err_out;
  112964. if(vi->channels<1)goto err_out;
  112965. if(ci->blocksizes[0]<8)goto err_out;
  112966. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  112967. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  112968. return(0);
  112969. err_out:
  112970. vorbis_info_clear(vi);
  112971. return(OV_EBADHEADER);
  112972. }
  112973. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  112974. int i;
  112975. int vendorlen=oggpack_read(opb,32);
  112976. if(vendorlen<0)goto err_out;
  112977. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  112978. _v_readstring(opb,vc->vendor,vendorlen);
  112979. vc->comments=oggpack_read(opb,32);
  112980. if(vc->comments<0)goto err_out;
  112981. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  112982. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  112983. for(i=0;i<vc->comments;i++){
  112984. int len=oggpack_read(opb,32);
  112985. if(len<0)goto err_out;
  112986. vc->comment_lengths[i]=len;
  112987. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  112988. _v_readstring(opb,vc->user_comments[i],len);
  112989. }
  112990. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  112991. return(0);
  112992. err_out:
  112993. vorbis_comment_clear(vc);
  112994. return(OV_EBADHEADER);
  112995. }
  112996. /* all of the real encoding details are here. The modes, books,
  112997. everything */
  112998. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  112999. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113000. int i;
  113001. if(!ci)return(OV_EFAULT);
  113002. /* codebooks */
  113003. ci->books=oggpack_read(opb,8)+1;
  113004. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  113005. for(i=0;i<ci->books;i++){
  113006. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  113007. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  113008. }
  113009. /* time backend settings; hooks are unused */
  113010. {
  113011. int times=oggpack_read(opb,6)+1;
  113012. for(i=0;i<times;i++){
  113013. int test=oggpack_read(opb,16);
  113014. if(test<0 || test>=VI_TIMEB)goto err_out;
  113015. }
  113016. }
  113017. /* floor backend settings */
  113018. ci->floors=oggpack_read(opb,6)+1;
  113019. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  113020. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  113021. for(i=0;i<ci->floors;i++){
  113022. ci->floor_type[i]=oggpack_read(opb,16);
  113023. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  113024. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  113025. if(!ci->floor_param[i])goto err_out;
  113026. }
  113027. /* residue backend settings */
  113028. ci->residues=oggpack_read(opb,6)+1;
  113029. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  113030. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  113031. for(i=0;i<ci->residues;i++){
  113032. ci->residue_type[i]=oggpack_read(opb,16);
  113033. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  113034. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  113035. if(!ci->residue_param[i])goto err_out;
  113036. }
  113037. /* map backend settings */
  113038. ci->maps=oggpack_read(opb,6)+1;
  113039. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  113040. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  113041. for(i=0;i<ci->maps;i++){
  113042. ci->map_type[i]=oggpack_read(opb,16);
  113043. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  113044. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  113045. if(!ci->map_param[i])goto err_out;
  113046. }
  113047. /* mode settings */
  113048. ci->modes=oggpack_read(opb,6)+1;
  113049. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  113050. for(i=0;i<ci->modes;i++){
  113051. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  113052. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  113053. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  113054. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  113055. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  113056. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  113057. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  113058. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  113059. }
  113060. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  113061. return(0);
  113062. err_out:
  113063. vorbis_info_clear(vi);
  113064. return(OV_EBADHEADER);
  113065. }
  113066. /* The Vorbis header is in three packets; the initial small packet in
  113067. the first page that identifies basic parameters, a second packet
  113068. with bitstream comments and a third packet that holds the
  113069. codebook. */
  113070. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  113071. oggpack_buffer opb;
  113072. if(op){
  113073. oggpack_readinit(&opb,op->packet,op->bytes);
  113074. /* Which of the three types of header is this? */
  113075. /* Also verify header-ness, vorbis */
  113076. {
  113077. char buffer[6];
  113078. int packtype=oggpack_read(&opb,8);
  113079. memset(buffer,0,6);
  113080. _v_readstring(&opb,buffer,6);
  113081. if(memcmp(buffer,"vorbis",6)){
  113082. /* not a vorbis header */
  113083. return(OV_ENOTVORBIS);
  113084. }
  113085. switch(packtype){
  113086. case 0x01: /* least significant *bit* is read first */
  113087. if(!op->b_o_s){
  113088. /* Not the initial packet */
  113089. return(OV_EBADHEADER);
  113090. }
  113091. if(vi->rate!=0){
  113092. /* previously initialized info header */
  113093. return(OV_EBADHEADER);
  113094. }
  113095. return(_vorbis_unpack_info(vi,&opb));
  113096. case 0x03: /* least significant *bit* is read first */
  113097. if(vi->rate==0){
  113098. /* um... we didn't get the initial header */
  113099. return(OV_EBADHEADER);
  113100. }
  113101. return(_vorbis_unpack_comment(vc,&opb));
  113102. case 0x05: /* least significant *bit* is read first */
  113103. if(vi->rate==0 || vc->vendor==NULL){
  113104. /* um... we didn;t get the initial header or comments yet */
  113105. return(OV_EBADHEADER);
  113106. }
  113107. return(_vorbis_unpack_books(vi,&opb));
  113108. default:
  113109. /* Not a valid vorbis header type */
  113110. return(OV_EBADHEADER);
  113111. break;
  113112. }
  113113. }
  113114. }
  113115. return(OV_EBADHEADER);
  113116. }
  113117. /* pack side **********************************************************/
  113118. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  113119. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113120. if(!ci)return(OV_EFAULT);
  113121. /* preamble */
  113122. oggpack_write(opb,0x01,8);
  113123. _v_writestring(opb,"vorbis", 6);
  113124. /* basic information about the stream */
  113125. oggpack_write(opb,0x00,32);
  113126. oggpack_write(opb,vi->channels,8);
  113127. oggpack_write(opb,vi->rate,32);
  113128. oggpack_write(opb,vi->bitrate_upper,32);
  113129. oggpack_write(opb,vi->bitrate_nominal,32);
  113130. oggpack_write(opb,vi->bitrate_lower,32);
  113131. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  113132. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  113133. oggpack_write(opb,1,1);
  113134. return(0);
  113135. }
  113136. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  113137. char temp[]="Xiph.Org libVorbis I 20050304";
  113138. int bytes = strlen(temp);
  113139. /* preamble */
  113140. oggpack_write(opb,0x03,8);
  113141. _v_writestring(opb,"vorbis", 6);
  113142. /* vendor */
  113143. oggpack_write(opb,bytes,32);
  113144. _v_writestring(opb,temp, bytes);
  113145. /* comments */
  113146. oggpack_write(opb,vc->comments,32);
  113147. if(vc->comments){
  113148. int i;
  113149. for(i=0;i<vc->comments;i++){
  113150. if(vc->user_comments[i]){
  113151. oggpack_write(opb,vc->comment_lengths[i],32);
  113152. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  113153. }else{
  113154. oggpack_write(opb,0,32);
  113155. }
  113156. }
  113157. }
  113158. oggpack_write(opb,1,1);
  113159. return(0);
  113160. }
  113161. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  113162. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113163. int i;
  113164. if(!ci)return(OV_EFAULT);
  113165. oggpack_write(opb,0x05,8);
  113166. _v_writestring(opb,"vorbis", 6);
  113167. /* books */
  113168. oggpack_write(opb,ci->books-1,8);
  113169. for(i=0;i<ci->books;i++)
  113170. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  113171. /* times; hook placeholders */
  113172. oggpack_write(opb,0,6);
  113173. oggpack_write(opb,0,16);
  113174. /* floors */
  113175. oggpack_write(opb,ci->floors-1,6);
  113176. for(i=0;i<ci->floors;i++){
  113177. oggpack_write(opb,ci->floor_type[i],16);
  113178. if(_floor_P[ci->floor_type[i]]->pack)
  113179. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  113180. else
  113181. goto err_out;
  113182. }
  113183. /* residues */
  113184. oggpack_write(opb,ci->residues-1,6);
  113185. for(i=0;i<ci->residues;i++){
  113186. oggpack_write(opb,ci->residue_type[i],16);
  113187. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  113188. }
  113189. /* maps */
  113190. oggpack_write(opb,ci->maps-1,6);
  113191. for(i=0;i<ci->maps;i++){
  113192. oggpack_write(opb,ci->map_type[i],16);
  113193. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  113194. }
  113195. /* modes */
  113196. oggpack_write(opb,ci->modes-1,6);
  113197. for(i=0;i<ci->modes;i++){
  113198. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  113199. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  113200. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  113201. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  113202. }
  113203. oggpack_write(opb,1,1);
  113204. return(0);
  113205. err_out:
  113206. return(-1);
  113207. }
  113208. int vorbis_commentheader_out(vorbis_comment *vc,
  113209. ogg_packet *op){
  113210. oggpack_buffer opb;
  113211. oggpack_writeinit(&opb);
  113212. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  113213. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113214. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  113215. op->bytes=oggpack_bytes(&opb);
  113216. op->b_o_s=0;
  113217. op->e_o_s=0;
  113218. op->granulepos=0;
  113219. op->packetno=1;
  113220. return 0;
  113221. }
  113222. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  113223. vorbis_comment *vc,
  113224. ogg_packet *op,
  113225. ogg_packet *op_comm,
  113226. ogg_packet *op_code){
  113227. int ret=OV_EIMPL;
  113228. vorbis_info *vi=v->vi;
  113229. oggpack_buffer opb;
  113230. private_state *b=(private_state*)v->backend_state;
  113231. if(!b){
  113232. ret=OV_EFAULT;
  113233. goto err_out;
  113234. }
  113235. /* first header packet **********************************************/
  113236. oggpack_writeinit(&opb);
  113237. if(_vorbis_pack_info(&opb,vi))goto err_out;
  113238. /* build the packet */
  113239. if(b->header)_ogg_free(b->header);
  113240. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113241. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  113242. op->packet=b->header;
  113243. op->bytes=oggpack_bytes(&opb);
  113244. op->b_o_s=1;
  113245. op->e_o_s=0;
  113246. op->granulepos=0;
  113247. op->packetno=0;
  113248. /* second header packet (comments) **********************************/
  113249. oggpack_reset(&opb);
  113250. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  113251. if(b->header1)_ogg_free(b->header1);
  113252. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113253. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  113254. op_comm->packet=b->header1;
  113255. op_comm->bytes=oggpack_bytes(&opb);
  113256. op_comm->b_o_s=0;
  113257. op_comm->e_o_s=0;
  113258. op_comm->granulepos=0;
  113259. op_comm->packetno=1;
  113260. /* third header packet (modes/codebooks) ****************************/
  113261. oggpack_reset(&opb);
  113262. if(_vorbis_pack_books(&opb,vi))goto err_out;
  113263. if(b->header2)_ogg_free(b->header2);
  113264. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113265. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  113266. op_code->packet=b->header2;
  113267. op_code->bytes=oggpack_bytes(&opb);
  113268. op_code->b_o_s=0;
  113269. op_code->e_o_s=0;
  113270. op_code->granulepos=0;
  113271. op_code->packetno=2;
  113272. oggpack_writeclear(&opb);
  113273. return(0);
  113274. err_out:
  113275. oggpack_writeclear(&opb);
  113276. memset(op,0,sizeof(*op));
  113277. memset(op_comm,0,sizeof(*op_comm));
  113278. memset(op_code,0,sizeof(*op_code));
  113279. if(b->header)_ogg_free(b->header);
  113280. if(b->header1)_ogg_free(b->header1);
  113281. if(b->header2)_ogg_free(b->header2);
  113282. b->header=NULL;
  113283. b->header1=NULL;
  113284. b->header2=NULL;
  113285. return(ret);
  113286. }
  113287. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  113288. if(granulepos>=0)
  113289. return((double)granulepos/v->vi->rate);
  113290. return(-1);
  113291. }
  113292. #endif
  113293. /*** End of inlined file: info.c ***/
  113294. /*** Start of inlined file: lpc.c ***/
  113295. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  113296. are derived from code written by Jutta Degener and Carsten Bormann;
  113297. thus we include their copyright below. The entirety of this file
  113298. is freely redistributable on the condition that both of these
  113299. copyright notices are preserved without modification. */
  113300. /* Preserved Copyright: *********************************************/
  113301. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  113302. Technische Universita"t Berlin
  113303. Any use of this software is permitted provided that this notice is not
  113304. removed and that neither the authors nor the Technische Universita"t
  113305. Berlin are deemed to have made any representations as to the
  113306. suitability of this software for any purpose nor are held responsible
  113307. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  113308. THIS SOFTWARE.
  113309. As a matter of courtesy, the authors request to be informed about uses
  113310. this software has found, about bugs in this software, and about any
  113311. improvements that may be of general interest.
  113312. Berlin, 28.11.1994
  113313. Jutta Degener
  113314. Carsten Bormann
  113315. *********************************************************************/
  113316. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113317. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113318. // tasks..
  113319. #if JUCE_MSVC
  113320. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113321. #endif
  113322. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113323. #if JUCE_USE_OGGVORBIS
  113324. #include <stdlib.h>
  113325. #include <string.h>
  113326. #include <math.h>
  113327. /* Autocorrelation LPC coeff generation algorithm invented by
  113328. N. Levinson in 1947, modified by J. Durbin in 1959. */
  113329. /* Input : n elements of time doamin data
  113330. Output: m lpc coefficients, excitation energy */
  113331. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  113332. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  113333. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  113334. double error;
  113335. int i,j;
  113336. /* autocorrelation, p+1 lag coefficients */
  113337. j=m+1;
  113338. while(j--){
  113339. double d=0; /* double needed for accumulator depth */
  113340. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  113341. aut[j]=d;
  113342. }
  113343. /* Generate lpc coefficients from autocorr values */
  113344. error=aut[0];
  113345. for(i=0;i<m;i++){
  113346. double r= -aut[i+1];
  113347. if(error==0){
  113348. memset(lpci,0,m*sizeof(*lpci));
  113349. return 0;
  113350. }
  113351. /* Sum up this iteration's reflection coefficient; note that in
  113352. Vorbis we don't save it. If anyone wants to recycle this code
  113353. and needs reflection coefficients, save the results of 'r' from
  113354. each iteration. */
  113355. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  113356. r/=error;
  113357. /* Update LPC coefficients and total error */
  113358. lpc[i]=r;
  113359. for(j=0;j<i/2;j++){
  113360. double tmp=lpc[j];
  113361. lpc[j]+=r*lpc[i-1-j];
  113362. lpc[i-1-j]+=r*tmp;
  113363. }
  113364. if(i%2)lpc[j]+=lpc[j]*r;
  113365. error*=1.f-r*r;
  113366. }
  113367. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  113368. /* we need the error value to know how big an impulse to hit the
  113369. filter with later */
  113370. return error;
  113371. }
  113372. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  113373. float *data,long n){
  113374. /* in: coeff[0...m-1] LPC coefficients
  113375. prime[0...m-1] initial values (allocated size of n+m-1)
  113376. out: data[0...n-1] data samples */
  113377. long i,j,o,p;
  113378. float y;
  113379. float *work=(float*)alloca(sizeof(*work)*(m+n));
  113380. if(!prime)
  113381. for(i=0;i<m;i++)
  113382. work[i]=0.f;
  113383. else
  113384. for(i=0;i<m;i++)
  113385. work[i]=prime[i];
  113386. for(i=0;i<n;i++){
  113387. y=0;
  113388. o=i;
  113389. p=m;
  113390. for(j=0;j<m;j++)
  113391. y-=work[o++]*coeff[--p];
  113392. data[i]=work[o]=y;
  113393. }
  113394. }
  113395. #endif
  113396. /*** End of inlined file: lpc.c ***/
  113397. /*** Start of inlined file: lsp.c ***/
  113398. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  113399. an iterative root polisher (CACM algorithm 283). It *is* possible
  113400. to confuse this algorithm into not converging; that should only
  113401. happen with absurdly closely spaced roots (very sharp peaks in the
  113402. LPC f response) which in turn should be impossible in our use of
  113403. the code. If this *does* happen anyway, it's a bug in the floor
  113404. finder; find the cause of the confusion (probably a single bin
  113405. spike or accidental near-float-limit resolution problems) and
  113406. correct it. */
  113407. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113408. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113409. // tasks..
  113410. #if JUCE_MSVC
  113411. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113412. #endif
  113413. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113414. #if JUCE_USE_OGGVORBIS
  113415. #include <math.h>
  113416. #include <string.h>
  113417. #include <stdlib.h>
  113418. /*** Start of inlined file: lookup.h ***/
  113419. #ifndef _V_LOOKUP_H_
  113420. #ifdef FLOAT_LOOKUP
  113421. extern float vorbis_coslook(float a);
  113422. extern float vorbis_invsqlook(float a);
  113423. extern float vorbis_invsq2explook(int a);
  113424. extern float vorbis_fromdBlook(float a);
  113425. #endif
  113426. #ifdef INT_LOOKUP
  113427. extern long vorbis_invsqlook_i(long a,long e);
  113428. extern long vorbis_coslook_i(long a);
  113429. extern float vorbis_fromdBlook_i(long a);
  113430. #endif
  113431. #endif
  113432. /*** End of inlined file: lookup.h ***/
  113433. /* three possible LSP to f curve functions; the exact computation
  113434. (float), a lookup based float implementation, and an integer
  113435. implementation. The float lookup is likely the optimal choice on
  113436. any machine with an FPU. The integer implementation is *not* fixed
  113437. point (due to the need for a large dynamic range and thus a
  113438. seperately tracked exponent) and thus much more complex than the
  113439. relatively simple float implementations. It's mostly for future
  113440. work on a fully fixed point implementation for processors like the
  113441. ARM family. */
  113442. /* undefine both for the 'old' but more precise implementation */
  113443. #define FLOAT_LOOKUP
  113444. #undef INT_LOOKUP
  113445. #ifdef FLOAT_LOOKUP
  113446. /*** Start of inlined file: lookup.c ***/
  113447. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113448. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113449. // tasks..
  113450. #if JUCE_MSVC
  113451. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113452. #endif
  113453. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113454. #if JUCE_USE_OGGVORBIS
  113455. #include <math.h>
  113456. /*** Start of inlined file: lookup.h ***/
  113457. #ifndef _V_LOOKUP_H_
  113458. #ifdef FLOAT_LOOKUP
  113459. extern float vorbis_coslook(float a);
  113460. extern float vorbis_invsqlook(float a);
  113461. extern float vorbis_invsq2explook(int a);
  113462. extern float vorbis_fromdBlook(float a);
  113463. #endif
  113464. #ifdef INT_LOOKUP
  113465. extern long vorbis_invsqlook_i(long a,long e);
  113466. extern long vorbis_coslook_i(long a);
  113467. extern float vorbis_fromdBlook_i(long a);
  113468. #endif
  113469. #endif
  113470. /*** End of inlined file: lookup.h ***/
  113471. /*** Start of inlined file: lookup_data.h ***/
  113472. #ifndef _V_LOOKUP_DATA_H_
  113473. #ifdef FLOAT_LOOKUP
  113474. #define COS_LOOKUP_SZ 128
  113475. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  113476. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  113477. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  113478. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  113479. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  113480. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  113481. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  113482. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  113483. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  113484. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  113485. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  113486. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  113487. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  113488. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  113489. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  113490. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  113491. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  113492. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  113493. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  113494. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  113495. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  113496. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  113497. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  113498. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  113499. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  113500. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  113501. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  113502. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  113503. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  113504. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  113505. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  113506. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  113507. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  113508. -1.0000000000000f,
  113509. };
  113510. #define INVSQ_LOOKUP_SZ 32
  113511. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  113512. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  113513. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  113514. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  113515. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  113516. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  113517. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  113518. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  113519. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  113520. 1.000000000000f,
  113521. };
  113522. #define INVSQ2EXP_LOOKUP_MIN (-32)
  113523. #define INVSQ2EXP_LOOKUP_MAX 32
  113524. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  113525. INVSQ2EXP_LOOKUP_MIN+1]={
  113526. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  113527. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  113528. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  113529. 1024.f, 724.0773439f, 512.f, 362.038672f,
  113530. 256.f, 181.019336f, 128.f, 90.50966799f,
  113531. 64.f, 45.254834f, 32.f, 22.627417f,
  113532. 16.f, 11.3137085f, 8.f, 5.656854249f,
  113533. 4.f, 2.828427125f, 2.f, 1.414213562f,
  113534. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  113535. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  113536. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  113537. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  113538. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  113539. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  113540. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  113541. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  113542. 1.525878906e-05f,
  113543. };
  113544. #endif
  113545. #define FROMdB_LOOKUP_SZ 35
  113546. #define FROMdB2_LOOKUP_SZ 32
  113547. #define FROMdB_SHIFT 5
  113548. #define FROMdB2_SHIFT 3
  113549. #define FROMdB2_MASK 31
  113550. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  113551. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  113552. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  113553. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  113554. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  113555. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  113556. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  113557. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  113558. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  113559. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  113560. };
  113561. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  113562. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  113563. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  113564. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  113565. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  113566. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  113567. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  113568. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  113569. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  113570. };
  113571. #ifdef INT_LOOKUP
  113572. #define INVSQ_LOOKUP_I_SHIFT 10
  113573. #define INVSQ_LOOKUP_I_MASK 1023
  113574. static long INVSQ_LOOKUP_I[64+1]={
  113575. 92682l, 91966l, 91267l, 90583l,
  113576. 89915l, 89261l, 88621l, 87995l,
  113577. 87381l, 86781l, 86192l, 85616l,
  113578. 85051l, 84497l, 83953l, 83420l,
  113579. 82897l, 82384l, 81880l, 81385l,
  113580. 80899l, 80422l, 79953l, 79492l,
  113581. 79039l, 78594l, 78156l, 77726l,
  113582. 77302l, 76885l, 76475l, 76072l,
  113583. 75674l, 75283l, 74898l, 74519l,
  113584. 74146l, 73778l, 73415l, 73058l,
  113585. 72706l, 72359l, 72016l, 71679l,
  113586. 71347l, 71019l, 70695l, 70376l,
  113587. 70061l, 69750l, 69444l, 69141l,
  113588. 68842l, 68548l, 68256l, 67969l,
  113589. 67685l, 67405l, 67128l, 66855l,
  113590. 66585l, 66318l, 66054l, 65794l,
  113591. 65536l,
  113592. };
  113593. #define COS_LOOKUP_I_SHIFT 9
  113594. #define COS_LOOKUP_I_MASK 511
  113595. #define COS_LOOKUP_I_SZ 128
  113596. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  113597. 16384l, 16379l, 16364l, 16340l,
  113598. 16305l, 16261l, 16207l, 16143l,
  113599. 16069l, 15986l, 15893l, 15791l,
  113600. 15679l, 15557l, 15426l, 15286l,
  113601. 15137l, 14978l, 14811l, 14635l,
  113602. 14449l, 14256l, 14053l, 13842l,
  113603. 13623l, 13395l, 13160l, 12916l,
  113604. 12665l, 12406l, 12140l, 11866l,
  113605. 11585l, 11297l, 11003l, 10702l,
  113606. 10394l, 10080l, 9760l, 9434l,
  113607. 9102l, 8765l, 8423l, 8076l,
  113608. 7723l, 7366l, 7005l, 6639l,
  113609. 6270l, 5897l, 5520l, 5139l,
  113610. 4756l, 4370l, 3981l, 3590l,
  113611. 3196l, 2801l, 2404l, 2006l,
  113612. 1606l, 1205l, 804l, 402l,
  113613. 0l, -401l, -803l, -1204l,
  113614. -1605l, -2005l, -2403l, -2800l,
  113615. -3195l, -3589l, -3980l, -4369l,
  113616. -4755l, -5138l, -5519l, -5896l,
  113617. -6269l, -6638l, -7004l, -7365l,
  113618. -7722l, -8075l, -8422l, -8764l,
  113619. -9101l, -9433l, -9759l, -10079l,
  113620. -10393l, -10701l, -11002l, -11296l,
  113621. -11584l, -11865l, -12139l, -12405l,
  113622. -12664l, -12915l, -13159l, -13394l,
  113623. -13622l, -13841l, -14052l, -14255l,
  113624. -14448l, -14634l, -14810l, -14977l,
  113625. -15136l, -15285l, -15425l, -15556l,
  113626. -15678l, -15790l, -15892l, -15985l,
  113627. -16068l, -16142l, -16206l, -16260l,
  113628. -16304l, -16339l, -16363l, -16378l,
  113629. -16383l,
  113630. };
  113631. #endif
  113632. #endif
  113633. /*** End of inlined file: lookup_data.h ***/
  113634. #ifdef FLOAT_LOOKUP
  113635. /* interpolated lookup based cos function, domain 0 to PI only */
  113636. float vorbis_coslook(float a){
  113637. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  113638. int i=vorbis_ftoi(d-.5);
  113639. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  113640. }
  113641. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  113642. float vorbis_invsqlook(float a){
  113643. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  113644. int i=vorbis_ftoi(d-.5f);
  113645. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  113646. }
  113647. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  113648. float vorbis_invsq2explook(int a){
  113649. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  113650. }
  113651. #include <stdio.h>
  113652. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  113653. float vorbis_fromdBlook(float a){
  113654. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  113655. return (i<0)?1.f:
  113656. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  113657. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  113658. }
  113659. #endif
  113660. #ifdef INT_LOOKUP
  113661. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  113662. 16.16 format
  113663. returns in m.8 format */
  113664. long vorbis_invsqlook_i(long a,long e){
  113665. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  113666. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  113667. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  113668. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  113669. d)>>16); /* result 1.16 */
  113670. e+=32;
  113671. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  113672. e=(e>>1)-8;
  113673. return(val>>e);
  113674. }
  113675. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  113676. /* a is in n.12 format */
  113677. float vorbis_fromdBlook_i(long a){
  113678. int i=(-a)>>(12-FROMdB2_SHIFT);
  113679. return (i<0)?1.f:
  113680. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  113681. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  113682. }
  113683. /* interpolated lookup based cos function, domain 0 to PI only */
  113684. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  113685. long vorbis_coslook_i(long a){
  113686. int i=a>>COS_LOOKUP_I_SHIFT;
  113687. int d=a&COS_LOOKUP_I_MASK;
  113688. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  113689. COS_LOOKUP_I_SHIFT);
  113690. }
  113691. #endif
  113692. #endif
  113693. /*** End of inlined file: lookup.c ***/
  113694. /* catch this in the build system; we #include for
  113695. compilers (like gcc) that can't inline across
  113696. modules */
  113697. /* side effect: changes *lsp to cosines of lsp */
  113698. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  113699. float amp,float ampoffset){
  113700. int i;
  113701. float wdel=M_PI/ln;
  113702. vorbis_fpu_control fpu;
  113703. (void) fpu; // to avoid an unused variable warning
  113704. vorbis_fpu_setround(&fpu);
  113705. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  113706. i=0;
  113707. while(i<n){
  113708. int k=map[i];
  113709. int qexp;
  113710. float p=.7071067812f;
  113711. float q=.7071067812f;
  113712. float w=vorbis_coslook(wdel*k);
  113713. float *ftmp=lsp;
  113714. int c=m>>1;
  113715. do{
  113716. q*=ftmp[0]-w;
  113717. p*=ftmp[1]-w;
  113718. ftmp+=2;
  113719. }while(--c);
  113720. if(m&1){
  113721. /* odd order filter; slightly assymetric */
  113722. /* the last coefficient */
  113723. q*=ftmp[0]-w;
  113724. q*=q;
  113725. p*=p*(1.f-w*w);
  113726. }else{
  113727. /* even order filter; still symmetric */
  113728. q*=q*(1.f+w);
  113729. p*=p*(1.f-w);
  113730. }
  113731. q=frexp(p+q,&qexp);
  113732. q=vorbis_fromdBlook(amp*
  113733. vorbis_invsqlook(q)*
  113734. vorbis_invsq2explook(qexp+m)-
  113735. ampoffset);
  113736. do{
  113737. curve[i++]*=q;
  113738. }while(map[i]==k);
  113739. }
  113740. vorbis_fpu_restore(fpu);
  113741. }
  113742. #else
  113743. #ifdef INT_LOOKUP
  113744. /*** Start of inlined file: lookup.c ***/
  113745. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113746. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113747. // tasks..
  113748. #if JUCE_MSVC
  113749. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113750. #endif
  113751. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113752. #if JUCE_USE_OGGVORBIS
  113753. #include <math.h>
  113754. /*** Start of inlined file: lookup.h ***/
  113755. #ifndef _V_LOOKUP_H_
  113756. #ifdef FLOAT_LOOKUP
  113757. extern float vorbis_coslook(float a);
  113758. extern float vorbis_invsqlook(float a);
  113759. extern float vorbis_invsq2explook(int a);
  113760. extern float vorbis_fromdBlook(float a);
  113761. #endif
  113762. #ifdef INT_LOOKUP
  113763. extern long vorbis_invsqlook_i(long a,long e);
  113764. extern long vorbis_coslook_i(long a);
  113765. extern float vorbis_fromdBlook_i(long a);
  113766. #endif
  113767. #endif
  113768. /*** End of inlined file: lookup.h ***/
  113769. /*** Start of inlined file: lookup_data.h ***/
  113770. #ifndef _V_LOOKUP_DATA_H_
  113771. #ifdef FLOAT_LOOKUP
  113772. #define COS_LOOKUP_SZ 128
  113773. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  113774. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  113775. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  113776. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  113777. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  113778. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  113779. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  113780. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  113781. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  113782. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  113783. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  113784. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  113785. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  113786. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  113787. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  113788. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  113789. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  113790. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  113791. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  113792. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  113793. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  113794. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  113795. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  113796. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  113797. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  113798. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  113799. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  113800. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  113801. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  113802. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  113803. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  113804. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  113805. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  113806. -1.0000000000000f,
  113807. };
  113808. #define INVSQ_LOOKUP_SZ 32
  113809. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  113810. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  113811. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  113812. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  113813. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  113814. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  113815. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  113816. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  113817. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  113818. 1.000000000000f,
  113819. };
  113820. #define INVSQ2EXP_LOOKUP_MIN (-32)
  113821. #define INVSQ2EXP_LOOKUP_MAX 32
  113822. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  113823. INVSQ2EXP_LOOKUP_MIN+1]={
  113824. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  113825. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  113826. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  113827. 1024.f, 724.0773439f, 512.f, 362.038672f,
  113828. 256.f, 181.019336f, 128.f, 90.50966799f,
  113829. 64.f, 45.254834f, 32.f, 22.627417f,
  113830. 16.f, 11.3137085f, 8.f, 5.656854249f,
  113831. 4.f, 2.828427125f, 2.f, 1.414213562f,
  113832. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  113833. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  113834. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  113835. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  113836. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  113837. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  113838. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  113839. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  113840. 1.525878906e-05f,
  113841. };
  113842. #endif
  113843. #define FROMdB_LOOKUP_SZ 35
  113844. #define FROMdB2_LOOKUP_SZ 32
  113845. #define FROMdB_SHIFT 5
  113846. #define FROMdB2_SHIFT 3
  113847. #define FROMdB2_MASK 31
  113848. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  113849. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  113850. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  113851. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  113852. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  113853. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  113854. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  113855. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  113856. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  113857. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  113858. };
  113859. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  113860. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  113861. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  113862. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  113863. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  113864. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  113865. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  113866. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  113867. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  113868. };
  113869. #ifdef INT_LOOKUP
  113870. #define INVSQ_LOOKUP_I_SHIFT 10
  113871. #define INVSQ_LOOKUP_I_MASK 1023
  113872. static long INVSQ_LOOKUP_I[64+1]={
  113873. 92682l, 91966l, 91267l, 90583l,
  113874. 89915l, 89261l, 88621l, 87995l,
  113875. 87381l, 86781l, 86192l, 85616l,
  113876. 85051l, 84497l, 83953l, 83420l,
  113877. 82897l, 82384l, 81880l, 81385l,
  113878. 80899l, 80422l, 79953l, 79492l,
  113879. 79039l, 78594l, 78156l, 77726l,
  113880. 77302l, 76885l, 76475l, 76072l,
  113881. 75674l, 75283l, 74898l, 74519l,
  113882. 74146l, 73778l, 73415l, 73058l,
  113883. 72706l, 72359l, 72016l, 71679l,
  113884. 71347l, 71019l, 70695l, 70376l,
  113885. 70061l, 69750l, 69444l, 69141l,
  113886. 68842l, 68548l, 68256l, 67969l,
  113887. 67685l, 67405l, 67128l, 66855l,
  113888. 66585l, 66318l, 66054l, 65794l,
  113889. 65536l,
  113890. };
  113891. #define COS_LOOKUP_I_SHIFT 9
  113892. #define COS_LOOKUP_I_MASK 511
  113893. #define COS_LOOKUP_I_SZ 128
  113894. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  113895. 16384l, 16379l, 16364l, 16340l,
  113896. 16305l, 16261l, 16207l, 16143l,
  113897. 16069l, 15986l, 15893l, 15791l,
  113898. 15679l, 15557l, 15426l, 15286l,
  113899. 15137l, 14978l, 14811l, 14635l,
  113900. 14449l, 14256l, 14053l, 13842l,
  113901. 13623l, 13395l, 13160l, 12916l,
  113902. 12665l, 12406l, 12140l, 11866l,
  113903. 11585l, 11297l, 11003l, 10702l,
  113904. 10394l, 10080l, 9760l, 9434l,
  113905. 9102l, 8765l, 8423l, 8076l,
  113906. 7723l, 7366l, 7005l, 6639l,
  113907. 6270l, 5897l, 5520l, 5139l,
  113908. 4756l, 4370l, 3981l, 3590l,
  113909. 3196l, 2801l, 2404l, 2006l,
  113910. 1606l, 1205l, 804l, 402l,
  113911. 0l, -401l, -803l, -1204l,
  113912. -1605l, -2005l, -2403l, -2800l,
  113913. -3195l, -3589l, -3980l, -4369l,
  113914. -4755l, -5138l, -5519l, -5896l,
  113915. -6269l, -6638l, -7004l, -7365l,
  113916. -7722l, -8075l, -8422l, -8764l,
  113917. -9101l, -9433l, -9759l, -10079l,
  113918. -10393l, -10701l, -11002l, -11296l,
  113919. -11584l, -11865l, -12139l, -12405l,
  113920. -12664l, -12915l, -13159l, -13394l,
  113921. -13622l, -13841l, -14052l, -14255l,
  113922. -14448l, -14634l, -14810l, -14977l,
  113923. -15136l, -15285l, -15425l, -15556l,
  113924. -15678l, -15790l, -15892l, -15985l,
  113925. -16068l, -16142l, -16206l, -16260l,
  113926. -16304l, -16339l, -16363l, -16378l,
  113927. -16383l,
  113928. };
  113929. #endif
  113930. #endif
  113931. /*** End of inlined file: lookup_data.h ***/
  113932. #ifdef FLOAT_LOOKUP
  113933. /* interpolated lookup based cos function, domain 0 to PI only */
  113934. float vorbis_coslook(float a){
  113935. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  113936. int i=vorbis_ftoi(d-.5);
  113937. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  113938. }
  113939. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  113940. float vorbis_invsqlook(float a){
  113941. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  113942. int i=vorbis_ftoi(d-.5f);
  113943. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  113944. }
  113945. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  113946. float vorbis_invsq2explook(int a){
  113947. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  113948. }
  113949. #include <stdio.h>
  113950. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  113951. float vorbis_fromdBlook(float a){
  113952. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  113953. return (i<0)?1.f:
  113954. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  113955. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  113956. }
  113957. #endif
  113958. #ifdef INT_LOOKUP
  113959. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  113960. 16.16 format
  113961. returns in m.8 format */
  113962. long vorbis_invsqlook_i(long a,long e){
  113963. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  113964. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  113965. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  113966. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  113967. d)>>16); /* result 1.16 */
  113968. e+=32;
  113969. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  113970. e=(e>>1)-8;
  113971. return(val>>e);
  113972. }
  113973. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  113974. /* a is in n.12 format */
  113975. float vorbis_fromdBlook_i(long a){
  113976. int i=(-a)>>(12-FROMdB2_SHIFT);
  113977. return (i<0)?1.f:
  113978. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  113979. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  113980. }
  113981. /* interpolated lookup based cos function, domain 0 to PI only */
  113982. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  113983. long vorbis_coslook_i(long a){
  113984. int i=a>>COS_LOOKUP_I_SHIFT;
  113985. int d=a&COS_LOOKUP_I_MASK;
  113986. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  113987. COS_LOOKUP_I_SHIFT);
  113988. }
  113989. #endif
  113990. #endif
  113991. /*** End of inlined file: lookup.c ***/
  113992. /* catch this in the build system; we #include for
  113993. compilers (like gcc) that can't inline across
  113994. modules */
  113995. static int MLOOP_1[64]={
  113996. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  113997. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  113998. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  113999. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  114000. };
  114001. static int MLOOP_2[64]={
  114002. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  114003. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  114004. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  114005. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  114006. };
  114007. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  114008. /* side effect: changes *lsp to cosines of lsp */
  114009. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114010. float amp,float ampoffset){
  114011. /* 0 <= m < 256 */
  114012. /* set up for using all int later */
  114013. int i;
  114014. int ampoffseti=rint(ampoffset*4096.f);
  114015. int ampi=rint(amp*16.f);
  114016. long *ilsp=alloca(m*sizeof(*ilsp));
  114017. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  114018. i=0;
  114019. while(i<n){
  114020. int j,k=map[i];
  114021. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  114022. unsigned long qi=46341;
  114023. int qexp=0,shift;
  114024. long wi=vorbis_coslook_i(k*65536/ln);
  114025. qi*=labs(ilsp[0]-wi);
  114026. pi*=labs(ilsp[1]-wi);
  114027. for(j=3;j<m;j+=2){
  114028. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114029. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114030. shift=MLOOP_3[(pi|qi)>>16];
  114031. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  114032. pi=(pi>>shift)*labs(ilsp[j]-wi);
  114033. qexp+=shift;
  114034. }
  114035. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114036. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114037. shift=MLOOP_3[(pi|qi)>>16];
  114038. /* pi,qi normalized collectively, both tracked using qexp */
  114039. if(m&1){
  114040. /* odd order filter; slightly assymetric */
  114041. /* the last coefficient */
  114042. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  114043. pi=(pi>>shift)<<14;
  114044. qexp+=shift;
  114045. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114046. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114047. shift=MLOOP_3[(pi|qi)>>16];
  114048. pi>>=shift;
  114049. qi>>=shift;
  114050. qexp+=shift-14*((m+1)>>1);
  114051. pi=((pi*pi)>>16);
  114052. qi=((qi*qi)>>16);
  114053. qexp=qexp*2+m;
  114054. pi*=(1<<14)-((wi*wi)>>14);
  114055. qi+=pi>>14;
  114056. }else{
  114057. /* even order filter; still symmetric */
  114058. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  114059. worth tracking step by step */
  114060. pi>>=shift;
  114061. qi>>=shift;
  114062. qexp+=shift-7*m;
  114063. pi=((pi*pi)>>16);
  114064. qi=((qi*qi)>>16);
  114065. qexp=qexp*2+m;
  114066. pi*=(1<<14)-wi;
  114067. qi*=(1<<14)+wi;
  114068. qi=(qi+pi)>>14;
  114069. }
  114070. /* we've let the normalization drift because it wasn't important;
  114071. however, for the lookup, things must be normalized again. We
  114072. need at most one right shift or a number of left shifts */
  114073. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  114074. qi>>=1; qexp++;
  114075. }else
  114076. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  114077. qi<<=1; qexp--;
  114078. }
  114079. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  114080. vorbis_invsqlook_i(qi,qexp)-
  114081. /* m.8, m+n<=8 */
  114082. ampoffseti); /* 8.12[0] */
  114083. curve[i]*=amp;
  114084. while(map[++i]==k)curve[i]*=amp;
  114085. }
  114086. }
  114087. #else
  114088. /* old, nonoptimized but simple version for any poor sap who needs to
  114089. figure out what the hell this code does, or wants the other
  114090. fraction of a dB precision */
  114091. /* side effect: changes *lsp to cosines of lsp */
  114092. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114093. float amp,float ampoffset){
  114094. int i;
  114095. float wdel=M_PI/ln;
  114096. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  114097. i=0;
  114098. while(i<n){
  114099. int j,k=map[i];
  114100. float p=.5f;
  114101. float q=.5f;
  114102. float w=2.f*cos(wdel*k);
  114103. for(j=1;j<m;j+=2){
  114104. q *= w-lsp[j-1];
  114105. p *= w-lsp[j];
  114106. }
  114107. if(j==m){
  114108. /* odd order filter; slightly assymetric */
  114109. /* the last coefficient */
  114110. q*=w-lsp[j-1];
  114111. p*=p*(4.f-w*w);
  114112. q*=q;
  114113. }else{
  114114. /* even order filter; still symmetric */
  114115. p*=p*(2.f-w);
  114116. q*=q*(2.f+w);
  114117. }
  114118. q=fromdB(amp/sqrt(p+q)-ampoffset);
  114119. curve[i]*=q;
  114120. while(map[++i]==k)curve[i]*=q;
  114121. }
  114122. }
  114123. #endif
  114124. #endif
  114125. static void cheby(float *g, int ord) {
  114126. int i, j;
  114127. g[0] *= .5f;
  114128. for(i=2; i<= ord; i++) {
  114129. for(j=ord; j >= i; j--) {
  114130. g[j-2] -= g[j];
  114131. g[j] += g[j];
  114132. }
  114133. }
  114134. }
  114135. static int comp(const void *a,const void *b){
  114136. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  114137. }
  114138. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  114139. but there are root sets for which it gets into limit cycles
  114140. (exacerbated by zero suppression) and fails. We can't afford to
  114141. fail, even if the failure is 1 in 100,000,000, so we now use
  114142. Laguerre and later polish with Newton-Raphson (which can then
  114143. afford to fail) */
  114144. #define EPSILON 10e-7
  114145. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  114146. int i,m;
  114147. double lastdelta=0.f;
  114148. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  114149. for(i=0;i<=ord;i++)defl[i]=a[i];
  114150. for(m=ord;m>0;m--){
  114151. double newx=0.f,delta;
  114152. /* iterate a root */
  114153. while(1){
  114154. double p=defl[m],pp=0.f,ppp=0.f,denom;
  114155. /* eval the polynomial and its first two derivatives */
  114156. for(i=m;i>0;i--){
  114157. ppp = newx*ppp + pp;
  114158. pp = newx*pp + p;
  114159. p = newx*p + defl[i-1];
  114160. }
  114161. /* Laguerre's method */
  114162. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  114163. if(denom<0)
  114164. return(-1); /* complex root! The LPC generator handed us a bad filter */
  114165. if(pp>0){
  114166. denom = pp + sqrt(denom);
  114167. if(denom<EPSILON)denom=EPSILON;
  114168. }else{
  114169. denom = pp - sqrt(denom);
  114170. if(denom>-(EPSILON))denom=-(EPSILON);
  114171. }
  114172. delta = m*p/denom;
  114173. newx -= delta;
  114174. if(delta<0.f)delta*=-1;
  114175. if(fabs(delta/newx)<10e-12)break;
  114176. lastdelta=delta;
  114177. }
  114178. r[m-1]=newx;
  114179. /* forward deflation */
  114180. for(i=m;i>0;i--)
  114181. defl[i-1]+=newx*defl[i];
  114182. defl++;
  114183. }
  114184. return(0);
  114185. }
  114186. /* for spit-and-polish only */
  114187. static int Newton_Raphson(float *a,int ord,float *r){
  114188. int i, k, count=0;
  114189. double error=1.f;
  114190. double *root=(double*)alloca(ord*sizeof(*root));
  114191. for(i=0; i<ord;i++) root[i] = r[i];
  114192. while(error>1e-20){
  114193. error=0;
  114194. for(i=0; i<ord; i++) { /* Update each point. */
  114195. double pp=0.,delta;
  114196. double rooti=root[i];
  114197. double p=a[ord];
  114198. for(k=ord-1; k>= 0; k--) {
  114199. pp= pp* rooti + p;
  114200. p = p * rooti + a[k];
  114201. }
  114202. delta = p/pp;
  114203. root[i] -= delta;
  114204. error+= delta*delta;
  114205. }
  114206. if(count>40)return(-1);
  114207. count++;
  114208. }
  114209. /* Replaced the original bubble sort with a real sort. With your
  114210. help, we can eliminate the bubble sort in our lifetime. --Monty */
  114211. for(i=0; i<ord;i++) r[i] = root[i];
  114212. return(0);
  114213. }
  114214. /* Convert lpc coefficients to lsp coefficients */
  114215. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  114216. int order2=(m+1)>>1;
  114217. int g1_order,g2_order;
  114218. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  114219. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  114220. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  114221. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  114222. int i;
  114223. /* even and odd are slightly different base cases */
  114224. g1_order=(m+1)>>1;
  114225. g2_order=(m) >>1;
  114226. /* Compute the lengths of the x polynomials. */
  114227. /* Compute the first half of K & R F1 & F2 polynomials. */
  114228. /* Compute half of the symmetric and antisymmetric polynomials. */
  114229. /* Remove the roots at +1 and -1. */
  114230. g1[g1_order] = 1.f;
  114231. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  114232. g2[g2_order] = 1.f;
  114233. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  114234. if(g1_order>g2_order){
  114235. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  114236. }else{
  114237. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  114238. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  114239. }
  114240. /* Convert into polynomials in cos(alpha) */
  114241. cheby(g1,g1_order);
  114242. cheby(g2,g2_order);
  114243. /* Find the roots of the 2 even polynomials.*/
  114244. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  114245. Laguerre_With_Deflation(g2,g2_order,g2r))
  114246. return(-1);
  114247. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  114248. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  114249. qsort(g1r,g1_order,sizeof(*g1r),comp);
  114250. qsort(g2r,g2_order,sizeof(*g2r),comp);
  114251. for(i=0;i<g1_order;i++)
  114252. lsp[i*2] = acos(g1r[i]);
  114253. for(i=0;i<g2_order;i++)
  114254. lsp[i*2+1] = acos(g2r[i]);
  114255. return(0);
  114256. }
  114257. #endif
  114258. /*** End of inlined file: lsp.c ***/
  114259. /*** Start of inlined file: mapping0.c ***/
  114260. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114261. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114262. // tasks..
  114263. #if JUCE_MSVC
  114264. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114265. #endif
  114266. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114267. #if JUCE_USE_OGGVORBIS
  114268. #include <stdlib.h>
  114269. #include <stdio.h>
  114270. #include <string.h>
  114271. #include <math.h>
  114272. /* simplistic, wasteful way of doing this (unique lookup for each
  114273. mode/submapping); there should be a central repository for
  114274. identical lookups. That will require minor work, so I'm putting it
  114275. off as low priority.
  114276. Why a lookup for each backend in a given mode? Because the
  114277. blocksize is set by the mode, and low backend lookups may require
  114278. parameters from other areas of the mode/mapping */
  114279. static void mapping0_free_info(vorbis_info_mapping *i){
  114280. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  114281. if(info){
  114282. memset(info,0,sizeof(*info));
  114283. _ogg_free(info);
  114284. }
  114285. }
  114286. static int ilog3(unsigned int v){
  114287. int ret=0;
  114288. if(v)--v;
  114289. while(v){
  114290. ret++;
  114291. v>>=1;
  114292. }
  114293. return(ret);
  114294. }
  114295. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  114296. oggpack_buffer *opb){
  114297. int i;
  114298. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  114299. /* another 'we meant to do it this way' hack... up to beta 4, we
  114300. packed 4 binary zeros here to signify one submapping in use. We
  114301. now redefine that to mean four bitflags that indicate use of
  114302. deeper features; bit0:submappings, bit1:coupling,
  114303. bit2,3:reserved. This is backward compatable with all actual uses
  114304. of the beta code. */
  114305. if(info->submaps>1){
  114306. oggpack_write(opb,1,1);
  114307. oggpack_write(opb,info->submaps-1,4);
  114308. }else
  114309. oggpack_write(opb,0,1);
  114310. if(info->coupling_steps>0){
  114311. oggpack_write(opb,1,1);
  114312. oggpack_write(opb,info->coupling_steps-1,8);
  114313. for(i=0;i<info->coupling_steps;i++){
  114314. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  114315. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  114316. }
  114317. }else
  114318. oggpack_write(opb,0,1);
  114319. oggpack_write(opb,0,2); /* 2,3:reserved */
  114320. /* we don't write the channel submappings if we only have one... */
  114321. if(info->submaps>1){
  114322. for(i=0;i<vi->channels;i++)
  114323. oggpack_write(opb,info->chmuxlist[i],4);
  114324. }
  114325. for(i=0;i<info->submaps;i++){
  114326. oggpack_write(opb,0,8); /* time submap unused */
  114327. oggpack_write(opb,info->floorsubmap[i],8);
  114328. oggpack_write(opb,info->residuesubmap[i],8);
  114329. }
  114330. }
  114331. /* also responsible for range checking */
  114332. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  114333. int i;
  114334. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  114335. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114336. memset(info,0,sizeof(*info));
  114337. if(oggpack_read(opb,1))
  114338. info->submaps=oggpack_read(opb,4)+1;
  114339. else
  114340. info->submaps=1;
  114341. if(oggpack_read(opb,1)){
  114342. info->coupling_steps=oggpack_read(opb,8)+1;
  114343. for(i=0;i<info->coupling_steps;i++){
  114344. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  114345. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  114346. if(testM<0 ||
  114347. testA<0 ||
  114348. testM==testA ||
  114349. testM>=vi->channels ||
  114350. testA>=vi->channels) goto err_out;
  114351. }
  114352. }
  114353. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  114354. if(info->submaps>1){
  114355. for(i=0;i<vi->channels;i++){
  114356. info->chmuxlist[i]=oggpack_read(opb,4);
  114357. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  114358. }
  114359. }
  114360. for(i=0;i<info->submaps;i++){
  114361. oggpack_read(opb,8); /* time submap unused */
  114362. info->floorsubmap[i]=oggpack_read(opb,8);
  114363. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  114364. info->residuesubmap[i]=oggpack_read(opb,8);
  114365. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  114366. }
  114367. return info;
  114368. err_out:
  114369. mapping0_free_info(info);
  114370. return(NULL);
  114371. }
  114372. #if 0
  114373. static long seq=0;
  114374. static ogg_int64_t total=0;
  114375. static float FLOOR1_fromdB_LOOKUP[256]={
  114376. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  114377. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  114378. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  114379. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  114380. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  114381. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  114382. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  114383. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  114384. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  114385. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  114386. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  114387. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  114388. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  114389. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  114390. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  114391. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  114392. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  114393. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  114394. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  114395. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  114396. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  114397. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  114398. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  114399. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  114400. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  114401. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  114402. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  114403. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  114404. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  114405. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  114406. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  114407. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  114408. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  114409. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  114410. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  114411. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  114412. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  114413. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  114414. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  114415. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  114416. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  114417. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  114418. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  114419. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  114420. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  114421. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  114422. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  114423. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  114424. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  114425. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  114426. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  114427. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  114428. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  114429. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  114430. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  114431. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  114432. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  114433. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  114434. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  114435. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  114436. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  114437. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  114438. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  114439. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  114440. };
  114441. #endif
  114442. extern int *floor1_fit(vorbis_block *vb,void *look,
  114443. const float *logmdct, /* in */
  114444. const float *logmask);
  114445. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  114446. int *A,int *B,
  114447. int del);
  114448. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  114449. void*look,
  114450. int *post,int *ilogmask);
  114451. static int mapping0_forward(vorbis_block *vb){
  114452. vorbis_dsp_state *vd=vb->vd;
  114453. vorbis_info *vi=vd->vi;
  114454. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114455. private_state *b=(private_state*)vb->vd->backend_state;
  114456. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  114457. int n=vb->pcmend;
  114458. int i,j,k;
  114459. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  114460. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  114461. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  114462. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  114463. float global_ampmax=vbi->ampmax;
  114464. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  114465. int blocktype=vbi->blocktype;
  114466. int modenumber=vb->W;
  114467. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  114468. vorbis_look_psy *psy_look=
  114469. b->psy+blocktype+(vb->W?2:0);
  114470. vb->mode=modenumber;
  114471. for(i=0;i<vi->channels;i++){
  114472. float scale=4.f/n;
  114473. float scale_dB;
  114474. float *pcm =vb->pcm[i];
  114475. float *logfft =pcm;
  114476. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  114477. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  114478. todB estimation used on IEEE 754
  114479. compliant machines had a bug that
  114480. returned dB values about a third
  114481. of a decibel too high. The bug
  114482. was harmless because tunings
  114483. implicitly took that into
  114484. account. However, fixing the bug
  114485. in the estimator requires
  114486. changing all the tunings as well.
  114487. For now, it's easier to sync
  114488. things back up here, and
  114489. recalibrate the tunings in the
  114490. next major model upgrade. */
  114491. #if 0
  114492. if(vi->channels==2)
  114493. if(i==0)
  114494. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  114495. else
  114496. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  114497. #endif
  114498. /* window the PCM data */
  114499. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  114500. #if 0
  114501. if(vi->channels==2)
  114502. if(i==0)
  114503. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  114504. else
  114505. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  114506. #endif
  114507. /* transform the PCM data */
  114508. /* only MDCT right now.... */
  114509. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  114510. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  114511. drft_forward(&b->fft_look[vb->W],pcm);
  114512. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  114513. original todB estimation used on
  114514. IEEE 754 compliant machines had a
  114515. bug that returned dB values about
  114516. a third of a decibel too high.
  114517. The bug was harmless because
  114518. tunings implicitly took that into
  114519. account. However, fixing the bug
  114520. in the estimator requires
  114521. changing all the tunings as well.
  114522. For now, it's easier to sync
  114523. things back up here, and
  114524. recalibrate the tunings in the
  114525. next major model upgrade. */
  114526. local_ampmax[i]=logfft[0];
  114527. for(j=1;j<n-1;j+=2){
  114528. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  114529. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  114530. .345 is a hack; the original todB
  114531. estimation used on IEEE 754
  114532. compliant machines had a bug that
  114533. returned dB values about a third
  114534. of a decibel too high. The bug
  114535. was harmless because tunings
  114536. implicitly took that into
  114537. account. However, fixing the bug
  114538. in the estimator requires
  114539. changing all the tunings as well.
  114540. For now, it's easier to sync
  114541. things back up here, and
  114542. recalibrate the tunings in the
  114543. next major model upgrade. */
  114544. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  114545. }
  114546. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  114547. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  114548. #if 0
  114549. if(vi->channels==2){
  114550. if(i==0){
  114551. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  114552. }else{
  114553. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  114554. }
  114555. }
  114556. #endif
  114557. }
  114558. {
  114559. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  114560. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  114561. for(i=0;i<vi->channels;i++){
  114562. /* the encoder setup assumes that all the modes used by any
  114563. specific bitrate tweaking use the same floor */
  114564. int submap=info->chmuxlist[i];
  114565. /* the following makes things clearer to *me* anyway */
  114566. float *mdct =gmdct[i];
  114567. float *logfft =vb->pcm[i];
  114568. float *logmdct =logfft+n/2;
  114569. float *logmask =logfft;
  114570. vb->mode=modenumber;
  114571. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  114572. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  114573. for(j=0;j<n/2;j++)
  114574. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  114575. todB estimation used on IEEE 754
  114576. compliant machines had a bug that
  114577. returned dB values about a third
  114578. of a decibel too high. The bug
  114579. was harmless because tunings
  114580. implicitly took that into
  114581. account. However, fixing the bug
  114582. in the estimator requires
  114583. changing all the tunings as well.
  114584. For now, it's easier to sync
  114585. things back up here, and
  114586. recalibrate the tunings in the
  114587. next major model upgrade. */
  114588. #if 0
  114589. if(vi->channels==2){
  114590. if(i==0)
  114591. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  114592. else
  114593. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  114594. }else{
  114595. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  114596. }
  114597. #endif
  114598. /* first step; noise masking. Not only does 'noise masking'
  114599. give us curves from which we can decide how much resolution
  114600. to give noise parts of the spectrum, it also implicitly hands
  114601. us a tonality estimate (the larger the value in the
  114602. 'noise_depth' vector, the more tonal that area is) */
  114603. _vp_noisemask(psy_look,
  114604. logmdct,
  114605. noise); /* noise does not have by-frequency offset
  114606. bias applied yet */
  114607. #if 0
  114608. if(vi->channels==2){
  114609. if(i==0)
  114610. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  114611. else
  114612. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  114613. }
  114614. #endif
  114615. /* second step: 'all the other crap'; all the stuff that isn't
  114616. computed/fit for bitrate management goes in the second psy
  114617. vector. This includes tone masking, peak limiting and ATH */
  114618. _vp_tonemask(psy_look,
  114619. logfft,
  114620. tone,
  114621. global_ampmax,
  114622. local_ampmax[i]);
  114623. #if 0
  114624. if(vi->channels==2){
  114625. if(i==0)
  114626. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  114627. else
  114628. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  114629. }
  114630. #endif
  114631. /* third step; we offset the noise vectors, overlay tone
  114632. masking. We then do a floor1-specific line fit. If we're
  114633. performing bitrate management, the line fit is performed
  114634. multiple times for up/down tweakage on demand. */
  114635. #if 0
  114636. {
  114637. float aotuv[psy_look->n];
  114638. #endif
  114639. _vp_offset_and_mix(psy_look,
  114640. noise,
  114641. tone,
  114642. 1,
  114643. logmask,
  114644. mdct,
  114645. logmdct);
  114646. #if 0
  114647. if(vi->channels==2){
  114648. if(i==0)
  114649. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  114650. else
  114651. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  114652. }
  114653. }
  114654. #endif
  114655. #if 0
  114656. if(vi->channels==2){
  114657. if(i==0)
  114658. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  114659. else
  114660. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  114661. }
  114662. #endif
  114663. /* this algorithm is hardwired to floor 1 for now; abort out if
  114664. we're *not* floor1. This won't happen unless someone has
  114665. broken the encode setup lib. Guard it anyway. */
  114666. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  114667. floor_posts[i][PACKETBLOBS/2]=
  114668. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  114669. logmdct,
  114670. logmask);
  114671. /* are we managing bitrate? If so, perform two more fits for
  114672. later rate tweaking (fits represent hi/lo) */
  114673. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  114674. /* higher rate by way of lower noise curve */
  114675. _vp_offset_and_mix(psy_look,
  114676. noise,
  114677. tone,
  114678. 2,
  114679. logmask,
  114680. mdct,
  114681. logmdct);
  114682. #if 0
  114683. if(vi->channels==2){
  114684. if(i==0)
  114685. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  114686. else
  114687. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  114688. }
  114689. #endif
  114690. floor_posts[i][PACKETBLOBS-1]=
  114691. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  114692. logmdct,
  114693. logmask);
  114694. /* lower rate by way of higher noise curve */
  114695. _vp_offset_and_mix(psy_look,
  114696. noise,
  114697. tone,
  114698. 0,
  114699. logmask,
  114700. mdct,
  114701. logmdct);
  114702. #if 0
  114703. if(vi->channels==2)
  114704. if(i==0)
  114705. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  114706. else
  114707. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  114708. #endif
  114709. floor_posts[i][0]=
  114710. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  114711. logmdct,
  114712. logmask);
  114713. /* we also interpolate a range of intermediate curves for
  114714. intermediate rates */
  114715. for(k=1;k<PACKETBLOBS/2;k++)
  114716. floor_posts[i][k]=
  114717. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  114718. floor_posts[i][0],
  114719. floor_posts[i][PACKETBLOBS/2],
  114720. k*65536/(PACKETBLOBS/2));
  114721. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  114722. floor_posts[i][k]=
  114723. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  114724. floor_posts[i][PACKETBLOBS/2],
  114725. floor_posts[i][PACKETBLOBS-1],
  114726. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  114727. }
  114728. }
  114729. }
  114730. vbi->ampmax=global_ampmax;
  114731. /*
  114732. the next phases are performed once for vbr-only and PACKETBLOB
  114733. times for bitrate managed modes.
  114734. 1) encode actual mode being used
  114735. 2) encode the floor for each channel, compute coded mask curve/res
  114736. 3) normalize and couple.
  114737. 4) encode residue
  114738. 5) save packet bytes to the packetblob vector
  114739. */
  114740. /* iterate over the many masking curve fits we've created */
  114741. {
  114742. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  114743. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  114744. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  114745. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  114746. float **mag_memo;
  114747. int **mag_sort;
  114748. if(info->coupling_steps){
  114749. mag_memo=_vp_quantize_couple_memo(vb,
  114750. &ci->psy_g_param,
  114751. psy_look,
  114752. info,
  114753. gmdct);
  114754. mag_sort=_vp_quantize_couple_sort(vb,
  114755. psy_look,
  114756. info,
  114757. mag_memo);
  114758. hf_reduction(&ci->psy_g_param,
  114759. psy_look,
  114760. info,
  114761. mag_memo);
  114762. }
  114763. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  114764. if(psy_look->vi->normal_channel_p){
  114765. for(i=0;i<vi->channels;i++){
  114766. float *mdct =gmdct[i];
  114767. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  114768. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  114769. }
  114770. }
  114771. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  114772. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  114773. k++){
  114774. oggpack_buffer *opb=vbi->packetblob[k];
  114775. /* start out our new packet blob with packet type and mode */
  114776. /* Encode the packet type */
  114777. oggpack_write(opb,0,1);
  114778. /* Encode the modenumber */
  114779. /* Encode frame mode, pre,post windowsize, then dispatch */
  114780. oggpack_write(opb,modenumber,b->modebits);
  114781. if(vb->W){
  114782. oggpack_write(opb,vb->lW,1);
  114783. oggpack_write(opb,vb->nW,1);
  114784. }
  114785. /* encode floor, compute masking curve, sep out residue */
  114786. for(i=0;i<vi->channels;i++){
  114787. int submap=info->chmuxlist[i];
  114788. float *mdct =gmdct[i];
  114789. float *res =vb->pcm[i];
  114790. int *ilogmask=ilogmaskch[i]=
  114791. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  114792. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  114793. floor_posts[i][k],
  114794. ilogmask);
  114795. #if 0
  114796. {
  114797. char buf[80];
  114798. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  114799. float work[n/2];
  114800. for(j=0;j<n/2;j++)
  114801. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  114802. _analysis_output(buf,seq,work,n/2,1,1,0);
  114803. }
  114804. #endif
  114805. _vp_remove_floor(psy_look,
  114806. mdct,
  114807. ilogmask,
  114808. res,
  114809. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  114810. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  114811. #if 0
  114812. {
  114813. char buf[80];
  114814. float work[n/2];
  114815. for(j=0;j<n/2;j++)
  114816. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  114817. sprintf(buf,"resI%c%d",i?'R':'L',k);
  114818. _analysis_output(buf,seq,work,n/2,1,1,0);
  114819. }
  114820. #endif
  114821. }
  114822. /* our iteration is now based on masking curve, not prequant and
  114823. coupling. Only one prequant/coupling step */
  114824. /* quantize/couple */
  114825. /* incomplete implementation that assumes the tree is all depth
  114826. one, or no tree at all */
  114827. if(info->coupling_steps){
  114828. _vp_couple(k,
  114829. &ci->psy_g_param,
  114830. psy_look,
  114831. info,
  114832. vb->pcm,
  114833. mag_memo,
  114834. mag_sort,
  114835. ilogmaskch,
  114836. nonzero,
  114837. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  114838. }
  114839. /* classify and encode by submap */
  114840. for(i=0;i<info->submaps;i++){
  114841. int ch_in_bundle=0;
  114842. long **classifications;
  114843. int resnum=info->residuesubmap[i];
  114844. for(j=0;j<vi->channels;j++){
  114845. if(info->chmuxlist[j]==i){
  114846. zerobundle[ch_in_bundle]=0;
  114847. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  114848. res_bundle[ch_in_bundle]=vb->pcm[j];
  114849. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  114850. }
  114851. }
  114852. classifications=_residue_P[ci->residue_type[resnum]]->
  114853. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  114854. _residue_P[ci->residue_type[resnum]]->
  114855. forward(opb,vb,b->residue[resnum],
  114856. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  114857. }
  114858. /* ok, done encoding. Next protopacket. */
  114859. }
  114860. }
  114861. #if 0
  114862. seq++;
  114863. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  114864. #endif
  114865. return(0);
  114866. }
  114867. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  114868. vorbis_dsp_state *vd=vb->vd;
  114869. vorbis_info *vi=vd->vi;
  114870. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  114871. private_state *b=(private_state*)vd->backend_state;
  114872. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  114873. int i,j;
  114874. long n=vb->pcmend=ci->blocksizes[vb->W];
  114875. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  114876. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  114877. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  114878. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  114879. /* recover the spectral envelope; store it in the PCM vector for now */
  114880. for(i=0;i<vi->channels;i++){
  114881. int submap=info->chmuxlist[i];
  114882. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  114883. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  114884. if(floormemo[i])
  114885. nonzero[i]=1;
  114886. else
  114887. nonzero[i]=0;
  114888. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  114889. }
  114890. /* channel coupling can 'dirty' the nonzero listing */
  114891. for(i=0;i<info->coupling_steps;i++){
  114892. if(nonzero[info->coupling_mag[i]] ||
  114893. nonzero[info->coupling_ang[i]]){
  114894. nonzero[info->coupling_mag[i]]=1;
  114895. nonzero[info->coupling_ang[i]]=1;
  114896. }
  114897. }
  114898. /* recover the residue into our working vectors */
  114899. for(i=0;i<info->submaps;i++){
  114900. int ch_in_bundle=0;
  114901. for(j=0;j<vi->channels;j++){
  114902. if(info->chmuxlist[j]==i){
  114903. if(nonzero[j])
  114904. zerobundle[ch_in_bundle]=1;
  114905. else
  114906. zerobundle[ch_in_bundle]=0;
  114907. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  114908. }
  114909. }
  114910. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  114911. inverse(vb,b->residue[info->residuesubmap[i]],
  114912. pcmbundle,zerobundle,ch_in_bundle);
  114913. }
  114914. /* channel coupling */
  114915. for(i=info->coupling_steps-1;i>=0;i--){
  114916. float *pcmM=vb->pcm[info->coupling_mag[i]];
  114917. float *pcmA=vb->pcm[info->coupling_ang[i]];
  114918. for(j=0;j<n/2;j++){
  114919. float mag=pcmM[j];
  114920. float ang=pcmA[j];
  114921. if(mag>0)
  114922. if(ang>0){
  114923. pcmM[j]=mag;
  114924. pcmA[j]=mag-ang;
  114925. }else{
  114926. pcmA[j]=mag;
  114927. pcmM[j]=mag+ang;
  114928. }
  114929. else
  114930. if(ang>0){
  114931. pcmM[j]=mag;
  114932. pcmA[j]=mag+ang;
  114933. }else{
  114934. pcmA[j]=mag;
  114935. pcmM[j]=mag-ang;
  114936. }
  114937. }
  114938. }
  114939. /* compute and apply spectral envelope */
  114940. for(i=0;i<vi->channels;i++){
  114941. float *pcm=vb->pcm[i];
  114942. int submap=info->chmuxlist[i];
  114943. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  114944. inverse2(vb,b->flr[info->floorsubmap[submap]],
  114945. floormemo[i],pcm);
  114946. }
  114947. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  114948. /* only MDCT right now.... */
  114949. for(i=0;i<vi->channels;i++){
  114950. float *pcm=vb->pcm[i];
  114951. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  114952. }
  114953. /* all done! */
  114954. return(0);
  114955. }
  114956. /* export hooks */
  114957. vorbis_func_mapping mapping0_exportbundle={
  114958. &mapping0_pack,
  114959. &mapping0_unpack,
  114960. &mapping0_free_info,
  114961. &mapping0_forward,
  114962. &mapping0_inverse
  114963. };
  114964. #endif
  114965. /*** End of inlined file: mapping0.c ***/
  114966. /*** Start of inlined file: mdct.c ***/
  114967. /* this can also be run as an integer transform by uncommenting a
  114968. define in mdct.h; the integerization is a first pass and although
  114969. it's likely stable for Vorbis, the dynamic range is constrained and
  114970. roundoff isn't done (so it's noisy). Consider it functional, but
  114971. only a starting point. There's no point on a machine with an FPU */
  114972. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114973. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114974. // tasks..
  114975. #if JUCE_MSVC
  114976. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114977. #endif
  114978. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114979. #if JUCE_USE_OGGVORBIS
  114980. #include <stdio.h>
  114981. #include <stdlib.h>
  114982. #include <string.h>
  114983. #include <math.h>
  114984. /* build lookups for trig functions; also pre-figure scaling and
  114985. some window function algebra. */
  114986. void mdct_init(mdct_lookup *lookup,int n){
  114987. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  114988. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  114989. int i;
  114990. int n2=n>>1;
  114991. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  114992. lookup->n=n;
  114993. lookup->trig=T;
  114994. lookup->bitrev=bitrev;
  114995. /* trig lookups... */
  114996. for(i=0;i<n/4;i++){
  114997. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  114998. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  114999. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  115000. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  115001. }
  115002. for(i=0;i<n/8;i++){
  115003. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  115004. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  115005. }
  115006. /* bitreverse lookup... */
  115007. {
  115008. int mask=(1<<(log2n-1))-1,i,j;
  115009. int msb=1<<(log2n-2);
  115010. for(i=0;i<n/8;i++){
  115011. int acc=0;
  115012. for(j=0;msb>>j;j++)
  115013. if((msb>>j)&i)acc|=1<<j;
  115014. bitrev[i*2]=((~acc)&mask)-1;
  115015. bitrev[i*2+1]=acc;
  115016. }
  115017. }
  115018. lookup->scale=FLOAT_CONV(4.f/n);
  115019. }
  115020. /* 8 point butterfly (in place, 4 register) */
  115021. STIN void mdct_butterfly_8(DATA_TYPE *x){
  115022. REG_TYPE r0 = x[6] + x[2];
  115023. REG_TYPE r1 = x[6] - x[2];
  115024. REG_TYPE r2 = x[4] + x[0];
  115025. REG_TYPE r3 = x[4] - x[0];
  115026. x[6] = r0 + r2;
  115027. x[4] = r0 - r2;
  115028. r0 = x[5] - x[1];
  115029. r2 = x[7] - x[3];
  115030. x[0] = r1 + r0;
  115031. x[2] = r1 - r0;
  115032. r0 = x[5] + x[1];
  115033. r1 = x[7] + x[3];
  115034. x[3] = r2 + r3;
  115035. x[1] = r2 - r3;
  115036. x[7] = r1 + r0;
  115037. x[5] = r1 - r0;
  115038. }
  115039. /* 16 point butterfly (in place, 4 register) */
  115040. STIN void mdct_butterfly_16(DATA_TYPE *x){
  115041. REG_TYPE r0 = x[1] - x[9];
  115042. REG_TYPE r1 = x[0] - x[8];
  115043. x[8] += x[0];
  115044. x[9] += x[1];
  115045. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  115046. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  115047. r0 = x[3] - x[11];
  115048. r1 = x[10] - x[2];
  115049. x[10] += x[2];
  115050. x[11] += x[3];
  115051. x[2] = r0;
  115052. x[3] = r1;
  115053. r0 = x[12] - x[4];
  115054. r1 = x[13] - x[5];
  115055. x[12] += x[4];
  115056. x[13] += x[5];
  115057. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  115058. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  115059. r0 = x[14] - x[6];
  115060. r1 = x[15] - x[7];
  115061. x[14] += x[6];
  115062. x[15] += x[7];
  115063. x[6] = r0;
  115064. x[7] = r1;
  115065. mdct_butterfly_8(x);
  115066. mdct_butterfly_8(x+8);
  115067. }
  115068. /* 32 point butterfly (in place, 4 register) */
  115069. STIN void mdct_butterfly_32(DATA_TYPE *x){
  115070. REG_TYPE r0 = x[30] - x[14];
  115071. REG_TYPE r1 = x[31] - x[15];
  115072. x[30] += x[14];
  115073. x[31] += x[15];
  115074. x[14] = r0;
  115075. x[15] = r1;
  115076. r0 = x[28] - x[12];
  115077. r1 = x[29] - x[13];
  115078. x[28] += x[12];
  115079. x[29] += x[13];
  115080. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  115081. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  115082. r0 = x[26] - x[10];
  115083. r1 = x[27] - x[11];
  115084. x[26] += x[10];
  115085. x[27] += x[11];
  115086. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  115087. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  115088. r0 = x[24] - x[8];
  115089. r1 = x[25] - x[9];
  115090. x[24] += x[8];
  115091. x[25] += x[9];
  115092. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  115093. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  115094. r0 = x[22] - x[6];
  115095. r1 = x[7] - x[23];
  115096. x[22] += x[6];
  115097. x[23] += x[7];
  115098. x[6] = r1;
  115099. x[7] = r0;
  115100. r0 = x[4] - x[20];
  115101. r1 = x[5] - x[21];
  115102. x[20] += x[4];
  115103. x[21] += x[5];
  115104. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  115105. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  115106. r0 = x[2] - x[18];
  115107. r1 = x[3] - x[19];
  115108. x[18] += x[2];
  115109. x[19] += x[3];
  115110. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  115111. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  115112. r0 = x[0] - x[16];
  115113. r1 = x[1] - x[17];
  115114. x[16] += x[0];
  115115. x[17] += x[1];
  115116. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  115117. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  115118. mdct_butterfly_16(x);
  115119. mdct_butterfly_16(x+16);
  115120. }
  115121. /* N point first stage butterfly (in place, 2 register) */
  115122. STIN void mdct_butterfly_first(DATA_TYPE *T,
  115123. DATA_TYPE *x,
  115124. int points){
  115125. DATA_TYPE *x1 = x + points - 8;
  115126. DATA_TYPE *x2 = x + (points>>1) - 8;
  115127. REG_TYPE r0;
  115128. REG_TYPE r1;
  115129. do{
  115130. r0 = x1[6] - x2[6];
  115131. r1 = x1[7] - x2[7];
  115132. x1[6] += x2[6];
  115133. x1[7] += x2[7];
  115134. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115135. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115136. r0 = x1[4] - x2[4];
  115137. r1 = x1[5] - x2[5];
  115138. x1[4] += x2[4];
  115139. x1[5] += x2[5];
  115140. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  115141. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  115142. r0 = x1[2] - x2[2];
  115143. r1 = x1[3] - x2[3];
  115144. x1[2] += x2[2];
  115145. x1[3] += x2[3];
  115146. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  115147. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  115148. r0 = x1[0] - x2[0];
  115149. r1 = x1[1] - x2[1];
  115150. x1[0] += x2[0];
  115151. x1[1] += x2[1];
  115152. x2[0] = MULT_NORM(r1 * T[13] + r0 * T[12]);
  115153. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  115154. x1-=8;
  115155. x2-=8;
  115156. T+=16;
  115157. }while(x2>=x);
  115158. }
  115159. /* N/stage point generic N stage butterfly (in place, 2 register) */
  115160. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  115161. DATA_TYPE *x,
  115162. int points,
  115163. int trigint){
  115164. DATA_TYPE *x1 = x + points - 8;
  115165. DATA_TYPE *x2 = x + (points>>1) - 8;
  115166. REG_TYPE r0;
  115167. REG_TYPE r1;
  115168. do{
  115169. r0 = x1[6] - x2[6];
  115170. r1 = x1[7] - x2[7];
  115171. x1[6] += x2[6];
  115172. x1[7] += x2[7];
  115173. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115174. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115175. T+=trigint;
  115176. r0 = x1[4] - x2[4];
  115177. r1 = x1[5] - x2[5];
  115178. x1[4] += x2[4];
  115179. x1[5] += x2[5];
  115180. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115181. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115182. T+=trigint;
  115183. r0 = x1[2] - x2[2];
  115184. r1 = x1[3] - x2[3];
  115185. x1[2] += x2[2];
  115186. x1[3] += x2[3];
  115187. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115188. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115189. T+=trigint;
  115190. r0 = x1[0] - x2[0];
  115191. r1 = x1[1] - x2[1];
  115192. x1[0] += x2[0];
  115193. x1[1] += x2[1];
  115194. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115195. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115196. T+=trigint;
  115197. x1-=8;
  115198. x2-=8;
  115199. }while(x2>=x);
  115200. }
  115201. STIN void mdct_butterflies(mdct_lookup *init,
  115202. DATA_TYPE *x,
  115203. int points){
  115204. DATA_TYPE *T=init->trig;
  115205. int stages=init->log2n-5;
  115206. int i,j;
  115207. if(--stages>0){
  115208. mdct_butterfly_first(T,x,points);
  115209. }
  115210. for(i=1;--stages>0;i++){
  115211. for(j=0;j<(1<<i);j++)
  115212. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  115213. }
  115214. for(j=0;j<points;j+=32)
  115215. mdct_butterfly_32(x+j);
  115216. }
  115217. void mdct_clear(mdct_lookup *l){
  115218. if(l){
  115219. if(l->trig)_ogg_free(l->trig);
  115220. if(l->bitrev)_ogg_free(l->bitrev);
  115221. memset(l,0,sizeof(*l));
  115222. }
  115223. }
  115224. STIN void mdct_bitreverse(mdct_lookup *init,
  115225. DATA_TYPE *x){
  115226. int n = init->n;
  115227. int *bit = init->bitrev;
  115228. DATA_TYPE *w0 = x;
  115229. DATA_TYPE *w1 = x = w0+(n>>1);
  115230. DATA_TYPE *T = init->trig+n;
  115231. do{
  115232. DATA_TYPE *x0 = x+bit[0];
  115233. DATA_TYPE *x1 = x+bit[1];
  115234. REG_TYPE r0 = x0[1] - x1[1];
  115235. REG_TYPE r1 = x0[0] + x1[0];
  115236. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  115237. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  115238. w1 -= 4;
  115239. r0 = HALVE(x0[1] + x1[1]);
  115240. r1 = HALVE(x0[0] - x1[0]);
  115241. w0[0] = r0 + r2;
  115242. w1[2] = r0 - r2;
  115243. w0[1] = r1 + r3;
  115244. w1[3] = r3 - r1;
  115245. x0 = x+bit[2];
  115246. x1 = x+bit[3];
  115247. r0 = x0[1] - x1[1];
  115248. r1 = x0[0] + x1[0];
  115249. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  115250. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  115251. r0 = HALVE(x0[1] + x1[1]);
  115252. r1 = HALVE(x0[0] - x1[0]);
  115253. w0[2] = r0 + r2;
  115254. w1[0] = r0 - r2;
  115255. w0[3] = r1 + r3;
  115256. w1[1] = r3 - r1;
  115257. T += 4;
  115258. bit += 4;
  115259. w0 += 4;
  115260. }while(w0<w1);
  115261. }
  115262. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  115263. int n=init->n;
  115264. int n2=n>>1;
  115265. int n4=n>>2;
  115266. /* rotate */
  115267. DATA_TYPE *iX = in+n2-7;
  115268. DATA_TYPE *oX = out+n2+n4;
  115269. DATA_TYPE *T = init->trig+n4;
  115270. do{
  115271. oX -= 4;
  115272. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  115273. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  115274. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  115275. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  115276. iX -= 8;
  115277. T += 4;
  115278. }while(iX>=in);
  115279. iX = in+n2-8;
  115280. oX = out+n2+n4;
  115281. T = init->trig+n4;
  115282. do{
  115283. T -= 4;
  115284. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  115285. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  115286. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  115287. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  115288. iX -= 8;
  115289. oX += 4;
  115290. }while(iX>=in);
  115291. mdct_butterflies(init,out+n2,n2);
  115292. mdct_bitreverse(init,out);
  115293. /* roatate + window */
  115294. {
  115295. DATA_TYPE *oX1=out+n2+n4;
  115296. DATA_TYPE *oX2=out+n2+n4;
  115297. DATA_TYPE *iX =out;
  115298. T =init->trig+n2;
  115299. do{
  115300. oX1-=4;
  115301. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  115302. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  115303. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  115304. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  115305. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  115306. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  115307. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  115308. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  115309. oX2+=4;
  115310. iX += 8;
  115311. T += 8;
  115312. }while(iX<oX1);
  115313. iX=out+n2+n4;
  115314. oX1=out+n4;
  115315. oX2=oX1;
  115316. do{
  115317. oX1-=4;
  115318. iX-=4;
  115319. oX2[0] = -(oX1[3] = iX[3]);
  115320. oX2[1] = -(oX1[2] = iX[2]);
  115321. oX2[2] = -(oX1[1] = iX[1]);
  115322. oX2[3] = -(oX1[0] = iX[0]);
  115323. oX2+=4;
  115324. }while(oX2<iX);
  115325. iX=out+n2+n4;
  115326. oX1=out+n2+n4;
  115327. oX2=out+n2;
  115328. do{
  115329. oX1-=4;
  115330. oX1[0]= iX[3];
  115331. oX1[1]= iX[2];
  115332. oX1[2]= iX[1];
  115333. oX1[3]= iX[0];
  115334. iX+=4;
  115335. }while(oX1>oX2);
  115336. }
  115337. }
  115338. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  115339. int n=init->n;
  115340. int n2=n>>1;
  115341. int n4=n>>2;
  115342. int n8=n>>3;
  115343. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  115344. DATA_TYPE *w2=w+n2;
  115345. /* rotate */
  115346. /* window + rotate + step 1 */
  115347. REG_TYPE r0;
  115348. REG_TYPE r1;
  115349. DATA_TYPE *x0=in+n2+n4;
  115350. DATA_TYPE *x1=x0+1;
  115351. DATA_TYPE *T=init->trig+n2;
  115352. int i=0;
  115353. for(i=0;i<n8;i+=2){
  115354. x0 -=4;
  115355. T-=2;
  115356. r0= x0[2] + x1[0];
  115357. r1= x0[0] + x1[2];
  115358. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  115359. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  115360. x1 +=4;
  115361. }
  115362. x1=in+1;
  115363. for(;i<n2-n8;i+=2){
  115364. T-=2;
  115365. x0 -=4;
  115366. r0= x0[2] - x1[0];
  115367. r1= x0[0] - x1[2];
  115368. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  115369. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  115370. x1 +=4;
  115371. }
  115372. x0=in+n;
  115373. for(;i<n2;i+=2){
  115374. T-=2;
  115375. x0 -=4;
  115376. r0= -x0[2] - x1[0];
  115377. r1= -x0[0] - x1[2];
  115378. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  115379. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  115380. x1 +=4;
  115381. }
  115382. mdct_butterflies(init,w+n2,n2);
  115383. mdct_bitreverse(init,w);
  115384. /* roatate + window */
  115385. T=init->trig+n2;
  115386. x0=out+n2;
  115387. for(i=0;i<n4;i++){
  115388. x0--;
  115389. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  115390. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  115391. w+=2;
  115392. T+=2;
  115393. }
  115394. }
  115395. #endif
  115396. /*** End of inlined file: mdct.c ***/
  115397. /*** Start of inlined file: psy.c ***/
  115398. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115399. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115400. // tasks..
  115401. #if JUCE_MSVC
  115402. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115403. #endif
  115404. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115405. #if JUCE_USE_OGGVORBIS
  115406. #include <stdlib.h>
  115407. #include <math.h>
  115408. #include <string.h>
  115409. /*** Start of inlined file: masking.h ***/
  115410. #ifndef _V_MASKING_H_
  115411. #define _V_MASKING_H_
  115412. /* more detailed ATH; the bass if flat to save stressing the floor
  115413. overly for only a bin or two of savings. */
  115414. #define MAX_ATH 88
  115415. static float ATH[]={
  115416. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  115417. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  115418. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  115419. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  115420. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  115421. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  115422. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  115423. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  115424. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  115425. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  115426. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  115427. };
  115428. /* The tone masking curves from Ehmer's and Fielder's papers have been
  115429. replaced by an empirically collected data set. The previously
  115430. published values were, far too often, simply on crack. */
  115431. #define EHMER_OFFSET 16
  115432. #define EHMER_MAX 56
  115433. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  115434. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  115435. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  115436. for collection of these curves) */
  115437. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  115438. /* 62.5 Hz */
  115439. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  115440. -60, -60, -60, -60, -62, -62, -65, -73,
  115441. -69, -68, -68, -67, -70, -70, -72, -74,
  115442. -75, -79, -79, -80, -83, -88, -93, -100,
  115443. -110, -999, -999, -999, -999, -999, -999, -999,
  115444. -999, -999, -999, -999, -999, -999, -999, -999,
  115445. -999, -999, -999, -999, -999, -999, -999, -999},
  115446. { -48, -48, -48, -48, -48, -48, -48, -48,
  115447. -48, -48, -48, -48, -48, -53, -61, -66,
  115448. -66, -68, -67, -70, -76, -76, -72, -73,
  115449. -75, -76, -78, -79, -83, -88, -93, -100,
  115450. -110, -999, -999, -999, -999, -999, -999, -999,
  115451. -999, -999, -999, -999, -999, -999, -999, -999,
  115452. -999, -999, -999, -999, -999, -999, -999, -999},
  115453. { -37, -37, -37, -37, -37, -37, -37, -37,
  115454. -38, -40, -42, -46, -48, -53, -55, -62,
  115455. -65, -58, -56, -56, -61, -60, -65, -67,
  115456. -69, -71, -77, -77, -78, -80, -82, -84,
  115457. -88, -93, -98, -106, -112, -999, -999, -999,
  115458. -999, -999, -999, -999, -999, -999, -999, -999,
  115459. -999, -999, -999, -999, -999, -999, -999, -999},
  115460. { -25, -25, -25, -25, -25, -25, -25, -25,
  115461. -25, -26, -27, -29, -32, -38, -48, -52,
  115462. -52, -50, -48, -48, -51, -52, -54, -60,
  115463. -67, -67, -66, -68, -69, -73, -73, -76,
  115464. -80, -81, -81, -85, -85, -86, -88, -93,
  115465. -100, -110, -999, -999, -999, -999, -999, -999,
  115466. -999, -999, -999, -999, -999, -999, -999, -999},
  115467. { -16, -16, -16, -16, -16, -16, -16, -16,
  115468. -17, -19, -20, -22, -26, -28, -31, -40,
  115469. -47, -39, -39, -40, -42, -43, -47, -51,
  115470. -57, -52, -55, -55, -60, -58, -62, -63,
  115471. -70, -67, -69, -72, -73, -77, -80, -82,
  115472. -83, -87, -90, -94, -98, -104, -115, -999,
  115473. -999, -999, -999, -999, -999, -999, -999, -999},
  115474. { -8, -8, -8, -8, -8, -8, -8, -8,
  115475. -8, -8, -10, -11, -15, -19, -25, -30,
  115476. -34, -31, -30, -31, -29, -32, -35, -42,
  115477. -48, -42, -44, -46, -50, -50, -51, -52,
  115478. -59, -54, -55, -55, -58, -62, -63, -66,
  115479. -72, -73, -76, -75, -78, -80, -80, -81,
  115480. -84, -88, -90, -94, -98, -101, -106, -110}},
  115481. /* 88Hz */
  115482. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  115483. -66, -66, -66, -66, -66, -67, -67, -67,
  115484. -76, -72, -71, -74, -76, -76, -75, -78,
  115485. -79, -79, -81, -83, -86, -89, -93, -97,
  115486. -100, -105, -110, -999, -999, -999, -999, -999,
  115487. -999, -999, -999, -999, -999, -999, -999, -999,
  115488. -999, -999, -999, -999, -999, -999, -999, -999},
  115489. { -47, -47, -47, -47, -47, -47, -47, -47,
  115490. -47, -47, -47, -48, -51, -55, -59, -66,
  115491. -66, -66, -67, -66, -68, -69, -70, -74,
  115492. -79, -77, -77, -78, -80, -81, -82, -84,
  115493. -86, -88, -91, -95, -100, -108, -116, -999,
  115494. -999, -999, -999, -999, -999, -999, -999, -999,
  115495. -999, -999, -999, -999, -999, -999, -999, -999},
  115496. { -36, -36, -36, -36, -36, -36, -36, -36,
  115497. -36, -37, -37, -41, -44, -48, -51, -58,
  115498. -62, -60, -57, -59, -59, -60, -63, -65,
  115499. -72, -71, -70, -72, -74, -77, -76, -78,
  115500. -81, -81, -80, -83, -86, -91, -96, -100,
  115501. -105, -110, -999, -999, -999, -999, -999, -999,
  115502. -999, -999, -999, -999, -999, -999, -999, -999},
  115503. { -28, -28, -28, -28, -28, -28, -28, -28,
  115504. -28, -30, -32, -32, -33, -35, -41, -49,
  115505. -50, -49, -47, -48, -48, -52, -51, -57,
  115506. -65, -61, -59, -61, -64, -69, -70, -74,
  115507. -77, -77, -78, -81, -84, -85, -87, -90,
  115508. -92, -96, -100, -107, -112, -999, -999, -999,
  115509. -999, -999, -999, -999, -999, -999, -999, -999},
  115510. { -19, -19, -19, -19, -19, -19, -19, -19,
  115511. -20, -21, -23, -27, -30, -35, -36, -41,
  115512. -46, -44, -42, -40, -41, -41, -43, -48,
  115513. -55, -53, -52, -53, -56, -59, -58, -60,
  115514. -67, -66, -69, -71, -72, -75, -79, -81,
  115515. -84, -87, -90, -93, -97, -101, -107, -114,
  115516. -999, -999, -999, -999, -999, -999, -999, -999},
  115517. { -9, -9, -9, -9, -9, -9, -9, -9,
  115518. -11, -12, -12, -15, -16, -20, -23, -30,
  115519. -37, -34, -33, -34, -31, -32, -32, -38,
  115520. -47, -44, -41, -40, -47, -49, -46, -46,
  115521. -58, -50, -50, -54, -58, -62, -64, -67,
  115522. -67, -70, -72, -76, -79, -83, -87, -91,
  115523. -96, -100, -104, -110, -999, -999, -999, -999}},
  115524. /* 125 Hz */
  115525. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  115526. -62, -62, -63, -64, -66, -67, -66, -68,
  115527. -75, -72, -76, -75, -76, -78, -79, -82,
  115528. -84, -85, -90, -94, -101, -110, -999, -999,
  115529. -999, -999, -999, -999, -999, -999, -999, -999,
  115530. -999, -999, -999, -999, -999, -999, -999, -999,
  115531. -999, -999, -999, -999, -999, -999, -999, -999},
  115532. { -59, -59, -59, -59, -59, -59, -59, -59,
  115533. -59, -59, -59, -60, -60, -61, -63, -66,
  115534. -71, -68, -70, -70, -71, -72, -72, -75,
  115535. -81, -78, -79, -82, -83, -86, -90, -97,
  115536. -103, -113, -999, -999, -999, -999, -999, -999,
  115537. -999, -999, -999, -999, -999, -999, -999, -999,
  115538. -999, -999, -999, -999, -999, -999, -999, -999},
  115539. { -53, -53, -53, -53, -53, -53, -53, -53,
  115540. -53, -54, -55, -57, -56, -57, -55, -61,
  115541. -65, -60, -60, -62, -63, -63, -66, -68,
  115542. -74, -73, -75, -75, -78, -80, -80, -82,
  115543. -85, -90, -96, -101, -108, -999, -999, -999,
  115544. -999, -999, -999, -999, -999, -999, -999, -999,
  115545. -999, -999, -999, -999, -999, -999, -999, -999},
  115546. { -46, -46, -46, -46, -46, -46, -46, -46,
  115547. -46, -46, -47, -47, -47, -47, -48, -51,
  115548. -57, -51, -49, -50, -51, -53, -54, -59,
  115549. -66, -60, -62, -67, -67, -70, -72, -75,
  115550. -76, -78, -81, -85, -88, -94, -97, -104,
  115551. -112, -999, -999, -999, -999, -999, -999, -999,
  115552. -999, -999, -999, -999, -999, -999, -999, -999},
  115553. { -36, -36, -36, -36, -36, -36, -36, -36,
  115554. -39, -41, -42, -42, -39, -38, -41, -43,
  115555. -52, -44, -40, -39, -37, -37, -40, -47,
  115556. -54, -50, -48, -50, -55, -61, -59, -62,
  115557. -66, -66, -66, -69, -69, -73, -74, -74,
  115558. -75, -77, -79, -82, -87, -91, -95, -100,
  115559. -108, -115, -999, -999, -999, -999, -999, -999},
  115560. { -28, -26, -24, -22, -20, -20, -23, -29,
  115561. -30, -31, -28, -27, -28, -28, -28, -35,
  115562. -40, -33, -32, -29, -30, -30, -30, -37,
  115563. -45, -41, -37, -38, -45, -47, -47, -48,
  115564. -53, -49, -48, -50, -49, -49, -51, -52,
  115565. -58, -56, -57, -56, -60, -61, -62, -70,
  115566. -72, -74, -78, -83, -88, -93, -100, -106}},
  115567. /* 177 Hz */
  115568. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115569. -999, -110, -105, -100, -95, -91, -87, -83,
  115570. -80, -78, -76, -78, -78, -81, -83, -85,
  115571. -86, -85, -86, -87, -90, -97, -107, -999,
  115572. -999, -999, -999, -999, -999, -999, -999, -999,
  115573. -999, -999, -999, -999, -999, -999, -999, -999,
  115574. -999, -999, -999, -999, -999, -999, -999, -999},
  115575. {-999, -999, -999, -110, -105, -100, -95, -90,
  115576. -85, -81, -77, -73, -70, -67, -67, -68,
  115577. -75, -73, -70, -69, -70, -72, -75, -79,
  115578. -84, -83, -84, -86, -88, -89, -89, -93,
  115579. -98, -105, -112, -999, -999, -999, -999, -999,
  115580. -999, -999, -999, -999, -999, -999, -999, -999,
  115581. -999, -999, -999, -999, -999, -999, -999, -999},
  115582. {-105, -100, -95, -90, -85, -80, -76, -71,
  115583. -68, -68, -65, -63, -63, -62, -62, -64,
  115584. -65, -64, -61, -62, -63, -64, -66, -68,
  115585. -73, -73, -74, -75, -76, -81, -83, -85,
  115586. -88, -89, -92, -95, -100, -108, -999, -999,
  115587. -999, -999, -999, -999, -999, -999, -999, -999,
  115588. -999, -999, -999, -999, -999, -999, -999, -999},
  115589. { -80, -75, -71, -68, -65, -63, -62, -61,
  115590. -61, -61, -61, -59, -56, -57, -53, -50,
  115591. -58, -52, -50, -50, -52, -53, -54, -58,
  115592. -67, -63, -67, -68, -72, -75, -78, -80,
  115593. -81, -81, -82, -85, -89, -90, -93, -97,
  115594. -101, -107, -114, -999, -999, -999, -999, -999,
  115595. -999, -999, -999, -999, -999, -999, -999, -999},
  115596. { -65, -61, -59, -57, -56, -55, -55, -56,
  115597. -56, -57, -55, -53, -52, -47, -44, -44,
  115598. -50, -44, -41, -39, -39, -42, -40, -46,
  115599. -51, -49, -50, -53, -54, -63, -60, -61,
  115600. -62, -66, -66, -66, -70, -73, -74, -75,
  115601. -76, -75, -79, -85, -89, -91, -96, -102,
  115602. -110, -999, -999, -999, -999, -999, -999, -999},
  115603. { -52, -50, -49, -49, -48, -48, -48, -49,
  115604. -50, -50, -49, -46, -43, -39, -35, -33,
  115605. -38, -36, -32, -29, -32, -32, -32, -35,
  115606. -44, -39, -38, -38, -46, -50, -45, -46,
  115607. -53, -50, -50, -50, -54, -54, -53, -53,
  115608. -56, -57, -59, -66, -70, -72, -74, -79,
  115609. -83, -85, -90, -97, -114, -999, -999, -999}},
  115610. /* 250 Hz */
  115611. {{-999, -999, -999, -999, -999, -999, -110, -105,
  115612. -100, -95, -90, -86, -80, -75, -75, -79,
  115613. -80, -79, -80, -81, -82, -88, -95, -103,
  115614. -110, -999, -999, -999, -999, -999, -999, -999,
  115615. -999, -999, -999, -999, -999, -999, -999, -999,
  115616. -999, -999, -999, -999, -999, -999, -999, -999,
  115617. -999, -999, -999, -999, -999, -999, -999, -999},
  115618. {-999, -999, -999, -999, -108, -103, -98, -93,
  115619. -88, -83, -79, -78, -75, -71, -67, -68,
  115620. -73, -73, -72, -73, -75, -77, -80, -82,
  115621. -88, -93, -100, -107, -114, -999, -999, -999,
  115622. -999, -999, -999, -999, -999, -999, -999, -999,
  115623. -999, -999, -999, -999, -999, -999, -999, -999,
  115624. -999, -999, -999, -999, -999, -999, -999, -999},
  115625. {-999, -999, -999, -110, -105, -101, -96, -90,
  115626. -86, -81, -77, -73, -69, -66, -61, -62,
  115627. -66, -64, -62, -65, -66, -70, -72, -76,
  115628. -81, -80, -84, -90, -95, -102, -110, -999,
  115629. -999, -999, -999, -999, -999, -999, -999, -999,
  115630. -999, -999, -999, -999, -999, -999, -999, -999,
  115631. -999, -999, -999, -999, -999, -999, -999, -999},
  115632. {-999, -999, -999, -107, -103, -97, -92, -88,
  115633. -83, -79, -74, -70, -66, -59, -53, -58,
  115634. -62, -55, -54, -54, -54, -58, -61, -62,
  115635. -72, -70, -72, -75, -78, -80, -81, -80,
  115636. -83, -83, -88, -93, -100, -107, -115, -999,
  115637. -999, -999, -999, -999, -999, -999, -999, -999,
  115638. -999, -999, -999, -999, -999, -999, -999, -999},
  115639. {-999, -999, -999, -105, -100, -95, -90, -85,
  115640. -80, -75, -70, -66, -62, -56, -48, -44,
  115641. -48, -46, -46, -43, -46, -48, -48, -51,
  115642. -58, -58, -59, -60, -62, -62, -61, -61,
  115643. -65, -64, -65, -68, -70, -74, -75, -78,
  115644. -81, -86, -95, -110, -999, -999, -999, -999,
  115645. -999, -999, -999, -999, -999, -999, -999, -999},
  115646. {-999, -999, -105, -100, -95, -90, -85, -80,
  115647. -75, -70, -65, -61, -55, -49, -39, -33,
  115648. -40, -35, -32, -38, -40, -33, -35, -37,
  115649. -46, -41, -45, -44, -46, -42, -45, -46,
  115650. -52, -50, -50, -50, -54, -54, -55, -57,
  115651. -62, -64, -66, -68, -70, -76, -81, -90,
  115652. -100, -110, -999, -999, -999, -999, -999, -999}},
  115653. /* 354 hz */
  115654. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115655. -105, -98, -90, -85, -82, -83, -80, -78,
  115656. -84, -79, -80, -83, -87, -89, -91, -93,
  115657. -99, -106, -117, -999, -999, -999, -999, -999,
  115658. -999, -999, -999, -999, -999, -999, -999, -999,
  115659. -999, -999, -999, -999, -999, -999, -999, -999,
  115660. -999, -999, -999, -999, -999, -999, -999, -999},
  115661. {-999, -999, -999, -999, -999, -999, -999, -999,
  115662. -105, -98, -90, -85, -80, -75, -70, -68,
  115663. -74, -72, -74, -77, -80, -82, -85, -87,
  115664. -92, -89, -91, -95, -100, -106, -112, -999,
  115665. -999, -999, -999, -999, -999, -999, -999, -999,
  115666. -999, -999, -999, -999, -999, -999, -999, -999,
  115667. -999, -999, -999, -999, -999, -999, -999, -999},
  115668. {-999, -999, -999, -999, -999, -999, -999, -999,
  115669. -105, -98, -90, -83, -75, -71, -63, -64,
  115670. -67, -62, -64, -67, -70, -73, -77, -81,
  115671. -84, -83, -85, -89, -90, -93, -98, -104,
  115672. -109, -114, -999, -999, -999, -999, -999, -999,
  115673. -999, -999, -999, -999, -999, -999, -999, -999,
  115674. -999, -999, -999, -999, -999, -999, -999, -999},
  115675. {-999, -999, -999, -999, -999, -999, -999, -999,
  115676. -103, -96, -88, -81, -75, -68, -58, -54,
  115677. -56, -54, -56, -56, -58, -60, -63, -66,
  115678. -74, -69, -72, -72, -75, -74, -77, -81,
  115679. -81, -82, -84, -87, -93, -96, -99, -104,
  115680. -110, -999, -999, -999, -999, -999, -999, -999,
  115681. -999, -999, -999, -999, -999, -999, -999, -999},
  115682. {-999, -999, -999, -999, -999, -108, -102, -96,
  115683. -91, -85, -80, -74, -68, -60, -51, -46,
  115684. -48, -46, -43, -45, -47, -47, -49, -48,
  115685. -56, -53, -55, -58, -57, -63, -58, -60,
  115686. -66, -64, -67, -70, -70, -74, -77, -84,
  115687. -86, -89, -91, -93, -94, -101, -109, -118,
  115688. -999, -999, -999, -999, -999, -999, -999, -999},
  115689. {-999, -999, -999, -108, -103, -98, -93, -88,
  115690. -83, -78, -73, -68, -60, -53, -44, -35,
  115691. -38, -38, -34, -34, -36, -40, -41, -44,
  115692. -51, -45, -46, -47, -46, -54, -50, -49,
  115693. -50, -50, -50, -51, -54, -57, -58, -60,
  115694. -66, -66, -66, -64, -65, -68, -77, -82,
  115695. -87, -95, -110, -999, -999, -999, -999, -999}},
  115696. /* 500 Hz */
  115697. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115698. -107, -102, -97, -92, -87, -83, -78, -75,
  115699. -82, -79, -83, -85, -89, -92, -95, -98,
  115700. -101, -105, -109, -113, -999, -999, -999, -999,
  115701. -999, -999, -999, -999, -999, -999, -999, -999,
  115702. -999, -999, -999, -999, -999, -999, -999, -999,
  115703. -999, -999, -999, -999, -999, -999, -999, -999},
  115704. {-999, -999, -999, -999, -999, -999, -999, -106,
  115705. -100, -95, -90, -86, -81, -78, -74, -69,
  115706. -74, -74, -76, -79, -83, -84, -86, -89,
  115707. -92, -97, -93, -100, -103, -107, -110, -999,
  115708. -999, -999, -999, -999, -999, -999, -999, -999,
  115709. -999, -999, -999, -999, -999, -999, -999, -999,
  115710. -999, -999, -999, -999, -999, -999, -999, -999},
  115711. {-999, -999, -999, -999, -999, -999, -106, -100,
  115712. -95, -90, -87, -83, -80, -75, -69, -60,
  115713. -66, -66, -68, -70, -74, -78, -79, -81,
  115714. -81, -83, -84, -87, -93, -96, -99, -103,
  115715. -107, -110, -999, -999, -999, -999, -999, -999,
  115716. -999, -999, -999, -999, -999, -999, -999, -999,
  115717. -999, -999, -999, -999, -999, -999, -999, -999},
  115718. {-999, -999, -999, -999, -999, -108, -103, -98,
  115719. -93, -89, -85, -82, -78, -71, -62, -55,
  115720. -58, -58, -54, -54, -55, -59, -61, -62,
  115721. -70, -66, -66, -67, -70, -72, -75, -78,
  115722. -84, -84, -84, -88, -91, -90, -95, -98,
  115723. -102, -103, -106, -110, -999, -999, -999, -999,
  115724. -999, -999, -999, -999, -999, -999, -999, -999},
  115725. {-999, -999, -999, -999, -108, -103, -98, -94,
  115726. -90, -87, -82, -79, -73, -67, -58, -47,
  115727. -50, -45, -41, -45, -48, -44, -44, -49,
  115728. -54, -51, -48, -47, -49, -50, -51, -57,
  115729. -58, -60, -63, -69, -70, -69, -71, -74,
  115730. -78, -82, -90, -95, -101, -105, -110, -999,
  115731. -999, -999, -999, -999, -999, -999, -999, -999},
  115732. {-999, -999, -999, -105, -101, -97, -93, -90,
  115733. -85, -80, -77, -72, -65, -56, -48, -37,
  115734. -40, -36, -34, -40, -50, -47, -38, -41,
  115735. -47, -38, -35, -39, -38, -43, -40, -45,
  115736. -50, -45, -44, -47, -50, -55, -48, -48,
  115737. -52, -66, -70, -76, -82, -90, -97, -105,
  115738. -110, -999, -999, -999, -999, -999, -999, -999}},
  115739. /* 707 Hz */
  115740. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115741. -999, -108, -103, -98, -93, -86, -79, -76,
  115742. -83, -81, -85, -87, -89, -93, -98, -102,
  115743. -107, -112, -999, -999, -999, -999, -999, -999,
  115744. -999, -999, -999, -999, -999, -999, -999, -999,
  115745. -999, -999, -999, -999, -999, -999, -999, -999,
  115746. -999, -999, -999, -999, -999, -999, -999, -999},
  115747. {-999, -999, -999, -999, -999, -999, -999, -999,
  115748. -999, -108, -103, -98, -93, -86, -79, -71,
  115749. -77, -74, -77, -79, -81, -84, -85, -90,
  115750. -92, -93, -92, -98, -101, -108, -112, -999,
  115751. -999, -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. {-999, -999, -999, -999, -999, -999, -999, -999,
  115755. -108, -103, -98, -93, -87, -78, -68, -65,
  115756. -66, -62, -65, -67, -70, -73, -75, -78,
  115757. -82, -82, -83, -84, -91, -93, -98, -102,
  115758. -106, -110, -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. {-999, -999, -999, -999, -999, -999, -999, -999,
  115762. -105, -100, -95, -90, -82, -74, -62, -57,
  115763. -58, -56, -51, -52, -52, -54, -54, -58,
  115764. -66, -59, -60, -63, -66, -69, -73, -79,
  115765. -83, -84, -80, -81, -81, -82, -88, -92,
  115766. -98, -105, -113, -999, -999, -999, -999, -999,
  115767. -999, -999, -999, -999, -999, -999, -999, -999},
  115768. {-999, -999, -999, -999, -999, -999, -999, -107,
  115769. -102, -97, -92, -84, -79, -69, -57, -47,
  115770. -52, -47, -44, -45, -50, -52, -42, -42,
  115771. -53, -43, -43, -48, -51, -56, -55, -52,
  115772. -57, -59, -61, -62, -67, -71, -78, -83,
  115773. -86, -94, -98, -103, -110, -999, -999, -999,
  115774. -999, -999, -999, -999, -999, -999, -999, -999},
  115775. {-999, -999, -999, -999, -999, -999, -105, -100,
  115776. -95, -90, -84, -78, -70, -61, -51, -41,
  115777. -40, -38, -40, -46, -52, -51, -41, -40,
  115778. -46, -40, -38, -38, -41, -46, -41, -46,
  115779. -47, -43, -43, -45, -41, -45, -56, -67,
  115780. -68, -83, -87, -90, -95, -102, -107, -113,
  115781. -999, -999, -999, -999, -999, -999, -999, -999}},
  115782. /* 1000 Hz */
  115783. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115784. -999, -109, -105, -101, -96, -91, -84, -77,
  115785. -82, -82, -85, -89, -94, -100, -106, -110,
  115786. -999, -999, -999, -999, -999, -999, -999, -999,
  115787. -999, -999, -999, -999, -999, -999, -999, -999,
  115788. -999, -999, -999, -999, -999, -999, -999, -999,
  115789. -999, -999, -999, -999, -999, -999, -999, -999},
  115790. {-999, -999, -999, -999, -999, -999, -999, -999,
  115791. -999, -106, -103, -98, -92, -85, -80, -71,
  115792. -75, -72, -76, -80, -84, -86, -89, -93,
  115793. -100, -107, -113, -999, -999, -999, -999, -999,
  115794. -999, -999, -999, -999, -999, -999, -999, -999,
  115795. -999, -999, -999, -999, -999, -999, -999, -999,
  115796. -999, -999, -999, -999, -999, -999, -999, -999},
  115797. {-999, -999, -999, -999, -999, -999, -999, -107,
  115798. -104, -101, -97, -92, -88, -84, -80, -64,
  115799. -66, -63, -64, -66, -69, -73, -77, -83,
  115800. -83, -86, -91, -98, -104, -111, -999, -999,
  115801. -999, -999, -999, -999, -999, -999, -999, -999,
  115802. -999, -999, -999, -999, -999, -999, -999, -999,
  115803. -999, -999, -999, -999, -999, -999, -999, -999},
  115804. {-999, -999, -999, -999, -999, -999, -999, -107,
  115805. -104, -101, -97, -92, -90, -84, -74, -57,
  115806. -58, -52, -55, -54, -50, -52, -50, -52,
  115807. -63, -62, -69, -76, -77, -78, -78, -79,
  115808. -82, -88, -94, -100, -106, -111, -999, -999,
  115809. -999, -999, -999, -999, -999, -999, -999, -999,
  115810. -999, -999, -999, -999, -999, -999, -999, -999},
  115811. {-999, -999, -999, -999, -999, -999, -106, -102,
  115812. -98, -95, -90, -85, -83, -78, -70, -50,
  115813. -50, -41, -44, -49, -47, -50, -50, -44,
  115814. -55, -46, -47, -48, -48, -54, -49, -49,
  115815. -58, -62, -71, -81, -87, -92, -97, -102,
  115816. -108, -114, -999, -999, -999, -999, -999, -999,
  115817. -999, -999, -999, -999, -999, -999, -999, -999},
  115818. {-999, -999, -999, -999, -999, -999, -106, -102,
  115819. -98, -95, -90, -85, -83, -78, -70, -45,
  115820. -43, -41, -47, -50, -51, -50, -49, -45,
  115821. -47, -41, -44, -41, -39, -43, -38, -37,
  115822. -40, -41, -44, -50, -58, -65, -73, -79,
  115823. -85, -92, -97, -101, -105, -109, -113, -999,
  115824. -999, -999, -999, -999, -999, -999, -999, -999}},
  115825. /* 1414 Hz */
  115826. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115827. -999, -999, -999, -107, -100, -95, -87, -81,
  115828. -85, -83, -88, -93, -100, -107, -114, -999,
  115829. -999, -999, -999, -999, -999, -999, -999, -999,
  115830. -999, -999, -999, -999, -999, -999, -999, -999,
  115831. -999, -999, -999, -999, -999, -999, -999, -999,
  115832. -999, -999, -999, -999, -999, -999, -999, -999},
  115833. {-999, -999, -999, -999, -999, -999, -999, -999,
  115834. -999, -999, -107, -101, -95, -88, -83, -76,
  115835. -73, -72, -79, -84, -90, -95, -100, -105,
  115836. -110, -115, -999, -999, -999, -999, -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. {-999, -999, -999, -999, -999, -999, -999, -999,
  115841. -999, -999, -104, -98, -92, -87, -81, -70,
  115842. -65, -62, -67, -71, -74, -80, -85, -91,
  115843. -95, -99, -103, -108, -111, -114, -999, -999,
  115844. -999, -999, -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. {-999, -999, -999, -999, -999, -999, -999, -999,
  115848. -999, -999, -103, -97, -90, -85, -76, -60,
  115849. -56, -54, -60, -62, -61, -56, -63, -65,
  115850. -73, -74, -77, -75, -78, -81, -86, -87,
  115851. -88, -91, -94, -98, -103, -110, -999, -999,
  115852. -999, -999, -999, -999, -999, -999, -999, -999,
  115853. -999, -999, -999, -999, -999, -999, -999, -999},
  115854. {-999, -999, -999, -999, -999, -999, -999, -105,
  115855. -100, -97, -92, -86, -81, -79, -70, -57,
  115856. -51, -47, -51, -58, -60, -56, -53, -50,
  115857. -58, -52, -50, -50, -53, -55, -64, -69,
  115858. -71, -85, -82, -78, -81, -85, -95, -102,
  115859. -112, -999, -999, -999, -999, -999, -999, -999,
  115860. -999, -999, -999, -999, -999, -999, -999, -999},
  115861. {-999, -999, -999, -999, -999, -999, -999, -105,
  115862. -100, -97, -92, -85, -83, -79, -72, -49,
  115863. -40, -43, -43, -54, -56, -51, -50, -40,
  115864. -43, -38, -36, -35, -37, -38, -37, -44,
  115865. -54, -60, -57, -60, -70, -75, -84, -92,
  115866. -103, -112, -999, -999, -999, -999, -999, -999,
  115867. -999, -999, -999, -999, -999, -999, -999, -999}},
  115868. /* 2000 Hz */
  115869. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115870. -999, -999, -999, -110, -102, -95, -89, -82,
  115871. -83, -84, -90, -92, -99, -107, -113, -999,
  115872. -999, -999, -999, -999, -999, -999, -999, -999,
  115873. -999, -999, -999, -999, -999, -999, -999, -999,
  115874. -999, -999, -999, -999, -999, -999, -999, -999,
  115875. -999, -999, -999, -999, -999, -999, -999, -999},
  115876. {-999, -999, -999, -999, -999, -999, -999, -999,
  115877. -999, -999, -107, -101, -95, -89, -83, -72,
  115878. -74, -78, -85, -88, -88, -90, -92, -98,
  115879. -105, -111, -999, -999, -999, -999, -999, -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, -999, -999, -999, -999, -999,
  115884. -999, -109, -103, -97, -93, -87, -81, -70,
  115885. -70, -67, -75, -73, -76, -79, -81, -83,
  115886. -88, -89, -97, -103, -110, -999, -999, -999,
  115887. -999, -999, -999, -999, -999, -999, -999, -999,
  115888. -999, -999, -999, -999, -999, -999, -999, -999,
  115889. -999, -999, -999, -999, -999, -999, -999, -999},
  115890. {-999, -999, -999, -999, -999, -999, -999, -999,
  115891. -999, -107, -100, -94, -88, -83, -75, -63,
  115892. -59, -59, -63, -66, -60, -62, -67, -67,
  115893. -77, -76, -81, -88, -86, -92, -96, -102,
  115894. -109, -116, -999, -999, -999, -999, -999, -999,
  115895. -999, -999, -999, -999, -999, -999, -999, -999,
  115896. -999, -999, -999, -999, -999, -999, -999, -999},
  115897. {-999, -999, -999, -999, -999, -999, -999, -999,
  115898. -999, -105, -98, -92, -86, -81, -73, -56,
  115899. -52, -47, -55, -60, -58, -52, -51, -45,
  115900. -49, -50, -53, -54, -61, -71, -70, -69,
  115901. -78, -79, -87, -90, -96, -104, -112, -999,
  115902. -999, -999, -999, -999, -999, -999, -999, -999,
  115903. -999, -999, -999, -999, -999, -999, -999, -999},
  115904. {-999, -999, -999, -999, -999, -999, -999, -999,
  115905. -999, -103, -96, -90, -86, -78, -70, -51,
  115906. -42, -47, -48, -55, -54, -54, -53, -42,
  115907. -35, -28, -33, -38, -37, -44, -47, -49,
  115908. -54, -63, -68, -78, -82, -89, -94, -99,
  115909. -104, -109, -114, -999, -999, -999, -999, -999,
  115910. -999, -999, -999, -999, -999, -999, -999, -999}},
  115911. /* 2828 Hz */
  115912. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115913. -999, -999, -999, -999, -110, -100, -90, -79,
  115914. -85, -81, -82, -82, -89, -94, -99, -103,
  115915. -109, -115, -999, -999, -999, -999, -999, -999,
  115916. -999, -999, -999, -999, -999, -999, -999, -999,
  115917. -999, -999, -999, -999, -999, -999, -999, -999,
  115918. -999, -999, -999, -999, -999, -999, -999, -999},
  115919. {-999, -999, -999, -999, -999, -999, -999, -999,
  115920. -999, -999, -999, -999, -105, -97, -85, -72,
  115921. -74, -70, -70, -70, -76, -85, -91, -93,
  115922. -97, -103, -109, -115, -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, -999, -999, -999, -999,
  115927. -999, -999, -999, -999, -112, -93, -81, -68,
  115928. -62, -60, -60, -57, -63, -70, -77, -82,
  115929. -90, -93, -98, -104, -109, -113, -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, -999, -999, -999, -999, -999,
  115934. -999, -999, -999, -113, -100, -93, -84, -63,
  115935. -58, -48, -53, -54, -52, -52, -57, -64,
  115936. -66, -76, -83, -81, -85, -85, -90, -95,
  115937. -98, -101, -103, -106, -108, -111, -999, -999,
  115938. -999, -999, -999, -999, -999, -999, -999, -999,
  115939. -999, -999, -999, -999, -999, -999, -999, -999},
  115940. {-999, -999, -999, -999, -999, -999, -999, -999,
  115941. -999, -999, -999, -105, -95, -86, -74, -53,
  115942. -50, -38, -43, -49, -43, -42, -39, -39,
  115943. -46, -52, -57, -56, -72, -69, -74, -81,
  115944. -87, -92, -94, -97, -99, -102, -105, -108,
  115945. -999, -999, -999, -999, -999, -999, -999, -999,
  115946. -999, -999, -999, -999, -999, -999, -999, -999},
  115947. {-999, -999, -999, -999, -999, -999, -999, -999,
  115948. -999, -999, -108, -99, -90, -76, -66, -45,
  115949. -43, -41, -44, -47, -43, -47, -40, -30,
  115950. -31, -31, -39, -33, -40, -41, -43, -53,
  115951. -59, -70, -73, -77, -79, -82, -84, -87,
  115952. -999, -999, -999, -999, -999, -999, -999, -999,
  115953. -999, -999, -999, -999, -999, -999, -999, -999}},
  115954. /* 4000 Hz */
  115955. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115956. -999, -999, -999, -999, -999, -110, -91, -76,
  115957. -75, -85, -93, -98, -104, -110, -999, -999,
  115958. -999, -999, -999, -999, -999, -999, -999, -999,
  115959. -999, -999, -999, -999, -999, -999, -999, -999,
  115960. -999, -999, -999, -999, -999, -999, -999, -999,
  115961. -999, -999, -999, -999, -999, -999, -999, -999},
  115962. {-999, -999, -999, -999, -999, -999, -999, -999,
  115963. -999, -999, -999, -999, -999, -110, -91, -70,
  115964. -70, -75, -86, -89, -94, -98, -101, -106,
  115965. -110, -999, -999, -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. -999, -999, -999, -999, -110, -95, -80, -60,
  115971. -65, -64, -74, -83, -88, -91, -95, -99,
  115972. -103, -107, -110, -999, -999, -999, -999, -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. -999, -999, -999, -999, -110, -95, -80, -58,
  115978. -55, -49, -66, -68, -71, -78, -78, -80,
  115979. -88, -85, -89, -97, -100, -105, -110, -999,
  115980. -999, -999, -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. -999, -999, -999, -999, -110, -95, -80, -53,
  115985. -52, -41, -59, -59, -49, -58, -56, -63,
  115986. -86, -79, -90, -93, -98, -103, -107, -112,
  115987. -999, -999, -999, -999, -999, -999, -999, -999,
  115988. -999, -999, -999, -999, -999, -999, -999, -999,
  115989. -999, -999, -999, -999, -999, -999, -999, -999},
  115990. {-999, -999, -999, -999, -999, -999, -999, -999,
  115991. -999, -999, -999, -110, -97, -91, -73, -45,
  115992. -40, -33, -53, -61, -49, -54, -50, -50,
  115993. -60, -52, -67, -74, -81, -92, -96, -100,
  115994. -105, -110, -999, -999, -999, -999, -999, -999,
  115995. -999, -999, -999, -999, -999, -999, -999, -999,
  115996. -999, -999, -999, -999, -999, -999, -999, -999}},
  115997. /* 5657 Hz */
  115998. {{-999, -999, -999, -999, -999, -999, -999, -999,
  115999. -999, -999, -999, -113, -106, -99, -92, -77,
  116000. -80, -88, -97, -106, -115, -999, -999, -999,
  116001. -999, -999, -999, -999, -999, -999, -999, -999,
  116002. -999, -999, -999, -999, -999, -999, -999, -999,
  116003. -999, -999, -999, -999, -999, -999, -999, -999,
  116004. -999, -999, -999, -999, -999, -999, -999, -999},
  116005. {-999, -999, -999, -999, -999, -999, -999, -999,
  116006. -999, -999, -116, -109, -102, -95, -89, -74,
  116007. -72, -88, -87, -95, -102, -109, -116, -999,
  116008. -999, -999, -999, -999, -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, -999,
  116013. -999, -999, -116, -109, -102, -95, -89, -75,
  116014. -66, -74, -77, -78, -86, -87, -90, -96,
  116015. -105, -115, -999, -999, -999, -999, -999, -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, -999, -999,
  116020. -999, -999, -115, -108, -101, -94, -88, -66,
  116021. -56, -61, -70, -65, -78, -72, -83, -84,
  116022. -93, -98, -105, -110, -999, -999, -999, -999,
  116023. -999, -999, -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, -999, -999, -999,
  116027. -999, -999, -110, -105, -95, -89, -82, -57,
  116028. -52, -52, -59, -56, -59, -58, -69, -67,
  116029. -88, -82, -82, -89, -94, -100, -108, -999,
  116030. -999, -999, -999, -999, -999, -999, -999, -999,
  116031. -999, -999, -999, -999, -999, -999, -999, -999,
  116032. -999, -999, -999, -999, -999, -999, -999, -999},
  116033. {-999, -999, -999, -999, -999, -999, -999, -999,
  116034. -999, -110, -101, -96, -90, -83, -77, -54,
  116035. -43, -38, -50, -48, -52, -48, -42, -42,
  116036. -51, -52, -53, -59, -65, -71, -78, -85,
  116037. -95, -999, -999, -999, -999, -999, -999, -999,
  116038. -999, -999, -999, -999, -999, -999, -999, -999,
  116039. -999, -999, -999, -999, -999, -999, -999, -999}},
  116040. /* 8000 Hz */
  116041. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116042. -999, -999, -999, -999, -120, -105, -86, -68,
  116043. -78, -79, -90, -100, -110, -999, -999, -999,
  116044. -999, -999, -999, -999, -999, -999, -999, -999,
  116045. -999, -999, -999, -999, -999, -999, -999, -999,
  116046. -999, -999, -999, -999, -999, -999, -999, -999,
  116047. -999, -999, -999, -999, -999, -999, -999, -999},
  116048. {-999, -999, -999, -999, -999, -999, -999, -999,
  116049. -999, -999, -999, -999, -120, -105, -86, -66,
  116050. -73, -77, -88, -96, -105, -115, -999, -999,
  116051. -999, -999, -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, -999, -999, -120, -105, -92, -80, -61,
  116057. -64, -68, -80, -87, -92, -100, -110, -999,
  116058. -999, -999, -999, -999, -999, -999, -999, -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. -999, -999, -999, -120, -104, -91, -79, -52,
  116064. -60, -54, -64, -69, -77, -80, -82, -84,
  116065. -85, -87, -88, -90, -999, -999, -999, -999,
  116066. -999, -999, -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. -999, -999, -999, -118, -100, -87, -77, -49,
  116071. -50, -44, -58, -61, -61, -67, -65, -62,
  116072. -62, -62, -65, -68, -999, -999, -999, -999,
  116073. -999, -999, -999, -999, -999, -999, -999, -999,
  116074. -999, -999, -999, -999, -999, -999, -999, -999,
  116075. -999, -999, -999, -999, -999, -999, -999, -999},
  116076. {-999, -999, -999, -999, -999, -999, -999, -999,
  116077. -999, -999, -999, -115, -98, -84, -62, -49,
  116078. -44, -38, -46, -49, -49, -46, -39, -37,
  116079. -39, -40, -42, -43, -999, -999, -999, -999,
  116080. -999, -999, -999, -999, -999, -999, -999, -999,
  116081. -999, -999, -999, -999, -999, -999, -999, -999,
  116082. -999, -999, -999, -999, -999, -999, -999, -999}},
  116083. /* 11314 Hz */
  116084. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116085. -999, -999, -999, -999, -999, -110, -88, -74,
  116086. -77, -82, -82, -85, -90, -94, -99, -104,
  116087. -999, -999, -999, -999, -999, -999, -999, -999,
  116088. -999, -999, -999, -999, -999, -999, -999, -999,
  116089. -999, -999, -999, -999, -999, -999, -999, -999,
  116090. -999, -999, -999, -999, -999, -999, -999, -999},
  116091. {-999, -999, -999, -999, -999, -999, -999, -999,
  116092. -999, -999, -999, -999, -999, -110, -88, -66,
  116093. -70, -81, -80, -81, -84, -88, -91, -93,
  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, -999, -999, -999, -999, -110, -88, -61,
  116100. -63, -70, -71, -74, -77, -80, -83, -85,
  116101. -999, -999, -999, -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, -999,
  116106. -999, -999, -999, -999, -999, -110, -86, -62,
  116107. -63, -62, -62, -58, -52, -50, -50, -52,
  116108. -54, -999, -999, -999, -999, -999, -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, -999,
  116113. -999, -999, -999, -999, -118, -108, -84, -53,
  116114. -50, -50, -50, -55, -47, -45, -40, -40,
  116115. -40, -999, -999, -999, -999, -999, -999, -999,
  116116. -999, -999, -999, -999, -999, -999, -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, -999, -999,
  116120. -999, -999, -999, -999, -118, -100, -73, -43,
  116121. -37, -42, -43, -53, -38, -37, -35, -35,
  116122. -38, -999, -999, -999, -999, -999, -999, -999,
  116123. -999, -999, -999, -999, -999, -999, -999, -999,
  116124. -999, -999, -999, -999, -999, -999, -999, -999,
  116125. -999, -999, -999, -999, -999, -999, -999, -999}},
  116126. /* 16000 Hz */
  116127. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116128. -999, -999, -999, -110, -100, -91, -84, -74,
  116129. -80, -80, -80, -80, -80, -999, -999, -999,
  116130. -999, -999, -999, -999, -999, -999, -999, -999,
  116131. -999, -999, -999, -999, -999, -999, -999, -999,
  116132. -999, -999, -999, -999, -999, -999, -999, -999,
  116133. -999, -999, -999, -999, -999, -999, -999, -999},
  116134. {-999, -999, -999, -999, -999, -999, -999, -999,
  116135. -999, -999, -999, -110, -100, -91, -84, -74,
  116136. -68, -68, -68, -68, -68, -999, -999, -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, -999, -110, -100, -86, -78, -70,
  116143. -60, -45, -30, -21, -999, -999, -999, -999,
  116144. -999, -999, -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, -999, -110, -100, -87, -78, -67,
  116150. -48, -38, -29, -21, -999, -999, -999, -999,
  116151. -999, -999, -999, -999, -999, -999, -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, -999, -110, -100, -86, -69, -56,
  116157. -45, -35, -33, -29, -999, -999, -999, -999,
  116158. -999, -999, -999, -999, -999, -999, -999, -999,
  116159. -999, -999, -999, -999, -999, -999, -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, -999,
  116163. -999, -999, -999, -110, -100, -83, -71, -48,
  116164. -27, -38, -37, -34, -999, -999, -999, -999,
  116165. -999, -999, -999, -999, -999, -999, -999, -999,
  116166. -999, -999, -999, -999, -999, -999, -999, -999,
  116167. -999, -999, -999, -999, -999, -999, -999, -999,
  116168. -999, -999, -999, -999, -999, -999, -999, -999}}
  116169. };
  116170. #endif
  116171. /*** End of inlined file: masking.h ***/
  116172. #define NEGINF -9999.f
  116173. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  116174. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  116175. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  116176. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  116177. vorbis_info_psy_global *gi=&ci->psy_g_param;
  116178. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  116179. look->channels=vi->channels;
  116180. look->ampmax=-9999.;
  116181. look->gi=gi;
  116182. return(look);
  116183. }
  116184. void _vp_global_free(vorbis_look_psy_global *look){
  116185. if(look){
  116186. memset(look,0,sizeof(*look));
  116187. _ogg_free(look);
  116188. }
  116189. }
  116190. void _vi_gpsy_free(vorbis_info_psy_global *i){
  116191. if(i){
  116192. memset(i,0,sizeof(*i));
  116193. _ogg_free(i);
  116194. }
  116195. }
  116196. void _vi_psy_free(vorbis_info_psy *i){
  116197. if(i){
  116198. memset(i,0,sizeof(*i));
  116199. _ogg_free(i);
  116200. }
  116201. }
  116202. static void min_curve(float *c,
  116203. float *c2){
  116204. int i;
  116205. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  116206. }
  116207. static void max_curve(float *c,
  116208. float *c2){
  116209. int i;
  116210. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  116211. }
  116212. static void attenuate_curve(float *c,float att){
  116213. int i;
  116214. for(i=0;i<EHMER_MAX;i++)
  116215. c[i]+=att;
  116216. }
  116217. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  116218. float center_boost, float center_decay_rate){
  116219. int i,j,k,m;
  116220. float ath[EHMER_MAX];
  116221. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  116222. float athc[P_LEVELS][EHMER_MAX];
  116223. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  116224. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  116225. memset(workc,0,sizeof(workc));
  116226. for(i=0;i<P_BANDS;i++){
  116227. /* we add back in the ATH to avoid low level curves falling off to
  116228. -infinity and unnecessarily cutting off high level curves in the
  116229. curve limiting (last step). */
  116230. /* A half-band's settings must be valid over the whole band, and
  116231. it's better to mask too little than too much */
  116232. int ath_offset=i*4;
  116233. for(j=0;j<EHMER_MAX;j++){
  116234. float min=999.;
  116235. for(k=0;k<4;k++)
  116236. if(j+k+ath_offset<MAX_ATH){
  116237. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  116238. }else{
  116239. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  116240. }
  116241. ath[j]=min;
  116242. }
  116243. /* copy curves into working space, replicate the 50dB curve to 30
  116244. and 40, replicate the 100dB curve to 110 */
  116245. for(j=0;j<6;j++)
  116246. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  116247. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  116248. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  116249. /* apply centered curve boost/decay */
  116250. for(j=0;j<P_LEVELS;j++){
  116251. for(k=0;k<EHMER_MAX;k++){
  116252. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  116253. if(adj<0. && center_boost>0)adj=0.;
  116254. if(adj>0. && center_boost<0)adj=0.;
  116255. workc[i][j][k]+=adj;
  116256. }
  116257. }
  116258. /* normalize curves so the driving amplitude is 0dB */
  116259. /* make temp curves with the ATH overlayed */
  116260. for(j=0;j<P_LEVELS;j++){
  116261. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  116262. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  116263. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  116264. max_curve(athc[j],workc[i][j]);
  116265. }
  116266. /* Now limit the louder curves.
  116267. the idea is this: We don't know what the playback attenuation
  116268. will be; 0dB SL moves every time the user twiddles the volume
  116269. knob. So that means we have to use a single 'most pessimal' curve
  116270. for all masking amplitudes, right? Wrong. The *loudest* sound
  116271. can be in (we assume) a range of ...+100dB] SL. However, sounds
  116272. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  116273. etc... */
  116274. for(j=1;j<P_LEVELS;j++){
  116275. min_curve(athc[j],athc[j-1]);
  116276. min_curve(workc[i][j],athc[j]);
  116277. }
  116278. }
  116279. for(i=0;i<P_BANDS;i++){
  116280. int hi_curve,lo_curve,bin;
  116281. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  116282. /* low frequency curves are measured with greater resolution than
  116283. the MDCT/FFT will actually give us; we want the curve applied
  116284. to the tone data to be pessimistic and thus apply the minimum
  116285. masking possible for a given bin. That means that a single bin
  116286. could span more than one octave and that the curve will be a
  116287. composite of multiple octaves. It also may mean that a single
  116288. bin may span > an eighth of an octave and that the eighth
  116289. octave values may also be composited. */
  116290. /* which octave curves will we be compositing? */
  116291. bin=floor(fromOC(i*.5)/binHz);
  116292. lo_curve= ceil(toOC(bin*binHz+1)*2);
  116293. hi_curve= floor(toOC((bin+1)*binHz)*2);
  116294. if(lo_curve>i)lo_curve=i;
  116295. if(lo_curve<0)lo_curve=0;
  116296. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  116297. for(m=0;m<P_LEVELS;m++){
  116298. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  116299. for(j=0;j<n;j++)brute_buffer[j]=999.;
  116300. /* render the curve into bins, then pull values back into curve.
  116301. The point is that any inherent subsampling aliasing results in
  116302. a safe minimum */
  116303. for(k=lo_curve;k<=hi_curve;k++){
  116304. int l=0;
  116305. for(j=0;j<EHMER_MAX;j++){
  116306. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  116307. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  116308. if(lo_bin<0)lo_bin=0;
  116309. if(lo_bin>n)lo_bin=n;
  116310. if(lo_bin<l)l=lo_bin;
  116311. if(hi_bin<0)hi_bin=0;
  116312. if(hi_bin>n)hi_bin=n;
  116313. for(;l<hi_bin && l<n;l++)
  116314. if(brute_buffer[l]>workc[k][m][j])
  116315. brute_buffer[l]=workc[k][m][j];
  116316. }
  116317. for(;l<n;l++)
  116318. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  116319. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  116320. }
  116321. /* be equally paranoid about being valid up to next half ocatve */
  116322. if(i+1<P_BANDS){
  116323. int l=0;
  116324. k=i+1;
  116325. for(j=0;j<EHMER_MAX;j++){
  116326. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  116327. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  116328. if(lo_bin<0)lo_bin=0;
  116329. if(lo_bin>n)lo_bin=n;
  116330. if(lo_bin<l)l=lo_bin;
  116331. if(hi_bin<0)hi_bin=0;
  116332. if(hi_bin>n)hi_bin=n;
  116333. for(;l<hi_bin && l<n;l++)
  116334. if(brute_buffer[l]>workc[k][m][j])
  116335. brute_buffer[l]=workc[k][m][j];
  116336. }
  116337. for(;l<n;l++)
  116338. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  116339. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  116340. }
  116341. for(j=0;j<EHMER_MAX;j++){
  116342. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  116343. if(bin<0){
  116344. ret[i][m][j+2]=-999.;
  116345. }else{
  116346. if(bin>=n){
  116347. ret[i][m][j+2]=-999.;
  116348. }else{
  116349. ret[i][m][j+2]=brute_buffer[bin];
  116350. }
  116351. }
  116352. }
  116353. /* add fenceposts */
  116354. for(j=0;j<EHMER_OFFSET;j++)
  116355. if(ret[i][m][j+2]>-200.f)break;
  116356. ret[i][m][0]=j;
  116357. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  116358. if(ret[i][m][j+2]>-200.f)
  116359. break;
  116360. ret[i][m][1]=j;
  116361. }
  116362. }
  116363. return(ret);
  116364. }
  116365. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  116366. vorbis_info_psy_global *gi,int n,long rate){
  116367. long i,j,lo=-99,hi=1;
  116368. long maxoc;
  116369. memset(p,0,sizeof(*p));
  116370. p->eighth_octave_lines=gi->eighth_octave_lines;
  116371. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  116372. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  116373. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  116374. p->total_octave_lines=maxoc-p->firstoc+1;
  116375. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  116376. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  116377. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  116378. p->vi=vi;
  116379. p->n=n;
  116380. p->rate=rate;
  116381. /* AoTuV HF weighting */
  116382. p->m_val = 1.;
  116383. if(rate < 26000) p->m_val = 0;
  116384. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  116385. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  116386. /* set up the lookups for a given blocksize and sample rate */
  116387. for(i=0,j=0;i<MAX_ATH-1;i++){
  116388. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  116389. float base=ATH[i];
  116390. if(j<endpos){
  116391. float delta=(ATH[i+1]-base)/(endpos-j);
  116392. for(;j<endpos && j<n;j++){
  116393. p->ath[j]=base+100.;
  116394. base+=delta;
  116395. }
  116396. }
  116397. }
  116398. for(i=0;i<n;i++){
  116399. float bark=toBARK(rate/(2*n)*i);
  116400. for(;lo+vi->noisewindowlomin<i &&
  116401. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  116402. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  116403. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  116404. p->bark[i]=((lo-1)<<16)+(hi-1);
  116405. }
  116406. for(i=0;i<n;i++)
  116407. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  116408. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  116409. vi->tone_centerboost,vi->tone_decay);
  116410. /* set up rolling noise median */
  116411. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  116412. for(i=0;i<P_NOISECURVES;i++)
  116413. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  116414. for(i=0;i<n;i++){
  116415. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  116416. int inthalfoc;
  116417. float del;
  116418. if(halfoc<0)halfoc=0;
  116419. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  116420. inthalfoc=(int)halfoc;
  116421. del=halfoc-inthalfoc;
  116422. for(j=0;j<P_NOISECURVES;j++)
  116423. p->noiseoffset[j][i]=
  116424. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  116425. p->vi->noiseoff[j][inthalfoc+1]*del;
  116426. }
  116427. #if 0
  116428. {
  116429. static int ls=0;
  116430. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  116431. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  116432. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  116433. }
  116434. #endif
  116435. }
  116436. void _vp_psy_clear(vorbis_look_psy *p){
  116437. int i,j;
  116438. if(p){
  116439. if(p->ath)_ogg_free(p->ath);
  116440. if(p->octave)_ogg_free(p->octave);
  116441. if(p->bark)_ogg_free(p->bark);
  116442. if(p->tonecurves){
  116443. for(i=0;i<P_BANDS;i++){
  116444. for(j=0;j<P_LEVELS;j++){
  116445. _ogg_free(p->tonecurves[i][j]);
  116446. }
  116447. _ogg_free(p->tonecurves[i]);
  116448. }
  116449. _ogg_free(p->tonecurves);
  116450. }
  116451. if(p->noiseoffset){
  116452. for(i=0;i<P_NOISECURVES;i++){
  116453. _ogg_free(p->noiseoffset[i]);
  116454. }
  116455. _ogg_free(p->noiseoffset);
  116456. }
  116457. memset(p,0,sizeof(*p));
  116458. }
  116459. }
  116460. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  116461. static void seed_curve(float *seed,
  116462. const float **curves,
  116463. float amp,
  116464. int oc, int n,
  116465. int linesper,float dBoffset){
  116466. int i,post1;
  116467. int seedptr;
  116468. const float *posts,*curve;
  116469. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  116470. choice=max(choice,0);
  116471. choice=min(choice,P_LEVELS-1);
  116472. posts=curves[choice];
  116473. curve=posts+2;
  116474. post1=(int)posts[1];
  116475. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  116476. for(i=posts[0];i<post1;i++){
  116477. if(seedptr>0){
  116478. float lin=amp+curve[i];
  116479. if(seed[seedptr]<lin)seed[seedptr]=lin;
  116480. }
  116481. seedptr+=linesper;
  116482. if(seedptr>=n)break;
  116483. }
  116484. }
  116485. static void seed_loop(vorbis_look_psy *p,
  116486. const float ***curves,
  116487. const float *f,
  116488. const float *flr,
  116489. float *seed,
  116490. float specmax){
  116491. vorbis_info_psy *vi=p->vi;
  116492. long n=p->n,i;
  116493. float dBoffset=vi->max_curve_dB-specmax;
  116494. /* prime the working vector with peak values */
  116495. for(i=0;i<n;i++){
  116496. float max=f[i];
  116497. long oc=p->octave[i];
  116498. while(i+1<n && p->octave[i+1]==oc){
  116499. i++;
  116500. if(f[i]>max)max=f[i];
  116501. }
  116502. if(max+6.f>flr[i]){
  116503. oc=oc>>p->shiftoc;
  116504. if(oc>=P_BANDS)oc=P_BANDS-1;
  116505. if(oc<0)oc=0;
  116506. seed_curve(seed,
  116507. curves[oc],
  116508. max,
  116509. p->octave[i]-p->firstoc,
  116510. p->total_octave_lines,
  116511. p->eighth_octave_lines,
  116512. dBoffset);
  116513. }
  116514. }
  116515. }
  116516. static void seed_chase(float *seeds, int linesper, long n){
  116517. long *posstack=(long*)alloca(n*sizeof(*posstack));
  116518. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  116519. long stack=0;
  116520. long pos=0;
  116521. long i;
  116522. for(i=0;i<n;i++){
  116523. if(stack<2){
  116524. posstack[stack]=i;
  116525. ampstack[stack++]=seeds[i];
  116526. }else{
  116527. while(1){
  116528. if(seeds[i]<ampstack[stack-1]){
  116529. posstack[stack]=i;
  116530. ampstack[stack++]=seeds[i];
  116531. break;
  116532. }else{
  116533. if(i<posstack[stack-1]+linesper){
  116534. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  116535. i<posstack[stack-2]+linesper){
  116536. /* we completely overlap, making stack-1 irrelevant. pop it */
  116537. stack--;
  116538. continue;
  116539. }
  116540. }
  116541. posstack[stack]=i;
  116542. ampstack[stack++]=seeds[i];
  116543. break;
  116544. }
  116545. }
  116546. }
  116547. }
  116548. /* the stack now contains only the positions that are relevant. Scan
  116549. 'em straight through */
  116550. for(i=0;i<stack;i++){
  116551. long endpos;
  116552. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  116553. endpos=posstack[i+1];
  116554. }else{
  116555. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  116556. discarded in short frames */
  116557. }
  116558. if(endpos>n)endpos=n;
  116559. for(;pos<endpos;pos++)
  116560. seeds[pos]=ampstack[i];
  116561. }
  116562. /* there. Linear time. I now remember this was on a problem set I
  116563. had in Grad Skool... I didn't solve it at the time ;-) */
  116564. }
  116565. /* bleaugh, this is more complicated than it needs to be */
  116566. #include<stdio.h>
  116567. static void max_seeds(vorbis_look_psy *p,
  116568. float *seed,
  116569. float *flr){
  116570. long n=p->total_octave_lines;
  116571. int linesper=p->eighth_octave_lines;
  116572. long linpos=0;
  116573. long pos;
  116574. seed_chase(seed,linesper,n); /* for masking */
  116575. pos=p->octave[0]-p->firstoc-(linesper>>1);
  116576. while(linpos+1<p->n){
  116577. float minV=seed[pos];
  116578. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  116579. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  116580. while(pos+1<=end){
  116581. pos++;
  116582. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  116583. minV=seed[pos];
  116584. }
  116585. end=pos+p->firstoc;
  116586. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  116587. if(flr[linpos]<minV)flr[linpos]=minV;
  116588. }
  116589. {
  116590. float minV=seed[p->total_octave_lines-1];
  116591. for(;linpos<p->n;linpos++)
  116592. if(flr[linpos]<minV)flr[linpos]=minV;
  116593. }
  116594. }
  116595. static void bark_noise_hybridmp(int n,const long *b,
  116596. const float *f,
  116597. float *noise,
  116598. const float offset,
  116599. const int fixed){
  116600. float *N=(float*) alloca(n*sizeof(*N));
  116601. float *X=(float*) alloca(n*sizeof(*N));
  116602. float *XX=(float*) alloca(n*sizeof(*N));
  116603. float *Y=(float*) alloca(n*sizeof(*N));
  116604. float *XY=(float*) alloca(n*sizeof(*N));
  116605. float tN, tX, tXX, tY, tXY;
  116606. int i;
  116607. int lo, hi;
  116608. float R, A, B, D;
  116609. float w, x, y;
  116610. tN = tX = tXX = tY = tXY = 0.f;
  116611. y = f[0] + offset;
  116612. if (y < 1.f) y = 1.f;
  116613. w = y * y * .5;
  116614. tN += w;
  116615. tX += w;
  116616. tY += w * y;
  116617. N[0] = tN;
  116618. X[0] = tX;
  116619. XX[0] = tXX;
  116620. Y[0] = tY;
  116621. XY[0] = tXY;
  116622. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  116623. y = f[i] + offset;
  116624. if (y < 1.f) y = 1.f;
  116625. w = y * y;
  116626. tN += w;
  116627. tX += w * x;
  116628. tXX += w * x * x;
  116629. tY += w * y;
  116630. tXY += w * x * y;
  116631. N[i] = tN;
  116632. X[i] = tX;
  116633. XX[i] = tXX;
  116634. Y[i] = tY;
  116635. XY[i] = tXY;
  116636. }
  116637. for (i = 0, x = 0.f;; i++, x += 1.f) {
  116638. lo = b[i] >> 16;
  116639. if( lo>=0 ) break;
  116640. hi = b[i] & 0xffff;
  116641. tN = N[hi] + N[-lo];
  116642. tX = X[hi] - X[-lo];
  116643. tXX = XX[hi] + XX[-lo];
  116644. tY = Y[hi] + Y[-lo];
  116645. tXY = XY[hi] - XY[-lo];
  116646. A = tY * tXX - tX * tXY;
  116647. B = tN * tXY - tX * tY;
  116648. D = tN * tXX - tX * tX;
  116649. R = (A + x * B) / D;
  116650. if (R < 0.f)
  116651. R = 0.f;
  116652. noise[i] = R - offset;
  116653. }
  116654. for ( ;; i++, x += 1.f) {
  116655. lo = b[i] >> 16;
  116656. hi = b[i] & 0xffff;
  116657. if(hi>=n)break;
  116658. tN = N[hi] - N[lo];
  116659. tX = X[hi] - X[lo];
  116660. tXX = XX[hi] - XX[lo];
  116661. tY = Y[hi] - Y[lo];
  116662. tXY = XY[hi] - XY[lo];
  116663. A = tY * tXX - tX * tXY;
  116664. B = tN * tXY - tX * tY;
  116665. D = tN * tXX - tX * tX;
  116666. R = (A + x * B) / D;
  116667. if (R < 0.f) R = 0.f;
  116668. noise[i] = R - offset;
  116669. }
  116670. for ( ; i < n; i++, x += 1.f) {
  116671. R = (A + x * B) / D;
  116672. if (R < 0.f) R = 0.f;
  116673. noise[i] = R - offset;
  116674. }
  116675. if (fixed <= 0) return;
  116676. for (i = 0, x = 0.f;; i++, x += 1.f) {
  116677. hi = i + fixed / 2;
  116678. lo = hi - fixed;
  116679. if(lo>=0)break;
  116680. tN = N[hi] + N[-lo];
  116681. tX = X[hi] - X[-lo];
  116682. tXX = XX[hi] + XX[-lo];
  116683. tY = Y[hi] + Y[-lo];
  116684. tXY = XY[hi] - XY[-lo];
  116685. A = tY * tXX - tX * tXY;
  116686. B = tN * tXY - tX * tY;
  116687. D = tN * tXX - tX * tX;
  116688. R = (A + x * B) / D;
  116689. if (R - offset < noise[i]) noise[i] = R - offset;
  116690. }
  116691. for ( ;; i++, x += 1.f) {
  116692. hi = i + fixed / 2;
  116693. lo = hi - fixed;
  116694. if(hi>=n)break;
  116695. tN = N[hi] - N[lo];
  116696. tX = X[hi] - X[lo];
  116697. tXX = XX[hi] - XX[lo];
  116698. tY = Y[hi] - Y[lo];
  116699. tXY = XY[hi] - XY[lo];
  116700. A = tY * tXX - tX * tXY;
  116701. B = tN * tXY - tX * tY;
  116702. D = tN * tXX - tX * tX;
  116703. R = (A + x * B) / D;
  116704. if (R - offset < noise[i]) noise[i] = R - offset;
  116705. }
  116706. for ( ; i < n; i++, x += 1.f) {
  116707. R = (A + x * B) / D;
  116708. if (R - offset < noise[i]) noise[i] = R - offset;
  116709. }
  116710. }
  116711. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  116712. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  116713. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  116714. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  116715. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  116716. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  116717. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  116718. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  116719. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  116720. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  116721. 973377.F, 913981.F, 858210.F, 805842.F,
  116722. 756669.F, 710497.F, 667142.F, 626433.F,
  116723. 588208.F, 552316.F, 518613.F, 486967.F,
  116724. 457252.F, 429351.F, 403152.F, 378551.F,
  116725. 355452.F, 333762.F, 313396.F, 294273.F,
  116726. 276316.F, 259455.F, 243623.F, 228757.F,
  116727. 214798.F, 201691.F, 189384.F, 177828.F,
  116728. 166977.F, 156788.F, 147221.F, 138237.F,
  116729. 129802.F, 121881.F, 114444.F, 107461.F,
  116730. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  116731. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  116732. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  116733. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  116734. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  116735. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  116736. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  116737. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  116738. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  116739. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  116740. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  116741. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  116742. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  116743. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  116744. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  116745. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  116746. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  116747. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  116748. 1084.32F, 1018.15F, 956.024F, 897.687F,
  116749. 842.910F, 791.475F, 743.179F, 697.830F,
  116750. 655.249F, 615.265F, 577.722F, 542.469F,
  116751. 509.367F, 478.286F, 449.101F, 421.696F,
  116752. 395.964F, 371.803F, 349.115F, 327.812F,
  116753. 307.809F, 289.026F, 271.390F, 254.830F,
  116754. 239.280F, 224.679F, 210.969F, 198.096F,
  116755. 186.008F, 174.658F, 164.000F, 153.993F,
  116756. 144.596F, 135.773F, 127.488F, 119.708F,
  116757. 112.404F, 105.545F, 99.1046F, 93.0572F,
  116758. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  116759. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  116760. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  116761. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  116762. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  116763. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  116764. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  116765. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  116766. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  116767. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  116768. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  116769. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  116770. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  116771. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  116772. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  116773. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  116774. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  116775. 1.20790F, 1.13419F, 1.06499F, 1.F
  116776. };
  116777. void _vp_remove_floor(vorbis_look_psy *p,
  116778. float *mdct,
  116779. int *codedflr,
  116780. float *residue,
  116781. int sliding_lowpass){
  116782. int i,n=p->n;
  116783. if(sliding_lowpass>n)sliding_lowpass=n;
  116784. for(i=0;i<sliding_lowpass;i++){
  116785. residue[i]=
  116786. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  116787. }
  116788. for(;i<n;i++)
  116789. residue[i]=0.;
  116790. }
  116791. void _vp_noisemask(vorbis_look_psy *p,
  116792. float *logmdct,
  116793. float *logmask){
  116794. int i,n=p->n;
  116795. float *work=(float*) alloca(n*sizeof(*work));
  116796. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  116797. 140.,-1);
  116798. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  116799. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  116800. p->vi->noisewindowfixed);
  116801. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  116802. #if 0
  116803. {
  116804. static int seq=0;
  116805. float work2[n];
  116806. for(i=0;i<n;i++){
  116807. work2[i]=logmask[i]+work[i];
  116808. }
  116809. if(seq&1)
  116810. _analysis_output("median2R",seq/2,work,n,1,0,0);
  116811. else
  116812. _analysis_output("median2L",seq/2,work,n,1,0,0);
  116813. if(seq&1)
  116814. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  116815. else
  116816. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  116817. seq++;
  116818. }
  116819. #endif
  116820. for(i=0;i<n;i++){
  116821. int dB=logmask[i]+.5;
  116822. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  116823. if(dB<0)dB=0;
  116824. logmask[i]= work[i]+p->vi->noisecompand[dB];
  116825. }
  116826. }
  116827. void _vp_tonemask(vorbis_look_psy *p,
  116828. float *logfft,
  116829. float *logmask,
  116830. float global_specmax,
  116831. float local_specmax){
  116832. int i,n=p->n;
  116833. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  116834. float att=local_specmax+p->vi->ath_adjatt;
  116835. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  116836. /* set the ATH (floating below localmax, not global max by a
  116837. specified att) */
  116838. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  116839. for(i=0;i<n;i++)
  116840. logmask[i]=p->ath[i]+att;
  116841. /* tone masking */
  116842. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  116843. max_seeds(p,seed,logmask);
  116844. }
  116845. void _vp_offset_and_mix(vorbis_look_psy *p,
  116846. float *noise,
  116847. float *tone,
  116848. int offset_select,
  116849. float *logmask,
  116850. float *mdct,
  116851. float *logmdct){
  116852. int i,n=p->n;
  116853. float de, coeffi, cx;/* AoTuV */
  116854. float toneatt=p->vi->tone_masteratt[offset_select];
  116855. cx = p->m_val;
  116856. for(i=0;i<n;i++){
  116857. float val= noise[i]+p->noiseoffset[offset_select][i];
  116858. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  116859. logmask[i]=max(val,tone[i]+toneatt);
  116860. /* AoTuV */
  116861. /** @ M1 **
  116862. The following codes improve a noise problem.
  116863. A fundamental idea uses the value of masking and carries out
  116864. the relative compensation of the MDCT.
  116865. However, this code is not perfect and all noise problems cannot be solved.
  116866. by Aoyumi @ 2004/04/18
  116867. */
  116868. if(offset_select == 1) {
  116869. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  116870. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  116871. if(val > coeffi){
  116872. /* mdct value is > -17.2 dB below floor */
  116873. de = 1.0-((val-coeffi)*0.005*cx);
  116874. /* pro-rated attenuation:
  116875. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  116876. -0.77 dB boost if mdct value is 0dB (relative to floor)
  116877. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  116878. etc... */
  116879. if(de < 0) de = 0.0001;
  116880. }else
  116881. /* mdct value is <= -17.2 dB below floor */
  116882. de = 1.0-((val-coeffi)*0.0003*cx);
  116883. /* pro-rated attenuation:
  116884. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  116885. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  116886. etc... */
  116887. mdct[i] *= de;
  116888. }
  116889. }
  116890. }
  116891. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  116892. vorbis_info *vi=vd->vi;
  116893. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  116894. vorbis_info_psy_global *gi=&ci->psy_g_param;
  116895. int n=ci->blocksizes[vd->W]/2;
  116896. float secs=(float)n/vi->rate;
  116897. amp+=secs*gi->ampmax_att_per_sec;
  116898. if(amp<-9999)amp=-9999;
  116899. return(amp);
  116900. }
  116901. static void couple_lossless(float A, float B,
  116902. float *qA, float *qB){
  116903. int test1=fabs(*qA)>fabs(*qB);
  116904. test1-= fabs(*qA)<fabs(*qB);
  116905. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  116906. if(test1==1){
  116907. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  116908. }else{
  116909. float temp=*qB;
  116910. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  116911. *qA=temp;
  116912. }
  116913. if(*qB>fabs(*qA)*1.9999f){
  116914. *qB= -fabs(*qA)*2.f;
  116915. *qA= -*qA;
  116916. }
  116917. }
  116918. static float hypot_lookup[32]={
  116919. -0.009935, -0.011245, -0.012726, -0.014397,
  116920. -0.016282, -0.018407, -0.020800, -0.023494,
  116921. -0.026522, -0.029923, -0.033737, -0.038010,
  116922. -0.042787, -0.048121, -0.054064, -0.060671,
  116923. -0.068000, -0.076109, -0.085054, -0.094892,
  116924. -0.105675, -0.117451, -0.130260, -0.144134,
  116925. -0.159093, -0.175146, -0.192286, -0.210490,
  116926. -0.229718, -0.249913, -0.271001, -0.292893};
  116927. static void precomputed_couple_point(float premag,
  116928. int floorA,int floorB,
  116929. float *mag, float *ang){
  116930. int test=(floorA>floorB)-1;
  116931. int offset=31-abs(floorA-floorB);
  116932. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  116933. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  116934. *mag=premag*floormag;
  116935. *ang=0.f;
  116936. }
  116937. /* just like below, this is currently set up to only do
  116938. single-step-depth coupling. Otherwise, we'd have to do more
  116939. copying (which will be inevitable later) */
  116940. /* doing the real circular magnitude calculation is audibly superior
  116941. to (A+B)/sqrt(2) */
  116942. static float dipole_hypot(float a, float b){
  116943. if(a>0.){
  116944. if(b>0.)return sqrt(a*a+b*b);
  116945. if(a>-b)return sqrt(a*a-b*b);
  116946. return -sqrt(b*b-a*a);
  116947. }
  116948. if(b<0.)return -sqrt(a*a+b*b);
  116949. if(-a>b)return -sqrt(a*a-b*b);
  116950. return sqrt(b*b-a*a);
  116951. }
  116952. static float round_hypot(float a, float b){
  116953. if(a>0.){
  116954. if(b>0.)return sqrt(a*a+b*b);
  116955. if(a>-b)return sqrt(a*a+b*b);
  116956. return -sqrt(b*b+a*a);
  116957. }
  116958. if(b<0.)return -sqrt(a*a+b*b);
  116959. if(-a>b)return -sqrt(a*a+b*b);
  116960. return sqrt(b*b+a*a);
  116961. }
  116962. /* revert to round hypot for now */
  116963. float **_vp_quantize_couple_memo(vorbis_block *vb,
  116964. vorbis_info_psy_global *g,
  116965. vorbis_look_psy *p,
  116966. vorbis_info_mapping0 *vi,
  116967. float **mdct){
  116968. int i,j,n=p->n;
  116969. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  116970. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  116971. for(i=0;i<vi->coupling_steps;i++){
  116972. float *mdctM=mdct[vi->coupling_mag[i]];
  116973. float *mdctA=mdct[vi->coupling_ang[i]];
  116974. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  116975. for(j=0;j<limit;j++)
  116976. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  116977. for(;j<n;j++)
  116978. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  116979. }
  116980. return(ret);
  116981. }
  116982. /* this is for per-channel noise normalization */
  116983. static int apsort(const void *a, const void *b){
  116984. float f1=fabs(**(float**)a);
  116985. float f2=fabs(**(float**)b);
  116986. return (f1<f2)-(f1>f2);
  116987. }
  116988. int **_vp_quantize_couple_sort(vorbis_block *vb,
  116989. vorbis_look_psy *p,
  116990. vorbis_info_mapping0 *vi,
  116991. float **mags){
  116992. if(p->vi->normal_point_p){
  116993. int i,j,k,n=p->n;
  116994. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  116995. int partition=p->vi->normal_partition;
  116996. float **work=(float**) alloca(sizeof(*work)*partition);
  116997. for(i=0;i<vi->coupling_steps;i++){
  116998. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  116999. for(j=0;j<n;j+=partition){
  117000. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  117001. qsort(work,partition,sizeof(*work),apsort);
  117002. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  117003. }
  117004. }
  117005. return(ret);
  117006. }
  117007. return(NULL);
  117008. }
  117009. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  117010. float *magnitudes,int *sortedindex){
  117011. int i,j,n=p->n;
  117012. vorbis_info_psy *vi=p->vi;
  117013. int partition=vi->normal_partition;
  117014. float **work=(float**) alloca(sizeof(*work)*partition);
  117015. int start=vi->normal_start;
  117016. for(j=start;j<n;j+=partition){
  117017. if(j+partition>n)partition=n-j;
  117018. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  117019. qsort(work,partition,sizeof(*work),apsort);
  117020. for(i=0;i<partition;i++){
  117021. sortedindex[i+j-start]=work[i]-magnitudes;
  117022. }
  117023. }
  117024. }
  117025. void _vp_noise_normalize(vorbis_look_psy *p,
  117026. float *in,float *out,int *sortedindex){
  117027. int flag=0,i,j=0,n=p->n;
  117028. vorbis_info_psy *vi=p->vi;
  117029. int partition=vi->normal_partition;
  117030. int start=vi->normal_start;
  117031. if(start>n)start=n;
  117032. if(vi->normal_channel_p){
  117033. for(;j<start;j++)
  117034. out[j]=rint(in[j]);
  117035. for(;j+partition<=n;j+=partition){
  117036. float acc=0.;
  117037. int k;
  117038. for(i=j;i<j+partition;i++)
  117039. acc+=in[i]*in[i];
  117040. for(i=0;i<partition;i++){
  117041. k=sortedindex[i+j-start];
  117042. if(in[k]*in[k]>=.25f){
  117043. out[k]=rint(in[k]);
  117044. acc-=in[k]*in[k];
  117045. flag=1;
  117046. }else{
  117047. if(acc<vi->normal_thresh)break;
  117048. out[k]=unitnorm(in[k]);
  117049. acc-=1.;
  117050. }
  117051. }
  117052. for(;i<partition;i++){
  117053. k=sortedindex[i+j-start];
  117054. out[k]=0.;
  117055. }
  117056. }
  117057. }
  117058. for(;j<n;j++)
  117059. out[j]=rint(in[j]);
  117060. }
  117061. void _vp_couple(int blobno,
  117062. vorbis_info_psy_global *g,
  117063. vorbis_look_psy *p,
  117064. vorbis_info_mapping0 *vi,
  117065. float **res,
  117066. float **mag_memo,
  117067. int **mag_sort,
  117068. int **ifloor,
  117069. int *nonzero,
  117070. int sliding_lowpass){
  117071. int i,j,k,n=p->n;
  117072. /* perform any requested channel coupling */
  117073. /* point stereo can only be used in a first stage (in this encoder)
  117074. because of the dependency on floor lookups */
  117075. for(i=0;i<vi->coupling_steps;i++){
  117076. /* once we're doing multistage coupling in which a channel goes
  117077. through more than one coupling step, the floor vector
  117078. magnitudes will also have to be recalculated an propogated
  117079. along with PCM. Right now, we're not (that will wait until 5.1
  117080. most likely), so the code isn't here yet. The memory management
  117081. here is all assuming single depth couplings anyway. */
  117082. /* make sure coupling a zero and a nonzero channel results in two
  117083. nonzero channels. */
  117084. if(nonzero[vi->coupling_mag[i]] ||
  117085. nonzero[vi->coupling_ang[i]]){
  117086. float *rM=res[vi->coupling_mag[i]];
  117087. float *rA=res[vi->coupling_ang[i]];
  117088. float *qM=rM+n;
  117089. float *qA=rA+n;
  117090. int *floorM=ifloor[vi->coupling_mag[i]];
  117091. int *floorA=ifloor[vi->coupling_ang[i]];
  117092. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  117093. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  117094. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  117095. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  117096. int pointlimit=limit;
  117097. nonzero[vi->coupling_mag[i]]=1;
  117098. nonzero[vi->coupling_ang[i]]=1;
  117099. /* The threshold of a stereo is changed with the size of n */
  117100. if(n > 1000)
  117101. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  117102. for(j=0;j<p->n;j+=partition){
  117103. float acc=0.f;
  117104. for(k=0;k<partition;k++){
  117105. int l=k+j;
  117106. if(l<sliding_lowpass){
  117107. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  117108. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  117109. precomputed_couple_point(mag_memo[i][l],
  117110. floorM[l],floorA[l],
  117111. qM+l,qA+l);
  117112. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  117113. }else{
  117114. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  117115. }
  117116. }else{
  117117. qM[l]=0.;
  117118. qA[l]=0.;
  117119. }
  117120. }
  117121. if(p->vi->normal_point_p){
  117122. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  117123. int l=mag_sort[i][j+k];
  117124. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  117125. qM[l]=unitnorm(qM[l]);
  117126. acc-=1.f;
  117127. }
  117128. }
  117129. }
  117130. }
  117131. }
  117132. }
  117133. }
  117134. /* AoTuV */
  117135. /** @ M2 **
  117136. The boost problem by the combination of noise normalization and point stereo is eased.
  117137. However, this is a temporary patch.
  117138. by Aoyumi @ 2004/04/18
  117139. */
  117140. void hf_reduction(vorbis_info_psy_global *g,
  117141. vorbis_look_psy *p,
  117142. vorbis_info_mapping0 *vi,
  117143. float **mdct){
  117144. int i,j,n=p->n, de=0.3*p->m_val;
  117145. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  117146. for(i=0; i<vi->coupling_steps; i++){
  117147. /* for(j=start; j<limit; j++){} // ???*/
  117148. for(j=limit; j<n; j++)
  117149. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  117150. }
  117151. }
  117152. #endif
  117153. /*** End of inlined file: psy.c ***/
  117154. /*** Start of inlined file: registry.c ***/
  117155. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  117156. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  117157. // tasks..
  117158. #if JUCE_MSVC
  117159. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  117160. #endif
  117161. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  117162. #if JUCE_USE_OGGVORBIS
  117163. /* seems like major overkill now; the backend numbers will grow into
  117164. the infrastructure soon enough */
  117165. extern vorbis_func_floor floor0_exportbundle;
  117166. extern vorbis_func_floor floor1_exportbundle;
  117167. extern vorbis_func_residue residue0_exportbundle;
  117168. extern vorbis_func_residue residue1_exportbundle;
  117169. extern vorbis_func_residue residue2_exportbundle;
  117170. extern vorbis_func_mapping mapping0_exportbundle;
  117171. vorbis_func_floor *_floor_P[]={
  117172. &floor0_exportbundle,
  117173. &floor1_exportbundle,
  117174. };
  117175. vorbis_func_residue *_residue_P[]={
  117176. &residue0_exportbundle,
  117177. &residue1_exportbundle,
  117178. &residue2_exportbundle,
  117179. };
  117180. vorbis_func_mapping *_mapping_P[]={
  117181. &mapping0_exportbundle,
  117182. };
  117183. #endif
  117184. /*** End of inlined file: registry.c ***/
  117185. /*** Start of inlined file: res0.c ***/
  117186. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  117187. encode/decode loops are coded for clarity and performance is not
  117188. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  117189. it's slow. */
  117190. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  117191. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  117192. // tasks..
  117193. #if JUCE_MSVC
  117194. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  117195. #endif
  117196. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  117197. #if JUCE_USE_OGGVORBIS
  117198. #include <stdlib.h>
  117199. #include <string.h>
  117200. #include <math.h>
  117201. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  117202. #include <stdio.h>
  117203. #endif
  117204. typedef struct {
  117205. vorbis_info_residue0 *info;
  117206. int parts;
  117207. int stages;
  117208. codebook *fullbooks;
  117209. codebook *phrasebook;
  117210. codebook ***partbooks;
  117211. int partvals;
  117212. int **decodemap;
  117213. long postbits;
  117214. long phrasebits;
  117215. long frames;
  117216. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  117217. int train_seq;
  117218. long *training_data[8][64];
  117219. float training_max[8][64];
  117220. float training_min[8][64];
  117221. float tmin;
  117222. float tmax;
  117223. #endif
  117224. } vorbis_look_residue0;
  117225. void res0_free_info(vorbis_info_residue *i){
  117226. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  117227. if(info){
  117228. memset(info,0,sizeof(*info));
  117229. _ogg_free(info);
  117230. }
  117231. }
  117232. void res0_free_look(vorbis_look_residue *i){
  117233. int j;
  117234. if(i){
  117235. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  117236. #ifdef TRAIN_RES
  117237. {
  117238. int j,k,l;
  117239. for(j=0;j<look->parts;j++){
  117240. /*fprintf(stderr,"partition %d: ",j);*/
  117241. for(k=0;k<8;k++)
  117242. if(look->training_data[k][j]){
  117243. char buffer[80];
  117244. FILE *of;
  117245. codebook *statebook=look->partbooks[j][k];
  117246. /* long and short into the same bucket by current convention */
  117247. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  117248. of=fopen(buffer,"a");
  117249. for(l=0;l<statebook->entries;l++)
  117250. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  117251. fclose(of);
  117252. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  117253. look->training_min[k][j],look->training_max[k][j]);*/
  117254. _ogg_free(look->training_data[k][j]);
  117255. look->training_data[k][j]=NULL;
  117256. }
  117257. /*fprintf(stderr,"\n");*/
  117258. }
  117259. }
  117260. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  117261. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  117262. (float)look->phrasebits/look->frames,
  117263. (float)look->postbits/look->frames,
  117264. (float)(look->postbits+look->phrasebits)/look->frames);*/
  117265. #endif
  117266. /*vorbis_info_residue0 *info=look->info;
  117267. fprintf(stderr,
  117268. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  117269. "(%g/frame) \n",look->frames,look->phrasebits,
  117270. look->resbitsflat,
  117271. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  117272. for(j=0;j<look->parts;j++){
  117273. long acc=0;
  117274. fprintf(stderr,"\t[%d] == ",j);
  117275. for(k=0;k<look->stages;k++)
  117276. if((info->secondstages[j]>>k)&1){
  117277. fprintf(stderr,"%ld,",look->resbits[j][k]);
  117278. acc+=look->resbits[j][k];
  117279. }
  117280. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  117281. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  117282. }
  117283. fprintf(stderr,"\n");*/
  117284. for(j=0;j<look->parts;j++)
  117285. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  117286. _ogg_free(look->partbooks);
  117287. for(j=0;j<look->partvals;j++)
  117288. _ogg_free(look->decodemap[j]);
  117289. _ogg_free(look->decodemap);
  117290. memset(look,0,sizeof(*look));
  117291. _ogg_free(look);
  117292. }
  117293. }
  117294. static int icount(unsigned int v){
  117295. int ret=0;
  117296. while(v){
  117297. ret+=v&1;
  117298. v>>=1;
  117299. }
  117300. return(ret);
  117301. }
  117302. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  117303. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  117304. int j,acc=0;
  117305. oggpack_write(opb,info->begin,24);
  117306. oggpack_write(opb,info->end,24);
  117307. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  117308. code with a partitioned book */
  117309. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  117310. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  117311. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  117312. bitmask of one indicates this partition class has bits to write
  117313. this pass */
  117314. for(j=0;j<info->partitions;j++){
  117315. if(ilog(info->secondstages[j])>3){
  117316. /* yes, this is a minor hack due to not thinking ahead */
  117317. oggpack_write(opb,info->secondstages[j],3);
  117318. oggpack_write(opb,1,1);
  117319. oggpack_write(opb,info->secondstages[j]>>3,5);
  117320. }else
  117321. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  117322. acc+=icount(info->secondstages[j]);
  117323. }
  117324. for(j=0;j<acc;j++)
  117325. oggpack_write(opb,info->booklist[j],8);
  117326. }
  117327. /* vorbis_info is for range checking */
  117328. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  117329. int j,acc=0;
  117330. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  117331. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  117332. info->begin=oggpack_read(opb,24);
  117333. info->end=oggpack_read(opb,24);
  117334. info->grouping=oggpack_read(opb,24)+1;
  117335. info->partitions=oggpack_read(opb,6)+1;
  117336. info->groupbook=oggpack_read(opb,8);
  117337. for(j=0;j<info->partitions;j++){
  117338. int cascade=oggpack_read(opb,3);
  117339. if(oggpack_read(opb,1))
  117340. cascade|=(oggpack_read(opb,5)<<3);
  117341. info->secondstages[j]=cascade;
  117342. acc+=icount(cascade);
  117343. }
  117344. for(j=0;j<acc;j++)
  117345. info->booklist[j]=oggpack_read(opb,8);
  117346. if(info->groupbook>=ci->books)goto errout;
  117347. for(j=0;j<acc;j++)
  117348. if(info->booklist[j]>=ci->books)goto errout;
  117349. return(info);
  117350. errout:
  117351. res0_free_info(info);
  117352. return(NULL);
  117353. }
  117354. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  117355. vorbis_info_residue *vr){
  117356. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  117357. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  117358. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  117359. int j,k,acc=0;
  117360. int dim;
  117361. int maxstage=0;
  117362. look->info=info;
  117363. look->parts=info->partitions;
  117364. look->fullbooks=ci->fullbooks;
  117365. look->phrasebook=ci->fullbooks+info->groupbook;
  117366. dim=look->phrasebook->dim;
  117367. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  117368. for(j=0;j<look->parts;j++){
  117369. int stages=ilog(info->secondstages[j]);
  117370. if(stages){
  117371. if(stages>maxstage)maxstage=stages;
  117372. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  117373. for(k=0;k<stages;k++)
  117374. if(info->secondstages[j]&(1<<k)){
  117375. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  117376. #ifdef TRAIN_RES
  117377. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  117378. sizeof(***look->training_data));
  117379. #endif
  117380. }
  117381. }
  117382. }
  117383. look->partvals=rint(pow((float)look->parts,(float)dim));
  117384. look->stages=maxstage;
  117385. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  117386. for(j=0;j<look->partvals;j++){
  117387. long val=j;
  117388. long mult=look->partvals/look->parts;
  117389. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  117390. for(k=0;k<dim;k++){
  117391. long deco=val/mult;
  117392. val-=deco*mult;
  117393. mult/=look->parts;
  117394. look->decodemap[j][k]=deco;
  117395. }
  117396. }
  117397. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  117398. {
  117399. static int train_seq=0;
  117400. look->train_seq=train_seq++;
  117401. }
  117402. #endif
  117403. return(look);
  117404. }
  117405. /* break an abstraction and copy some code for performance purposes */
  117406. static int local_book_besterror(codebook *book,float *a){
  117407. int dim=book->dim,i,k,o;
  117408. int best=0;
  117409. encode_aux_threshmatch *tt=book->c->thresh_tree;
  117410. /* find the quant val of each scalar */
  117411. for(k=0,o=dim;k<dim;++k){
  117412. float val=a[--o];
  117413. i=tt->threshvals>>1;
  117414. if(val<tt->quantthresh[i]){
  117415. if(val<tt->quantthresh[i-1]){
  117416. for(--i;i>0;--i)
  117417. if(val>=tt->quantthresh[i-1])
  117418. break;
  117419. }
  117420. }else{
  117421. for(++i;i<tt->threshvals-1;++i)
  117422. if(val<tt->quantthresh[i])break;
  117423. }
  117424. best=(best*tt->quantvals)+tt->quantmap[i];
  117425. }
  117426. /* regular lattices are easy :-) */
  117427. if(book->c->lengthlist[best]<=0){
  117428. const static_codebook *c=book->c;
  117429. int i,j;
  117430. float bestf=0.f;
  117431. float *e=book->valuelist;
  117432. best=-1;
  117433. for(i=0;i<book->entries;i++){
  117434. if(c->lengthlist[i]>0){
  117435. float thisx=0.f;
  117436. for(j=0;j<dim;j++){
  117437. float val=(e[j]-a[j]);
  117438. thisx+=val*val;
  117439. }
  117440. if(best==-1 || thisx<bestf){
  117441. bestf=thisx;
  117442. best=i;
  117443. }
  117444. }
  117445. e+=dim;
  117446. }
  117447. }
  117448. {
  117449. float *ptr=book->valuelist+best*dim;
  117450. for(i=0;i<dim;i++)
  117451. *a++ -= *ptr++;
  117452. }
  117453. return(best);
  117454. }
  117455. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  117456. codebook *book,long *acc){
  117457. int i,bits=0;
  117458. int dim=book->dim;
  117459. int step=n/dim;
  117460. for(i=0;i<step;i++){
  117461. int entry=local_book_besterror(book,vec+i*dim);
  117462. #ifdef TRAIN_RES
  117463. acc[entry]++;
  117464. #endif
  117465. bits+=vorbis_book_encode(book,entry,opb);
  117466. }
  117467. return(bits);
  117468. }
  117469. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  117470. float **in,int ch){
  117471. long i,j,k;
  117472. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  117473. vorbis_info_residue0 *info=look->info;
  117474. /* move all this setup out later */
  117475. int samples_per_partition=info->grouping;
  117476. int possible_partitions=info->partitions;
  117477. int n=info->end-info->begin;
  117478. int partvals=n/samples_per_partition;
  117479. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  117480. float scale=100./samples_per_partition;
  117481. /* we find the partition type for each partition of each
  117482. channel. We'll go back and do the interleaved encoding in a
  117483. bit. For now, clarity */
  117484. for(i=0;i<ch;i++){
  117485. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  117486. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  117487. }
  117488. for(i=0;i<partvals;i++){
  117489. int offset=i*samples_per_partition+info->begin;
  117490. for(j=0;j<ch;j++){
  117491. float max=0.;
  117492. float ent=0.;
  117493. for(k=0;k<samples_per_partition;k++){
  117494. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  117495. ent+=fabs(rint(in[j][offset+k]));
  117496. }
  117497. ent*=scale;
  117498. for(k=0;k<possible_partitions-1;k++)
  117499. if(max<=info->classmetric1[k] &&
  117500. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  117501. break;
  117502. partword[j][i]=k;
  117503. }
  117504. }
  117505. #ifdef TRAIN_RESAUX
  117506. {
  117507. FILE *of;
  117508. char buffer[80];
  117509. for(i=0;i<ch;i++){
  117510. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  117511. of=fopen(buffer,"a");
  117512. for(j=0;j<partvals;j++)
  117513. fprintf(of,"%ld, ",partword[i][j]);
  117514. fprintf(of,"\n");
  117515. fclose(of);
  117516. }
  117517. }
  117518. #endif
  117519. look->frames++;
  117520. return(partword);
  117521. }
  117522. /* designed for stereo or other modes where the partition size is an
  117523. integer multiple of the number of channels encoded in the current
  117524. submap */
  117525. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  117526. int ch){
  117527. long i,j,k,l;
  117528. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  117529. vorbis_info_residue0 *info=look->info;
  117530. /* move all this setup out later */
  117531. int samples_per_partition=info->grouping;
  117532. int possible_partitions=info->partitions;
  117533. int n=info->end-info->begin;
  117534. int partvals=n/samples_per_partition;
  117535. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  117536. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  117537. FILE *of;
  117538. char buffer[80];
  117539. #endif
  117540. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  117541. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  117542. for(i=0,l=info->begin/ch;i<partvals;i++){
  117543. float magmax=0.f;
  117544. float angmax=0.f;
  117545. for(j=0;j<samples_per_partition;j+=ch){
  117546. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  117547. for(k=1;k<ch;k++)
  117548. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  117549. l++;
  117550. }
  117551. for(j=0;j<possible_partitions-1;j++)
  117552. if(magmax<=info->classmetric1[j] &&
  117553. angmax<=info->classmetric2[j])
  117554. break;
  117555. partword[0][i]=j;
  117556. }
  117557. #ifdef TRAIN_RESAUX
  117558. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  117559. of=fopen(buffer,"a");
  117560. for(i=0;i<partvals;i++)
  117561. fprintf(of,"%ld, ",partword[0][i]);
  117562. fprintf(of,"\n");
  117563. fclose(of);
  117564. #endif
  117565. look->frames++;
  117566. return(partword);
  117567. }
  117568. static int _01forward(oggpack_buffer *opb,
  117569. vorbis_block *vb,vorbis_look_residue *vl,
  117570. float **in,int ch,
  117571. long **partword,
  117572. int (*encode)(oggpack_buffer *,float *,int,
  117573. codebook *,long *)){
  117574. long i,j,k,s;
  117575. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  117576. vorbis_info_residue0 *info=look->info;
  117577. /* move all this setup out later */
  117578. int samples_per_partition=info->grouping;
  117579. int possible_partitions=info->partitions;
  117580. int partitions_per_word=look->phrasebook->dim;
  117581. int n=info->end-info->begin;
  117582. int partvals=n/samples_per_partition;
  117583. long resbits[128];
  117584. long resvals[128];
  117585. #ifdef TRAIN_RES
  117586. for(i=0;i<ch;i++)
  117587. for(j=info->begin;j<info->end;j++){
  117588. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  117589. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  117590. }
  117591. #endif
  117592. memset(resbits,0,sizeof(resbits));
  117593. memset(resvals,0,sizeof(resvals));
  117594. /* we code the partition words for each channel, then the residual
  117595. words for a partition per channel until we've written all the
  117596. residual words for that partition word. Then write the next
  117597. partition channel words... */
  117598. for(s=0;s<look->stages;s++){
  117599. for(i=0;i<partvals;){
  117600. /* first we encode a partition codeword for each channel */
  117601. if(s==0){
  117602. for(j=0;j<ch;j++){
  117603. long val=partword[j][i];
  117604. for(k=1;k<partitions_per_word;k++){
  117605. val*=possible_partitions;
  117606. if(i+k<partvals)
  117607. val+=partword[j][i+k];
  117608. }
  117609. /* training hack */
  117610. if(val<look->phrasebook->entries)
  117611. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  117612. #if 0 /*def TRAIN_RES*/
  117613. else
  117614. fprintf(stderr,"!");
  117615. #endif
  117616. }
  117617. }
  117618. /* now we encode interleaved residual values for the partitions */
  117619. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  117620. long offset=i*samples_per_partition+info->begin;
  117621. for(j=0;j<ch;j++){
  117622. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  117623. if(info->secondstages[partword[j][i]]&(1<<s)){
  117624. codebook *statebook=look->partbooks[partword[j][i]][s];
  117625. if(statebook){
  117626. int ret;
  117627. long *accumulator=NULL;
  117628. #ifdef TRAIN_RES
  117629. accumulator=look->training_data[s][partword[j][i]];
  117630. {
  117631. int l;
  117632. float *samples=in[j]+offset;
  117633. for(l=0;l<samples_per_partition;l++){
  117634. if(samples[l]<look->training_min[s][partword[j][i]])
  117635. look->training_min[s][partword[j][i]]=samples[l];
  117636. if(samples[l]>look->training_max[s][partword[j][i]])
  117637. look->training_max[s][partword[j][i]]=samples[l];
  117638. }
  117639. }
  117640. #endif
  117641. ret=encode(opb,in[j]+offset,samples_per_partition,
  117642. statebook,accumulator);
  117643. look->postbits+=ret;
  117644. resbits[partword[j][i]]+=ret;
  117645. }
  117646. }
  117647. }
  117648. }
  117649. }
  117650. }
  117651. /*{
  117652. long total=0;
  117653. long totalbits=0;
  117654. fprintf(stderr,"%d :: ",vb->mode);
  117655. for(k=0;k<possible_partitions;k++){
  117656. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  117657. total+=resvals[k];
  117658. totalbits+=resbits[k];
  117659. }
  117660. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  117661. }*/
  117662. return(0);
  117663. }
  117664. /* a truncated packet here just means 'stop working'; it's not an error */
  117665. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  117666. float **in,int ch,
  117667. long (*decodepart)(codebook *, float *,
  117668. oggpack_buffer *,int)){
  117669. long i,j,k,l,s;
  117670. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  117671. vorbis_info_residue0 *info=look->info;
  117672. /* move all this setup out later */
  117673. int samples_per_partition=info->grouping;
  117674. int partitions_per_word=look->phrasebook->dim;
  117675. int n=info->end-info->begin;
  117676. int partvals=n/samples_per_partition;
  117677. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  117678. int ***partword=(int***)alloca(ch*sizeof(*partword));
  117679. for(j=0;j<ch;j++)
  117680. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  117681. for(s=0;s<look->stages;s++){
  117682. /* each loop decodes on partition codeword containing
  117683. partitions_pre_word partitions */
  117684. for(i=0,l=0;i<partvals;l++){
  117685. if(s==0){
  117686. /* fetch the partition word for each channel */
  117687. for(j=0;j<ch;j++){
  117688. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  117689. if(temp==-1)goto eopbreak;
  117690. partword[j][l]=look->decodemap[temp];
  117691. if(partword[j][l]==NULL)goto errout;
  117692. }
  117693. }
  117694. /* now we decode residual values for the partitions */
  117695. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  117696. for(j=0;j<ch;j++){
  117697. long offset=info->begin+i*samples_per_partition;
  117698. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  117699. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  117700. if(stagebook){
  117701. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  117702. samples_per_partition)==-1)goto eopbreak;
  117703. }
  117704. }
  117705. }
  117706. }
  117707. }
  117708. errout:
  117709. eopbreak:
  117710. return(0);
  117711. }
  117712. #if 0
  117713. /* residue 0 and 1 are just slight variants of one another. 0 is
  117714. interleaved, 1 is not */
  117715. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  117716. float **in,int *nonzero,int ch){
  117717. /* we encode only the nonzero parts of a bundle */
  117718. int i,used=0;
  117719. for(i=0;i<ch;i++)
  117720. if(nonzero[i])
  117721. in[used++]=in[i];
  117722. if(used)
  117723. /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
  117724. return(_01class(vb,vl,in,used));
  117725. else
  117726. return(0);
  117727. }
  117728. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  117729. float **in,float **out,int *nonzero,int ch,
  117730. long **partword){
  117731. /* we encode only the nonzero parts of a bundle */
  117732. int i,j,used=0,n=vb->pcmend/2;
  117733. for(i=0;i<ch;i++)
  117734. if(nonzero[i]){
  117735. if(out)
  117736. for(j=0;j<n;j++)
  117737. out[i][j]+=in[i][j];
  117738. in[used++]=in[i];
  117739. }
  117740. if(used){
  117741. int ret=_01forward(vb,vl,in,used,partword,
  117742. _interleaved_encodepart);
  117743. if(out){
  117744. used=0;
  117745. for(i=0;i<ch;i++)
  117746. if(nonzero[i]){
  117747. for(j=0;j<n;j++)
  117748. out[i][j]-=in[used][j];
  117749. used++;
  117750. }
  117751. }
  117752. return(ret);
  117753. }else{
  117754. return(0);
  117755. }
  117756. }
  117757. #endif
  117758. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  117759. float **in,int *nonzero,int ch){
  117760. int i,used=0;
  117761. for(i=0;i<ch;i++)
  117762. if(nonzero[i])
  117763. in[used++]=in[i];
  117764. if(used)
  117765. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  117766. else
  117767. return(0);
  117768. }
  117769. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  117770. float **in,float **out,int *nonzero,int ch,
  117771. long **partword){
  117772. int i,j,used=0,n=vb->pcmend/2;
  117773. for(i=0;i<ch;i++)
  117774. if(nonzero[i]){
  117775. if(out)
  117776. for(j=0;j<n;j++)
  117777. out[i][j]+=in[i][j];
  117778. in[used++]=in[i];
  117779. }
  117780. if(used){
  117781. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  117782. if(out){
  117783. used=0;
  117784. for(i=0;i<ch;i++)
  117785. if(nonzero[i]){
  117786. for(j=0;j<n;j++)
  117787. out[i][j]-=in[used][j];
  117788. used++;
  117789. }
  117790. }
  117791. return(ret);
  117792. }else{
  117793. return(0);
  117794. }
  117795. }
  117796. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  117797. float **in,int *nonzero,int ch){
  117798. int i,used=0;
  117799. for(i=0;i<ch;i++)
  117800. if(nonzero[i])
  117801. in[used++]=in[i];
  117802. if(used)
  117803. return(_01class(vb,vl,in,used));
  117804. else
  117805. return(0);
  117806. }
  117807. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  117808. float **in,int *nonzero,int ch){
  117809. int i,used=0;
  117810. for(i=0;i<ch;i++)
  117811. if(nonzero[i])
  117812. in[used++]=in[i];
  117813. if(used)
  117814. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  117815. else
  117816. return(0);
  117817. }
  117818. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  117819. float **in,int *nonzero,int ch){
  117820. int i,used=0;
  117821. for(i=0;i<ch;i++)
  117822. if(nonzero[i])used++;
  117823. if(used)
  117824. return(_2class(vb,vl,in,ch));
  117825. else
  117826. return(0);
  117827. }
  117828. /* res2 is slightly more different; all the channels are interleaved
  117829. into a single vector and encoded. */
  117830. int res2_forward(oggpack_buffer *opb,
  117831. vorbis_block *vb,vorbis_look_residue *vl,
  117832. float **in,float **out,int *nonzero,int ch,
  117833. long **partword){
  117834. long i,j,k,n=vb->pcmend/2,used=0;
  117835. /* don't duplicate the code; use a working vector hack for now and
  117836. reshape ourselves into a single channel res1 */
  117837. /* ugly; reallocs for each coupling pass :-( */
  117838. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  117839. for(i=0;i<ch;i++){
  117840. float *pcm=in[i];
  117841. if(nonzero[i])used++;
  117842. for(j=0,k=i;j<n;j++,k+=ch)
  117843. work[k]=pcm[j];
  117844. }
  117845. if(used){
  117846. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  117847. /* update the sofar vector */
  117848. if(out){
  117849. for(i=0;i<ch;i++){
  117850. float *pcm=in[i];
  117851. float *sofar=out[i];
  117852. for(j=0,k=i;j<n;j++,k+=ch)
  117853. sofar[j]+=pcm[j]-work[k];
  117854. }
  117855. }
  117856. return(ret);
  117857. }else{
  117858. return(0);
  117859. }
  117860. }
  117861. /* duplicate code here as speed is somewhat more important */
  117862. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  117863. float **in,int *nonzero,int ch){
  117864. long i,k,l,s;
  117865. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  117866. vorbis_info_residue0 *info=look->info;
  117867. /* move all this setup out later */
  117868. int samples_per_partition=info->grouping;
  117869. int partitions_per_word=look->phrasebook->dim;
  117870. int n=info->end-info->begin;
  117871. int partvals=n/samples_per_partition;
  117872. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  117873. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  117874. for(i=0;i<ch;i++)if(nonzero[i])break;
  117875. if(i==ch)return(0); /* no nonzero vectors */
  117876. for(s=0;s<look->stages;s++){
  117877. for(i=0,l=0;i<partvals;l++){
  117878. if(s==0){
  117879. /* fetch the partition word */
  117880. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  117881. if(temp==-1)goto eopbreak;
  117882. partword[l]=look->decodemap[temp];
  117883. if(partword[l]==NULL)goto errout;
  117884. }
  117885. /* now we decode residual values for the partitions */
  117886. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  117887. if(info->secondstages[partword[l][k]]&(1<<s)){
  117888. codebook *stagebook=look->partbooks[partword[l][k]][s];
  117889. if(stagebook){
  117890. if(vorbis_book_decodevv_add(stagebook,in,
  117891. i*samples_per_partition+info->begin,ch,
  117892. &vb->opb,samples_per_partition)==-1)
  117893. goto eopbreak;
  117894. }
  117895. }
  117896. }
  117897. }
  117898. errout:
  117899. eopbreak:
  117900. return(0);
  117901. }
  117902. vorbis_func_residue residue0_exportbundle={
  117903. NULL,
  117904. &res0_unpack,
  117905. &res0_look,
  117906. &res0_free_info,
  117907. &res0_free_look,
  117908. NULL,
  117909. NULL,
  117910. &res0_inverse
  117911. };
  117912. vorbis_func_residue residue1_exportbundle={
  117913. &res0_pack,
  117914. &res0_unpack,
  117915. &res0_look,
  117916. &res0_free_info,
  117917. &res0_free_look,
  117918. &res1_class,
  117919. &res1_forward,
  117920. &res1_inverse
  117921. };
  117922. vorbis_func_residue residue2_exportbundle={
  117923. &res0_pack,
  117924. &res0_unpack,
  117925. &res0_look,
  117926. &res0_free_info,
  117927. &res0_free_look,
  117928. &res2_class,
  117929. &res2_forward,
  117930. &res2_inverse
  117931. };
  117932. #endif
  117933. /*** End of inlined file: res0.c ***/
  117934. /*** Start of inlined file: sharedbook.c ***/
  117935. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  117936. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  117937. // tasks..
  117938. #if JUCE_MSVC
  117939. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  117940. #endif
  117941. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  117942. #if JUCE_USE_OGGVORBIS
  117943. #include <stdlib.h>
  117944. #include <math.h>
  117945. #include <string.h>
  117946. /**** pack/unpack helpers ******************************************/
  117947. int _ilog(unsigned int v){
  117948. int ret=0;
  117949. while(v){
  117950. ret++;
  117951. v>>=1;
  117952. }
  117953. return(ret);
  117954. }
  117955. /* 32 bit float (not IEEE; nonnormalized mantissa +
  117956. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  117957. Why not IEEE? It's just not that important here. */
  117958. #define VQ_FEXP 10
  117959. #define VQ_FMAN 21
  117960. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  117961. /* doesn't currently guard under/overflow */
  117962. long _float32_pack(float val){
  117963. int sign=0;
  117964. long exp;
  117965. long mant;
  117966. if(val<0){
  117967. sign=0x80000000;
  117968. val= -val;
  117969. }
  117970. exp= floor(log(val)/log(2.f));
  117971. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  117972. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  117973. return(sign|exp|mant);
  117974. }
  117975. float _float32_unpack(long val){
  117976. double mant=val&0x1fffff;
  117977. int sign=val&0x80000000;
  117978. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  117979. if(sign)mant= -mant;
  117980. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  117981. }
  117982. /* given a list of word lengths, generate a list of codewords. Works
  117983. for length ordered or unordered, always assigns the lowest valued
  117984. codewords first. Extended to handle unused entries (length 0) */
  117985. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  117986. long i,j,count=0;
  117987. ogg_uint32_t marker[33];
  117988. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  117989. memset(marker,0,sizeof(marker));
  117990. for(i=0;i<n;i++){
  117991. long length=l[i];
  117992. if(length>0){
  117993. ogg_uint32_t entry=marker[length];
  117994. /* when we claim a node for an entry, we also claim the nodes
  117995. below it (pruning off the imagined tree that may have dangled
  117996. from it) as well as blocking the use of any nodes directly
  117997. above for leaves */
  117998. /* update ourself */
  117999. if(length<32 && (entry>>length)){
  118000. /* error condition; the lengths must specify an overpopulated tree */
  118001. _ogg_free(r);
  118002. return(NULL);
  118003. }
  118004. r[count++]=entry;
  118005. /* Look to see if the next shorter marker points to the node
  118006. above. if so, update it and repeat. */
  118007. {
  118008. for(j=length;j>0;j--){
  118009. if(marker[j]&1){
  118010. /* have to jump branches */
  118011. if(j==1)
  118012. marker[1]++;
  118013. else
  118014. marker[j]=marker[j-1]<<1;
  118015. break; /* invariant says next upper marker would already
  118016. have been moved if it was on the same path */
  118017. }
  118018. marker[j]++;
  118019. }
  118020. }
  118021. /* prune the tree; the implicit invariant says all the longer
  118022. markers were dangling from our just-taken node. Dangle them
  118023. from our *new* node. */
  118024. for(j=length+1;j<33;j++)
  118025. if((marker[j]>>1) == entry){
  118026. entry=marker[j];
  118027. marker[j]=marker[j-1]<<1;
  118028. }else
  118029. break;
  118030. }else
  118031. if(sparsecount==0)count++;
  118032. }
  118033. /* bitreverse the words because our bitwise packer/unpacker is LSb
  118034. endian */
  118035. for(i=0,count=0;i<n;i++){
  118036. ogg_uint32_t temp=0;
  118037. for(j=0;j<l[i];j++){
  118038. temp<<=1;
  118039. temp|=(r[count]>>j)&1;
  118040. }
  118041. if(sparsecount){
  118042. if(l[i])
  118043. r[count++]=temp;
  118044. }else
  118045. r[count++]=temp;
  118046. }
  118047. return(r);
  118048. }
  118049. /* there might be a straightforward one-line way to do the below
  118050. that's portable and totally safe against roundoff, but I haven't
  118051. thought of it. Therefore, we opt on the side of caution */
  118052. long _book_maptype1_quantvals(const static_codebook *b){
  118053. long vals=floor(pow((float)b->entries,1.f/b->dim));
  118054. /* the above *should* be reliable, but we'll not assume that FP is
  118055. ever reliable when bitstream sync is at stake; verify via integer
  118056. means that vals really is the greatest value of dim for which
  118057. vals^b->bim <= b->entries */
  118058. /* treat the above as an initial guess */
  118059. while(1){
  118060. long acc=1;
  118061. long acc1=1;
  118062. int i;
  118063. for(i=0;i<b->dim;i++){
  118064. acc*=vals;
  118065. acc1*=vals+1;
  118066. }
  118067. if(acc<=b->entries && acc1>b->entries){
  118068. return(vals);
  118069. }else{
  118070. if(acc>b->entries){
  118071. vals--;
  118072. }else{
  118073. vals++;
  118074. }
  118075. }
  118076. }
  118077. }
  118078. /* unpack the quantized list of values for encode/decode ***********/
  118079. /* we need to deal with two map types: in map type 1, the values are
  118080. generated algorithmically (each column of the vector counts through
  118081. the values in the quant vector). in map type 2, all the values came
  118082. in in an explicit list. Both value lists must be unpacked */
  118083. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  118084. long j,k,count=0;
  118085. if(b->maptype==1 || b->maptype==2){
  118086. int quantvals;
  118087. float mindel=_float32_unpack(b->q_min);
  118088. float delta=_float32_unpack(b->q_delta);
  118089. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  118090. /* maptype 1 and 2 both use a quantized value vector, but
  118091. different sizes */
  118092. switch(b->maptype){
  118093. case 1:
  118094. /* most of the time, entries%dimensions == 0, but we need to be
  118095. well defined. We define that the possible vales at each
  118096. scalar is values == entries/dim. If entries%dim != 0, we'll
  118097. have 'too few' values (values*dim<entries), which means that
  118098. we'll have 'left over' entries; left over entries use zeroed
  118099. values (and are wasted). So don't generate codebooks like
  118100. that */
  118101. quantvals=_book_maptype1_quantvals(b);
  118102. for(j=0;j<b->entries;j++){
  118103. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  118104. float last=0.f;
  118105. int indexdiv=1;
  118106. for(k=0;k<b->dim;k++){
  118107. int index= (j/indexdiv)%quantvals;
  118108. float val=b->quantlist[index];
  118109. val=fabs(val)*delta+mindel+last;
  118110. if(b->q_sequencep)last=val;
  118111. if(sparsemap)
  118112. r[sparsemap[count]*b->dim+k]=val;
  118113. else
  118114. r[count*b->dim+k]=val;
  118115. indexdiv*=quantvals;
  118116. }
  118117. count++;
  118118. }
  118119. }
  118120. break;
  118121. case 2:
  118122. for(j=0;j<b->entries;j++){
  118123. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  118124. float last=0.f;
  118125. for(k=0;k<b->dim;k++){
  118126. float val=b->quantlist[j*b->dim+k];
  118127. val=fabs(val)*delta+mindel+last;
  118128. if(b->q_sequencep)last=val;
  118129. if(sparsemap)
  118130. r[sparsemap[count]*b->dim+k]=val;
  118131. else
  118132. r[count*b->dim+k]=val;
  118133. }
  118134. count++;
  118135. }
  118136. }
  118137. break;
  118138. }
  118139. return(r);
  118140. }
  118141. return(NULL);
  118142. }
  118143. void vorbis_staticbook_clear(static_codebook *b){
  118144. if(b->allocedp){
  118145. if(b->quantlist)_ogg_free(b->quantlist);
  118146. if(b->lengthlist)_ogg_free(b->lengthlist);
  118147. if(b->nearest_tree){
  118148. _ogg_free(b->nearest_tree->ptr0);
  118149. _ogg_free(b->nearest_tree->ptr1);
  118150. _ogg_free(b->nearest_tree->p);
  118151. _ogg_free(b->nearest_tree->q);
  118152. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  118153. _ogg_free(b->nearest_tree);
  118154. }
  118155. if(b->thresh_tree){
  118156. _ogg_free(b->thresh_tree->quantthresh);
  118157. _ogg_free(b->thresh_tree->quantmap);
  118158. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  118159. _ogg_free(b->thresh_tree);
  118160. }
  118161. memset(b,0,sizeof(*b));
  118162. }
  118163. }
  118164. void vorbis_staticbook_destroy(static_codebook *b){
  118165. if(b->allocedp){
  118166. vorbis_staticbook_clear(b);
  118167. _ogg_free(b);
  118168. }
  118169. }
  118170. void vorbis_book_clear(codebook *b){
  118171. /* static book is not cleared; we're likely called on the lookup and
  118172. the static codebook belongs to the info struct */
  118173. if(b->valuelist)_ogg_free(b->valuelist);
  118174. if(b->codelist)_ogg_free(b->codelist);
  118175. if(b->dec_index)_ogg_free(b->dec_index);
  118176. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  118177. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  118178. memset(b,0,sizeof(*b));
  118179. }
  118180. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  118181. memset(c,0,sizeof(*c));
  118182. c->c=s;
  118183. c->entries=s->entries;
  118184. c->used_entries=s->entries;
  118185. c->dim=s->dim;
  118186. c->codelist=_make_words(s->lengthlist,s->entries,0);
  118187. c->valuelist=_book_unquantize(s,s->entries,NULL);
  118188. return(0);
  118189. }
  118190. static int sort32a(const void *a,const void *b){
  118191. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  118192. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  118193. }
  118194. /* decode codebook arrangement is more heavily optimized than encode */
  118195. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  118196. int i,j,n=0,tabn;
  118197. int *sortindex;
  118198. memset(c,0,sizeof(*c));
  118199. /* count actually used entries */
  118200. for(i=0;i<s->entries;i++)
  118201. if(s->lengthlist[i]>0)
  118202. n++;
  118203. c->entries=s->entries;
  118204. c->used_entries=n;
  118205. c->dim=s->dim;
  118206. /* two different remappings go on here.
  118207. First, we collapse the likely sparse codebook down only to
  118208. actually represented values/words. This collapsing needs to be
  118209. indexed as map-valueless books are used to encode original entry
  118210. positions as integers.
  118211. Second, we reorder all vectors, including the entry index above,
  118212. by sorted bitreversed codeword to allow treeless decode. */
  118213. {
  118214. /* perform sort */
  118215. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  118216. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  118217. if(codes==NULL)goto err_out;
  118218. for(i=0;i<n;i++){
  118219. codes[i]=ogg_bitreverse(codes[i]);
  118220. codep[i]=codes+i;
  118221. }
  118222. qsort(codep,n,sizeof(*codep),sort32a);
  118223. sortindex=(int*)alloca(n*sizeof(*sortindex));
  118224. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  118225. /* the index is a reverse index */
  118226. for(i=0;i<n;i++){
  118227. int position=codep[i]-codes;
  118228. sortindex[position]=i;
  118229. }
  118230. for(i=0;i<n;i++)
  118231. c->codelist[sortindex[i]]=codes[i];
  118232. _ogg_free(codes);
  118233. }
  118234. c->valuelist=_book_unquantize(s,n,sortindex);
  118235. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  118236. for(n=0,i=0;i<s->entries;i++)
  118237. if(s->lengthlist[i]>0)
  118238. c->dec_index[sortindex[n++]]=i;
  118239. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  118240. for(n=0,i=0;i<s->entries;i++)
  118241. if(s->lengthlist[i]>0)
  118242. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  118243. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  118244. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  118245. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  118246. tabn=1<<c->dec_firsttablen;
  118247. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  118248. c->dec_maxlength=0;
  118249. for(i=0;i<n;i++){
  118250. if(c->dec_maxlength<c->dec_codelengths[i])
  118251. c->dec_maxlength=c->dec_codelengths[i];
  118252. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  118253. ogg_uint32_t orig=ogg_bitreverse(c->codelist[i]);
  118254. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  118255. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  118256. }
  118257. }
  118258. /* now fill in 'unused' entries in the firsttable with hi/lo search
  118259. hints for the non-direct-hits */
  118260. {
  118261. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  118262. long lo=0,hi=0;
  118263. for(i=0;i<tabn;i++){
  118264. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  118265. if(c->dec_firsttable[ogg_bitreverse(word)]==0){
  118266. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  118267. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  118268. /* we only actually have 15 bits per hint to play with here.
  118269. In order to overflow gracefully (nothing breaks, efficiency
  118270. just drops), encode as the difference from the extremes. */
  118271. {
  118272. unsigned long loval=lo;
  118273. unsigned long hival=n-hi;
  118274. if(loval>0x7fff)loval=0x7fff;
  118275. if(hival>0x7fff)hival=0x7fff;
  118276. c->dec_firsttable[ogg_bitreverse(word)]=
  118277. 0x80000000UL | (loval<<15) | hival;
  118278. }
  118279. }
  118280. }
  118281. }
  118282. return(0);
  118283. err_out:
  118284. vorbis_book_clear(c);
  118285. return(-1);
  118286. }
  118287. static float _dist(int el,float *ref, float *b,int step){
  118288. int i;
  118289. float acc=0.f;
  118290. for(i=0;i<el;i++){
  118291. float val=(ref[i]-b[i*step]);
  118292. acc+=val*val;
  118293. }
  118294. return(acc);
  118295. }
  118296. int _best(codebook *book, float *a, int step){
  118297. encode_aux_threshmatch *tt=book->c->thresh_tree;
  118298. #if 0
  118299. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  118300. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  118301. #endif
  118302. int dim=book->dim;
  118303. int k,o;
  118304. /*int savebest=-1;
  118305. float saverr;*/
  118306. /* do we have a threshhold encode hint? */
  118307. if(tt){
  118308. int index=0,i;
  118309. /* find the quant val of each scalar */
  118310. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  118311. i=tt->threshvals>>1;
  118312. if(a[o]<tt->quantthresh[i]){
  118313. for(;i>0;i--)
  118314. if(a[o]>=tt->quantthresh[i-1])
  118315. break;
  118316. }else{
  118317. for(i++;i<tt->threshvals-1;i++)
  118318. if(a[o]<tt->quantthresh[i])break;
  118319. }
  118320. index=(index*tt->quantvals)+tt->quantmap[i];
  118321. }
  118322. /* regular lattices are easy :-) */
  118323. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  118324. use a decision tree after all
  118325. and fall through*/
  118326. return(index);
  118327. }
  118328. #if 0
  118329. /* do we have a pigeonhole encode hint? */
  118330. if(pt){
  118331. const static_codebook *c=book->c;
  118332. int i,besti=-1;
  118333. float best=0.f;
  118334. int entry=0;
  118335. /* dealing with sequentialness is a pain in the ass */
  118336. if(c->q_sequencep){
  118337. int pv;
  118338. long mul=1;
  118339. float qlast=0;
  118340. for(k=0,o=0;k<dim;k++,o+=step){
  118341. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  118342. if(pv<0 || pv>=pt->mapentries)break;
  118343. entry+=pt->pigeonmap[pv]*mul;
  118344. mul*=pt->quantvals;
  118345. qlast+=pv*pt->del+pt->min;
  118346. }
  118347. }else{
  118348. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  118349. int pv=(int)((a[o]-pt->min)/pt->del);
  118350. if(pv<0 || pv>=pt->mapentries)break;
  118351. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  118352. }
  118353. }
  118354. /* must be within the pigeonholable range; if we quant outside (or
  118355. in an entry that we define no list for), brute force it */
  118356. if(k==dim && pt->fitlength[entry]){
  118357. /* search the abbreviated list */
  118358. long *list=pt->fitlist+pt->fitmap[entry];
  118359. for(i=0;i<pt->fitlength[entry];i++){
  118360. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  118361. if(besti==-1 || this<best){
  118362. best=this;
  118363. besti=list[i];
  118364. }
  118365. }
  118366. return(besti);
  118367. }
  118368. }
  118369. if(nt){
  118370. /* optimized using the decision tree */
  118371. while(1){
  118372. float c=0.f;
  118373. float *p=book->valuelist+nt->p[ptr];
  118374. float *q=book->valuelist+nt->q[ptr];
  118375. for(k=0,o=0;k<dim;k++,o+=step)
  118376. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  118377. if(c>0.f) /* in A */
  118378. ptr= -nt->ptr0[ptr];
  118379. else /* in B */
  118380. ptr= -nt->ptr1[ptr];
  118381. if(ptr<=0)break;
  118382. }
  118383. return(-ptr);
  118384. }
  118385. #endif
  118386. /* brute force it! */
  118387. {
  118388. const static_codebook *c=book->c;
  118389. int i,besti=-1;
  118390. float best=0.f;
  118391. float *e=book->valuelist;
  118392. for(i=0;i<book->entries;i++){
  118393. if(c->lengthlist[i]>0){
  118394. float thisx=_dist(dim,e,a,step);
  118395. if(besti==-1 || thisx<best){
  118396. best=thisx;
  118397. besti=i;
  118398. }
  118399. }
  118400. e+=dim;
  118401. }
  118402. /*if(savebest!=-1 && savebest!=besti){
  118403. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  118404. "original:");
  118405. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  118406. fprintf(stderr,"\n"
  118407. "pigeonhole (entry %d, err %g):",savebest,saverr);
  118408. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  118409. (book->valuelist+savebest*dim)[i]);
  118410. fprintf(stderr,"\n"
  118411. "bruteforce (entry %d, err %g):",besti,best);
  118412. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  118413. (book->valuelist+besti*dim)[i]);
  118414. fprintf(stderr,"\n");
  118415. }*/
  118416. return(besti);
  118417. }
  118418. }
  118419. long vorbis_book_codeword(codebook *book,int entry){
  118420. if(book->c) /* only use with encode; decode optimizations are
  118421. allowed to break this */
  118422. return book->codelist[entry];
  118423. return -1;
  118424. }
  118425. long vorbis_book_codelen(codebook *book,int entry){
  118426. if(book->c) /* only use with encode; decode optimizations are
  118427. allowed to break this */
  118428. return book->c->lengthlist[entry];
  118429. return -1;
  118430. }
  118431. #ifdef _V_SELFTEST
  118432. /* Unit tests of the dequantizer; this stuff will be OK
  118433. cross-platform, I simply want to be sure that special mapping cases
  118434. actually work properly; a bug could go unnoticed for a while */
  118435. #include <stdio.h>
  118436. /* cases:
  118437. no mapping
  118438. full, explicit mapping
  118439. algorithmic mapping
  118440. nonsequential
  118441. sequential
  118442. */
  118443. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  118444. static long partial_quantlist1[]={0,7,2};
  118445. /* no mapping */
  118446. static_codebook test1={
  118447. 4,16,
  118448. NULL,
  118449. 0,
  118450. 0,0,0,0,
  118451. NULL,
  118452. NULL,NULL
  118453. };
  118454. static float *test1_result=NULL;
  118455. /* linear, full mapping, nonsequential */
  118456. static_codebook test2={
  118457. 4,3,
  118458. NULL,
  118459. 2,
  118460. -533200896,1611661312,4,0,
  118461. full_quantlist1,
  118462. NULL,NULL
  118463. };
  118464. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  118465. /* linear, full mapping, sequential */
  118466. static_codebook test3={
  118467. 4,3,
  118468. NULL,
  118469. 2,
  118470. -533200896,1611661312,4,1,
  118471. full_quantlist1,
  118472. NULL,NULL
  118473. };
  118474. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  118475. /* linear, algorithmic mapping, nonsequential */
  118476. static_codebook test4={
  118477. 3,27,
  118478. NULL,
  118479. 1,
  118480. -533200896,1611661312,4,0,
  118481. partial_quantlist1,
  118482. NULL,NULL
  118483. };
  118484. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  118485. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  118486. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  118487. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  118488. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  118489. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  118490. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  118491. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  118492. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  118493. /* linear, algorithmic mapping, sequential */
  118494. static_codebook test5={
  118495. 3,27,
  118496. NULL,
  118497. 1,
  118498. -533200896,1611661312,4,1,
  118499. partial_quantlist1,
  118500. NULL,NULL
  118501. };
  118502. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  118503. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  118504. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  118505. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  118506. -3, 1, 5, 4, 8,12, -1, 3, 7,
  118507. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  118508. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  118509. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  118510. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  118511. void run_test(static_codebook *b,float *comp){
  118512. float *out=_book_unquantize(b,b->entries,NULL);
  118513. int i;
  118514. if(comp){
  118515. if(!out){
  118516. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  118517. exit(1);
  118518. }
  118519. for(i=0;i<b->entries*b->dim;i++)
  118520. if(fabs(out[i]-comp[i])>.0001){
  118521. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  118522. "position %d, %g != %g\n",i,out[i],comp[i]);
  118523. exit(1);
  118524. }
  118525. }else{
  118526. if(out){
  118527. fprintf(stderr,"_book_unquantize returned a value array: \n"
  118528. " correct result should have been NULL\n");
  118529. exit(1);
  118530. }
  118531. }
  118532. }
  118533. int main(){
  118534. /* run the nine dequant tests, and compare to the hand-rolled results */
  118535. fprintf(stderr,"Dequant test 1... ");
  118536. run_test(&test1,test1_result);
  118537. fprintf(stderr,"OK\nDequant test 2... ");
  118538. run_test(&test2,test2_result);
  118539. fprintf(stderr,"OK\nDequant test 3... ");
  118540. run_test(&test3,test3_result);
  118541. fprintf(stderr,"OK\nDequant test 4... ");
  118542. run_test(&test4,test4_result);
  118543. fprintf(stderr,"OK\nDequant test 5... ");
  118544. run_test(&test5,test5_result);
  118545. fprintf(stderr,"OK\n\n");
  118546. return(0);
  118547. }
  118548. #endif
  118549. #endif
  118550. /*** End of inlined file: sharedbook.c ***/
  118551. /*** Start of inlined file: smallft.c ***/
  118552. /* FFT implementation from OggSquish, minus cosine transforms,
  118553. * minus all but radix 2/4 case. In Vorbis we only need this
  118554. * cut-down version.
  118555. *
  118556. * To do more than just power-of-two sized vectors, see the full
  118557. * version I wrote for NetLib.
  118558. *
  118559. * Note that the packing is a little strange; rather than the FFT r/i
  118560. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  118561. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  118562. * FORTRAN version
  118563. */
  118564. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118565. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118566. // tasks..
  118567. #if JUCE_MSVC
  118568. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118569. #endif
  118570. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118571. #if JUCE_USE_OGGVORBIS
  118572. #include <stdlib.h>
  118573. #include <string.h>
  118574. #include <math.h>
  118575. static void drfti1(int n, float *wa, int *ifac){
  118576. static int ntryh[4] = { 4,2,3,5 };
  118577. static float tpi = 6.28318530717958648f;
  118578. float arg,argh,argld,fi;
  118579. int ntry=0,i,j=-1;
  118580. int k1, l1, l2, ib;
  118581. int ld, ii, ip, is, nq, nr;
  118582. int ido, ipm, nfm1;
  118583. int nl=n;
  118584. int nf=0;
  118585. L101:
  118586. j++;
  118587. if (j < 4)
  118588. ntry=ntryh[j];
  118589. else
  118590. ntry+=2;
  118591. L104:
  118592. nq=nl/ntry;
  118593. nr=nl-ntry*nq;
  118594. if (nr!=0) goto L101;
  118595. nf++;
  118596. ifac[nf+1]=ntry;
  118597. nl=nq;
  118598. if(ntry!=2)goto L107;
  118599. if(nf==1)goto L107;
  118600. for (i=1;i<nf;i++){
  118601. ib=nf-i+1;
  118602. ifac[ib+1]=ifac[ib];
  118603. }
  118604. ifac[2] = 2;
  118605. L107:
  118606. if(nl!=1)goto L104;
  118607. ifac[0]=n;
  118608. ifac[1]=nf;
  118609. argh=tpi/n;
  118610. is=0;
  118611. nfm1=nf-1;
  118612. l1=1;
  118613. if(nfm1==0)return;
  118614. for (k1=0;k1<nfm1;k1++){
  118615. ip=ifac[k1+2];
  118616. ld=0;
  118617. l2=l1*ip;
  118618. ido=n/l2;
  118619. ipm=ip-1;
  118620. for (j=0;j<ipm;j++){
  118621. ld+=l1;
  118622. i=is;
  118623. argld=(float)ld*argh;
  118624. fi=0.f;
  118625. for (ii=2;ii<ido;ii+=2){
  118626. fi+=1.f;
  118627. arg=fi*argld;
  118628. wa[i++]=cos(arg);
  118629. wa[i++]=sin(arg);
  118630. }
  118631. is+=ido;
  118632. }
  118633. l1=l2;
  118634. }
  118635. }
  118636. static void fdrffti(int n, float *wsave, int *ifac){
  118637. if (n == 1) return;
  118638. drfti1(n, wsave+n, ifac);
  118639. }
  118640. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  118641. int i,k;
  118642. float ti2,tr2;
  118643. int t0,t1,t2,t3,t4,t5,t6;
  118644. t1=0;
  118645. t0=(t2=l1*ido);
  118646. t3=ido<<1;
  118647. for(k=0;k<l1;k++){
  118648. ch[t1<<1]=cc[t1]+cc[t2];
  118649. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  118650. t1+=ido;
  118651. t2+=ido;
  118652. }
  118653. if(ido<2)return;
  118654. if(ido==2)goto L105;
  118655. t1=0;
  118656. t2=t0;
  118657. for(k=0;k<l1;k++){
  118658. t3=t2;
  118659. t4=(t1<<1)+(ido<<1);
  118660. t5=t1;
  118661. t6=t1+t1;
  118662. for(i=2;i<ido;i+=2){
  118663. t3+=2;
  118664. t4-=2;
  118665. t5+=2;
  118666. t6+=2;
  118667. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  118668. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  118669. ch[t6]=cc[t5]+ti2;
  118670. ch[t4]=ti2-cc[t5];
  118671. ch[t6-1]=cc[t5-1]+tr2;
  118672. ch[t4-1]=cc[t5-1]-tr2;
  118673. }
  118674. t1+=ido;
  118675. t2+=ido;
  118676. }
  118677. if(ido%2==1)return;
  118678. L105:
  118679. t3=(t2=(t1=ido)-1);
  118680. t2+=t0;
  118681. for(k=0;k<l1;k++){
  118682. ch[t1]=-cc[t2];
  118683. ch[t1-1]=cc[t3];
  118684. t1+=ido<<1;
  118685. t2+=ido;
  118686. t3+=ido;
  118687. }
  118688. }
  118689. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  118690. float *wa2,float *wa3){
  118691. static float hsqt2 = .70710678118654752f;
  118692. int i,k,t0,t1,t2,t3,t4,t5,t6;
  118693. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  118694. t0=l1*ido;
  118695. t1=t0;
  118696. t4=t1<<1;
  118697. t2=t1+(t1<<1);
  118698. t3=0;
  118699. for(k=0;k<l1;k++){
  118700. tr1=cc[t1]+cc[t2];
  118701. tr2=cc[t3]+cc[t4];
  118702. ch[t5=t3<<2]=tr1+tr2;
  118703. ch[(ido<<2)+t5-1]=tr2-tr1;
  118704. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  118705. ch[t5]=cc[t2]-cc[t1];
  118706. t1+=ido;
  118707. t2+=ido;
  118708. t3+=ido;
  118709. t4+=ido;
  118710. }
  118711. if(ido<2)return;
  118712. if(ido==2)goto L105;
  118713. t1=0;
  118714. for(k=0;k<l1;k++){
  118715. t2=t1;
  118716. t4=t1<<2;
  118717. t5=(t6=ido<<1)+t4;
  118718. for(i=2;i<ido;i+=2){
  118719. t3=(t2+=2);
  118720. t4+=2;
  118721. t5-=2;
  118722. t3+=t0;
  118723. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  118724. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  118725. t3+=t0;
  118726. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  118727. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  118728. t3+=t0;
  118729. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  118730. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  118731. tr1=cr2+cr4;
  118732. tr4=cr4-cr2;
  118733. ti1=ci2+ci4;
  118734. ti4=ci2-ci4;
  118735. ti2=cc[t2]+ci3;
  118736. ti3=cc[t2]-ci3;
  118737. tr2=cc[t2-1]+cr3;
  118738. tr3=cc[t2-1]-cr3;
  118739. ch[t4-1]=tr1+tr2;
  118740. ch[t4]=ti1+ti2;
  118741. ch[t5-1]=tr3-ti4;
  118742. ch[t5]=tr4-ti3;
  118743. ch[t4+t6-1]=ti4+tr3;
  118744. ch[t4+t6]=tr4+ti3;
  118745. ch[t5+t6-1]=tr2-tr1;
  118746. ch[t5+t6]=ti1-ti2;
  118747. }
  118748. t1+=ido;
  118749. }
  118750. if(ido&1)return;
  118751. L105:
  118752. t2=(t1=t0+ido-1)+(t0<<1);
  118753. t3=ido<<2;
  118754. t4=ido;
  118755. t5=ido<<1;
  118756. t6=ido;
  118757. for(k=0;k<l1;k++){
  118758. ti1=-hsqt2*(cc[t1]+cc[t2]);
  118759. tr1=hsqt2*(cc[t1]-cc[t2]);
  118760. ch[t4-1]=tr1+cc[t6-1];
  118761. ch[t4+t5-1]=cc[t6-1]-tr1;
  118762. ch[t4]=ti1-cc[t1+t0];
  118763. ch[t4+t5]=ti1+cc[t1+t0];
  118764. t1+=ido;
  118765. t2+=ido;
  118766. t4+=t3;
  118767. t6+=ido;
  118768. }
  118769. }
  118770. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  118771. float *c2,float *ch,float *ch2,float *wa){
  118772. static float tpi=6.283185307179586f;
  118773. int idij,ipph,i,j,k,l,ic,ik,is;
  118774. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  118775. float dc2,ai1,ai2,ar1,ar2,ds2;
  118776. int nbd;
  118777. float dcp,arg,dsp,ar1h,ar2h;
  118778. int idp2,ipp2;
  118779. arg=tpi/(float)ip;
  118780. dcp=cos(arg);
  118781. dsp=sin(arg);
  118782. ipph=(ip+1)>>1;
  118783. ipp2=ip;
  118784. idp2=ido;
  118785. nbd=(ido-1)>>1;
  118786. t0=l1*ido;
  118787. t10=ip*ido;
  118788. if(ido==1)goto L119;
  118789. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  118790. t1=0;
  118791. for(j=1;j<ip;j++){
  118792. t1+=t0;
  118793. t2=t1;
  118794. for(k=0;k<l1;k++){
  118795. ch[t2]=c1[t2];
  118796. t2+=ido;
  118797. }
  118798. }
  118799. is=-ido;
  118800. t1=0;
  118801. if(nbd>l1){
  118802. for(j=1;j<ip;j++){
  118803. t1+=t0;
  118804. is+=ido;
  118805. t2= -ido+t1;
  118806. for(k=0;k<l1;k++){
  118807. idij=is-1;
  118808. t2+=ido;
  118809. t3=t2;
  118810. for(i=2;i<ido;i+=2){
  118811. idij+=2;
  118812. t3+=2;
  118813. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  118814. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  118815. }
  118816. }
  118817. }
  118818. }else{
  118819. for(j=1;j<ip;j++){
  118820. is+=ido;
  118821. idij=is-1;
  118822. t1+=t0;
  118823. t2=t1;
  118824. for(i=2;i<ido;i+=2){
  118825. idij+=2;
  118826. t2+=2;
  118827. t3=t2;
  118828. for(k=0;k<l1;k++){
  118829. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  118830. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  118831. t3+=ido;
  118832. }
  118833. }
  118834. }
  118835. }
  118836. t1=0;
  118837. t2=ipp2*t0;
  118838. if(nbd<l1){
  118839. for(j=1;j<ipph;j++){
  118840. t1+=t0;
  118841. t2-=t0;
  118842. t3=t1;
  118843. t4=t2;
  118844. for(i=2;i<ido;i+=2){
  118845. t3+=2;
  118846. t4+=2;
  118847. t5=t3-ido;
  118848. t6=t4-ido;
  118849. for(k=0;k<l1;k++){
  118850. t5+=ido;
  118851. t6+=ido;
  118852. c1[t5-1]=ch[t5-1]+ch[t6-1];
  118853. c1[t6-1]=ch[t5]-ch[t6];
  118854. c1[t5]=ch[t5]+ch[t6];
  118855. c1[t6]=ch[t6-1]-ch[t5-1];
  118856. }
  118857. }
  118858. }
  118859. }else{
  118860. for(j=1;j<ipph;j++){
  118861. t1+=t0;
  118862. t2-=t0;
  118863. t3=t1;
  118864. t4=t2;
  118865. for(k=0;k<l1;k++){
  118866. t5=t3;
  118867. t6=t4;
  118868. for(i=2;i<ido;i+=2){
  118869. t5+=2;
  118870. t6+=2;
  118871. c1[t5-1]=ch[t5-1]+ch[t6-1];
  118872. c1[t6-1]=ch[t5]-ch[t6];
  118873. c1[t5]=ch[t5]+ch[t6];
  118874. c1[t6]=ch[t6-1]-ch[t5-1];
  118875. }
  118876. t3+=ido;
  118877. t4+=ido;
  118878. }
  118879. }
  118880. }
  118881. L119:
  118882. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  118883. t1=0;
  118884. t2=ipp2*idl1;
  118885. for(j=1;j<ipph;j++){
  118886. t1+=t0;
  118887. t2-=t0;
  118888. t3=t1-ido;
  118889. t4=t2-ido;
  118890. for(k=0;k<l1;k++){
  118891. t3+=ido;
  118892. t4+=ido;
  118893. c1[t3]=ch[t3]+ch[t4];
  118894. c1[t4]=ch[t4]-ch[t3];
  118895. }
  118896. }
  118897. ar1=1.f;
  118898. ai1=0.f;
  118899. t1=0;
  118900. t2=ipp2*idl1;
  118901. t3=(ip-1)*idl1;
  118902. for(l=1;l<ipph;l++){
  118903. t1+=idl1;
  118904. t2-=idl1;
  118905. ar1h=dcp*ar1-dsp*ai1;
  118906. ai1=dcp*ai1+dsp*ar1;
  118907. ar1=ar1h;
  118908. t4=t1;
  118909. t5=t2;
  118910. t6=t3;
  118911. t7=idl1;
  118912. for(ik=0;ik<idl1;ik++){
  118913. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  118914. ch2[t5++]=ai1*c2[t6++];
  118915. }
  118916. dc2=ar1;
  118917. ds2=ai1;
  118918. ar2=ar1;
  118919. ai2=ai1;
  118920. t4=idl1;
  118921. t5=(ipp2-1)*idl1;
  118922. for(j=2;j<ipph;j++){
  118923. t4+=idl1;
  118924. t5-=idl1;
  118925. ar2h=dc2*ar2-ds2*ai2;
  118926. ai2=dc2*ai2+ds2*ar2;
  118927. ar2=ar2h;
  118928. t6=t1;
  118929. t7=t2;
  118930. t8=t4;
  118931. t9=t5;
  118932. for(ik=0;ik<idl1;ik++){
  118933. ch2[t6++]+=ar2*c2[t8++];
  118934. ch2[t7++]+=ai2*c2[t9++];
  118935. }
  118936. }
  118937. }
  118938. t1=0;
  118939. for(j=1;j<ipph;j++){
  118940. t1+=idl1;
  118941. t2=t1;
  118942. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  118943. }
  118944. if(ido<l1)goto L132;
  118945. t1=0;
  118946. t2=0;
  118947. for(k=0;k<l1;k++){
  118948. t3=t1;
  118949. t4=t2;
  118950. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  118951. t1+=ido;
  118952. t2+=t10;
  118953. }
  118954. goto L135;
  118955. L132:
  118956. for(i=0;i<ido;i++){
  118957. t1=i;
  118958. t2=i;
  118959. for(k=0;k<l1;k++){
  118960. cc[t2]=ch[t1];
  118961. t1+=ido;
  118962. t2+=t10;
  118963. }
  118964. }
  118965. L135:
  118966. t1=0;
  118967. t2=ido<<1;
  118968. t3=0;
  118969. t4=ipp2*t0;
  118970. for(j=1;j<ipph;j++){
  118971. t1+=t2;
  118972. t3+=t0;
  118973. t4-=t0;
  118974. t5=t1;
  118975. t6=t3;
  118976. t7=t4;
  118977. for(k=0;k<l1;k++){
  118978. cc[t5-1]=ch[t6];
  118979. cc[t5]=ch[t7];
  118980. t5+=t10;
  118981. t6+=ido;
  118982. t7+=ido;
  118983. }
  118984. }
  118985. if(ido==1)return;
  118986. if(nbd<l1)goto L141;
  118987. t1=-ido;
  118988. t3=0;
  118989. t4=0;
  118990. t5=ipp2*t0;
  118991. for(j=1;j<ipph;j++){
  118992. t1+=t2;
  118993. t3+=t2;
  118994. t4+=t0;
  118995. t5-=t0;
  118996. t6=t1;
  118997. t7=t3;
  118998. t8=t4;
  118999. t9=t5;
  119000. for(k=0;k<l1;k++){
  119001. for(i=2;i<ido;i+=2){
  119002. ic=idp2-i;
  119003. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  119004. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  119005. cc[i+t7]=ch[i+t8]+ch[i+t9];
  119006. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  119007. }
  119008. t6+=t10;
  119009. t7+=t10;
  119010. t8+=ido;
  119011. t9+=ido;
  119012. }
  119013. }
  119014. return;
  119015. L141:
  119016. t1=-ido;
  119017. t3=0;
  119018. t4=0;
  119019. t5=ipp2*t0;
  119020. for(j=1;j<ipph;j++){
  119021. t1+=t2;
  119022. t3+=t2;
  119023. t4+=t0;
  119024. t5-=t0;
  119025. for(i=2;i<ido;i+=2){
  119026. t6=idp2+t1-i;
  119027. t7=i+t3;
  119028. t8=i+t4;
  119029. t9=i+t5;
  119030. for(k=0;k<l1;k++){
  119031. cc[t7-1]=ch[t8-1]+ch[t9-1];
  119032. cc[t6-1]=ch[t8-1]-ch[t9-1];
  119033. cc[t7]=ch[t8]+ch[t9];
  119034. cc[t6]=ch[t9]-ch[t8];
  119035. t6+=t10;
  119036. t7+=t10;
  119037. t8+=ido;
  119038. t9+=ido;
  119039. }
  119040. }
  119041. }
  119042. }
  119043. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  119044. int i,k1,l1,l2;
  119045. int na,kh,nf;
  119046. int ip,iw,ido,idl1,ix2,ix3;
  119047. nf=ifac[1];
  119048. na=1;
  119049. l2=n;
  119050. iw=n;
  119051. for(k1=0;k1<nf;k1++){
  119052. kh=nf-k1;
  119053. ip=ifac[kh+1];
  119054. l1=l2/ip;
  119055. ido=n/l2;
  119056. idl1=ido*l1;
  119057. iw-=(ip-1)*ido;
  119058. na=1-na;
  119059. if(ip!=4)goto L102;
  119060. ix2=iw+ido;
  119061. ix3=ix2+ido;
  119062. if(na!=0)
  119063. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119064. else
  119065. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119066. goto L110;
  119067. L102:
  119068. if(ip!=2)goto L104;
  119069. if(na!=0)goto L103;
  119070. dradf2(ido,l1,c,ch,wa+iw-1);
  119071. goto L110;
  119072. L103:
  119073. dradf2(ido,l1,ch,c,wa+iw-1);
  119074. goto L110;
  119075. L104:
  119076. if(ido==1)na=1-na;
  119077. if(na!=0)goto L109;
  119078. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  119079. na=1;
  119080. goto L110;
  119081. L109:
  119082. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  119083. na=0;
  119084. L110:
  119085. l2=l1;
  119086. }
  119087. if(na==1)return;
  119088. for(i=0;i<n;i++)c[i]=ch[i];
  119089. }
  119090. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  119091. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119092. float ti2,tr2;
  119093. t0=l1*ido;
  119094. t1=0;
  119095. t2=0;
  119096. t3=(ido<<1)-1;
  119097. for(k=0;k<l1;k++){
  119098. ch[t1]=cc[t2]+cc[t3+t2];
  119099. ch[t1+t0]=cc[t2]-cc[t3+t2];
  119100. t2=(t1+=ido)<<1;
  119101. }
  119102. if(ido<2)return;
  119103. if(ido==2)goto L105;
  119104. t1=0;
  119105. t2=0;
  119106. for(k=0;k<l1;k++){
  119107. t3=t1;
  119108. t5=(t4=t2)+(ido<<1);
  119109. t6=t0+t1;
  119110. for(i=2;i<ido;i+=2){
  119111. t3+=2;
  119112. t4+=2;
  119113. t5-=2;
  119114. t6+=2;
  119115. ch[t3-1]=cc[t4-1]+cc[t5-1];
  119116. tr2=cc[t4-1]-cc[t5-1];
  119117. ch[t3]=cc[t4]-cc[t5];
  119118. ti2=cc[t4]+cc[t5];
  119119. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  119120. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  119121. }
  119122. t2=(t1+=ido)<<1;
  119123. }
  119124. if(ido%2==1)return;
  119125. L105:
  119126. t1=ido-1;
  119127. t2=ido-1;
  119128. for(k=0;k<l1;k++){
  119129. ch[t1]=cc[t2]+cc[t2];
  119130. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  119131. t1+=ido;
  119132. t2+=ido<<1;
  119133. }
  119134. }
  119135. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  119136. float *wa2){
  119137. static float taur = -.5f;
  119138. static float taui = .8660254037844386f;
  119139. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  119140. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  119141. t0=l1*ido;
  119142. t1=0;
  119143. t2=t0<<1;
  119144. t3=ido<<1;
  119145. t4=ido+(ido<<1);
  119146. t5=0;
  119147. for(k=0;k<l1;k++){
  119148. tr2=cc[t3-1]+cc[t3-1];
  119149. cr2=cc[t5]+(taur*tr2);
  119150. ch[t1]=cc[t5]+tr2;
  119151. ci3=taui*(cc[t3]+cc[t3]);
  119152. ch[t1+t0]=cr2-ci3;
  119153. ch[t1+t2]=cr2+ci3;
  119154. t1+=ido;
  119155. t3+=t4;
  119156. t5+=t4;
  119157. }
  119158. if(ido==1)return;
  119159. t1=0;
  119160. t3=ido<<1;
  119161. for(k=0;k<l1;k++){
  119162. t7=t1+(t1<<1);
  119163. t6=(t5=t7+t3);
  119164. t8=t1;
  119165. t10=(t9=t1+t0)+t0;
  119166. for(i=2;i<ido;i+=2){
  119167. t5+=2;
  119168. t6-=2;
  119169. t7+=2;
  119170. t8+=2;
  119171. t9+=2;
  119172. t10+=2;
  119173. tr2=cc[t5-1]+cc[t6-1];
  119174. cr2=cc[t7-1]+(taur*tr2);
  119175. ch[t8-1]=cc[t7-1]+tr2;
  119176. ti2=cc[t5]-cc[t6];
  119177. ci2=cc[t7]+(taur*ti2);
  119178. ch[t8]=cc[t7]+ti2;
  119179. cr3=taui*(cc[t5-1]-cc[t6-1]);
  119180. ci3=taui*(cc[t5]+cc[t6]);
  119181. dr2=cr2-ci3;
  119182. dr3=cr2+ci3;
  119183. di2=ci2+cr3;
  119184. di3=ci2-cr3;
  119185. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  119186. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  119187. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  119188. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  119189. }
  119190. t1+=ido;
  119191. }
  119192. }
  119193. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  119194. float *wa2,float *wa3){
  119195. static float sqrt2=1.414213562373095f;
  119196. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  119197. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  119198. t0=l1*ido;
  119199. t1=0;
  119200. t2=ido<<2;
  119201. t3=0;
  119202. t6=ido<<1;
  119203. for(k=0;k<l1;k++){
  119204. t4=t3+t6;
  119205. t5=t1;
  119206. tr3=cc[t4-1]+cc[t4-1];
  119207. tr4=cc[t4]+cc[t4];
  119208. tr1=cc[t3]-cc[(t4+=t6)-1];
  119209. tr2=cc[t3]+cc[t4-1];
  119210. ch[t5]=tr2+tr3;
  119211. ch[t5+=t0]=tr1-tr4;
  119212. ch[t5+=t0]=tr2-tr3;
  119213. ch[t5+=t0]=tr1+tr4;
  119214. t1+=ido;
  119215. t3+=t2;
  119216. }
  119217. if(ido<2)return;
  119218. if(ido==2)goto L105;
  119219. t1=0;
  119220. for(k=0;k<l1;k++){
  119221. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  119222. t7=t1;
  119223. for(i=2;i<ido;i+=2){
  119224. t2+=2;
  119225. t3+=2;
  119226. t4-=2;
  119227. t5-=2;
  119228. t7+=2;
  119229. ti1=cc[t2]+cc[t5];
  119230. ti2=cc[t2]-cc[t5];
  119231. ti3=cc[t3]-cc[t4];
  119232. tr4=cc[t3]+cc[t4];
  119233. tr1=cc[t2-1]-cc[t5-1];
  119234. tr2=cc[t2-1]+cc[t5-1];
  119235. ti4=cc[t3-1]-cc[t4-1];
  119236. tr3=cc[t3-1]+cc[t4-1];
  119237. ch[t7-1]=tr2+tr3;
  119238. cr3=tr2-tr3;
  119239. ch[t7]=ti2+ti3;
  119240. ci3=ti2-ti3;
  119241. cr2=tr1-tr4;
  119242. cr4=tr1+tr4;
  119243. ci2=ti1+ti4;
  119244. ci4=ti1-ti4;
  119245. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  119246. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  119247. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  119248. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  119249. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  119250. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  119251. }
  119252. t1+=ido;
  119253. }
  119254. if(ido%2 == 1)return;
  119255. L105:
  119256. t1=ido;
  119257. t2=ido<<2;
  119258. t3=ido-1;
  119259. t4=ido+(ido<<1);
  119260. for(k=0;k<l1;k++){
  119261. t5=t3;
  119262. ti1=cc[t1]+cc[t4];
  119263. ti2=cc[t4]-cc[t1];
  119264. tr1=cc[t1-1]-cc[t4-1];
  119265. tr2=cc[t1-1]+cc[t4-1];
  119266. ch[t5]=tr2+tr2;
  119267. ch[t5+=t0]=sqrt2*(tr1-ti1);
  119268. ch[t5+=t0]=ti2+ti2;
  119269. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  119270. t3+=ido;
  119271. t1+=t2;
  119272. t4+=t2;
  119273. }
  119274. }
  119275. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  119276. float *c2,float *ch,float *ch2,float *wa){
  119277. static float tpi=6.283185307179586f;
  119278. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  119279. t11,t12;
  119280. float dc2,ai1,ai2,ar1,ar2,ds2;
  119281. int nbd;
  119282. float dcp,arg,dsp,ar1h,ar2h;
  119283. int ipp2;
  119284. t10=ip*ido;
  119285. t0=l1*ido;
  119286. arg=tpi/(float)ip;
  119287. dcp=cos(arg);
  119288. dsp=sin(arg);
  119289. nbd=(ido-1)>>1;
  119290. ipp2=ip;
  119291. ipph=(ip+1)>>1;
  119292. if(ido<l1)goto L103;
  119293. t1=0;
  119294. t2=0;
  119295. for(k=0;k<l1;k++){
  119296. t3=t1;
  119297. t4=t2;
  119298. for(i=0;i<ido;i++){
  119299. ch[t3]=cc[t4];
  119300. t3++;
  119301. t4++;
  119302. }
  119303. t1+=ido;
  119304. t2+=t10;
  119305. }
  119306. goto L106;
  119307. L103:
  119308. t1=0;
  119309. for(i=0;i<ido;i++){
  119310. t2=t1;
  119311. t3=t1;
  119312. for(k=0;k<l1;k++){
  119313. ch[t2]=cc[t3];
  119314. t2+=ido;
  119315. t3+=t10;
  119316. }
  119317. t1++;
  119318. }
  119319. L106:
  119320. t1=0;
  119321. t2=ipp2*t0;
  119322. t7=(t5=ido<<1);
  119323. for(j=1;j<ipph;j++){
  119324. t1+=t0;
  119325. t2-=t0;
  119326. t3=t1;
  119327. t4=t2;
  119328. t6=t5;
  119329. for(k=0;k<l1;k++){
  119330. ch[t3]=cc[t6-1]+cc[t6-1];
  119331. ch[t4]=cc[t6]+cc[t6];
  119332. t3+=ido;
  119333. t4+=ido;
  119334. t6+=t10;
  119335. }
  119336. t5+=t7;
  119337. }
  119338. if (ido == 1)goto L116;
  119339. if(nbd<l1)goto L112;
  119340. t1=0;
  119341. t2=ipp2*t0;
  119342. t7=0;
  119343. for(j=1;j<ipph;j++){
  119344. t1+=t0;
  119345. t2-=t0;
  119346. t3=t1;
  119347. t4=t2;
  119348. t7+=(ido<<1);
  119349. t8=t7;
  119350. for(k=0;k<l1;k++){
  119351. t5=t3;
  119352. t6=t4;
  119353. t9=t8;
  119354. t11=t8;
  119355. for(i=2;i<ido;i+=2){
  119356. t5+=2;
  119357. t6+=2;
  119358. t9+=2;
  119359. t11-=2;
  119360. ch[t5-1]=cc[t9-1]+cc[t11-1];
  119361. ch[t6-1]=cc[t9-1]-cc[t11-1];
  119362. ch[t5]=cc[t9]-cc[t11];
  119363. ch[t6]=cc[t9]+cc[t11];
  119364. }
  119365. t3+=ido;
  119366. t4+=ido;
  119367. t8+=t10;
  119368. }
  119369. }
  119370. goto L116;
  119371. L112:
  119372. t1=0;
  119373. t2=ipp2*t0;
  119374. t7=0;
  119375. for(j=1;j<ipph;j++){
  119376. t1+=t0;
  119377. t2-=t0;
  119378. t3=t1;
  119379. t4=t2;
  119380. t7+=(ido<<1);
  119381. t8=t7;
  119382. t9=t7;
  119383. for(i=2;i<ido;i+=2){
  119384. t3+=2;
  119385. t4+=2;
  119386. t8+=2;
  119387. t9-=2;
  119388. t5=t3;
  119389. t6=t4;
  119390. t11=t8;
  119391. t12=t9;
  119392. for(k=0;k<l1;k++){
  119393. ch[t5-1]=cc[t11-1]+cc[t12-1];
  119394. ch[t6-1]=cc[t11-1]-cc[t12-1];
  119395. ch[t5]=cc[t11]-cc[t12];
  119396. ch[t6]=cc[t11]+cc[t12];
  119397. t5+=ido;
  119398. t6+=ido;
  119399. t11+=t10;
  119400. t12+=t10;
  119401. }
  119402. }
  119403. }
  119404. L116:
  119405. ar1=1.f;
  119406. ai1=0.f;
  119407. t1=0;
  119408. t9=(t2=ipp2*idl1);
  119409. t3=(ip-1)*idl1;
  119410. for(l=1;l<ipph;l++){
  119411. t1+=idl1;
  119412. t2-=idl1;
  119413. ar1h=dcp*ar1-dsp*ai1;
  119414. ai1=dcp*ai1+dsp*ar1;
  119415. ar1=ar1h;
  119416. t4=t1;
  119417. t5=t2;
  119418. t6=0;
  119419. t7=idl1;
  119420. t8=t3;
  119421. for(ik=0;ik<idl1;ik++){
  119422. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  119423. c2[t5++]=ai1*ch2[t8++];
  119424. }
  119425. dc2=ar1;
  119426. ds2=ai1;
  119427. ar2=ar1;
  119428. ai2=ai1;
  119429. t6=idl1;
  119430. t7=t9-idl1;
  119431. for(j=2;j<ipph;j++){
  119432. t6+=idl1;
  119433. t7-=idl1;
  119434. ar2h=dc2*ar2-ds2*ai2;
  119435. ai2=dc2*ai2+ds2*ar2;
  119436. ar2=ar2h;
  119437. t4=t1;
  119438. t5=t2;
  119439. t11=t6;
  119440. t12=t7;
  119441. for(ik=0;ik<idl1;ik++){
  119442. c2[t4++]+=ar2*ch2[t11++];
  119443. c2[t5++]+=ai2*ch2[t12++];
  119444. }
  119445. }
  119446. }
  119447. t1=0;
  119448. for(j=1;j<ipph;j++){
  119449. t1+=idl1;
  119450. t2=t1;
  119451. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  119452. }
  119453. t1=0;
  119454. t2=ipp2*t0;
  119455. for(j=1;j<ipph;j++){
  119456. t1+=t0;
  119457. t2-=t0;
  119458. t3=t1;
  119459. t4=t2;
  119460. for(k=0;k<l1;k++){
  119461. ch[t3]=c1[t3]-c1[t4];
  119462. ch[t4]=c1[t3]+c1[t4];
  119463. t3+=ido;
  119464. t4+=ido;
  119465. }
  119466. }
  119467. if(ido==1)goto L132;
  119468. if(nbd<l1)goto L128;
  119469. t1=0;
  119470. t2=ipp2*t0;
  119471. for(j=1;j<ipph;j++){
  119472. t1+=t0;
  119473. t2-=t0;
  119474. t3=t1;
  119475. t4=t2;
  119476. for(k=0;k<l1;k++){
  119477. t5=t3;
  119478. t6=t4;
  119479. for(i=2;i<ido;i+=2){
  119480. t5+=2;
  119481. t6+=2;
  119482. ch[t5-1]=c1[t5-1]-c1[t6];
  119483. ch[t6-1]=c1[t5-1]+c1[t6];
  119484. ch[t5]=c1[t5]+c1[t6-1];
  119485. ch[t6]=c1[t5]-c1[t6-1];
  119486. }
  119487. t3+=ido;
  119488. t4+=ido;
  119489. }
  119490. }
  119491. goto L132;
  119492. L128:
  119493. t1=0;
  119494. t2=ipp2*t0;
  119495. for(j=1;j<ipph;j++){
  119496. t1+=t0;
  119497. t2-=t0;
  119498. t3=t1;
  119499. t4=t2;
  119500. for(i=2;i<ido;i+=2){
  119501. t3+=2;
  119502. t4+=2;
  119503. t5=t3;
  119504. t6=t4;
  119505. for(k=0;k<l1;k++){
  119506. ch[t5-1]=c1[t5-1]-c1[t6];
  119507. ch[t6-1]=c1[t5-1]+c1[t6];
  119508. ch[t5]=c1[t5]+c1[t6-1];
  119509. ch[t6]=c1[t5]-c1[t6-1];
  119510. t5+=ido;
  119511. t6+=ido;
  119512. }
  119513. }
  119514. }
  119515. L132:
  119516. if(ido==1)return;
  119517. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  119518. t1=0;
  119519. for(j=1;j<ip;j++){
  119520. t2=(t1+=t0);
  119521. for(k=0;k<l1;k++){
  119522. c1[t2]=ch[t2];
  119523. t2+=ido;
  119524. }
  119525. }
  119526. if(nbd>l1)goto L139;
  119527. is= -ido-1;
  119528. t1=0;
  119529. for(j=1;j<ip;j++){
  119530. is+=ido;
  119531. t1+=t0;
  119532. idij=is;
  119533. t2=t1;
  119534. for(i=2;i<ido;i+=2){
  119535. t2+=2;
  119536. idij+=2;
  119537. t3=t2;
  119538. for(k=0;k<l1;k++){
  119539. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  119540. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  119541. t3+=ido;
  119542. }
  119543. }
  119544. }
  119545. return;
  119546. L139:
  119547. is= -ido-1;
  119548. t1=0;
  119549. for(j=1;j<ip;j++){
  119550. is+=ido;
  119551. t1+=t0;
  119552. t2=t1;
  119553. for(k=0;k<l1;k++){
  119554. idij=is;
  119555. t3=t2;
  119556. for(i=2;i<ido;i+=2){
  119557. idij+=2;
  119558. t3+=2;
  119559. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  119560. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  119561. }
  119562. t2+=ido;
  119563. }
  119564. }
  119565. }
  119566. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  119567. int i,k1,l1,l2;
  119568. int na;
  119569. int nf,ip,iw,ix2,ix3,ido,idl1;
  119570. nf=ifac[1];
  119571. na=0;
  119572. l1=1;
  119573. iw=1;
  119574. for(k1=0;k1<nf;k1++){
  119575. ip=ifac[k1 + 2];
  119576. l2=ip*l1;
  119577. ido=n/l2;
  119578. idl1=ido*l1;
  119579. if(ip!=4)goto L103;
  119580. ix2=iw+ido;
  119581. ix3=ix2+ido;
  119582. if(na!=0)
  119583. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119584. else
  119585. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119586. na=1-na;
  119587. goto L115;
  119588. L103:
  119589. if(ip!=2)goto L106;
  119590. if(na!=0)
  119591. dradb2(ido,l1,ch,c,wa+iw-1);
  119592. else
  119593. dradb2(ido,l1,c,ch,wa+iw-1);
  119594. na=1-na;
  119595. goto L115;
  119596. L106:
  119597. if(ip!=3)goto L109;
  119598. ix2=iw+ido;
  119599. if(na!=0)
  119600. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  119601. else
  119602. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  119603. na=1-na;
  119604. goto L115;
  119605. L109:
  119606. /* The radix five case can be translated later..... */
  119607. /* if(ip!=5)goto L112;
  119608. ix2=iw+ido;
  119609. ix3=ix2+ido;
  119610. ix4=ix3+ido;
  119611. if(na!=0)
  119612. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  119613. else
  119614. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  119615. na=1-na;
  119616. goto L115;
  119617. L112:*/
  119618. if(na!=0)
  119619. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  119620. else
  119621. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  119622. if(ido==1)na=1-na;
  119623. L115:
  119624. l1=l2;
  119625. iw+=(ip-1)*ido;
  119626. }
  119627. if(na==0)return;
  119628. for(i=0;i<n;i++)c[i]=ch[i];
  119629. }
  119630. void drft_forward(drft_lookup *l,float *data){
  119631. if(l->n==1)return;
  119632. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  119633. }
  119634. void drft_backward(drft_lookup *l,float *data){
  119635. if (l->n==1)return;
  119636. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  119637. }
  119638. void drft_init(drft_lookup *l,int n){
  119639. l->n=n;
  119640. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  119641. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  119642. fdrffti(n, l->trigcache, l->splitcache);
  119643. }
  119644. void drft_clear(drft_lookup *l){
  119645. if(l){
  119646. if(l->trigcache)_ogg_free(l->trigcache);
  119647. if(l->splitcache)_ogg_free(l->splitcache);
  119648. memset(l,0,sizeof(*l));
  119649. }
  119650. }
  119651. #endif
  119652. /*** End of inlined file: smallft.c ***/
  119653. /*** Start of inlined file: synthesis.c ***/
  119654. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  119655. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  119656. // tasks..
  119657. #if JUCE_MSVC
  119658. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  119659. #endif
  119660. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  119661. #if JUCE_USE_OGGVORBIS
  119662. #include <stdio.h>
  119663. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  119664. vorbis_dsp_state *vd=vb->vd;
  119665. private_state *b=(private_state*)vd->backend_state;
  119666. vorbis_info *vi=vd->vi;
  119667. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  119668. oggpack_buffer *opb=&vb->opb;
  119669. int type,mode,i;
  119670. /* first things first. Make sure decode is ready */
  119671. _vorbis_block_ripcord(vb);
  119672. oggpack_readinit(opb,op->packet,op->bytes);
  119673. /* Check the packet type */
  119674. if(oggpack_read(opb,1)!=0){
  119675. /* Oops. This is not an audio data packet */
  119676. return(OV_ENOTAUDIO);
  119677. }
  119678. /* read our mode and pre/post windowsize */
  119679. mode=oggpack_read(opb,b->modebits);
  119680. if(mode==-1)return(OV_EBADPACKET);
  119681. vb->mode=mode;
  119682. vb->W=ci->mode_param[mode]->blockflag;
  119683. if(vb->W){
  119684. /* this doesn;t get mapped through mode selection as it's used
  119685. only for window selection */
  119686. vb->lW=oggpack_read(opb,1);
  119687. vb->nW=oggpack_read(opb,1);
  119688. if(vb->nW==-1) return(OV_EBADPACKET);
  119689. }else{
  119690. vb->lW=0;
  119691. vb->nW=0;
  119692. }
  119693. /* more setup */
  119694. vb->granulepos=op->granulepos;
  119695. vb->sequence=op->packetno;
  119696. vb->eofflag=op->e_o_s;
  119697. /* alloc pcm passback storage */
  119698. vb->pcmend=ci->blocksizes[vb->W];
  119699. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  119700. for(i=0;i<vi->channels;i++)
  119701. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  119702. /* unpack_header enforces range checking */
  119703. type=ci->map_type[ci->mode_param[mode]->mapping];
  119704. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  119705. mapping]));
  119706. }
  119707. /* used to track pcm position without actually performing decode.
  119708. Useful for sequential 'fast forward' */
  119709. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  119710. vorbis_dsp_state *vd=vb->vd;
  119711. private_state *b=(private_state*)vd->backend_state;
  119712. vorbis_info *vi=vd->vi;
  119713. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  119714. oggpack_buffer *opb=&vb->opb;
  119715. int mode;
  119716. /* first things first. Make sure decode is ready */
  119717. _vorbis_block_ripcord(vb);
  119718. oggpack_readinit(opb,op->packet,op->bytes);
  119719. /* Check the packet type */
  119720. if(oggpack_read(opb,1)!=0){
  119721. /* Oops. This is not an audio data packet */
  119722. return(OV_ENOTAUDIO);
  119723. }
  119724. /* read our mode and pre/post windowsize */
  119725. mode=oggpack_read(opb,b->modebits);
  119726. if(mode==-1)return(OV_EBADPACKET);
  119727. vb->mode=mode;
  119728. vb->W=ci->mode_param[mode]->blockflag;
  119729. if(vb->W){
  119730. vb->lW=oggpack_read(opb,1);
  119731. vb->nW=oggpack_read(opb,1);
  119732. if(vb->nW==-1) return(OV_EBADPACKET);
  119733. }else{
  119734. vb->lW=0;
  119735. vb->nW=0;
  119736. }
  119737. /* more setup */
  119738. vb->granulepos=op->granulepos;
  119739. vb->sequence=op->packetno;
  119740. vb->eofflag=op->e_o_s;
  119741. /* no pcm */
  119742. vb->pcmend=0;
  119743. vb->pcm=NULL;
  119744. return(0);
  119745. }
  119746. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  119747. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  119748. oggpack_buffer opb;
  119749. int mode;
  119750. oggpack_readinit(&opb,op->packet,op->bytes);
  119751. /* Check the packet type */
  119752. if(oggpack_read(&opb,1)!=0){
  119753. /* Oops. This is not an audio data packet */
  119754. return(OV_ENOTAUDIO);
  119755. }
  119756. {
  119757. int modebits=0;
  119758. int v=ci->modes;
  119759. while(v>1){
  119760. modebits++;
  119761. v>>=1;
  119762. }
  119763. /* read our mode and pre/post windowsize */
  119764. mode=oggpack_read(&opb,modebits);
  119765. }
  119766. if(mode==-1)return(OV_EBADPACKET);
  119767. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  119768. }
  119769. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  119770. /* set / clear half-sample-rate mode */
  119771. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  119772. /* right now, our MDCT can't handle < 64 sample windows. */
  119773. if(ci->blocksizes[0]<=64 && flag)return -1;
  119774. ci->halfrate_flag=(flag?1:0);
  119775. return 0;
  119776. }
  119777. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  119778. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  119779. return ci->halfrate_flag;
  119780. }
  119781. #endif
  119782. /*** End of inlined file: synthesis.c ***/
  119783. /*** Start of inlined file: vorbisenc.c ***/
  119784. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  119785. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  119786. // tasks..
  119787. #if JUCE_MSVC
  119788. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  119789. #endif
  119790. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  119791. #if JUCE_USE_OGGVORBIS
  119792. #include <stdlib.h>
  119793. #include <string.h>
  119794. #include <math.h>
  119795. /* careful with this; it's using static array sizing to make managing
  119796. all the modes a little less annoying. If we use a residue backend
  119797. with > 12 partition types, or a different division of iteration,
  119798. this needs to be updated. */
  119799. typedef struct {
  119800. static_codebook *books[12][3];
  119801. } static_bookblock;
  119802. typedef struct {
  119803. int res_type;
  119804. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  119805. vorbis_info_residue0 *res;
  119806. static_codebook *book_aux;
  119807. static_codebook *book_aux_managed;
  119808. static_bookblock *books_base;
  119809. static_bookblock *books_base_managed;
  119810. } vorbis_residue_template;
  119811. typedef struct {
  119812. vorbis_info_mapping0 *map;
  119813. vorbis_residue_template *res;
  119814. } vorbis_mapping_template;
  119815. typedef struct vp_adjblock{
  119816. int block[P_BANDS];
  119817. } vp_adjblock;
  119818. typedef struct {
  119819. int data[NOISE_COMPAND_LEVELS];
  119820. } compandblock;
  119821. /* high level configuration information for setting things up
  119822. step-by-step with the detailed vorbis_encode_ctl interface.
  119823. There's a fair amount of redundancy such that interactive setup
  119824. does not directly deal with any vorbis_info or codec_setup_info
  119825. initialization; it's all stored (until full init) in this highlevel
  119826. setup, then flushed out to the real codec setup structs later. */
  119827. typedef struct {
  119828. int att[P_NOISECURVES];
  119829. float boost;
  119830. float decay;
  119831. } att3;
  119832. typedef struct { int data[P_NOISECURVES]; } adj3;
  119833. typedef struct {
  119834. int pre[PACKETBLOBS];
  119835. int post[PACKETBLOBS];
  119836. float kHz[PACKETBLOBS];
  119837. float lowpasskHz[PACKETBLOBS];
  119838. } adj_stereo;
  119839. typedef struct {
  119840. int lo;
  119841. int hi;
  119842. int fixed;
  119843. } noiseguard;
  119844. typedef struct {
  119845. int data[P_NOISECURVES][17];
  119846. } noise3;
  119847. typedef struct {
  119848. int mappings;
  119849. double *rate_mapping;
  119850. double *quality_mapping;
  119851. int coupling_restriction;
  119852. long samplerate_min_restriction;
  119853. long samplerate_max_restriction;
  119854. int *blocksize_short;
  119855. int *blocksize_long;
  119856. att3 *psy_tone_masteratt;
  119857. int *psy_tone_0dB;
  119858. int *psy_tone_dBsuppress;
  119859. vp_adjblock *psy_tone_adj_impulse;
  119860. vp_adjblock *psy_tone_adj_long;
  119861. vp_adjblock *psy_tone_adj_other;
  119862. noiseguard *psy_noiseguards;
  119863. noise3 *psy_noise_bias_impulse;
  119864. noise3 *psy_noise_bias_padding;
  119865. noise3 *psy_noise_bias_trans;
  119866. noise3 *psy_noise_bias_long;
  119867. int *psy_noise_dBsuppress;
  119868. compandblock *psy_noise_compand;
  119869. double *psy_noise_compand_short_mapping;
  119870. double *psy_noise_compand_long_mapping;
  119871. int *psy_noise_normal_start[2];
  119872. int *psy_noise_normal_partition[2];
  119873. double *psy_noise_normal_thresh;
  119874. int *psy_ath_float;
  119875. int *psy_ath_abs;
  119876. double *psy_lowpass;
  119877. vorbis_info_psy_global *global_params;
  119878. double *global_mapping;
  119879. adj_stereo *stereo_modes;
  119880. static_codebook ***floor_books;
  119881. vorbis_info_floor1 *floor_params;
  119882. int *floor_short_mapping;
  119883. int *floor_long_mapping;
  119884. vorbis_mapping_template *maps;
  119885. } ve_setup_data_template;
  119886. /* a few static coder conventions */
  119887. static vorbis_info_mode _mode_template[2]={
  119888. {0,0,0,0},
  119889. {1,0,0,1}
  119890. };
  119891. static vorbis_info_mapping0 _map_nominal[2]={
  119892. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  119893. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  119894. };
  119895. /*** Start of inlined file: setup_44.h ***/
  119896. /*** Start of inlined file: floor_all.h ***/
  119897. /*** Start of inlined file: floor_books.h ***/
  119898. static long _huff_lengthlist_line_256x7_0sub1[] = {
  119899. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  119900. };
  119901. static static_codebook _huff_book_line_256x7_0sub1 = {
  119902. 1, 9,
  119903. _huff_lengthlist_line_256x7_0sub1,
  119904. 0, 0, 0, 0, 0,
  119905. NULL,
  119906. NULL,
  119907. NULL,
  119908. NULL,
  119909. 0
  119910. };
  119911. static long _huff_lengthlist_line_256x7_0sub2[] = {
  119912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  119913. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  119914. };
  119915. static static_codebook _huff_book_line_256x7_0sub2 = {
  119916. 1, 25,
  119917. _huff_lengthlist_line_256x7_0sub2,
  119918. 0, 0, 0, 0, 0,
  119919. NULL,
  119920. NULL,
  119921. NULL,
  119922. NULL,
  119923. 0
  119924. };
  119925. static long _huff_lengthlist_line_256x7_0sub3[] = {
  119926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  119928. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  119929. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  119930. };
  119931. static static_codebook _huff_book_line_256x7_0sub3 = {
  119932. 1, 64,
  119933. _huff_lengthlist_line_256x7_0sub3,
  119934. 0, 0, 0, 0, 0,
  119935. NULL,
  119936. NULL,
  119937. NULL,
  119938. NULL,
  119939. 0
  119940. };
  119941. static long _huff_lengthlist_line_256x7_1sub1[] = {
  119942. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  119943. };
  119944. static static_codebook _huff_book_line_256x7_1sub1 = {
  119945. 1, 9,
  119946. _huff_lengthlist_line_256x7_1sub1,
  119947. 0, 0, 0, 0, 0,
  119948. NULL,
  119949. NULL,
  119950. NULL,
  119951. NULL,
  119952. 0
  119953. };
  119954. static long _huff_lengthlist_line_256x7_1sub2[] = {
  119955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  119956. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  119957. };
  119958. static static_codebook _huff_book_line_256x7_1sub2 = {
  119959. 1, 25,
  119960. _huff_lengthlist_line_256x7_1sub2,
  119961. 0, 0, 0, 0, 0,
  119962. NULL,
  119963. NULL,
  119964. NULL,
  119965. NULL,
  119966. 0
  119967. };
  119968. static long _huff_lengthlist_line_256x7_1sub3[] = {
  119969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 4, 3, 6, 3, 7,
  119971. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119972. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  119973. };
  119974. static static_codebook _huff_book_line_256x7_1sub3 = {
  119975. 1, 64,
  119976. _huff_lengthlist_line_256x7_1sub3,
  119977. 0, 0, 0, 0, 0,
  119978. NULL,
  119979. NULL,
  119980. NULL,
  119981. NULL,
  119982. 0
  119983. };
  119984. static long _huff_lengthlist_line_256x7_class0[] = {
  119985. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  119986. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  119987. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  119988. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  119989. };
  119990. static static_codebook _huff_book_line_256x7_class0 = {
  119991. 1, 64,
  119992. _huff_lengthlist_line_256x7_class0,
  119993. 0, 0, 0, 0, 0,
  119994. NULL,
  119995. NULL,
  119996. NULL,
  119997. NULL,
  119998. 0
  119999. };
  120000. static long _huff_lengthlist_line_256x7_class1[] = {
  120001. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  120002. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  120003. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  120004. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  120005. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  120006. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  120007. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  120008. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  120009. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  120010. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  120011. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  120012. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  120013. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120014. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120015. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  120016. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  120017. };
  120018. static static_codebook _huff_book_line_256x7_class1 = {
  120019. 1, 256,
  120020. _huff_lengthlist_line_256x7_class1,
  120021. 0, 0, 0, 0, 0,
  120022. NULL,
  120023. NULL,
  120024. NULL,
  120025. NULL,
  120026. 0
  120027. };
  120028. static long _huff_lengthlist_line_512x17_0sub0[] = {
  120029. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  120030. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  120031. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  120032. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  120033. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  120034. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  120035. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  120036. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  120037. };
  120038. static static_codebook _huff_book_line_512x17_0sub0 = {
  120039. 1, 128,
  120040. _huff_lengthlist_line_512x17_0sub0,
  120041. 0, 0, 0, 0, 0,
  120042. NULL,
  120043. NULL,
  120044. NULL,
  120045. NULL,
  120046. 0
  120047. };
  120048. static long _huff_lengthlist_line_512x17_1sub0[] = {
  120049. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  120050. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  120051. };
  120052. static static_codebook _huff_book_line_512x17_1sub0 = {
  120053. 1, 32,
  120054. _huff_lengthlist_line_512x17_1sub0,
  120055. 0, 0, 0, 0, 0,
  120056. NULL,
  120057. NULL,
  120058. NULL,
  120059. NULL,
  120060. 0
  120061. };
  120062. static long _huff_lengthlist_line_512x17_1sub1[] = {
  120063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120065. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  120066. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  120067. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  120068. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  120069. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  120070. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120071. };
  120072. static static_codebook _huff_book_line_512x17_1sub1 = {
  120073. 1, 128,
  120074. _huff_lengthlist_line_512x17_1sub1,
  120075. 0, 0, 0, 0, 0,
  120076. NULL,
  120077. NULL,
  120078. NULL,
  120079. NULL,
  120080. 0
  120081. };
  120082. static long _huff_lengthlist_line_512x17_2sub1[] = {
  120083. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  120084. 5, 3,
  120085. };
  120086. static static_codebook _huff_book_line_512x17_2sub1 = {
  120087. 1, 18,
  120088. _huff_lengthlist_line_512x17_2sub1,
  120089. 0, 0, 0, 0, 0,
  120090. NULL,
  120091. NULL,
  120092. NULL,
  120093. NULL,
  120094. 0
  120095. };
  120096. static long _huff_lengthlist_line_512x17_2sub2[] = {
  120097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120098. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  120099. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  120100. 9, 8,
  120101. };
  120102. static static_codebook _huff_book_line_512x17_2sub2 = {
  120103. 1, 50,
  120104. _huff_lengthlist_line_512x17_2sub2,
  120105. 0, 0, 0, 0, 0,
  120106. NULL,
  120107. NULL,
  120108. NULL,
  120109. NULL,
  120110. 0
  120111. };
  120112. static long _huff_lengthlist_line_512x17_2sub3[] = {
  120113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120116. 0, 0, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  120117. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  120118. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120119. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120120. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120121. };
  120122. static static_codebook _huff_book_line_512x17_2sub3 = {
  120123. 1, 128,
  120124. _huff_lengthlist_line_512x17_2sub3,
  120125. 0, 0, 0, 0, 0,
  120126. NULL,
  120127. NULL,
  120128. NULL,
  120129. NULL,
  120130. 0
  120131. };
  120132. static long _huff_lengthlist_line_512x17_3sub1[] = {
  120133. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  120134. 5, 5,
  120135. };
  120136. static static_codebook _huff_book_line_512x17_3sub1 = {
  120137. 1, 18,
  120138. _huff_lengthlist_line_512x17_3sub1,
  120139. 0, 0, 0, 0, 0,
  120140. NULL,
  120141. NULL,
  120142. NULL,
  120143. NULL,
  120144. 0
  120145. };
  120146. static long _huff_lengthlist_line_512x17_3sub2[] = {
  120147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120148. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  120149. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  120150. 11,14,
  120151. };
  120152. static static_codebook _huff_book_line_512x17_3sub2 = {
  120153. 1, 50,
  120154. _huff_lengthlist_line_512x17_3sub2,
  120155. 0, 0, 0, 0, 0,
  120156. NULL,
  120157. NULL,
  120158. NULL,
  120159. NULL,
  120160. 0
  120161. };
  120162. static long _huff_lengthlist_line_512x17_3sub3[] = {
  120163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120166. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  120167. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120168. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120169. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120170. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120171. };
  120172. static static_codebook _huff_book_line_512x17_3sub3 = {
  120173. 1, 128,
  120174. _huff_lengthlist_line_512x17_3sub3,
  120175. 0, 0, 0, 0, 0,
  120176. NULL,
  120177. NULL,
  120178. NULL,
  120179. NULL,
  120180. 0
  120181. };
  120182. static long _huff_lengthlist_line_512x17_class1[] = {
  120183. 1, 2, 3, 6, 5, 4, 7, 7,
  120184. };
  120185. static static_codebook _huff_book_line_512x17_class1 = {
  120186. 1, 8,
  120187. _huff_lengthlist_line_512x17_class1,
  120188. 0, 0, 0, 0, 0,
  120189. NULL,
  120190. NULL,
  120191. NULL,
  120192. NULL,
  120193. 0
  120194. };
  120195. static long _huff_lengthlist_line_512x17_class2[] = {
  120196. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  120197. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  120198. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  120199. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  120200. };
  120201. static static_codebook _huff_book_line_512x17_class2 = {
  120202. 1, 64,
  120203. _huff_lengthlist_line_512x17_class2,
  120204. 0, 0, 0, 0, 0,
  120205. NULL,
  120206. NULL,
  120207. NULL,
  120208. NULL,
  120209. 0
  120210. };
  120211. static long _huff_lengthlist_line_512x17_class3[] = {
  120212. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  120213. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  120214. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  120215. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  120216. };
  120217. static static_codebook _huff_book_line_512x17_class3 = {
  120218. 1, 64,
  120219. _huff_lengthlist_line_512x17_class3,
  120220. 0, 0, 0, 0, 0,
  120221. NULL,
  120222. NULL,
  120223. NULL,
  120224. NULL,
  120225. 0
  120226. };
  120227. static long _huff_lengthlist_line_128x4_class0[] = {
  120228. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  120229. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  120230. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  120231. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  120232. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  120233. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  120234. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  120235. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  120236. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  120237. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  120238. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  120239. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  120240. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  120241. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  120242. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  120243. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  120244. };
  120245. static static_codebook _huff_book_line_128x4_class0 = {
  120246. 1, 256,
  120247. _huff_lengthlist_line_128x4_class0,
  120248. 0, 0, 0, 0, 0,
  120249. NULL,
  120250. NULL,
  120251. NULL,
  120252. NULL,
  120253. 0
  120254. };
  120255. static long _huff_lengthlist_line_128x4_0sub0[] = {
  120256. 2, 2, 2, 2,
  120257. };
  120258. static static_codebook _huff_book_line_128x4_0sub0 = {
  120259. 1, 4,
  120260. _huff_lengthlist_line_128x4_0sub0,
  120261. 0, 0, 0, 0, 0,
  120262. NULL,
  120263. NULL,
  120264. NULL,
  120265. NULL,
  120266. 0
  120267. };
  120268. static long _huff_lengthlist_line_128x4_0sub1[] = {
  120269. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  120270. };
  120271. static static_codebook _huff_book_line_128x4_0sub1 = {
  120272. 1, 10,
  120273. _huff_lengthlist_line_128x4_0sub1,
  120274. 0, 0, 0, 0, 0,
  120275. NULL,
  120276. NULL,
  120277. NULL,
  120278. NULL,
  120279. 0
  120280. };
  120281. static long _huff_lengthlist_line_128x4_0sub2[] = {
  120282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  120283. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  120284. };
  120285. static static_codebook _huff_book_line_128x4_0sub2 = {
  120286. 1, 25,
  120287. _huff_lengthlist_line_128x4_0sub2,
  120288. 0, 0, 0, 0, 0,
  120289. NULL,
  120290. NULL,
  120291. NULL,
  120292. NULL,
  120293. 0
  120294. };
  120295. static long _huff_lengthlist_line_128x4_0sub3[] = {
  120296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  120298. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  120299. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  120300. };
  120301. static static_codebook _huff_book_line_128x4_0sub3 = {
  120302. 1, 64,
  120303. _huff_lengthlist_line_128x4_0sub3,
  120304. 0, 0, 0, 0, 0,
  120305. NULL,
  120306. NULL,
  120307. NULL,
  120308. NULL,
  120309. 0
  120310. };
  120311. static long _huff_lengthlist_line_256x4_class0[] = {
  120312. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  120313. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  120314. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  120315. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  120316. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  120317. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  120318. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  120319. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  120320. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  120321. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  120322. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  120323. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  120324. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  120325. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  120326. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  120327. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  120328. };
  120329. static static_codebook _huff_book_line_256x4_class0 = {
  120330. 1, 256,
  120331. _huff_lengthlist_line_256x4_class0,
  120332. 0, 0, 0, 0, 0,
  120333. NULL,
  120334. NULL,
  120335. NULL,
  120336. NULL,
  120337. 0
  120338. };
  120339. static long _huff_lengthlist_line_256x4_0sub0[] = {
  120340. 2, 2, 2, 2,
  120341. };
  120342. static static_codebook _huff_book_line_256x4_0sub0 = {
  120343. 1, 4,
  120344. _huff_lengthlist_line_256x4_0sub0,
  120345. 0, 0, 0, 0, 0,
  120346. NULL,
  120347. NULL,
  120348. NULL,
  120349. NULL,
  120350. 0
  120351. };
  120352. static long _huff_lengthlist_line_256x4_0sub1[] = {
  120353. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  120354. };
  120355. static static_codebook _huff_book_line_256x4_0sub1 = {
  120356. 1, 10,
  120357. _huff_lengthlist_line_256x4_0sub1,
  120358. 0, 0, 0, 0, 0,
  120359. NULL,
  120360. NULL,
  120361. NULL,
  120362. NULL,
  120363. 0
  120364. };
  120365. static long _huff_lengthlist_line_256x4_0sub2[] = {
  120366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  120367. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  120368. };
  120369. static static_codebook _huff_book_line_256x4_0sub2 = {
  120370. 1, 25,
  120371. _huff_lengthlist_line_256x4_0sub2,
  120372. 0, 0, 0, 0, 0,
  120373. NULL,
  120374. NULL,
  120375. NULL,
  120376. NULL,
  120377. 0
  120378. };
  120379. static long _huff_lengthlist_line_256x4_0sub3[] = {
  120380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  120382. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  120383. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  120384. };
  120385. static static_codebook _huff_book_line_256x4_0sub3 = {
  120386. 1, 64,
  120387. _huff_lengthlist_line_256x4_0sub3,
  120388. 0, 0, 0, 0, 0,
  120389. NULL,
  120390. NULL,
  120391. NULL,
  120392. NULL,
  120393. 0
  120394. };
  120395. static long _huff_lengthlist_line_128x7_class0[] = {
  120396. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  120397. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  120398. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  120399. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  120400. };
  120401. static static_codebook _huff_book_line_128x7_class0 = {
  120402. 1, 64,
  120403. _huff_lengthlist_line_128x7_class0,
  120404. 0, 0, 0, 0, 0,
  120405. NULL,
  120406. NULL,
  120407. NULL,
  120408. NULL,
  120409. 0
  120410. };
  120411. static long _huff_lengthlist_line_128x7_class1[] = {
  120412. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  120413. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  120414. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  120415. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  120416. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  120417. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  120418. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  120419. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  120420. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  120421. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  120422. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  120423. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  120424. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  120425. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  120426. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  120427. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  120428. };
  120429. static static_codebook _huff_book_line_128x7_class1 = {
  120430. 1, 256,
  120431. _huff_lengthlist_line_128x7_class1,
  120432. 0, 0, 0, 0, 0,
  120433. NULL,
  120434. NULL,
  120435. NULL,
  120436. NULL,
  120437. 0
  120438. };
  120439. static long _huff_lengthlist_line_128x7_0sub1[] = {
  120440. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  120441. };
  120442. static static_codebook _huff_book_line_128x7_0sub1 = {
  120443. 1, 9,
  120444. _huff_lengthlist_line_128x7_0sub1,
  120445. 0, 0, 0, 0, 0,
  120446. NULL,
  120447. NULL,
  120448. NULL,
  120449. NULL,
  120450. 0
  120451. };
  120452. static long _huff_lengthlist_line_128x7_0sub2[] = {
  120453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  120454. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  120455. };
  120456. static static_codebook _huff_book_line_128x7_0sub2 = {
  120457. 1, 25,
  120458. _huff_lengthlist_line_128x7_0sub2,
  120459. 0, 0, 0, 0, 0,
  120460. NULL,
  120461. NULL,
  120462. NULL,
  120463. NULL,
  120464. 0
  120465. };
  120466. static long _huff_lengthlist_line_128x7_0sub3[] = {
  120467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 3, 5, 3, 5, 4,
  120469. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  120470. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  120471. };
  120472. static static_codebook _huff_book_line_128x7_0sub3 = {
  120473. 1, 64,
  120474. _huff_lengthlist_line_128x7_0sub3,
  120475. 0, 0, 0, 0, 0,
  120476. NULL,
  120477. NULL,
  120478. NULL,
  120479. NULL,
  120480. 0
  120481. };
  120482. static long _huff_lengthlist_line_128x7_1sub1[] = {
  120483. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  120484. };
  120485. static static_codebook _huff_book_line_128x7_1sub1 = {
  120486. 1, 9,
  120487. _huff_lengthlist_line_128x7_1sub1,
  120488. 0, 0, 0, 0, 0,
  120489. NULL,
  120490. NULL,
  120491. NULL,
  120492. NULL,
  120493. 0
  120494. };
  120495. static long _huff_lengthlist_line_128x7_1sub2[] = {
  120496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  120497. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  120498. };
  120499. static static_codebook _huff_book_line_128x7_1sub2 = {
  120500. 1, 25,
  120501. _huff_lengthlist_line_128x7_1sub2,
  120502. 0, 0, 0, 0, 0,
  120503. NULL,
  120504. NULL,
  120505. NULL,
  120506. NULL,
  120507. 0
  120508. };
  120509. static long _huff_lengthlist_line_128x7_1sub3[] = {
  120510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 2, 7, 3, 8, 4,
  120512. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  120513. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  120514. };
  120515. static static_codebook _huff_book_line_128x7_1sub3 = {
  120516. 1, 64,
  120517. _huff_lengthlist_line_128x7_1sub3,
  120518. 0, 0, 0, 0, 0,
  120519. NULL,
  120520. NULL,
  120521. NULL,
  120522. NULL,
  120523. 0
  120524. };
  120525. static long _huff_lengthlist_line_128x11_class1[] = {
  120526. 1, 6, 3, 7, 2, 4, 5, 7,
  120527. };
  120528. static static_codebook _huff_book_line_128x11_class1 = {
  120529. 1, 8,
  120530. _huff_lengthlist_line_128x11_class1,
  120531. 0, 0, 0, 0, 0,
  120532. NULL,
  120533. NULL,
  120534. NULL,
  120535. NULL,
  120536. 0
  120537. };
  120538. static long _huff_lengthlist_line_128x11_class2[] = {
  120539. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  120540. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  120541. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  120542. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  120543. };
  120544. static static_codebook _huff_book_line_128x11_class2 = {
  120545. 1, 64,
  120546. _huff_lengthlist_line_128x11_class2,
  120547. 0, 0, 0, 0, 0,
  120548. NULL,
  120549. NULL,
  120550. NULL,
  120551. NULL,
  120552. 0
  120553. };
  120554. static long _huff_lengthlist_line_128x11_class3[] = {
  120555. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  120556. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  120557. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  120558. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  120559. };
  120560. static static_codebook _huff_book_line_128x11_class3 = {
  120561. 1, 64,
  120562. _huff_lengthlist_line_128x11_class3,
  120563. 0, 0, 0, 0, 0,
  120564. NULL,
  120565. NULL,
  120566. NULL,
  120567. NULL,
  120568. 0
  120569. };
  120570. static long _huff_lengthlist_line_128x11_0sub0[] = {
  120571. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  120572. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  120573. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  120574. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  120575. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  120576. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  120577. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  120578. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  120579. };
  120580. static static_codebook _huff_book_line_128x11_0sub0 = {
  120581. 1, 128,
  120582. _huff_lengthlist_line_128x11_0sub0,
  120583. 0, 0, 0, 0, 0,
  120584. NULL,
  120585. NULL,
  120586. NULL,
  120587. NULL,
  120588. 0
  120589. };
  120590. static long _huff_lengthlist_line_128x11_1sub0[] = {
  120591. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  120592. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  120593. };
  120594. static static_codebook _huff_book_line_128x11_1sub0 = {
  120595. 1, 32,
  120596. _huff_lengthlist_line_128x11_1sub0,
  120597. 0, 0, 0, 0, 0,
  120598. NULL,
  120599. NULL,
  120600. NULL,
  120601. NULL,
  120602. 0
  120603. };
  120604. static long _huff_lengthlist_line_128x11_1sub1[] = {
  120605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120607. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  120608. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  120609. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  120610. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  120611. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  120612. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  120613. };
  120614. static static_codebook _huff_book_line_128x11_1sub1 = {
  120615. 1, 128,
  120616. _huff_lengthlist_line_128x11_1sub1,
  120617. 0, 0, 0, 0, 0,
  120618. NULL,
  120619. NULL,
  120620. NULL,
  120621. NULL,
  120622. 0
  120623. };
  120624. static long _huff_lengthlist_line_128x11_2sub1[] = {
  120625. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  120626. 5, 5,
  120627. };
  120628. static static_codebook _huff_book_line_128x11_2sub1 = {
  120629. 1, 18,
  120630. _huff_lengthlist_line_128x11_2sub1,
  120631. 0, 0, 0, 0, 0,
  120632. NULL,
  120633. NULL,
  120634. NULL,
  120635. NULL,
  120636. 0
  120637. };
  120638. static long _huff_lengthlist_line_128x11_2sub2[] = {
  120639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120640. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  120641. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  120642. 8,11,
  120643. };
  120644. static static_codebook _huff_book_line_128x11_2sub2 = {
  120645. 1, 50,
  120646. _huff_lengthlist_line_128x11_2sub2,
  120647. 0, 0, 0, 0, 0,
  120648. NULL,
  120649. NULL,
  120650. NULL,
  120651. NULL,
  120652. 0
  120653. };
  120654. static long _huff_lengthlist_line_128x11_2sub3[] = {
  120655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120658. 0, 0, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  120659. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120660. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120661. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120662. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120663. };
  120664. static static_codebook _huff_book_line_128x11_2sub3 = {
  120665. 1, 128,
  120666. _huff_lengthlist_line_128x11_2sub3,
  120667. 0, 0, 0, 0, 0,
  120668. NULL,
  120669. NULL,
  120670. NULL,
  120671. NULL,
  120672. 0
  120673. };
  120674. static long _huff_lengthlist_line_128x11_3sub1[] = {
  120675. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  120676. 5, 4,
  120677. };
  120678. static static_codebook _huff_book_line_128x11_3sub1 = {
  120679. 1, 18,
  120680. _huff_lengthlist_line_128x11_3sub1,
  120681. 0, 0, 0, 0, 0,
  120682. NULL,
  120683. NULL,
  120684. NULL,
  120685. NULL,
  120686. 0
  120687. };
  120688. static long _huff_lengthlist_line_128x11_3sub2[] = {
  120689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120690. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  120691. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  120692. 12, 6,
  120693. };
  120694. static static_codebook _huff_book_line_128x11_3sub2 = {
  120695. 1, 50,
  120696. _huff_lengthlist_line_128x11_3sub2,
  120697. 0, 0, 0, 0, 0,
  120698. NULL,
  120699. NULL,
  120700. NULL,
  120701. NULL,
  120702. 0
  120703. };
  120704. static long _huff_lengthlist_line_128x11_3sub3[] = {
  120705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120708. 0, 0, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  120709. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  120710. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120711. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120712. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  120713. };
  120714. static static_codebook _huff_book_line_128x11_3sub3 = {
  120715. 1, 128,
  120716. _huff_lengthlist_line_128x11_3sub3,
  120717. 0, 0, 0, 0, 0,
  120718. NULL,
  120719. NULL,
  120720. NULL,
  120721. NULL,
  120722. 0
  120723. };
  120724. static long _huff_lengthlist_line_128x17_class1[] = {
  120725. 1, 3, 4, 7, 2, 5, 6, 7,
  120726. };
  120727. static static_codebook _huff_book_line_128x17_class1 = {
  120728. 1, 8,
  120729. _huff_lengthlist_line_128x17_class1,
  120730. 0, 0, 0, 0, 0,
  120731. NULL,
  120732. NULL,
  120733. NULL,
  120734. NULL,
  120735. 0
  120736. };
  120737. static long _huff_lengthlist_line_128x17_class2[] = {
  120738. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  120739. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  120740. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  120741. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  120742. };
  120743. static static_codebook _huff_book_line_128x17_class2 = {
  120744. 1, 64,
  120745. _huff_lengthlist_line_128x17_class2,
  120746. 0, 0, 0, 0, 0,
  120747. NULL,
  120748. NULL,
  120749. NULL,
  120750. NULL,
  120751. 0
  120752. };
  120753. static long _huff_lengthlist_line_128x17_class3[] = {
  120754. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  120755. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  120756. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  120757. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  120758. };
  120759. static static_codebook _huff_book_line_128x17_class3 = {
  120760. 1, 64,
  120761. _huff_lengthlist_line_128x17_class3,
  120762. 0, 0, 0, 0, 0,
  120763. NULL,
  120764. NULL,
  120765. NULL,
  120766. NULL,
  120767. 0
  120768. };
  120769. static long _huff_lengthlist_line_128x17_0sub0[] = {
  120770. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  120771. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  120772. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  120773. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  120774. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  120775. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  120776. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  120777. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  120778. };
  120779. static static_codebook _huff_book_line_128x17_0sub0 = {
  120780. 1, 128,
  120781. _huff_lengthlist_line_128x17_0sub0,
  120782. 0, 0, 0, 0, 0,
  120783. NULL,
  120784. NULL,
  120785. NULL,
  120786. NULL,
  120787. 0
  120788. };
  120789. static long _huff_lengthlist_line_128x17_1sub0[] = {
  120790. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  120791. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  120792. };
  120793. static static_codebook _huff_book_line_128x17_1sub0 = {
  120794. 1, 32,
  120795. _huff_lengthlist_line_128x17_1sub0,
  120796. 0, 0, 0, 0, 0,
  120797. NULL,
  120798. NULL,
  120799. NULL,
  120800. NULL,
  120801. 0
  120802. };
  120803. static long _huff_lengthlist_line_128x17_1sub1[] = {
  120804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120806. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  120807. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  120808. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  120809. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  120810. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  120811. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  120812. };
  120813. static static_codebook _huff_book_line_128x17_1sub1 = {
  120814. 1, 128,
  120815. _huff_lengthlist_line_128x17_1sub1,
  120816. 0, 0, 0, 0, 0,
  120817. NULL,
  120818. NULL,
  120819. NULL,
  120820. NULL,
  120821. 0
  120822. };
  120823. static long _huff_lengthlist_line_128x17_2sub1[] = {
  120824. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  120825. 9, 4,
  120826. };
  120827. static static_codebook _huff_book_line_128x17_2sub1 = {
  120828. 1, 18,
  120829. _huff_lengthlist_line_128x17_2sub1,
  120830. 0, 0, 0, 0, 0,
  120831. NULL,
  120832. NULL,
  120833. NULL,
  120834. NULL,
  120835. 0
  120836. };
  120837. static long _huff_lengthlist_line_128x17_2sub2[] = {
  120838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120839. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  120840. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  120841. 13,13,
  120842. };
  120843. static static_codebook _huff_book_line_128x17_2sub2 = {
  120844. 1, 50,
  120845. _huff_lengthlist_line_128x17_2sub2,
  120846. 0, 0, 0, 0, 0,
  120847. NULL,
  120848. NULL,
  120849. NULL,
  120850. NULL,
  120851. 0
  120852. };
  120853. static long _huff_lengthlist_line_128x17_2sub3[] = {
  120854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120857. 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120858. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  120859. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  120860. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  120861. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  120862. };
  120863. static static_codebook _huff_book_line_128x17_2sub3 = {
  120864. 1, 128,
  120865. _huff_lengthlist_line_128x17_2sub3,
  120866. 0, 0, 0, 0, 0,
  120867. NULL,
  120868. NULL,
  120869. NULL,
  120870. NULL,
  120871. 0
  120872. };
  120873. static long _huff_lengthlist_line_128x17_3sub1[] = {
  120874. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  120875. 6, 4,
  120876. };
  120877. static static_codebook _huff_book_line_128x17_3sub1 = {
  120878. 1, 18,
  120879. _huff_lengthlist_line_128x17_3sub1,
  120880. 0, 0, 0, 0, 0,
  120881. NULL,
  120882. NULL,
  120883. NULL,
  120884. NULL,
  120885. 0
  120886. };
  120887. static long _huff_lengthlist_line_128x17_3sub2[] = {
  120888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120889. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  120890. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  120891. 10, 8,
  120892. };
  120893. static static_codebook _huff_book_line_128x17_3sub2 = {
  120894. 1, 50,
  120895. _huff_lengthlist_line_128x17_3sub2,
  120896. 0, 0, 0, 0, 0,
  120897. NULL,
  120898. NULL,
  120899. NULL,
  120900. NULL,
  120901. 0
  120902. };
  120903. static long _huff_lengthlist_line_128x17_3sub3[] = {
  120904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120907. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  120908. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  120909. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  120910. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  120911. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  120912. };
  120913. static static_codebook _huff_book_line_128x17_3sub3 = {
  120914. 1, 128,
  120915. _huff_lengthlist_line_128x17_3sub3,
  120916. 0, 0, 0, 0, 0,
  120917. NULL,
  120918. NULL,
  120919. NULL,
  120920. NULL,
  120921. 0
  120922. };
  120923. static long _huff_lengthlist_line_1024x27_class1[] = {
  120924. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  120925. };
  120926. static static_codebook _huff_book_line_1024x27_class1 = {
  120927. 1, 16,
  120928. _huff_lengthlist_line_1024x27_class1,
  120929. 0, 0, 0, 0, 0,
  120930. NULL,
  120931. NULL,
  120932. NULL,
  120933. NULL,
  120934. 0
  120935. };
  120936. static long _huff_lengthlist_line_1024x27_class2[] = {
  120937. 1, 4, 2, 6, 3, 7, 5, 7,
  120938. };
  120939. static static_codebook _huff_book_line_1024x27_class2 = {
  120940. 1, 8,
  120941. _huff_lengthlist_line_1024x27_class2,
  120942. 0, 0, 0, 0, 0,
  120943. NULL,
  120944. NULL,
  120945. NULL,
  120946. NULL,
  120947. 0
  120948. };
  120949. static long _huff_lengthlist_line_1024x27_class3[] = {
  120950. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  120951. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  120952. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  120953. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  120954. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  120955. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  120956. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  120957. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  120958. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  120959. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  120960. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  120961. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  120962. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  120963. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  120964. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  120965. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  120966. };
  120967. static static_codebook _huff_book_line_1024x27_class3 = {
  120968. 1, 256,
  120969. _huff_lengthlist_line_1024x27_class3,
  120970. 0, 0, 0, 0, 0,
  120971. NULL,
  120972. NULL,
  120973. NULL,
  120974. NULL,
  120975. 0
  120976. };
  120977. static long _huff_lengthlist_line_1024x27_class4[] = {
  120978. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  120979. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  120980. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  120981. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  120982. };
  120983. static static_codebook _huff_book_line_1024x27_class4 = {
  120984. 1, 64,
  120985. _huff_lengthlist_line_1024x27_class4,
  120986. 0, 0, 0, 0, 0,
  120987. NULL,
  120988. NULL,
  120989. NULL,
  120990. NULL,
  120991. 0
  120992. };
  120993. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  120994. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  120995. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  120996. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  120997. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  120998. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  120999. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  121000. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  121001. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  121002. };
  121003. static static_codebook _huff_book_line_1024x27_0sub0 = {
  121004. 1, 128,
  121005. _huff_lengthlist_line_1024x27_0sub0,
  121006. 0, 0, 0, 0, 0,
  121007. NULL,
  121008. NULL,
  121009. NULL,
  121010. NULL,
  121011. 0
  121012. };
  121013. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  121014. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  121015. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  121016. };
  121017. static static_codebook _huff_book_line_1024x27_1sub0 = {
  121018. 1, 32,
  121019. _huff_lengthlist_line_1024x27_1sub0,
  121020. 0, 0, 0, 0, 0,
  121021. NULL,
  121022. NULL,
  121023. NULL,
  121024. NULL,
  121025. 0
  121026. };
  121027. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  121028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121030. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  121031. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  121032. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  121033. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  121034. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  121035. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  121036. };
  121037. static static_codebook _huff_book_line_1024x27_1sub1 = {
  121038. 1, 128,
  121039. _huff_lengthlist_line_1024x27_1sub1,
  121040. 0, 0, 0, 0, 0,
  121041. NULL,
  121042. NULL,
  121043. NULL,
  121044. NULL,
  121045. 0
  121046. };
  121047. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  121048. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121049. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  121050. };
  121051. static static_codebook _huff_book_line_1024x27_2sub0 = {
  121052. 1, 32,
  121053. _huff_lengthlist_line_1024x27_2sub0,
  121054. 0, 0, 0, 0, 0,
  121055. NULL,
  121056. NULL,
  121057. NULL,
  121058. NULL,
  121059. 0
  121060. };
  121061. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  121062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121064. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  121065. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  121066. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  121067. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  121068. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  121069. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  121070. };
  121071. static static_codebook _huff_book_line_1024x27_2sub1 = {
  121072. 1, 128,
  121073. _huff_lengthlist_line_1024x27_2sub1,
  121074. 0, 0, 0, 0, 0,
  121075. NULL,
  121076. NULL,
  121077. NULL,
  121078. NULL,
  121079. 0
  121080. };
  121081. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  121082. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  121083. 5, 5,
  121084. };
  121085. static static_codebook _huff_book_line_1024x27_3sub1 = {
  121086. 1, 18,
  121087. _huff_lengthlist_line_1024x27_3sub1,
  121088. 0, 0, 0, 0, 0,
  121089. NULL,
  121090. NULL,
  121091. NULL,
  121092. NULL,
  121093. 0
  121094. };
  121095. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  121096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121097. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  121098. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  121099. 9,11,
  121100. };
  121101. static static_codebook _huff_book_line_1024x27_3sub2 = {
  121102. 1, 50,
  121103. _huff_lengthlist_line_1024x27_3sub2,
  121104. 0, 0, 0, 0, 0,
  121105. NULL,
  121106. NULL,
  121107. NULL,
  121108. NULL,
  121109. 0
  121110. };
  121111. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  121112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121115. 0, 0, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  121116. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  121117. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121118. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121119. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121120. };
  121121. static static_codebook _huff_book_line_1024x27_3sub3 = {
  121122. 1, 128,
  121123. _huff_lengthlist_line_1024x27_3sub3,
  121124. 0, 0, 0, 0, 0,
  121125. NULL,
  121126. NULL,
  121127. NULL,
  121128. NULL,
  121129. 0
  121130. };
  121131. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  121132. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  121133. 5, 4,
  121134. };
  121135. static static_codebook _huff_book_line_1024x27_4sub1 = {
  121136. 1, 18,
  121137. _huff_lengthlist_line_1024x27_4sub1,
  121138. 0, 0, 0, 0, 0,
  121139. NULL,
  121140. NULL,
  121141. NULL,
  121142. NULL,
  121143. 0
  121144. };
  121145. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  121146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121147. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  121148. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  121149. 9,12,
  121150. };
  121151. static static_codebook _huff_book_line_1024x27_4sub2 = {
  121152. 1, 50,
  121153. _huff_lengthlist_line_1024x27_4sub2,
  121154. 0, 0, 0, 0, 0,
  121155. NULL,
  121156. NULL,
  121157. NULL,
  121158. NULL,
  121159. 0
  121160. };
  121161. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  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, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  121166. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  121167. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121168. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121169. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  121170. };
  121171. static static_codebook _huff_book_line_1024x27_4sub3 = {
  121172. 1, 128,
  121173. _huff_lengthlist_line_1024x27_4sub3,
  121174. 0, 0, 0, 0, 0,
  121175. NULL,
  121176. NULL,
  121177. NULL,
  121178. NULL,
  121179. 0
  121180. };
  121181. static long _huff_lengthlist_line_2048x27_class1[] = {
  121182. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  121183. };
  121184. static static_codebook _huff_book_line_2048x27_class1 = {
  121185. 1, 16,
  121186. _huff_lengthlist_line_2048x27_class1,
  121187. 0, 0, 0, 0, 0,
  121188. NULL,
  121189. NULL,
  121190. NULL,
  121191. NULL,
  121192. 0
  121193. };
  121194. static long _huff_lengthlist_line_2048x27_class2[] = {
  121195. 1, 2, 3, 6, 4, 7, 5, 7,
  121196. };
  121197. static static_codebook _huff_book_line_2048x27_class2 = {
  121198. 1, 8,
  121199. _huff_lengthlist_line_2048x27_class2,
  121200. 0, 0, 0, 0, 0,
  121201. NULL,
  121202. NULL,
  121203. NULL,
  121204. NULL,
  121205. 0
  121206. };
  121207. static long _huff_lengthlist_line_2048x27_class3[] = {
  121208. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  121209. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  121210. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  121211. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  121212. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  121213. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  121214. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  121215. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  121216. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  121217. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  121218. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  121219. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  121220. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  121221. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  121222. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  121223. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  121224. };
  121225. static static_codebook _huff_book_line_2048x27_class3 = {
  121226. 1, 256,
  121227. _huff_lengthlist_line_2048x27_class3,
  121228. 0, 0, 0, 0, 0,
  121229. NULL,
  121230. NULL,
  121231. NULL,
  121232. NULL,
  121233. 0
  121234. };
  121235. static long _huff_lengthlist_line_2048x27_class4[] = {
  121236. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  121237. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  121238. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  121239. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  121240. };
  121241. static static_codebook _huff_book_line_2048x27_class4 = {
  121242. 1, 64,
  121243. _huff_lengthlist_line_2048x27_class4,
  121244. 0, 0, 0, 0, 0,
  121245. NULL,
  121246. NULL,
  121247. NULL,
  121248. NULL,
  121249. 0
  121250. };
  121251. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  121252. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121253. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  121254. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  121255. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  121256. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  121257. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  121258. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  121259. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  121260. };
  121261. static static_codebook _huff_book_line_2048x27_0sub0 = {
  121262. 1, 128,
  121263. _huff_lengthlist_line_2048x27_0sub0,
  121264. 0, 0, 0, 0, 0,
  121265. NULL,
  121266. NULL,
  121267. NULL,
  121268. NULL,
  121269. 0
  121270. };
  121271. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  121272. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  121273. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  121274. };
  121275. static static_codebook _huff_book_line_2048x27_1sub0 = {
  121276. 1, 32,
  121277. _huff_lengthlist_line_2048x27_1sub0,
  121278. 0, 0, 0, 0, 0,
  121279. NULL,
  121280. NULL,
  121281. NULL,
  121282. NULL,
  121283. 0
  121284. };
  121285. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  121286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121288. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  121289. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  121290. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  121291. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  121292. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  121293. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  121294. };
  121295. static static_codebook _huff_book_line_2048x27_1sub1 = {
  121296. 1, 128,
  121297. _huff_lengthlist_line_2048x27_1sub1,
  121298. 0, 0, 0, 0, 0,
  121299. NULL,
  121300. NULL,
  121301. NULL,
  121302. NULL,
  121303. 0
  121304. };
  121305. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  121306. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121307. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  121308. };
  121309. static static_codebook _huff_book_line_2048x27_2sub0 = {
  121310. 1, 32,
  121311. _huff_lengthlist_line_2048x27_2sub0,
  121312. 0, 0, 0, 0, 0,
  121313. NULL,
  121314. NULL,
  121315. NULL,
  121316. NULL,
  121317. 0
  121318. };
  121319. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  121320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121322. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  121323. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  121324. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  121325. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  121326. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  121327. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121328. };
  121329. static static_codebook _huff_book_line_2048x27_2sub1 = {
  121330. 1, 128,
  121331. _huff_lengthlist_line_2048x27_2sub1,
  121332. 0, 0, 0, 0, 0,
  121333. NULL,
  121334. NULL,
  121335. NULL,
  121336. NULL,
  121337. 0
  121338. };
  121339. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  121340. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  121341. 5, 5,
  121342. };
  121343. static static_codebook _huff_book_line_2048x27_3sub1 = {
  121344. 1, 18,
  121345. _huff_lengthlist_line_2048x27_3sub1,
  121346. 0, 0, 0, 0, 0,
  121347. NULL,
  121348. NULL,
  121349. NULL,
  121350. NULL,
  121351. 0
  121352. };
  121353. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  121354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121355. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  121356. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  121357. 10,12,
  121358. };
  121359. static static_codebook _huff_book_line_2048x27_3sub2 = {
  121360. 1, 50,
  121361. _huff_lengthlist_line_2048x27_3sub2,
  121362. 0, 0, 0, 0, 0,
  121363. NULL,
  121364. NULL,
  121365. NULL,
  121366. NULL,
  121367. 0
  121368. };
  121369. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  121370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121373. 0, 0, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  121374. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121375. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121376. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121377. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121378. };
  121379. static static_codebook _huff_book_line_2048x27_3sub3 = {
  121380. 1, 128,
  121381. _huff_lengthlist_line_2048x27_3sub3,
  121382. 0, 0, 0, 0, 0,
  121383. NULL,
  121384. NULL,
  121385. NULL,
  121386. NULL,
  121387. 0
  121388. };
  121389. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  121390. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  121391. 4, 5,
  121392. };
  121393. static static_codebook _huff_book_line_2048x27_4sub1 = {
  121394. 1, 18,
  121395. _huff_lengthlist_line_2048x27_4sub1,
  121396. 0, 0, 0, 0, 0,
  121397. NULL,
  121398. NULL,
  121399. NULL,
  121400. NULL,
  121401. 0
  121402. };
  121403. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  121404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121405. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  121406. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  121407. 10,10,
  121408. };
  121409. static static_codebook _huff_book_line_2048x27_4sub2 = {
  121410. 1, 50,
  121411. _huff_lengthlist_line_2048x27_4sub2,
  121412. 0, 0, 0, 0, 0,
  121413. NULL,
  121414. NULL,
  121415. NULL,
  121416. NULL,
  121417. 0
  121418. };
  121419. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  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, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  121424. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  121425. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121426. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121427. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121428. };
  121429. static static_codebook _huff_book_line_2048x27_4sub3 = {
  121430. 1, 128,
  121431. _huff_lengthlist_line_2048x27_4sub3,
  121432. 0, 0, 0, 0, 0,
  121433. NULL,
  121434. NULL,
  121435. NULL,
  121436. NULL,
  121437. 0
  121438. };
  121439. static long _huff_lengthlist_line_256x4low_class0[] = {
  121440. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  121441. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  121442. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  121443. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  121444. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  121445. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  121446. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  121447. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  121448. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  121449. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  121450. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  121451. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  121452. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  121453. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  121454. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  121455. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  121456. };
  121457. static static_codebook _huff_book_line_256x4low_class0 = {
  121458. 1, 256,
  121459. _huff_lengthlist_line_256x4low_class0,
  121460. 0, 0, 0, 0, 0,
  121461. NULL,
  121462. NULL,
  121463. NULL,
  121464. NULL,
  121465. 0
  121466. };
  121467. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  121468. 1, 3, 2, 3,
  121469. };
  121470. static static_codebook _huff_book_line_256x4low_0sub0 = {
  121471. 1, 4,
  121472. _huff_lengthlist_line_256x4low_0sub0,
  121473. 0, 0, 0, 0, 0,
  121474. NULL,
  121475. NULL,
  121476. NULL,
  121477. NULL,
  121478. 0
  121479. };
  121480. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  121481. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  121482. };
  121483. static static_codebook _huff_book_line_256x4low_0sub1 = {
  121484. 1, 10,
  121485. _huff_lengthlist_line_256x4low_0sub1,
  121486. 0, 0, 0, 0, 0,
  121487. NULL,
  121488. NULL,
  121489. NULL,
  121490. NULL,
  121491. 0
  121492. };
  121493. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  121494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  121495. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  121496. };
  121497. static static_codebook _huff_book_line_256x4low_0sub2 = {
  121498. 1, 25,
  121499. _huff_lengthlist_line_256x4low_0sub2,
  121500. 0, 0, 0, 0, 0,
  121501. NULL,
  121502. NULL,
  121503. NULL,
  121504. NULL,
  121505. 0
  121506. };
  121507. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  121508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 2, 4, 3, 5, 4,
  121510. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  121511. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  121512. };
  121513. static static_codebook _huff_book_line_256x4low_0sub3 = {
  121514. 1, 64,
  121515. _huff_lengthlist_line_256x4low_0sub3,
  121516. 0, 0, 0, 0, 0,
  121517. NULL,
  121518. NULL,
  121519. NULL,
  121520. NULL,
  121521. 0
  121522. };
  121523. /*** End of inlined file: floor_books.h ***/
  121524. static static_codebook *_floor_128x4_books[]={
  121525. &_huff_book_line_128x4_class0,
  121526. &_huff_book_line_128x4_0sub0,
  121527. &_huff_book_line_128x4_0sub1,
  121528. &_huff_book_line_128x4_0sub2,
  121529. &_huff_book_line_128x4_0sub3,
  121530. };
  121531. static static_codebook *_floor_256x4_books[]={
  121532. &_huff_book_line_256x4_class0,
  121533. &_huff_book_line_256x4_0sub0,
  121534. &_huff_book_line_256x4_0sub1,
  121535. &_huff_book_line_256x4_0sub2,
  121536. &_huff_book_line_256x4_0sub3,
  121537. };
  121538. static static_codebook *_floor_128x7_books[]={
  121539. &_huff_book_line_128x7_class0,
  121540. &_huff_book_line_128x7_class1,
  121541. &_huff_book_line_128x7_0sub1,
  121542. &_huff_book_line_128x7_0sub2,
  121543. &_huff_book_line_128x7_0sub3,
  121544. &_huff_book_line_128x7_1sub1,
  121545. &_huff_book_line_128x7_1sub2,
  121546. &_huff_book_line_128x7_1sub3,
  121547. };
  121548. static static_codebook *_floor_256x7_books[]={
  121549. &_huff_book_line_256x7_class0,
  121550. &_huff_book_line_256x7_class1,
  121551. &_huff_book_line_256x7_0sub1,
  121552. &_huff_book_line_256x7_0sub2,
  121553. &_huff_book_line_256x7_0sub3,
  121554. &_huff_book_line_256x7_1sub1,
  121555. &_huff_book_line_256x7_1sub2,
  121556. &_huff_book_line_256x7_1sub3,
  121557. };
  121558. static static_codebook *_floor_128x11_books[]={
  121559. &_huff_book_line_128x11_class1,
  121560. &_huff_book_line_128x11_class2,
  121561. &_huff_book_line_128x11_class3,
  121562. &_huff_book_line_128x11_0sub0,
  121563. &_huff_book_line_128x11_1sub0,
  121564. &_huff_book_line_128x11_1sub1,
  121565. &_huff_book_line_128x11_2sub1,
  121566. &_huff_book_line_128x11_2sub2,
  121567. &_huff_book_line_128x11_2sub3,
  121568. &_huff_book_line_128x11_3sub1,
  121569. &_huff_book_line_128x11_3sub2,
  121570. &_huff_book_line_128x11_3sub3,
  121571. };
  121572. static static_codebook *_floor_128x17_books[]={
  121573. &_huff_book_line_128x17_class1,
  121574. &_huff_book_line_128x17_class2,
  121575. &_huff_book_line_128x17_class3,
  121576. &_huff_book_line_128x17_0sub0,
  121577. &_huff_book_line_128x17_1sub0,
  121578. &_huff_book_line_128x17_1sub1,
  121579. &_huff_book_line_128x17_2sub1,
  121580. &_huff_book_line_128x17_2sub2,
  121581. &_huff_book_line_128x17_2sub3,
  121582. &_huff_book_line_128x17_3sub1,
  121583. &_huff_book_line_128x17_3sub2,
  121584. &_huff_book_line_128x17_3sub3,
  121585. };
  121586. static static_codebook *_floor_256x4low_books[]={
  121587. &_huff_book_line_256x4low_class0,
  121588. &_huff_book_line_256x4low_0sub0,
  121589. &_huff_book_line_256x4low_0sub1,
  121590. &_huff_book_line_256x4low_0sub2,
  121591. &_huff_book_line_256x4low_0sub3,
  121592. };
  121593. static static_codebook *_floor_1024x27_books[]={
  121594. &_huff_book_line_1024x27_class1,
  121595. &_huff_book_line_1024x27_class2,
  121596. &_huff_book_line_1024x27_class3,
  121597. &_huff_book_line_1024x27_class4,
  121598. &_huff_book_line_1024x27_0sub0,
  121599. &_huff_book_line_1024x27_1sub0,
  121600. &_huff_book_line_1024x27_1sub1,
  121601. &_huff_book_line_1024x27_2sub0,
  121602. &_huff_book_line_1024x27_2sub1,
  121603. &_huff_book_line_1024x27_3sub1,
  121604. &_huff_book_line_1024x27_3sub2,
  121605. &_huff_book_line_1024x27_3sub3,
  121606. &_huff_book_line_1024x27_4sub1,
  121607. &_huff_book_line_1024x27_4sub2,
  121608. &_huff_book_line_1024x27_4sub3,
  121609. };
  121610. static static_codebook *_floor_2048x27_books[]={
  121611. &_huff_book_line_2048x27_class1,
  121612. &_huff_book_line_2048x27_class2,
  121613. &_huff_book_line_2048x27_class3,
  121614. &_huff_book_line_2048x27_class4,
  121615. &_huff_book_line_2048x27_0sub0,
  121616. &_huff_book_line_2048x27_1sub0,
  121617. &_huff_book_line_2048x27_1sub1,
  121618. &_huff_book_line_2048x27_2sub0,
  121619. &_huff_book_line_2048x27_2sub1,
  121620. &_huff_book_line_2048x27_3sub1,
  121621. &_huff_book_line_2048x27_3sub2,
  121622. &_huff_book_line_2048x27_3sub3,
  121623. &_huff_book_line_2048x27_4sub1,
  121624. &_huff_book_line_2048x27_4sub2,
  121625. &_huff_book_line_2048x27_4sub3,
  121626. };
  121627. static static_codebook *_floor_512x17_books[]={
  121628. &_huff_book_line_512x17_class1,
  121629. &_huff_book_line_512x17_class2,
  121630. &_huff_book_line_512x17_class3,
  121631. &_huff_book_line_512x17_0sub0,
  121632. &_huff_book_line_512x17_1sub0,
  121633. &_huff_book_line_512x17_1sub1,
  121634. &_huff_book_line_512x17_2sub1,
  121635. &_huff_book_line_512x17_2sub2,
  121636. &_huff_book_line_512x17_2sub3,
  121637. &_huff_book_line_512x17_3sub1,
  121638. &_huff_book_line_512x17_3sub2,
  121639. &_huff_book_line_512x17_3sub3,
  121640. };
  121641. static static_codebook **_floor_books[10]={
  121642. _floor_128x4_books,
  121643. _floor_256x4_books,
  121644. _floor_128x7_books,
  121645. _floor_256x7_books,
  121646. _floor_128x11_books,
  121647. _floor_128x17_books,
  121648. _floor_256x4low_books,
  121649. _floor_1024x27_books,
  121650. _floor_2048x27_books,
  121651. _floor_512x17_books,
  121652. };
  121653. static vorbis_info_floor1 _floor[10]={
  121654. /* 128 x 4 */
  121655. {
  121656. 1,{0},{4},{2},{0},
  121657. {{1,2,3,4}},
  121658. 4,{0,128, 33,8,16,70},
  121659. 60,30,500, 1.,18., -1
  121660. },
  121661. /* 256 x 4 */
  121662. {
  121663. 1,{0},{4},{2},{0},
  121664. {{1,2,3,4}},
  121665. 4,{0,256, 66,16,32,140},
  121666. 60,30,500, 1.,18., -1
  121667. },
  121668. /* 128 x 7 */
  121669. {
  121670. 2,{0,1},{3,4},{2,2},{0,1},
  121671. {{-1,2,3,4},{-1,5,6,7}},
  121672. 4,{0,128, 14,4,58, 2,8,28,90},
  121673. 60,30,500, 1.,18., -1
  121674. },
  121675. /* 256 x 7 */
  121676. {
  121677. 2,{0,1},{3,4},{2,2},{0,1},
  121678. {{-1,2,3,4},{-1,5,6,7}},
  121679. 4,{0,256, 28,8,116, 4,16,56,180},
  121680. 60,30,500, 1.,18., -1
  121681. },
  121682. /* 128 x 11 */
  121683. {
  121684. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  121685. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  121686. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  121687. 60,30,500, 1,18., -1
  121688. },
  121689. /* 128 x 17 */
  121690. {
  121691. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  121692. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  121693. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  121694. 60,30,500, 1,18., -1
  121695. },
  121696. /* 256 x 4 (low bitrate version) */
  121697. {
  121698. 1,{0},{4},{2},{0},
  121699. {{1,2,3,4}},
  121700. 4,{0,256, 66,16,32,140},
  121701. 60,30,500, 1.,18., -1
  121702. },
  121703. /* 1024 x 27 */
  121704. {
  121705. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  121706. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  121707. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  121708. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  121709. 60,30,500, 3,18., -1 /* lowpass */
  121710. },
  121711. /* 2048 x 27 */
  121712. {
  121713. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  121714. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  121715. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  121716. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  121717. 60,30,500, 3,18., -1 /* lowpass */
  121718. },
  121719. /* 512 x 17 */
  121720. {
  121721. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  121722. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  121723. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  121724. 7,23,39, 55,79,110, 156,232,360},
  121725. 60,30,500, 1,18., -1 /* lowpass! */
  121726. },
  121727. };
  121728. /*** End of inlined file: floor_all.h ***/
  121729. /*** Start of inlined file: residue_44.h ***/
  121730. /*** Start of inlined file: res_books_stereo.h ***/
  121731. static long _vq_quantlist__16c0_s_p1_0[] = {
  121732. 1,
  121733. 0,
  121734. 2,
  121735. };
  121736. static long _vq_lengthlist__16c0_s_p1_0[] = {
  121737. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  121738. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121742. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  121743. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121747. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  121748. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  121783. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  121784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  121788. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  121789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  121793. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  121794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0,
  121818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121828. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  121829. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121833. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  121834. 0, 0, 0, 0, 0, 9,10,12, 0, 0, 0, 0, 0, 0, 0, 0,
  121835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121838. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  121839. 0, 0, 0, 0, 0, 0, 9,12, 9, 0, 0, 0, 0, 0, 0, 0,
  121840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122147. 0,
  122148. };
  122149. static float _vq_quantthresh__16c0_s_p1_0[] = {
  122150. -0.5, 0.5,
  122151. };
  122152. static long _vq_quantmap__16c0_s_p1_0[] = {
  122153. 1, 0, 2,
  122154. };
  122155. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  122156. _vq_quantthresh__16c0_s_p1_0,
  122157. _vq_quantmap__16c0_s_p1_0,
  122158. 3,
  122159. 3
  122160. };
  122161. static static_codebook _16c0_s_p1_0 = {
  122162. 8, 6561,
  122163. _vq_lengthlist__16c0_s_p1_0,
  122164. 1, -535822336, 1611661312, 2, 0,
  122165. _vq_quantlist__16c0_s_p1_0,
  122166. NULL,
  122167. &_vq_auxt__16c0_s_p1_0,
  122168. NULL,
  122169. 0
  122170. };
  122171. static long _vq_quantlist__16c0_s_p2_0[] = {
  122172. 2,
  122173. 1,
  122174. 3,
  122175. 0,
  122176. 4,
  122177. };
  122178. static long _vq_lengthlist__16c0_s_p2_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,
  122219. };
  122220. static float _vq_quantthresh__16c0_s_p2_0[] = {
  122221. -1.5, -0.5, 0.5, 1.5,
  122222. };
  122223. static long _vq_quantmap__16c0_s_p2_0[] = {
  122224. 3, 1, 0, 2, 4,
  122225. };
  122226. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  122227. _vq_quantthresh__16c0_s_p2_0,
  122228. _vq_quantmap__16c0_s_p2_0,
  122229. 5,
  122230. 5
  122231. };
  122232. static static_codebook _16c0_s_p2_0 = {
  122233. 4, 625,
  122234. _vq_lengthlist__16c0_s_p2_0,
  122235. 1, -533725184, 1611661312, 3, 0,
  122236. _vq_quantlist__16c0_s_p2_0,
  122237. NULL,
  122238. &_vq_auxt__16c0_s_p2_0,
  122239. NULL,
  122240. 0
  122241. };
  122242. static long _vq_quantlist__16c0_s_p3_0[] = {
  122243. 2,
  122244. 1,
  122245. 3,
  122246. 0,
  122247. 4,
  122248. };
  122249. static long _vq_lengthlist__16c0_s_p3_0[] = {
  122250. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  122252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122253. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  122255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122256. 0, 0, 0, 0, 6, 6, 6, 9, 9, 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,
  122290. };
  122291. static float _vq_quantthresh__16c0_s_p3_0[] = {
  122292. -1.5, -0.5, 0.5, 1.5,
  122293. };
  122294. static long _vq_quantmap__16c0_s_p3_0[] = {
  122295. 3, 1, 0, 2, 4,
  122296. };
  122297. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  122298. _vq_quantthresh__16c0_s_p3_0,
  122299. _vq_quantmap__16c0_s_p3_0,
  122300. 5,
  122301. 5
  122302. };
  122303. static static_codebook _16c0_s_p3_0 = {
  122304. 4, 625,
  122305. _vq_lengthlist__16c0_s_p3_0,
  122306. 1, -533725184, 1611661312, 3, 0,
  122307. _vq_quantlist__16c0_s_p3_0,
  122308. NULL,
  122309. &_vq_auxt__16c0_s_p3_0,
  122310. NULL,
  122311. 0
  122312. };
  122313. static long _vq_quantlist__16c0_s_p4_0[] = {
  122314. 4,
  122315. 3,
  122316. 5,
  122317. 2,
  122318. 6,
  122319. 1,
  122320. 7,
  122321. 0,
  122322. 8,
  122323. };
  122324. static long _vq_lengthlist__16c0_s_p4_0[] = {
  122325. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  122326. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  122327. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  122328. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  122329. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122330. 0,
  122331. };
  122332. static float _vq_quantthresh__16c0_s_p4_0[] = {
  122333. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122334. };
  122335. static long _vq_quantmap__16c0_s_p4_0[] = {
  122336. 7, 5, 3, 1, 0, 2, 4, 6,
  122337. 8,
  122338. };
  122339. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  122340. _vq_quantthresh__16c0_s_p4_0,
  122341. _vq_quantmap__16c0_s_p4_0,
  122342. 9,
  122343. 9
  122344. };
  122345. static static_codebook _16c0_s_p4_0 = {
  122346. 2, 81,
  122347. _vq_lengthlist__16c0_s_p4_0,
  122348. 1, -531628032, 1611661312, 4, 0,
  122349. _vq_quantlist__16c0_s_p4_0,
  122350. NULL,
  122351. &_vq_auxt__16c0_s_p4_0,
  122352. NULL,
  122353. 0
  122354. };
  122355. static long _vq_quantlist__16c0_s_p5_0[] = {
  122356. 4,
  122357. 3,
  122358. 5,
  122359. 2,
  122360. 6,
  122361. 1,
  122362. 7,
  122363. 0,
  122364. 8,
  122365. };
  122366. static long _vq_lengthlist__16c0_s_p5_0[] = {
  122367. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  122368. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  122369. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  122370. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  122371. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  122372. 10,
  122373. };
  122374. static float _vq_quantthresh__16c0_s_p5_0[] = {
  122375. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122376. };
  122377. static long _vq_quantmap__16c0_s_p5_0[] = {
  122378. 7, 5, 3, 1, 0, 2, 4, 6,
  122379. 8,
  122380. };
  122381. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  122382. _vq_quantthresh__16c0_s_p5_0,
  122383. _vq_quantmap__16c0_s_p5_0,
  122384. 9,
  122385. 9
  122386. };
  122387. static static_codebook _16c0_s_p5_0 = {
  122388. 2, 81,
  122389. _vq_lengthlist__16c0_s_p5_0,
  122390. 1, -531628032, 1611661312, 4, 0,
  122391. _vq_quantlist__16c0_s_p5_0,
  122392. NULL,
  122393. &_vq_auxt__16c0_s_p5_0,
  122394. NULL,
  122395. 0
  122396. };
  122397. static long _vq_quantlist__16c0_s_p6_0[] = {
  122398. 8,
  122399. 7,
  122400. 9,
  122401. 6,
  122402. 10,
  122403. 5,
  122404. 11,
  122405. 4,
  122406. 12,
  122407. 3,
  122408. 13,
  122409. 2,
  122410. 14,
  122411. 1,
  122412. 15,
  122413. 0,
  122414. 16,
  122415. };
  122416. static long _vq_lengthlist__16c0_s_p6_0[] = {
  122417. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  122418. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  122419. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  122420. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  122421. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  122422. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  122423. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  122424. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  122425. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  122426. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  122427. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  122428. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  122429. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  122430. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  122431. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  122432. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  122433. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  122434. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  122435. 14,
  122436. };
  122437. static float _vq_quantthresh__16c0_s_p6_0[] = {
  122438. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  122439. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  122440. };
  122441. static long _vq_quantmap__16c0_s_p6_0[] = {
  122442. 15, 13, 11, 9, 7, 5, 3, 1,
  122443. 0, 2, 4, 6, 8, 10, 12, 14,
  122444. 16,
  122445. };
  122446. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  122447. _vq_quantthresh__16c0_s_p6_0,
  122448. _vq_quantmap__16c0_s_p6_0,
  122449. 17,
  122450. 17
  122451. };
  122452. static static_codebook _16c0_s_p6_0 = {
  122453. 2, 289,
  122454. _vq_lengthlist__16c0_s_p6_0,
  122455. 1, -529530880, 1611661312, 5, 0,
  122456. _vq_quantlist__16c0_s_p6_0,
  122457. NULL,
  122458. &_vq_auxt__16c0_s_p6_0,
  122459. NULL,
  122460. 0
  122461. };
  122462. static long _vq_quantlist__16c0_s_p7_0[] = {
  122463. 1,
  122464. 0,
  122465. 2,
  122466. };
  122467. static long _vq_lengthlist__16c0_s_p7_0[] = {
  122468. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  122469. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  122470. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  122471. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  122472. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  122473. 13,
  122474. };
  122475. static float _vq_quantthresh__16c0_s_p7_0[] = {
  122476. -5.5, 5.5,
  122477. };
  122478. static long _vq_quantmap__16c0_s_p7_0[] = {
  122479. 1, 0, 2,
  122480. };
  122481. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  122482. _vq_quantthresh__16c0_s_p7_0,
  122483. _vq_quantmap__16c0_s_p7_0,
  122484. 3,
  122485. 3
  122486. };
  122487. static static_codebook _16c0_s_p7_0 = {
  122488. 4, 81,
  122489. _vq_lengthlist__16c0_s_p7_0,
  122490. 1, -529137664, 1618345984, 2, 0,
  122491. _vq_quantlist__16c0_s_p7_0,
  122492. NULL,
  122493. &_vq_auxt__16c0_s_p7_0,
  122494. NULL,
  122495. 0
  122496. };
  122497. static long _vq_quantlist__16c0_s_p7_1[] = {
  122498. 5,
  122499. 4,
  122500. 6,
  122501. 3,
  122502. 7,
  122503. 2,
  122504. 8,
  122505. 1,
  122506. 9,
  122507. 0,
  122508. 10,
  122509. };
  122510. static long _vq_lengthlist__16c0_s_p7_1[] = {
  122511. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  122512. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  122513. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  122514. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  122515. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  122516. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  122517. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  122518. 11,11,11, 9, 9, 9, 9,10,10,
  122519. };
  122520. static float _vq_quantthresh__16c0_s_p7_1[] = {
  122521. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  122522. 3.5, 4.5,
  122523. };
  122524. static long _vq_quantmap__16c0_s_p7_1[] = {
  122525. 9, 7, 5, 3, 1, 0, 2, 4,
  122526. 6, 8, 10,
  122527. };
  122528. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  122529. _vq_quantthresh__16c0_s_p7_1,
  122530. _vq_quantmap__16c0_s_p7_1,
  122531. 11,
  122532. 11
  122533. };
  122534. static static_codebook _16c0_s_p7_1 = {
  122535. 2, 121,
  122536. _vq_lengthlist__16c0_s_p7_1,
  122537. 1, -531365888, 1611661312, 4, 0,
  122538. _vq_quantlist__16c0_s_p7_1,
  122539. NULL,
  122540. &_vq_auxt__16c0_s_p7_1,
  122541. NULL,
  122542. 0
  122543. };
  122544. static long _vq_quantlist__16c0_s_p8_0[] = {
  122545. 6,
  122546. 5,
  122547. 7,
  122548. 4,
  122549. 8,
  122550. 3,
  122551. 9,
  122552. 2,
  122553. 10,
  122554. 1,
  122555. 11,
  122556. 0,
  122557. 12,
  122558. };
  122559. static long _vq_lengthlist__16c0_s_p8_0[] = {
  122560. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  122561. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  122562. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  122563. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  122564. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  122565. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  122566. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  122567. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  122568. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  122569. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  122570. 0,12,13,13,12,13,14,14,14,
  122571. };
  122572. static float _vq_quantthresh__16c0_s_p8_0[] = {
  122573. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  122574. 12.5, 17.5, 22.5, 27.5,
  122575. };
  122576. static long _vq_quantmap__16c0_s_p8_0[] = {
  122577. 11, 9, 7, 5, 3, 1, 0, 2,
  122578. 4, 6, 8, 10, 12,
  122579. };
  122580. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  122581. _vq_quantthresh__16c0_s_p8_0,
  122582. _vq_quantmap__16c0_s_p8_0,
  122583. 13,
  122584. 13
  122585. };
  122586. static static_codebook _16c0_s_p8_0 = {
  122587. 2, 169,
  122588. _vq_lengthlist__16c0_s_p8_0,
  122589. 1, -526516224, 1616117760, 4, 0,
  122590. _vq_quantlist__16c0_s_p8_0,
  122591. NULL,
  122592. &_vq_auxt__16c0_s_p8_0,
  122593. NULL,
  122594. 0
  122595. };
  122596. static long _vq_quantlist__16c0_s_p8_1[] = {
  122597. 2,
  122598. 1,
  122599. 3,
  122600. 0,
  122601. 4,
  122602. };
  122603. static long _vq_lengthlist__16c0_s_p8_1[] = {
  122604. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  122605. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  122606. };
  122607. static float _vq_quantthresh__16c0_s_p8_1[] = {
  122608. -1.5, -0.5, 0.5, 1.5,
  122609. };
  122610. static long _vq_quantmap__16c0_s_p8_1[] = {
  122611. 3, 1, 0, 2, 4,
  122612. };
  122613. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  122614. _vq_quantthresh__16c0_s_p8_1,
  122615. _vq_quantmap__16c0_s_p8_1,
  122616. 5,
  122617. 5
  122618. };
  122619. static static_codebook _16c0_s_p8_1 = {
  122620. 2, 25,
  122621. _vq_lengthlist__16c0_s_p8_1,
  122622. 1, -533725184, 1611661312, 3, 0,
  122623. _vq_quantlist__16c0_s_p8_1,
  122624. NULL,
  122625. &_vq_auxt__16c0_s_p8_1,
  122626. NULL,
  122627. 0
  122628. };
  122629. static long _vq_quantlist__16c0_s_p9_0[] = {
  122630. 1,
  122631. 0,
  122632. 2,
  122633. };
  122634. static long _vq_lengthlist__16c0_s_p9_0[] = {
  122635. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  122636. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  122637. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122638. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122639. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122640. 7,
  122641. };
  122642. static float _vq_quantthresh__16c0_s_p9_0[] = {
  122643. -157.5, 157.5,
  122644. };
  122645. static long _vq_quantmap__16c0_s_p9_0[] = {
  122646. 1, 0, 2,
  122647. };
  122648. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  122649. _vq_quantthresh__16c0_s_p9_0,
  122650. _vq_quantmap__16c0_s_p9_0,
  122651. 3,
  122652. 3
  122653. };
  122654. static static_codebook _16c0_s_p9_0 = {
  122655. 4, 81,
  122656. _vq_lengthlist__16c0_s_p9_0,
  122657. 1, -518803456, 1628680192, 2, 0,
  122658. _vq_quantlist__16c0_s_p9_0,
  122659. NULL,
  122660. &_vq_auxt__16c0_s_p9_0,
  122661. NULL,
  122662. 0
  122663. };
  122664. static long _vq_quantlist__16c0_s_p9_1[] = {
  122665. 7,
  122666. 6,
  122667. 8,
  122668. 5,
  122669. 9,
  122670. 4,
  122671. 10,
  122672. 3,
  122673. 11,
  122674. 2,
  122675. 12,
  122676. 1,
  122677. 13,
  122678. 0,
  122679. 14,
  122680. };
  122681. static long _vq_lengthlist__16c0_s_p9_1[] = {
  122682. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  122683. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  122684. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  122685. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  122686. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122687. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122688. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122689. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122690. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122691. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122692. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122693. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122694. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122695. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122696. 10,
  122697. };
  122698. static float _vq_quantthresh__16c0_s_p9_1[] = {
  122699. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  122700. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  122701. };
  122702. static long _vq_quantmap__16c0_s_p9_1[] = {
  122703. 13, 11, 9, 7, 5, 3, 1, 0,
  122704. 2, 4, 6, 8, 10, 12, 14,
  122705. };
  122706. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  122707. _vq_quantthresh__16c0_s_p9_1,
  122708. _vq_quantmap__16c0_s_p9_1,
  122709. 15,
  122710. 15
  122711. };
  122712. static static_codebook _16c0_s_p9_1 = {
  122713. 2, 225,
  122714. _vq_lengthlist__16c0_s_p9_1,
  122715. 1, -520986624, 1620377600, 4, 0,
  122716. _vq_quantlist__16c0_s_p9_1,
  122717. NULL,
  122718. &_vq_auxt__16c0_s_p9_1,
  122719. NULL,
  122720. 0
  122721. };
  122722. static long _vq_quantlist__16c0_s_p9_2[] = {
  122723. 10,
  122724. 9,
  122725. 11,
  122726. 8,
  122727. 12,
  122728. 7,
  122729. 13,
  122730. 6,
  122731. 14,
  122732. 5,
  122733. 15,
  122734. 4,
  122735. 16,
  122736. 3,
  122737. 17,
  122738. 2,
  122739. 18,
  122740. 1,
  122741. 19,
  122742. 0,
  122743. 20,
  122744. };
  122745. static long _vq_lengthlist__16c0_s_p9_2[] = {
  122746. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  122747. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  122748. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  122749. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  122750. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  122751. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  122752. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  122753. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  122754. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  122755. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  122756. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  122757. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  122758. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  122759. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  122760. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  122761. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  122762. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  122763. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  122764. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  122765. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  122766. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  122767. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  122768. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  122769. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  122770. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  122771. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  122772. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  122773. 10,11,10,10,11, 9,10,10,10,
  122774. };
  122775. static float _vq_quantthresh__16c0_s_p9_2[] = {
  122776. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  122777. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  122778. 6.5, 7.5, 8.5, 9.5,
  122779. };
  122780. static long _vq_quantmap__16c0_s_p9_2[] = {
  122781. 19, 17, 15, 13, 11, 9, 7, 5,
  122782. 3, 1, 0, 2, 4, 6, 8, 10,
  122783. 12, 14, 16, 18, 20,
  122784. };
  122785. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  122786. _vq_quantthresh__16c0_s_p9_2,
  122787. _vq_quantmap__16c0_s_p9_2,
  122788. 21,
  122789. 21
  122790. };
  122791. static static_codebook _16c0_s_p9_2 = {
  122792. 2, 441,
  122793. _vq_lengthlist__16c0_s_p9_2,
  122794. 1, -529268736, 1611661312, 5, 0,
  122795. _vq_quantlist__16c0_s_p9_2,
  122796. NULL,
  122797. &_vq_auxt__16c0_s_p9_2,
  122798. NULL,
  122799. 0
  122800. };
  122801. static long _huff_lengthlist__16c0_s_single[] = {
  122802. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  122803. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  122804. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  122805. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  122806. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  122807. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  122808. 16,16,18,18,
  122809. };
  122810. static static_codebook _huff_book__16c0_s_single = {
  122811. 2, 100,
  122812. _huff_lengthlist__16c0_s_single,
  122813. 0, 0, 0, 0, 0,
  122814. NULL,
  122815. NULL,
  122816. NULL,
  122817. NULL,
  122818. 0
  122819. };
  122820. static long _huff_lengthlist__16c1_s_long[] = {
  122821. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  122822. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  122823. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  122824. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  122825. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  122826. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  122827. 12,11,11,13,
  122828. };
  122829. static static_codebook _huff_book__16c1_s_long = {
  122830. 2, 100,
  122831. _huff_lengthlist__16c1_s_long,
  122832. 0, 0, 0, 0, 0,
  122833. NULL,
  122834. NULL,
  122835. NULL,
  122836. NULL,
  122837. 0
  122838. };
  122839. static long _vq_quantlist__16c1_s_p1_0[] = {
  122840. 1,
  122841. 0,
  122842. 2,
  122843. };
  122844. static long _vq_lengthlist__16c1_s_p1_0[] = {
  122845. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  122846. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122850. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  122851. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122855. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  122856. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  122891. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  122892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  122896. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  122897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  122901. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  122902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122936. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  122937. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122941. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  122942. 0, 0, 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  122943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122946. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  122947. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  122948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123255. 0,
  123256. };
  123257. static float _vq_quantthresh__16c1_s_p1_0[] = {
  123258. -0.5, 0.5,
  123259. };
  123260. static long _vq_quantmap__16c1_s_p1_0[] = {
  123261. 1, 0, 2,
  123262. };
  123263. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  123264. _vq_quantthresh__16c1_s_p1_0,
  123265. _vq_quantmap__16c1_s_p1_0,
  123266. 3,
  123267. 3
  123268. };
  123269. static static_codebook _16c1_s_p1_0 = {
  123270. 8, 6561,
  123271. _vq_lengthlist__16c1_s_p1_0,
  123272. 1, -535822336, 1611661312, 2, 0,
  123273. _vq_quantlist__16c1_s_p1_0,
  123274. NULL,
  123275. &_vq_auxt__16c1_s_p1_0,
  123276. NULL,
  123277. 0
  123278. };
  123279. static long _vq_quantlist__16c1_s_p2_0[] = {
  123280. 2,
  123281. 1,
  123282. 3,
  123283. 0,
  123284. 4,
  123285. };
  123286. static long _vq_lengthlist__16c1_s_p2_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,
  123327. };
  123328. static float _vq_quantthresh__16c1_s_p2_0[] = {
  123329. -1.5, -0.5, 0.5, 1.5,
  123330. };
  123331. static long _vq_quantmap__16c1_s_p2_0[] = {
  123332. 3, 1, 0, 2, 4,
  123333. };
  123334. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  123335. _vq_quantthresh__16c1_s_p2_0,
  123336. _vq_quantmap__16c1_s_p2_0,
  123337. 5,
  123338. 5
  123339. };
  123340. static static_codebook _16c1_s_p2_0 = {
  123341. 4, 625,
  123342. _vq_lengthlist__16c1_s_p2_0,
  123343. 1, -533725184, 1611661312, 3, 0,
  123344. _vq_quantlist__16c1_s_p2_0,
  123345. NULL,
  123346. &_vq_auxt__16c1_s_p2_0,
  123347. NULL,
  123348. 0
  123349. };
  123350. static long _vq_quantlist__16c1_s_p3_0[] = {
  123351. 2,
  123352. 1,
  123353. 3,
  123354. 0,
  123355. 4,
  123356. };
  123357. static long _vq_lengthlist__16c1_s_p3_0[] = {
  123358. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  123360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123361. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  123363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123364. 0, 0, 0, 0, 6, 7, 7, 9, 9, 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,
  123398. };
  123399. static float _vq_quantthresh__16c1_s_p3_0[] = {
  123400. -1.5, -0.5, 0.5, 1.5,
  123401. };
  123402. static long _vq_quantmap__16c1_s_p3_0[] = {
  123403. 3, 1, 0, 2, 4,
  123404. };
  123405. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  123406. _vq_quantthresh__16c1_s_p3_0,
  123407. _vq_quantmap__16c1_s_p3_0,
  123408. 5,
  123409. 5
  123410. };
  123411. static static_codebook _16c1_s_p3_0 = {
  123412. 4, 625,
  123413. _vq_lengthlist__16c1_s_p3_0,
  123414. 1, -533725184, 1611661312, 3, 0,
  123415. _vq_quantlist__16c1_s_p3_0,
  123416. NULL,
  123417. &_vq_auxt__16c1_s_p3_0,
  123418. NULL,
  123419. 0
  123420. };
  123421. static long _vq_quantlist__16c1_s_p4_0[] = {
  123422. 4,
  123423. 3,
  123424. 5,
  123425. 2,
  123426. 6,
  123427. 1,
  123428. 7,
  123429. 0,
  123430. 8,
  123431. };
  123432. static long _vq_lengthlist__16c1_s_p4_0[] = {
  123433. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  123434. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  123435. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  123436. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  123437. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123438. 0,
  123439. };
  123440. static float _vq_quantthresh__16c1_s_p4_0[] = {
  123441. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123442. };
  123443. static long _vq_quantmap__16c1_s_p4_0[] = {
  123444. 7, 5, 3, 1, 0, 2, 4, 6,
  123445. 8,
  123446. };
  123447. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  123448. _vq_quantthresh__16c1_s_p4_0,
  123449. _vq_quantmap__16c1_s_p4_0,
  123450. 9,
  123451. 9
  123452. };
  123453. static static_codebook _16c1_s_p4_0 = {
  123454. 2, 81,
  123455. _vq_lengthlist__16c1_s_p4_0,
  123456. 1, -531628032, 1611661312, 4, 0,
  123457. _vq_quantlist__16c1_s_p4_0,
  123458. NULL,
  123459. &_vq_auxt__16c1_s_p4_0,
  123460. NULL,
  123461. 0
  123462. };
  123463. static long _vq_quantlist__16c1_s_p5_0[] = {
  123464. 4,
  123465. 3,
  123466. 5,
  123467. 2,
  123468. 6,
  123469. 1,
  123470. 7,
  123471. 0,
  123472. 8,
  123473. };
  123474. static long _vq_lengthlist__16c1_s_p5_0[] = {
  123475. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  123476. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  123477. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  123478. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  123479. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  123480. 10,
  123481. };
  123482. static float _vq_quantthresh__16c1_s_p5_0[] = {
  123483. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123484. };
  123485. static long _vq_quantmap__16c1_s_p5_0[] = {
  123486. 7, 5, 3, 1, 0, 2, 4, 6,
  123487. 8,
  123488. };
  123489. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  123490. _vq_quantthresh__16c1_s_p5_0,
  123491. _vq_quantmap__16c1_s_p5_0,
  123492. 9,
  123493. 9
  123494. };
  123495. static static_codebook _16c1_s_p5_0 = {
  123496. 2, 81,
  123497. _vq_lengthlist__16c1_s_p5_0,
  123498. 1, -531628032, 1611661312, 4, 0,
  123499. _vq_quantlist__16c1_s_p5_0,
  123500. NULL,
  123501. &_vq_auxt__16c1_s_p5_0,
  123502. NULL,
  123503. 0
  123504. };
  123505. static long _vq_quantlist__16c1_s_p6_0[] = {
  123506. 8,
  123507. 7,
  123508. 9,
  123509. 6,
  123510. 10,
  123511. 5,
  123512. 11,
  123513. 4,
  123514. 12,
  123515. 3,
  123516. 13,
  123517. 2,
  123518. 14,
  123519. 1,
  123520. 15,
  123521. 0,
  123522. 16,
  123523. };
  123524. static long _vq_lengthlist__16c1_s_p6_0[] = {
  123525. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  123526. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  123527. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  123528. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  123529. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  123530. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  123531. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  123532. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  123533. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  123534. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  123535. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  123536. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  123537. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  123538. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  123539. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  123540. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  123541. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  123542. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  123543. 14,
  123544. };
  123545. static float _vq_quantthresh__16c1_s_p6_0[] = {
  123546. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123547. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123548. };
  123549. static long _vq_quantmap__16c1_s_p6_0[] = {
  123550. 15, 13, 11, 9, 7, 5, 3, 1,
  123551. 0, 2, 4, 6, 8, 10, 12, 14,
  123552. 16,
  123553. };
  123554. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  123555. _vq_quantthresh__16c1_s_p6_0,
  123556. _vq_quantmap__16c1_s_p6_0,
  123557. 17,
  123558. 17
  123559. };
  123560. static static_codebook _16c1_s_p6_0 = {
  123561. 2, 289,
  123562. _vq_lengthlist__16c1_s_p6_0,
  123563. 1, -529530880, 1611661312, 5, 0,
  123564. _vq_quantlist__16c1_s_p6_0,
  123565. NULL,
  123566. &_vq_auxt__16c1_s_p6_0,
  123567. NULL,
  123568. 0
  123569. };
  123570. static long _vq_quantlist__16c1_s_p7_0[] = {
  123571. 1,
  123572. 0,
  123573. 2,
  123574. };
  123575. static long _vq_lengthlist__16c1_s_p7_0[] = {
  123576. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  123577. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  123578. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  123579. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  123580. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  123581. 11,
  123582. };
  123583. static float _vq_quantthresh__16c1_s_p7_0[] = {
  123584. -5.5, 5.5,
  123585. };
  123586. static long _vq_quantmap__16c1_s_p7_0[] = {
  123587. 1, 0, 2,
  123588. };
  123589. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  123590. _vq_quantthresh__16c1_s_p7_0,
  123591. _vq_quantmap__16c1_s_p7_0,
  123592. 3,
  123593. 3
  123594. };
  123595. static static_codebook _16c1_s_p7_0 = {
  123596. 4, 81,
  123597. _vq_lengthlist__16c1_s_p7_0,
  123598. 1, -529137664, 1618345984, 2, 0,
  123599. _vq_quantlist__16c1_s_p7_0,
  123600. NULL,
  123601. &_vq_auxt__16c1_s_p7_0,
  123602. NULL,
  123603. 0
  123604. };
  123605. static long _vq_quantlist__16c1_s_p7_1[] = {
  123606. 5,
  123607. 4,
  123608. 6,
  123609. 3,
  123610. 7,
  123611. 2,
  123612. 8,
  123613. 1,
  123614. 9,
  123615. 0,
  123616. 10,
  123617. };
  123618. static long _vq_lengthlist__16c1_s_p7_1[] = {
  123619. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  123620. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  123621. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  123622. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  123623. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  123624. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  123625. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  123626. 10,10,10, 8, 8, 8, 8, 9, 9,
  123627. };
  123628. static float _vq_quantthresh__16c1_s_p7_1[] = {
  123629. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123630. 3.5, 4.5,
  123631. };
  123632. static long _vq_quantmap__16c1_s_p7_1[] = {
  123633. 9, 7, 5, 3, 1, 0, 2, 4,
  123634. 6, 8, 10,
  123635. };
  123636. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  123637. _vq_quantthresh__16c1_s_p7_1,
  123638. _vq_quantmap__16c1_s_p7_1,
  123639. 11,
  123640. 11
  123641. };
  123642. static static_codebook _16c1_s_p7_1 = {
  123643. 2, 121,
  123644. _vq_lengthlist__16c1_s_p7_1,
  123645. 1, -531365888, 1611661312, 4, 0,
  123646. _vq_quantlist__16c1_s_p7_1,
  123647. NULL,
  123648. &_vq_auxt__16c1_s_p7_1,
  123649. NULL,
  123650. 0
  123651. };
  123652. static long _vq_quantlist__16c1_s_p8_0[] = {
  123653. 6,
  123654. 5,
  123655. 7,
  123656. 4,
  123657. 8,
  123658. 3,
  123659. 9,
  123660. 2,
  123661. 10,
  123662. 1,
  123663. 11,
  123664. 0,
  123665. 12,
  123666. };
  123667. static long _vq_lengthlist__16c1_s_p8_0[] = {
  123668. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  123669. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  123670. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  123671. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  123672. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  123673. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  123674. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  123675. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  123676. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  123677. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  123678. 0,12,12,12,12,13,13,14,15,
  123679. };
  123680. static float _vq_quantthresh__16c1_s_p8_0[] = {
  123681. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  123682. 12.5, 17.5, 22.5, 27.5,
  123683. };
  123684. static long _vq_quantmap__16c1_s_p8_0[] = {
  123685. 11, 9, 7, 5, 3, 1, 0, 2,
  123686. 4, 6, 8, 10, 12,
  123687. };
  123688. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  123689. _vq_quantthresh__16c1_s_p8_0,
  123690. _vq_quantmap__16c1_s_p8_0,
  123691. 13,
  123692. 13
  123693. };
  123694. static static_codebook _16c1_s_p8_0 = {
  123695. 2, 169,
  123696. _vq_lengthlist__16c1_s_p8_0,
  123697. 1, -526516224, 1616117760, 4, 0,
  123698. _vq_quantlist__16c1_s_p8_0,
  123699. NULL,
  123700. &_vq_auxt__16c1_s_p8_0,
  123701. NULL,
  123702. 0
  123703. };
  123704. static long _vq_quantlist__16c1_s_p8_1[] = {
  123705. 2,
  123706. 1,
  123707. 3,
  123708. 0,
  123709. 4,
  123710. };
  123711. static long _vq_lengthlist__16c1_s_p8_1[] = {
  123712. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  123713. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  123714. };
  123715. static float _vq_quantthresh__16c1_s_p8_1[] = {
  123716. -1.5, -0.5, 0.5, 1.5,
  123717. };
  123718. static long _vq_quantmap__16c1_s_p8_1[] = {
  123719. 3, 1, 0, 2, 4,
  123720. };
  123721. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  123722. _vq_quantthresh__16c1_s_p8_1,
  123723. _vq_quantmap__16c1_s_p8_1,
  123724. 5,
  123725. 5
  123726. };
  123727. static static_codebook _16c1_s_p8_1 = {
  123728. 2, 25,
  123729. _vq_lengthlist__16c1_s_p8_1,
  123730. 1, -533725184, 1611661312, 3, 0,
  123731. _vq_quantlist__16c1_s_p8_1,
  123732. NULL,
  123733. &_vq_auxt__16c1_s_p8_1,
  123734. NULL,
  123735. 0
  123736. };
  123737. static long _vq_quantlist__16c1_s_p9_0[] = {
  123738. 6,
  123739. 5,
  123740. 7,
  123741. 4,
  123742. 8,
  123743. 3,
  123744. 9,
  123745. 2,
  123746. 10,
  123747. 1,
  123748. 11,
  123749. 0,
  123750. 12,
  123751. };
  123752. static long _vq_lengthlist__16c1_s_p9_0[] = {
  123753. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  123754. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  123755. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  123756. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  123757. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  123758. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123759. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123760. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123761. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123762. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123763. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123764. };
  123765. static float _vq_quantthresh__16c1_s_p9_0[] = {
  123766. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  123767. 787.5, 1102.5, 1417.5, 1732.5,
  123768. };
  123769. static long _vq_quantmap__16c1_s_p9_0[] = {
  123770. 11, 9, 7, 5, 3, 1, 0, 2,
  123771. 4, 6, 8, 10, 12,
  123772. };
  123773. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  123774. _vq_quantthresh__16c1_s_p9_0,
  123775. _vq_quantmap__16c1_s_p9_0,
  123776. 13,
  123777. 13
  123778. };
  123779. static static_codebook _16c1_s_p9_0 = {
  123780. 2, 169,
  123781. _vq_lengthlist__16c1_s_p9_0,
  123782. 1, -513964032, 1628680192, 4, 0,
  123783. _vq_quantlist__16c1_s_p9_0,
  123784. NULL,
  123785. &_vq_auxt__16c1_s_p9_0,
  123786. NULL,
  123787. 0
  123788. };
  123789. static long _vq_quantlist__16c1_s_p9_1[] = {
  123790. 7,
  123791. 6,
  123792. 8,
  123793. 5,
  123794. 9,
  123795. 4,
  123796. 10,
  123797. 3,
  123798. 11,
  123799. 2,
  123800. 12,
  123801. 1,
  123802. 13,
  123803. 0,
  123804. 14,
  123805. };
  123806. static long _vq_lengthlist__16c1_s_p9_1[] = {
  123807. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  123808. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  123809. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  123810. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  123811. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  123812. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  123813. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  123814. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  123815. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  123816. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  123817. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  123818. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  123819. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  123820. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  123821. 13,
  123822. };
  123823. static float _vq_quantthresh__16c1_s_p9_1[] = {
  123824. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  123825. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  123826. };
  123827. static long _vq_quantmap__16c1_s_p9_1[] = {
  123828. 13, 11, 9, 7, 5, 3, 1, 0,
  123829. 2, 4, 6, 8, 10, 12, 14,
  123830. };
  123831. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  123832. _vq_quantthresh__16c1_s_p9_1,
  123833. _vq_quantmap__16c1_s_p9_1,
  123834. 15,
  123835. 15
  123836. };
  123837. static static_codebook _16c1_s_p9_1 = {
  123838. 2, 225,
  123839. _vq_lengthlist__16c1_s_p9_1,
  123840. 1, -520986624, 1620377600, 4, 0,
  123841. _vq_quantlist__16c1_s_p9_1,
  123842. NULL,
  123843. &_vq_auxt__16c1_s_p9_1,
  123844. NULL,
  123845. 0
  123846. };
  123847. static long _vq_quantlist__16c1_s_p9_2[] = {
  123848. 10,
  123849. 9,
  123850. 11,
  123851. 8,
  123852. 12,
  123853. 7,
  123854. 13,
  123855. 6,
  123856. 14,
  123857. 5,
  123858. 15,
  123859. 4,
  123860. 16,
  123861. 3,
  123862. 17,
  123863. 2,
  123864. 18,
  123865. 1,
  123866. 19,
  123867. 0,
  123868. 20,
  123869. };
  123870. static long _vq_lengthlist__16c1_s_p9_2[] = {
  123871. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  123872. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  123873. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  123874. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  123875. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  123876. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  123877. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  123878. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  123879. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  123880. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  123881. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  123882. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  123883. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  123884. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  123885. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  123886. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  123887. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  123888. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  123889. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  123890. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  123891. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  123892. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  123893. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  123894. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  123895. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  123896. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  123897. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  123898. 11,11,11,11,12,11,11,12,11,
  123899. };
  123900. static float _vq_quantthresh__16c1_s_p9_2[] = {
  123901. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  123902. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  123903. 6.5, 7.5, 8.5, 9.5,
  123904. };
  123905. static long _vq_quantmap__16c1_s_p9_2[] = {
  123906. 19, 17, 15, 13, 11, 9, 7, 5,
  123907. 3, 1, 0, 2, 4, 6, 8, 10,
  123908. 12, 14, 16, 18, 20,
  123909. };
  123910. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  123911. _vq_quantthresh__16c1_s_p9_2,
  123912. _vq_quantmap__16c1_s_p9_2,
  123913. 21,
  123914. 21
  123915. };
  123916. static static_codebook _16c1_s_p9_2 = {
  123917. 2, 441,
  123918. _vq_lengthlist__16c1_s_p9_2,
  123919. 1, -529268736, 1611661312, 5, 0,
  123920. _vq_quantlist__16c1_s_p9_2,
  123921. NULL,
  123922. &_vq_auxt__16c1_s_p9_2,
  123923. NULL,
  123924. 0
  123925. };
  123926. static long _huff_lengthlist__16c1_s_short[] = {
  123927. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  123928. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  123929. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  123930. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  123931. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  123932. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  123933. 9, 9,10,13,
  123934. };
  123935. static static_codebook _huff_book__16c1_s_short = {
  123936. 2, 100,
  123937. _huff_lengthlist__16c1_s_short,
  123938. 0, 0, 0, 0, 0,
  123939. NULL,
  123940. NULL,
  123941. NULL,
  123942. NULL,
  123943. 0
  123944. };
  123945. static long _huff_lengthlist__16c2_s_long[] = {
  123946. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  123947. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  123948. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  123949. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  123950. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  123951. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  123952. 14,14,16,18,
  123953. };
  123954. static static_codebook _huff_book__16c2_s_long = {
  123955. 2, 100,
  123956. _huff_lengthlist__16c2_s_long,
  123957. 0, 0, 0, 0, 0,
  123958. NULL,
  123959. NULL,
  123960. NULL,
  123961. NULL,
  123962. 0
  123963. };
  123964. static long _vq_quantlist__16c2_s_p1_0[] = {
  123965. 1,
  123966. 0,
  123967. 2,
  123968. };
  123969. static long _vq_lengthlist__16c2_s_p1_0[] = {
  123970. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  123971. 0, 0, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123975. 0,
  123976. };
  123977. static float _vq_quantthresh__16c2_s_p1_0[] = {
  123978. -0.5, 0.5,
  123979. };
  123980. static long _vq_quantmap__16c2_s_p1_0[] = {
  123981. 1, 0, 2,
  123982. };
  123983. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  123984. _vq_quantthresh__16c2_s_p1_0,
  123985. _vq_quantmap__16c2_s_p1_0,
  123986. 3,
  123987. 3
  123988. };
  123989. static static_codebook _16c2_s_p1_0 = {
  123990. 4, 81,
  123991. _vq_lengthlist__16c2_s_p1_0,
  123992. 1, -535822336, 1611661312, 2, 0,
  123993. _vq_quantlist__16c2_s_p1_0,
  123994. NULL,
  123995. &_vq_auxt__16c2_s_p1_0,
  123996. NULL,
  123997. 0
  123998. };
  123999. static long _vq_quantlist__16c2_s_p2_0[] = {
  124000. 2,
  124001. 1,
  124002. 3,
  124003. 0,
  124004. 4,
  124005. };
  124006. static long _vq_lengthlist__16c2_s_p2_0[] = {
  124007. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  124008. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  124009. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  124010. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  124011. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  124012. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  124013. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  124014. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 0, 0, 0,
  124015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124019. 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8,11,11, 0, 0, 0,
  124020. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  124021. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  124022. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  124023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124027. 0, 0, 0, 0, 0, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  124028. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  124029. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  124030. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124035. 0, 0, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  124036. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  124037. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  124038. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8,
  124043. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  124044. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  124045. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  124046. 13,
  124047. };
  124048. static float _vq_quantthresh__16c2_s_p2_0[] = {
  124049. -1.5, -0.5, 0.5, 1.5,
  124050. };
  124051. static long _vq_quantmap__16c2_s_p2_0[] = {
  124052. 3, 1, 0, 2, 4,
  124053. };
  124054. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  124055. _vq_quantthresh__16c2_s_p2_0,
  124056. _vq_quantmap__16c2_s_p2_0,
  124057. 5,
  124058. 5
  124059. };
  124060. static static_codebook _16c2_s_p2_0 = {
  124061. 4, 625,
  124062. _vq_lengthlist__16c2_s_p2_0,
  124063. 1, -533725184, 1611661312, 3, 0,
  124064. _vq_quantlist__16c2_s_p2_0,
  124065. NULL,
  124066. &_vq_auxt__16c2_s_p2_0,
  124067. NULL,
  124068. 0
  124069. };
  124070. static long _vq_quantlist__16c2_s_p3_0[] = {
  124071. 4,
  124072. 3,
  124073. 5,
  124074. 2,
  124075. 6,
  124076. 1,
  124077. 7,
  124078. 0,
  124079. 8,
  124080. };
  124081. static long _vq_lengthlist__16c2_s_p3_0[] = {
  124082. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  124083. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  124084. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  124085. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  124086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124087. 0,
  124088. };
  124089. static float _vq_quantthresh__16c2_s_p3_0[] = {
  124090. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124091. };
  124092. static long _vq_quantmap__16c2_s_p3_0[] = {
  124093. 7, 5, 3, 1, 0, 2, 4, 6,
  124094. 8,
  124095. };
  124096. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  124097. _vq_quantthresh__16c2_s_p3_0,
  124098. _vq_quantmap__16c2_s_p3_0,
  124099. 9,
  124100. 9
  124101. };
  124102. static static_codebook _16c2_s_p3_0 = {
  124103. 2, 81,
  124104. _vq_lengthlist__16c2_s_p3_0,
  124105. 1, -531628032, 1611661312, 4, 0,
  124106. _vq_quantlist__16c2_s_p3_0,
  124107. NULL,
  124108. &_vq_auxt__16c2_s_p3_0,
  124109. NULL,
  124110. 0
  124111. };
  124112. static long _vq_quantlist__16c2_s_p4_0[] = {
  124113. 8,
  124114. 7,
  124115. 9,
  124116. 6,
  124117. 10,
  124118. 5,
  124119. 11,
  124120. 4,
  124121. 12,
  124122. 3,
  124123. 13,
  124124. 2,
  124125. 14,
  124126. 1,
  124127. 15,
  124128. 0,
  124129. 16,
  124130. };
  124131. static long _vq_lengthlist__16c2_s_p4_0[] = {
  124132. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  124133. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  124134. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  124135. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  124136. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  124137. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  124138. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  124139. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  124140. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  124141. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  124142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124150. 0,
  124151. };
  124152. static float _vq_quantthresh__16c2_s_p4_0[] = {
  124153. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124154. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124155. };
  124156. static long _vq_quantmap__16c2_s_p4_0[] = {
  124157. 15, 13, 11, 9, 7, 5, 3, 1,
  124158. 0, 2, 4, 6, 8, 10, 12, 14,
  124159. 16,
  124160. };
  124161. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  124162. _vq_quantthresh__16c2_s_p4_0,
  124163. _vq_quantmap__16c2_s_p4_0,
  124164. 17,
  124165. 17
  124166. };
  124167. static static_codebook _16c2_s_p4_0 = {
  124168. 2, 289,
  124169. _vq_lengthlist__16c2_s_p4_0,
  124170. 1, -529530880, 1611661312, 5, 0,
  124171. _vq_quantlist__16c2_s_p4_0,
  124172. NULL,
  124173. &_vq_auxt__16c2_s_p4_0,
  124174. NULL,
  124175. 0
  124176. };
  124177. static long _vq_quantlist__16c2_s_p5_0[] = {
  124178. 1,
  124179. 0,
  124180. 2,
  124181. };
  124182. static long _vq_lengthlist__16c2_s_p5_0[] = {
  124183. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  124184. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  124185. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  124186. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  124187. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  124188. 12,
  124189. };
  124190. static float _vq_quantthresh__16c2_s_p5_0[] = {
  124191. -5.5, 5.5,
  124192. };
  124193. static long _vq_quantmap__16c2_s_p5_0[] = {
  124194. 1, 0, 2,
  124195. };
  124196. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  124197. _vq_quantthresh__16c2_s_p5_0,
  124198. _vq_quantmap__16c2_s_p5_0,
  124199. 3,
  124200. 3
  124201. };
  124202. static static_codebook _16c2_s_p5_0 = {
  124203. 4, 81,
  124204. _vq_lengthlist__16c2_s_p5_0,
  124205. 1, -529137664, 1618345984, 2, 0,
  124206. _vq_quantlist__16c2_s_p5_0,
  124207. NULL,
  124208. &_vq_auxt__16c2_s_p5_0,
  124209. NULL,
  124210. 0
  124211. };
  124212. static long _vq_quantlist__16c2_s_p5_1[] = {
  124213. 5,
  124214. 4,
  124215. 6,
  124216. 3,
  124217. 7,
  124218. 2,
  124219. 8,
  124220. 1,
  124221. 9,
  124222. 0,
  124223. 10,
  124224. };
  124225. static long _vq_lengthlist__16c2_s_p5_1[] = {
  124226. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  124227. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  124228. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  124229. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  124230. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  124231. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  124232. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  124233. 11,11,11, 7, 7, 8, 8, 8, 8,
  124234. };
  124235. static float _vq_quantthresh__16c2_s_p5_1[] = {
  124236. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124237. 3.5, 4.5,
  124238. };
  124239. static long _vq_quantmap__16c2_s_p5_1[] = {
  124240. 9, 7, 5, 3, 1, 0, 2, 4,
  124241. 6, 8, 10,
  124242. };
  124243. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  124244. _vq_quantthresh__16c2_s_p5_1,
  124245. _vq_quantmap__16c2_s_p5_1,
  124246. 11,
  124247. 11
  124248. };
  124249. static static_codebook _16c2_s_p5_1 = {
  124250. 2, 121,
  124251. _vq_lengthlist__16c2_s_p5_1,
  124252. 1, -531365888, 1611661312, 4, 0,
  124253. _vq_quantlist__16c2_s_p5_1,
  124254. NULL,
  124255. &_vq_auxt__16c2_s_p5_1,
  124256. NULL,
  124257. 0
  124258. };
  124259. static long _vq_quantlist__16c2_s_p6_0[] = {
  124260. 6,
  124261. 5,
  124262. 7,
  124263. 4,
  124264. 8,
  124265. 3,
  124266. 9,
  124267. 2,
  124268. 10,
  124269. 1,
  124270. 11,
  124271. 0,
  124272. 12,
  124273. };
  124274. static long _vq_lengthlist__16c2_s_p6_0[] = {
  124275. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  124276. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  124277. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  124278. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  124279. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  124280. 12, 8, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  124281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124285. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124286. };
  124287. static float _vq_quantthresh__16c2_s_p6_0[] = {
  124288. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124289. 12.5, 17.5, 22.5, 27.5,
  124290. };
  124291. static long _vq_quantmap__16c2_s_p6_0[] = {
  124292. 11, 9, 7, 5, 3, 1, 0, 2,
  124293. 4, 6, 8, 10, 12,
  124294. };
  124295. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  124296. _vq_quantthresh__16c2_s_p6_0,
  124297. _vq_quantmap__16c2_s_p6_0,
  124298. 13,
  124299. 13
  124300. };
  124301. static static_codebook _16c2_s_p6_0 = {
  124302. 2, 169,
  124303. _vq_lengthlist__16c2_s_p6_0,
  124304. 1, -526516224, 1616117760, 4, 0,
  124305. _vq_quantlist__16c2_s_p6_0,
  124306. NULL,
  124307. &_vq_auxt__16c2_s_p6_0,
  124308. NULL,
  124309. 0
  124310. };
  124311. static long _vq_quantlist__16c2_s_p6_1[] = {
  124312. 2,
  124313. 1,
  124314. 3,
  124315. 0,
  124316. 4,
  124317. };
  124318. static long _vq_lengthlist__16c2_s_p6_1[] = {
  124319. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  124320. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  124321. };
  124322. static float _vq_quantthresh__16c2_s_p6_1[] = {
  124323. -1.5, -0.5, 0.5, 1.5,
  124324. };
  124325. static long _vq_quantmap__16c2_s_p6_1[] = {
  124326. 3, 1, 0, 2, 4,
  124327. };
  124328. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  124329. _vq_quantthresh__16c2_s_p6_1,
  124330. _vq_quantmap__16c2_s_p6_1,
  124331. 5,
  124332. 5
  124333. };
  124334. static static_codebook _16c2_s_p6_1 = {
  124335. 2, 25,
  124336. _vq_lengthlist__16c2_s_p6_1,
  124337. 1, -533725184, 1611661312, 3, 0,
  124338. _vq_quantlist__16c2_s_p6_1,
  124339. NULL,
  124340. &_vq_auxt__16c2_s_p6_1,
  124341. NULL,
  124342. 0
  124343. };
  124344. static long _vq_quantlist__16c2_s_p7_0[] = {
  124345. 6,
  124346. 5,
  124347. 7,
  124348. 4,
  124349. 8,
  124350. 3,
  124351. 9,
  124352. 2,
  124353. 10,
  124354. 1,
  124355. 11,
  124356. 0,
  124357. 12,
  124358. };
  124359. static long _vq_lengthlist__16c2_s_p7_0[] = {
  124360. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  124361. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  124362. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  124363. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  124364. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  124365. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  124366. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  124367. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  124368. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  124369. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  124370. 18,13,14,13,13,14,13,15,14,
  124371. };
  124372. static float _vq_quantthresh__16c2_s_p7_0[] = {
  124373. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  124374. 27.5, 38.5, 49.5, 60.5,
  124375. };
  124376. static long _vq_quantmap__16c2_s_p7_0[] = {
  124377. 11, 9, 7, 5, 3, 1, 0, 2,
  124378. 4, 6, 8, 10, 12,
  124379. };
  124380. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  124381. _vq_quantthresh__16c2_s_p7_0,
  124382. _vq_quantmap__16c2_s_p7_0,
  124383. 13,
  124384. 13
  124385. };
  124386. static static_codebook _16c2_s_p7_0 = {
  124387. 2, 169,
  124388. _vq_lengthlist__16c2_s_p7_0,
  124389. 1, -523206656, 1618345984, 4, 0,
  124390. _vq_quantlist__16c2_s_p7_0,
  124391. NULL,
  124392. &_vq_auxt__16c2_s_p7_0,
  124393. NULL,
  124394. 0
  124395. };
  124396. static long _vq_quantlist__16c2_s_p7_1[] = {
  124397. 5,
  124398. 4,
  124399. 6,
  124400. 3,
  124401. 7,
  124402. 2,
  124403. 8,
  124404. 1,
  124405. 9,
  124406. 0,
  124407. 10,
  124408. };
  124409. static long _vq_lengthlist__16c2_s_p7_1[] = {
  124410. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  124411. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  124412. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  124413. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  124414. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  124415. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  124416. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  124417. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  124418. };
  124419. static float _vq_quantthresh__16c2_s_p7_1[] = {
  124420. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124421. 3.5, 4.5,
  124422. };
  124423. static long _vq_quantmap__16c2_s_p7_1[] = {
  124424. 9, 7, 5, 3, 1, 0, 2, 4,
  124425. 6, 8, 10,
  124426. };
  124427. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  124428. _vq_quantthresh__16c2_s_p7_1,
  124429. _vq_quantmap__16c2_s_p7_1,
  124430. 11,
  124431. 11
  124432. };
  124433. static static_codebook _16c2_s_p7_1 = {
  124434. 2, 121,
  124435. _vq_lengthlist__16c2_s_p7_1,
  124436. 1, -531365888, 1611661312, 4, 0,
  124437. _vq_quantlist__16c2_s_p7_1,
  124438. NULL,
  124439. &_vq_auxt__16c2_s_p7_1,
  124440. NULL,
  124441. 0
  124442. };
  124443. static long _vq_quantlist__16c2_s_p8_0[] = {
  124444. 7,
  124445. 6,
  124446. 8,
  124447. 5,
  124448. 9,
  124449. 4,
  124450. 10,
  124451. 3,
  124452. 11,
  124453. 2,
  124454. 12,
  124455. 1,
  124456. 13,
  124457. 0,
  124458. 14,
  124459. };
  124460. static long _vq_lengthlist__16c2_s_p8_0[] = {
  124461. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  124462. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  124463. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  124464. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  124465. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  124466. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  124467. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  124468. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  124469. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  124470. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  124471. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  124472. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  124473. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  124474. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  124475. 13,
  124476. };
  124477. static float _vq_quantthresh__16c2_s_p8_0[] = {
  124478. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  124479. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  124480. };
  124481. static long _vq_quantmap__16c2_s_p8_0[] = {
  124482. 13, 11, 9, 7, 5, 3, 1, 0,
  124483. 2, 4, 6, 8, 10, 12, 14,
  124484. };
  124485. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  124486. _vq_quantthresh__16c2_s_p8_0,
  124487. _vq_quantmap__16c2_s_p8_0,
  124488. 15,
  124489. 15
  124490. };
  124491. static static_codebook _16c2_s_p8_0 = {
  124492. 2, 225,
  124493. _vq_lengthlist__16c2_s_p8_0,
  124494. 1, -520986624, 1620377600, 4, 0,
  124495. _vq_quantlist__16c2_s_p8_0,
  124496. NULL,
  124497. &_vq_auxt__16c2_s_p8_0,
  124498. NULL,
  124499. 0
  124500. };
  124501. static long _vq_quantlist__16c2_s_p8_1[] = {
  124502. 10,
  124503. 9,
  124504. 11,
  124505. 8,
  124506. 12,
  124507. 7,
  124508. 13,
  124509. 6,
  124510. 14,
  124511. 5,
  124512. 15,
  124513. 4,
  124514. 16,
  124515. 3,
  124516. 17,
  124517. 2,
  124518. 18,
  124519. 1,
  124520. 19,
  124521. 0,
  124522. 20,
  124523. };
  124524. static long _vq_lengthlist__16c2_s_p8_1[] = {
  124525. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  124526. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  124527. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  124528. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  124529. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  124530. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  124531. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  124532. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  124533. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  124534. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  124535. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  124536. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  124537. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  124538. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  124539. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  124540. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  124541. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  124542. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  124543. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  124544. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  124545. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  124546. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  124547. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  124548. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  124549. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  124550. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  124551. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  124552. 10,11,10,10,10,10,10,10,10,
  124553. };
  124554. static float _vq_quantthresh__16c2_s_p8_1[] = {
  124555. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  124556. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  124557. 6.5, 7.5, 8.5, 9.5,
  124558. };
  124559. static long _vq_quantmap__16c2_s_p8_1[] = {
  124560. 19, 17, 15, 13, 11, 9, 7, 5,
  124561. 3, 1, 0, 2, 4, 6, 8, 10,
  124562. 12, 14, 16, 18, 20,
  124563. };
  124564. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  124565. _vq_quantthresh__16c2_s_p8_1,
  124566. _vq_quantmap__16c2_s_p8_1,
  124567. 21,
  124568. 21
  124569. };
  124570. static static_codebook _16c2_s_p8_1 = {
  124571. 2, 441,
  124572. _vq_lengthlist__16c2_s_p8_1,
  124573. 1, -529268736, 1611661312, 5, 0,
  124574. _vq_quantlist__16c2_s_p8_1,
  124575. NULL,
  124576. &_vq_auxt__16c2_s_p8_1,
  124577. NULL,
  124578. 0
  124579. };
  124580. static long _vq_quantlist__16c2_s_p9_0[] = {
  124581. 6,
  124582. 5,
  124583. 7,
  124584. 4,
  124585. 8,
  124586. 3,
  124587. 9,
  124588. 2,
  124589. 10,
  124590. 1,
  124591. 11,
  124592. 0,
  124593. 12,
  124594. };
  124595. static long _vq_lengthlist__16c2_s_p9_0[] = {
  124596. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124597. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124598. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124599. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124600. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124601. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124602. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124603. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124604. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124605. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124606. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124607. };
  124608. static float _vq_quantthresh__16c2_s_p9_0[] = {
  124609. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  124610. 2327.5, 3258.5, 4189.5, 5120.5,
  124611. };
  124612. static long _vq_quantmap__16c2_s_p9_0[] = {
  124613. 11, 9, 7, 5, 3, 1, 0, 2,
  124614. 4, 6, 8, 10, 12,
  124615. };
  124616. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  124617. _vq_quantthresh__16c2_s_p9_0,
  124618. _vq_quantmap__16c2_s_p9_0,
  124619. 13,
  124620. 13
  124621. };
  124622. static static_codebook _16c2_s_p9_0 = {
  124623. 2, 169,
  124624. _vq_lengthlist__16c2_s_p9_0,
  124625. 1, -510275072, 1631393792, 4, 0,
  124626. _vq_quantlist__16c2_s_p9_0,
  124627. NULL,
  124628. &_vq_auxt__16c2_s_p9_0,
  124629. NULL,
  124630. 0
  124631. };
  124632. static long _vq_quantlist__16c2_s_p9_1[] = {
  124633. 8,
  124634. 7,
  124635. 9,
  124636. 6,
  124637. 10,
  124638. 5,
  124639. 11,
  124640. 4,
  124641. 12,
  124642. 3,
  124643. 13,
  124644. 2,
  124645. 14,
  124646. 1,
  124647. 15,
  124648. 0,
  124649. 16,
  124650. };
  124651. static long _vq_lengthlist__16c2_s_p9_1[] = {
  124652. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  124653. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  124654. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  124655. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  124656. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  124657. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  124658. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  124659. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  124660. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  124661. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  124662. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124663. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124664. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124665. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124666. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124667. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  124668. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  124669. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124670. 10,
  124671. };
  124672. static float _vq_quantthresh__16c2_s_p9_1[] = {
  124673. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  124674. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  124675. };
  124676. static long _vq_quantmap__16c2_s_p9_1[] = {
  124677. 15, 13, 11, 9, 7, 5, 3, 1,
  124678. 0, 2, 4, 6, 8, 10, 12, 14,
  124679. 16,
  124680. };
  124681. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  124682. _vq_quantthresh__16c2_s_p9_1,
  124683. _vq_quantmap__16c2_s_p9_1,
  124684. 17,
  124685. 17
  124686. };
  124687. static static_codebook _16c2_s_p9_1 = {
  124688. 2, 289,
  124689. _vq_lengthlist__16c2_s_p9_1,
  124690. 1, -518488064, 1622704128, 5, 0,
  124691. _vq_quantlist__16c2_s_p9_1,
  124692. NULL,
  124693. &_vq_auxt__16c2_s_p9_1,
  124694. NULL,
  124695. 0
  124696. };
  124697. static long _vq_quantlist__16c2_s_p9_2[] = {
  124698. 13,
  124699. 12,
  124700. 14,
  124701. 11,
  124702. 15,
  124703. 10,
  124704. 16,
  124705. 9,
  124706. 17,
  124707. 8,
  124708. 18,
  124709. 7,
  124710. 19,
  124711. 6,
  124712. 20,
  124713. 5,
  124714. 21,
  124715. 4,
  124716. 22,
  124717. 3,
  124718. 23,
  124719. 2,
  124720. 24,
  124721. 1,
  124722. 25,
  124723. 0,
  124724. 26,
  124725. };
  124726. static long _vq_lengthlist__16c2_s_p9_2[] = {
  124727. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  124728. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  124729. };
  124730. static float _vq_quantthresh__16c2_s_p9_2[] = {
  124731. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  124732. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124733. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  124734. 11.5, 12.5,
  124735. };
  124736. static long _vq_quantmap__16c2_s_p9_2[] = {
  124737. 25, 23, 21, 19, 17, 15, 13, 11,
  124738. 9, 7, 5, 3, 1, 0, 2, 4,
  124739. 6, 8, 10, 12, 14, 16, 18, 20,
  124740. 22, 24, 26,
  124741. };
  124742. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  124743. _vq_quantthresh__16c2_s_p9_2,
  124744. _vq_quantmap__16c2_s_p9_2,
  124745. 27,
  124746. 27
  124747. };
  124748. static static_codebook _16c2_s_p9_2 = {
  124749. 1, 27,
  124750. _vq_lengthlist__16c2_s_p9_2,
  124751. 1, -528875520, 1611661312, 5, 0,
  124752. _vq_quantlist__16c2_s_p9_2,
  124753. NULL,
  124754. &_vq_auxt__16c2_s_p9_2,
  124755. NULL,
  124756. 0
  124757. };
  124758. static long _huff_lengthlist__16c2_s_short[] = {
  124759. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  124760. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  124761. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  124762. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  124763. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  124764. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  124765. 15,12,14,14,
  124766. };
  124767. static static_codebook _huff_book__16c2_s_short = {
  124768. 2, 100,
  124769. _huff_lengthlist__16c2_s_short,
  124770. 0, 0, 0, 0, 0,
  124771. NULL,
  124772. NULL,
  124773. NULL,
  124774. NULL,
  124775. 0
  124776. };
  124777. static long _vq_quantlist__8c0_s_p1_0[] = {
  124778. 1,
  124779. 0,
  124780. 2,
  124781. };
  124782. static long _vq_lengthlist__8c0_s_p1_0[] = {
  124783. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  124784. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124788. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  124789. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124793. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  124794. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  124829. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  124830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  124834. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  124835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9,10, 0, 0,
  124839. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  124840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124874. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  124875. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124879. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  124880. 0, 0, 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 0, 0,
  124881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124884. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  124885. 0, 0, 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 0,
  124886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125193. 0,
  125194. };
  125195. static float _vq_quantthresh__8c0_s_p1_0[] = {
  125196. -0.5, 0.5,
  125197. };
  125198. static long _vq_quantmap__8c0_s_p1_0[] = {
  125199. 1, 0, 2,
  125200. };
  125201. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  125202. _vq_quantthresh__8c0_s_p1_0,
  125203. _vq_quantmap__8c0_s_p1_0,
  125204. 3,
  125205. 3
  125206. };
  125207. static static_codebook _8c0_s_p1_0 = {
  125208. 8, 6561,
  125209. _vq_lengthlist__8c0_s_p1_0,
  125210. 1, -535822336, 1611661312, 2, 0,
  125211. _vq_quantlist__8c0_s_p1_0,
  125212. NULL,
  125213. &_vq_auxt__8c0_s_p1_0,
  125214. NULL,
  125215. 0
  125216. };
  125217. static long _vq_quantlist__8c0_s_p2_0[] = {
  125218. 2,
  125219. 1,
  125220. 3,
  125221. 0,
  125222. 4,
  125223. };
  125224. static long _vq_lengthlist__8c0_s_p2_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,
  125265. };
  125266. static float _vq_quantthresh__8c0_s_p2_0[] = {
  125267. -1.5, -0.5, 0.5, 1.5,
  125268. };
  125269. static long _vq_quantmap__8c0_s_p2_0[] = {
  125270. 3, 1, 0, 2, 4,
  125271. };
  125272. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  125273. _vq_quantthresh__8c0_s_p2_0,
  125274. _vq_quantmap__8c0_s_p2_0,
  125275. 5,
  125276. 5
  125277. };
  125278. static static_codebook _8c0_s_p2_0 = {
  125279. 4, 625,
  125280. _vq_lengthlist__8c0_s_p2_0,
  125281. 1, -533725184, 1611661312, 3, 0,
  125282. _vq_quantlist__8c0_s_p2_0,
  125283. NULL,
  125284. &_vq_auxt__8c0_s_p2_0,
  125285. NULL,
  125286. 0
  125287. };
  125288. static long _vq_quantlist__8c0_s_p3_0[] = {
  125289. 2,
  125290. 1,
  125291. 3,
  125292. 0,
  125293. 4,
  125294. };
  125295. static long _vq_lengthlist__8c0_s_p3_0[] = {
  125296. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  125298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125299. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  125301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125302. 0, 0, 0, 0, 6, 7, 7, 8, 8, 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,
  125336. };
  125337. static float _vq_quantthresh__8c0_s_p3_0[] = {
  125338. -1.5, -0.5, 0.5, 1.5,
  125339. };
  125340. static long _vq_quantmap__8c0_s_p3_0[] = {
  125341. 3, 1, 0, 2, 4,
  125342. };
  125343. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  125344. _vq_quantthresh__8c0_s_p3_0,
  125345. _vq_quantmap__8c0_s_p3_0,
  125346. 5,
  125347. 5
  125348. };
  125349. static static_codebook _8c0_s_p3_0 = {
  125350. 4, 625,
  125351. _vq_lengthlist__8c0_s_p3_0,
  125352. 1, -533725184, 1611661312, 3, 0,
  125353. _vq_quantlist__8c0_s_p3_0,
  125354. NULL,
  125355. &_vq_auxt__8c0_s_p3_0,
  125356. NULL,
  125357. 0
  125358. };
  125359. static long _vq_quantlist__8c0_s_p4_0[] = {
  125360. 4,
  125361. 3,
  125362. 5,
  125363. 2,
  125364. 6,
  125365. 1,
  125366. 7,
  125367. 0,
  125368. 8,
  125369. };
  125370. static long _vq_lengthlist__8c0_s_p4_0[] = {
  125371. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  125372. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  125373. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  125374. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  125375. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125376. 0,
  125377. };
  125378. static float _vq_quantthresh__8c0_s_p4_0[] = {
  125379. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125380. };
  125381. static long _vq_quantmap__8c0_s_p4_0[] = {
  125382. 7, 5, 3, 1, 0, 2, 4, 6,
  125383. 8,
  125384. };
  125385. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  125386. _vq_quantthresh__8c0_s_p4_0,
  125387. _vq_quantmap__8c0_s_p4_0,
  125388. 9,
  125389. 9
  125390. };
  125391. static static_codebook _8c0_s_p4_0 = {
  125392. 2, 81,
  125393. _vq_lengthlist__8c0_s_p4_0,
  125394. 1, -531628032, 1611661312, 4, 0,
  125395. _vq_quantlist__8c0_s_p4_0,
  125396. NULL,
  125397. &_vq_auxt__8c0_s_p4_0,
  125398. NULL,
  125399. 0
  125400. };
  125401. static long _vq_quantlist__8c0_s_p5_0[] = {
  125402. 4,
  125403. 3,
  125404. 5,
  125405. 2,
  125406. 6,
  125407. 1,
  125408. 7,
  125409. 0,
  125410. 8,
  125411. };
  125412. static long _vq_lengthlist__8c0_s_p5_0[] = {
  125413. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  125414. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  125415. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  125416. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  125417. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  125418. 10,
  125419. };
  125420. static float _vq_quantthresh__8c0_s_p5_0[] = {
  125421. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125422. };
  125423. static long _vq_quantmap__8c0_s_p5_0[] = {
  125424. 7, 5, 3, 1, 0, 2, 4, 6,
  125425. 8,
  125426. };
  125427. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  125428. _vq_quantthresh__8c0_s_p5_0,
  125429. _vq_quantmap__8c0_s_p5_0,
  125430. 9,
  125431. 9
  125432. };
  125433. static static_codebook _8c0_s_p5_0 = {
  125434. 2, 81,
  125435. _vq_lengthlist__8c0_s_p5_0,
  125436. 1, -531628032, 1611661312, 4, 0,
  125437. _vq_quantlist__8c0_s_p5_0,
  125438. NULL,
  125439. &_vq_auxt__8c0_s_p5_0,
  125440. NULL,
  125441. 0
  125442. };
  125443. static long _vq_quantlist__8c0_s_p6_0[] = {
  125444. 8,
  125445. 7,
  125446. 9,
  125447. 6,
  125448. 10,
  125449. 5,
  125450. 11,
  125451. 4,
  125452. 12,
  125453. 3,
  125454. 13,
  125455. 2,
  125456. 14,
  125457. 1,
  125458. 15,
  125459. 0,
  125460. 16,
  125461. };
  125462. static long _vq_lengthlist__8c0_s_p6_0[] = {
  125463. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  125464. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  125465. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  125466. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  125467. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  125468. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  125469. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  125470. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  125471. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  125472. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  125473. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  125474. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  125475. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  125476. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  125477. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  125478. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  125479. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  125480. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  125481. 14,
  125482. };
  125483. static float _vq_quantthresh__8c0_s_p6_0[] = {
  125484. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125485. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125486. };
  125487. static long _vq_quantmap__8c0_s_p6_0[] = {
  125488. 15, 13, 11, 9, 7, 5, 3, 1,
  125489. 0, 2, 4, 6, 8, 10, 12, 14,
  125490. 16,
  125491. };
  125492. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  125493. _vq_quantthresh__8c0_s_p6_0,
  125494. _vq_quantmap__8c0_s_p6_0,
  125495. 17,
  125496. 17
  125497. };
  125498. static static_codebook _8c0_s_p6_0 = {
  125499. 2, 289,
  125500. _vq_lengthlist__8c0_s_p6_0,
  125501. 1, -529530880, 1611661312, 5, 0,
  125502. _vq_quantlist__8c0_s_p6_0,
  125503. NULL,
  125504. &_vq_auxt__8c0_s_p6_0,
  125505. NULL,
  125506. 0
  125507. };
  125508. static long _vq_quantlist__8c0_s_p7_0[] = {
  125509. 1,
  125510. 0,
  125511. 2,
  125512. };
  125513. static long _vq_lengthlist__8c0_s_p7_0[] = {
  125514. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  125515. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  125516. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  125517. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  125518. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  125519. 10,
  125520. };
  125521. static float _vq_quantthresh__8c0_s_p7_0[] = {
  125522. -5.5, 5.5,
  125523. };
  125524. static long _vq_quantmap__8c0_s_p7_0[] = {
  125525. 1, 0, 2,
  125526. };
  125527. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  125528. _vq_quantthresh__8c0_s_p7_0,
  125529. _vq_quantmap__8c0_s_p7_0,
  125530. 3,
  125531. 3
  125532. };
  125533. static static_codebook _8c0_s_p7_0 = {
  125534. 4, 81,
  125535. _vq_lengthlist__8c0_s_p7_0,
  125536. 1, -529137664, 1618345984, 2, 0,
  125537. _vq_quantlist__8c0_s_p7_0,
  125538. NULL,
  125539. &_vq_auxt__8c0_s_p7_0,
  125540. NULL,
  125541. 0
  125542. };
  125543. static long _vq_quantlist__8c0_s_p7_1[] = {
  125544. 5,
  125545. 4,
  125546. 6,
  125547. 3,
  125548. 7,
  125549. 2,
  125550. 8,
  125551. 1,
  125552. 9,
  125553. 0,
  125554. 10,
  125555. };
  125556. static long _vq_lengthlist__8c0_s_p7_1[] = {
  125557. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  125558. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  125559. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  125560. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  125561. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  125562. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  125563. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  125564. 10,10,10, 9, 9, 9,10,10,10,
  125565. };
  125566. static float _vq_quantthresh__8c0_s_p7_1[] = {
  125567. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125568. 3.5, 4.5,
  125569. };
  125570. static long _vq_quantmap__8c0_s_p7_1[] = {
  125571. 9, 7, 5, 3, 1, 0, 2, 4,
  125572. 6, 8, 10,
  125573. };
  125574. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  125575. _vq_quantthresh__8c0_s_p7_1,
  125576. _vq_quantmap__8c0_s_p7_1,
  125577. 11,
  125578. 11
  125579. };
  125580. static static_codebook _8c0_s_p7_1 = {
  125581. 2, 121,
  125582. _vq_lengthlist__8c0_s_p7_1,
  125583. 1, -531365888, 1611661312, 4, 0,
  125584. _vq_quantlist__8c0_s_p7_1,
  125585. NULL,
  125586. &_vq_auxt__8c0_s_p7_1,
  125587. NULL,
  125588. 0
  125589. };
  125590. static long _vq_quantlist__8c0_s_p8_0[] = {
  125591. 6,
  125592. 5,
  125593. 7,
  125594. 4,
  125595. 8,
  125596. 3,
  125597. 9,
  125598. 2,
  125599. 10,
  125600. 1,
  125601. 11,
  125602. 0,
  125603. 12,
  125604. };
  125605. static long _vq_lengthlist__8c0_s_p8_0[] = {
  125606. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  125607. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  125608. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  125609. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  125610. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  125611. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  125612. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  125613. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  125614. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  125615. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  125616. 0, 0,13,13,11,13,13,11,12,
  125617. };
  125618. static float _vq_quantthresh__8c0_s_p8_0[] = {
  125619. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  125620. 12.5, 17.5, 22.5, 27.5,
  125621. };
  125622. static long _vq_quantmap__8c0_s_p8_0[] = {
  125623. 11, 9, 7, 5, 3, 1, 0, 2,
  125624. 4, 6, 8, 10, 12,
  125625. };
  125626. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  125627. _vq_quantthresh__8c0_s_p8_0,
  125628. _vq_quantmap__8c0_s_p8_0,
  125629. 13,
  125630. 13
  125631. };
  125632. static static_codebook _8c0_s_p8_0 = {
  125633. 2, 169,
  125634. _vq_lengthlist__8c0_s_p8_0,
  125635. 1, -526516224, 1616117760, 4, 0,
  125636. _vq_quantlist__8c0_s_p8_0,
  125637. NULL,
  125638. &_vq_auxt__8c0_s_p8_0,
  125639. NULL,
  125640. 0
  125641. };
  125642. static long _vq_quantlist__8c0_s_p8_1[] = {
  125643. 2,
  125644. 1,
  125645. 3,
  125646. 0,
  125647. 4,
  125648. };
  125649. static long _vq_lengthlist__8c0_s_p8_1[] = {
  125650. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  125651. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  125652. };
  125653. static float _vq_quantthresh__8c0_s_p8_1[] = {
  125654. -1.5, -0.5, 0.5, 1.5,
  125655. };
  125656. static long _vq_quantmap__8c0_s_p8_1[] = {
  125657. 3, 1, 0, 2, 4,
  125658. };
  125659. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  125660. _vq_quantthresh__8c0_s_p8_1,
  125661. _vq_quantmap__8c0_s_p8_1,
  125662. 5,
  125663. 5
  125664. };
  125665. static static_codebook _8c0_s_p8_1 = {
  125666. 2, 25,
  125667. _vq_lengthlist__8c0_s_p8_1,
  125668. 1, -533725184, 1611661312, 3, 0,
  125669. _vq_quantlist__8c0_s_p8_1,
  125670. NULL,
  125671. &_vq_auxt__8c0_s_p8_1,
  125672. NULL,
  125673. 0
  125674. };
  125675. static long _vq_quantlist__8c0_s_p9_0[] = {
  125676. 1,
  125677. 0,
  125678. 2,
  125679. };
  125680. static long _vq_lengthlist__8c0_s_p9_0[] = {
  125681. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125682. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125683. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  125684. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  125685. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  125686. 7,
  125687. };
  125688. static float _vq_quantthresh__8c0_s_p9_0[] = {
  125689. -157.5, 157.5,
  125690. };
  125691. static long _vq_quantmap__8c0_s_p9_0[] = {
  125692. 1, 0, 2,
  125693. };
  125694. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  125695. _vq_quantthresh__8c0_s_p9_0,
  125696. _vq_quantmap__8c0_s_p9_0,
  125697. 3,
  125698. 3
  125699. };
  125700. static static_codebook _8c0_s_p9_0 = {
  125701. 4, 81,
  125702. _vq_lengthlist__8c0_s_p9_0,
  125703. 1, -518803456, 1628680192, 2, 0,
  125704. _vq_quantlist__8c0_s_p9_0,
  125705. NULL,
  125706. &_vq_auxt__8c0_s_p9_0,
  125707. NULL,
  125708. 0
  125709. };
  125710. static long _vq_quantlist__8c0_s_p9_1[] = {
  125711. 7,
  125712. 6,
  125713. 8,
  125714. 5,
  125715. 9,
  125716. 4,
  125717. 10,
  125718. 3,
  125719. 11,
  125720. 2,
  125721. 12,
  125722. 1,
  125723. 13,
  125724. 0,
  125725. 14,
  125726. };
  125727. static long _vq_lengthlist__8c0_s_p9_1[] = {
  125728. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  125729. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  125730. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  125731. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  125732. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  125733. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  125734. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125735. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125736. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125737. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125738. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125739. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125740. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125741. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125742. 11,
  125743. };
  125744. static float _vq_quantthresh__8c0_s_p9_1[] = {
  125745. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  125746. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  125747. };
  125748. static long _vq_quantmap__8c0_s_p9_1[] = {
  125749. 13, 11, 9, 7, 5, 3, 1, 0,
  125750. 2, 4, 6, 8, 10, 12, 14,
  125751. };
  125752. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  125753. _vq_quantthresh__8c0_s_p9_1,
  125754. _vq_quantmap__8c0_s_p9_1,
  125755. 15,
  125756. 15
  125757. };
  125758. static static_codebook _8c0_s_p9_1 = {
  125759. 2, 225,
  125760. _vq_lengthlist__8c0_s_p9_1,
  125761. 1, -520986624, 1620377600, 4, 0,
  125762. _vq_quantlist__8c0_s_p9_1,
  125763. NULL,
  125764. &_vq_auxt__8c0_s_p9_1,
  125765. NULL,
  125766. 0
  125767. };
  125768. static long _vq_quantlist__8c0_s_p9_2[] = {
  125769. 10,
  125770. 9,
  125771. 11,
  125772. 8,
  125773. 12,
  125774. 7,
  125775. 13,
  125776. 6,
  125777. 14,
  125778. 5,
  125779. 15,
  125780. 4,
  125781. 16,
  125782. 3,
  125783. 17,
  125784. 2,
  125785. 18,
  125786. 1,
  125787. 19,
  125788. 0,
  125789. 20,
  125790. };
  125791. static long _vq_lengthlist__8c0_s_p9_2[] = {
  125792. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  125793. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  125794. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  125795. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  125796. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  125797. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  125798. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  125799. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  125800. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  125801. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  125802. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  125803. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  125804. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  125805. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  125806. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  125807. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  125808. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  125809. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  125810. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  125811. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  125812. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  125813. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  125814. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  125815. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  125816. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  125817. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  125818. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  125819. 10,11, 9,11,10, 9,10, 9,10,
  125820. };
  125821. static float _vq_quantthresh__8c0_s_p9_2[] = {
  125822. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  125823. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  125824. 6.5, 7.5, 8.5, 9.5,
  125825. };
  125826. static long _vq_quantmap__8c0_s_p9_2[] = {
  125827. 19, 17, 15, 13, 11, 9, 7, 5,
  125828. 3, 1, 0, 2, 4, 6, 8, 10,
  125829. 12, 14, 16, 18, 20,
  125830. };
  125831. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  125832. _vq_quantthresh__8c0_s_p9_2,
  125833. _vq_quantmap__8c0_s_p9_2,
  125834. 21,
  125835. 21
  125836. };
  125837. static static_codebook _8c0_s_p9_2 = {
  125838. 2, 441,
  125839. _vq_lengthlist__8c0_s_p9_2,
  125840. 1, -529268736, 1611661312, 5, 0,
  125841. _vq_quantlist__8c0_s_p9_2,
  125842. NULL,
  125843. &_vq_auxt__8c0_s_p9_2,
  125844. NULL,
  125845. 0
  125846. };
  125847. static long _huff_lengthlist__8c0_s_single[] = {
  125848. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  125849. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  125850. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  125851. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  125852. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  125853. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  125854. 17,16,17,17,
  125855. };
  125856. static static_codebook _huff_book__8c0_s_single = {
  125857. 2, 100,
  125858. _huff_lengthlist__8c0_s_single,
  125859. 0, 0, 0, 0, 0,
  125860. NULL,
  125861. NULL,
  125862. NULL,
  125863. NULL,
  125864. 0
  125865. };
  125866. static long _vq_quantlist__8c1_s_p1_0[] = {
  125867. 1,
  125868. 0,
  125869. 2,
  125870. };
  125871. static long _vq_lengthlist__8c1_s_p1_0[] = {
  125872. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  125873. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125877. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  125878. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125882. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  125883. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  125918. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  125923. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  125924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  125928. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  125929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125963. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125964. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125968. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  125969. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  125970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125973. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  125974. 0, 0, 0, 0, 0, 0, 8,10, 8, 0, 0, 0, 0, 0, 0, 0,
  125975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126282. 0,
  126283. };
  126284. static float _vq_quantthresh__8c1_s_p1_0[] = {
  126285. -0.5, 0.5,
  126286. };
  126287. static long _vq_quantmap__8c1_s_p1_0[] = {
  126288. 1, 0, 2,
  126289. };
  126290. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  126291. _vq_quantthresh__8c1_s_p1_0,
  126292. _vq_quantmap__8c1_s_p1_0,
  126293. 3,
  126294. 3
  126295. };
  126296. static static_codebook _8c1_s_p1_0 = {
  126297. 8, 6561,
  126298. _vq_lengthlist__8c1_s_p1_0,
  126299. 1, -535822336, 1611661312, 2, 0,
  126300. _vq_quantlist__8c1_s_p1_0,
  126301. NULL,
  126302. &_vq_auxt__8c1_s_p1_0,
  126303. NULL,
  126304. 0
  126305. };
  126306. static long _vq_quantlist__8c1_s_p2_0[] = {
  126307. 2,
  126308. 1,
  126309. 3,
  126310. 0,
  126311. 4,
  126312. };
  126313. static long _vq_lengthlist__8c1_s_p2_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,
  126354. };
  126355. static float _vq_quantthresh__8c1_s_p2_0[] = {
  126356. -1.5, -0.5, 0.5, 1.5,
  126357. };
  126358. static long _vq_quantmap__8c1_s_p2_0[] = {
  126359. 3, 1, 0, 2, 4,
  126360. };
  126361. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  126362. _vq_quantthresh__8c1_s_p2_0,
  126363. _vq_quantmap__8c1_s_p2_0,
  126364. 5,
  126365. 5
  126366. };
  126367. static static_codebook _8c1_s_p2_0 = {
  126368. 4, 625,
  126369. _vq_lengthlist__8c1_s_p2_0,
  126370. 1, -533725184, 1611661312, 3, 0,
  126371. _vq_quantlist__8c1_s_p2_0,
  126372. NULL,
  126373. &_vq_auxt__8c1_s_p2_0,
  126374. NULL,
  126375. 0
  126376. };
  126377. static long _vq_quantlist__8c1_s_p3_0[] = {
  126378. 2,
  126379. 1,
  126380. 3,
  126381. 0,
  126382. 4,
  126383. };
  126384. static long _vq_lengthlist__8c1_s_p3_0[] = {
  126385. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  126387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126388. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  126390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126391. 0, 0, 0, 0, 6, 6, 6, 7, 7, 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,
  126425. };
  126426. static float _vq_quantthresh__8c1_s_p3_0[] = {
  126427. -1.5, -0.5, 0.5, 1.5,
  126428. };
  126429. static long _vq_quantmap__8c1_s_p3_0[] = {
  126430. 3, 1, 0, 2, 4,
  126431. };
  126432. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  126433. _vq_quantthresh__8c1_s_p3_0,
  126434. _vq_quantmap__8c1_s_p3_0,
  126435. 5,
  126436. 5
  126437. };
  126438. static static_codebook _8c1_s_p3_0 = {
  126439. 4, 625,
  126440. _vq_lengthlist__8c1_s_p3_0,
  126441. 1, -533725184, 1611661312, 3, 0,
  126442. _vq_quantlist__8c1_s_p3_0,
  126443. NULL,
  126444. &_vq_auxt__8c1_s_p3_0,
  126445. NULL,
  126446. 0
  126447. };
  126448. static long _vq_quantlist__8c1_s_p4_0[] = {
  126449. 4,
  126450. 3,
  126451. 5,
  126452. 2,
  126453. 6,
  126454. 1,
  126455. 7,
  126456. 0,
  126457. 8,
  126458. };
  126459. static long _vq_lengthlist__8c1_s_p4_0[] = {
  126460. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  126461. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  126462. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  126463. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  126464. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126465. 0,
  126466. };
  126467. static float _vq_quantthresh__8c1_s_p4_0[] = {
  126468. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126469. };
  126470. static long _vq_quantmap__8c1_s_p4_0[] = {
  126471. 7, 5, 3, 1, 0, 2, 4, 6,
  126472. 8,
  126473. };
  126474. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  126475. _vq_quantthresh__8c1_s_p4_0,
  126476. _vq_quantmap__8c1_s_p4_0,
  126477. 9,
  126478. 9
  126479. };
  126480. static static_codebook _8c1_s_p4_0 = {
  126481. 2, 81,
  126482. _vq_lengthlist__8c1_s_p4_0,
  126483. 1, -531628032, 1611661312, 4, 0,
  126484. _vq_quantlist__8c1_s_p4_0,
  126485. NULL,
  126486. &_vq_auxt__8c1_s_p4_0,
  126487. NULL,
  126488. 0
  126489. };
  126490. static long _vq_quantlist__8c1_s_p5_0[] = {
  126491. 4,
  126492. 3,
  126493. 5,
  126494. 2,
  126495. 6,
  126496. 1,
  126497. 7,
  126498. 0,
  126499. 8,
  126500. };
  126501. static long _vq_lengthlist__8c1_s_p5_0[] = {
  126502. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  126503. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  126504. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  126505. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  126506. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  126507. 10,
  126508. };
  126509. static float _vq_quantthresh__8c1_s_p5_0[] = {
  126510. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126511. };
  126512. static long _vq_quantmap__8c1_s_p5_0[] = {
  126513. 7, 5, 3, 1, 0, 2, 4, 6,
  126514. 8,
  126515. };
  126516. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  126517. _vq_quantthresh__8c1_s_p5_0,
  126518. _vq_quantmap__8c1_s_p5_0,
  126519. 9,
  126520. 9
  126521. };
  126522. static static_codebook _8c1_s_p5_0 = {
  126523. 2, 81,
  126524. _vq_lengthlist__8c1_s_p5_0,
  126525. 1, -531628032, 1611661312, 4, 0,
  126526. _vq_quantlist__8c1_s_p5_0,
  126527. NULL,
  126528. &_vq_auxt__8c1_s_p5_0,
  126529. NULL,
  126530. 0
  126531. };
  126532. static long _vq_quantlist__8c1_s_p6_0[] = {
  126533. 8,
  126534. 7,
  126535. 9,
  126536. 6,
  126537. 10,
  126538. 5,
  126539. 11,
  126540. 4,
  126541. 12,
  126542. 3,
  126543. 13,
  126544. 2,
  126545. 14,
  126546. 1,
  126547. 15,
  126548. 0,
  126549. 16,
  126550. };
  126551. static long _vq_lengthlist__8c1_s_p6_0[] = {
  126552. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  126553. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  126554. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  126555. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  126556. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  126557. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  126558. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  126559. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  126560. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  126561. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  126562. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  126563. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  126564. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  126565. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  126566. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  126567. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  126568. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  126569. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  126570. 14,
  126571. };
  126572. static float _vq_quantthresh__8c1_s_p6_0[] = {
  126573. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126574. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126575. };
  126576. static long _vq_quantmap__8c1_s_p6_0[] = {
  126577. 15, 13, 11, 9, 7, 5, 3, 1,
  126578. 0, 2, 4, 6, 8, 10, 12, 14,
  126579. 16,
  126580. };
  126581. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  126582. _vq_quantthresh__8c1_s_p6_0,
  126583. _vq_quantmap__8c1_s_p6_0,
  126584. 17,
  126585. 17
  126586. };
  126587. static static_codebook _8c1_s_p6_0 = {
  126588. 2, 289,
  126589. _vq_lengthlist__8c1_s_p6_0,
  126590. 1, -529530880, 1611661312, 5, 0,
  126591. _vq_quantlist__8c1_s_p6_0,
  126592. NULL,
  126593. &_vq_auxt__8c1_s_p6_0,
  126594. NULL,
  126595. 0
  126596. };
  126597. static long _vq_quantlist__8c1_s_p7_0[] = {
  126598. 1,
  126599. 0,
  126600. 2,
  126601. };
  126602. static long _vq_lengthlist__8c1_s_p7_0[] = {
  126603. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  126604. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  126605. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  126606. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  126607. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  126608. 9,
  126609. };
  126610. static float _vq_quantthresh__8c1_s_p7_0[] = {
  126611. -5.5, 5.5,
  126612. };
  126613. static long _vq_quantmap__8c1_s_p7_0[] = {
  126614. 1, 0, 2,
  126615. };
  126616. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  126617. _vq_quantthresh__8c1_s_p7_0,
  126618. _vq_quantmap__8c1_s_p7_0,
  126619. 3,
  126620. 3
  126621. };
  126622. static static_codebook _8c1_s_p7_0 = {
  126623. 4, 81,
  126624. _vq_lengthlist__8c1_s_p7_0,
  126625. 1, -529137664, 1618345984, 2, 0,
  126626. _vq_quantlist__8c1_s_p7_0,
  126627. NULL,
  126628. &_vq_auxt__8c1_s_p7_0,
  126629. NULL,
  126630. 0
  126631. };
  126632. static long _vq_quantlist__8c1_s_p7_1[] = {
  126633. 5,
  126634. 4,
  126635. 6,
  126636. 3,
  126637. 7,
  126638. 2,
  126639. 8,
  126640. 1,
  126641. 9,
  126642. 0,
  126643. 10,
  126644. };
  126645. static long _vq_lengthlist__8c1_s_p7_1[] = {
  126646. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  126647. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  126648. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  126649. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  126650. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  126651. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  126652. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  126653. 10,10,10, 8, 8, 8, 8, 8, 8,
  126654. };
  126655. static float _vq_quantthresh__8c1_s_p7_1[] = {
  126656. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126657. 3.5, 4.5,
  126658. };
  126659. static long _vq_quantmap__8c1_s_p7_1[] = {
  126660. 9, 7, 5, 3, 1, 0, 2, 4,
  126661. 6, 8, 10,
  126662. };
  126663. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  126664. _vq_quantthresh__8c1_s_p7_1,
  126665. _vq_quantmap__8c1_s_p7_1,
  126666. 11,
  126667. 11
  126668. };
  126669. static static_codebook _8c1_s_p7_1 = {
  126670. 2, 121,
  126671. _vq_lengthlist__8c1_s_p7_1,
  126672. 1, -531365888, 1611661312, 4, 0,
  126673. _vq_quantlist__8c1_s_p7_1,
  126674. NULL,
  126675. &_vq_auxt__8c1_s_p7_1,
  126676. NULL,
  126677. 0
  126678. };
  126679. static long _vq_quantlist__8c1_s_p8_0[] = {
  126680. 6,
  126681. 5,
  126682. 7,
  126683. 4,
  126684. 8,
  126685. 3,
  126686. 9,
  126687. 2,
  126688. 10,
  126689. 1,
  126690. 11,
  126691. 0,
  126692. 12,
  126693. };
  126694. static long _vq_lengthlist__8c1_s_p8_0[] = {
  126695. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  126696. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  126697. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  126698. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  126699. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  126700. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  126701. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  126702. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  126703. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  126704. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  126705. 0,12,12,11,10,12,11,13,12,
  126706. };
  126707. static float _vq_quantthresh__8c1_s_p8_0[] = {
  126708. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126709. 12.5, 17.5, 22.5, 27.5,
  126710. };
  126711. static long _vq_quantmap__8c1_s_p8_0[] = {
  126712. 11, 9, 7, 5, 3, 1, 0, 2,
  126713. 4, 6, 8, 10, 12,
  126714. };
  126715. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  126716. _vq_quantthresh__8c1_s_p8_0,
  126717. _vq_quantmap__8c1_s_p8_0,
  126718. 13,
  126719. 13
  126720. };
  126721. static static_codebook _8c1_s_p8_0 = {
  126722. 2, 169,
  126723. _vq_lengthlist__8c1_s_p8_0,
  126724. 1, -526516224, 1616117760, 4, 0,
  126725. _vq_quantlist__8c1_s_p8_0,
  126726. NULL,
  126727. &_vq_auxt__8c1_s_p8_0,
  126728. NULL,
  126729. 0
  126730. };
  126731. static long _vq_quantlist__8c1_s_p8_1[] = {
  126732. 2,
  126733. 1,
  126734. 3,
  126735. 0,
  126736. 4,
  126737. };
  126738. static long _vq_lengthlist__8c1_s_p8_1[] = {
  126739. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  126740. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  126741. };
  126742. static float _vq_quantthresh__8c1_s_p8_1[] = {
  126743. -1.5, -0.5, 0.5, 1.5,
  126744. };
  126745. static long _vq_quantmap__8c1_s_p8_1[] = {
  126746. 3, 1, 0, 2, 4,
  126747. };
  126748. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  126749. _vq_quantthresh__8c1_s_p8_1,
  126750. _vq_quantmap__8c1_s_p8_1,
  126751. 5,
  126752. 5
  126753. };
  126754. static static_codebook _8c1_s_p8_1 = {
  126755. 2, 25,
  126756. _vq_lengthlist__8c1_s_p8_1,
  126757. 1, -533725184, 1611661312, 3, 0,
  126758. _vq_quantlist__8c1_s_p8_1,
  126759. NULL,
  126760. &_vq_auxt__8c1_s_p8_1,
  126761. NULL,
  126762. 0
  126763. };
  126764. static long _vq_quantlist__8c1_s_p9_0[] = {
  126765. 6,
  126766. 5,
  126767. 7,
  126768. 4,
  126769. 8,
  126770. 3,
  126771. 9,
  126772. 2,
  126773. 10,
  126774. 1,
  126775. 11,
  126776. 0,
  126777. 12,
  126778. };
  126779. static long _vq_lengthlist__8c1_s_p9_0[] = {
  126780. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  126781. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  126782. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126783. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126784. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126785. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126786. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126787. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126788. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126789. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126790. 10,10,10,10,10, 9, 9, 9, 9,
  126791. };
  126792. static float _vq_quantthresh__8c1_s_p9_0[] = {
  126793. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  126794. 787.5, 1102.5, 1417.5, 1732.5,
  126795. };
  126796. static long _vq_quantmap__8c1_s_p9_0[] = {
  126797. 11, 9, 7, 5, 3, 1, 0, 2,
  126798. 4, 6, 8, 10, 12,
  126799. };
  126800. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  126801. _vq_quantthresh__8c1_s_p9_0,
  126802. _vq_quantmap__8c1_s_p9_0,
  126803. 13,
  126804. 13
  126805. };
  126806. static static_codebook _8c1_s_p9_0 = {
  126807. 2, 169,
  126808. _vq_lengthlist__8c1_s_p9_0,
  126809. 1, -513964032, 1628680192, 4, 0,
  126810. _vq_quantlist__8c1_s_p9_0,
  126811. NULL,
  126812. &_vq_auxt__8c1_s_p9_0,
  126813. NULL,
  126814. 0
  126815. };
  126816. static long _vq_quantlist__8c1_s_p9_1[] = {
  126817. 7,
  126818. 6,
  126819. 8,
  126820. 5,
  126821. 9,
  126822. 4,
  126823. 10,
  126824. 3,
  126825. 11,
  126826. 2,
  126827. 12,
  126828. 1,
  126829. 13,
  126830. 0,
  126831. 14,
  126832. };
  126833. static long _vq_lengthlist__8c1_s_p9_1[] = {
  126834. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  126835. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  126836. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  126837. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  126838. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  126839. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  126840. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  126841. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  126842. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  126843. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  126844. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  126845. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  126846. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  126847. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  126848. 15,
  126849. };
  126850. static float _vq_quantthresh__8c1_s_p9_1[] = {
  126851. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  126852. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  126853. };
  126854. static long _vq_quantmap__8c1_s_p9_1[] = {
  126855. 13, 11, 9, 7, 5, 3, 1, 0,
  126856. 2, 4, 6, 8, 10, 12, 14,
  126857. };
  126858. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  126859. _vq_quantthresh__8c1_s_p9_1,
  126860. _vq_quantmap__8c1_s_p9_1,
  126861. 15,
  126862. 15
  126863. };
  126864. static static_codebook _8c1_s_p9_1 = {
  126865. 2, 225,
  126866. _vq_lengthlist__8c1_s_p9_1,
  126867. 1, -520986624, 1620377600, 4, 0,
  126868. _vq_quantlist__8c1_s_p9_1,
  126869. NULL,
  126870. &_vq_auxt__8c1_s_p9_1,
  126871. NULL,
  126872. 0
  126873. };
  126874. static long _vq_quantlist__8c1_s_p9_2[] = {
  126875. 10,
  126876. 9,
  126877. 11,
  126878. 8,
  126879. 12,
  126880. 7,
  126881. 13,
  126882. 6,
  126883. 14,
  126884. 5,
  126885. 15,
  126886. 4,
  126887. 16,
  126888. 3,
  126889. 17,
  126890. 2,
  126891. 18,
  126892. 1,
  126893. 19,
  126894. 0,
  126895. 20,
  126896. };
  126897. static long _vq_lengthlist__8c1_s_p9_2[] = {
  126898. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  126899. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  126900. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  126901. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  126902. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  126903. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  126904. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  126905. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  126906. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  126907. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  126908. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  126909. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  126910. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  126911. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  126912. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  126913. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  126914. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126915. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  126916. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  126917. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  126918. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126919. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  126920. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  126921. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  126922. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  126923. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  126924. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  126925. 10,10,10,10,10,10,10,10,10,
  126926. };
  126927. static float _vq_quantthresh__8c1_s_p9_2[] = {
  126928. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  126929. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  126930. 6.5, 7.5, 8.5, 9.5,
  126931. };
  126932. static long _vq_quantmap__8c1_s_p9_2[] = {
  126933. 19, 17, 15, 13, 11, 9, 7, 5,
  126934. 3, 1, 0, 2, 4, 6, 8, 10,
  126935. 12, 14, 16, 18, 20,
  126936. };
  126937. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  126938. _vq_quantthresh__8c1_s_p9_2,
  126939. _vq_quantmap__8c1_s_p9_2,
  126940. 21,
  126941. 21
  126942. };
  126943. static static_codebook _8c1_s_p9_2 = {
  126944. 2, 441,
  126945. _vq_lengthlist__8c1_s_p9_2,
  126946. 1, -529268736, 1611661312, 5, 0,
  126947. _vq_quantlist__8c1_s_p9_2,
  126948. NULL,
  126949. &_vq_auxt__8c1_s_p9_2,
  126950. NULL,
  126951. 0
  126952. };
  126953. static long _huff_lengthlist__8c1_s_single[] = {
  126954. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  126955. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  126956. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  126957. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  126958. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  126959. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  126960. 9, 7, 7, 8,
  126961. };
  126962. static static_codebook _huff_book__8c1_s_single = {
  126963. 2, 100,
  126964. _huff_lengthlist__8c1_s_single,
  126965. 0, 0, 0, 0, 0,
  126966. NULL,
  126967. NULL,
  126968. NULL,
  126969. NULL,
  126970. 0
  126971. };
  126972. static long _huff_lengthlist__44c2_s_long[] = {
  126973. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  126974. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  126975. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  126976. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  126977. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  126978. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  126979. 10, 8, 8, 9,
  126980. };
  126981. static static_codebook _huff_book__44c2_s_long = {
  126982. 2, 100,
  126983. _huff_lengthlist__44c2_s_long,
  126984. 0, 0, 0, 0, 0,
  126985. NULL,
  126986. NULL,
  126987. NULL,
  126988. NULL,
  126989. 0
  126990. };
  126991. static long _vq_quantlist__44c2_s_p1_0[] = {
  126992. 1,
  126993. 0,
  126994. 2,
  126995. };
  126996. static long _vq_lengthlist__44c2_s_p1_0[] = {
  126997. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  126998. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127002. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  127003. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127007. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  127008. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  127043. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  127044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  127048. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  127049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  127053. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  127054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127088. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  127089. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127093. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  127094. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  127095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127098. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  127099. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  127100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127407. 0,
  127408. };
  127409. static float _vq_quantthresh__44c2_s_p1_0[] = {
  127410. -0.5, 0.5,
  127411. };
  127412. static long _vq_quantmap__44c2_s_p1_0[] = {
  127413. 1, 0, 2,
  127414. };
  127415. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  127416. _vq_quantthresh__44c2_s_p1_0,
  127417. _vq_quantmap__44c2_s_p1_0,
  127418. 3,
  127419. 3
  127420. };
  127421. static static_codebook _44c2_s_p1_0 = {
  127422. 8, 6561,
  127423. _vq_lengthlist__44c2_s_p1_0,
  127424. 1, -535822336, 1611661312, 2, 0,
  127425. _vq_quantlist__44c2_s_p1_0,
  127426. NULL,
  127427. &_vq_auxt__44c2_s_p1_0,
  127428. NULL,
  127429. 0
  127430. };
  127431. static long _vq_quantlist__44c2_s_p2_0[] = {
  127432. 2,
  127433. 1,
  127434. 3,
  127435. 0,
  127436. 4,
  127437. };
  127438. static long _vq_lengthlist__44c2_s_p2_0[] = {
  127439. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  127440. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  127441. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  127442. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  127443. 0, 0, 9, 9, 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, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  127449. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  127450. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  127451. 12, 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, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  127457. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  127458. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 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. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  127465. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  127466. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 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,
  127479. };
  127480. static float _vq_quantthresh__44c2_s_p2_0[] = {
  127481. -1.5, -0.5, 0.5, 1.5,
  127482. };
  127483. static long _vq_quantmap__44c2_s_p2_0[] = {
  127484. 3, 1, 0, 2, 4,
  127485. };
  127486. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  127487. _vq_quantthresh__44c2_s_p2_0,
  127488. _vq_quantmap__44c2_s_p2_0,
  127489. 5,
  127490. 5
  127491. };
  127492. static static_codebook _44c2_s_p2_0 = {
  127493. 4, 625,
  127494. _vq_lengthlist__44c2_s_p2_0,
  127495. 1, -533725184, 1611661312, 3, 0,
  127496. _vq_quantlist__44c2_s_p2_0,
  127497. NULL,
  127498. &_vq_auxt__44c2_s_p2_0,
  127499. NULL,
  127500. 0
  127501. };
  127502. static long _vq_quantlist__44c2_s_p3_0[] = {
  127503. 2,
  127504. 1,
  127505. 3,
  127506. 0,
  127507. 4,
  127508. };
  127509. static long _vq_lengthlist__44c2_s_p3_0[] = {
  127510. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  127512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127513. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  127515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127516. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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,
  127550. };
  127551. static float _vq_quantthresh__44c2_s_p3_0[] = {
  127552. -1.5, -0.5, 0.5, 1.5,
  127553. };
  127554. static long _vq_quantmap__44c2_s_p3_0[] = {
  127555. 3, 1, 0, 2, 4,
  127556. };
  127557. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  127558. _vq_quantthresh__44c2_s_p3_0,
  127559. _vq_quantmap__44c2_s_p3_0,
  127560. 5,
  127561. 5
  127562. };
  127563. static static_codebook _44c2_s_p3_0 = {
  127564. 4, 625,
  127565. _vq_lengthlist__44c2_s_p3_0,
  127566. 1, -533725184, 1611661312, 3, 0,
  127567. _vq_quantlist__44c2_s_p3_0,
  127568. NULL,
  127569. &_vq_auxt__44c2_s_p3_0,
  127570. NULL,
  127571. 0
  127572. };
  127573. static long _vq_quantlist__44c2_s_p4_0[] = {
  127574. 4,
  127575. 3,
  127576. 5,
  127577. 2,
  127578. 6,
  127579. 1,
  127580. 7,
  127581. 0,
  127582. 8,
  127583. };
  127584. static long _vq_lengthlist__44c2_s_p4_0[] = {
  127585. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  127586. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  127587. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  127588. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  127589. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127590. 0,
  127591. };
  127592. static float _vq_quantthresh__44c2_s_p4_0[] = {
  127593. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127594. };
  127595. static long _vq_quantmap__44c2_s_p4_0[] = {
  127596. 7, 5, 3, 1, 0, 2, 4, 6,
  127597. 8,
  127598. };
  127599. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  127600. _vq_quantthresh__44c2_s_p4_0,
  127601. _vq_quantmap__44c2_s_p4_0,
  127602. 9,
  127603. 9
  127604. };
  127605. static static_codebook _44c2_s_p4_0 = {
  127606. 2, 81,
  127607. _vq_lengthlist__44c2_s_p4_0,
  127608. 1, -531628032, 1611661312, 4, 0,
  127609. _vq_quantlist__44c2_s_p4_0,
  127610. NULL,
  127611. &_vq_auxt__44c2_s_p4_0,
  127612. NULL,
  127613. 0
  127614. };
  127615. static long _vq_quantlist__44c2_s_p5_0[] = {
  127616. 4,
  127617. 3,
  127618. 5,
  127619. 2,
  127620. 6,
  127621. 1,
  127622. 7,
  127623. 0,
  127624. 8,
  127625. };
  127626. static long _vq_lengthlist__44c2_s_p5_0[] = {
  127627. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  127628. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  127629. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  127630. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  127631. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  127632. 11,
  127633. };
  127634. static float _vq_quantthresh__44c2_s_p5_0[] = {
  127635. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127636. };
  127637. static long _vq_quantmap__44c2_s_p5_0[] = {
  127638. 7, 5, 3, 1, 0, 2, 4, 6,
  127639. 8,
  127640. };
  127641. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  127642. _vq_quantthresh__44c2_s_p5_0,
  127643. _vq_quantmap__44c2_s_p5_0,
  127644. 9,
  127645. 9
  127646. };
  127647. static static_codebook _44c2_s_p5_0 = {
  127648. 2, 81,
  127649. _vq_lengthlist__44c2_s_p5_0,
  127650. 1, -531628032, 1611661312, 4, 0,
  127651. _vq_quantlist__44c2_s_p5_0,
  127652. NULL,
  127653. &_vq_auxt__44c2_s_p5_0,
  127654. NULL,
  127655. 0
  127656. };
  127657. static long _vq_quantlist__44c2_s_p6_0[] = {
  127658. 8,
  127659. 7,
  127660. 9,
  127661. 6,
  127662. 10,
  127663. 5,
  127664. 11,
  127665. 4,
  127666. 12,
  127667. 3,
  127668. 13,
  127669. 2,
  127670. 14,
  127671. 1,
  127672. 15,
  127673. 0,
  127674. 16,
  127675. };
  127676. static long _vq_lengthlist__44c2_s_p6_0[] = {
  127677. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  127678. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  127679. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  127680. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  127681. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  127682. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  127683. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  127684. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  127685. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  127686. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  127687. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  127688. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  127689. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  127690. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  127691. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  127692. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  127693. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  127694. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  127695. 14,
  127696. };
  127697. static float _vq_quantthresh__44c2_s_p6_0[] = {
  127698. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127699. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127700. };
  127701. static long _vq_quantmap__44c2_s_p6_0[] = {
  127702. 15, 13, 11, 9, 7, 5, 3, 1,
  127703. 0, 2, 4, 6, 8, 10, 12, 14,
  127704. 16,
  127705. };
  127706. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  127707. _vq_quantthresh__44c2_s_p6_0,
  127708. _vq_quantmap__44c2_s_p6_0,
  127709. 17,
  127710. 17
  127711. };
  127712. static static_codebook _44c2_s_p6_0 = {
  127713. 2, 289,
  127714. _vq_lengthlist__44c2_s_p6_0,
  127715. 1, -529530880, 1611661312, 5, 0,
  127716. _vq_quantlist__44c2_s_p6_0,
  127717. NULL,
  127718. &_vq_auxt__44c2_s_p6_0,
  127719. NULL,
  127720. 0
  127721. };
  127722. static long _vq_quantlist__44c2_s_p7_0[] = {
  127723. 1,
  127724. 0,
  127725. 2,
  127726. };
  127727. static long _vq_lengthlist__44c2_s_p7_0[] = {
  127728. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  127729. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  127730. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  127731. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  127732. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  127733. 11,
  127734. };
  127735. static float _vq_quantthresh__44c2_s_p7_0[] = {
  127736. -5.5, 5.5,
  127737. };
  127738. static long _vq_quantmap__44c2_s_p7_0[] = {
  127739. 1, 0, 2,
  127740. };
  127741. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  127742. _vq_quantthresh__44c2_s_p7_0,
  127743. _vq_quantmap__44c2_s_p7_0,
  127744. 3,
  127745. 3
  127746. };
  127747. static static_codebook _44c2_s_p7_0 = {
  127748. 4, 81,
  127749. _vq_lengthlist__44c2_s_p7_0,
  127750. 1, -529137664, 1618345984, 2, 0,
  127751. _vq_quantlist__44c2_s_p7_0,
  127752. NULL,
  127753. &_vq_auxt__44c2_s_p7_0,
  127754. NULL,
  127755. 0
  127756. };
  127757. static long _vq_quantlist__44c2_s_p7_1[] = {
  127758. 5,
  127759. 4,
  127760. 6,
  127761. 3,
  127762. 7,
  127763. 2,
  127764. 8,
  127765. 1,
  127766. 9,
  127767. 0,
  127768. 10,
  127769. };
  127770. static long _vq_lengthlist__44c2_s_p7_1[] = {
  127771. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  127772. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  127773. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  127774. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  127775. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  127776. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  127777. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  127778. 10,10,10, 8, 8, 8, 8, 8, 8,
  127779. };
  127780. static float _vq_quantthresh__44c2_s_p7_1[] = {
  127781. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127782. 3.5, 4.5,
  127783. };
  127784. static long _vq_quantmap__44c2_s_p7_1[] = {
  127785. 9, 7, 5, 3, 1, 0, 2, 4,
  127786. 6, 8, 10,
  127787. };
  127788. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  127789. _vq_quantthresh__44c2_s_p7_1,
  127790. _vq_quantmap__44c2_s_p7_1,
  127791. 11,
  127792. 11
  127793. };
  127794. static static_codebook _44c2_s_p7_1 = {
  127795. 2, 121,
  127796. _vq_lengthlist__44c2_s_p7_1,
  127797. 1, -531365888, 1611661312, 4, 0,
  127798. _vq_quantlist__44c2_s_p7_1,
  127799. NULL,
  127800. &_vq_auxt__44c2_s_p7_1,
  127801. NULL,
  127802. 0
  127803. };
  127804. static long _vq_quantlist__44c2_s_p8_0[] = {
  127805. 6,
  127806. 5,
  127807. 7,
  127808. 4,
  127809. 8,
  127810. 3,
  127811. 9,
  127812. 2,
  127813. 10,
  127814. 1,
  127815. 11,
  127816. 0,
  127817. 12,
  127818. };
  127819. static long _vq_lengthlist__44c2_s_p8_0[] = {
  127820. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  127821. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  127822. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  127823. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127824. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  127825. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  127826. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  127827. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  127828. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  127829. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  127830. 0,12,12,12,12,13,12,14,14,
  127831. };
  127832. static float _vq_quantthresh__44c2_s_p8_0[] = {
  127833. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127834. 12.5, 17.5, 22.5, 27.5,
  127835. };
  127836. static long _vq_quantmap__44c2_s_p8_0[] = {
  127837. 11, 9, 7, 5, 3, 1, 0, 2,
  127838. 4, 6, 8, 10, 12,
  127839. };
  127840. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  127841. _vq_quantthresh__44c2_s_p8_0,
  127842. _vq_quantmap__44c2_s_p8_0,
  127843. 13,
  127844. 13
  127845. };
  127846. static static_codebook _44c2_s_p8_0 = {
  127847. 2, 169,
  127848. _vq_lengthlist__44c2_s_p8_0,
  127849. 1, -526516224, 1616117760, 4, 0,
  127850. _vq_quantlist__44c2_s_p8_0,
  127851. NULL,
  127852. &_vq_auxt__44c2_s_p8_0,
  127853. NULL,
  127854. 0
  127855. };
  127856. static long _vq_quantlist__44c2_s_p8_1[] = {
  127857. 2,
  127858. 1,
  127859. 3,
  127860. 0,
  127861. 4,
  127862. };
  127863. static long _vq_lengthlist__44c2_s_p8_1[] = {
  127864. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  127865. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  127866. };
  127867. static float _vq_quantthresh__44c2_s_p8_1[] = {
  127868. -1.5, -0.5, 0.5, 1.5,
  127869. };
  127870. static long _vq_quantmap__44c2_s_p8_1[] = {
  127871. 3, 1, 0, 2, 4,
  127872. };
  127873. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  127874. _vq_quantthresh__44c2_s_p8_1,
  127875. _vq_quantmap__44c2_s_p8_1,
  127876. 5,
  127877. 5
  127878. };
  127879. static static_codebook _44c2_s_p8_1 = {
  127880. 2, 25,
  127881. _vq_lengthlist__44c2_s_p8_1,
  127882. 1, -533725184, 1611661312, 3, 0,
  127883. _vq_quantlist__44c2_s_p8_1,
  127884. NULL,
  127885. &_vq_auxt__44c2_s_p8_1,
  127886. NULL,
  127887. 0
  127888. };
  127889. static long _vq_quantlist__44c2_s_p9_0[] = {
  127890. 6,
  127891. 5,
  127892. 7,
  127893. 4,
  127894. 8,
  127895. 3,
  127896. 9,
  127897. 2,
  127898. 10,
  127899. 1,
  127900. 11,
  127901. 0,
  127902. 12,
  127903. };
  127904. static long _vq_lengthlist__44c2_s_p9_0[] = {
  127905. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  127906. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  127907. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127908. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  127909. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127910. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127911. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127912. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127913. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127914. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127915. 11,11,11,11,11,11,11,11,11,
  127916. };
  127917. static float _vq_quantthresh__44c2_s_p9_0[] = {
  127918. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  127919. 552.5, 773.5, 994.5, 1215.5,
  127920. };
  127921. static long _vq_quantmap__44c2_s_p9_0[] = {
  127922. 11, 9, 7, 5, 3, 1, 0, 2,
  127923. 4, 6, 8, 10, 12,
  127924. };
  127925. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  127926. _vq_quantthresh__44c2_s_p9_0,
  127927. _vq_quantmap__44c2_s_p9_0,
  127928. 13,
  127929. 13
  127930. };
  127931. static static_codebook _44c2_s_p9_0 = {
  127932. 2, 169,
  127933. _vq_lengthlist__44c2_s_p9_0,
  127934. 1, -514541568, 1627103232, 4, 0,
  127935. _vq_quantlist__44c2_s_p9_0,
  127936. NULL,
  127937. &_vq_auxt__44c2_s_p9_0,
  127938. NULL,
  127939. 0
  127940. };
  127941. static long _vq_quantlist__44c2_s_p9_1[] = {
  127942. 6,
  127943. 5,
  127944. 7,
  127945. 4,
  127946. 8,
  127947. 3,
  127948. 9,
  127949. 2,
  127950. 10,
  127951. 1,
  127952. 11,
  127953. 0,
  127954. 12,
  127955. };
  127956. static long _vq_lengthlist__44c2_s_p9_1[] = {
  127957. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  127958. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  127959. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  127960. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  127961. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  127962. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  127963. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  127964. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  127965. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  127966. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  127967. 17,13,12,12,10,13,11,14,14,
  127968. };
  127969. static float _vq_quantthresh__44c2_s_p9_1[] = {
  127970. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  127971. 42.5, 59.5, 76.5, 93.5,
  127972. };
  127973. static long _vq_quantmap__44c2_s_p9_1[] = {
  127974. 11, 9, 7, 5, 3, 1, 0, 2,
  127975. 4, 6, 8, 10, 12,
  127976. };
  127977. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  127978. _vq_quantthresh__44c2_s_p9_1,
  127979. _vq_quantmap__44c2_s_p9_1,
  127980. 13,
  127981. 13
  127982. };
  127983. static static_codebook _44c2_s_p9_1 = {
  127984. 2, 169,
  127985. _vq_lengthlist__44c2_s_p9_1,
  127986. 1, -522616832, 1620115456, 4, 0,
  127987. _vq_quantlist__44c2_s_p9_1,
  127988. NULL,
  127989. &_vq_auxt__44c2_s_p9_1,
  127990. NULL,
  127991. 0
  127992. };
  127993. static long _vq_quantlist__44c2_s_p9_2[] = {
  127994. 8,
  127995. 7,
  127996. 9,
  127997. 6,
  127998. 10,
  127999. 5,
  128000. 11,
  128001. 4,
  128002. 12,
  128003. 3,
  128004. 13,
  128005. 2,
  128006. 14,
  128007. 1,
  128008. 15,
  128009. 0,
  128010. 16,
  128011. };
  128012. static long _vq_lengthlist__44c2_s_p9_2[] = {
  128013. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  128014. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  128015. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  128016. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  128017. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  128018. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  128019. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  128020. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  128021. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  128022. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  128023. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  128024. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  128025. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  128026. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  128027. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  128028. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  128029. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  128030. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  128031. 10,
  128032. };
  128033. static float _vq_quantthresh__44c2_s_p9_2[] = {
  128034. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128035. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128036. };
  128037. static long _vq_quantmap__44c2_s_p9_2[] = {
  128038. 15, 13, 11, 9, 7, 5, 3, 1,
  128039. 0, 2, 4, 6, 8, 10, 12, 14,
  128040. 16,
  128041. };
  128042. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  128043. _vq_quantthresh__44c2_s_p9_2,
  128044. _vq_quantmap__44c2_s_p9_2,
  128045. 17,
  128046. 17
  128047. };
  128048. static static_codebook _44c2_s_p9_2 = {
  128049. 2, 289,
  128050. _vq_lengthlist__44c2_s_p9_2,
  128051. 1, -529530880, 1611661312, 5, 0,
  128052. _vq_quantlist__44c2_s_p9_2,
  128053. NULL,
  128054. &_vq_auxt__44c2_s_p9_2,
  128055. NULL,
  128056. 0
  128057. };
  128058. static long _huff_lengthlist__44c2_s_short[] = {
  128059. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  128060. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  128061. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  128062. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  128063. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  128064. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  128065. 6, 8, 9,12,
  128066. };
  128067. static static_codebook _huff_book__44c2_s_short = {
  128068. 2, 100,
  128069. _huff_lengthlist__44c2_s_short,
  128070. 0, 0, 0, 0, 0,
  128071. NULL,
  128072. NULL,
  128073. NULL,
  128074. NULL,
  128075. 0
  128076. };
  128077. static long _huff_lengthlist__44c3_s_long[] = {
  128078. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  128079. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  128080. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  128081. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  128082. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  128083. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  128084. 9, 8, 8, 8,
  128085. };
  128086. static static_codebook _huff_book__44c3_s_long = {
  128087. 2, 100,
  128088. _huff_lengthlist__44c3_s_long,
  128089. 0, 0, 0, 0, 0,
  128090. NULL,
  128091. NULL,
  128092. NULL,
  128093. NULL,
  128094. 0
  128095. };
  128096. static long _vq_quantlist__44c3_s_p1_0[] = {
  128097. 1,
  128098. 0,
  128099. 2,
  128100. };
  128101. static long _vq_lengthlist__44c3_s_p1_0[] = {
  128102. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  128103. 0, 0, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128107. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  128108. 0, 0, 0, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128112. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  128113. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  128148. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  128149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  128153. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  128154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  128158. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  128159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128193. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  128194. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128198. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  128199. 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  128200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128203. 0, 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  128204. 0, 0, 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 0,
  128205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128512. 0,
  128513. };
  128514. static float _vq_quantthresh__44c3_s_p1_0[] = {
  128515. -0.5, 0.5,
  128516. };
  128517. static long _vq_quantmap__44c3_s_p1_0[] = {
  128518. 1, 0, 2,
  128519. };
  128520. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  128521. _vq_quantthresh__44c3_s_p1_0,
  128522. _vq_quantmap__44c3_s_p1_0,
  128523. 3,
  128524. 3
  128525. };
  128526. static static_codebook _44c3_s_p1_0 = {
  128527. 8, 6561,
  128528. _vq_lengthlist__44c3_s_p1_0,
  128529. 1, -535822336, 1611661312, 2, 0,
  128530. _vq_quantlist__44c3_s_p1_0,
  128531. NULL,
  128532. &_vq_auxt__44c3_s_p1_0,
  128533. NULL,
  128534. 0
  128535. };
  128536. static long _vq_quantlist__44c3_s_p2_0[] = {
  128537. 2,
  128538. 1,
  128539. 3,
  128540. 0,
  128541. 4,
  128542. };
  128543. static long _vq_lengthlist__44c3_s_p2_0[] = {
  128544. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  128545. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  128546. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  128547. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  128548. 0, 0,10,10, 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, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  128554. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  128555. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  128556. 9, 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, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  128562. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  128563. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 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. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  128570. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  128571. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 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,
  128584. };
  128585. static float _vq_quantthresh__44c3_s_p2_0[] = {
  128586. -1.5, -0.5, 0.5, 1.5,
  128587. };
  128588. static long _vq_quantmap__44c3_s_p2_0[] = {
  128589. 3, 1, 0, 2, 4,
  128590. };
  128591. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  128592. _vq_quantthresh__44c3_s_p2_0,
  128593. _vq_quantmap__44c3_s_p2_0,
  128594. 5,
  128595. 5
  128596. };
  128597. static static_codebook _44c3_s_p2_0 = {
  128598. 4, 625,
  128599. _vq_lengthlist__44c3_s_p2_0,
  128600. 1, -533725184, 1611661312, 3, 0,
  128601. _vq_quantlist__44c3_s_p2_0,
  128602. NULL,
  128603. &_vq_auxt__44c3_s_p2_0,
  128604. NULL,
  128605. 0
  128606. };
  128607. static long _vq_quantlist__44c3_s_p3_0[] = {
  128608. 2,
  128609. 1,
  128610. 3,
  128611. 0,
  128612. 4,
  128613. };
  128614. static long _vq_lengthlist__44c3_s_p3_0[] = {
  128615. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  128617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128618. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  128620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128621. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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,
  128655. };
  128656. static float _vq_quantthresh__44c3_s_p3_0[] = {
  128657. -1.5, -0.5, 0.5, 1.5,
  128658. };
  128659. static long _vq_quantmap__44c3_s_p3_0[] = {
  128660. 3, 1, 0, 2, 4,
  128661. };
  128662. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  128663. _vq_quantthresh__44c3_s_p3_0,
  128664. _vq_quantmap__44c3_s_p3_0,
  128665. 5,
  128666. 5
  128667. };
  128668. static static_codebook _44c3_s_p3_0 = {
  128669. 4, 625,
  128670. _vq_lengthlist__44c3_s_p3_0,
  128671. 1, -533725184, 1611661312, 3, 0,
  128672. _vq_quantlist__44c3_s_p3_0,
  128673. NULL,
  128674. &_vq_auxt__44c3_s_p3_0,
  128675. NULL,
  128676. 0
  128677. };
  128678. static long _vq_quantlist__44c3_s_p4_0[] = {
  128679. 4,
  128680. 3,
  128681. 5,
  128682. 2,
  128683. 6,
  128684. 1,
  128685. 7,
  128686. 0,
  128687. 8,
  128688. };
  128689. static long _vq_lengthlist__44c3_s_p4_0[] = {
  128690. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  128691. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  128692. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  128693. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  128694. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128695. 0,
  128696. };
  128697. static float _vq_quantthresh__44c3_s_p4_0[] = {
  128698. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128699. };
  128700. static long _vq_quantmap__44c3_s_p4_0[] = {
  128701. 7, 5, 3, 1, 0, 2, 4, 6,
  128702. 8,
  128703. };
  128704. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  128705. _vq_quantthresh__44c3_s_p4_0,
  128706. _vq_quantmap__44c3_s_p4_0,
  128707. 9,
  128708. 9
  128709. };
  128710. static static_codebook _44c3_s_p4_0 = {
  128711. 2, 81,
  128712. _vq_lengthlist__44c3_s_p4_0,
  128713. 1, -531628032, 1611661312, 4, 0,
  128714. _vq_quantlist__44c3_s_p4_0,
  128715. NULL,
  128716. &_vq_auxt__44c3_s_p4_0,
  128717. NULL,
  128718. 0
  128719. };
  128720. static long _vq_quantlist__44c3_s_p5_0[] = {
  128721. 4,
  128722. 3,
  128723. 5,
  128724. 2,
  128725. 6,
  128726. 1,
  128727. 7,
  128728. 0,
  128729. 8,
  128730. };
  128731. static long _vq_lengthlist__44c3_s_p5_0[] = {
  128732. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  128733. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  128734. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  128735. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  128736. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  128737. 11,
  128738. };
  128739. static float _vq_quantthresh__44c3_s_p5_0[] = {
  128740. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128741. };
  128742. static long _vq_quantmap__44c3_s_p5_0[] = {
  128743. 7, 5, 3, 1, 0, 2, 4, 6,
  128744. 8,
  128745. };
  128746. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  128747. _vq_quantthresh__44c3_s_p5_0,
  128748. _vq_quantmap__44c3_s_p5_0,
  128749. 9,
  128750. 9
  128751. };
  128752. static static_codebook _44c3_s_p5_0 = {
  128753. 2, 81,
  128754. _vq_lengthlist__44c3_s_p5_0,
  128755. 1, -531628032, 1611661312, 4, 0,
  128756. _vq_quantlist__44c3_s_p5_0,
  128757. NULL,
  128758. &_vq_auxt__44c3_s_p5_0,
  128759. NULL,
  128760. 0
  128761. };
  128762. static long _vq_quantlist__44c3_s_p6_0[] = {
  128763. 8,
  128764. 7,
  128765. 9,
  128766. 6,
  128767. 10,
  128768. 5,
  128769. 11,
  128770. 4,
  128771. 12,
  128772. 3,
  128773. 13,
  128774. 2,
  128775. 14,
  128776. 1,
  128777. 15,
  128778. 0,
  128779. 16,
  128780. };
  128781. static long _vq_lengthlist__44c3_s_p6_0[] = {
  128782. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  128783. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  128784. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  128785. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  128786. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  128787. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  128788. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  128789. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  128790. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  128791. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  128792. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  128793. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  128794. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  128795. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  128796. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  128797. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  128798. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  128799. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  128800. 13,
  128801. };
  128802. static float _vq_quantthresh__44c3_s_p6_0[] = {
  128803. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128804. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128805. };
  128806. static long _vq_quantmap__44c3_s_p6_0[] = {
  128807. 15, 13, 11, 9, 7, 5, 3, 1,
  128808. 0, 2, 4, 6, 8, 10, 12, 14,
  128809. 16,
  128810. };
  128811. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  128812. _vq_quantthresh__44c3_s_p6_0,
  128813. _vq_quantmap__44c3_s_p6_0,
  128814. 17,
  128815. 17
  128816. };
  128817. static static_codebook _44c3_s_p6_0 = {
  128818. 2, 289,
  128819. _vq_lengthlist__44c3_s_p6_0,
  128820. 1, -529530880, 1611661312, 5, 0,
  128821. _vq_quantlist__44c3_s_p6_0,
  128822. NULL,
  128823. &_vq_auxt__44c3_s_p6_0,
  128824. NULL,
  128825. 0
  128826. };
  128827. static long _vq_quantlist__44c3_s_p7_0[] = {
  128828. 1,
  128829. 0,
  128830. 2,
  128831. };
  128832. static long _vq_lengthlist__44c3_s_p7_0[] = {
  128833. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  128834. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  128835. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  128836. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  128837. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  128838. 10,
  128839. };
  128840. static float _vq_quantthresh__44c3_s_p7_0[] = {
  128841. -5.5, 5.5,
  128842. };
  128843. static long _vq_quantmap__44c3_s_p7_0[] = {
  128844. 1, 0, 2,
  128845. };
  128846. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  128847. _vq_quantthresh__44c3_s_p7_0,
  128848. _vq_quantmap__44c3_s_p7_0,
  128849. 3,
  128850. 3
  128851. };
  128852. static static_codebook _44c3_s_p7_0 = {
  128853. 4, 81,
  128854. _vq_lengthlist__44c3_s_p7_0,
  128855. 1, -529137664, 1618345984, 2, 0,
  128856. _vq_quantlist__44c3_s_p7_0,
  128857. NULL,
  128858. &_vq_auxt__44c3_s_p7_0,
  128859. NULL,
  128860. 0
  128861. };
  128862. static long _vq_quantlist__44c3_s_p7_1[] = {
  128863. 5,
  128864. 4,
  128865. 6,
  128866. 3,
  128867. 7,
  128868. 2,
  128869. 8,
  128870. 1,
  128871. 9,
  128872. 0,
  128873. 10,
  128874. };
  128875. static long _vq_lengthlist__44c3_s_p7_1[] = {
  128876. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  128877. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  128878. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  128879. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  128880. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  128881. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  128882. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  128883. 10,10,10, 8, 8, 8, 8, 8, 8,
  128884. };
  128885. static float _vq_quantthresh__44c3_s_p7_1[] = {
  128886. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128887. 3.5, 4.5,
  128888. };
  128889. static long _vq_quantmap__44c3_s_p7_1[] = {
  128890. 9, 7, 5, 3, 1, 0, 2, 4,
  128891. 6, 8, 10,
  128892. };
  128893. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  128894. _vq_quantthresh__44c3_s_p7_1,
  128895. _vq_quantmap__44c3_s_p7_1,
  128896. 11,
  128897. 11
  128898. };
  128899. static static_codebook _44c3_s_p7_1 = {
  128900. 2, 121,
  128901. _vq_lengthlist__44c3_s_p7_1,
  128902. 1, -531365888, 1611661312, 4, 0,
  128903. _vq_quantlist__44c3_s_p7_1,
  128904. NULL,
  128905. &_vq_auxt__44c3_s_p7_1,
  128906. NULL,
  128907. 0
  128908. };
  128909. static long _vq_quantlist__44c3_s_p8_0[] = {
  128910. 6,
  128911. 5,
  128912. 7,
  128913. 4,
  128914. 8,
  128915. 3,
  128916. 9,
  128917. 2,
  128918. 10,
  128919. 1,
  128920. 11,
  128921. 0,
  128922. 12,
  128923. };
  128924. static long _vq_lengthlist__44c3_s_p8_0[] = {
  128925. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  128926. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  128927. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  128928. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  128929. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  128930. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  128931. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  128932. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  128933. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  128934. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  128935. 0,13,13,12,12,13,12,14,13,
  128936. };
  128937. static float _vq_quantthresh__44c3_s_p8_0[] = {
  128938. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  128939. 12.5, 17.5, 22.5, 27.5,
  128940. };
  128941. static long _vq_quantmap__44c3_s_p8_0[] = {
  128942. 11, 9, 7, 5, 3, 1, 0, 2,
  128943. 4, 6, 8, 10, 12,
  128944. };
  128945. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  128946. _vq_quantthresh__44c3_s_p8_0,
  128947. _vq_quantmap__44c3_s_p8_0,
  128948. 13,
  128949. 13
  128950. };
  128951. static static_codebook _44c3_s_p8_0 = {
  128952. 2, 169,
  128953. _vq_lengthlist__44c3_s_p8_0,
  128954. 1, -526516224, 1616117760, 4, 0,
  128955. _vq_quantlist__44c3_s_p8_0,
  128956. NULL,
  128957. &_vq_auxt__44c3_s_p8_0,
  128958. NULL,
  128959. 0
  128960. };
  128961. static long _vq_quantlist__44c3_s_p8_1[] = {
  128962. 2,
  128963. 1,
  128964. 3,
  128965. 0,
  128966. 4,
  128967. };
  128968. static long _vq_lengthlist__44c3_s_p8_1[] = {
  128969. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  128970. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  128971. };
  128972. static float _vq_quantthresh__44c3_s_p8_1[] = {
  128973. -1.5, -0.5, 0.5, 1.5,
  128974. };
  128975. static long _vq_quantmap__44c3_s_p8_1[] = {
  128976. 3, 1, 0, 2, 4,
  128977. };
  128978. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  128979. _vq_quantthresh__44c3_s_p8_1,
  128980. _vq_quantmap__44c3_s_p8_1,
  128981. 5,
  128982. 5
  128983. };
  128984. static static_codebook _44c3_s_p8_1 = {
  128985. 2, 25,
  128986. _vq_lengthlist__44c3_s_p8_1,
  128987. 1, -533725184, 1611661312, 3, 0,
  128988. _vq_quantlist__44c3_s_p8_1,
  128989. NULL,
  128990. &_vq_auxt__44c3_s_p8_1,
  128991. NULL,
  128992. 0
  128993. };
  128994. static long _vq_quantlist__44c3_s_p9_0[] = {
  128995. 6,
  128996. 5,
  128997. 7,
  128998. 4,
  128999. 8,
  129000. 3,
  129001. 9,
  129002. 2,
  129003. 10,
  129004. 1,
  129005. 11,
  129006. 0,
  129007. 12,
  129008. };
  129009. static long _vq_lengthlist__44c3_s_p9_0[] = {
  129010. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  129011. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  129012. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129013. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  129014. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129015. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129016. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129017. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129018. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  129019. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129020. 11,11,11,11,11,11,11,11,11,
  129021. };
  129022. static float _vq_quantthresh__44c3_s_p9_0[] = {
  129023. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  129024. 637.5, 892.5, 1147.5, 1402.5,
  129025. };
  129026. static long _vq_quantmap__44c3_s_p9_0[] = {
  129027. 11, 9, 7, 5, 3, 1, 0, 2,
  129028. 4, 6, 8, 10, 12,
  129029. };
  129030. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  129031. _vq_quantthresh__44c3_s_p9_0,
  129032. _vq_quantmap__44c3_s_p9_0,
  129033. 13,
  129034. 13
  129035. };
  129036. static static_codebook _44c3_s_p9_0 = {
  129037. 2, 169,
  129038. _vq_lengthlist__44c3_s_p9_0,
  129039. 1, -514332672, 1627381760, 4, 0,
  129040. _vq_quantlist__44c3_s_p9_0,
  129041. NULL,
  129042. &_vq_auxt__44c3_s_p9_0,
  129043. NULL,
  129044. 0
  129045. };
  129046. static long _vq_quantlist__44c3_s_p9_1[] = {
  129047. 7,
  129048. 6,
  129049. 8,
  129050. 5,
  129051. 9,
  129052. 4,
  129053. 10,
  129054. 3,
  129055. 11,
  129056. 2,
  129057. 12,
  129058. 1,
  129059. 13,
  129060. 0,
  129061. 14,
  129062. };
  129063. static long _vq_lengthlist__44c3_s_p9_1[] = {
  129064. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  129065. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  129066. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  129067. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  129068. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  129069. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  129070. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  129071. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  129072. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  129073. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  129074. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  129075. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  129076. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  129077. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  129078. 15,
  129079. };
  129080. static float _vq_quantthresh__44c3_s_p9_1[] = {
  129081. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  129082. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  129083. };
  129084. static long _vq_quantmap__44c3_s_p9_1[] = {
  129085. 13, 11, 9, 7, 5, 3, 1, 0,
  129086. 2, 4, 6, 8, 10, 12, 14,
  129087. };
  129088. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  129089. _vq_quantthresh__44c3_s_p9_1,
  129090. _vq_quantmap__44c3_s_p9_1,
  129091. 15,
  129092. 15
  129093. };
  129094. static static_codebook _44c3_s_p9_1 = {
  129095. 2, 225,
  129096. _vq_lengthlist__44c3_s_p9_1,
  129097. 1, -522338304, 1620115456, 4, 0,
  129098. _vq_quantlist__44c3_s_p9_1,
  129099. NULL,
  129100. &_vq_auxt__44c3_s_p9_1,
  129101. NULL,
  129102. 0
  129103. };
  129104. static long _vq_quantlist__44c3_s_p9_2[] = {
  129105. 8,
  129106. 7,
  129107. 9,
  129108. 6,
  129109. 10,
  129110. 5,
  129111. 11,
  129112. 4,
  129113. 12,
  129114. 3,
  129115. 13,
  129116. 2,
  129117. 14,
  129118. 1,
  129119. 15,
  129120. 0,
  129121. 16,
  129122. };
  129123. static long _vq_lengthlist__44c3_s_p9_2[] = {
  129124. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  129125. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  129126. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  129127. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  129128. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  129129. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  129130. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  129131. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  129132. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  129133. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  129134. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  129135. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  129136. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  129137. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  129138. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  129139. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  129140. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  129141. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  129142. 10,
  129143. };
  129144. static float _vq_quantthresh__44c3_s_p9_2[] = {
  129145. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129146. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129147. };
  129148. static long _vq_quantmap__44c3_s_p9_2[] = {
  129149. 15, 13, 11, 9, 7, 5, 3, 1,
  129150. 0, 2, 4, 6, 8, 10, 12, 14,
  129151. 16,
  129152. };
  129153. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  129154. _vq_quantthresh__44c3_s_p9_2,
  129155. _vq_quantmap__44c3_s_p9_2,
  129156. 17,
  129157. 17
  129158. };
  129159. static static_codebook _44c3_s_p9_2 = {
  129160. 2, 289,
  129161. _vq_lengthlist__44c3_s_p9_2,
  129162. 1, -529530880, 1611661312, 5, 0,
  129163. _vq_quantlist__44c3_s_p9_2,
  129164. NULL,
  129165. &_vq_auxt__44c3_s_p9_2,
  129166. NULL,
  129167. 0
  129168. };
  129169. static long _huff_lengthlist__44c3_s_short[] = {
  129170. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  129171. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  129172. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  129173. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  129174. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  129175. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  129176. 6, 8, 9,11,
  129177. };
  129178. static static_codebook _huff_book__44c3_s_short = {
  129179. 2, 100,
  129180. _huff_lengthlist__44c3_s_short,
  129181. 0, 0, 0, 0, 0,
  129182. NULL,
  129183. NULL,
  129184. NULL,
  129185. NULL,
  129186. 0
  129187. };
  129188. static long _huff_lengthlist__44c4_s_long[] = {
  129189. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  129190. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  129191. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  129192. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  129193. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  129194. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  129195. 9, 8, 7, 7,
  129196. };
  129197. static static_codebook _huff_book__44c4_s_long = {
  129198. 2, 100,
  129199. _huff_lengthlist__44c4_s_long,
  129200. 0, 0, 0, 0, 0,
  129201. NULL,
  129202. NULL,
  129203. NULL,
  129204. NULL,
  129205. 0
  129206. };
  129207. static long _vq_quantlist__44c4_s_p1_0[] = {
  129208. 1,
  129209. 0,
  129210. 2,
  129211. };
  129212. static long _vq_lengthlist__44c4_s_p1_0[] = {
  129213. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  129214. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129218. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  129219. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129223. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  129224. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  129259. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  129260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  129264. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  129269. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129304. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  129305. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129309. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129310. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  129311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129314. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129315. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  129316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129586. 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129623. 0,
  129624. };
  129625. static float _vq_quantthresh__44c4_s_p1_0[] = {
  129626. -0.5, 0.5,
  129627. };
  129628. static long _vq_quantmap__44c4_s_p1_0[] = {
  129629. 1, 0, 2,
  129630. };
  129631. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  129632. _vq_quantthresh__44c4_s_p1_0,
  129633. _vq_quantmap__44c4_s_p1_0,
  129634. 3,
  129635. 3
  129636. };
  129637. static static_codebook _44c4_s_p1_0 = {
  129638. 8, 6561,
  129639. _vq_lengthlist__44c4_s_p1_0,
  129640. 1, -535822336, 1611661312, 2, 0,
  129641. _vq_quantlist__44c4_s_p1_0,
  129642. NULL,
  129643. &_vq_auxt__44c4_s_p1_0,
  129644. NULL,
  129645. 0
  129646. };
  129647. static long _vq_quantlist__44c4_s_p2_0[] = {
  129648. 2,
  129649. 1,
  129650. 3,
  129651. 0,
  129652. 4,
  129653. };
  129654. static long _vq_lengthlist__44c4_s_p2_0[] = {
  129655. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  129656. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  129657. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129658. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  129659. 0, 0,10,10, 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, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  129665. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  129666. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  129667. 9, 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, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  129673. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  129674. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 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. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  129681. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  129682. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 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,
  129695. };
  129696. static float _vq_quantthresh__44c4_s_p2_0[] = {
  129697. -1.5, -0.5, 0.5, 1.5,
  129698. };
  129699. static long _vq_quantmap__44c4_s_p2_0[] = {
  129700. 3, 1, 0, 2, 4,
  129701. };
  129702. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  129703. _vq_quantthresh__44c4_s_p2_0,
  129704. _vq_quantmap__44c4_s_p2_0,
  129705. 5,
  129706. 5
  129707. };
  129708. static static_codebook _44c4_s_p2_0 = {
  129709. 4, 625,
  129710. _vq_lengthlist__44c4_s_p2_0,
  129711. 1, -533725184, 1611661312, 3, 0,
  129712. _vq_quantlist__44c4_s_p2_0,
  129713. NULL,
  129714. &_vq_auxt__44c4_s_p2_0,
  129715. NULL,
  129716. 0
  129717. };
  129718. static long _vq_quantlist__44c4_s_p3_0[] = {
  129719. 2,
  129720. 1,
  129721. 3,
  129722. 0,
  129723. 4,
  129724. };
  129725. static long _vq_lengthlist__44c4_s_p3_0[] = {
  129726. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  129728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129729. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  129731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129732. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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,
  129766. };
  129767. static float _vq_quantthresh__44c4_s_p3_0[] = {
  129768. -1.5, -0.5, 0.5, 1.5,
  129769. };
  129770. static long _vq_quantmap__44c4_s_p3_0[] = {
  129771. 3, 1, 0, 2, 4,
  129772. };
  129773. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  129774. _vq_quantthresh__44c4_s_p3_0,
  129775. _vq_quantmap__44c4_s_p3_0,
  129776. 5,
  129777. 5
  129778. };
  129779. static static_codebook _44c4_s_p3_0 = {
  129780. 4, 625,
  129781. _vq_lengthlist__44c4_s_p3_0,
  129782. 1, -533725184, 1611661312, 3, 0,
  129783. _vq_quantlist__44c4_s_p3_0,
  129784. NULL,
  129785. &_vq_auxt__44c4_s_p3_0,
  129786. NULL,
  129787. 0
  129788. };
  129789. static long _vq_quantlist__44c4_s_p4_0[] = {
  129790. 4,
  129791. 3,
  129792. 5,
  129793. 2,
  129794. 6,
  129795. 1,
  129796. 7,
  129797. 0,
  129798. 8,
  129799. };
  129800. static long _vq_lengthlist__44c4_s_p4_0[] = {
  129801. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  129802. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  129803. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  129804. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  129805. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129806. 0,
  129807. };
  129808. static float _vq_quantthresh__44c4_s_p4_0[] = {
  129809. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129810. };
  129811. static long _vq_quantmap__44c4_s_p4_0[] = {
  129812. 7, 5, 3, 1, 0, 2, 4, 6,
  129813. 8,
  129814. };
  129815. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  129816. _vq_quantthresh__44c4_s_p4_0,
  129817. _vq_quantmap__44c4_s_p4_0,
  129818. 9,
  129819. 9
  129820. };
  129821. static static_codebook _44c4_s_p4_0 = {
  129822. 2, 81,
  129823. _vq_lengthlist__44c4_s_p4_0,
  129824. 1, -531628032, 1611661312, 4, 0,
  129825. _vq_quantlist__44c4_s_p4_0,
  129826. NULL,
  129827. &_vq_auxt__44c4_s_p4_0,
  129828. NULL,
  129829. 0
  129830. };
  129831. static long _vq_quantlist__44c4_s_p5_0[] = {
  129832. 4,
  129833. 3,
  129834. 5,
  129835. 2,
  129836. 6,
  129837. 1,
  129838. 7,
  129839. 0,
  129840. 8,
  129841. };
  129842. static long _vq_lengthlist__44c4_s_p5_0[] = {
  129843. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  129844. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  129845. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  129846. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  129847. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  129848. 10,
  129849. };
  129850. static float _vq_quantthresh__44c4_s_p5_0[] = {
  129851. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129852. };
  129853. static long _vq_quantmap__44c4_s_p5_0[] = {
  129854. 7, 5, 3, 1, 0, 2, 4, 6,
  129855. 8,
  129856. };
  129857. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  129858. _vq_quantthresh__44c4_s_p5_0,
  129859. _vq_quantmap__44c4_s_p5_0,
  129860. 9,
  129861. 9
  129862. };
  129863. static static_codebook _44c4_s_p5_0 = {
  129864. 2, 81,
  129865. _vq_lengthlist__44c4_s_p5_0,
  129866. 1, -531628032, 1611661312, 4, 0,
  129867. _vq_quantlist__44c4_s_p5_0,
  129868. NULL,
  129869. &_vq_auxt__44c4_s_p5_0,
  129870. NULL,
  129871. 0
  129872. };
  129873. static long _vq_quantlist__44c4_s_p6_0[] = {
  129874. 8,
  129875. 7,
  129876. 9,
  129877. 6,
  129878. 10,
  129879. 5,
  129880. 11,
  129881. 4,
  129882. 12,
  129883. 3,
  129884. 13,
  129885. 2,
  129886. 14,
  129887. 1,
  129888. 15,
  129889. 0,
  129890. 16,
  129891. };
  129892. static long _vq_lengthlist__44c4_s_p6_0[] = {
  129893. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  129894. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  129895. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  129896. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  129897. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  129898. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129899. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  129900. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  129901. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  129902. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  129903. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  129904. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  129905. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  129906. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  129907. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  129908. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  129909. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  129910. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  129911. 13,
  129912. };
  129913. static float _vq_quantthresh__44c4_s_p6_0[] = {
  129914. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129915. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129916. };
  129917. static long _vq_quantmap__44c4_s_p6_0[] = {
  129918. 15, 13, 11, 9, 7, 5, 3, 1,
  129919. 0, 2, 4, 6, 8, 10, 12, 14,
  129920. 16,
  129921. };
  129922. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  129923. _vq_quantthresh__44c4_s_p6_0,
  129924. _vq_quantmap__44c4_s_p6_0,
  129925. 17,
  129926. 17
  129927. };
  129928. static static_codebook _44c4_s_p6_0 = {
  129929. 2, 289,
  129930. _vq_lengthlist__44c4_s_p6_0,
  129931. 1, -529530880, 1611661312, 5, 0,
  129932. _vq_quantlist__44c4_s_p6_0,
  129933. NULL,
  129934. &_vq_auxt__44c4_s_p6_0,
  129935. NULL,
  129936. 0
  129937. };
  129938. static long _vq_quantlist__44c4_s_p7_0[] = {
  129939. 1,
  129940. 0,
  129941. 2,
  129942. };
  129943. static long _vq_lengthlist__44c4_s_p7_0[] = {
  129944. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  129945. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  129946. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  129947. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  129948. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  129949. 10,
  129950. };
  129951. static float _vq_quantthresh__44c4_s_p7_0[] = {
  129952. -5.5, 5.5,
  129953. };
  129954. static long _vq_quantmap__44c4_s_p7_0[] = {
  129955. 1, 0, 2,
  129956. };
  129957. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  129958. _vq_quantthresh__44c4_s_p7_0,
  129959. _vq_quantmap__44c4_s_p7_0,
  129960. 3,
  129961. 3
  129962. };
  129963. static static_codebook _44c4_s_p7_0 = {
  129964. 4, 81,
  129965. _vq_lengthlist__44c4_s_p7_0,
  129966. 1, -529137664, 1618345984, 2, 0,
  129967. _vq_quantlist__44c4_s_p7_0,
  129968. NULL,
  129969. &_vq_auxt__44c4_s_p7_0,
  129970. NULL,
  129971. 0
  129972. };
  129973. static long _vq_quantlist__44c4_s_p7_1[] = {
  129974. 5,
  129975. 4,
  129976. 6,
  129977. 3,
  129978. 7,
  129979. 2,
  129980. 8,
  129981. 1,
  129982. 9,
  129983. 0,
  129984. 10,
  129985. };
  129986. static long _vq_lengthlist__44c4_s_p7_1[] = {
  129987. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  129988. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  129989. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  129990. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  129991. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  129992. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  129993. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  129994. 10,10,10, 8, 8, 8, 8, 9, 9,
  129995. };
  129996. static float _vq_quantthresh__44c4_s_p7_1[] = {
  129997. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129998. 3.5, 4.5,
  129999. };
  130000. static long _vq_quantmap__44c4_s_p7_1[] = {
  130001. 9, 7, 5, 3, 1, 0, 2, 4,
  130002. 6, 8, 10,
  130003. };
  130004. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  130005. _vq_quantthresh__44c4_s_p7_1,
  130006. _vq_quantmap__44c4_s_p7_1,
  130007. 11,
  130008. 11
  130009. };
  130010. static static_codebook _44c4_s_p7_1 = {
  130011. 2, 121,
  130012. _vq_lengthlist__44c4_s_p7_1,
  130013. 1, -531365888, 1611661312, 4, 0,
  130014. _vq_quantlist__44c4_s_p7_1,
  130015. NULL,
  130016. &_vq_auxt__44c4_s_p7_1,
  130017. NULL,
  130018. 0
  130019. };
  130020. static long _vq_quantlist__44c4_s_p8_0[] = {
  130021. 6,
  130022. 5,
  130023. 7,
  130024. 4,
  130025. 8,
  130026. 3,
  130027. 9,
  130028. 2,
  130029. 10,
  130030. 1,
  130031. 11,
  130032. 0,
  130033. 12,
  130034. };
  130035. static long _vq_lengthlist__44c4_s_p8_0[] = {
  130036. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  130037. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  130038. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130039. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  130040. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  130041. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  130042. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  130043. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  130044. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  130045. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  130046. 0,13,12,12,12,12,12,13,13,
  130047. };
  130048. static float _vq_quantthresh__44c4_s_p8_0[] = {
  130049. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  130050. 12.5, 17.5, 22.5, 27.5,
  130051. };
  130052. static long _vq_quantmap__44c4_s_p8_0[] = {
  130053. 11, 9, 7, 5, 3, 1, 0, 2,
  130054. 4, 6, 8, 10, 12,
  130055. };
  130056. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  130057. _vq_quantthresh__44c4_s_p8_0,
  130058. _vq_quantmap__44c4_s_p8_0,
  130059. 13,
  130060. 13
  130061. };
  130062. static static_codebook _44c4_s_p8_0 = {
  130063. 2, 169,
  130064. _vq_lengthlist__44c4_s_p8_0,
  130065. 1, -526516224, 1616117760, 4, 0,
  130066. _vq_quantlist__44c4_s_p8_0,
  130067. NULL,
  130068. &_vq_auxt__44c4_s_p8_0,
  130069. NULL,
  130070. 0
  130071. };
  130072. static long _vq_quantlist__44c4_s_p8_1[] = {
  130073. 2,
  130074. 1,
  130075. 3,
  130076. 0,
  130077. 4,
  130078. };
  130079. static long _vq_lengthlist__44c4_s_p8_1[] = {
  130080. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  130081. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  130082. };
  130083. static float _vq_quantthresh__44c4_s_p8_1[] = {
  130084. -1.5, -0.5, 0.5, 1.5,
  130085. };
  130086. static long _vq_quantmap__44c4_s_p8_1[] = {
  130087. 3, 1, 0, 2, 4,
  130088. };
  130089. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  130090. _vq_quantthresh__44c4_s_p8_1,
  130091. _vq_quantmap__44c4_s_p8_1,
  130092. 5,
  130093. 5
  130094. };
  130095. static static_codebook _44c4_s_p8_1 = {
  130096. 2, 25,
  130097. _vq_lengthlist__44c4_s_p8_1,
  130098. 1, -533725184, 1611661312, 3, 0,
  130099. _vq_quantlist__44c4_s_p8_1,
  130100. NULL,
  130101. &_vq_auxt__44c4_s_p8_1,
  130102. NULL,
  130103. 0
  130104. };
  130105. static long _vq_quantlist__44c4_s_p9_0[] = {
  130106. 6,
  130107. 5,
  130108. 7,
  130109. 4,
  130110. 8,
  130111. 3,
  130112. 9,
  130113. 2,
  130114. 10,
  130115. 1,
  130116. 11,
  130117. 0,
  130118. 12,
  130119. };
  130120. static long _vq_lengthlist__44c4_s_p9_0[] = {
  130121. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  130122. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  130123. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130124. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130125. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130126. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130127. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130128. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130129. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130130. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130131. 12,12,12,12,12,12,12,12,12,
  130132. };
  130133. static float _vq_quantthresh__44c4_s_p9_0[] = {
  130134. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  130135. 787.5, 1102.5, 1417.5, 1732.5,
  130136. };
  130137. static long _vq_quantmap__44c4_s_p9_0[] = {
  130138. 11, 9, 7, 5, 3, 1, 0, 2,
  130139. 4, 6, 8, 10, 12,
  130140. };
  130141. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  130142. _vq_quantthresh__44c4_s_p9_0,
  130143. _vq_quantmap__44c4_s_p9_0,
  130144. 13,
  130145. 13
  130146. };
  130147. static static_codebook _44c4_s_p9_0 = {
  130148. 2, 169,
  130149. _vq_lengthlist__44c4_s_p9_0,
  130150. 1, -513964032, 1628680192, 4, 0,
  130151. _vq_quantlist__44c4_s_p9_0,
  130152. NULL,
  130153. &_vq_auxt__44c4_s_p9_0,
  130154. NULL,
  130155. 0
  130156. };
  130157. static long _vq_quantlist__44c4_s_p9_1[] = {
  130158. 7,
  130159. 6,
  130160. 8,
  130161. 5,
  130162. 9,
  130163. 4,
  130164. 10,
  130165. 3,
  130166. 11,
  130167. 2,
  130168. 12,
  130169. 1,
  130170. 13,
  130171. 0,
  130172. 14,
  130173. };
  130174. static long _vq_lengthlist__44c4_s_p9_1[] = {
  130175. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  130176. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  130177. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  130178. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  130179. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  130180. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  130181. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  130182. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  130183. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  130184. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  130185. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  130186. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  130187. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  130188. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  130189. 15,
  130190. };
  130191. static float _vq_quantthresh__44c4_s_p9_1[] = {
  130192. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  130193. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  130194. };
  130195. static long _vq_quantmap__44c4_s_p9_1[] = {
  130196. 13, 11, 9, 7, 5, 3, 1, 0,
  130197. 2, 4, 6, 8, 10, 12, 14,
  130198. };
  130199. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  130200. _vq_quantthresh__44c4_s_p9_1,
  130201. _vq_quantmap__44c4_s_p9_1,
  130202. 15,
  130203. 15
  130204. };
  130205. static static_codebook _44c4_s_p9_1 = {
  130206. 2, 225,
  130207. _vq_lengthlist__44c4_s_p9_1,
  130208. 1, -520986624, 1620377600, 4, 0,
  130209. _vq_quantlist__44c4_s_p9_1,
  130210. NULL,
  130211. &_vq_auxt__44c4_s_p9_1,
  130212. NULL,
  130213. 0
  130214. };
  130215. static long _vq_quantlist__44c4_s_p9_2[] = {
  130216. 10,
  130217. 9,
  130218. 11,
  130219. 8,
  130220. 12,
  130221. 7,
  130222. 13,
  130223. 6,
  130224. 14,
  130225. 5,
  130226. 15,
  130227. 4,
  130228. 16,
  130229. 3,
  130230. 17,
  130231. 2,
  130232. 18,
  130233. 1,
  130234. 19,
  130235. 0,
  130236. 20,
  130237. };
  130238. static long _vq_lengthlist__44c4_s_p9_2[] = {
  130239. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  130240. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  130241. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  130242. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  130243. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  130244. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  130245. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  130246. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  130247. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  130248. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  130249. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  130250. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  130251. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  130252. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  130253. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  130254. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  130255. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  130256. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  130257. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  130258. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  130259. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130260. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  130261. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  130262. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  130263. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  130264. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  130265. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  130266. 10,10,10,10,10,10,10,10,10,
  130267. };
  130268. static float _vq_quantthresh__44c4_s_p9_2[] = {
  130269. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  130270. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  130271. 6.5, 7.5, 8.5, 9.5,
  130272. };
  130273. static long _vq_quantmap__44c4_s_p9_2[] = {
  130274. 19, 17, 15, 13, 11, 9, 7, 5,
  130275. 3, 1, 0, 2, 4, 6, 8, 10,
  130276. 12, 14, 16, 18, 20,
  130277. };
  130278. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  130279. _vq_quantthresh__44c4_s_p9_2,
  130280. _vq_quantmap__44c4_s_p9_2,
  130281. 21,
  130282. 21
  130283. };
  130284. static static_codebook _44c4_s_p9_2 = {
  130285. 2, 441,
  130286. _vq_lengthlist__44c4_s_p9_2,
  130287. 1, -529268736, 1611661312, 5, 0,
  130288. _vq_quantlist__44c4_s_p9_2,
  130289. NULL,
  130290. &_vq_auxt__44c4_s_p9_2,
  130291. NULL,
  130292. 0
  130293. };
  130294. static long _huff_lengthlist__44c4_s_short[] = {
  130295. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  130296. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  130297. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  130298. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  130299. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  130300. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  130301. 7, 9,12,17,
  130302. };
  130303. static static_codebook _huff_book__44c4_s_short = {
  130304. 2, 100,
  130305. _huff_lengthlist__44c4_s_short,
  130306. 0, 0, 0, 0, 0,
  130307. NULL,
  130308. NULL,
  130309. NULL,
  130310. NULL,
  130311. 0
  130312. };
  130313. static long _huff_lengthlist__44c5_s_long[] = {
  130314. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  130315. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  130316. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  130317. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  130318. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  130319. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  130320. 9, 8, 7, 7,
  130321. };
  130322. static static_codebook _huff_book__44c5_s_long = {
  130323. 2, 100,
  130324. _huff_lengthlist__44c5_s_long,
  130325. 0, 0, 0, 0, 0,
  130326. NULL,
  130327. NULL,
  130328. NULL,
  130329. NULL,
  130330. 0
  130331. };
  130332. static long _vq_quantlist__44c5_s_p1_0[] = {
  130333. 1,
  130334. 0,
  130335. 2,
  130336. };
  130337. static long _vq_lengthlist__44c5_s_p1_0[] = {
  130338. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  130339. 0, 0, 4, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130343. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  130344. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130348. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  130349. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  130384. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  130389. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  130390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130394. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  130395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130429. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130430. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130434. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  130435. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  130436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130439. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  130440. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  130441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130647. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130652. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130657. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  130692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130708. 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130738. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130743. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130748. 0,
  130749. };
  130750. static float _vq_quantthresh__44c5_s_p1_0[] = {
  130751. -0.5, 0.5,
  130752. };
  130753. static long _vq_quantmap__44c5_s_p1_0[] = {
  130754. 1, 0, 2,
  130755. };
  130756. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  130757. _vq_quantthresh__44c5_s_p1_0,
  130758. _vq_quantmap__44c5_s_p1_0,
  130759. 3,
  130760. 3
  130761. };
  130762. static static_codebook _44c5_s_p1_0 = {
  130763. 8, 6561,
  130764. _vq_lengthlist__44c5_s_p1_0,
  130765. 1, -535822336, 1611661312, 2, 0,
  130766. _vq_quantlist__44c5_s_p1_0,
  130767. NULL,
  130768. &_vq_auxt__44c5_s_p1_0,
  130769. NULL,
  130770. 0
  130771. };
  130772. static long _vq_quantlist__44c5_s_p2_0[] = {
  130773. 2,
  130774. 1,
  130775. 3,
  130776. 0,
  130777. 4,
  130778. };
  130779. static long _vq_lengthlist__44c5_s_p2_0[] = {
  130780. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  130781. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  130782. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130783. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  130784. 0, 0,10,10, 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, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  130790. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  130791. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  130792. 10, 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, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  130798. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  130799. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 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. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  130806. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  130807. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 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,
  130820. };
  130821. static float _vq_quantthresh__44c5_s_p2_0[] = {
  130822. -1.5, -0.5, 0.5, 1.5,
  130823. };
  130824. static long _vq_quantmap__44c5_s_p2_0[] = {
  130825. 3, 1, 0, 2, 4,
  130826. };
  130827. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  130828. _vq_quantthresh__44c5_s_p2_0,
  130829. _vq_quantmap__44c5_s_p2_0,
  130830. 5,
  130831. 5
  130832. };
  130833. static static_codebook _44c5_s_p2_0 = {
  130834. 4, 625,
  130835. _vq_lengthlist__44c5_s_p2_0,
  130836. 1, -533725184, 1611661312, 3, 0,
  130837. _vq_quantlist__44c5_s_p2_0,
  130838. NULL,
  130839. &_vq_auxt__44c5_s_p2_0,
  130840. NULL,
  130841. 0
  130842. };
  130843. static long _vq_quantlist__44c5_s_p3_0[] = {
  130844. 2,
  130845. 1,
  130846. 3,
  130847. 0,
  130848. 4,
  130849. };
  130850. static long _vq_lengthlist__44c5_s_p3_0[] = {
  130851. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  130853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130854. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  130856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130857. 0, 0, 0, 0, 5, 6, 6, 8, 8, 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,
  130891. };
  130892. static float _vq_quantthresh__44c5_s_p3_0[] = {
  130893. -1.5, -0.5, 0.5, 1.5,
  130894. };
  130895. static long _vq_quantmap__44c5_s_p3_0[] = {
  130896. 3, 1, 0, 2, 4,
  130897. };
  130898. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  130899. _vq_quantthresh__44c5_s_p3_0,
  130900. _vq_quantmap__44c5_s_p3_0,
  130901. 5,
  130902. 5
  130903. };
  130904. static static_codebook _44c5_s_p3_0 = {
  130905. 4, 625,
  130906. _vq_lengthlist__44c5_s_p3_0,
  130907. 1, -533725184, 1611661312, 3, 0,
  130908. _vq_quantlist__44c5_s_p3_0,
  130909. NULL,
  130910. &_vq_auxt__44c5_s_p3_0,
  130911. NULL,
  130912. 0
  130913. };
  130914. static long _vq_quantlist__44c5_s_p4_0[] = {
  130915. 4,
  130916. 3,
  130917. 5,
  130918. 2,
  130919. 6,
  130920. 1,
  130921. 7,
  130922. 0,
  130923. 8,
  130924. };
  130925. static long _vq_lengthlist__44c5_s_p4_0[] = {
  130926. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  130927. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  130928. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  130929. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  130930. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130931. 0,
  130932. };
  130933. static float _vq_quantthresh__44c5_s_p4_0[] = {
  130934. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130935. };
  130936. static long _vq_quantmap__44c5_s_p4_0[] = {
  130937. 7, 5, 3, 1, 0, 2, 4, 6,
  130938. 8,
  130939. };
  130940. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  130941. _vq_quantthresh__44c5_s_p4_0,
  130942. _vq_quantmap__44c5_s_p4_0,
  130943. 9,
  130944. 9
  130945. };
  130946. static static_codebook _44c5_s_p4_0 = {
  130947. 2, 81,
  130948. _vq_lengthlist__44c5_s_p4_0,
  130949. 1, -531628032, 1611661312, 4, 0,
  130950. _vq_quantlist__44c5_s_p4_0,
  130951. NULL,
  130952. &_vq_auxt__44c5_s_p4_0,
  130953. NULL,
  130954. 0
  130955. };
  130956. static long _vq_quantlist__44c5_s_p5_0[] = {
  130957. 4,
  130958. 3,
  130959. 5,
  130960. 2,
  130961. 6,
  130962. 1,
  130963. 7,
  130964. 0,
  130965. 8,
  130966. };
  130967. static long _vq_lengthlist__44c5_s_p5_0[] = {
  130968. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  130969. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  130970. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  130971. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  130972. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  130973. 10,
  130974. };
  130975. static float _vq_quantthresh__44c5_s_p5_0[] = {
  130976. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130977. };
  130978. static long _vq_quantmap__44c5_s_p5_0[] = {
  130979. 7, 5, 3, 1, 0, 2, 4, 6,
  130980. 8,
  130981. };
  130982. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  130983. _vq_quantthresh__44c5_s_p5_0,
  130984. _vq_quantmap__44c5_s_p5_0,
  130985. 9,
  130986. 9
  130987. };
  130988. static static_codebook _44c5_s_p5_0 = {
  130989. 2, 81,
  130990. _vq_lengthlist__44c5_s_p5_0,
  130991. 1, -531628032, 1611661312, 4, 0,
  130992. _vq_quantlist__44c5_s_p5_0,
  130993. NULL,
  130994. &_vq_auxt__44c5_s_p5_0,
  130995. NULL,
  130996. 0
  130997. };
  130998. static long _vq_quantlist__44c5_s_p6_0[] = {
  130999. 8,
  131000. 7,
  131001. 9,
  131002. 6,
  131003. 10,
  131004. 5,
  131005. 11,
  131006. 4,
  131007. 12,
  131008. 3,
  131009. 13,
  131010. 2,
  131011. 14,
  131012. 1,
  131013. 15,
  131014. 0,
  131015. 16,
  131016. };
  131017. static long _vq_lengthlist__44c5_s_p6_0[] = {
  131018. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  131019. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  131020. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  131021. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  131022. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  131023. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  131024. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  131025. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  131026. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  131027. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  131028. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  131029. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  131030. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  131031. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  131032. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  131033. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  131034. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  131035. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  131036. 13,
  131037. };
  131038. static float _vq_quantthresh__44c5_s_p6_0[] = {
  131039. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131040. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131041. };
  131042. static long _vq_quantmap__44c5_s_p6_0[] = {
  131043. 15, 13, 11, 9, 7, 5, 3, 1,
  131044. 0, 2, 4, 6, 8, 10, 12, 14,
  131045. 16,
  131046. };
  131047. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  131048. _vq_quantthresh__44c5_s_p6_0,
  131049. _vq_quantmap__44c5_s_p6_0,
  131050. 17,
  131051. 17
  131052. };
  131053. static static_codebook _44c5_s_p6_0 = {
  131054. 2, 289,
  131055. _vq_lengthlist__44c5_s_p6_0,
  131056. 1, -529530880, 1611661312, 5, 0,
  131057. _vq_quantlist__44c5_s_p6_0,
  131058. NULL,
  131059. &_vq_auxt__44c5_s_p6_0,
  131060. NULL,
  131061. 0
  131062. };
  131063. static long _vq_quantlist__44c5_s_p7_0[] = {
  131064. 1,
  131065. 0,
  131066. 2,
  131067. };
  131068. static long _vq_lengthlist__44c5_s_p7_0[] = {
  131069. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  131070. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  131071. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  131072. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  131073. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  131074. 10,
  131075. };
  131076. static float _vq_quantthresh__44c5_s_p7_0[] = {
  131077. -5.5, 5.5,
  131078. };
  131079. static long _vq_quantmap__44c5_s_p7_0[] = {
  131080. 1, 0, 2,
  131081. };
  131082. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  131083. _vq_quantthresh__44c5_s_p7_0,
  131084. _vq_quantmap__44c5_s_p7_0,
  131085. 3,
  131086. 3
  131087. };
  131088. static static_codebook _44c5_s_p7_0 = {
  131089. 4, 81,
  131090. _vq_lengthlist__44c5_s_p7_0,
  131091. 1, -529137664, 1618345984, 2, 0,
  131092. _vq_quantlist__44c5_s_p7_0,
  131093. NULL,
  131094. &_vq_auxt__44c5_s_p7_0,
  131095. NULL,
  131096. 0
  131097. };
  131098. static long _vq_quantlist__44c5_s_p7_1[] = {
  131099. 5,
  131100. 4,
  131101. 6,
  131102. 3,
  131103. 7,
  131104. 2,
  131105. 8,
  131106. 1,
  131107. 9,
  131108. 0,
  131109. 10,
  131110. };
  131111. static long _vq_lengthlist__44c5_s_p7_1[] = {
  131112. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  131113. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  131114. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  131115. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  131116. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  131117. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  131118. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  131119. 10,10,10, 8, 8, 8, 8, 8, 8,
  131120. };
  131121. static float _vq_quantthresh__44c5_s_p7_1[] = {
  131122. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131123. 3.5, 4.5,
  131124. };
  131125. static long _vq_quantmap__44c5_s_p7_1[] = {
  131126. 9, 7, 5, 3, 1, 0, 2, 4,
  131127. 6, 8, 10,
  131128. };
  131129. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  131130. _vq_quantthresh__44c5_s_p7_1,
  131131. _vq_quantmap__44c5_s_p7_1,
  131132. 11,
  131133. 11
  131134. };
  131135. static static_codebook _44c5_s_p7_1 = {
  131136. 2, 121,
  131137. _vq_lengthlist__44c5_s_p7_1,
  131138. 1, -531365888, 1611661312, 4, 0,
  131139. _vq_quantlist__44c5_s_p7_1,
  131140. NULL,
  131141. &_vq_auxt__44c5_s_p7_1,
  131142. NULL,
  131143. 0
  131144. };
  131145. static long _vq_quantlist__44c5_s_p8_0[] = {
  131146. 6,
  131147. 5,
  131148. 7,
  131149. 4,
  131150. 8,
  131151. 3,
  131152. 9,
  131153. 2,
  131154. 10,
  131155. 1,
  131156. 11,
  131157. 0,
  131158. 12,
  131159. };
  131160. static long _vq_lengthlist__44c5_s_p8_0[] = {
  131161. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  131162. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  131163. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  131164. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  131165. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  131166. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  131167. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  131168. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  131169. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  131170. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  131171. 0,12,12,12,12,12,12,13,13,
  131172. };
  131173. static float _vq_quantthresh__44c5_s_p8_0[] = {
  131174. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  131175. 12.5, 17.5, 22.5, 27.5,
  131176. };
  131177. static long _vq_quantmap__44c5_s_p8_0[] = {
  131178. 11, 9, 7, 5, 3, 1, 0, 2,
  131179. 4, 6, 8, 10, 12,
  131180. };
  131181. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  131182. _vq_quantthresh__44c5_s_p8_0,
  131183. _vq_quantmap__44c5_s_p8_0,
  131184. 13,
  131185. 13
  131186. };
  131187. static static_codebook _44c5_s_p8_0 = {
  131188. 2, 169,
  131189. _vq_lengthlist__44c5_s_p8_0,
  131190. 1, -526516224, 1616117760, 4, 0,
  131191. _vq_quantlist__44c5_s_p8_0,
  131192. NULL,
  131193. &_vq_auxt__44c5_s_p8_0,
  131194. NULL,
  131195. 0
  131196. };
  131197. static long _vq_quantlist__44c5_s_p8_1[] = {
  131198. 2,
  131199. 1,
  131200. 3,
  131201. 0,
  131202. 4,
  131203. };
  131204. static long _vq_lengthlist__44c5_s_p8_1[] = {
  131205. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  131206. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  131207. };
  131208. static float _vq_quantthresh__44c5_s_p8_1[] = {
  131209. -1.5, -0.5, 0.5, 1.5,
  131210. };
  131211. static long _vq_quantmap__44c5_s_p8_1[] = {
  131212. 3, 1, 0, 2, 4,
  131213. };
  131214. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  131215. _vq_quantthresh__44c5_s_p8_1,
  131216. _vq_quantmap__44c5_s_p8_1,
  131217. 5,
  131218. 5
  131219. };
  131220. static static_codebook _44c5_s_p8_1 = {
  131221. 2, 25,
  131222. _vq_lengthlist__44c5_s_p8_1,
  131223. 1, -533725184, 1611661312, 3, 0,
  131224. _vq_quantlist__44c5_s_p8_1,
  131225. NULL,
  131226. &_vq_auxt__44c5_s_p8_1,
  131227. NULL,
  131228. 0
  131229. };
  131230. static long _vq_quantlist__44c5_s_p9_0[] = {
  131231. 7,
  131232. 6,
  131233. 8,
  131234. 5,
  131235. 9,
  131236. 4,
  131237. 10,
  131238. 3,
  131239. 11,
  131240. 2,
  131241. 12,
  131242. 1,
  131243. 13,
  131244. 0,
  131245. 14,
  131246. };
  131247. static long _vq_lengthlist__44c5_s_p9_0[] = {
  131248. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  131249. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  131250. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131251. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131252. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131253. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131254. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131255. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131256. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131257. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131258. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131259. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131260. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131261. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  131262. 12,
  131263. };
  131264. static float _vq_quantthresh__44c5_s_p9_0[] = {
  131265. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  131266. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  131267. };
  131268. static long _vq_quantmap__44c5_s_p9_0[] = {
  131269. 13, 11, 9, 7, 5, 3, 1, 0,
  131270. 2, 4, 6, 8, 10, 12, 14,
  131271. };
  131272. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  131273. _vq_quantthresh__44c5_s_p9_0,
  131274. _vq_quantmap__44c5_s_p9_0,
  131275. 15,
  131276. 15
  131277. };
  131278. static static_codebook _44c5_s_p9_0 = {
  131279. 2, 225,
  131280. _vq_lengthlist__44c5_s_p9_0,
  131281. 1, -512522752, 1628852224, 4, 0,
  131282. _vq_quantlist__44c5_s_p9_0,
  131283. NULL,
  131284. &_vq_auxt__44c5_s_p9_0,
  131285. NULL,
  131286. 0
  131287. };
  131288. static long _vq_quantlist__44c5_s_p9_1[] = {
  131289. 8,
  131290. 7,
  131291. 9,
  131292. 6,
  131293. 10,
  131294. 5,
  131295. 11,
  131296. 4,
  131297. 12,
  131298. 3,
  131299. 13,
  131300. 2,
  131301. 14,
  131302. 1,
  131303. 15,
  131304. 0,
  131305. 16,
  131306. };
  131307. static long _vq_lengthlist__44c5_s_p9_1[] = {
  131308. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  131309. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  131310. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  131311. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  131312. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  131313. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  131314. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  131315. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  131316. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  131317. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  131318. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  131319. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  131320. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  131321. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  131322. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  131323. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  131324. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  131325. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  131326. 15,
  131327. };
  131328. static float _vq_quantthresh__44c5_s_p9_1[] = {
  131329. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  131330. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  131331. };
  131332. static long _vq_quantmap__44c5_s_p9_1[] = {
  131333. 15, 13, 11, 9, 7, 5, 3, 1,
  131334. 0, 2, 4, 6, 8, 10, 12, 14,
  131335. 16,
  131336. };
  131337. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  131338. _vq_quantthresh__44c5_s_p9_1,
  131339. _vq_quantmap__44c5_s_p9_1,
  131340. 17,
  131341. 17
  131342. };
  131343. static static_codebook _44c5_s_p9_1 = {
  131344. 2, 289,
  131345. _vq_lengthlist__44c5_s_p9_1,
  131346. 1, -520814592, 1620377600, 5, 0,
  131347. _vq_quantlist__44c5_s_p9_1,
  131348. NULL,
  131349. &_vq_auxt__44c5_s_p9_1,
  131350. NULL,
  131351. 0
  131352. };
  131353. static long _vq_quantlist__44c5_s_p9_2[] = {
  131354. 10,
  131355. 9,
  131356. 11,
  131357. 8,
  131358. 12,
  131359. 7,
  131360. 13,
  131361. 6,
  131362. 14,
  131363. 5,
  131364. 15,
  131365. 4,
  131366. 16,
  131367. 3,
  131368. 17,
  131369. 2,
  131370. 18,
  131371. 1,
  131372. 19,
  131373. 0,
  131374. 20,
  131375. };
  131376. static long _vq_lengthlist__44c5_s_p9_2[] = {
  131377. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  131378. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  131379. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  131380. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  131381. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  131382. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  131383. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  131384. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  131385. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  131386. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131387. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  131388. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  131389. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  131390. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  131391. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  131392. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  131393. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  131394. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  131395. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  131396. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  131397. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131398. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  131399. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  131400. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  131401. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  131402. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  131403. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  131404. 10,10,10,10,10,10,10,10,10,
  131405. };
  131406. static float _vq_quantthresh__44c5_s_p9_2[] = {
  131407. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  131408. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  131409. 6.5, 7.5, 8.5, 9.5,
  131410. };
  131411. static long _vq_quantmap__44c5_s_p9_2[] = {
  131412. 19, 17, 15, 13, 11, 9, 7, 5,
  131413. 3, 1, 0, 2, 4, 6, 8, 10,
  131414. 12, 14, 16, 18, 20,
  131415. };
  131416. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  131417. _vq_quantthresh__44c5_s_p9_2,
  131418. _vq_quantmap__44c5_s_p9_2,
  131419. 21,
  131420. 21
  131421. };
  131422. static static_codebook _44c5_s_p9_2 = {
  131423. 2, 441,
  131424. _vq_lengthlist__44c5_s_p9_2,
  131425. 1, -529268736, 1611661312, 5, 0,
  131426. _vq_quantlist__44c5_s_p9_2,
  131427. NULL,
  131428. &_vq_auxt__44c5_s_p9_2,
  131429. NULL,
  131430. 0
  131431. };
  131432. static long _huff_lengthlist__44c5_s_short[] = {
  131433. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  131434. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  131435. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  131436. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  131437. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  131438. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  131439. 6, 8,11,16,
  131440. };
  131441. static static_codebook _huff_book__44c5_s_short = {
  131442. 2, 100,
  131443. _huff_lengthlist__44c5_s_short,
  131444. 0, 0, 0, 0, 0,
  131445. NULL,
  131446. NULL,
  131447. NULL,
  131448. NULL,
  131449. 0
  131450. };
  131451. static long _huff_lengthlist__44c6_s_long[] = {
  131452. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  131453. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  131454. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  131455. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  131456. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  131457. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  131458. 11,10,10,12,
  131459. };
  131460. static static_codebook _huff_book__44c6_s_long = {
  131461. 2, 100,
  131462. _huff_lengthlist__44c6_s_long,
  131463. 0, 0, 0, 0, 0,
  131464. NULL,
  131465. NULL,
  131466. NULL,
  131467. NULL,
  131468. 0
  131469. };
  131470. static long _vq_quantlist__44c6_s_p1_0[] = {
  131471. 1,
  131472. 0,
  131473. 2,
  131474. };
  131475. static long _vq_lengthlist__44c6_s_p1_0[] = {
  131476. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  131477. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  131478. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  131479. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  131480. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  131481. 8,
  131482. };
  131483. static float _vq_quantthresh__44c6_s_p1_0[] = {
  131484. -0.5, 0.5,
  131485. };
  131486. static long _vq_quantmap__44c6_s_p1_0[] = {
  131487. 1, 0, 2,
  131488. };
  131489. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  131490. _vq_quantthresh__44c6_s_p1_0,
  131491. _vq_quantmap__44c6_s_p1_0,
  131492. 3,
  131493. 3
  131494. };
  131495. static static_codebook _44c6_s_p1_0 = {
  131496. 4, 81,
  131497. _vq_lengthlist__44c6_s_p1_0,
  131498. 1, -535822336, 1611661312, 2, 0,
  131499. _vq_quantlist__44c6_s_p1_0,
  131500. NULL,
  131501. &_vq_auxt__44c6_s_p1_0,
  131502. NULL,
  131503. 0
  131504. };
  131505. static long _vq_quantlist__44c6_s_p2_0[] = {
  131506. 2,
  131507. 1,
  131508. 3,
  131509. 0,
  131510. 4,
  131511. };
  131512. static long _vq_lengthlist__44c6_s_p2_0[] = {
  131513. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  131514. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  131515. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  131516. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  131517. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  131518. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  131519. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  131520. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  131521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131522. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  131523. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  131524. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  131525. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  131526. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  131527. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  131528. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  131529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131530. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  131531. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  131532. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  131533. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  131534. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  131535. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  131536. 13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131538. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  131539. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  131540. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  131541. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  131542. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  131543. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  131544. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  131549. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  131550. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  131551. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  131552. 13,
  131553. };
  131554. static float _vq_quantthresh__44c6_s_p2_0[] = {
  131555. -1.5, -0.5, 0.5, 1.5,
  131556. };
  131557. static long _vq_quantmap__44c6_s_p2_0[] = {
  131558. 3, 1, 0, 2, 4,
  131559. };
  131560. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  131561. _vq_quantthresh__44c6_s_p2_0,
  131562. _vq_quantmap__44c6_s_p2_0,
  131563. 5,
  131564. 5
  131565. };
  131566. static static_codebook _44c6_s_p2_0 = {
  131567. 4, 625,
  131568. _vq_lengthlist__44c6_s_p2_0,
  131569. 1, -533725184, 1611661312, 3, 0,
  131570. _vq_quantlist__44c6_s_p2_0,
  131571. NULL,
  131572. &_vq_auxt__44c6_s_p2_0,
  131573. NULL,
  131574. 0
  131575. };
  131576. static long _vq_quantlist__44c6_s_p3_0[] = {
  131577. 4,
  131578. 3,
  131579. 5,
  131580. 2,
  131581. 6,
  131582. 1,
  131583. 7,
  131584. 0,
  131585. 8,
  131586. };
  131587. static long _vq_lengthlist__44c6_s_p3_0[] = {
  131588. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  131589. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  131590. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  131591. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  131592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131593. 0,
  131594. };
  131595. static float _vq_quantthresh__44c6_s_p3_0[] = {
  131596. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131597. };
  131598. static long _vq_quantmap__44c6_s_p3_0[] = {
  131599. 7, 5, 3, 1, 0, 2, 4, 6,
  131600. 8,
  131601. };
  131602. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  131603. _vq_quantthresh__44c6_s_p3_0,
  131604. _vq_quantmap__44c6_s_p3_0,
  131605. 9,
  131606. 9
  131607. };
  131608. static static_codebook _44c6_s_p3_0 = {
  131609. 2, 81,
  131610. _vq_lengthlist__44c6_s_p3_0,
  131611. 1, -531628032, 1611661312, 4, 0,
  131612. _vq_quantlist__44c6_s_p3_0,
  131613. NULL,
  131614. &_vq_auxt__44c6_s_p3_0,
  131615. NULL,
  131616. 0
  131617. };
  131618. static long _vq_quantlist__44c6_s_p4_0[] = {
  131619. 8,
  131620. 7,
  131621. 9,
  131622. 6,
  131623. 10,
  131624. 5,
  131625. 11,
  131626. 4,
  131627. 12,
  131628. 3,
  131629. 13,
  131630. 2,
  131631. 14,
  131632. 1,
  131633. 15,
  131634. 0,
  131635. 16,
  131636. };
  131637. static long _vq_lengthlist__44c6_s_p4_0[] = {
  131638. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  131639. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  131640. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  131641. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  131642. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  131643. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  131644. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  131645. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  131646. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  131647. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  131648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131656. 0,
  131657. };
  131658. static float _vq_quantthresh__44c6_s_p4_0[] = {
  131659. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131660. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131661. };
  131662. static long _vq_quantmap__44c6_s_p4_0[] = {
  131663. 15, 13, 11, 9, 7, 5, 3, 1,
  131664. 0, 2, 4, 6, 8, 10, 12, 14,
  131665. 16,
  131666. };
  131667. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  131668. _vq_quantthresh__44c6_s_p4_0,
  131669. _vq_quantmap__44c6_s_p4_0,
  131670. 17,
  131671. 17
  131672. };
  131673. static static_codebook _44c6_s_p4_0 = {
  131674. 2, 289,
  131675. _vq_lengthlist__44c6_s_p4_0,
  131676. 1, -529530880, 1611661312, 5, 0,
  131677. _vq_quantlist__44c6_s_p4_0,
  131678. NULL,
  131679. &_vq_auxt__44c6_s_p4_0,
  131680. NULL,
  131681. 0
  131682. };
  131683. static long _vq_quantlist__44c6_s_p5_0[] = {
  131684. 1,
  131685. 0,
  131686. 2,
  131687. };
  131688. static long _vq_lengthlist__44c6_s_p5_0[] = {
  131689. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  131690. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  131691. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  131692. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  131693. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  131694. 12,
  131695. };
  131696. static float _vq_quantthresh__44c6_s_p5_0[] = {
  131697. -5.5, 5.5,
  131698. };
  131699. static long _vq_quantmap__44c6_s_p5_0[] = {
  131700. 1, 0, 2,
  131701. };
  131702. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  131703. _vq_quantthresh__44c6_s_p5_0,
  131704. _vq_quantmap__44c6_s_p5_0,
  131705. 3,
  131706. 3
  131707. };
  131708. static static_codebook _44c6_s_p5_0 = {
  131709. 4, 81,
  131710. _vq_lengthlist__44c6_s_p5_0,
  131711. 1, -529137664, 1618345984, 2, 0,
  131712. _vq_quantlist__44c6_s_p5_0,
  131713. NULL,
  131714. &_vq_auxt__44c6_s_p5_0,
  131715. NULL,
  131716. 0
  131717. };
  131718. static long _vq_quantlist__44c6_s_p5_1[] = {
  131719. 5,
  131720. 4,
  131721. 6,
  131722. 3,
  131723. 7,
  131724. 2,
  131725. 8,
  131726. 1,
  131727. 9,
  131728. 0,
  131729. 10,
  131730. };
  131731. static long _vq_lengthlist__44c6_s_p5_1[] = {
  131732. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  131733. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  131734. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  131735. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  131736. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  131737. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  131738. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  131739. 11,10,10, 7, 7, 8, 8, 8, 8,
  131740. };
  131741. static float _vq_quantthresh__44c6_s_p5_1[] = {
  131742. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131743. 3.5, 4.5,
  131744. };
  131745. static long _vq_quantmap__44c6_s_p5_1[] = {
  131746. 9, 7, 5, 3, 1, 0, 2, 4,
  131747. 6, 8, 10,
  131748. };
  131749. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  131750. _vq_quantthresh__44c6_s_p5_1,
  131751. _vq_quantmap__44c6_s_p5_1,
  131752. 11,
  131753. 11
  131754. };
  131755. static static_codebook _44c6_s_p5_1 = {
  131756. 2, 121,
  131757. _vq_lengthlist__44c6_s_p5_1,
  131758. 1, -531365888, 1611661312, 4, 0,
  131759. _vq_quantlist__44c6_s_p5_1,
  131760. NULL,
  131761. &_vq_auxt__44c6_s_p5_1,
  131762. NULL,
  131763. 0
  131764. };
  131765. static long _vq_quantlist__44c6_s_p6_0[] = {
  131766. 6,
  131767. 5,
  131768. 7,
  131769. 4,
  131770. 8,
  131771. 3,
  131772. 9,
  131773. 2,
  131774. 10,
  131775. 1,
  131776. 11,
  131777. 0,
  131778. 12,
  131779. };
  131780. static long _vq_lengthlist__44c6_s_p6_0[] = {
  131781. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  131782. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  131783. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  131784. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  131785. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  131786. 12, 9, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  131787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131791. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131792. };
  131793. static float _vq_quantthresh__44c6_s_p6_0[] = {
  131794. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  131795. 12.5, 17.5, 22.5, 27.5,
  131796. };
  131797. static long _vq_quantmap__44c6_s_p6_0[] = {
  131798. 11, 9, 7, 5, 3, 1, 0, 2,
  131799. 4, 6, 8, 10, 12,
  131800. };
  131801. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  131802. _vq_quantthresh__44c6_s_p6_0,
  131803. _vq_quantmap__44c6_s_p6_0,
  131804. 13,
  131805. 13
  131806. };
  131807. static static_codebook _44c6_s_p6_0 = {
  131808. 2, 169,
  131809. _vq_lengthlist__44c6_s_p6_0,
  131810. 1, -526516224, 1616117760, 4, 0,
  131811. _vq_quantlist__44c6_s_p6_0,
  131812. NULL,
  131813. &_vq_auxt__44c6_s_p6_0,
  131814. NULL,
  131815. 0
  131816. };
  131817. static long _vq_quantlist__44c6_s_p6_1[] = {
  131818. 2,
  131819. 1,
  131820. 3,
  131821. 0,
  131822. 4,
  131823. };
  131824. static long _vq_lengthlist__44c6_s_p6_1[] = {
  131825. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  131826. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  131827. };
  131828. static float _vq_quantthresh__44c6_s_p6_1[] = {
  131829. -1.5, -0.5, 0.5, 1.5,
  131830. };
  131831. static long _vq_quantmap__44c6_s_p6_1[] = {
  131832. 3, 1, 0, 2, 4,
  131833. };
  131834. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  131835. _vq_quantthresh__44c6_s_p6_1,
  131836. _vq_quantmap__44c6_s_p6_1,
  131837. 5,
  131838. 5
  131839. };
  131840. static static_codebook _44c6_s_p6_1 = {
  131841. 2, 25,
  131842. _vq_lengthlist__44c6_s_p6_1,
  131843. 1, -533725184, 1611661312, 3, 0,
  131844. _vq_quantlist__44c6_s_p6_1,
  131845. NULL,
  131846. &_vq_auxt__44c6_s_p6_1,
  131847. NULL,
  131848. 0
  131849. };
  131850. static long _vq_quantlist__44c6_s_p7_0[] = {
  131851. 6,
  131852. 5,
  131853. 7,
  131854. 4,
  131855. 8,
  131856. 3,
  131857. 9,
  131858. 2,
  131859. 10,
  131860. 1,
  131861. 11,
  131862. 0,
  131863. 12,
  131864. };
  131865. static long _vq_lengthlist__44c6_s_p7_0[] = {
  131866. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  131867. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  131868. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  131869. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  131870. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  131871. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  131872. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  131873. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  131874. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  131875. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  131876. 20,13,13,13,13,13,13,14,14,
  131877. };
  131878. static float _vq_quantthresh__44c6_s_p7_0[] = {
  131879. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  131880. 27.5, 38.5, 49.5, 60.5,
  131881. };
  131882. static long _vq_quantmap__44c6_s_p7_0[] = {
  131883. 11, 9, 7, 5, 3, 1, 0, 2,
  131884. 4, 6, 8, 10, 12,
  131885. };
  131886. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_0 = {
  131887. _vq_quantthresh__44c6_s_p7_0,
  131888. _vq_quantmap__44c6_s_p7_0,
  131889. 13,
  131890. 13
  131891. };
  131892. static static_codebook _44c6_s_p7_0 = {
  131893. 2, 169,
  131894. _vq_lengthlist__44c6_s_p7_0,
  131895. 1, -523206656, 1618345984, 4, 0,
  131896. _vq_quantlist__44c6_s_p7_0,
  131897. NULL,
  131898. &_vq_auxt__44c6_s_p7_0,
  131899. NULL,
  131900. 0
  131901. };
  131902. static long _vq_quantlist__44c6_s_p7_1[] = {
  131903. 5,
  131904. 4,
  131905. 6,
  131906. 3,
  131907. 7,
  131908. 2,
  131909. 8,
  131910. 1,
  131911. 9,
  131912. 0,
  131913. 10,
  131914. };
  131915. static long _vq_lengthlist__44c6_s_p7_1[] = {
  131916. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  131917. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  131918. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  131919. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  131920. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  131921. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  131922. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  131923. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  131924. };
  131925. static float _vq_quantthresh__44c6_s_p7_1[] = {
  131926. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131927. 3.5, 4.5,
  131928. };
  131929. static long _vq_quantmap__44c6_s_p7_1[] = {
  131930. 9, 7, 5, 3, 1, 0, 2, 4,
  131931. 6, 8, 10,
  131932. };
  131933. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  131934. _vq_quantthresh__44c6_s_p7_1,
  131935. _vq_quantmap__44c6_s_p7_1,
  131936. 11,
  131937. 11
  131938. };
  131939. static static_codebook _44c6_s_p7_1 = {
  131940. 2, 121,
  131941. _vq_lengthlist__44c6_s_p7_1,
  131942. 1, -531365888, 1611661312, 4, 0,
  131943. _vq_quantlist__44c6_s_p7_1,
  131944. NULL,
  131945. &_vq_auxt__44c6_s_p7_1,
  131946. NULL,
  131947. 0
  131948. };
  131949. static long _vq_quantlist__44c6_s_p8_0[] = {
  131950. 7,
  131951. 6,
  131952. 8,
  131953. 5,
  131954. 9,
  131955. 4,
  131956. 10,
  131957. 3,
  131958. 11,
  131959. 2,
  131960. 12,
  131961. 1,
  131962. 13,
  131963. 0,
  131964. 14,
  131965. };
  131966. static long _vq_lengthlist__44c6_s_p8_0[] = {
  131967. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  131968. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  131969. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  131970. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  131971. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  131972. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  131973. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  131974. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  131975. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  131976. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  131977. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  131978. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  131979. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  131980. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  131981. 14,
  131982. };
  131983. static float _vq_quantthresh__44c6_s_p8_0[] = {
  131984. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  131985. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  131986. };
  131987. static long _vq_quantmap__44c6_s_p8_0[] = {
  131988. 13, 11, 9, 7, 5, 3, 1, 0,
  131989. 2, 4, 6, 8, 10, 12, 14,
  131990. };
  131991. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  131992. _vq_quantthresh__44c6_s_p8_0,
  131993. _vq_quantmap__44c6_s_p8_0,
  131994. 15,
  131995. 15
  131996. };
  131997. static static_codebook _44c6_s_p8_0 = {
  131998. 2, 225,
  131999. _vq_lengthlist__44c6_s_p8_0,
  132000. 1, -520986624, 1620377600, 4, 0,
  132001. _vq_quantlist__44c6_s_p8_0,
  132002. NULL,
  132003. &_vq_auxt__44c6_s_p8_0,
  132004. NULL,
  132005. 0
  132006. };
  132007. static long _vq_quantlist__44c6_s_p8_1[] = {
  132008. 10,
  132009. 9,
  132010. 11,
  132011. 8,
  132012. 12,
  132013. 7,
  132014. 13,
  132015. 6,
  132016. 14,
  132017. 5,
  132018. 15,
  132019. 4,
  132020. 16,
  132021. 3,
  132022. 17,
  132023. 2,
  132024. 18,
  132025. 1,
  132026. 19,
  132027. 0,
  132028. 20,
  132029. };
  132030. static long _vq_lengthlist__44c6_s_p8_1[] = {
  132031. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  132032. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  132033. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  132034. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  132035. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132036. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  132037. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  132038. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  132039. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132040. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132041. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  132042. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  132043. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  132044. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  132045. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  132046. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  132047. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  132048. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  132049. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  132050. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  132051. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  132052. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  132053. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  132054. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  132055. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  132056. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  132057. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  132058. 10,10,10,10,10,10,10,10,10,
  132059. };
  132060. static float _vq_quantthresh__44c6_s_p8_1[] = {
  132061. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132062. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132063. 6.5, 7.5, 8.5, 9.5,
  132064. };
  132065. static long _vq_quantmap__44c6_s_p8_1[] = {
  132066. 19, 17, 15, 13, 11, 9, 7, 5,
  132067. 3, 1, 0, 2, 4, 6, 8, 10,
  132068. 12, 14, 16, 18, 20,
  132069. };
  132070. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  132071. _vq_quantthresh__44c6_s_p8_1,
  132072. _vq_quantmap__44c6_s_p8_1,
  132073. 21,
  132074. 21
  132075. };
  132076. static static_codebook _44c6_s_p8_1 = {
  132077. 2, 441,
  132078. _vq_lengthlist__44c6_s_p8_1,
  132079. 1, -529268736, 1611661312, 5, 0,
  132080. _vq_quantlist__44c6_s_p8_1,
  132081. NULL,
  132082. &_vq_auxt__44c6_s_p8_1,
  132083. NULL,
  132084. 0
  132085. };
  132086. static long _vq_quantlist__44c6_s_p9_0[] = {
  132087. 6,
  132088. 5,
  132089. 7,
  132090. 4,
  132091. 8,
  132092. 3,
  132093. 9,
  132094. 2,
  132095. 10,
  132096. 1,
  132097. 11,
  132098. 0,
  132099. 12,
  132100. };
  132101. static long _vq_lengthlist__44c6_s_p9_0[] = {
  132102. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  132103. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  132104. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132105. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  132106. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132107. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132108. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132109. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132110. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132111. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132112. 10,10,10,10,10,10,10,10,10,
  132113. };
  132114. static float _vq_quantthresh__44c6_s_p9_0[] = {
  132115. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  132116. 1592.5, 2229.5, 2866.5, 3503.5,
  132117. };
  132118. static long _vq_quantmap__44c6_s_p9_0[] = {
  132119. 11, 9, 7, 5, 3, 1, 0, 2,
  132120. 4, 6, 8, 10, 12,
  132121. };
  132122. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  132123. _vq_quantthresh__44c6_s_p9_0,
  132124. _vq_quantmap__44c6_s_p9_0,
  132125. 13,
  132126. 13
  132127. };
  132128. static static_codebook _44c6_s_p9_0 = {
  132129. 2, 169,
  132130. _vq_lengthlist__44c6_s_p9_0,
  132131. 1, -511845376, 1630791680, 4, 0,
  132132. _vq_quantlist__44c6_s_p9_0,
  132133. NULL,
  132134. &_vq_auxt__44c6_s_p9_0,
  132135. NULL,
  132136. 0
  132137. };
  132138. static long _vq_quantlist__44c6_s_p9_1[] = {
  132139. 6,
  132140. 5,
  132141. 7,
  132142. 4,
  132143. 8,
  132144. 3,
  132145. 9,
  132146. 2,
  132147. 10,
  132148. 1,
  132149. 11,
  132150. 0,
  132151. 12,
  132152. };
  132153. static long _vq_lengthlist__44c6_s_p9_1[] = {
  132154. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  132155. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  132156. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  132157. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  132158. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  132159. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  132160. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  132161. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  132162. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  132163. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  132164. 15,12,10,11,11,13,11,12,13,
  132165. };
  132166. static float _vq_quantthresh__44c6_s_p9_1[] = {
  132167. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  132168. 122.5, 171.5, 220.5, 269.5,
  132169. };
  132170. static long _vq_quantmap__44c6_s_p9_1[] = {
  132171. 11, 9, 7, 5, 3, 1, 0, 2,
  132172. 4, 6, 8, 10, 12,
  132173. };
  132174. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  132175. _vq_quantthresh__44c6_s_p9_1,
  132176. _vq_quantmap__44c6_s_p9_1,
  132177. 13,
  132178. 13
  132179. };
  132180. static static_codebook _44c6_s_p9_1 = {
  132181. 2, 169,
  132182. _vq_lengthlist__44c6_s_p9_1,
  132183. 1, -518889472, 1622704128, 4, 0,
  132184. _vq_quantlist__44c6_s_p9_1,
  132185. NULL,
  132186. &_vq_auxt__44c6_s_p9_1,
  132187. NULL,
  132188. 0
  132189. };
  132190. static long _vq_quantlist__44c6_s_p9_2[] = {
  132191. 24,
  132192. 23,
  132193. 25,
  132194. 22,
  132195. 26,
  132196. 21,
  132197. 27,
  132198. 20,
  132199. 28,
  132200. 19,
  132201. 29,
  132202. 18,
  132203. 30,
  132204. 17,
  132205. 31,
  132206. 16,
  132207. 32,
  132208. 15,
  132209. 33,
  132210. 14,
  132211. 34,
  132212. 13,
  132213. 35,
  132214. 12,
  132215. 36,
  132216. 11,
  132217. 37,
  132218. 10,
  132219. 38,
  132220. 9,
  132221. 39,
  132222. 8,
  132223. 40,
  132224. 7,
  132225. 41,
  132226. 6,
  132227. 42,
  132228. 5,
  132229. 43,
  132230. 4,
  132231. 44,
  132232. 3,
  132233. 45,
  132234. 2,
  132235. 46,
  132236. 1,
  132237. 47,
  132238. 0,
  132239. 48,
  132240. };
  132241. static long _vq_lengthlist__44c6_s_p9_2[] = {
  132242. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  132243. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  132244. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  132245. 7,
  132246. };
  132247. static float _vq_quantthresh__44c6_s_p9_2[] = {
  132248. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  132249. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  132250. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132251. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132252. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  132253. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  132254. };
  132255. static long _vq_quantmap__44c6_s_p9_2[] = {
  132256. 47, 45, 43, 41, 39, 37, 35, 33,
  132257. 31, 29, 27, 25, 23, 21, 19, 17,
  132258. 15, 13, 11, 9, 7, 5, 3, 1,
  132259. 0, 2, 4, 6, 8, 10, 12, 14,
  132260. 16, 18, 20, 22, 24, 26, 28, 30,
  132261. 32, 34, 36, 38, 40, 42, 44, 46,
  132262. 48,
  132263. };
  132264. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  132265. _vq_quantthresh__44c6_s_p9_2,
  132266. _vq_quantmap__44c6_s_p9_2,
  132267. 49,
  132268. 49
  132269. };
  132270. static static_codebook _44c6_s_p9_2 = {
  132271. 1, 49,
  132272. _vq_lengthlist__44c6_s_p9_2,
  132273. 1, -526909440, 1611661312, 6, 0,
  132274. _vq_quantlist__44c6_s_p9_2,
  132275. NULL,
  132276. &_vq_auxt__44c6_s_p9_2,
  132277. NULL,
  132278. 0
  132279. };
  132280. static long _huff_lengthlist__44c6_s_short[] = {
  132281. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  132282. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  132283. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  132284. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  132285. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  132286. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  132287. 9,10,17,18,
  132288. };
  132289. static static_codebook _huff_book__44c6_s_short = {
  132290. 2, 100,
  132291. _huff_lengthlist__44c6_s_short,
  132292. 0, 0, 0, 0, 0,
  132293. NULL,
  132294. NULL,
  132295. NULL,
  132296. NULL,
  132297. 0
  132298. };
  132299. static long _huff_lengthlist__44c7_s_long[] = {
  132300. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  132301. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  132302. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  132303. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  132304. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  132305. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  132306. 11,10,10,12,
  132307. };
  132308. static static_codebook _huff_book__44c7_s_long = {
  132309. 2, 100,
  132310. _huff_lengthlist__44c7_s_long,
  132311. 0, 0, 0, 0, 0,
  132312. NULL,
  132313. NULL,
  132314. NULL,
  132315. NULL,
  132316. 0
  132317. };
  132318. static long _vq_quantlist__44c7_s_p1_0[] = {
  132319. 1,
  132320. 0,
  132321. 2,
  132322. };
  132323. static long _vq_lengthlist__44c7_s_p1_0[] = {
  132324. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  132325. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  132326. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  132327. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  132328. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  132329. 8,
  132330. };
  132331. static float _vq_quantthresh__44c7_s_p1_0[] = {
  132332. -0.5, 0.5,
  132333. };
  132334. static long _vq_quantmap__44c7_s_p1_0[] = {
  132335. 1, 0, 2,
  132336. };
  132337. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  132338. _vq_quantthresh__44c7_s_p1_0,
  132339. _vq_quantmap__44c7_s_p1_0,
  132340. 3,
  132341. 3
  132342. };
  132343. static static_codebook _44c7_s_p1_0 = {
  132344. 4, 81,
  132345. _vq_lengthlist__44c7_s_p1_0,
  132346. 1, -535822336, 1611661312, 2, 0,
  132347. _vq_quantlist__44c7_s_p1_0,
  132348. NULL,
  132349. &_vq_auxt__44c7_s_p1_0,
  132350. NULL,
  132351. 0
  132352. };
  132353. static long _vq_quantlist__44c7_s_p2_0[] = {
  132354. 2,
  132355. 1,
  132356. 3,
  132357. 0,
  132358. 4,
  132359. };
  132360. static long _vq_lengthlist__44c7_s_p2_0[] = {
  132361. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  132362. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  132363. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  132364. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  132365. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  132366. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  132367. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  132368. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  132369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132370. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  132371. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  132372. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  132373. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  132374. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  132375. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  132376. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  132377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132378. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  132379. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  132380. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  132381. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  132382. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  132383. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  132384. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132386. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  132387. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  132388. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  132389. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  132390. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  132391. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  132392. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  132397. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  132398. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  132399. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  132400. 13,
  132401. };
  132402. static float _vq_quantthresh__44c7_s_p2_0[] = {
  132403. -1.5, -0.5, 0.5, 1.5,
  132404. };
  132405. static long _vq_quantmap__44c7_s_p2_0[] = {
  132406. 3, 1, 0, 2, 4,
  132407. };
  132408. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  132409. _vq_quantthresh__44c7_s_p2_0,
  132410. _vq_quantmap__44c7_s_p2_0,
  132411. 5,
  132412. 5
  132413. };
  132414. static static_codebook _44c7_s_p2_0 = {
  132415. 4, 625,
  132416. _vq_lengthlist__44c7_s_p2_0,
  132417. 1, -533725184, 1611661312, 3, 0,
  132418. _vq_quantlist__44c7_s_p2_0,
  132419. NULL,
  132420. &_vq_auxt__44c7_s_p2_0,
  132421. NULL,
  132422. 0
  132423. };
  132424. static long _vq_quantlist__44c7_s_p3_0[] = {
  132425. 4,
  132426. 3,
  132427. 5,
  132428. 2,
  132429. 6,
  132430. 1,
  132431. 7,
  132432. 0,
  132433. 8,
  132434. };
  132435. static long _vq_lengthlist__44c7_s_p3_0[] = {
  132436. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  132437. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  132438. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  132439. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  132440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132441. 0,
  132442. };
  132443. static float _vq_quantthresh__44c7_s_p3_0[] = {
  132444. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132445. };
  132446. static long _vq_quantmap__44c7_s_p3_0[] = {
  132447. 7, 5, 3, 1, 0, 2, 4, 6,
  132448. 8,
  132449. };
  132450. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  132451. _vq_quantthresh__44c7_s_p3_0,
  132452. _vq_quantmap__44c7_s_p3_0,
  132453. 9,
  132454. 9
  132455. };
  132456. static static_codebook _44c7_s_p3_0 = {
  132457. 2, 81,
  132458. _vq_lengthlist__44c7_s_p3_0,
  132459. 1, -531628032, 1611661312, 4, 0,
  132460. _vq_quantlist__44c7_s_p3_0,
  132461. NULL,
  132462. &_vq_auxt__44c7_s_p3_0,
  132463. NULL,
  132464. 0
  132465. };
  132466. static long _vq_quantlist__44c7_s_p4_0[] = {
  132467. 8,
  132468. 7,
  132469. 9,
  132470. 6,
  132471. 10,
  132472. 5,
  132473. 11,
  132474. 4,
  132475. 12,
  132476. 3,
  132477. 13,
  132478. 2,
  132479. 14,
  132480. 1,
  132481. 15,
  132482. 0,
  132483. 16,
  132484. };
  132485. static long _vq_lengthlist__44c7_s_p4_0[] = {
  132486. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  132487. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  132488. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  132489. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  132490. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  132491. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  132492. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  132493. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  132494. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  132495. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  132496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132504. 0,
  132505. };
  132506. static float _vq_quantthresh__44c7_s_p4_0[] = {
  132507. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132508. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132509. };
  132510. static long _vq_quantmap__44c7_s_p4_0[] = {
  132511. 15, 13, 11, 9, 7, 5, 3, 1,
  132512. 0, 2, 4, 6, 8, 10, 12, 14,
  132513. 16,
  132514. };
  132515. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  132516. _vq_quantthresh__44c7_s_p4_0,
  132517. _vq_quantmap__44c7_s_p4_0,
  132518. 17,
  132519. 17
  132520. };
  132521. static static_codebook _44c7_s_p4_0 = {
  132522. 2, 289,
  132523. _vq_lengthlist__44c7_s_p4_0,
  132524. 1, -529530880, 1611661312, 5, 0,
  132525. _vq_quantlist__44c7_s_p4_0,
  132526. NULL,
  132527. &_vq_auxt__44c7_s_p4_0,
  132528. NULL,
  132529. 0
  132530. };
  132531. static long _vq_quantlist__44c7_s_p5_0[] = {
  132532. 1,
  132533. 0,
  132534. 2,
  132535. };
  132536. static long _vq_lengthlist__44c7_s_p5_0[] = {
  132537. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  132538. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  132539. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  132540. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  132541. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  132542. 12,
  132543. };
  132544. static float _vq_quantthresh__44c7_s_p5_0[] = {
  132545. -5.5, 5.5,
  132546. };
  132547. static long _vq_quantmap__44c7_s_p5_0[] = {
  132548. 1, 0, 2,
  132549. };
  132550. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  132551. _vq_quantthresh__44c7_s_p5_0,
  132552. _vq_quantmap__44c7_s_p5_0,
  132553. 3,
  132554. 3
  132555. };
  132556. static static_codebook _44c7_s_p5_0 = {
  132557. 4, 81,
  132558. _vq_lengthlist__44c7_s_p5_0,
  132559. 1, -529137664, 1618345984, 2, 0,
  132560. _vq_quantlist__44c7_s_p5_0,
  132561. NULL,
  132562. &_vq_auxt__44c7_s_p5_0,
  132563. NULL,
  132564. 0
  132565. };
  132566. static long _vq_quantlist__44c7_s_p5_1[] = {
  132567. 5,
  132568. 4,
  132569. 6,
  132570. 3,
  132571. 7,
  132572. 2,
  132573. 8,
  132574. 1,
  132575. 9,
  132576. 0,
  132577. 10,
  132578. };
  132579. static long _vq_lengthlist__44c7_s_p5_1[] = {
  132580. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  132581. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  132582. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  132583. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  132584. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  132585. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  132586. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  132587. 11,11,11, 7, 7, 8, 8, 8, 8,
  132588. };
  132589. static float _vq_quantthresh__44c7_s_p5_1[] = {
  132590. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132591. 3.5, 4.5,
  132592. };
  132593. static long _vq_quantmap__44c7_s_p5_1[] = {
  132594. 9, 7, 5, 3, 1, 0, 2, 4,
  132595. 6, 8, 10,
  132596. };
  132597. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  132598. _vq_quantthresh__44c7_s_p5_1,
  132599. _vq_quantmap__44c7_s_p5_1,
  132600. 11,
  132601. 11
  132602. };
  132603. static static_codebook _44c7_s_p5_1 = {
  132604. 2, 121,
  132605. _vq_lengthlist__44c7_s_p5_1,
  132606. 1, -531365888, 1611661312, 4, 0,
  132607. _vq_quantlist__44c7_s_p5_1,
  132608. NULL,
  132609. &_vq_auxt__44c7_s_p5_1,
  132610. NULL,
  132611. 0
  132612. };
  132613. static long _vq_quantlist__44c7_s_p6_0[] = {
  132614. 6,
  132615. 5,
  132616. 7,
  132617. 4,
  132618. 8,
  132619. 3,
  132620. 9,
  132621. 2,
  132622. 10,
  132623. 1,
  132624. 11,
  132625. 0,
  132626. 12,
  132627. };
  132628. static long _vq_lengthlist__44c7_s_p6_0[] = {
  132629. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  132630. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  132631. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  132632. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  132633. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  132634. 12, 9, 9,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0,
  132635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132639. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132640. };
  132641. static float _vq_quantthresh__44c7_s_p6_0[] = {
  132642. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132643. 12.5, 17.5, 22.5, 27.5,
  132644. };
  132645. static long _vq_quantmap__44c7_s_p6_0[] = {
  132646. 11, 9, 7, 5, 3, 1, 0, 2,
  132647. 4, 6, 8, 10, 12,
  132648. };
  132649. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  132650. _vq_quantthresh__44c7_s_p6_0,
  132651. _vq_quantmap__44c7_s_p6_0,
  132652. 13,
  132653. 13
  132654. };
  132655. static static_codebook _44c7_s_p6_0 = {
  132656. 2, 169,
  132657. _vq_lengthlist__44c7_s_p6_0,
  132658. 1, -526516224, 1616117760, 4, 0,
  132659. _vq_quantlist__44c7_s_p6_0,
  132660. NULL,
  132661. &_vq_auxt__44c7_s_p6_0,
  132662. NULL,
  132663. 0
  132664. };
  132665. static long _vq_quantlist__44c7_s_p6_1[] = {
  132666. 2,
  132667. 1,
  132668. 3,
  132669. 0,
  132670. 4,
  132671. };
  132672. static long _vq_lengthlist__44c7_s_p6_1[] = {
  132673. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  132674. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132675. };
  132676. static float _vq_quantthresh__44c7_s_p6_1[] = {
  132677. -1.5, -0.5, 0.5, 1.5,
  132678. };
  132679. static long _vq_quantmap__44c7_s_p6_1[] = {
  132680. 3, 1, 0, 2, 4,
  132681. };
  132682. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  132683. _vq_quantthresh__44c7_s_p6_1,
  132684. _vq_quantmap__44c7_s_p6_1,
  132685. 5,
  132686. 5
  132687. };
  132688. static static_codebook _44c7_s_p6_1 = {
  132689. 2, 25,
  132690. _vq_lengthlist__44c7_s_p6_1,
  132691. 1, -533725184, 1611661312, 3, 0,
  132692. _vq_quantlist__44c7_s_p6_1,
  132693. NULL,
  132694. &_vq_auxt__44c7_s_p6_1,
  132695. NULL,
  132696. 0
  132697. };
  132698. static long _vq_quantlist__44c7_s_p7_0[] = {
  132699. 6,
  132700. 5,
  132701. 7,
  132702. 4,
  132703. 8,
  132704. 3,
  132705. 9,
  132706. 2,
  132707. 10,
  132708. 1,
  132709. 11,
  132710. 0,
  132711. 12,
  132712. };
  132713. static long _vq_lengthlist__44c7_s_p7_0[] = {
  132714. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  132715. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  132716. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  132717. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  132718. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  132719. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  132720. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  132721. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  132722. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  132723. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  132724. 19,13,13,13,13,14,14,15,15,
  132725. };
  132726. static float _vq_quantthresh__44c7_s_p7_0[] = {
  132727. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  132728. 27.5, 38.5, 49.5, 60.5,
  132729. };
  132730. static long _vq_quantmap__44c7_s_p7_0[] = {
  132731. 11, 9, 7, 5, 3, 1, 0, 2,
  132732. 4, 6, 8, 10, 12,
  132733. };
  132734. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_0 = {
  132735. _vq_quantthresh__44c7_s_p7_0,
  132736. _vq_quantmap__44c7_s_p7_0,
  132737. 13,
  132738. 13
  132739. };
  132740. static static_codebook _44c7_s_p7_0 = {
  132741. 2, 169,
  132742. _vq_lengthlist__44c7_s_p7_0,
  132743. 1, -523206656, 1618345984, 4, 0,
  132744. _vq_quantlist__44c7_s_p7_0,
  132745. NULL,
  132746. &_vq_auxt__44c7_s_p7_0,
  132747. NULL,
  132748. 0
  132749. };
  132750. static long _vq_quantlist__44c7_s_p7_1[] = {
  132751. 5,
  132752. 4,
  132753. 6,
  132754. 3,
  132755. 7,
  132756. 2,
  132757. 8,
  132758. 1,
  132759. 9,
  132760. 0,
  132761. 10,
  132762. };
  132763. static long _vq_lengthlist__44c7_s_p7_1[] = {
  132764. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  132765. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  132766. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  132767. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  132768. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  132769. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  132770. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  132771. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  132772. };
  132773. static float _vq_quantthresh__44c7_s_p7_1[] = {
  132774. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132775. 3.5, 4.5,
  132776. };
  132777. static long _vq_quantmap__44c7_s_p7_1[] = {
  132778. 9, 7, 5, 3, 1, 0, 2, 4,
  132779. 6, 8, 10,
  132780. };
  132781. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  132782. _vq_quantthresh__44c7_s_p7_1,
  132783. _vq_quantmap__44c7_s_p7_1,
  132784. 11,
  132785. 11
  132786. };
  132787. static static_codebook _44c7_s_p7_1 = {
  132788. 2, 121,
  132789. _vq_lengthlist__44c7_s_p7_1,
  132790. 1, -531365888, 1611661312, 4, 0,
  132791. _vq_quantlist__44c7_s_p7_1,
  132792. NULL,
  132793. &_vq_auxt__44c7_s_p7_1,
  132794. NULL,
  132795. 0
  132796. };
  132797. static long _vq_quantlist__44c7_s_p8_0[] = {
  132798. 7,
  132799. 6,
  132800. 8,
  132801. 5,
  132802. 9,
  132803. 4,
  132804. 10,
  132805. 3,
  132806. 11,
  132807. 2,
  132808. 12,
  132809. 1,
  132810. 13,
  132811. 0,
  132812. 14,
  132813. };
  132814. static long _vq_lengthlist__44c7_s_p8_0[] = {
  132815. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  132816. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  132817. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  132818. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  132819. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  132820. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  132821. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  132822. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  132823. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  132824. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  132825. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  132826. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  132827. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  132828. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  132829. 14,
  132830. };
  132831. static float _vq_quantthresh__44c7_s_p8_0[] = {
  132832. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  132833. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  132834. };
  132835. static long _vq_quantmap__44c7_s_p8_0[] = {
  132836. 13, 11, 9, 7, 5, 3, 1, 0,
  132837. 2, 4, 6, 8, 10, 12, 14,
  132838. };
  132839. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  132840. _vq_quantthresh__44c7_s_p8_0,
  132841. _vq_quantmap__44c7_s_p8_0,
  132842. 15,
  132843. 15
  132844. };
  132845. static static_codebook _44c7_s_p8_0 = {
  132846. 2, 225,
  132847. _vq_lengthlist__44c7_s_p8_0,
  132848. 1, -520986624, 1620377600, 4, 0,
  132849. _vq_quantlist__44c7_s_p8_0,
  132850. NULL,
  132851. &_vq_auxt__44c7_s_p8_0,
  132852. NULL,
  132853. 0
  132854. };
  132855. static long _vq_quantlist__44c7_s_p8_1[] = {
  132856. 10,
  132857. 9,
  132858. 11,
  132859. 8,
  132860. 12,
  132861. 7,
  132862. 13,
  132863. 6,
  132864. 14,
  132865. 5,
  132866. 15,
  132867. 4,
  132868. 16,
  132869. 3,
  132870. 17,
  132871. 2,
  132872. 18,
  132873. 1,
  132874. 19,
  132875. 0,
  132876. 20,
  132877. };
  132878. static long _vq_lengthlist__44c7_s_p8_1[] = {
  132879. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  132880. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  132881. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  132882. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  132883. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132884. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  132885. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  132886. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  132887. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132888. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132889. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  132890. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  132891. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  132892. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  132893. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  132894. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  132895. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  132896. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  132897. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  132898. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  132899. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  132900. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  132901. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  132902. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  132903. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  132904. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  132905. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  132906. 10,10,10,10,10,10,10,10,10,
  132907. };
  132908. static float _vq_quantthresh__44c7_s_p8_1[] = {
  132909. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132910. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132911. 6.5, 7.5, 8.5, 9.5,
  132912. };
  132913. static long _vq_quantmap__44c7_s_p8_1[] = {
  132914. 19, 17, 15, 13, 11, 9, 7, 5,
  132915. 3, 1, 0, 2, 4, 6, 8, 10,
  132916. 12, 14, 16, 18, 20,
  132917. };
  132918. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  132919. _vq_quantthresh__44c7_s_p8_1,
  132920. _vq_quantmap__44c7_s_p8_1,
  132921. 21,
  132922. 21
  132923. };
  132924. static static_codebook _44c7_s_p8_1 = {
  132925. 2, 441,
  132926. _vq_lengthlist__44c7_s_p8_1,
  132927. 1, -529268736, 1611661312, 5, 0,
  132928. _vq_quantlist__44c7_s_p8_1,
  132929. NULL,
  132930. &_vq_auxt__44c7_s_p8_1,
  132931. NULL,
  132932. 0
  132933. };
  132934. static long _vq_quantlist__44c7_s_p9_0[] = {
  132935. 6,
  132936. 5,
  132937. 7,
  132938. 4,
  132939. 8,
  132940. 3,
  132941. 9,
  132942. 2,
  132943. 10,
  132944. 1,
  132945. 11,
  132946. 0,
  132947. 12,
  132948. };
  132949. static long _vq_lengthlist__44c7_s_p9_0[] = {
  132950. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  132951. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  132952. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132953. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132954. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132955. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132956. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132957. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132958. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132959. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132960. 11,11,11,11,11,11,11,11,11,
  132961. };
  132962. static float _vq_quantthresh__44c7_s_p9_0[] = {
  132963. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  132964. 1592.5, 2229.5, 2866.5, 3503.5,
  132965. };
  132966. static long _vq_quantmap__44c7_s_p9_0[] = {
  132967. 11, 9, 7, 5, 3, 1, 0, 2,
  132968. 4, 6, 8, 10, 12,
  132969. };
  132970. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  132971. _vq_quantthresh__44c7_s_p9_0,
  132972. _vq_quantmap__44c7_s_p9_0,
  132973. 13,
  132974. 13
  132975. };
  132976. static static_codebook _44c7_s_p9_0 = {
  132977. 2, 169,
  132978. _vq_lengthlist__44c7_s_p9_0,
  132979. 1, -511845376, 1630791680, 4, 0,
  132980. _vq_quantlist__44c7_s_p9_0,
  132981. NULL,
  132982. &_vq_auxt__44c7_s_p9_0,
  132983. NULL,
  132984. 0
  132985. };
  132986. static long _vq_quantlist__44c7_s_p9_1[] = {
  132987. 6,
  132988. 5,
  132989. 7,
  132990. 4,
  132991. 8,
  132992. 3,
  132993. 9,
  132994. 2,
  132995. 10,
  132996. 1,
  132997. 11,
  132998. 0,
  132999. 12,
  133000. };
  133001. static long _vq_lengthlist__44c7_s_p9_1[] = {
  133002. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  133003. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  133004. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  133005. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  133006. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  133007. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  133008. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  133009. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  133010. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  133011. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  133012. 15,11,11,10,10,12,12,12,12,
  133013. };
  133014. static float _vq_quantthresh__44c7_s_p9_1[] = {
  133015. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  133016. 122.5, 171.5, 220.5, 269.5,
  133017. };
  133018. static long _vq_quantmap__44c7_s_p9_1[] = {
  133019. 11, 9, 7, 5, 3, 1, 0, 2,
  133020. 4, 6, 8, 10, 12,
  133021. };
  133022. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  133023. _vq_quantthresh__44c7_s_p9_1,
  133024. _vq_quantmap__44c7_s_p9_1,
  133025. 13,
  133026. 13
  133027. };
  133028. static static_codebook _44c7_s_p9_1 = {
  133029. 2, 169,
  133030. _vq_lengthlist__44c7_s_p9_1,
  133031. 1, -518889472, 1622704128, 4, 0,
  133032. _vq_quantlist__44c7_s_p9_1,
  133033. NULL,
  133034. &_vq_auxt__44c7_s_p9_1,
  133035. NULL,
  133036. 0
  133037. };
  133038. static long _vq_quantlist__44c7_s_p9_2[] = {
  133039. 24,
  133040. 23,
  133041. 25,
  133042. 22,
  133043. 26,
  133044. 21,
  133045. 27,
  133046. 20,
  133047. 28,
  133048. 19,
  133049. 29,
  133050. 18,
  133051. 30,
  133052. 17,
  133053. 31,
  133054. 16,
  133055. 32,
  133056. 15,
  133057. 33,
  133058. 14,
  133059. 34,
  133060. 13,
  133061. 35,
  133062. 12,
  133063. 36,
  133064. 11,
  133065. 37,
  133066. 10,
  133067. 38,
  133068. 9,
  133069. 39,
  133070. 8,
  133071. 40,
  133072. 7,
  133073. 41,
  133074. 6,
  133075. 42,
  133076. 5,
  133077. 43,
  133078. 4,
  133079. 44,
  133080. 3,
  133081. 45,
  133082. 2,
  133083. 46,
  133084. 1,
  133085. 47,
  133086. 0,
  133087. 48,
  133088. };
  133089. static long _vq_lengthlist__44c7_s_p9_2[] = {
  133090. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  133091. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133092. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133093. 7,
  133094. };
  133095. static float _vq_quantthresh__44c7_s_p9_2[] = {
  133096. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  133097. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  133098. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133099. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133100. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  133101. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  133102. };
  133103. static long _vq_quantmap__44c7_s_p9_2[] = {
  133104. 47, 45, 43, 41, 39, 37, 35, 33,
  133105. 31, 29, 27, 25, 23, 21, 19, 17,
  133106. 15, 13, 11, 9, 7, 5, 3, 1,
  133107. 0, 2, 4, 6, 8, 10, 12, 14,
  133108. 16, 18, 20, 22, 24, 26, 28, 30,
  133109. 32, 34, 36, 38, 40, 42, 44, 46,
  133110. 48,
  133111. };
  133112. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  133113. _vq_quantthresh__44c7_s_p9_2,
  133114. _vq_quantmap__44c7_s_p9_2,
  133115. 49,
  133116. 49
  133117. };
  133118. static static_codebook _44c7_s_p9_2 = {
  133119. 1, 49,
  133120. _vq_lengthlist__44c7_s_p9_2,
  133121. 1, -526909440, 1611661312, 6, 0,
  133122. _vq_quantlist__44c7_s_p9_2,
  133123. NULL,
  133124. &_vq_auxt__44c7_s_p9_2,
  133125. NULL,
  133126. 0
  133127. };
  133128. static long _huff_lengthlist__44c7_s_short[] = {
  133129. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  133130. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  133131. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  133132. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  133133. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  133134. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  133135. 10, 9,11,14,
  133136. };
  133137. static static_codebook _huff_book__44c7_s_short = {
  133138. 2, 100,
  133139. _huff_lengthlist__44c7_s_short,
  133140. 0, 0, 0, 0, 0,
  133141. NULL,
  133142. NULL,
  133143. NULL,
  133144. NULL,
  133145. 0
  133146. };
  133147. static long _huff_lengthlist__44c8_s_long[] = {
  133148. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  133149. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  133150. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  133151. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  133152. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  133153. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  133154. 11, 9, 9,10,
  133155. };
  133156. static static_codebook _huff_book__44c8_s_long = {
  133157. 2, 100,
  133158. _huff_lengthlist__44c8_s_long,
  133159. 0, 0, 0, 0, 0,
  133160. NULL,
  133161. NULL,
  133162. NULL,
  133163. NULL,
  133164. 0
  133165. };
  133166. static long _vq_quantlist__44c8_s_p1_0[] = {
  133167. 1,
  133168. 0,
  133169. 2,
  133170. };
  133171. static long _vq_lengthlist__44c8_s_p1_0[] = {
  133172. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  133173. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  133174. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  133175. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  133176. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  133177. 8,
  133178. };
  133179. static float _vq_quantthresh__44c8_s_p1_0[] = {
  133180. -0.5, 0.5,
  133181. };
  133182. static long _vq_quantmap__44c8_s_p1_0[] = {
  133183. 1, 0, 2,
  133184. };
  133185. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  133186. _vq_quantthresh__44c8_s_p1_0,
  133187. _vq_quantmap__44c8_s_p1_0,
  133188. 3,
  133189. 3
  133190. };
  133191. static static_codebook _44c8_s_p1_0 = {
  133192. 4, 81,
  133193. _vq_lengthlist__44c8_s_p1_0,
  133194. 1, -535822336, 1611661312, 2, 0,
  133195. _vq_quantlist__44c8_s_p1_0,
  133196. NULL,
  133197. &_vq_auxt__44c8_s_p1_0,
  133198. NULL,
  133199. 0
  133200. };
  133201. static long _vq_quantlist__44c8_s_p2_0[] = {
  133202. 2,
  133203. 1,
  133204. 3,
  133205. 0,
  133206. 4,
  133207. };
  133208. static long _vq_lengthlist__44c8_s_p2_0[] = {
  133209. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  133210. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  133211. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  133212. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  133213. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  133214. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  133215. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  133216. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  133217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133218. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  133219. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  133220. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  133221. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  133222. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  133223. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  133224. 0,12,12,13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0,
  133225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133226. 0, 0, 0, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  133227. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  133228. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  133229. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  133230. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  133231. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  133232. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133234. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  133235. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  133236. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  133237. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  133238. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  133239. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  133240. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  133245. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  133246. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  133247. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  133248. 13,
  133249. };
  133250. static float _vq_quantthresh__44c8_s_p2_0[] = {
  133251. -1.5, -0.5, 0.5, 1.5,
  133252. };
  133253. static long _vq_quantmap__44c8_s_p2_0[] = {
  133254. 3, 1, 0, 2, 4,
  133255. };
  133256. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  133257. _vq_quantthresh__44c8_s_p2_0,
  133258. _vq_quantmap__44c8_s_p2_0,
  133259. 5,
  133260. 5
  133261. };
  133262. static static_codebook _44c8_s_p2_0 = {
  133263. 4, 625,
  133264. _vq_lengthlist__44c8_s_p2_0,
  133265. 1, -533725184, 1611661312, 3, 0,
  133266. _vq_quantlist__44c8_s_p2_0,
  133267. NULL,
  133268. &_vq_auxt__44c8_s_p2_0,
  133269. NULL,
  133270. 0
  133271. };
  133272. static long _vq_quantlist__44c8_s_p3_0[] = {
  133273. 4,
  133274. 3,
  133275. 5,
  133276. 2,
  133277. 6,
  133278. 1,
  133279. 7,
  133280. 0,
  133281. 8,
  133282. };
  133283. static long _vq_lengthlist__44c8_s_p3_0[] = {
  133284. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  133285. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  133286. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  133287. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  133288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133289. 0,
  133290. };
  133291. static float _vq_quantthresh__44c8_s_p3_0[] = {
  133292. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133293. };
  133294. static long _vq_quantmap__44c8_s_p3_0[] = {
  133295. 7, 5, 3, 1, 0, 2, 4, 6,
  133296. 8,
  133297. };
  133298. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  133299. _vq_quantthresh__44c8_s_p3_0,
  133300. _vq_quantmap__44c8_s_p3_0,
  133301. 9,
  133302. 9
  133303. };
  133304. static static_codebook _44c8_s_p3_0 = {
  133305. 2, 81,
  133306. _vq_lengthlist__44c8_s_p3_0,
  133307. 1, -531628032, 1611661312, 4, 0,
  133308. _vq_quantlist__44c8_s_p3_0,
  133309. NULL,
  133310. &_vq_auxt__44c8_s_p3_0,
  133311. NULL,
  133312. 0
  133313. };
  133314. static long _vq_quantlist__44c8_s_p4_0[] = {
  133315. 8,
  133316. 7,
  133317. 9,
  133318. 6,
  133319. 10,
  133320. 5,
  133321. 11,
  133322. 4,
  133323. 12,
  133324. 3,
  133325. 13,
  133326. 2,
  133327. 14,
  133328. 1,
  133329. 15,
  133330. 0,
  133331. 16,
  133332. };
  133333. static long _vq_lengthlist__44c8_s_p4_0[] = {
  133334. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  133335. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  133336. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  133337. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  133338. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  133339. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  133340. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  133341. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  133342. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  133343. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  133344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133352. 0,
  133353. };
  133354. static float _vq_quantthresh__44c8_s_p4_0[] = {
  133355. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133356. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133357. };
  133358. static long _vq_quantmap__44c8_s_p4_0[] = {
  133359. 15, 13, 11, 9, 7, 5, 3, 1,
  133360. 0, 2, 4, 6, 8, 10, 12, 14,
  133361. 16,
  133362. };
  133363. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  133364. _vq_quantthresh__44c8_s_p4_0,
  133365. _vq_quantmap__44c8_s_p4_0,
  133366. 17,
  133367. 17
  133368. };
  133369. static static_codebook _44c8_s_p4_0 = {
  133370. 2, 289,
  133371. _vq_lengthlist__44c8_s_p4_0,
  133372. 1, -529530880, 1611661312, 5, 0,
  133373. _vq_quantlist__44c8_s_p4_0,
  133374. NULL,
  133375. &_vq_auxt__44c8_s_p4_0,
  133376. NULL,
  133377. 0
  133378. };
  133379. static long _vq_quantlist__44c8_s_p5_0[] = {
  133380. 1,
  133381. 0,
  133382. 2,
  133383. };
  133384. static long _vq_lengthlist__44c8_s_p5_0[] = {
  133385. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  133386. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  133387. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  133388. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  133389. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  133390. 12,
  133391. };
  133392. static float _vq_quantthresh__44c8_s_p5_0[] = {
  133393. -5.5, 5.5,
  133394. };
  133395. static long _vq_quantmap__44c8_s_p5_0[] = {
  133396. 1, 0, 2,
  133397. };
  133398. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  133399. _vq_quantthresh__44c8_s_p5_0,
  133400. _vq_quantmap__44c8_s_p5_0,
  133401. 3,
  133402. 3
  133403. };
  133404. static static_codebook _44c8_s_p5_0 = {
  133405. 4, 81,
  133406. _vq_lengthlist__44c8_s_p5_0,
  133407. 1, -529137664, 1618345984, 2, 0,
  133408. _vq_quantlist__44c8_s_p5_0,
  133409. NULL,
  133410. &_vq_auxt__44c8_s_p5_0,
  133411. NULL,
  133412. 0
  133413. };
  133414. static long _vq_quantlist__44c8_s_p5_1[] = {
  133415. 5,
  133416. 4,
  133417. 6,
  133418. 3,
  133419. 7,
  133420. 2,
  133421. 8,
  133422. 1,
  133423. 9,
  133424. 0,
  133425. 10,
  133426. };
  133427. static long _vq_lengthlist__44c8_s_p5_1[] = {
  133428. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  133429. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  133430. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  133431. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  133432. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  133433. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  133434. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  133435. 11,11,11, 7, 7, 7, 7, 8, 8,
  133436. };
  133437. static float _vq_quantthresh__44c8_s_p5_1[] = {
  133438. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133439. 3.5, 4.5,
  133440. };
  133441. static long _vq_quantmap__44c8_s_p5_1[] = {
  133442. 9, 7, 5, 3, 1, 0, 2, 4,
  133443. 6, 8, 10,
  133444. };
  133445. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  133446. _vq_quantthresh__44c8_s_p5_1,
  133447. _vq_quantmap__44c8_s_p5_1,
  133448. 11,
  133449. 11
  133450. };
  133451. static static_codebook _44c8_s_p5_1 = {
  133452. 2, 121,
  133453. _vq_lengthlist__44c8_s_p5_1,
  133454. 1, -531365888, 1611661312, 4, 0,
  133455. _vq_quantlist__44c8_s_p5_1,
  133456. NULL,
  133457. &_vq_auxt__44c8_s_p5_1,
  133458. NULL,
  133459. 0
  133460. };
  133461. static long _vq_quantlist__44c8_s_p6_0[] = {
  133462. 6,
  133463. 5,
  133464. 7,
  133465. 4,
  133466. 8,
  133467. 3,
  133468. 9,
  133469. 2,
  133470. 10,
  133471. 1,
  133472. 11,
  133473. 0,
  133474. 12,
  133475. };
  133476. static long _vq_lengthlist__44c8_s_p6_0[] = {
  133477. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  133478. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  133479. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  133480. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  133481. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  133482. 12, 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  133483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133487. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133488. };
  133489. static float _vq_quantthresh__44c8_s_p6_0[] = {
  133490. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133491. 12.5, 17.5, 22.5, 27.5,
  133492. };
  133493. static long _vq_quantmap__44c8_s_p6_0[] = {
  133494. 11, 9, 7, 5, 3, 1, 0, 2,
  133495. 4, 6, 8, 10, 12,
  133496. };
  133497. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  133498. _vq_quantthresh__44c8_s_p6_0,
  133499. _vq_quantmap__44c8_s_p6_0,
  133500. 13,
  133501. 13
  133502. };
  133503. static static_codebook _44c8_s_p6_0 = {
  133504. 2, 169,
  133505. _vq_lengthlist__44c8_s_p6_0,
  133506. 1, -526516224, 1616117760, 4, 0,
  133507. _vq_quantlist__44c8_s_p6_0,
  133508. NULL,
  133509. &_vq_auxt__44c8_s_p6_0,
  133510. NULL,
  133511. 0
  133512. };
  133513. static long _vq_quantlist__44c8_s_p6_1[] = {
  133514. 2,
  133515. 1,
  133516. 3,
  133517. 0,
  133518. 4,
  133519. };
  133520. static long _vq_lengthlist__44c8_s_p6_1[] = {
  133521. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  133522. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  133523. };
  133524. static float _vq_quantthresh__44c8_s_p6_1[] = {
  133525. -1.5, -0.5, 0.5, 1.5,
  133526. };
  133527. static long _vq_quantmap__44c8_s_p6_1[] = {
  133528. 3, 1, 0, 2, 4,
  133529. };
  133530. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  133531. _vq_quantthresh__44c8_s_p6_1,
  133532. _vq_quantmap__44c8_s_p6_1,
  133533. 5,
  133534. 5
  133535. };
  133536. static static_codebook _44c8_s_p6_1 = {
  133537. 2, 25,
  133538. _vq_lengthlist__44c8_s_p6_1,
  133539. 1, -533725184, 1611661312, 3, 0,
  133540. _vq_quantlist__44c8_s_p6_1,
  133541. NULL,
  133542. &_vq_auxt__44c8_s_p6_1,
  133543. NULL,
  133544. 0
  133545. };
  133546. static long _vq_quantlist__44c8_s_p7_0[] = {
  133547. 6,
  133548. 5,
  133549. 7,
  133550. 4,
  133551. 8,
  133552. 3,
  133553. 9,
  133554. 2,
  133555. 10,
  133556. 1,
  133557. 11,
  133558. 0,
  133559. 12,
  133560. };
  133561. static long _vq_lengthlist__44c8_s_p7_0[] = {
  133562. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  133563. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  133564. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  133565. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  133566. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  133567. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  133568. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  133569. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  133570. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  133571. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  133572. 20,13,13,13,13,14,13,15,15,
  133573. };
  133574. static float _vq_quantthresh__44c8_s_p7_0[] = {
  133575. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  133576. 27.5, 38.5, 49.5, 60.5,
  133577. };
  133578. static long _vq_quantmap__44c8_s_p7_0[] = {
  133579. 11, 9, 7, 5, 3, 1, 0, 2,
  133580. 4, 6, 8, 10, 12,
  133581. };
  133582. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  133583. _vq_quantthresh__44c8_s_p7_0,
  133584. _vq_quantmap__44c8_s_p7_0,
  133585. 13,
  133586. 13
  133587. };
  133588. static static_codebook _44c8_s_p7_0 = {
  133589. 2, 169,
  133590. _vq_lengthlist__44c8_s_p7_0,
  133591. 1, -523206656, 1618345984, 4, 0,
  133592. _vq_quantlist__44c8_s_p7_0,
  133593. NULL,
  133594. &_vq_auxt__44c8_s_p7_0,
  133595. NULL,
  133596. 0
  133597. };
  133598. static long _vq_quantlist__44c8_s_p7_1[] = {
  133599. 5,
  133600. 4,
  133601. 6,
  133602. 3,
  133603. 7,
  133604. 2,
  133605. 8,
  133606. 1,
  133607. 9,
  133608. 0,
  133609. 10,
  133610. };
  133611. static long _vq_lengthlist__44c8_s_p7_1[] = {
  133612. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  133613. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  133614. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  133615. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133616. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  133617. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  133618. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  133619. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133620. };
  133621. static float _vq_quantthresh__44c8_s_p7_1[] = {
  133622. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133623. 3.5, 4.5,
  133624. };
  133625. static long _vq_quantmap__44c8_s_p7_1[] = {
  133626. 9, 7, 5, 3, 1, 0, 2, 4,
  133627. 6, 8, 10,
  133628. };
  133629. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  133630. _vq_quantthresh__44c8_s_p7_1,
  133631. _vq_quantmap__44c8_s_p7_1,
  133632. 11,
  133633. 11
  133634. };
  133635. static static_codebook _44c8_s_p7_1 = {
  133636. 2, 121,
  133637. _vq_lengthlist__44c8_s_p7_1,
  133638. 1, -531365888, 1611661312, 4, 0,
  133639. _vq_quantlist__44c8_s_p7_1,
  133640. NULL,
  133641. &_vq_auxt__44c8_s_p7_1,
  133642. NULL,
  133643. 0
  133644. };
  133645. static long _vq_quantlist__44c8_s_p8_0[] = {
  133646. 7,
  133647. 6,
  133648. 8,
  133649. 5,
  133650. 9,
  133651. 4,
  133652. 10,
  133653. 3,
  133654. 11,
  133655. 2,
  133656. 12,
  133657. 1,
  133658. 13,
  133659. 0,
  133660. 14,
  133661. };
  133662. static long _vq_lengthlist__44c8_s_p8_0[] = {
  133663. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  133664. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  133665. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  133666. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  133667. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  133668. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  133669. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  133670. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  133671. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  133672. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  133673. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  133674. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  133675. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  133676. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  133677. 15,
  133678. };
  133679. static float _vq_quantthresh__44c8_s_p8_0[] = {
  133680. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  133681. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  133682. };
  133683. static long _vq_quantmap__44c8_s_p8_0[] = {
  133684. 13, 11, 9, 7, 5, 3, 1, 0,
  133685. 2, 4, 6, 8, 10, 12, 14,
  133686. };
  133687. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  133688. _vq_quantthresh__44c8_s_p8_0,
  133689. _vq_quantmap__44c8_s_p8_0,
  133690. 15,
  133691. 15
  133692. };
  133693. static static_codebook _44c8_s_p8_0 = {
  133694. 2, 225,
  133695. _vq_lengthlist__44c8_s_p8_0,
  133696. 1, -520986624, 1620377600, 4, 0,
  133697. _vq_quantlist__44c8_s_p8_0,
  133698. NULL,
  133699. &_vq_auxt__44c8_s_p8_0,
  133700. NULL,
  133701. 0
  133702. };
  133703. static long _vq_quantlist__44c8_s_p8_1[] = {
  133704. 10,
  133705. 9,
  133706. 11,
  133707. 8,
  133708. 12,
  133709. 7,
  133710. 13,
  133711. 6,
  133712. 14,
  133713. 5,
  133714. 15,
  133715. 4,
  133716. 16,
  133717. 3,
  133718. 17,
  133719. 2,
  133720. 18,
  133721. 1,
  133722. 19,
  133723. 0,
  133724. 20,
  133725. };
  133726. static long _vq_lengthlist__44c8_s_p8_1[] = {
  133727. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  133728. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  133729. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  133730. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  133731. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133732. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  133733. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  133734. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  133735. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133736. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133737. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  133738. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  133739. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  133740. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133741. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  133742. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  133743. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  133744. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  133745. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  133746. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  133747. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  133748. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  133749. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  133750. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  133751. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  133752. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  133753. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  133754. 10, 9, 9,10,10, 9,10, 9, 9,
  133755. };
  133756. static float _vq_quantthresh__44c8_s_p8_1[] = {
  133757. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  133758. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  133759. 6.5, 7.5, 8.5, 9.5,
  133760. };
  133761. static long _vq_quantmap__44c8_s_p8_1[] = {
  133762. 19, 17, 15, 13, 11, 9, 7, 5,
  133763. 3, 1, 0, 2, 4, 6, 8, 10,
  133764. 12, 14, 16, 18, 20,
  133765. };
  133766. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  133767. _vq_quantthresh__44c8_s_p8_1,
  133768. _vq_quantmap__44c8_s_p8_1,
  133769. 21,
  133770. 21
  133771. };
  133772. static static_codebook _44c8_s_p8_1 = {
  133773. 2, 441,
  133774. _vq_lengthlist__44c8_s_p8_1,
  133775. 1, -529268736, 1611661312, 5, 0,
  133776. _vq_quantlist__44c8_s_p8_1,
  133777. NULL,
  133778. &_vq_auxt__44c8_s_p8_1,
  133779. NULL,
  133780. 0
  133781. };
  133782. static long _vq_quantlist__44c8_s_p9_0[] = {
  133783. 8,
  133784. 7,
  133785. 9,
  133786. 6,
  133787. 10,
  133788. 5,
  133789. 11,
  133790. 4,
  133791. 12,
  133792. 3,
  133793. 13,
  133794. 2,
  133795. 14,
  133796. 1,
  133797. 15,
  133798. 0,
  133799. 16,
  133800. };
  133801. static long _vq_lengthlist__44c8_s_p9_0[] = {
  133802. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133803. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  133804. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  133805. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133806. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133807. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133808. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133809. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133810. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133811. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133812. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133813. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133814. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133815. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133816. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133817. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133818. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133819. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133820. 10,
  133821. };
  133822. static float _vq_quantthresh__44c8_s_p9_0[] = {
  133823. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  133824. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  133825. };
  133826. static long _vq_quantmap__44c8_s_p9_0[] = {
  133827. 15, 13, 11, 9, 7, 5, 3, 1,
  133828. 0, 2, 4, 6, 8, 10, 12, 14,
  133829. 16,
  133830. };
  133831. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  133832. _vq_quantthresh__44c8_s_p9_0,
  133833. _vq_quantmap__44c8_s_p9_0,
  133834. 17,
  133835. 17
  133836. };
  133837. static static_codebook _44c8_s_p9_0 = {
  133838. 2, 289,
  133839. _vq_lengthlist__44c8_s_p9_0,
  133840. 1, -509798400, 1631393792, 5, 0,
  133841. _vq_quantlist__44c8_s_p9_0,
  133842. NULL,
  133843. &_vq_auxt__44c8_s_p9_0,
  133844. NULL,
  133845. 0
  133846. };
  133847. static long _vq_quantlist__44c8_s_p9_1[] = {
  133848. 9,
  133849. 8,
  133850. 10,
  133851. 7,
  133852. 11,
  133853. 6,
  133854. 12,
  133855. 5,
  133856. 13,
  133857. 4,
  133858. 14,
  133859. 3,
  133860. 15,
  133861. 2,
  133862. 16,
  133863. 1,
  133864. 17,
  133865. 0,
  133866. 18,
  133867. };
  133868. static long _vq_lengthlist__44c8_s_p9_1[] = {
  133869. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  133870. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  133871. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  133872. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  133873. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  133874. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  133875. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  133876. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  133877. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  133878. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  133879. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  133880. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  133881. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  133882. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  133883. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  133884. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  133885. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  133886. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  133887. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  133888. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  133889. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  133890. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  133891. 14,13,13,14,14,15,14,15,14,
  133892. };
  133893. static float _vq_quantthresh__44c8_s_p9_1[] = {
  133894. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  133895. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  133896. 367.5, 416.5,
  133897. };
  133898. static long _vq_quantmap__44c8_s_p9_1[] = {
  133899. 17, 15, 13, 11, 9, 7, 5, 3,
  133900. 1, 0, 2, 4, 6, 8, 10, 12,
  133901. 14, 16, 18,
  133902. };
  133903. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  133904. _vq_quantthresh__44c8_s_p9_1,
  133905. _vq_quantmap__44c8_s_p9_1,
  133906. 19,
  133907. 19
  133908. };
  133909. static static_codebook _44c8_s_p9_1 = {
  133910. 2, 361,
  133911. _vq_lengthlist__44c8_s_p9_1,
  133912. 1, -518287360, 1622704128, 5, 0,
  133913. _vq_quantlist__44c8_s_p9_1,
  133914. NULL,
  133915. &_vq_auxt__44c8_s_p9_1,
  133916. NULL,
  133917. 0
  133918. };
  133919. static long _vq_quantlist__44c8_s_p9_2[] = {
  133920. 24,
  133921. 23,
  133922. 25,
  133923. 22,
  133924. 26,
  133925. 21,
  133926. 27,
  133927. 20,
  133928. 28,
  133929. 19,
  133930. 29,
  133931. 18,
  133932. 30,
  133933. 17,
  133934. 31,
  133935. 16,
  133936. 32,
  133937. 15,
  133938. 33,
  133939. 14,
  133940. 34,
  133941. 13,
  133942. 35,
  133943. 12,
  133944. 36,
  133945. 11,
  133946. 37,
  133947. 10,
  133948. 38,
  133949. 9,
  133950. 39,
  133951. 8,
  133952. 40,
  133953. 7,
  133954. 41,
  133955. 6,
  133956. 42,
  133957. 5,
  133958. 43,
  133959. 4,
  133960. 44,
  133961. 3,
  133962. 45,
  133963. 2,
  133964. 46,
  133965. 1,
  133966. 47,
  133967. 0,
  133968. 48,
  133969. };
  133970. static long _vq_lengthlist__44c8_s_p9_2[] = {
  133971. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  133972. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133973. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133974. 7,
  133975. };
  133976. static float _vq_quantthresh__44c8_s_p9_2[] = {
  133977. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  133978. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  133979. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133980. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133981. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  133982. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  133983. };
  133984. static long _vq_quantmap__44c8_s_p9_2[] = {
  133985. 47, 45, 43, 41, 39, 37, 35, 33,
  133986. 31, 29, 27, 25, 23, 21, 19, 17,
  133987. 15, 13, 11, 9, 7, 5, 3, 1,
  133988. 0, 2, 4, 6, 8, 10, 12, 14,
  133989. 16, 18, 20, 22, 24, 26, 28, 30,
  133990. 32, 34, 36, 38, 40, 42, 44, 46,
  133991. 48,
  133992. };
  133993. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  133994. _vq_quantthresh__44c8_s_p9_2,
  133995. _vq_quantmap__44c8_s_p9_2,
  133996. 49,
  133997. 49
  133998. };
  133999. static static_codebook _44c8_s_p9_2 = {
  134000. 1, 49,
  134001. _vq_lengthlist__44c8_s_p9_2,
  134002. 1, -526909440, 1611661312, 6, 0,
  134003. _vq_quantlist__44c8_s_p9_2,
  134004. NULL,
  134005. &_vq_auxt__44c8_s_p9_2,
  134006. NULL,
  134007. 0
  134008. };
  134009. static long _huff_lengthlist__44c8_s_short[] = {
  134010. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  134011. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  134012. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  134013. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  134014. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  134015. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  134016. 10, 9,11,14,
  134017. };
  134018. static static_codebook _huff_book__44c8_s_short = {
  134019. 2, 100,
  134020. _huff_lengthlist__44c8_s_short,
  134021. 0, 0, 0, 0, 0,
  134022. NULL,
  134023. NULL,
  134024. NULL,
  134025. NULL,
  134026. 0
  134027. };
  134028. static long _huff_lengthlist__44c9_s_long[] = {
  134029. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  134030. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  134031. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  134032. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  134033. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  134034. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  134035. 10, 9, 8, 9,
  134036. };
  134037. static static_codebook _huff_book__44c9_s_long = {
  134038. 2, 100,
  134039. _huff_lengthlist__44c9_s_long,
  134040. 0, 0, 0, 0, 0,
  134041. NULL,
  134042. NULL,
  134043. NULL,
  134044. NULL,
  134045. 0
  134046. };
  134047. static long _vq_quantlist__44c9_s_p1_0[] = {
  134048. 1,
  134049. 0,
  134050. 2,
  134051. };
  134052. static long _vq_lengthlist__44c9_s_p1_0[] = {
  134053. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  134054. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  134055. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  134056. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  134057. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  134058. 7,
  134059. };
  134060. static float _vq_quantthresh__44c9_s_p1_0[] = {
  134061. -0.5, 0.5,
  134062. };
  134063. static long _vq_quantmap__44c9_s_p1_0[] = {
  134064. 1, 0, 2,
  134065. };
  134066. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  134067. _vq_quantthresh__44c9_s_p1_0,
  134068. _vq_quantmap__44c9_s_p1_0,
  134069. 3,
  134070. 3
  134071. };
  134072. static static_codebook _44c9_s_p1_0 = {
  134073. 4, 81,
  134074. _vq_lengthlist__44c9_s_p1_0,
  134075. 1, -535822336, 1611661312, 2, 0,
  134076. _vq_quantlist__44c9_s_p1_0,
  134077. NULL,
  134078. &_vq_auxt__44c9_s_p1_0,
  134079. NULL,
  134080. 0
  134081. };
  134082. static long _vq_quantlist__44c9_s_p2_0[] = {
  134083. 2,
  134084. 1,
  134085. 3,
  134086. 0,
  134087. 4,
  134088. };
  134089. static long _vq_lengthlist__44c9_s_p2_0[] = {
  134090. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  134091. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  134092. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  134093. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  134094. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  134095. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  134096. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  134097. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 0, 0, 0,
  134098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134099. 0, 0, 0, 0, 0, 0, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  134100. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  134101. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  134102. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  134103. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  134104. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  134105. 0,12,12,12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0,
  134106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134107. 0, 0, 0, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  134108. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  134109. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  134110. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  134111. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  134112. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  134113. 12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134115. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  134116. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  134117. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  134118. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  134119. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  134120. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  134121. 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  134126. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  134127. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  134128. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  134129. 12,
  134130. };
  134131. static float _vq_quantthresh__44c9_s_p2_0[] = {
  134132. -1.5, -0.5, 0.5, 1.5,
  134133. };
  134134. static long _vq_quantmap__44c9_s_p2_0[] = {
  134135. 3, 1, 0, 2, 4,
  134136. };
  134137. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  134138. _vq_quantthresh__44c9_s_p2_0,
  134139. _vq_quantmap__44c9_s_p2_0,
  134140. 5,
  134141. 5
  134142. };
  134143. static static_codebook _44c9_s_p2_0 = {
  134144. 4, 625,
  134145. _vq_lengthlist__44c9_s_p2_0,
  134146. 1, -533725184, 1611661312, 3, 0,
  134147. _vq_quantlist__44c9_s_p2_0,
  134148. NULL,
  134149. &_vq_auxt__44c9_s_p2_0,
  134150. NULL,
  134151. 0
  134152. };
  134153. static long _vq_quantlist__44c9_s_p3_0[] = {
  134154. 4,
  134155. 3,
  134156. 5,
  134157. 2,
  134158. 6,
  134159. 1,
  134160. 7,
  134161. 0,
  134162. 8,
  134163. };
  134164. static long _vq_lengthlist__44c9_s_p3_0[] = {
  134165. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  134166. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  134167. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  134168. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  134169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134170. 0,
  134171. };
  134172. static float _vq_quantthresh__44c9_s_p3_0[] = {
  134173. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134174. };
  134175. static long _vq_quantmap__44c9_s_p3_0[] = {
  134176. 7, 5, 3, 1, 0, 2, 4, 6,
  134177. 8,
  134178. };
  134179. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  134180. _vq_quantthresh__44c9_s_p3_0,
  134181. _vq_quantmap__44c9_s_p3_0,
  134182. 9,
  134183. 9
  134184. };
  134185. static static_codebook _44c9_s_p3_0 = {
  134186. 2, 81,
  134187. _vq_lengthlist__44c9_s_p3_0,
  134188. 1, -531628032, 1611661312, 4, 0,
  134189. _vq_quantlist__44c9_s_p3_0,
  134190. NULL,
  134191. &_vq_auxt__44c9_s_p3_0,
  134192. NULL,
  134193. 0
  134194. };
  134195. static long _vq_quantlist__44c9_s_p4_0[] = {
  134196. 8,
  134197. 7,
  134198. 9,
  134199. 6,
  134200. 10,
  134201. 5,
  134202. 11,
  134203. 4,
  134204. 12,
  134205. 3,
  134206. 13,
  134207. 2,
  134208. 14,
  134209. 1,
  134210. 15,
  134211. 0,
  134212. 16,
  134213. };
  134214. static long _vq_lengthlist__44c9_s_p4_0[] = {
  134215. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  134216. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  134217. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  134218. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  134219. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  134220. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  134221. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  134222. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  134223. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  134224. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  134225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134233. 0,
  134234. };
  134235. static float _vq_quantthresh__44c9_s_p4_0[] = {
  134236. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134237. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134238. };
  134239. static long _vq_quantmap__44c9_s_p4_0[] = {
  134240. 15, 13, 11, 9, 7, 5, 3, 1,
  134241. 0, 2, 4, 6, 8, 10, 12, 14,
  134242. 16,
  134243. };
  134244. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  134245. _vq_quantthresh__44c9_s_p4_0,
  134246. _vq_quantmap__44c9_s_p4_0,
  134247. 17,
  134248. 17
  134249. };
  134250. static static_codebook _44c9_s_p4_0 = {
  134251. 2, 289,
  134252. _vq_lengthlist__44c9_s_p4_0,
  134253. 1, -529530880, 1611661312, 5, 0,
  134254. _vq_quantlist__44c9_s_p4_0,
  134255. NULL,
  134256. &_vq_auxt__44c9_s_p4_0,
  134257. NULL,
  134258. 0
  134259. };
  134260. static long _vq_quantlist__44c9_s_p5_0[] = {
  134261. 1,
  134262. 0,
  134263. 2,
  134264. };
  134265. static long _vq_lengthlist__44c9_s_p5_0[] = {
  134266. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  134267. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  134268. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  134269. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  134270. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  134271. 12,
  134272. };
  134273. static float _vq_quantthresh__44c9_s_p5_0[] = {
  134274. -5.5, 5.5,
  134275. };
  134276. static long _vq_quantmap__44c9_s_p5_0[] = {
  134277. 1, 0, 2,
  134278. };
  134279. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  134280. _vq_quantthresh__44c9_s_p5_0,
  134281. _vq_quantmap__44c9_s_p5_0,
  134282. 3,
  134283. 3
  134284. };
  134285. static static_codebook _44c9_s_p5_0 = {
  134286. 4, 81,
  134287. _vq_lengthlist__44c9_s_p5_0,
  134288. 1, -529137664, 1618345984, 2, 0,
  134289. _vq_quantlist__44c9_s_p5_0,
  134290. NULL,
  134291. &_vq_auxt__44c9_s_p5_0,
  134292. NULL,
  134293. 0
  134294. };
  134295. static long _vq_quantlist__44c9_s_p5_1[] = {
  134296. 5,
  134297. 4,
  134298. 6,
  134299. 3,
  134300. 7,
  134301. 2,
  134302. 8,
  134303. 1,
  134304. 9,
  134305. 0,
  134306. 10,
  134307. };
  134308. static long _vq_lengthlist__44c9_s_p5_1[] = {
  134309. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  134310. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  134311. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  134312. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  134313. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  134314. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  134315. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  134316. 11,11,11, 7, 7, 7, 7, 7, 7,
  134317. };
  134318. static float _vq_quantthresh__44c9_s_p5_1[] = {
  134319. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134320. 3.5, 4.5,
  134321. };
  134322. static long _vq_quantmap__44c9_s_p5_1[] = {
  134323. 9, 7, 5, 3, 1, 0, 2, 4,
  134324. 6, 8, 10,
  134325. };
  134326. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  134327. _vq_quantthresh__44c9_s_p5_1,
  134328. _vq_quantmap__44c9_s_p5_1,
  134329. 11,
  134330. 11
  134331. };
  134332. static static_codebook _44c9_s_p5_1 = {
  134333. 2, 121,
  134334. _vq_lengthlist__44c9_s_p5_1,
  134335. 1, -531365888, 1611661312, 4, 0,
  134336. _vq_quantlist__44c9_s_p5_1,
  134337. NULL,
  134338. &_vq_auxt__44c9_s_p5_1,
  134339. NULL,
  134340. 0
  134341. };
  134342. static long _vq_quantlist__44c9_s_p6_0[] = {
  134343. 6,
  134344. 5,
  134345. 7,
  134346. 4,
  134347. 8,
  134348. 3,
  134349. 9,
  134350. 2,
  134351. 10,
  134352. 1,
  134353. 11,
  134354. 0,
  134355. 12,
  134356. };
  134357. static long _vq_lengthlist__44c9_s_p6_0[] = {
  134358. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  134359. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  134360. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  134361. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  134362. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  134363. 11, 8, 8, 9, 9,10,10,11,11,12,12, 0, 0, 0, 0, 0,
  134364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134368. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134369. };
  134370. static float _vq_quantthresh__44c9_s_p6_0[] = {
  134371. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134372. 12.5, 17.5, 22.5, 27.5,
  134373. };
  134374. static long _vq_quantmap__44c9_s_p6_0[] = {
  134375. 11, 9, 7, 5, 3, 1, 0, 2,
  134376. 4, 6, 8, 10, 12,
  134377. };
  134378. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  134379. _vq_quantthresh__44c9_s_p6_0,
  134380. _vq_quantmap__44c9_s_p6_0,
  134381. 13,
  134382. 13
  134383. };
  134384. static static_codebook _44c9_s_p6_0 = {
  134385. 2, 169,
  134386. _vq_lengthlist__44c9_s_p6_0,
  134387. 1, -526516224, 1616117760, 4, 0,
  134388. _vq_quantlist__44c9_s_p6_0,
  134389. NULL,
  134390. &_vq_auxt__44c9_s_p6_0,
  134391. NULL,
  134392. 0
  134393. };
  134394. static long _vq_quantlist__44c9_s_p6_1[] = {
  134395. 2,
  134396. 1,
  134397. 3,
  134398. 0,
  134399. 4,
  134400. };
  134401. static long _vq_lengthlist__44c9_s_p6_1[] = {
  134402. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  134403. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  134404. };
  134405. static float _vq_quantthresh__44c9_s_p6_1[] = {
  134406. -1.5, -0.5, 0.5, 1.5,
  134407. };
  134408. static long _vq_quantmap__44c9_s_p6_1[] = {
  134409. 3, 1, 0, 2, 4,
  134410. };
  134411. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  134412. _vq_quantthresh__44c9_s_p6_1,
  134413. _vq_quantmap__44c9_s_p6_1,
  134414. 5,
  134415. 5
  134416. };
  134417. static static_codebook _44c9_s_p6_1 = {
  134418. 2, 25,
  134419. _vq_lengthlist__44c9_s_p6_1,
  134420. 1, -533725184, 1611661312, 3, 0,
  134421. _vq_quantlist__44c9_s_p6_1,
  134422. NULL,
  134423. &_vq_auxt__44c9_s_p6_1,
  134424. NULL,
  134425. 0
  134426. };
  134427. static long _vq_quantlist__44c9_s_p7_0[] = {
  134428. 6,
  134429. 5,
  134430. 7,
  134431. 4,
  134432. 8,
  134433. 3,
  134434. 9,
  134435. 2,
  134436. 10,
  134437. 1,
  134438. 11,
  134439. 0,
  134440. 12,
  134441. };
  134442. static long _vq_lengthlist__44c9_s_p7_0[] = {
  134443. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  134444. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  134445. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  134446. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  134447. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  134448. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  134449. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  134450. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  134451. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  134452. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  134453. 19,12,12,12,12,13,13,14,14,
  134454. };
  134455. static float _vq_quantthresh__44c9_s_p7_0[] = {
  134456. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  134457. 27.5, 38.5, 49.5, 60.5,
  134458. };
  134459. static long _vq_quantmap__44c9_s_p7_0[] = {
  134460. 11, 9, 7, 5, 3, 1, 0, 2,
  134461. 4, 6, 8, 10, 12,
  134462. };
  134463. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  134464. _vq_quantthresh__44c9_s_p7_0,
  134465. _vq_quantmap__44c9_s_p7_0,
  134466. 13,
  134467. 13
  134468. };
  134469. static static_codebook _44c9_s_p7_0 = {
  134470. 2, 169,
  134471. _vq_lengthlist__44c9_s_p7_0,
  134472. 1, -523206656, 1618345984, 4, 0,
  134473. _vq_quantlist__44c9_s_p7_0,
  134474. NULL,
  134475. &_vq_auxt__44c9_s_p7_0,
  134476. NULL,
  134477. 0
  134478. };
  134479. static long _vq_quantlist__44c9_s_p7_1[] = {
  134480. 5,
  134481. 4,
  134482. 6,
  134483. 3,
  134484. 7,
  134485. 2,
  134486. 8,
  134487. 1,
  134488. 9,
  134489. 0,
  134490. 10,
  134491. };
  134492. static long _vq_lengthlist__44c9_s_p7_1[] = {
  134493. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  134494. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  134495. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  134496. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134497. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  134498. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  134499. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  134500. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134501. };
  134502. static float _vq_quantthresh__44c9_s_p7_1[] = {
  134503. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134504. 3.5, 4.5,
  134505. };
  134506. static long _vq_quantmap__44c9_s_p7_1[] = {
  134507. 9, 7, 5, 3, 1, 0, 2, 4,
  134508. 6, 8, 10,
  134509. };
  134510. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  134511. _vq_quantthresh__44c9_s_p7_1,
  134512. _vq_quantmap__44c9_s_p7_1,
  134513. 11,
  134514. 11
  134515. };
  134516. static static_codebook _44c9_s_p7_1 = {
  134517. 2, 121,
  134518. _vq_lengthlist__44c9_s_p7_1,
  134519. 1, -531365888, 1611661312, 4, 0,
  134520. _vq_quantlist__44c9_s_p7_1,
  134521. NULL,
  134522. &_vq_auxt__44c9_s_p7_1,
  134523. NULL,
  134524. 0
  134525. };
  134526. static long _vq_quantlist__44c9_s_p8_0[] = {
  134527. 7,
  134528. 6,
  134529. 8,
  134530. 5,
  134531. 9,
  134532. 4,
  134533. 10,
  134534. 3,
  134535. 11,
  134536. 2,
  134537. 12,
  134538. 1,
  134539. 13,
  134540. 0,
  134541. 14,
  134542. };
  134543. static long _vq_lengthlist__44c9_s_p8_0[] = {
  134544. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  134545. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  134546. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  134547. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  134548. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  134549. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  134550. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  134551. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  134552. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  134553. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  134554. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  134555. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  134556. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  134557. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  134558. 14,
  134559. };
  134560. static float _vq_quantthresh__44c9_s_p8_0[] = {
  134561. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  134562. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  134563. };
  134564. static long _vq_quantmap__44c9_s_p8_0[] = {
  134565. 13, 11, 9, 7, 5, 3, 1, 0,
  134566. 2, 4, 6, 8, 10, 12, 14,
  134567. };
  134568. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  134569. _vq_quantthresh__44c9_s_p8_0,
  134570. _vq_quantmap__44c9_s_p8_0,
  134571. 15,
  134572. 15
  134573. };
  134574. static static_codebook _44c9_s_p8_0 = {
  134575. 2, 225,
  134576. _vq_lengthlist__44c9_s_p8_0,
  134577. 1, -520986624, 1620377600, 4, 0,
  134578. _vq_quantlist__44c9_s_p8_0,
  134579. NULL,
  134580. &_vq_auxt__44c9_s_p8_0,
  134581. NULL,
  134582. 0
  134583. };
  134584. static long _vq_quantlist__44c9_s_p8_1[] = {
  134585. 10,
  134586. 9,
  134587. 11,
  134588. 8,
  134589. 12,
  134590. 7,
  134591. 13,
  134592. 6,
  134593. 14,
  134594. 5,
  134595. 15,
  134596. 4,
  134597. 16,
  134598. 3,
  134599. 17,
  134600. 2,
  134601. 18,
  134602. 1,
  134603. 19,
  134604. 0,
  134605. 20,
  134606. };
  134607. static long _vq_lengthlist__44c9_s_p8_1[] = {
  134608. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  134609. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  134610. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  134611. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  134612. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134613. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  134614. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  134615. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  134616. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134617. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134618. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  134619. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  134620. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134621. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134622. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  134623. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  134624. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  134625. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  134626. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  134627. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  134628. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  134629. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  134630. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  134631. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  134632. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  134633. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  134634. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  134635. 9, 9, 9,10, 9, 9, 9, 9, 9,
  134636. };
  134637. static float _vq_quantthresh__44c9_s_p8_1[] = {
  134638. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  134639. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  134640. 6.5, 7.5, 8.5, 9.5,
  134641. };
  134642. static long _vq_quantmap__44c9_s_p8_1[] = {
  134643. 19, 17, 15, 13, 11, 9, 7, 5,
  134644. 3, 1, 0, 2, 4, 6, 8, 10,
  134645. 12, 14, 16, 18, 20,
  134646. };
  134647. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  134648. _vq_quantthresh__44c9_s_p8_1,
  134649. _vq_quantmap__44c9_s_p8_1,
  134650. 21,
  134651. 21
  134652. };
  134653. static static_codebook _44c9_s_p8_1 = {
  134654. 2, 441,
  134655. _vq_lengthlist__44c9_s_p8_1,
  134656. 1, -529268736, 1611661312, 5, 0,
  134657. _vq_quantlist__44c9_s_p8_1,
  134658. NULL,
  134659. &_vq_auxt__44c9_s_p8_1,
  134660. NULL,
  134661. 0
  134662. };
  134663. static long _vq_quantlist__44c9_s_p9_0[] = {
  134664. 9,
  134665. 8,
  134666. 10,
  134667. 7,
  134668. 11,
  134669. 6,
  134670. 12,
  134671. 5,
  134672. 13,
  134673. 4,
  134674. 14,
  134675. 3,
  134676. 15,
  134677. 2,
  134678. 16,
  134679. 1,
  134680. 17,
  134681. 0,
  134682. 18,
  134683. };
  134684. static long _vq_lengthlist__44c9_s_p9_0[] = {
  134685. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134686. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  134687. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  134688. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  134689. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134690. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134691. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134692. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134693. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134694. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134695. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134696. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134697. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134698. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134699. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134700. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134701. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  134702. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134703. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134704. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134705. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134706. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134707. 11,11,11,11,11,11,11,11,11,
  134708. };
  134709. static float _vq_quantthresh__44c9_s_p9_0[] = {
  134710. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  134711. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  134712. 6982.5, 7913.5,
  134713. };
  134714. static long _vq_quantmap__44c9_s_p9_0[] = {
  134715. 17, 15, 13, 11, 9, 7, 5, 3,
  134716. 1, 0, 2, 4, 6, 8, 10, 12,
  134717. 14, 16, 18,
  134718. };
  134719. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  134720. _vq_quantthresh__44c9_s_p9_0,
  134721. _vq_quantmap__44c9_s_p9_0,
  134722. 19,
  134723. 19
  134724. };
  134725. static static_codebook _44c9_s_p9_0 = {
  134726. 2, 361,
  134727. _vq_lengthlist__44c9_s_p9_0,
  134728. 1, -508535424, 1631393792, 5, 0,
  134729. _vq_quantlist__44c9_s_p9_0,
  134730. NULL,
  134731. &_vq_auxt__44c9_s_p9_0,
  134732. NULL,
  134733. 0
  134734. };
  134735. static long _vq_quantlist__44c9_s_p9_1[] = {
  134736. 9,
  134737. 8,
  134738. 10,
  134739. 7,
  134740. 11,
  134741. 6,
  134742. 12,
  134743. 5,
  134744. 13,
  134745. 4,
  134746. 14,
  134747. 3,
  134748. 15,
  134749. 2,
  134750. 16,
  134751. 1,
  134752. 17,
  134753. 0,
  134754. 18,
  134755. };
  134756. static long _vq_lengthlist__44c9_s_p9_1[] = {
  134757. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  134758. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  134759. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  134760. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  134761. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  134762. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  134763. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  134764. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  134765. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  134766. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  134767. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  134768. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  134769. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  134770. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  134771. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  134772. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  134773. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  134774. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  134775. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  134776. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  134777. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  134778. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  134779. 13,13,13,14,13,14,15,15,15,
  134780. };
  134781. static float _vq_quantthresh__44c9_s_p9_1[] = {
  134782. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  134783. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  134784. 367.5, 416.5,
  134785. };
  134786. static long _vq_quantmap__44c9_s_p9_1[] = {
  134787. 17, 15, 13, 11, 9, 7, 5, 3,
  134788. 1, 0, 2, 4, 6, 8, 10, 12,
  134789. 14, 16, 18,
  134790. };
  134791. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  134792. _vq_quantthresh__44c9_s_p9_1,
  134793. _vq_quantmap__44c9_s_p9_1,
  134794. 19,
  134795. 19
  134796. };
  134797. static static_codebook _44c9_s_p9_1 = {
  134798. 2, 361,
  134799. _vq_lengthlist__44c9_s_p9_1,
  134800. 1, -518287360, 1622704128, 5, 0,
  134801. _vq_quantlist__44c9_s_p9_1,
  134802. NULL,
  134803. &_vq_auxt__44c9_s_p9_1,
  134804. NULL,
  134805. 0
  134806. };
  134807. static long _vq_quantlist__44c9_s_p9_2[] = {
  134808. 24,
  134809. 23,
  134810. 25,
  134811. 22,
  134812. 26,
  134813. 21,
  134814. 27,
  134815. 20,
  134816. 28,
  134817. 19,
  134818. 29,
  134819. 18,
  134820. 30,
  134821. 17,
  134822. 31,
  134823. 16,
  134824. 32,
  134825. 15,
  134826. 33,
  134827. 14,
  134828. 34,
  134829. 13,
  134830. 35,
  134831. 12,
  134832. 36,
  134833. 11,
  134834. 37,
  134835. 10,
  134836. 38,
  134837. 9,
  134838. 39,
  134839. 8,
  134840. 40,
  134841. 7,
  134842. 41,
  134843. 6,
  134844. 42,
  134845. 5,
  134846. 43,
  134847. 4,
  134848. 44,
  134849. 3,
  134850. 45,
  134851. 2,
  134852. 46,
  134853. 1,
  134854. 47,
  134855. 0,
  134856. 48,
  134857. };
  134858. static long _vq_lengthlist__44c9_s_p9_2[] = {
  134859. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  134860. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  134861. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134862. 7,
  134863. };
  134864. static float _vq_quantthresh__44c9_s_p9_2[] = {
  134865. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  134866. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  134867. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134868. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134869. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  134870. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  134871. };
  134872. static long _vq_quantmap__44c9_s_p9_2[] = {
  134873. 47, 45, 43, 41, 39, 37, 35, 33,
  134874. 31, 29, 27, 25, 23, 21, 19, 17,
  134875. 15, 13, 11, 9, 7, 5, 3, 1,
  134876. 0, 2, 4, 6, 8, 10, 12, 14,
  134877. 16, 18, 20, 22, 24, 26, 28, 30,
  134878. 32, 34, 36, 38, 40, 42, 44, 46,
  134879. 48,
  134880. };
  134881. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  134882. _vq_quantthresh__44c9_s_p9_2,
  134883. _vq_quantmap__44c9_s_p9_2,
  134884. 49,
  134885. 49
  134886. };
  134887. static static_codebook _44c9_s_p9_2 = {
  134888. 1, 49,
  134889. _vq_lengthlist__44c9_s_p9_2,
  134890. 1, -526909440, 1611661312, 6, 0,
  134891. _vq_quantlist__44c9_s_p9_2,
  134892. NULL,
  134893. &_vq_auxt__44c9_s_p9_2,
  134894. NULL,
  134895. 0
  134896. };
  134897. static long _huff_lengthlist__44c9_s_short[] = {
  134898. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  134899. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  134900. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  134901. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  134902. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  134903. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  134904. 9, 8,10,13,
  134905. };
  134906. static static_codebook _huff_book__44c9_s_short = {
  134907. 2, 100,
  134908. _huff_lengthlist__44c9_s_short,
  134909. 0, 0, 0, 0, 0,
  134910. NULL,
  134911. NULL,
  134912. NULL,
  134913. NULL,
  134914. 0
  134915. };
  134916. static long _huff_lengthlist__44c0_s_long[] = {
  134917. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  134918. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  134919. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  134920. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  134921. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  134922. 12,
  134923. };
  134924. static static_codebook _huff_book__44c0_s_long = {
  134925. 2, 81,
  134926. _huff_lengthlist__44c0_s_long,
  134927. 0, 0, 0, 0, 0,
  134928. NULL,
  134929. NULL,
  134930. NULL,
  134931. NULL,
  134932. 0
  134933. };
  134934. static long _vq_quantlist__44c0_s_p1_0[] = {
  134935. 1,
  134936. 0,
  134937. 2,
  134938. };
  134939. static long _vq_lengthlist__44c0_s_p1_0[] = {
  134940. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  134941. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134945. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  134946. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134950. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  134951. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  134986. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  134987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  134991. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  134992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  134996. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  134997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135031. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135032. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135036. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  135037. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  135038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135041. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  135042. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  135043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135350. 0,
  135351. };
  135352. static float _vq_quantthresh__44c0_s_p1_0[] = {
  135353. -0.5, 0.5,
  135354. };
  135355. static long _vq_quantmap__44c0_s_p1_0[] = {
  135356. 1, 0, 2,
  135357. };
  135358. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  135359. _vq_quantthresh__44c0_s_p1_0,
  135360. _vq_quantmap__44c0_s_p1_0,
  135361. 3,
  135362. 3
  135363. };
  135364. static static_codebook _44c0_s_p1_0 = {
  135365. 8, 6561,
  135366. _vq_lengthlist__44c0_s_p1_0,
  135367. 1, -535822336, 1611661312, 2, 0,
  135368. _vq_quantlist__44c0_s_p1_0,
  135369. NULL,
  135370. &_vq_auxt__44c0_s_p1_0,
  135371. NULL,
  135372. 0
  135373. };
  135374. static long _vq_quantlist__44c0_s_p2_0[] = {
  135375. 2,
  135376. 1,
  135377. 3,
  135378. 0,
  135379. 4,
  135380. };
  135381. static long _vq_lengthlist__44c0_s_p2_0[] = {
  135382. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  135384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135385. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  135387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135388. 0, 0, 0, 0, 6, 7, 7, 9, 9, 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,
  135422. };
  135423. static float _vq_quantthresh__44c0_s_p2_0[] = {
  135424. -1.5, -0.5, 0.5, 1.5,
  135425. };
  135426. static long _vq_quantmap__44c0_s_p2_0[] = {
  135427. 3, 1, 0, 2, 4,
  135428. };
  135429. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  135430. _vq_quantthresh__44c0_s_p2_0,
  135431. _vq_quantmap__44c0_s_p2_0,
  135432. 5,
  135433. 5
  135434. };
  135435. static static_codebook _44c0_s_p2_0 = {
  135436. 4, 625,
  135437. _vq_lengthlist__44c0_s_p2_0,
  135438. 1, -533725184, 1611661312, 3, 0,
  135439. _vq_quantlist__44c0_s_p2_0,
  135440. NULL,
  135441. &_vq_auxt__44c0_s_p2_0,
  135442. NULL,
  135443. 0
  135444. };
  135445. static long _vq_quantlist__44c0_s_p3_0[] = {
  135446. 4,
  135447. 3,
  135448. 5,
  135449. 2,
  135450. 6,
  135451. 1,
  135452. 7,
  135453. 0,
  135454. 8,
  135455. };
  135456. static long _vq_lengthlist__44c0_s_p3_0[] = {
  135457. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  135458. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  135459. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  135460. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  135461. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135462. 0,
  135463. };
  135464. static float _vq_quantthresh__44c0_s_p3_0[] = {
  135465. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135466. };
  135467. static long _vq_quantmap__44c0_s_p3_0[] = {
  135468. 7, 5, 3, 1, 0, 2, 4, 6,
  135469. 8,
  135470. };
  135471. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  135472. _vq_quantthresh__44c0_s_p3_0,
  135473. _vq_quantmap__44c0_s_p3_0,
  135474. 9,
  135475. 9
  135476. };
  135477. static static_codebook _44c0_s_p3_0 = {
  135478. 2, 81,
  135479. _vq_lengthlist__44c0_s_p3_0,
  135480. 1, -531628032, 1611661312, 4, 0,
  135481. _vq_quantlist__44c0_s_p3_0,
  135482. NULL,
  135483. &_vq_auxt__44c0_s_p3_0,
  135484. NULL,
  135485. 0
  135486. };
  135487. static long _vq_quantlist__44c0_s_p4_0[] = {
  135488. 4,
  135489. 3,
  135490. 5,
  135491. 2,
  135492. 6,
  135493. 1,
  135494. 7,
  135495. 0,
  135496. 8,
  135497. };
  135498. static long _vq_lengthlist__44c0_s_p4_0[] = {
  135499. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  135500. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  135501. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  135502. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  135503. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  135504. 10,
  135505. };
  135506. static float _vq_quantthresh__44c0_s_p4_0[] = {
  135507. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135508. };
  135509. static long _vq_quantmap__44c0_s_p4_0[] = {
  135510. 7, 5, 3, 1, 0, 2, 4, 6,
  135511. 8,
  135512. };
  135513. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  135514. _vq_quantthresh__44c0_s_p4_0,
  135515. _vq_quantmap__44c0_s_p4_0,
  135516. 9,
  135517. 9
  135518. };
  135519. static static_codebook _44c0_s_p4_0 = {
  135520. 2, 81,
  135521. _vq_lengthlist__44c0_s_p4_0,
  135522. 1, -531628032, 1611661312, 4, 0,
  135523. _vq_quantlist__44c0_s_p4_0,
  135524. NULL,
  135525. &_vq_auxt__44c0_s_p4_0,
  135526. NULL,
  135527. 0
  135528. };
  135529. static long _vq_quantlist__44c0_s_p5_0[] = {
  135530. 8,
  135531. 7,
  135532. 9,
  135533. 6,
  135534. 10,
  135535. 5,
  135536. 11,
  135537. 4,
  135538. 12,
  135539. 3,
  135540. 13,
  135541. 2,
  135542. 14,
  135543. 1,
  135544. 15,
  135545. 0,
  135546. 16,
  135547. };
  135548. static long _vq_lengthlist__44c0_s_p5_0[] = {
  135549. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  135550. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  135551. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  135552. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  135553. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  135554. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  135555. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  135556. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  135557. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  135558. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  135559. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  135560. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  135561. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  135562. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  135563. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  135564. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  135565. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  135566. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  135567. 14,
  135568. };
  135569. static float _vq_quantthresh__44c0_s_p5_0[] = {
  135570. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135571. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135572. };
  135573. static long _vq_quantmap__44c0_s_p5_0[] = {
  135574. 15, 13, 11, 9, 7, 5, 3, 1,
  135575. 0, 2, 4, 6, 8, 10, 12, 14,
  135576. 16,
  135577. };
  135578. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  135579. _vq_quantthresh__44c0_s_p5_0,
  135580. _vq_quantmap__44c0_s_p5_0,
  135581. 17,
  135582. 17
  135583. };
  135584. static static_codebook _44c0_s_p5_0 = {
  135585. 2, 289,
  135586. _vq_lengthlist__44c0_s_p5_0,
  135587. 1, -529530880, 1611661312, 5, 0,
  135588. _vq_quantlist__44c0_s_p5_0,
  135589. NULL,
  135590. &_vq_auxt__44c0_s_p5_0,
  135591. NULL,
  135592. 0
  135593. };
  135594. static long _vq_quantlist__44c0_s_p6_0[] = {
  135595. 1,
  135596. 0,
  135597. 2,
  135598. };
  135599. static long _vq_lengthlist__44c0_s_p6_0[] = {
  135600. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  135601. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  135602. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  135603. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  135604. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  135605. 10,
  135606. };
  135607. static float _vq_quantthresh__44c0_s_p6_0[] = {
  135608. -5.5, 5.5,
  135609. };
  135610. static long _vq_quantmap__44c0_s_p6_0[] = {
  135611. 1, 0, 2,
  135612. };
  135613. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  135614. _vq_quantthresh__44c0_s_p6_0,
  135615. _vq_quantmap__44c0_s_p6_0,
  135616. 3,
  135617. 3
  135618. };
  135619. static static_codebook _44c0_s_p6_0 = {
  135620. 4, 81,
  135621. _vq_lengthlist__44c0_s_p6_0,
  135622. 1, -529137664, 1618345984, 2, 0,
  135623. _vq_quantlist__44c0_s_p6_0,
  135624. NULL,
  135625. &_vq_auxt__44c0_s_p6_0,
  135626. NULL,
  135627. 0
  135628. };
  135629. static long _vq_quantlist__44c0_s_p6_1[] = {
  135630. 5,
  135631. 4,
  135632. 6,
  135633. 3,
  135634. 7,
  135635. 2,
  135636. 8,
  135637. 1,
  135638. 9,
  135639. 0,
  135640. 10,
  135641. };
  135642. static long _vq_lengthlist__44c0_s_p6_1[] = {
  135643. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  135644. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  135645. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  135646. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  135647. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  135648. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  135649. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  135650. 10,10,10, 8, 8, 8, 8, 8, 8,
  135651. };
  135652. static float _vq_quantthresh__44c0_s_p6_1[] = {
  135653. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135654. 3.5, 4.5,
  135655. };
  135656. static long _vq_quantmap__44c0_s_p6_1[] = {
  135657. 9, 7, 5, 3, 1, 0, 2, 4,
  135658. 6, 8, 10,
  135659. };
  135660. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  135661. _vq_quantthresh__44c0_s_p6_1,
  135662. _vq_quantmap__44c0_s_p6_1,
  135663. 11,
  135664. 11
  135665. };
  135666. static static_codebook _44c0_s_p6_1 = {
  135667. 2, 121,
  135668. _vq_lengthlist__44c0_s_p6_1,
  135669. 1, -531365888, 1611661312, 4, 0,
  135670. _vq_quantlist__44c0_s_p6_1,
  135671. NULL,
  135672. &_vq_auxt__44c0_s_p6_1,
  135673. NULL,
  135674. 0
  135675. };
  135676. static long _vq_quantlist__44c0_s_p7_0[] = {
  135677. 6,
  135678. 5,
  135679. 7,
  135680. 4,
  135681. 8,
  135682. 3,
  135683. 9,
  135684. 2,
  135685. 10,
  135686. 1,
  135687. 11,
  135688. 0,
  135689. 12,
  135690. };
  135691. static long _vq_lengthlist__44c0_s_p7_0[] = {
  135692. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  135693. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  135694. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  135695. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  135696. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  135697. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  135698. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  135699. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  135700. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  135701. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  135702. 0,12,12,11,11,12,12,13,13,
  135703. };
  135704. static float _vq_quantthresh__44c0_s_p7_0[] = {
  135705. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  135706. 12.5, 17.5, 22.5, 27.5,
  135707. };
  135708. static long _vq_quantmap__44c0_s_p7_0[] = {
  135709. 11, 9, 7, 5, 3, 1, 0, 2,
  135710. 4, 6, 8, 10, 12,
  135711. };
  135712. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  135713. _vq_quantthresh__44c0_s_p7_0,
  135714. _vq_quantmap__44c0_s_p7_0,
  135715. 13,
  135716. 13
  135717. };
  135718. static static_codebook _44c0_s_p7_0 = {
  135719. 2, 169,
  135720. _vq_lengthlist__44c0_s_p7_0,
  135721. 1, -526516224, 1616117760, 4, 0,
  135722. _vq_quantlist__44c0_s_p7_0,
  135723. NULL,
  135724. &_vq_auxt__44c0_s_p7_0,
  135725. NULL,
  135726. 0
  135727. };
  135728. static long _vq_quantlist__44c0_s_p7_1[] = {
  135729. 2,
  135730. 1,
  135731. 3,
  135732. 0,
  135733. 4,
  135734. };
  135735. static long _vq_lengthlist__44c0_s_p7_1[] = {
  135736. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  135737. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  135738. };
  135739. static float _vq_quantthresh__44c0_s_p7_1[] = {
  135740. -1.5, -0.5, 0.5, 1.5,
  135741. };
  135742. static long _vq_quantmap__44c0_s_p7_1[] = {
  135743. 3, 1, 0, 2, 4,
  135744. };
  135745. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  135746. _vq_quantthresh__44c0_s_p7_1,
  135747. _vq_quantmap__44c0_s_p7_1,
  135748. 5,
  135749. 5
  135750. };
  135751. static static_codebook _44c0_s_p7_1 = {
  135752. 2, 25,
  135753. _vq_lengthlist__44c0_s_p7_1,
  135754. 1, -533725184, 1611661312, 3, 0,
  135755. _vq_quantlist__44c0_s_p7_1,
  135756. NULL,
  135757. &_vq_auxt__44c0_s_p7_1,
  135758. NULL,
  135759. 0
  135760. };
  135761. static long _vq_quantlist__44c0_s_p8_0[] = {
  135762. 2,
  135763. 1,
  135764. 3,
  135765. 0,
  135766. 4,
  135767. };
  135768. static long _vq_lengthlist__44c0_s_p8_0[] = {
  135769. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  135770. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135771. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135772. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135773. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135774. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135775. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135776. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  135777. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135778. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135779. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135780. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135781. 10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,
  135782. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135783. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135784. 11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,
  135785. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135786. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135787. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135788. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135789. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135790. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135791. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135792. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135793. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135794. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135795. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135796. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135797. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135798. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135799. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135800. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135801. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135802. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135803. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135804. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135805. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135806. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135807. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135808. 11,
  135809. };
  135810. static float _vq_quantthresh__44c0_s_p8_0[] = {
  135811. -331.5, -110.5, 110.5, 331.5,
  135812. };
  135813. static long _vq_quantmap__44c0_s_p8_0[] = {
  135814. 3, 1, 0, 2, 4,
  135815. };
  135816. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  135817. _vq_quantthresh__44c0_s_p8_0,
  135818. _vq_quantmap__44c0_s_p8_0,
  135819. 5,
  135820. 5
  135821. };
  135822. static static_codebook _44c0_s_p8_0 = {
  135823. 4, 625,
  135824. _vq_lengthlist__44c0_s_p8_0,
  135825. 1, -518283264, 1627103232, 3, 0,
  135826. _vq_quantlist__44c0_s_p8_0,
  135827. NULL,
  135828. &_vq_auxt__44c0_s_p8_0,
  135829. NULL,
  135830. 0
  135831. };
  135832. static long _vq_quantlist__44c0_s_p8_1[] = {
  135833. 6,
  135834. 5,
  135835. 7,
  135836. 4,
  135837. 8,
  135838. 3,
  135839. 9,
  135840. 2,
  135841. 10,
  135842. 1,
  135843. 11,
  135844. 0,
  135845. 12,
  135846. };
  135847. static long _vq_lengthlist__44c0_s_p8_1[] = {
  135848. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  135849. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  135850. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  135851. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  135852. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  135853. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  135854. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  135855. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  135856. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  135857. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  135858. 16,13,13,12,12,14,14,15,13,
  135859. };
  135860. static float _vq_quantthresh__44c0_s_p8_1[] = {
  135861. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  135862. 42.5, 59.5, 76.5, 93.5,
  135863. };
  135864. static long _vq_quantmap__44c0_s_p8_1[] = {
  135865. 11, 9, 7, 5, 3, 1, 0, 2,
  135866. 4, 6, 8, 10, 12,
  135867. };
  135868. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  135869. _vq_quantthresh__44c0_s_p8_1,
  135870. _vq_quantmap__44c0_s_p8_1,
  135871. 13,
  135872. 13
  135873. };
  135874. static static_codebook _44c0_s_p8_1 = {
  135875. 2, 169,
  135876. _vq_lengthlist__44c0_s_p8_1,
  135877. 1, -522616832, 1620115456, 4, 0,
  135878. _vq_quantlist__44c0_s_p8_1,
  135879. NULL,
  135880. &_vq_auxt__44c0_s_p8_1,
  135881. NULL,
  135882. 0
  135883. };
  135884. static long _vq_quantlist__44c0_s_p8_2[] = {
  135885. 8,
  135886. 7,
  135887. 9,
  135888. 6,
  135889. 10,
  135890. 5,
  135891. 11,
  135892. 4,
  135893. 12,
  135894. 3,
  135895. 13,
  135896. 2,
  135897. 14,
  135898. 1,
  135899. 15,
  135900. 0,
  135901. 16,
  135902. };
  135903. static long _vq_lengthlist__44c0_s_p8_2[] = {
  135904. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  135905. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  135906. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  135907. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  135908. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  135909. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  135910. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  135911. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  135912. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  135913. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  135914. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  135915. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  135916. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  135917. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  135918. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  135919. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  135920. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  135921. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  135922. 10,
  135923. };
  135924. static float _vq_quantthresh__44c0_s_p8_2[] = {
  135925. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135926. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135927. };
  135928. static long _vq_quantmap__44c0_s_p8_2[] = {
  135929. 15, 13, 11, 9, 7, 5, 3, 1,
  135930. 0, 2, 4, 6, 8, 10, 12, 14,
  135931. 16,
  135932. };
  135933. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  135934. _vq_quantthresh__44c0_s_p8_2,
  135935. _vq_quantmap__44c0_s_p8_2,
  135936. 17,
  135937. 17
  135938. };
  135939. static static_codebook _44c0_s_p8_2 = {
  135940. 2, 289,
  135941. _vq_lengthlist__44c0_s_p8_2,
  135942. 1, -529530880, 1611661312, 5, 0,
  135943. _vq_quantlist__44c0_s_p8_2,
  135944. NULL,
  135945. &_vq_auxt__44c0_s_p8_2,
  135946. NULL,
  135947. 0
  135948. };
  135949. static long _huff_lengthlist__44c0_s_short[] = {
  135950. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  135951. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  135952. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  135953. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  135954. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  135955. 12,
  135956. };
  135957. static static_codebook _huff_book__44c0_s_short = {
  135958. 2, 81,
  135959. _huff_lengthlist__44c0_s_short,
  135960. 0, 0, 0, 0, 0,
  135961. NULL,
  135962. NULL,
  135963. NULL,
  135964. NULL,
  135965. 0
  135966. };
  135967. static long _huff_lengthlist__44c0_sm_long[] = {
  135968. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  135969. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  135970. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  135971. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  135972. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  135973. 13,
  135974. };
  135975. static static_codebook _huff_book__44c0_sm_long = {
  135976. 2, 81,
  135977. _huff_lengthlist__44c0_sm_long,
  135978. 0, 0, 0, 0, 0,
  135979. NULL,
  135980. NULL,
  135981. NULL,
  135982. NULL,
  135983. 0
  135984. };
  135985. static long _vq_quantlist__44c0_sm_p1_0[] = {
  135986. 1,
  135987. 0,
  135988. 2,
  135989. };
  135990. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  135991. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135992. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135996. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  135997. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136001. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  136002. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  136037. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  136038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136042. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  136043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136047. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  136048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136082. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136083. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136087. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  136088. 0, 0, 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  136089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136092. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  136093. 0, 0, 0, 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 0,
  136094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136315. 0, 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, 0, 0, 0, 0, 0, 0, 0,
  136345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  136350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  136355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136386. 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136391. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136396. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136401. 0,
  136402. };
  136403. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  136404. -0.5, 0.5,
  136405. };
  136406. static long _vq_quantmap__44c0_sm_p1_0[] = {
  136407. 1, 0, 2,
  136408. };
  136409. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  136410. _vq_quantthresh__44c0_sm_p1_0,
  136411. _vq_quantmap__44c0_sm_p1_0,
  136412. 3,
  136413. 3
  136414. };
  136415. static static_codebook _44c0_sm_p1_0 = {
  136416. 8, 6561,
  136417. _vq_lengthlist__44c0_sm_p1_0,
  136418. 1, -535822336, 1611661312, 2, 0,
  136419. _vq_quantlist__44c0_sm_p1_0,
  136420. NULL,
  136421. &_vq_auxt__44c0_sm_p1_0,
  136422. NULL,
  136423. 0
  136424. };
  136425. static long _vq_quantlist__44c0_sm_p2_0[] = {
  136426. 2,
  136427. 1,
  136428. 3,
  136429. 0,
  136430. 4,
  136431. };
  136432. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  136433. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  136435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136436. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  136438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136439. 0, 0, 0, 0, 7, 7, 7, 9, 9, 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,
  136473. };
  136474. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  136475. -1.5, -0.5, 0.5, 1.5,
  136476. };
  136477. static long _vq_quantmap__44c0_sm_p2_0[] = {
  136478. 3, 1, 0, 2, 4,
  136479. };
  136480. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  136481. _vq_quantthresh__44c0_sm_p2_0,
  136482. _vq_quantmap__44c0_sm_p2_0,
  136483. 5,
  136484. 5
  136485. };
  136486. static static_codebook _44c0_sm_p2_0 = {
  136487. 4, 625,
  136488. _vq_lengthlist__44c0_sm_p2_0,
  136489. 1, -533725184, 1611661312, 3, 0,
  136490. _vq_quantlist__44c0_sm_p2_0,
  136491. NULL,
  136492. &_vq_auxt__44c0_sm_p2_0,
  136493. NULL,
  136494. 0
  136495. };
  136496. static long _vq_quantlist__44c0_sm_p3_0[] = {
  136497. 4,
  136498. 3,
  136499. 5,
  136500. 2,
  136501. 6,
  136502. 1,
  136503. 7,
  136504. 0,
  136505. 8,
  136506. };
  136507. static long _vq_lengthlist__44c0_sm_p3_0[] = {
  136508. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  136509. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  136510. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  136511. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  136512. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136513. 0,
  136514. };
  136515. static float _vq_quantthresh__44c0_sm_p3_0[] = {
  136516. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136517. };
  136518. static long _vq_quantmap__44c0_sm_p3_0[] = {
  136519. 7, 5, 3, 1, 0, 2, 4, 6,
  136520. 8,
  136521. };
  136522. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  136523. _vq_quantthresh__44c0_sm_p3_0,
  136524. _vq_quantmap__44c0_sm_p3_0,
  136525. 9,
  136526. 9
  136527. };
  136528. static static_codebook _44c0_sm_p3_0 = {
  136529. 2, 81,
  136530. _vq_lengthlist__44c0_sm_p3_0,
  136531. 1, -531628032, 1611661312, 4, 0,
  136532. _vq_quantlist__44c0_sm_p3_0,
  136533. NULL,
  136534. &_vq_auxt__44c0_sm_p3_0,
  136535. NULL,
  136536. 0
  136537. };
  136538. static long _vq_quantlist__44c0_sm_p4_0[] = {
  136539. 4,
  136540. 3,
  136541. 5,
  136542. 2,
  136543. 6,
  136544. 1,
  136545. 7,
  136546. 0,
  136547. 8,
  136548. };
  136549. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  136550. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  136551. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  136552. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  136553. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  136554. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  136555. 11,
  136556. };
  136557. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  136558. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136559. };
  136560. static long _vq_quantmap__44c0_sm_p4_0[] = {
  136561. 7, 5, 3, 1, 0, 2, 4, 6,
  136562. 8,
  136563. };
  136564. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  136565. _vq_quantthresh__44c0_sm_p4_0,
  136566. _vq_quantmap__44c0_sm_p4_0,
  136567. 9,
  136568. 9
  136569. };
  136570. static static_codebook _44c0_sm_p4_0 = {
  136571. 2, 81,
  136572. _vq_lengthlist__44c0_sm_p4_0,
  136573. 1, -531628032, 1611661312, 4, 0,
  136574. _vq_quantlist__44c0_sm_p4_0,
  136575. NULL,
  136576. &_vq_auxt__44c0_sm_p4_0,
  136577. NULL,
  136578. 0
  136579. };
  136580. static long _vq_quantlist__44c0_sm_p5_0[] = {
  136581. 8,
  136582. 7,
  136583. 9,
  136584. 6,
  136585. 10,
  136586. 5,
  136587. 11,
  136588. 4,
  136589. 12,
  136590. 3,
  136591. 13,
  136592. 2,
  136593. 14,
  136594. 1,
  136595. 15,
  136596. 0,
  136597. 16,
  136598. };
  136599. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  136600. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  136601. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  136602. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  136603. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  136604. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  136605. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  136606. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  136607. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  136608. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  136609. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  136610. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  136611. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  136612. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  136613. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  136614. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  136615. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  136616. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  136617. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  136618. 14,
  136619. };
  136620. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  136621. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136622. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136623. };
  136624. static long _vq_quantmap__44c0_sm_p5_0[] = {
  136625. 15, 13, 11, 9, 7, 5, 3, 1,
  136626. 0, 2, 4, 6, 8, 10, 12, 14,
  136627. 16,
  136628. };
  136629. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  136630. _vq_quantthresh__44c0_sm_p5_0,
  136631. _vq_quantmap__44c0_sm_p5_0,
  136632. 17,
  136633. 17
  136634. };
  136635. static static_codebook _44c0_sm_p5_0 = {
  136636. 2, 289,
  136637. _vq_lengthlist__44c0_sm_p5_0,
  136638. 1, -529530880, 1611661312, 5, 0,
  136639. _vq_quantlist__44c0_sm_p5_0,
  136640. NULL,
  136641. &_vq_auxt__44c0_sm_p5_0,
  136642. NULL,
  136643. 0
  136644. };
  136645. static long _vq_quantlist__44c0_sm_p6_0[] = {
  136646. 1,
  136647. 0,
  136648. 2,
  136649. };
  136650. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  136651. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  136652. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  136653. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  136654. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  136655. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  136656. 11,
  136657. };
  136658. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  136659. -5.5, 5.5,
  136660. };
  136661. static long _vq_quantmap__44c0_sm_p6_0[] = {
  136662. 1, 0, 2,
  136663. };
  136664. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  136665. _vq_quantthresh__44c0_sm_p6_0,
  136666. _vq_quantmap__44c0_sm_p6_0,
  136667. 3,
  136668. 3
  136669. };
  136670. static static_codebook _44c0_sm_p6_0 = {
  136671. 4, 81,
  136672. _vq_lengthlist__44c0_sm_p6_0,
  136673. 1, -529137664, 1618345984, 2, 0,
  136674. _vq_quantlist__44c0_sm_p6_0,
  136675. NULL,
  136676. &_vq_auxt__44c0_sm_p6_0,
  136677. NULL,
  136678. 0
  136679. };
  136680. static long _vq_quantlist__44c0_sm_p6_1[] = {
  136681. 5,
  136682. 4,
  136683. 6,
  136684. 3,
  136685. 7,
  136686. 2,
  136687. 8,
  136688. 1,
  136689. 9,
  136690. 0,
  136691. 10,
  136692. };
  136693. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  136694. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  136695. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  136696. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  136697. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  136698. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  136699. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  136700. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  136701. 10,10,10, 8, 8, 8, 8, 8, 8,
  136702. };
  136703. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  136704. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  136705. 3.5, 4.5,
  136706. };
  136707. static long _vq_quantmap__44c0_sm_p6_1[] = {
  136708. 9, 7, 5, 3, 1, 0, 2, 4,
  136709. 6, 8, 10,
  136710. };
  136711. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  136712. _vq_quantthresh__44c0_sm_p6_1,
  136713. _vq_quantmap__44c0_sm_p6_1,
  136714. 11,
  136715. 11
  136716. };
  136717. static static_codebook _44c0_sm_p6_1 = {
  136718. 2, 121,
  136719. _vq_lengthlist__44c0_sm_p6_1,
  136720. 1, -531365888, 1611661312, 4, 0,
  136721. _vq_quantlist__44c0_sm_p6_1,
  136722. NULL,
  136723. &_vq_auxt__44c0_sm_p6_1,
  136724. NULL,
  136725. 0
  136726. };
  136727. static long _vq_quantlist__44c0_sm_p7_0[] = {
  136728. 6,
  136729. 5,
  136730. 7,
  136731. 4,
  136732. 8,
  136733. 3,
  136734. 9,
  136735. 2,
  136736. 10,
  136737. 1,
  136738. 11,
  136739. 0,
  136740. 12,
  136741. };
  136742. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  136743. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  136744. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  136745. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  136746. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  136747. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  136748. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  136749. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  136750. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  136751. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  136752. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  136753. 0,12,12,11,11,13,12,14,14,
  136754. };
  136755. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  136756. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  136757. 12.5, 17.5, 22.5, 27.5,
  136758. };
  136759. static long _vq_quantmap__44c0_sm_p7_0[] = {
  136760. 11, 9, 7, 5, 3, 1, 0, 2,
  136761. 4, 6, 8, 10, 12,
  136762. };
  136763. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  136764. _vq_quantthresh__44c0_sm_p7_0,
  136765. _vq_quantmap__44c0_sm_p7_0,
  136766. 13,
  136767. 13
  136768. };
  136769. static static_codebook _44c0_sm_p7_0 = {
  136770. 2, 169,
  136771. _vq_lengthlist__44c0_sm_p7_0,
  136772. 1, -526516224, 1616117760, 4, 0,
  136773. _vq_quantlist__44c0_sm_p7_0,
  136774. NULL,
  136775. &_vq_auxt__44c0_sm_p7_0,
  136776. NULL,
  136777. 0
  136778. };
  136779. static long _vq_quantlist__44c0_sm_p7_1[] = {
  136780. 2,
  136781. 1,
  136782. 3,
  136783. 0,
  136784. 4,
  136785. };
  136786. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  136787. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  136788. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  136789. };
  136790. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  136791. -1.5, -0.5, 0.5, 1.5,
  136792. };
  136793. static long _vq_quantmap__44c0_sm_p7_1[] = {
  136794. 3, 1, 0, 2, 4,
  136795. };
  136796. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  136797. _vq_quantthresh__44c0_sm_p7_1,
  136798. _vq_quantmap__44c0_sm_p7_1,
  136799. 5,
  136800. 5
  136801. };
  136802. static static_codebook _44c0_sm_p7_1 = {
  136803. 2, 25,
  136804. _vq_lengthlist__44c0_sm_p7_1,
  136805. 1, -533725184, 1611661312, 3, 0,
  136806. _vq_quantlist__44c0_sm_p7_1,
  136807. NULL,
  136808. &_vq_auxt__44c0_sm_p7_1,
  136809. NULL,
  136810. 0
  136811. };
  136812. static long _vq_quantlist__44c0_sm_p8_0[] = {
  136813. 4,
  136814. 3,
  136815. 5,
  136816. 2,
  136817. 6,
  136818. 1,
  136819. 7,
  136820. 0,
  136821. 8,
  136822. };
  136823. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  136824. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  136825. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  136826. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136827. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  136828. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  136829. 12,
  136830. };
  136831. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  136832. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  136833. };
  136834. static long _vq_quantmap__44c0_sm_p8_0[] = {
  136835. 7, 5, 3, 1, 0, 2, 4, 6,
  136836. 8,
  136837. };
  136838. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  136839. _vq_quantthresh__44c0_sm_p8_0,
  136840. _vq_quantmap__44c0_sm_p8_0,
  136841. 9,
  136842. 9
  136843. };
  136844. static static_codebook _44c0_sm_p8_0 = {
  136845. 2, 81,
  136846. _vq_lengthlist__44c0_sm_p8_0,
  136847. 1, -516186112, 1627103232, 4, 0,
  136848. _vq_quantlist__44c0_sm_p8_0,
  136849. NULL,
  136850. &_vq_auxt__44c0_sm_p8_0,
  136851. NULL,
  136852. 0
  136853. };
  136854. static long _vq_quantlist__44c0_sm_p8_1[] = {
  136855. 6,
  136856. 5,
  136857. 7,
  136858. 4,
  136859. 8,
  136860. 3,
  136861. 9,
  136862. 2,
  136863. 10,
  136864. 1,
  136865. 11,
  136866. 0,
  136867. 12,
  136868. };
  136869. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  136870. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  136871. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  136872. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  136873. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  136874. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  136875. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  136876. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  136877. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  136878. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  136879. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  136880. 20,13,13,12,12,16,13,15,13,
  136881. };
  136882. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  136883. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  136884. 42.5, 59.5, 76.5, 93.5,
  136885. };
  136886. static long _vq_quantmap__44c0_sm_p8_1[] = {
  136887. 11, 9, 7, 5, 3, 1, 0, 2,
  136888. 4, 6, 8, 10, 12,
  136889. };
  136890. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  136891. _vq_quantthresh__44c0_sm_p8_1,
  136892. _vq_quantmap__44c0_sm_p8_1,
  136893. 13,
  136894. 13
  136895. };
  136896. static static_codebook _44c0_sm_p8_1 = {
  136897. 2, 169,
  136898. _vq_lengthlist__44c0_sm_p8_1,
  136899. 1, -522616832, 1620115456, 4, 0,
  136900. _vq_quantlist__44c0_sm_p8_1,
  136901. NULL,
  136902. &_vq_auxt__44c0_sm_p8_1,
  136903. NULL,
  136904. 0
  136905. };
  136906. static long _vq_quantlist__44c0_sm_p8_2[] = {
  136907. 8,
  136908. 7,
  136909. 9,
  136910. 6,
  136911. 10,
  136912. 5,
  136913. 11,
  136914. 4,
  136915. 12,
  136916. 3,
  136917. 13,
  136918. 2,
  136919. 14,
  136920. 1,
  136921. 15,
  136922. 0,
  136923. 16,
  136924. };
  136925. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  136926. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  136927. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  136928. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  136929. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  136930. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  136931. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  136932. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  136933. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  136934. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  136935. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  136936. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  136937. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  136938. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  136939. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  136940. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  136941. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  136942. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  136943. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  136944. 9,
  136945. };
  136946. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  136947. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136948. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136949. };
  136950. static long _vq_quantmap__44c0_sm_p8_2[] = {
  136951. 15, 13, 11, 9, 7, 5, 3, 1,
  136952. 0, 2, 4, 6, 8, 10, 12, 14,
  136953. 16,
  136954. };
  136955. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  136956. _vq_quantthresh__44c0_sm_p8_2,
  136957. _vq_quantmap__44c0_sm_p8_2,
  136958. 17,
  136959. 17
  136960. };
  136961. static static_codebook _44c0_sm_p8_2 = {
  136962. 2, 289,
  136963. _vq_lengthlist__44c0_sm_p8_2,
  136964. 1, -529530880, 1611661312, 5, 0,
  136965. _vq_quantlist__44c0_sm_p8_2,
  136966. NULL,
  136967. &_vq_auxt__44c0_sm_p8_2,
  136968. NULL,
  136969. 0
  136970. };
  136971. static long _huff_lengthlist__44c0_sm_short[] = {
  136972. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  136973. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  136974. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  136975. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  136976. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  136977. 12,
  136978. };
  136979. static static_codebook _huff_book__44c0_sm_short = {
  136980. 2, 81,
  136981. _huff_lengthlist__44c0_sm_short,
  136982. 0, 0, 0, 0, 0,
  136983. NULL,
  136984. NULL,
  136985. NULL,
  136986. NULL,
  136987. 0
  136988. };
  136989. static long _huff_lengthlist__44c1_s_long[] = {
  136990. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  136991. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  136992. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  136993. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  136994. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  136995. 11,
  136996. };
  136997. static static_codebook _huff_book__44c1_s_long = {
  136998. 2, 81,
  136999. _huff_lengthlist__44c1_s_long,
  137000. 0, 0, 0, 0, 0,
  137001. NULL,
  137002. NULL,
  137003. NULL,
  137004. NULL,
  137005. 0
  137006. };
  137007. static long _vq_quantlist__44c1_s_p1_0[] = {
  137008. 1,
  137009. 0,
  137010. 2,
  137011. };
  137012. static long _vq_lengthlist__44c1_s_p1_0[] = {
  137013. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  137014. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137018. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  137019. 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137023. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137024. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  137059. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  137064. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  137065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  137069. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  137070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137104. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137105. 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137109. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  137110. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  137111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137114. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  137115. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  137116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137347. 0, 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, 0, 0, 0, 0, 0, 0, 0,
  137367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  137372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  137377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137418. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137423. 0,
  137424. };
  137425. static float _vq_quantthresh__44c1_s_p1_0[] = {
  137426. -0.5, 0.5,
  137427. };
  137428. static long _vq_quantmap__44c1_s_p1_0[] = {
  137429. 1, 0, 2,
  137430. };
  137431. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  137432. _vq_quantthresh__44c1_s_p1_0,
  137433. _vq_quantmap__44c1_s_p1_0,
  137434. 3,
  137435. 3
  137436. };
  137437. static static_codebook _44c1_s_p1_0 = {
  137438. 8, 6561,
  137439. _vq_lengthlist__44c1_s_p1_0,
  137440. 1, -535822336, 1611661312, 2, 0,
  137441. _vq_quantlist__44c1_s_p1_0,
  137442. NULL,
  137443. &_vq_auxt__44c1_s_p1_0,
  137444. NULL,
  137445. 0
  137446. };
  137447. static long _vq_quantlist__44c1_s_p2_0[] = {
  137448. 2,
  137449. 1,
  137450. 3,
  137451. 0,
  137452. 4,
  137453. };
  137454. static long _vq_lengthlist__44c1_s_p2_0[] = {
  137455. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  137457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137458. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  137460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137461. 0, 0, 0, 0, 6, 6, 6, 8, 8, 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,
  137495. };
  137496. static float _vq_quantthresh__44c1_s_p2_0[] = {
  137497. -1.5, -0.5, 0.5, 1.5,
  137498. };
  137499. static long _vq_quantmap__44c1_s_p2_0[] = {
  137500. 3, 1, 0, 2, 4,
  137501. };
  137502. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  137503. _vq_quantthresh__44c1_s_p2_0,
  137504. _vq_quantmap__44c1_s_p2_0,
  137505. 5,
  137506. 5
  137507. };
  137508. static static_codebook _44c1_s_p2_0 = {
  137509. 4, 625,
  137510. _vq_lengthlist__44c1_s_p2_0,
  137511. 1, -533725184, 1611661312, 3, 0,
  137512. _vq_quantlist__44c1_s_p2_0,
  137513. NULL,
  137514. &_vq_auxt__44c1_s_p2_0,
  137515. NULL,
  137516. 0
  137517. };
  137518. static long _vq_quantlist__44c1_s_p3_0[] = {
  137519. 4,
  137520. 3,
  137521. 5,
  137522. 2,
  137523. 6,
  137524. 1,
  137525. 7,
  137526. 0,
  137527. 8,
  137528. };
  137529. static long _vq_lengthlist__44c1_s_p3_0[] = {
  137530. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  137531. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  137532. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  137533. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  137534. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137535. 0,
  137536. };
  137537. static float _vq_quantthresh__44c1_s_p3_0[] = {
  137538. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137539. };
  137540. static long _vq_quantmap__44c1_s_p3_0[] = {
  137541. 7, 5, 3, 1, 0, 2, 4, 6,
  137542. 8,
  137543. };
  137544. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  137545. _vq_quantthresh__44c1_s_p3_0,
  137546. _vq_quantmap__44c1_s_p3_0,
  137547. 9,
  137548. 9
  137549. };
  137550. static static_codebook _44c1_s_p3_0 = {
  137551. 2, 81,
  137552. _vq_lengthlist__44c1_s_p3_0,
  137553. 1, -531628032, 1611661312, 4, 0,
  137554. _vq_quantlist__44c1_s_p3_0,
  137555. NULL,
  137556. &_vq_auxt__44c1_s_p3_0,
  137557. NULL,
  137558. 0
  137559. };
  137560. static long _vq_quantlist__44c1_s_p4_0[] = {
  137561. 4,
  137562. 3,
  137563. 5,
  137564. 2,
  137565. 6,
  137566. 1,
  137567. 7,
  137568. 0,
  137569. 8,
  137570. };
  137571. static long _vq_lengthlist__44c1_s_p4_0[] = {
  137572. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  137573. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  137574. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  137575. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  137576. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  137577. 11,
  137578. };
  137579. static float _vq_quantthresh__44c1_s_p4_0[] = {
  137580. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137581. };
  137582. static long _vq_quantmap__44c1_s_p4_0[] = {
  137583. 7, 5, 3, 1, 0, 2, 4, 6,
  137584. 8,
  137585. };
  137586. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  137587. _vq_quantthresh__44c1_s_p4_0,
  137588. _vq_quantmap__44c1_s_p4_0,
  137589. 9,
  137590. 9
  137591. };
  137592. static static_codebook _44c1_s_p4_0 = {
  137593. 2, 81,
  137594. _vq_lengthlist__44c1_s_p4_0,
  137595. 1, -531628032, 1611661312, 4, 0,
  137596. _vq_quantlist__44c1_s_p4_0,
  137597. NULL,
  137598. &_vq_auxt__44c1_s_p4_0,
  137599. NULL,
  137600. 0
  137601. };
  137602. static long _vq_quantlist__44c1_s_p5_0[] = {
  137603. 8,
  137604. 7,
  137605. 9,
  137606. 6,
  137607. 10,
  137608. 5,
  137609. 11,
  137610. 4,
  137611. 12,
  137612. 3,
  137613. 13,
  137614. 2,
  137615. 14,
  137616. 1,
  137617. 15,
  137618. 0,
  137619. 16,
  137620. };
  137621. static long _vq_lengthlist__44c1_s_p5_0[] = {
  137622. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  137623. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  137624. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  137625. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  137626. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  137627. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  137628. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  137629. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  137630. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  137631. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  137632. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  137633. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  137634. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  137635. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  137636. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  137637. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  137638. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  137639. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  137640. 14,
  137641. };
  137642. static float _vq_quantthresh__44c1_s_p5_0[] = {
  137643. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137644. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137645. };
  137646. static long _vq_quantmap__44c1_s_p5_0[] = {
  137647. 15, 13, 11, 9, 7, 5, 3, 1,
  137648. 0, 2, 4, 6, 8, 10, 12, 14,
  137649. 16,
  137650. };
  137651. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  137652. _vq_quantthresh__44c1_s_p5_0,
  137653. _vq_quantmap__44c1_s_p5_0,
  137654. 17,
  137655. 17
  137656. };
  137657. static static_codebook _44c1_s_p5_0 = {
  137658. 2, 289,
  137659. _vq_lengthlist__44c1_s_p5_0,
  137660. 1, -529530880, 1611661312, 5, 0,
  137661. _vq_quantlist__44c1_s_p5_0,
  137662. NULL,
  137663. &_vq_auxt__44c1_s_p5_0,
  137664. NULL,
  137665. 0
  137666. };
  137667. static long _vq_quantlist__44c1_s_p6_0[] = {
  137668. 1,
  137669. 0,
  137670. 2,
  137671. };
  137672. static long _vq_lengthlist__44c1_s_p6_0[] = {
  137673. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  137674. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  137675. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  137676. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  137677. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  137678. 11,
  137679. };
  137680. static float _vq_quantthresh__44c1_s_p6_0[] = {
  137681. -5.5, 5.5,
  137682. };
  137683. static long _vq_quantmap__44c1_s_p6_0[] = {
  137684. 1, 0, 2,
  137685. };
  137686. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  137687. _vq_quantthresh__44c1_s_p6_0,
  137688. _vq_quantmap__44c1_s_p6_0,
  137689. 3,
  137690. 3
  137691. };
  137692. static static_codebook _44c1_s_p6_0 = {
  137693. 4, 81,
  137694. _vq_lengthlist__44c1_s_p6_0,
  137695. 1, -529137664, 1618345984, 2, 0,
  137696. _vq_quantlist__44c1_s_p6_0,
  137697. NULL,
  137698. &_vq_auxt__44c1_s_p6_0,
  137699. NULL,
  137700. 0
  137701. };
  137702. static long _vq_quantlist__44c1_s_p6_1[] = {
  137703. 5,
  137704. 4,
  137705. 6,
  137706. 3,
  137707. 7,
  137708. 2,
  137709. 8,
  137710. 1,
  137711. 9,
  137712. 0,
  137713. 10,
  137714. };
  137715. static long _vq_lengthlist__44c1_s_p6_1[] = {
  137716. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  137717. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  137718. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  137719. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  137720. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  137721. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  137722. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  137723. 10,10,10, 8, 8, 8, 8, 8, 8,
  137724. };
  137725. static float _vq_quantthresh__44c1_s_p6_1[] = {
  137726. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137727. 3.5, 4.5,
  137728. };
  137729. static long _vq_quantmap__44c1_s_p6_1[] = {
  137730. 9, 7, 5, 3, 1, 0, 2, 4,
  137731. 6, 8, 10,
  137732. };
  137733. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  137734. _vq_quantthresh__44c1_s_p6_1,
  137735. _vq_quantmap__44c1_s_p6_1,
  137736. 11,
  137737. 11
  137738. };
  137739. static static_codebook _44c1_s_p6_1 = {
  137740. 2, 121,
  137741. _vq_lengthlist__44c1_s_p6_1,
  137742. 1, -531365888, 1611661312, 4, 0,
  137743. _vq_quantlist__44c1_s_p6_1,
  137744. NULL,
  137745. &_vq_auxt__44c1_s_p6_1,
  137746. NULL,
  137747. 0
  137748. };
  137749. static long _vq_quantlist__44c1_s_p7_0[] = {
  137750. 6,
  137751. 5,
  137752. 7,
  137753. 4,
  137754. 8,
  137755. 3,
  137756. 9,
  137757. 2,
  137758. 10,
  137759. 1,
  137760. 11,
  137761. 0,
  137762. 12,
  137763. };
  137764. static long _vq_lengthlist__44c1_s_p7_0[] = {
  137765. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  137766. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  137767. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  137768. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  137769. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  137770. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  137771. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  137772. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  137773. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  137774. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  137775. 0,12,11,11,11,13,10,14,13,
  137776. };
  137777. static float _vq_quantthresh__44c1_s_p7_0[] = {
  137778. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  137779. 12.5, 17.5, 22.5, 27.5,
  137780. };
  137781. static long _vq_quantmap__44c1_s_p7_0[] = {
  137782. 11, 9, 7, 5, 3, 1, 0, 2,
  137783. 4, 6, 8, 10, 12,
  137784. };
  137785. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  137786. _vq_quantthresh__44c1_s_p7_0,
  137787. _vq_quantmap__44c1_s_p7_0,
  137788. 13,
  137789. 13
  137790. };
  137791. static static_codebook _44c1_s_p7_0 = {
  137792. 2, 169,
  137793. _vq_lengthlist__44c1_s_p7_0,
  137794. 1, -526516224, 1616117760, 4, 0,
  137795. _vq_quantlist__44c1_s_p7_0,
  137796. NULL,
  137797. &_vq_auxt__44c1_s_p7_0,
  137798. NULL,
  137799. 0
  137800. };
  137801. static long _vq_quantlist__44c1_s_p7_1[] = {
  137802. 2,
  137803. 1,
  137804. 3,
  137805. 0,
  137806. 4,
  137807. };
  137808. static long _vq_lengthlist__44c1_s_p7_1[] = {
  137809. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  137810. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  137811. };
  137812. static float _vq_quantthresh__44c1_s_p7_1[] = {
  137813. -1.5, -0.5, 0.5, 1.5,
  137814. };
  137815. static long _vq_quantmap__44c1_s_p7_1[] = {
  137816. 3, 1, 0, 2, 4,
  137817. };
  137818. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  137819. _vq_quantthresh__44c1_s_p7_1,
  137820. _vq_quantmap__44c1_s_p7_1,
  137821. 5,
  137822. 5
  137823. };
  137824. static static_codebook _44c1_s_p7_1 = {
  137825. 2, 25,
  137826. _vq_lengthlist__44c1_s_p7_1,
  137827. 1, -533725184, 1611661312, 3, 0,
  137828. _vq_quantlist__44c1_s_p7_1,
  137829. NULL,
  137830. &_vq_auxt__44c1_s_p7_1,
  137831. NULL,
  137832. 0
  137833. };
  137834. static long _vq_quantlist__44c1_s_p8_0[] = {
  137835. 6,
  137836. 5,
  137837. 7,
  137838. 4,
  137839. 8,
  137840. 3,
  137841. 9,
  137842. 2,
  137843. 10,
  137844. 1,
  137845. 11,
  137846. 0,
  137847. 12,
  137848. };
  137849. static long _vq_lengthlist__44c1_s_p8_0[] = {
  137850. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  137851. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  137852. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137853. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137854. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137855. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137856. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137857. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137858. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137859. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137860. 10,10,10,10,10,10,10,10,10,
  137861. };
  137862. static float _vq_quantthresh__44c1_s_p8_0[] = {
  137863. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  137864. 552.5, 773.5, 994.5, 1215.5,
  137865. };
  137866. static long _vq_quantmap__44c1_s_p8_0[] = {
  137867. 11, 9, 7, 5, 3, 1, 0, 2,
  137868. 4, 6, 8, 10, 12,
  137869. };
  137870. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  137871. _vq_quantthresh__44c1_s_p8_0,
  137872. _vq_quantmap__44c1_s_p8_0,
  137873. 13,
  137874. 13
  137875. };
  137876. static static_codebook _44c1_s_p8_0 = {
  137877. 2, 169,
  137878. _vq_lengthlist__44c1_s_p8_0,
  137879. 1, -514541568, 1627103232, 4, 0,
  137880. _vq_quantlist__44c1_s_p8_0,
  137881. NULL,
  137882. &_vq_auxt__44c1_s_p8_0,
  137883. NULL,
  137884. 0
  137885. };
  137886. static long _vq_quantlist__44c1_s_p8_1[] = {
  137887. 6,
  137888. 5,
  137889. 7,
  137890. 4,
  137891. 8,
  137892. 3,
  137893. 9,
  137894. 2,
  137895. 10,
  137896. 1,
  137897. 11,
  137898. 0,
  137899. 12,
  137900. };
  137901. static long _vq_lengthlist__44c1_s_p8_1[] = {
  137902. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  137903. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  137904. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  137905. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  137906. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  137907. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  137908. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  137909. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  137910. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  137911. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  137912. 16,13,12,12,11,14,12,15,13,
  137913. };
  137914. static float _vq_quantthresh__44c1_s_p8_1[] = {
  137915. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  137916. 42.5, 59.5, 76.5, 93.5,
  137917. };
  137918. static long _vq_quantmap__44c1_s_p8_1[] = {
  137919. 11, 9, 7, 5, 3, 1, 0, 2,
  137920. 4, 6, 8, 10, 12,
  137921. };
  137922. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  137923. _vq_quantthresh__44c1_s_p8_1,
  137924. _vq_quantmap__44c1_s_p8_1,
  137925. 13,
  137926. 13
  137927. };
  137928. static static_codebook _44c1_s_p8_1 = {
  137929. 2, 169,
  137930. _vq_lengthlist__44c1_s_p8_1,
  137931. 1, -522616832, 1620115456, 4, 0,
  137932. _vq_quantlist__44c1_s_p8_1,
  137933. NULL,
  137934. &_vq_auxt__44c1_s_p8_1,
  137935. NULL,
  137936. 0
  137937. };
  137938. static long _vq_quantlist__44c1_s_p8_2[] = {
  137939. 8,
  137940. 7,
  137941. 9,
  137942. 6,
  137943. 10,
  137944. 5,
  137945. 11,
  137946. 4,
  137947. 12,
  137948. 3,
  137949. 13,
  137950. 2,
  137951. 14,
  137952. 1,
  137953. 15,
  137954. 0,
  137955. 16,
  137956. };
  137957. static long _vq_lengthlist__44c1_s_p8_2[] = {
  137958. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  137959. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  137960. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  137961. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  137962. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  137963. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  137964. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  137965. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  137966. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  137967. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  137968. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  137969. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  137970. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  137971. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  137972. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  137973. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  137974. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  137975. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  137976. 9,
  137977. };
  137978. static float _vq_quantthresh__44c1_s_p8_2[] = {
  137979. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137980. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137981. };
  137982. static long _vq_quantmap__44c1_s_p8_2[] = {
  137983. 15, 13, 11, 9, 7, 5, 3, 1,
  137984. 0, 2, 4, 6, 8, 10, 12, 14,
  137985. 16,
  137986. };
  137987. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  137988. _vq_quantthresh__44c1_s_p8_2,
  137989. _vq_quantmap__44c1_s_p8_2,
  137990. 17,
  137991. 17
  137992. };
  137993. static static_codebook _44c1_s_p8_2 = {
  137994. 2, 289,
  137995. _vq_lengthlist__44c1_s_p8_2,
  137996. 1, -529530880, 1611661312, 5, 0,
  137997. _vq_quantlist__44c1_s_p8_2,
  137998. NULL,
  137999. &_vq_auxt__44c1_s_p8_2,
  138000. NULL,
  138001. 0
  138002. };
  138003. static long _huff_lengthlist__44c1_s_short[] = {
  138004. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  138005. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  138006. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  138007. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  138008. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  138009. 11,
  138010. };
  138011. static static_codebook _huff_book__44c1_s_short = {
  138012. 2, 81,
  138013. _huff_lengthlist__44c1_s_short,
  138014. 0, 0, 0, 0, 0,
  138015. NULL,
  138016. NULL,
  138017. NULL,
  138018. NULL,
  138019. 0
  138020. };
  138021. static long _huff_lengthlist__44c1_sm_long[] = {
  138022. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  138023. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  138024. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  138025. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  138026. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  138027. 11,
  138028. };
  138029. static static_codebook _huff_book__44c1_sm_long = {
  138030. 2, 81,
  138031. _huff_lengthlist__44c1_sm_long,
  138032. 0, 0, 0, 0, 0,
  138033. NULL,
  138034. NULL,
  138035. NULL,
  138036. NULL,
  138037. 0
  138038. };
  138039. static long _vq_quantlist__44c1_sm_p1_0[] = {
  138040. 1,
  138041. 0,
  138042. 2,
  138043. };
  138044. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  138045. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  138046. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138050. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  138051. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138055. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  138056. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  138091. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  138092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  138096. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  138097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  138101. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  138102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138136. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  138137. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138141. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  138142. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  138143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138146. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  138147. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  138148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  138404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  138409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138455. 0,
  138456. };
  138457. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  138458. -0.5, 0.5,
  138459. };
  138460. static long _vq_quantmap__44c1_sm_p1_0[] = {
  138461. 1, 0, 2,
  138462. };
  138463. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  138464. _vq_quantthresh__44c1_sm_p1_0,
  138465. _vq_quantmap__44c1_sm_p1_0,
  138466. 3,
  138467. 3
  138468. };
  138469. static static_codebook _44c1_sm_p1_0 = {
  138470. 8, 6561,
  138471. _vq_lengthlist__44c1_sm_p1_0,
  138472. 1, -535822336, 1611661312, 2, 0,
  138473. _vq_quantlist__44c1_sm_p1_0,
  138474. NULL,
  138475. &_vq_auxt__44c1_sm_p1_0,
  138476. NULL,
  138477. 0
  138478. };
  138479. static long _vq_quantlist__44c1_sm_p2_0[] = {
  138480. 2,
  138481. 1,
  138482. 3,
  138483. 0,
  138484. 4,
  138485. };
  138486. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  138487. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  138489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138490. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  138492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138493. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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,
  138527. };
  138528. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  138529. -1.5, -0.5, 0.5, 1.5,
  138530. };
  138531. static long _vq_quantmap__44c1_sm_p2_0[] = {
  138532. 3, 1, 0, 2, 4,
  138533. };
  138534. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  138535. _vq_quantthresh__44c1_sm_p2_0,
  138536. _vq_quantmap__44c1_sm_p2_0,
  138537. 5,
  138538. 5
  138539. };
  138540. static static_codebook _44c1_sm_p2_0 = {
  138541. 4, 625,
  138542. _vq_lengthlist__44c1_sm_p2_0,
  138543. 1, -533725184, 1611661312, 3, 0,
  138544. _vq_quantlist__44c1_sm_p2_0,
  138545. NULL,
  138546. &_vq_auxt__44c1_sm_p2_0,
  138547. NULL,
  138548. 0
  138549. };
  138550. static long _vq_quantlist__44c1_sm_p3_0[] = {
  138551. 4,
  138552. 3,
  138553. 5,
  138554. 2,
  138555. 6,
  138556. 1,
  138557. 7,
  138558. 0,
  138559. 8,
  138560. };
  138561. static long _vq_lengthlist__44c1_sm_p3_0[] = {
  138562. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  138563. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  138564. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  138565. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  138566. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138567. 0,
  138568. };
  138569. static float _vq_quantthresh__44c1_sm_p3_0[] = {
  138570. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138571. };
  138572. static long _vq_quantmap__44c1_sm_p3_0[] = {
  138573. 7, 5, 3, 1, 0, 2, 4, 6,
  138574. 8,
  138575. };
  138576. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  138577. _vq_quantthresh__44c1_sm_p3_0,
  138578. _vq_quantmap__44c1_sm_p3_0,
  138579. 9,
  138580. 9
  138581. };
  138582. static static_codebook _44c1_sm_p3_0 = {
  138583. 2, 81,
  138584. _vq_lengthlist__44c1_sm_p3_0,
  138585. 1, -531628032, 1611661312, 4, 0,
  138586. _vq_quantlist__44c1_sm_p3_0,
  138587. NULL,
  138588. &_vq_auxt__44c1_sm_p3_0,
  138589. NULL,
  138590. 0
  138591. };
  138592. static long _vq_quantlist__44c1_sm_p4_0[] = {
  138593. 4,
  138594. 3,
  138595. 5,
  138596. 2,
  138597. 6,
  138598. 1,
  138599. 7,
  138600. 0,
  138601. 8,
  138602. };
  138603. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  138604. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  138605. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  138606. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  138607. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  138608. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  138609. 11,
  138610. };
  138611. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  138612. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138613. };
  138614. static long _vq_quantmap__44c1_sm_p4_0[] = {
  138615. 7, 5, 3, 1, 0, 2, 4, 6,
  138616. 8,
  138617. };
  138618. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  138619. _vq_quantthresh__44c1_sm_p4_0,
  138620. _vq_quantmap__44c1_sm_p4_0,
  138621. 9,
  138622. 9
  138623. };
  138624. static static_codebook _44c1_sm_p4_0 = {
  138625. 2, 81,
  138626. _vq_lengthlist__44c1_sm_p4_0,
  138627. 1, -531628032, 1611661312, 4, 0,
  138628. _vq_quantlist__44c1_sm_p4_0,
  138629. NULL,
  138630. &_vq_auxt__44c1_sm_p4_0,
  138631. NULL,
  138632. 0
  138633. };
  138634. static long _vq_quantlist__44c1_sm_p5_0[] = {
  138635. 8,
  138636. 7,
  138637. 9,
  138638. 6,
  138639. 10,
  138640. 5,
  138641. 11,
  138642. 4,
  138643. 12,
  138644. 3,
  138645. 13,
  138646. 2,
  138647. 14,
  138648. 1,
  138649. 15,
  138650. 0,
  138651. 16,
  138652. };
  138653. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  138654. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  138655. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  138656. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  138657. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  138658. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  138659. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  138660. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  138661. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  138662. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  138663. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  138664. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  138665. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  138666. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  138667. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  138668. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  138669. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  138670. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  138671. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  138672. 14,
  138673. };
  138674. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  138675. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138676. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138677. };
  138678. static long _vq_quantmap__44c1_sm_p5_0[] = {
  138679. 15, 13, 11, 9, 7, 5, 3, 1,
  138680. 0, 2, 4, 6, 8, 10, 12, 14,
  138681. 16,
  138682. };
  138683. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  138684. _vq_quantthresh__44c1_sm_p5_0,
  138685. _vq_quantmap__44c1_sm_p5_0,
  138686. 17,
  138687. 17
  138688. };
  138689. static static_codebook _44c1_sm_p5_0 = {
  138690. 2, 289,
  138691. _vq_lengthlist__44c1_sm_p5_0,
  138692. 1, -529530880, 1611661312, 5, 0,
  138693. _vq_quantlist__44c1_sm_p5_0,
  138694. NULL,
  138695. &_vq_auxt__44c1_sm_p5_0,
  138696. NULL,
  138697. 0
  138698. };
  138699. static long _vq_quantlist__44c1_sm_p6_0[] = {
  138700. 1,
  138701. 0,
  138702. 2,
  138703. };
  138704. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  138705. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  138706. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  138707. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  138708. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  138709. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  138710. 11,
  138711. };
  138712. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  138713. -5.5, 5.5,
  138714. };
  138715. static long _vq_quantmap__44c1_sm_p6_0[] = {
  138716. 1, 0, 2,
  138717. };
  138718. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  138719. _vq_quantthresh__44c1_sm_p6_0,
  138720. _vq_quantmap__44c1_sm_p6_0,
  138721. 3,
  138722. 3
  138723. };
  138724. static static_codebook _44c1_sm_p6_0 = {
  138725. 4, 81,
  138726. _vq_lengthlist__44c1_sm_p6_0,
  138727. 1, -529137664, 1618345984, 2, 0,
  138728. _vq_quantlist__44c1_sm_p6_0,
  138729. NULL,
  138730. &_vq_auxt__44c1_sm_p6_0,
  138731. NULL,
  138732. 0
  138733. };
  138734. static long _vq_quantlist__44c1_sm_p6_1[] = {
  138735. 5,
  138736. 4,
  138737. 6,
  138738. 3,
  138739. 7,
  138740. 2,
  138741. 8,
  138742. 1,
  138743. 9,
  138744. 0,
  138745. 10,
  138746. };
  138747. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  138748. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  138749. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  138750. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  138751. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  138752. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  138753. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  138754. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  138755. 10,10,10, 8, 8, 8, 8, 8, 8,
  138756. };
  138757. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  138758. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138759. 3.5, 4.5,
  138760. };
  138761. static long _vq_quantmap__44c1_sm_p6_1[] = {
  138762. 9, 7, 5, 3, 1, 0, 2, 4,
  138763. 6, 8, 10,
  138764. };
  138765. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  138766. _vq_quantthresh__44c1_sm_p6_1,
  138767. _vq_quantmap__44c1_sm_p6_1,
  138768. 11,
  138769. 11
  138770. };
  138771. static static_codebook _44c1_sm_p6_1 = {
  138772. 2, 121,
  138773. _vq_lengthlist__44c1_sm_p6_1,
  138774. 1, -531365888, 1611661312, 4, 0,
  138775. _vq_quantlist__44c1_sm_p6_1,
  138776. NULL,
  138777. &_vq_auxt__44c1_sm_p6_1,
  138778. NULL,
  138779. 0
  138780. };
  138781. static long _vq_quantlist__44c1_sm_p7_0[] = {
  138782. 6,
  138783. 5,
  138784. 7,
  138785. 4,
  138786. 8,
  138787. 3,
  138788. 9,
  138789. 2,
  138790. 10,
  138791. 1,
  138792. 11,
  138793. 0,
  138794. 12,
  138795. };
  138796. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  138797. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  138798. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  138799. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  138800. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  138801. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  138802. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  138803. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  138804. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  138805. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  138806. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  138807. 0,12,12,11,11,13,12,14,13,
  138808. };
  138809. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  138810. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138811. 12.5, 17.5, 22.5, 27.5,
  138812. };
  138813. static long _vq_quantmap__44c1_sm_p7_0[] = {
  138814. 11, 9, 7, 5, 3, 1, 0, 2,
  138815. 4, 6, 8, 10, 12,
  138816. };
  138817. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  138818. _vq_quantthresh__44c1_sm_p7_0,
  138819. _vq_quantmap__44c1_sm_p7_0,
  138820. 13,
  138821. 13
  138822. };
  138823. static static_codebook _44c1_sm_p7_0 = {
  138824. 2, 169,
  138825. _vq_lengthlist__44c1_sm_p7_0,
  138826. 1, -526516224, 1616117760, 4, 0,
  138827. _vq_quantlist__44c1_sm_p7_0,
  138828. NULL,
  138829. &_vq_auxt__44c1_sm_p7_0,
  138830. NULL,
  138831. 0
  138832. };
  138833. static long _vq_quantlist__44c1_sm_p7_1[] = {
  138834. 2,
  138835. 1,
  138836. 3,
  138837. 0,
  138838. 4,
  138839. };
  138840. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  138841. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  138842. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  138843. };
  138844. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  138845. -1.5, -0.5, 0.5, 1.5,
  138846. };
  138847. static long _vq_quantmap__44c1_sm_p7_1[] = {
  138848. 3, 1, 0, 2, 4,
  138849. };
  138850. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  138851. _vq_quantthresh__44c1_sm_p7_1,
  138852. _vq_quantmap__44c1_sm_p7_1,
  138853. 5,
  138854. 5
  138855. };
  138856. static static_codebook _44c1_sm_p7_1 = {
  138857. 2, 25,
  138858. _vq_lengthlist__44c1_sm_p7_1,
  138859. 1, -533725184, 1611661312, 3, 0,
  138860. _vq_quantlist__44c1_sm_p7_1,
  138861. NULL,
  138862. &_vq_auxt__44c1_sm_p7_1,
  138863. NULL,
  138864. 0
  138865. };
  138866. static long _vq_quantlist__44c1_sm_p8_0[] = {
  138867. 6,
  138868. 5,
  138869. 7,
  138870. 4,
  138871. 8,
  138872. 3,
  138873. 9,
  138874. 2,
  138875. 10,
  138876. 1,
  138877. 11,
  138878. 0,
  138879. 12,
  138880. };
  138881. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  138882. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  138883. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  138884. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  138885. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  138886. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  138887. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  138888. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  138889. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  138890. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  138891. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  138892. 13,13,13,13,13,13,13,13,13,
  138893. };
  138894. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  138895. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  138896. 552.5, 773.5, 994.5, 1215.5,
  138897. };
  138898. static long _vq_quantmap__44c1_sm_p8_0[] = {
  138899. 11, 9, 7, 5, 3, 1, 0, 2,
  138900. 4, 6, 8, 10, 12,
  138901. };
  138902. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  138903. _vq_quantthresh__44c1_sm_p8_0,
  138904. _vq_quantmap__44c1_sm_p8_0,
  138905. 13,
  138906. 13
  138907. };
  138908. static static_codebook _44c1_sm_p8_0 = {
  138909. 2, 169,
  138910. _vq_lengthlist__44c1_sm_p8_0,
  138911. 1, -514541568, 1627103232, 4, 0,
  138912. _vq_quantlist__44c1_sm_p8_0,
  138913. NULL,
  138914. &_vq_auxt__44c1_sm_p8_0,
  138915. NULL,
  138916. 0
  138917. };
  138918. static long _vq_quantlist__44c1_sm_p8_1[] = {
  138919. 6,
  138920. 5,
  138921. 7,
  138922. 4,
  138923. 8,
  138924. 3,
  138925. 9,
  138926. 2,
  138927. 10,
  138928. 1,
  138929. 11,
  138930. 0,
  138931. 12,
  138932. };
  138933. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  138934. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  138935. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  138936. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  138937. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  138938. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  138939. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  138940. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  138941. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  138942. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  138943. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  138944. 20,13,12,12,12,14,12,14,13,
  138945. };
  138946. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  138947. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  138948. 42.5, 59.5, 76.5, 93.5,
  138949. };
  138950. static long _vq_quantmap__44c1_sm_p8_1[] = {
  138951. 11, 9, 7, 5, 3, 1, 0, 2,
  138952. 4, 6, 8, 10, 12,
  138953. };
  138954. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  138955. _vq_quantthresh__44c1_sm_p8_1,
  138956. _vq_quantmap__44c1_sm_p8_1,
  138957. 13,
  138958. 13
  138959. };
  138960. static static_codebook _44c1_sm_p8_1 = {
  138961. 2, 169,
  138962. _vq_lengthlist__44c1_sm_p8_1,
  138963. 1, -522616832, 1620115456, 4, 0,
  138964. _vq_quantlist__44c1_sm_p8_1,
  138965. NULL,
  138966. &_vq_auxt__44c1_sm_p8_1,
  138967. NULL,
  138968. 0
  138969. };
  138970. static long _vq_quantlist__44c1_sm_p8_2[] = {
  138971. 8,
  138972. 7,
  138973. 9,
  138974. 6,
  138975. 10,
  138976. 5,
  138977. 11,
  138978. 4,
  138979. 12,
  138980. 3,
  138981. 13,
  138982. 2,
  138983. 14,
  138984. 1,
  138985. 15,
  138986. 0,
  138987. 16,
  138988. };
  138989. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  138990. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  138991. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  138992. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  138993. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  138994. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  138995. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  138996. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  138997. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  138998. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  138999. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  139000. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  139001. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  139002. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  139003. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  139004. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  139005. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  139006. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  139007. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  139008. 9,
  139009. };
  139010. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  139011. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139012. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139013. };
  139014. static long _vq_quantmap__44c1_sm_p8_2[] = {
  139015. 15, 13, 11, 9, 7, 5, 3, 1,
  139016. 0, 2, 4, 6, 8, 10, 12, 14,
  139017. 16,
  139018. };
  139019. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  139020. _vq_quantthresh__44c1_sm_p8_2,
  139021. _vq_quantmap__44c1_sm_p8_2,
  139022. 17,
  139023. 17
  139024. };
  139025. static static_codebook _44c1_sm_p8_2 = {
  139026. 2, 289,
  139027. _vq_lengthlist__44c1_sm_p8_2,
  139028. 1, -529530880, 1611661312, 5, 0,
  139029. _vq_quantlist__44c1_sm_p8_2,
  139030. NULL,
  139031. &_vq_auxt__44c1_sm_p8_2,
  139032. NULL,
  139033. 0
  139034. };
  139035. static long _huff_lengthlist__44c1_sm_short[] = {
  139036. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  139037. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  139038. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  139039. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  139040. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  139041. 11,
  139042. };
  139043. static static_codebook _huff_book__44c1_sm_short = {
  139044. 2, 81,
  139045. _huff_lengthlist__44c1_sm_short,
  139046. 0, 0, 0, 0, 0,
  139047. NULL,
  139048. NULL,
  139049. NULL,
  139050. NULL,
  139051. 0
  139052. };
  139053. static long _huff_lengthlist__44cn1_s_long[] = {
  139054. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  139055. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  139056. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  139057. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  139058. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  139059. 20,
  139060. };
  139061. static static_codebook _huff_book__44cn1_s_long = {
  139062. 2, 81,
  139063. _huff_lengthlist__44cn1_s_long,
  139064. 0, 0, 0, 0, 0,
  139065. NULL,
  139066. NULL,
  139067. NULL,
  139068. NULL,
  139069. 0
  139070. };
  139071. static long _vq_quantlist__44cn1_s_p1_0[] = {
  139072. 1,
  139073. 0,
  139074. 2,
  139075. };
  139076. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  139077. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  139078. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139082. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  139083. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139087. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  139088. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  139123. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0,
  139124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  139128. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  139129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  139133. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  139134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139168. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  139169. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139173. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  139174. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  139175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139178. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  139179. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  139180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139386. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139391. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139396. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  139431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  139436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  139441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139477. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139482. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139487. 0,
  139488. };
  139489. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  139490. -0.5, 0.5,
  139491. };
  139492. static long _vq_quantmap__44cn1_s_p1_0[] = {
  139493. 1, 0, 2,
  139494. };
  139495. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  139496. _vq_quantthresh__44cn1_s_p1_0,
  139497. _vq_quantmap__44cn1_s_p1_0,
  139498. 3,
  139499. 3
  139500. };
  139501. static static_codebook _44cn1_s_p1_0 = {
  139502. 8, 6561,
  139503. _vq_lengthlist__44cn1_s_p1_0,
  139504. 1, -535822336, 1611661312, 2, 0,
  139505. _vq_quantlist__44cn1_s_p1_0,
  139506. NULL,
  139507. &_vq_auxt__44cn1_s_p1_0,
  139508. NULL,
  139509. 0
  139510. };
  139511. static long _vq_quantlist__44cn1_s_p2_0[] = {
  139512. 2,
  139513. 1,
  139514. 3,
  139515. 0,
  139516. 4,
  139517. };
  139518. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  139519. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  139521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139522. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  139524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139525. 0, 0, 0, 0, 6, 7, 7, 9, 9, 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,
  139559. };
  139560. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  139561. -1.5, -0.5, 0.5, 1.5,
  139562. };
  139563. static long _vq_quantmap__44cn1_s_p2_0[] = {
  139564. 3, 1, 0, 2, 4,
  139565. };
  139566. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  139567. _vq_quantthresh__44cn1_s_p2_0,
  139568. _vq_quantmap__44cn1_s_p2_0,
  139569. 5,
  139570. 5
  139571. };
  139572. static static_codebook _44cn1_s_p2_0 = {
  139573. 4, 625,
  139574. _vq_lengthlist__44cn1_s_p2_0,
  139575. 1, -533725184, 1611661312, 3, 0,
  139576. _vq_quantlist__44cn1_s_p2_0,
  139577. NULL,
  139578. &_vq_auxt__44cn1_s_p2_0,
  139579. NULL,
  139580. 0
  139581. };
  139582. static long _vq_quantlist__44cn1_s_p3_0[] = {
  139583. 4,
  139584. 3,
  139585. 5,
  139586. 2,
  139587. 6,
  139588. 1,
  139589. 7,
  139590. 0,
  139591. 8,
  139592. };
  139593. static long _vq_lengthlist__44cn1_s_p3_0[] = {
  139594. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  139595. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  139596. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  139597. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  139598. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139599. 0,
  139600. };
  139601. static float _vq_quantthresh__44cn1_s_p3_0[] = {
  139602. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139603. };
  139604. static long _vq_quantmap__44cn1_s_p3_0[] = {
  139605. 7, 5, 3, 1, 0, 2, 4, 6,
  139606. 8,
  139607. };
  139608. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  139609. _vq_quantthresh__44cn1_s_p3_0,
  139610. _vq_quantmap__44cn1_s_p3_0,
  139611. 9,
  139612. 9
  139613. };
  139614. static static_codebook _44cn1_s_p3_0 = {
  139615. 2, 81,
  139616. _vq_lengthlist__44cn1_s_p3_0,
  139617. 1, -531628032, 1611661312, 4, 0,
  139618. _vq_quantlist__44cn1_s_p3_0,
  139619. NULL,
  139620. &_vq_auxt__44cn1_s_p3_0,
  139621. NULL,
  139622. 0
  139623. };
  139624. static long _vq_quantlist__44cn1_s_p4_0[] = {
  139625. 4,
  139626. 3,
  139627. 5,
  139628. 2,
  139629. 6,
  139630. 1,
  139631. 7,
  139632. 0,
  139633. 8,
  139634. };
  139635. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  139636. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  139637. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  139638. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  139639. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  139640. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  139641. 11,
  139642. };
  139643. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  139644. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139645. };
  139646. static long _vq_quantmap__44cn1_s_p4_0[] = {
  139647. 7, 5, 3, 1, 0, 2, 4, 6,
  139648. 8,
  139649. };
  139650. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  139651. _vq_quantthresh__44cn1_s_p4_0,
  139652. _vq_quantmap__44cn1_s_p4_0,
  139653. 9,
  139654. 9
  139655. };
  139656. static static_codebook _44cn1_s_p4_0 = {
  139657. 2, 81,
  139658. _vq_lengthlist__44cn1_s_p4_0,
  139659. 1, -531628032, 1611661312, 4, 0,
  139660. _vq_quantlist__44cn1_s_p4_0,
  139661. NULL,
  139662. &_vq_auxt__44cn1_s_p4_0,
  139663. NULL,
  139664. 0
  139665. };
  139666. static long _vq_quantlist__44cn1_s_p5_0[] = {
  139667. 8,
  139668. 7,
  139669. 9,
  139670. 6,
  139671. 10,
  139672. 5,
  139673. 11,
  139674. 4,
  139675. 12,
  139676. 3,
  139677. 13,
  139678. 2,
  139679. 14,
  139680. 1,
  139681. 15,
  139682. 0,
  139683. 16,
  139684. };
  139685. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  139686. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  139687. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  139688. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  139689. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  139690. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  139691. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  139692. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  139693. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  139694. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  139695. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  139696. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  139697. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  139698. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  139699. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  139700. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  139701. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  139702. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  139703. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  139704. 14,
  139705. };
  139706. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  139707. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139708. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139709. };
  139710. static long _vq_quantmap__44cn1_s_p5_0[] = {
  139711. 15, 13, 11, 9, 7, 5, 3, 1,
  139712. 0, 2, 4, 6, 8, 10, 12, 14,
  139713. 16,
  139714. };
  139715. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  139716. _vq_quantthresh__44cn1_s_p5_0,
  139717. _vq_quantmap__44cn1_s_p5_0,
  139718. 17,
  139719. 17
  139720. };
  139721. static static_codebook _44cn1_s_p5_0 = {
  139722. 2, 289,
  139723. _vq_lengthlist__44cn1_s_p5_0,
  139724. 1, -529530880, 1611661312, 5, 0,
  139725. _vq_quantlist__44cn1_s_p5_0,
  139726. NULL,
  139727. &_vq_auxt__44cn1_s_p5_0,
  139728. NULL,
  139729. 0
  139730. };
  139731. static long _vq_quantlist__44cn1_s_p6_0[] = {
  139732. 1,
  139733. 0,
  139734. 2,
  139735. };
  139736. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  139737. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  139738. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  139739. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  139740. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  139741. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  139742. 10,
  139743. };
  139744. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  139745. -5.5, 5.5,
  139746. };
  139747. static long _vq_quantmap__44cn1_s_p6_0[] = {
  139748. 1, 0, 2,
  139749. };
  139750. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  139751. _vq_quantthresh__44cn1_s_p6_0,
  139752. _vq_quantmap__44cn1_s_p6_0,
  139753. 3,
  139754. 3
  139755. };
  139756. static static_codebook _44cn1_s_p6_0 = {
  139757. 4, 81,
  139758. _vq_lengthlist__44cn1_s_p6_0,
  139759. 1, -529137664, 1618345984, 2, 0,
  139760. _vq_quantlist__44cn1_s_p6_0,
  139761. NULL,
  139762. &_vq_auxt__44cn1_s_p6_0,
  139763. NULL,
  139764. 0
  139765. };
  139766. static long _vq_quantlist__44cn1_s_p6_1[] = {
  139767. 5,
  139768. 4,
  139769. 6,
  139770. 3,
  139771. 7,
  139772. 2,
  139773. 8,
  139774. 1,
  139775. 9,
  139776. 0,
  139777. 10,
  139778. };
  139779. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  139780. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  139781. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  139782. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  139783. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  139784. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  139785. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  139786. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  139787. 10,10,10, 9, 9, 9, 9, 9, 9,
  139788. };
  139789. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  139790. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139791. 3.5, 4.5,
  139792. };
  139793. static long _vq_quantmap__44cn1_s_p6_1[] = {
  139794. 9, 7, 5, 3, 1, 0, 2, 4,
  139795. 6, 8, 10,
  139796. };
  139797. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  139798. _vq_quantthresh__44cn1_s_p6_1,
  139799. _vq_quantmap__44cn1_s_p6_1,
  139800. 11,
  139801. 11
  139802. };
  139803. static static_codebook _44cn1_s_p6_1 = {
  139804. 2, 121,
  139805. _vq_lengthlist__44cn1_s_p6_1,
  139806. 1, -531365888, 1611661312, 4, 0,
  139807. _vq_quantlist__44cn1_s_p6_1,
  139808. NULL,
  139809. &_vq_auxt__44cn1_s_p6_1,
  139810. NULL,
  139811. 0
  139812. };
  139813. static long _vq_quantlist__44cn1_s_p7_0[] = {
  139814. 6,
  139815. 5,
  139816. 7,
  139817. 4,
  139818. 8,
  139819. 3,
  139820. 9,
  139821. 2,
  139822. 10,
  139823. 1,
  139824. 11,
  139825. 0,
  139826. 12,
  139827. };
  139828. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  139829. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  139830. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  139831. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  139832. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  139833. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  139834. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  139835. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  139836. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  139837. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  139838. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  139839. 0,13,13,12,12,13,13,13,14,
  139840. };
  139841. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  139842. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  139843. 12.5, 17.5, 22.5, 27.5,
  139844. };
  139845. static long _vq_quantmap__44cn1_s_p7_0[] = {
  139846. 11, 9, 7, 5, 3, 1, 0, 2,
  139847. 4, 6, 8, 10, 12,
  139848. };
  139849. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  139850. _vq_quantthresh__44cn1_s_p7_0,
  139851. _vq_quantmap__44cn1_s_p7_0,
  139852. 13,
  139853. 13
  139854. };
  139855. static static_codebook _44cn1_s_p7_0 = {
  139856. 2, 169,
  139857. _vq_lengthlist__44cn1_s_p7_0,
  139858. 1, -526516224, 1616117760, 4, 0,
  139859. _vq_quantlist__44cn1_s_p7_0,
  139860. NULL,
  139861. &_vq_auxt__44cn1_s_p7_0,
  139862. NULL,
  139863. 0
  139864. };
  139865. static long _vq_quantlist__44cn1_s_p7_1[] = {
  139866. 2,
  139867. 1,
  139868. 3,
  139869. 0,
  139870. 4,
  139871. };
  139872. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  139873. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  139874. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  139875. };
  139876. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  139877. -1.5, -0.5, 0.5, 1.5,
  139878. };
  139879. static long _vq_quantmap__44cn1_s_p7_1[] = {
  139880. 3, 1, 0, 2, 4,
  139881. };
  139882. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  139883. _vq_quantthresh__44cn1_s_p7_1,
  139884. _vq_quantmap__44cn1_s_p7_1,
  139885. 5,
  139886. 5
  139887. };
  139888. static static_codebook _44cn1_s_p7_1 = {
  139889. 2, 25,
  139890. _vq_lengthlist__44cn1_s_p7_1,
  139891. 1, -533725184, 1611661312, 3, 0,
  139892. _vq_quantlist__44cn1_s_p7_1,
  139893. NULL,
  139894. &_vq_auxt__44cn1_s_p7_1,
  139895. NULL,
  139896. 0
  139897. };
  139898. static long _vq_quantlist__44cn1_s_p8_0[] = {
  139899. 2,
  139900. 1,
  139901. 3,
  139902. 0,
  139903. 4,
  139904. };
  139905. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  139906. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  139907. 11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,
  139908. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139909. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  139910. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139911. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139912. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139913. 11,11,11,11,11,11,11,11,11,11,11,11,11, 7,11,11,
  139914. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139915. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  139916. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  139917. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139918. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139919. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139920. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139921. 11,11,11,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  139922. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139923. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139924. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139925. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139926. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139927. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139928. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139929. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139930. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139931. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139932. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139933. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139934. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139935. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139936. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139937. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139938. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139939. 11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
  139940. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  139941. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  139942. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  139943. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  139944. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  139945. 12,
  139946. };
  139947. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  139948. -331.5, -110.5, 110.5, 331.5,
  139949. };
  139950. static long _vq_quantmap__44cn1_s_p8_0[] = {
  139951. 3, 1, 0, 2, 4,
  139952. };
  139953. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  139954. _vq_quantthresh__44cn1_s_p8_0,
  139955. _vq_quantmap__44cn1_s_p8_0,
  139956. 5,
  139957. 5
  139958. };
  139959. static static_codebook _44cn1_s_p8_0 = {
  139960. 4, 625,
  139961. _vq_lengthlist__44cn1_s_p8_0,
  139962. 1, -518283264, 1627103232, 3, 0,
  139963. _vq_quantlist__44cn1_s_p8_0,
  139964. NULL,
  139965. &_vq_auxt__44cn1_s_p8_0,
  139966. NULL,
  139967. 0
  139968. };
  139969. static long _vq_quantlist__44cn1_s_p8_1[] = {
  139970. 6,
  139971. 5,
  139972. 7,
  139973. 4,
  139974. 8,
  139975. 3,
  139976. 9,
  139977. 2,
  139978. 10,
  139979. 1,
  139980. 11,
  139981. 0,
  139982. 12,
  139983. };
  139984. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  139985. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  139986. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  139987. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  139988. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  139989. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  139990. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  139991. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  139992. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  139993. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  139994. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  139995. 15,12,12,11,11,14,12,13,14,
  139996. };
  139997. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  139998. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  139999. 42.5, 59.5, 76.5, 93.5,
  140000. };
  140001. static long _vq_quantmap__44cn1_s_p8_1[] = {
  140002. 11, 9, 7, 5, 3, 1, 0, 2,
  140003. 4, 6, 8, 10, 12,
  140004. };
  140005. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  140006. _vq_quantthresh__44cn1_s_p8_1,
  140007. _vq_quantmap__44cn1_s_p8_1,
  140008. 13,
  140009. 13
  140010. };
  140011. static static_codebook _44cn1_s_p8_1 = {
  140012. 2, 169,
  140013. _vq_lengthlist__44cn1_s_p8_1,
  140014. 1, -522616832, 1620115456, 4, 0,
  140015. _vq_quantlist__44cn1_s_p8_1,
  140016. NULL,
  140017. &_vq_auxt__44cn1_s_p8_1,
  140018. NULL,
  140019. 0
  140020. };
  140021. static long _vq_quantlist__44cn1_s_p8_2[] = {
  140022. 8,
  140023. 7,
  140024. 9,
  140025. 6,
  140026. 10,
  140027. 5,
  140028. 11,
  140029. 4,
  140030. 12,
  140031. 3,
  140032. 13,
  140033. 2,
  140034. 14,
  140035. 1,
  140036. 15,
  140037. 0,
  140038. 16,
  140039. };
  140040. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  140041. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  140042. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  140043. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  140044. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  140045. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  140046. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  140047. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  140048. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  140049. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  140050. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  140051. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  140052. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  140053. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  140054. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  140055. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  140056. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  140057. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  140058. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  140059. 9,
  140060. };
  140061. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  140062. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140063. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140064. };
  140065. static long _vq_quantmap__44cn1_s_p8_2[] = {
  140066. 15, 13, 11, 9, 7, 5, 3, 1,
  140067. 0, 2, 4, 6, 8, 10, 12, 14,
  140068. 16,
  140069. };
  140070. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  140071. _vq_quantthresh__44cn1_s_p8_2,
  140072. _vq_quantmap__44cn1_s_p8_2,
  140073. 17,
  140074. 17
  140075. };
  140076. static static_codebook _44cn1_s_p8_2 = {
  140077. 2, 289,
  140078. _vq_lengthlist__44cn1_s_p8_2,
  140079. 1, -529530880, 1611661312, 5, 0,
  140080. _vq_quantlist__44cn1_s_p8_2,
  140081. NULL,
  140082. &_vq_auxt__44cn1_s_p8_2,
  140083. NULL,
  140084. 0
  140085. };
  140086. static long _huff_lengthlist__44cn1_s_short[] = {
  140087. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  140088. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  140089. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  140090. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  140091. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  140092. 10,
  140093. };
  140094. static static_codebook _huff_book__44cn1_s_short = {
  140095. 2, 81,
  140096. _huff_lengthlist__44cn1_s_short,
  140097. 0, 0, 0, 0, 0,
  140098. NULL,
  140099. NULL,
  140100. NULL,
  140101. NULL,
  140102. 0
  140103. };
  140104. static long _huff_lengthlist__44cn1_sm_long[] = {
  140105. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  140106. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  140107. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  140108. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  140109. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  140110. 17,
  140111. };
  140112. static static_codebook _huff_book__44cn1_sm_long = {
  140113. 2, 81,
  140114. _huff_lengthlist__44cn1_sm_long,
  140115. 0, 0, 0, 0, 0,
  140116. NULL,
  140117. NULL,
  140118. NULL,
  140119. NULL,
  140120. 0
  140121. };
  140122. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  140123. 1,
  140124. 0,
  140125. 2,
  140126. };
  140127. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  140128. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  140129. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140133. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  140134. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140138. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  140139. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  140174. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  140175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  140179. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  140180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  140184. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  140185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140219. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  140220. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140224. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  140225. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  140226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140229. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  140230. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  140231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140437. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140442. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140447. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  140482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  140487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  140492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140528. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140533. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140538. 0,
  140539. };
  140540. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  140541. -0.5, 0.5,
  140542. };
  140543. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  140544. 1, 0, 2,
  140545. };
  140546. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  140547. _vq_quantthresh__44cn1_sm_p1_0,
  140548. _vq_quantmap__44cn1_sm_p1_0,
  140549. 3,
  140550. 3
  140551. };
  140552. static static_codebook _44cn1_sm_p1_0 = {
  140553. 8, 6561,
  140554. _vq_lengthlist__44cn1_sm_p1_0,
  140555. 1, -535822336, 1611661312, 2, 0,
  140556. _vq_quantlist__44cn1_sm_p1_0,
  140557. NULL,
  140558. &_vq_auxt__44cn1_sm_p1_0,
  140559. NULL,
  140560. 0
  140561. };
  140562. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  140563. 2,
  140564. 1,
  140565. 3,
  140566. 0,
  140567. 4,
  140568. };
  140569. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  140570. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  140572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140573. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  140575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140576. 0, 0, 0, 0, 7, 7, 7, 9, 9, 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,
  140610. };
  140611. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  140612. -1.5, -0.5, 0.5, 1.5,
  140613. };
  140614. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  140615. 3, 1, 0, 2, 4,
  140616. };
  140617. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  140618. _vq_quantthresh__44cn1_sm_p2_0,
  140619. _vq_quantmap__44cn1_sm_p2_0,
  140620. 5,
  140621. 5
  140622. };
  140623. static static_codebook _44cn1_sm_p2_0 = {
  140624. 4, 625,
  140625. _vq_lengthlist__44cn1_sm_p2_0,
  140626. 1, -533725184, 1611661312, 3, 0,
  140627. _vq_quantlist__44cn1_sm_p2_0,
  140628. NULL,
  140629. &_vq_auxt__44cn1_sm_p2_0,
  140630. NULL,
  140631. 0
  140632. };
  140633. static long _vq_quantlist__44cn1_sm_p3_0[] = {
  140634. 4,
  140635. 3,
  140636. 5,
  140637. 2,
  140638. 6,
  140639. 1,
  140640. 7,
  140641. 0,
  140642. 8,
  140643. };
  140644. static long _vq_lengthlist__44cn1_sm_p3_0[] = {
  140645. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  140646. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  140647. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  140648. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  140649. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140650. 0,
  140651. };
  140652. static float _vq_quantthresh__44cn1_sm_p3_0[] = {
  140653. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140654. };
  140655. static long _vq_quantmap__44cn1_sm_p3_0[] = {
  140656. 7, 5, 3, 1, 0, 2, 4, 6,
  140657. 8,
  140658. };
  140659. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  140660. _vq_quantthresh__44cn1_sm_p3_0,
  140661. _vq_quantmap__44cn1_sm_p3_0,
  140662. 9,
  140663. 9
  140664. };
  140665. static static_codebook _44cn1_sm_p3_0 = {
  140666. 2, 81,
  140667. _vq_lengthlist__44cn1_sm_p3_0,
  140668. 1, -531628032, 1611661312, 4, 0,
  140669. _vq_quantlist__44cn1_sm_p3_0,
  140670. NULL,
  140671. &_vq_auxt__44cn1_sm_p3_0,
  140672. NULL,
  140673. 0
  140674. };
  140675. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  140676. 4,
  140677. 3,
  140678. 5,
  140679. 2,
  140680. 6,
  140681. 1,
  140682. 7,
  140683. 0,
  140684. 8,
  140685. };
  140686. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  140687. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  140688. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  140689. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  140690. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  140691. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  140692. 11,
  140693. };
  140694. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  140695. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140696. };
  140697. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  140698. 7, 5, 3, 1, 0, 2, 4, 6,
  140699. 8,
  140700. };
  140701. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  140702. _vq_quantthresh__44cn1_sm_p4_0,
  140703. _vq_quantmap__44cn1_sm_p4_0,
  140704. 9,
  140705. 9
  140706. };
  140707. static static_codebook _44cn1_sm_p4_0 = {
  140708. 2, 81,
  140709. _vq_lengthlist__44cn1_sm_p4_0,
  140710. 1, -531628032, 1611661312, 4, 0,
  140711. _vq_quantlist__44cn1_sm_p4_0,
  140712. NULL,
  140713. &_vq_auxt__44cn1_sm_p4_0,
  140714. NULL,
  140715. 0
  140716. };
  140717. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  140718. 8,
  140719. 7,
  140720. 9,
  140721. 6,
  140722. 10,
  140723. 5,
  140724. 11,
  140725. 4,
  140726. 12,
  140727. 3,
  140728. 13,
  140729. 2,
  140730. 14,
  140731. 1,
  140732. 15,
  140733. 0,
  140734. 16,
  140735. };
  140736. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  140737. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  140738. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  140739. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  140740. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  140741. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  140742. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  140743. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  140744. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  140745. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  140746. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  140747. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  140748. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  140749. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  140750. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  140751. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  140752. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  140753. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  140754. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  140755. 14,
  140756. };
  140757. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  140758. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140759. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140760. };
  140761. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  140762. 15, 13, 11, 9, 7, 5, 3, 1,
  140763. 0, 2, 4, 6, 8, 10, 12, 14,
  140764. 16,
  140765. };
  140766. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  140767. _vq_quantthresh__44cn1_sm_p5_0,
  140768. _vq_quantmap__44cn1_sm_p5_0,
  140769. 17,
  140770. 17
  140771. };
  140772. static static_codebook _44cn1_sm_p5_0 = {
  140773. 2, 289,
  140774. _vq_lengthlist__44cn1_sm_p5_0,
  140775. 1, -529530880, 1611661312, 5, 0,
  140776. _vq_quantlist__44cn1_sm_p5_0,
  140777. NULL,
  140778. &_vq_auxt__44cn1_sm_p5_0,
  140779. NULL,
  140780. 0
  140781. };
  140782. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  140783. 1,
  140784. 0,
  140785. 2,
  140786. };
  140787. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  140788. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  140789. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  140790. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  140791. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  140792. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  140793. 10,
  140794. };
  140795. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  140796. -5.5, 5.5,
  140797. };
  140798. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  140799. 1, 0, 2,
  140800. };
  140801. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  140802. _vq_quantthresh__44cn1_sm_p6_0,
  140803. _vq_quantmap__44cn1_sm_p6_0,
  140804. 3,
  140805. 3
  140806. };
  140807. static static_codebook _44cn1_sm_p6_0 = {
  140808. 4, 81,
  140809. _vq_lengthlist__44cn1_sm_p6_0,
  140810. 1, -529137664, 1618345984, 2, 0,
  140811. _vq_quantlist__44cn1_sm_p6_0,
  140812. NULL,
  140813. &_vq_auxt__44cn1_sm_p6_0,
  140814. NULL,
  140815. 0
  140816. };
  140817. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  140818. 5,
  140819. 4,
  140820. 6,
  140821. 3,
  140822. 7,
  140823. 2,
  140824. 8,
  140825. 1,
  140826. 9,
  140827. 0,
  140828. 10,
  140829. };
  140830. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  140831. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  140832. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  140833. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  140834. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  140835. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  140836. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  140837. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  140838. 10,10,10, 8, 9, 8, 8, 9, 8,
  140839. };
  140840. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  140841. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140842. 3.5, 4.5,
  140843. };
  140844. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  140845. 9, 7, 5, 3, 1, 0, 2, 4,
  140846. 6, 8, 10,
  140847. };
  140848. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  140849. _vq_quantthresh__44cn1_sm_p6_1,
  140850. _vq_quantmap__44cn1_sm_p6_1,
  140851. 11,
  140852. 11
  140853. };
  140854. static static_codebook _44cn1_sm_p6_1 = {
  140855. 2, 121,
  140856. _vq_lengthlist__44cn1_sm_p6_1,
  140857. 1, -531365888, 1611661312, 4, 0,
  140858. _vq_quantlist__44cn1_sm_p6_1,
  140859. NULL,
  140860. &_vq_auxt__44cn1_sm_p6_1,
  140861. NULL,
  140862. 0
  140863. };
  140864. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  140865. 6,
  140866. 5,
  140867. 7,
  140868. 4,
  140869. 8,
  140870. 3,
  140871. 9,
  140872. 2,
  140873. 10,
  140874. 1,
  140875. 11,
  140876. 0,
  140877. 12,
  140878. };
  140879. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  140880. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  140881. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  140882. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  140883. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  140884. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  140885. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  140886. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  140887. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  140888. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  140889. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  140890. 0,13,12,12,12,13,13,13,14,
  140891. };
  140892. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  140893. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140894. 12.5, 17.5, 22.5, 27.5,
  140895. };
  140896. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  140897. 11, 9, 7, 5, 3, 1, 0, 2,
  140898. 4, 6, 8, 10, 12,
  140899. };
  140900. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  140901. _vq_quantthresh__44cn1_sm_p7_0,
  140902. _vq_quantmap__44cn1_sm_p7_0,
  140903. 13,
  140904. 13
  140905. };
  140906. static static_codebook _44cn1_sm_p7_0 = {
  140907. 2, 169,
  140908. _vq_lengthlist__44cn1_sm_p7_0,
  140909. 1, -526516224, 1616117760, 4, 0,
  140910. _vq_quantlist__44cn1_sm_p7_0,
  140911. NULL,
  140912. &_vq_auxt__44cn1_sm_p7_0,
  140913. NULL,
  140914. 0
  140915. };
  140916. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  140917. 2,
  140918. 1,
  140919. 3,
  140920. 0,
  140921. 4,
  140922. };
  140923. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  140924. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  140925. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  140926. };
  140927. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  140928. -1.5, -0.5, 0.5, 1.5,
  140929. };
  140930. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  140931. 3, 1, 0, 2, 4,
  140932. };
  140933. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  140934. _vq_quantthresh__44cn1_sm_p7_1,
  140935. _vq_quantmap__44cn1_sm_p7_1,
  140936. 5,
  140937. 5
  140938. };
  140939. static static_codebook _44cn1_sm_p7_1 = {
  140940. 2, 25,
  140941. _vq_lengthlist__44cn1_sm_p7_1,
  140942. 1, -533725184, 1611661312, 3, 0,
  140943. _vq_quantlist__44cn1_sm_p7_1,
  140944. NULL,
  140945. &_vq_auxt__44cn1_sm_p7_1,
  140946. NULL,
  140947. 0
  140948. };
  140949. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  140950. 4,
  140951. 3,
  140952. 5,
  140953. 2,
  140954. 6,
  140955. 1,
  140956. 7,
  140957. 0,
  140958. 8,
  140959. };
  140960. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  140961. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  140962. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  140963. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  140964. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  140965. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  140966. 14,
  140967. };
  140968. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  140969. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  140970. };
  140971. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  140972. 7, 5, 3, 1, 0, 2, 4, 6,
  140973. 8,
  140974. };
  140975. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  140976. _vq_quantthresh__44cn1_sm_p8_0,
  140977. _vq_quantmap__44cn1_sm_p8_0,
  140978. 9,
  140979. 9
  140980. };
  140981. static static_codebook _44cn1_sm_p8_0 = {
  140982. 2, 81,
  140983. _vq_lengthlist__44cn1_sm_p8_0,
  140984. 1, -516186112, 1627103232, 4, 0,
  140985. _vq_quantlist__44cn1_sm_p8_0,
  140986. NULL,
  140987. &_vq_auxt__44cn1_sm_p8_0,
  140988. NULL,
  140989. 0
  140990. };
  140991. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  140992. 6,
  140993. 5,
  140994. 7,
  140995. 4,
  140996. 8,
  140997. 3,
  140998. 9,
  140999. 2,
  141000. 10,
  141001. 1,
  141002. 11,
  141003. 0,
  141004. 12,
  141005. };
  141006. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  141007. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  141008. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  141009. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  141010. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  141011. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  141012. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  141013. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  141014. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  141015. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  141016. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  141017. 17,12,12,11,10,13,11,13,13,
  141018. };
  141019. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  141020. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  141021. 42.5, 59.5, 76.5, 93.5,
  141022. };
  141023. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  141024. 11, 9, 7, 5, 3, 1, 0, 2,
  141025. 4, 6, 8, 10, 12,
  141026. };
  141027. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  141028. _vq_quantthresh__44cn1_sm_p8_1,
  141029. _vq_quantmap__44cn1_sm_p8_1,
  141030. 13,
  141031. 13
  141032. };
  141033. static static_codebook _44cn1_sm_p8_1 = {
  141034. 2, 169,
  141035. _vq_lengthlist__44cn1_sm_p8_1,
  141036. 1, -522616832, 1620115456, 4, 0,
  141037. _vq_quantlist__44cn1_sm_p8_1,
  141038. NULL,
  141039. &_vq_auxt__44cn1_sm_p8_1,
  141040. NULL,
  141041. 0
  141042. };
  141043. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  141044. 8,
  141045. 7,
  141046. 9,
  141047. 6,
  141048. 10,
  141049. 5,
  141050. 11,
  141051. 4,
  141052. 12,
  141053. 3,
  141054. 13,
  141055. 2,
  141056. 14,
  141057. 1,
  141058. 15,
  141059. 0,
  141060. 16,
  141061. };
  141062. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  141063. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  141064. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  141065. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  141066. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  141067. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  141068. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  141069. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  141070. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  141071. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  141072. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  141073. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  141074. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  141075. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  141076. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  141077. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  141078. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  141079. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  141080. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  141081. 9,
  141082. };
  141083. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  141084. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141085. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141086. };
  141087. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  141088. 15, 13, 11, 9, 7, 5, 3, 1,
  141089. 0, 2, 4, 6, 8, 10, 12, 14,
  141090. 16,
  141091. };
  141092. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  141093. _vq_quantthresh__44cn1_sm_p8_2,
  141094. _vq_quantmap__44cn1_sm_p8_2,
  141095. 17,
  141096. 17
  141097. };
  141098. static static_codebook _44cn1_sm_p8_2 = {
  141099. 2, 289,
  141100. _vq_lengthlist__44cn1_sm_p8_2,
  141101. 1, -529530880, 1611661312, 5, 0,
  141102. _vq_quantlist__44cn1_sm_p8_2,
  141103. NULL,
  141104. &_vq_auxt__44cn1_sm_p8_2,
  141105. NULL,
  141106. 0
  141107. };
  141108. static long _huff_lengthlist__44cn1_sm_short[] = {
  141109. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  141110. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  141111. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  141112. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  141113. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  141114. 9,
  141115. };
  141116. static static_codebook _huff_book__44cn1_sm_short = {
  141117. 2, 81,
  141118. _huff_lengthlist__44cn1_sm_short,
  141119. 0, 0, 0, 0, 0,
  141120. NULL,
  141121. NULL,
  141122. NULL,
  141123. NULL,
  141124. 0
  141125. };
  141126. /*** End of inlined file: res_books_stereo.h ***/
  141127. /***** residue backends *********************************************/
  141128. static vorbis_info_residue0 _residue_44_low={
  141129. 0,-1, -1, 9,-1,
  141130. /* 0 1 2 3 4 5 6 7 */
  141131. {0},
  141132. {-1},
  141133. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  141134. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  141135. };
  141136. static vorbis_info_residue0 _residue_44_mid={
  141137. 0,-1, -1, 10,-1,
  141138. /* 0 1 2 3 4 5 6 7 8 */
  141139. {0},
  141140. {-1},
  141141. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  141142. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  141143. };
  141144. static vorbis_info_residue0 _residue_44_high={
  141145. 0,-1, -1, 10,-1,
  141146. /* 0 1 2 3 4 5 6 7 8 */
  141147. {0},
  141148. {-1},
  141149. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  141150. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  141151. };
  141152. static static_bookblock _resbook_44s_n1={
  141153. {
  141154. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  141155. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  141156. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  141157. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  141158. }
  141159. };
  141160. static static_bookblock _resbook_44sm_n1={
  141161. {
  141162. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  141163. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  141164. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  141165. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  141166. }
  141167. };
  141168. static static_bookblock _resbook_44s_0={
  141169. {
  141170. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  141171. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  141172. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  141173. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  141174. }
  141175. };
  141176. static static_bookblock _resbook_44sm_0={
  141177. {
  141178. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  141179. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  141180. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  141181. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  141182. }
  141183. };
  141184. static static_bookblock _resbook_44s_1={
  141185. {
  141186. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  141187. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  141188. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  141189. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  141190. }
  141191. };
  141192. static static_bookblock _resbook_44sm_1={
  141193. {
  141194. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  141195. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  141196. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  141197. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  141198. }
  141199. };
  141200. static static_bookblock _resbook_44s_2={
  141201. {
  141202. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  141203. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  141204. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  141205. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  141206. }
  141207. };
  141208. static static_bookblock _resbook_44s_3={
  141209. {
  141210. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  141211. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  141212. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  141213. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  141214. }
  141215. };
  141216. static static_bookblock _resbook_44s_4={
  141217. {
  141218. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  141219. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  141220. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  141221. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  141222. }
  141223. };
  141224. static static_bookblock _resbook_44s_5={
  141225. {
  141226. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  141227. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  141228. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  141229. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  141230. }
  141231. };
  141232. static static_bookblock _resbook_44s_6={
  141233. {
  141234. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  141235. {0,0,&_44c6_s_p4_0},
  141236. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  141237. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  141238. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  141239. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  141240. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  141241. }
  141242. };
  141243. static static_bookblock _resbook_44s_7={
  141244. {
  141245. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  141246. {0,0,&_44c7_s_p4_0},
  141247. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  141248. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  141249. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  141250. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  141251. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  141252. }
  141253. };
  141254. static static_bookblock _resbook_44s_8={
  141255. {
  141256. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  141257. {0,0,&_44c8_s_p4_0},
  141258. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  141259. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  141260. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  141261. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  141262. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  141263. }
  141264. };
  141265. static static_bookblock _resbook_44s_9={
  141266. {
  141267. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  141268. {0,0,&_44c9_s_p4_0},
  141269. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  141270. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  141271. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  141272. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  141273. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  141274. }
  141275. };
  141276. static vorbis_residue_template _res_44s_n1[]={
  141277. {2,0, &_residue_44_low,
  141278. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  141279. &_resbook_44s_n1,&_resbook_44sm_n1},
  141280. {2,0, &_residue_44_low,
  141281. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  141282. &_resbook_44s_n1,&_resbook_44sm_n1}
  141283. };
  141284. static vorbis_residue_template _res_44s_0[]={
  141285. {2,0, &_residue_44_low,
  141286. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  141287. &_resbook_44s_0,&_resbook_44sm_0},
  141288. {2,0, &_residue_44_low,
  141289. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  141290. &_resbook_44s_0,&_resbook_44sm_0}
  141291. };
  141292. static vorbis_residue_template _res_44s_1[]={
  141293. {2,0, &_residue_44_low,
  141294. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  141295. &_resbook_44s_1,&_resbook_44sm_1},
  141296. {2,0, &_residue_44_low,
  141297. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  141298. &_resbook_44s_1,&_resbook_44sm_1}
  141299. };
  141300. static vorbis_residue_template _res_44s_2[]={
  141301. {2,0, &_residue_44_mid,
  141302. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  141303. &_resbook_44s_2,&_resbook_44s_2},
  141304. {2,0, &_residue_44_mid,
  141305. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  141306. &_resbook_44s_2,&_resbook_44s_2}
  141307. };
  141308. static vorbis_residue_template _res_44s_3[]={
  141309. {2,0, &_residue_44_mid,
  141310. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  141311. &_resbook_44s_3,&_resbook_44s_3},
  141312. {2,0, &_residue_44_mid,
  141313. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  141314. &_resbook_44s_3,&_resbook_44s_3}
  141315. };
  141316. static vorbis_residue_template _res_44s_4[]={
  141317. {2,0, &_residue_44_mid,
  141318. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  141319. &_resbook_44s_4,&_resbook_44s_4},
  141320. {2,0, &_residue_44_mid,
  141321. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  141322. &_resbook_44s_4,&_resbook_44s_4}
  141323. };
  141324. static vorbis_residue_template _res_44s_5[]={
  141325. {2,0, &_residue_44_mid,
  141326. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  141327. &_resbook_44s_5,&_resbook_44s_5},
  141328. {2,0, &_residue_44_mid,
  141329. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  141330. &_resbook_44s_5,&_resbook_44s_5}
  141331. };
  141332. static vorbis_residue_template _res_44s_6[]={
  141333. {2,0, &_residue_44_high,
  141334. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  141335. &_resbook_44s_6,&_resbook_44s_6},
  141336. {2,0, &_residue_44_high,
  141337. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  141338. &_resbook_44s_6,&_resbook_44s_6}
  141339. };
  141340. static vorbis_residue_template _res_44s_7[]={
  141341. {2,0, &_residue_44_high,
  141342. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  141343. &_resbook_44s_7,&_resbook_44s_7},
  141344. {2,0, &_residue_44_high,
  141345. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  141346. &_resbook_44s_7,&_resbook_44s_7}
  141347. };
  141348. static vorbis_residue_template _res_44s_8[]={
  141349. {2,0, &_residue_44_high,
  141350. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  141351. &_resbook_44s_8,&_resbook_44s_8},
  141352. {2,0, &_residue_44_high,
  141353. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  141354. &_resbook_44s_8,&_resbook_44s_8}
  141355. };
  141356. static vorbis_residue_template _res_44s_9[]={
  141357. {2,0, &_residue_44_high,
  141358. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  141359. &_resbook_44s_9,&_resbook_44s_9},
  141360. {2,0, &_residue_44_high,
  141361. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  141362. &_resbook_44s_9,&_resbook_44s_9}
  141363. };
  141364. static vorbis_mapping_template _mapres_template_44_stereo[]={
  141365. { _map_nominal, _res_44s_n1 }, /* -1 */
  141366. { _map_nominal, _res_44s_0 }, /* 0 */
  141367. { _map_nominal, _res_44s_1 }, /* 1 */
  141368. { _map_nominal, _res_44s_2 }, /* 2 */
  141369. { _map_nominal, _res_44s_3 }, /* 3 */
  141370. { _map_nominal, _res_44s_4 }, /* 4 */
  141371. { _map_nominal, _res_44s_5 }, /* 5 */
  141372. { _map_nominal, _res_44s_6 }, /* 6 */
  141373. { _map_nominal, _res_44s_7 }, /* 7 */
  141374. { _map_nominal, _res_44s_8 }, /* 8 */
  141375. { _map_nominal, _res_44s_9 }, /* 9 */
  141376. };
  141377. /*** End of inlined file: residue_44.h ***/
  141378. /*** Start of inlined file: psych_44.h ***/
  141379. /* preecho trigger settings *****************************************/
  141380. static vorbis_info_psy_global _psy_global_44[5]={
  141381. {8, /* lines per eighth octave */
  141382. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  141383. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  141384. -6.f,
  141385. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141386. },
  141387. {8, /* lines per eighth octave */
  141388. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  141389. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  141390. -6.f,
  141391. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141392. },
  141393. {8, /* lines per eighth octave */
  141394. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  141395. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  141396. -6.f,
  141397. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141398. },
  141399. {8, /* lines per eighth octave */
  141400. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  141401. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  141402. -6.f,
  141403. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141404. },
  141405. {8, /* lines per eighth octave */
  141406. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  141407. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  141408. -6.f,
  141409. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141410. },
  141411. };
  141412. /* noise compander lookups * low, mid, high quality ****************/
  141413. static compandblock _psy_compand_44[6]={
  141414. /* sub-mode Z short */
  141415. {{
  141416. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  141417. 8, 9,10,11,12,13,14, 15, /* 15dB */
  141418. 16,17,18,19,20,21,22, 23, /* 23dB */
  141419. 24,25,26,27,28,29,30, 31, /* 31dB */
  141420. 32,33,34,35,36,37,38, 39, /* 39dB */
  141421. }},
  141422. /* mode_Z nominal short */
  141423. {{
  141424. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  141425. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  141426. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  141427. 15,16,17,17,17,18,18, 19, /* 31dB */
  141428. 19,19,20,21,22,23,24, 25, /* 39dB */
  141429. }},
  141430. /* mode A short */
  141431. {{
  141432. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  141433. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  141434. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  141435. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  141436. 11,12,13,14,15,16,17, 18, /* 39dB */
  141437. }},
  141438. /* sub-mode Z long */
  141439. {{
  141440. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  141441. 8, 9,10,11,12,13,14, 15, /* 15dB */
  141442. 16,17,18,19,20,21,22, 23, /* 23dB */
  141443. 24,25,26,27,28,29,30, 31, /* 31dB */
  141444. 32,33,34,35,36,37,38, 39, /* 39dB */
  141445. }},
  141446. /* mode_Z nominal long */
  141447. {{
  141448. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  141449. 8, 9,10,11,12,12,13, 13, /* 15dB */
  141450. 13,14,14,14,15,15,15, 15, /* 23dB */
  141451. 16,16,17,17,17,18,18, 19, /* 31dB */
  141452. 19,19,20,21,22,23,24, 25, /* 39dB */
  141453. }},
  141454. /* mode A long */
  141455. {{
  141456. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  141457. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  141458. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  141459. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  141460. 11,12,13,14,15,16,17, 18, /* 39dB */
  141461. }}
  141462. };
  141463. /* tonal masking curve level adjustments *************************/
  141464. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  141465. /* 63 125 250 500 1 2 4 8 16 */
  141466. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  141467. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  141468. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  141469. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  141470. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  141471. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  141472. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  141473. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  141474. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  141475. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  141476. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  141477. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  141478. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  141479. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  141480. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  141481. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  141482. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  141483. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  141484. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  141485. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  141486. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  141487. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  141488. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  141489. };
  141490. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  141491. /* 63 125 250 500 1 2 4 8 16 */
  141492. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  141493. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  141494. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  141495. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  141496. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  141497. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  141498. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  141499. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  141500. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  141501. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  141502. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  141503. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  141504. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  141505. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  141506. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  141507. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  141508. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  141509. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  141510. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  141511. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  141512. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  141513. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  141514. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  141515. };
  141516. /* noise bias (transition block) */
  141517. static noise3 _psy_noisebias_trans[12]={
  141518. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  141519. /* -1 */
  141520. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  141521. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  141522. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  141523. /* 0
  141524. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  141525. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  141526. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  141527. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  141528. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  141529. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  141530. /* 1
  141531. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  141532. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  141533. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  141534. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  141535. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  141536. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  141537. /* 2
  141538. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  141539. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  141540. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  141541. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  141542. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  141543. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  141544. /* 3
  141545. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  141546. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  141547. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  141548. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  141549. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  141550. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  141551. /* 4
  141552. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141553. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  141554. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  141555. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141556. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  141557. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  141558. /* 5
  141559. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141560. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  141561. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  141562. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141563. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  141564. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  141565. /* 6
  141566. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141567. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  141568. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  141569. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141570. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  141571. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  141572. /* 7
  141573. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141574. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  141575. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  141576. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  141577. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  141578. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  141579. /* 8
  141580. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  141581. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  141582. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  141583. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  141584. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  141585. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  141586. /* 9
  141587. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  141588. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  141589. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  141590. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  141591. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  141592. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  141593. /* 10 */
  141594. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  141595. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  141596. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  141597. };
  141598. /* noise bias (long block) */
  141599. static noise3 _psy_noisebias_long[12]={
  141600. /*63 125 250 500 1k 2k 4k 8k 16k*/
  141601. /* -1 */
  141602. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  141603. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  141604. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  141605. /* 0 */
  141606. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  141607. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  141608. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  141609. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  141610. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  141611. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  141612. /* 1 */
  141613. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  141614. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  141615. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  141616. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  141617. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  141618. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  141619. /* 2 */
  141620. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  141621. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  141622. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  141623. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  141624. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  141625. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  141626. /* 3 */
  141627. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  141628. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  141629. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  141630. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  141631. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  141632. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  141633. /* 4 */
  141634. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141635. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  141636. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  141637. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141638. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  141639. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  141640. /* 5 */
  141641. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141642. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  141643. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  141644. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141645. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  141646. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  141647. /* 6 */
  141648. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141649. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  141650. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  141651. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141652. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  141653. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  141654. /* 7 */
  141655. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  141656. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  141657. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  141658. /* 8 */
  141659. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  141660. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  141661. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  141662. /* 9 */
  141663. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  141664. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  141665. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  141666. /* 10 */
  141667. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  141668. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  141669. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  141670. };
  141671. /* noise bias (impulse block) */
  141672. static noise3 _psy_noisebias_impulse[12]={
  141673. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  141674. /* -1 */
  141675. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  141676. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  141677. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  141678. /* 0 */
  141679. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  141680. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  141681. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  141682. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  141683. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  141684. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  141685. /* 1 */
  141686. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  141687. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  141688. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  141689. /* 2 */
  141690. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  141691. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  141692. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  141693. /* 3 */
  141694. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  141695. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  141696. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  141697. /* 4 */
  141698. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  141699. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  141700. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  141701. /* 5 */
  141702. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  141703. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  141704. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  141705. /* 6
  141706. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  141707. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  141708. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  141709. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  141710. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  141711. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  141712. /* 7 */
  141713. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  141714. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  141715. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  141716. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  141717. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  141718. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  141719. /* 8 */
  141720. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  141721. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  141722. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  141723. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  141724. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  141725. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  141726. /* 9 */
  141727. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  141728. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  141729. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  141730. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  141731. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  141732. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  141733. /* 10 */
  141734. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  141735. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  141736. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  141737. };
  141738. /* noise bias (padding block) */
  141739. static noise3 _psy_noisebias_padding[12]={
  141740. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  141741. /* -1 */
  141742. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  141743. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  141744. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  141745. /* 0 */
  141746. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  141747. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  141748. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  141749. /* 1 */
  141750. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  141751. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  141752. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  141753. /* 2 */
  141754. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  141755. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  141756. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  141757. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  141758. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  141759. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  141760. /* 3 */
  141761. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  141762. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  141763. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  141764. /* 4 */
  141765. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  141766. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  141767. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  141768. /* 5 */
  141769. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  141770. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  141771. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  141772. /* 6 */
  141773. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  141774. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  141775. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  141776. /* 7 */
  141777. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  141778. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  141779. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  141780. /* 8 */
  141781. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  141782. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  141783. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  141784. /* 9 */
  141785. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  141786. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  141787. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  141788. /* 10 */
  141789. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  141790. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  141791. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  141792. };
  141793. static noiseguard _psy_noiseguards_44[4]={
  141794. {3,3,15},
  141795. {3,3,15},
  141796. {10,10,100},
  141797. {10,10,100},
  141798. };
  141799. static int _psy_tone_suppress[12]={
  141800. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  141801. };
  141802. static int _psy_tone_0dB[12]={
  141803. 90,90,95,95,95,95,105,105,105,105,105,105,
  141804. };
  141805. static int _psy_noise_suppress[12]={
  141806. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  141807. };
  141808. static vorbis_info_psy _psy_info_template={
  141809. /* blockflag */
  141810. -1,
  141811. /* ath_adjatt, ath_maxatt */
  141812. -140.,-140.,
  141813. /* tonemask att boost/decay,suppr,curves */
  141814. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  141815. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  141816. 1, -0.f, .5f, .5f, 0,0,0,
  141817. /* noiseoffset*3, noisecompand, max_curve_dB */
  141818. {{-1},{-1},{-1}},{-1},105.f,
  141819. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  141820. 0,0,-1,-1,0.,
  141821. };
  141822. /* ath ****************/
  141823. static int _psy_ath_floater[12]={
  141824. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  141825. };
  141826. static int _psy_ath_abs[12]={
  141827. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  141828. };
  141829. /* stereo setup. These don't map directly to quality level, there's
  141830. an additional indirection as several of the below may be used in a
  141831. single bitmanaged stream
  141832. ****************/
  141833. /* various stereo possibilities */
  141834. /* stereo mode by base quality level */
  141835. static adj_stereo _psy_stereo_modes_44[12]={
  141836. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  141837. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  141838. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  141839. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  141840. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  141841. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  141842. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  141843. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  141844. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  141845. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  141846. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  141847. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  141848. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  141849. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  141850. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  141851. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  141852. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  141853. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  141854. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  141855. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  141856. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  141857. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  141858. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  141859. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  141860. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  141861. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  141862. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  141863. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  141864. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  141865. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  141866. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  141867. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  141868. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  141869. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  141870. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141871. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  141872. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  141873. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  141874. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  141875. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141876. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  141877. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  141878. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  141879. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141880. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  141881. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  141882. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  141883. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  141884. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141885. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141886. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  141887. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  141888. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141889. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141890. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  141891. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  141892. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  141893. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141894. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141895. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  141896. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  141897. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141898. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141899. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  141900. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  141901. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  141902. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141903. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141904. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  141905. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  141906. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141907. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141908. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  141909. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  141910. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  141911. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141912. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141913. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  141914. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  141915. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  141916. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141917. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  141918. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  141919. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  141920. };
  141921. /* tone master attenuation by base quality mode and bitrate tweak */
  141922. static att3 _psy_tone_masteratt_44[12]={
  141923. {{ 35, 21, 9}, 0, 0}, /* -1 */
  141924. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  141925. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  141926. {{ 25, 12, 2}, 0, 0}, /* 1 */
  141927. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  141928. {{ 20, 9, -3}, 0, 0}, /* 2 */
  141929. {{ 20, 9, -4}, 0, 0}, /* 3 */
  141930. {{ 20, 9, -4}, 0, 0}, /* 4 */
  141931. {{ 20, 6, -6}, 0, 0}, /* 5 */
  141932. {{ 20, 3, -10}, 0, 0}, /* 6 */
  141933. {{ 18, 1, -14}, 0, 0}, /* 7 */
  141934. {{ 18, 0, -16}, 0, 0}, /* 8 */
  141935. {{ 18, -2, -16}, 0, 0}, /* 9 */
  141936. {{ 12, -2, -20}, 0, 0}, /* 10 */
  141937. };
  141938. /* lowpass by mode **************/
  141939. static double _psy_lowpass_44[12]={
  141940. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  141941. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  141942. };
  141943. /* noise normalization **********/
  141944. static int _noise_start_short_44[11]={
  141945. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  141946. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  141947. };
  141948. static int _noise_start_long_44[11]={
  141949. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  141950. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  141951. };
  141952. static int _noise_part_short_44[11]={
  141953. 8,8,8,8,8,8,8,8,8,8,8
  141954. };
  141955. static int _noise_part_long_44[11]={
  141956. 32,32,32,32,32,32,32,32,32,32,32
  141957. };
  141958. static double _noise_thresh_44[11]={
  141959. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  141960. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  141961. };
  141962. static double _noise_thresh_5only[2]={
  141963. .5,.5,
  141964. };
  141965. /*** End of inlined file: psych_44.h ***/
  141966. static double rate_mapping_44_stereo[12]={
  141967. 22500.,32000.,40000.,48000.,56000.,64000.,
  141968. 80000.,96000.,112000.,128000.,160000.,250001.
  141969. };
  141970. static double quality_mapping_44[12]={
  141971. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  141972. };
  141973. static int blocksize_short_44[11]={
  141974. 512,256,256,256,256,256,256,256,256,256,256
  141975. };
  141976. static int blocksize_long_44[11]={
  141977. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  141978. };
  141979. static double _psy_compand_short_mapping[12]={
  141980. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  141981. };
  141982. static double _psy_compand_long_mapping[12]={
  141983. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  141984. };
  141985. static double _global_mapping_44[12]={
  141986. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  141987. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  141988. };
  141989. static int _floor_short_mapping_44[11]={
  141990. 1,0,0,2,2,4,5,5,5,5,5
  141991. };
  141992. static int _floor_long_mapping_44[11]={
  141993. 8,7,7,7,7,7,7,7,7,7,7
  141994. };
  141995. ve_setup_data_template ve_setup_44_stereo={
  141996. 11,
  141997. rate_mapping_44_stereo,
  141998. quality_mapping_44,
  141999. 2,
  142000. 40000,
  142001. 50000,
  142002. blocksize_short_44,
  142003. blocksize_long_44,
  142004. _psy_tone_masteratt_44,
  142005. _psy_tone_0dB,
  142006. _psy_tone_suppress,
  142007. _vp_tonemask_adj_otherblock,
  142008. _vp_tonemask_adj_longblock,
  142009. _vp_tonemask_adj_otherblock,
  142010. _psy_noiseguards_44,
  142011. _psy_noisebias_impulse,
  142012. _psy_noisebias_padding,
  142013. _psy_noisebias_trans,
  142014. _psy_noisebias_long,
  142015. _psy_noise_suppress,
  142016. _psy_compand_44,
  142017. _psy_compand_short_mapping,
  142018. _psy_compand_long_mapping,
  142019. {_noise_start_short_44,_noise_start_long_44},
  142020. {_noise_part_short_44,_noise_part_long_44},
  142021. _noise_thresh_44,
  142022. _psy_ath_floater,
  142023. _psy_ath_abs,
  142024. _psy_lowpass_44,
  142025. _psy_global_44,
  142026. _global_mapping_44,
  142027. _psy_stereo_modes_44,
  142028. _floor_books,
  142029. _floor,
  142030. _floor_short_mapping_44,
  142031. _floor_long_mapping_44,
  142032. _mapres_template_44_stereo
  142033. };
  142034. /*** End of inlined file: setup_44.h ***/
  142035. /*** Start of inlined file: setup_44u.h ***/
  142036. /*** Start of inlined file: residue_44u.h ***/
  142037. /*** Start of inlined file: res_books_uncoupled.h ***/
  142038. static long _vq_quantlist__16u0__p1_0[] = {
  142039. 1,
  142040. 0,
  142041. 2,
  142042. };
  142043. static long _vq_lengthlist__16u0__p1_0[] = {
  142044. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  142045. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  142046. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  142047. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  142048. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  142049. 12,
  142050. };
  142051. static float _vq_quantthresh__16u0__p1_0[] = {
  142052. -0.5, 0.5,
  142053. };
  142054. static long _vq_quantmap__16u0__p1_0[] = {
  142055. 1, 0, 2,
  142056. };
  142057. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  142058. _vq_quantthresh__16u0__p1_0,
  142059. _vq_quantmap__16u0__p1_0,
  142060. 3,
  142061. 3
  142062. };
  142063. static static_codebook _16u0__p1_0 = {
  142064. 4, 81,
  142065. _vq_lengthlist__16u0__p1_0,
  142066. 1, -535822336, 1611661312, 2, 0,
  142067. _vq_quantlist__16u0__p1_0,
  142068. NULL,
  142069. &_vq_auxt__16u0__p1_0,
  142070. NULL,
  142071. 0
  142072. };
  142073. static long _vq_quantlist__16u0__p2_0[] = {
  142074. 1,
  142075. 0,
  142076. 2,
  142077. };
  142078. static long _vq_lengthlist__16u0__p2_0[] = {
  142079. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  142080. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  142081. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  142082. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  142083. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  142084. 8,
  142085. };
  142086. static float _vq_quantthresh__16u0__p2_0[] = {
  142087. -0.5, 0.5,
  142088. };
  142089. static long _vq_quantmap__16u0__p2_0[] = {
  142090. 1, 0, 2,
  142091. };
  142092. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  142093. _vq_quantthresh__16u0__p2_0,
  142094. _vq_quantmap__16u0__p2_0,
  142095. 3,
  142096. 3
  142097. };
  142098. static static_codebook _16u0__p2_0 = {
  142099. 4, 81,
  142100. _vq_lengthlist__16u0__p2_0,
  142101. 1, -535822336, 1611661312, 2, 0,
  142102. _vq_quantlist__16u0__p2_0,
  142103. NULL,
  142104. &_vq_auxt__16u0__p2_0,
  142105. NULL,
  142106. 0
  142107. };
  142108. static long _vq_quantlist__16u0__p3_0[] = {
  142109. 2,
  142110. 1,
  142111. 3,
  142112. 0,
  142113. 4,
  142114. };
  142115. static long _vq_lengthlist__16u0__p3_0[] = {
  142116. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  142117. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  142118. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  142119. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  142120. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  142121. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  142122. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  142123. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  142124. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  142125. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  142126. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  142127. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  142128. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  142129. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  142130. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  142131. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  142132. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  142133. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  142134. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  142135. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  142136. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  142137. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  142138. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  142139. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  142140. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  142141. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  142142. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  142143. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  142144. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  142145. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  142146. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  142147. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  142148. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  142149. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  142150. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  142151. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  142152. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  142153. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  142154. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  142155. 18,
  142156. };
  142157. static float _vq_quantthresh__16u0__p3_0[] = {
  142158. -1.5, -0.5, 0.5, 1.5,
  142159. };
  142160. static long _vq_quantmap__16u0__p3_0[] = {
  142161. 3, 1, 0, 2, 4,
  142162. };
  142163. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  142164. _vq_quantthresh__16u0__p3_0,
  142165. _vq_quantmap__16u0__p3_0,
  142166. 5,
  142167. 5
  142168. };
  142169. static static_codebook _16u0__p3_0 = {
  142170. 4, 625,
  142171. _vq_lengthlist__16u0__p3_0,
  142172. 1, -533725184, 1611661312, 3, 0,
  142173. _vq_quantlist__16u0__p3_0,
  142174. NULL,
  142175. &_vq_auxt__16u0__p3_0,
  142176. NULL,
  142177. 0
  142178. };
  142179. static long _vq_quantlist__16u0__p4_0[] = {
  142180. 2,
  142181. 1,
  142182. 3,
  142183. 0,
  142184. 4,
  142185. };
  142186. static long _vq_lengthlist__16u0__p4_0[] = {
  142187. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  142188. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  142189. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  142190. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  142191. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  142192. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  142193. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  142194. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  142195. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  142196. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  142197. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  142198. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  142199. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  142200. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  142201. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  142202. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  142203. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  142204. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  142205. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  142206. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  142207. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  142208. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  142209. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  142210. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  142211. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  142212. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  142213. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  142214. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  142215. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  142216. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  142217. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  142218. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  142219. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  142220. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  142221. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  142222. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  142223. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  142224. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  142225. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  142226. 11,
  142227. };
  142228. static float _vq_quantthresh__16u0__p4_0[] = {
  142229. -1.5, -0.5, 0.5, 1.5,
  142230. };
  142231. static long _vq_quantmap__16u0__p4_0[] = {
  142232. 3, 1, 0, 2, 4,
  142233. };
  142234. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  142235. _vq_quantthresh__16u0__p4_0,
  142236. _vq_quantmap__16u0__p4_0,
  142237. 5,
  142238. 5
  142239. };
  142240. static static_codebook _16u0__p4_0 = {
  142241. 4, 625,
  142242. _vq_lengthlist__16u0__p4_0,
  142243. 1, -533725184, 1611661312, 3, 0,
  142244. _vq_quantlist__16u0__p4_0,
  142245. NULL,
  142246. &_vq_auxt__16u0__p4_0,
  142247. NULL,
  142248. 0
  142249. };
  142250. static long _vq_quantlist__16u0__p5_0[] = {
  142251. 4,
  142252. 3,
  142253. 5,
  142254. 2,
  142255. 6,
  142256. 1,
  142257. 7,
  142258. 0,
  142259. 8,
  142260. };
  142261. static long _vq_lengthlist__16u0__p5_0[] = {
  142262. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  142263. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  142264. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  142265. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  142266. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  142267. 12,
  142268. };
  142269. static float _vq_quantthresh__16u0__p5_0[] = {
  142270. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142271. };
  142272. static long _vq_quantmap__16u0__p5_0[] = {
  142273. 7, 5, 3, 1, 0, 2, 4, 6,
  142274. 8,
  142275. };
  142276. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  142277. _vq_quantthresh__16u0__p5_0,
  142278. _vq_quantmap__16u0__p5_0,
  142279. 9,
  142280. 9
  142281. };
  142282. static static_codebook _16u0__p5_0 = {
  142283. 2, 81,
  142284. _vq_lengthlist__16u0__p5_0,
  142285. 1, -531628032, 1611661312, 4, 0,
  142286. _vq_quantlist__16u0__p5_0,
  142287. NULL,
  142288. &_vq_auxt__16u0__p5_0,
  142289. NULL,
  142290. 0
  142291. };
  142292. static long _vq_quantlist__16u0__p6_0[] = {
  142293. 6,
  142294. 5,
  142295. 7,
  142296. 4,
  142297. 8,
  142298. 3,
  142299. 9,
  142300. 2,
  142301. 10,
  142302. 1,
  142303. 11,
  142304. 0,
  142305. 12,
  142306. };
  142307. static long _vq_lengthlist__16u0__p6_0[] = {
  142308. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  142309. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  142310. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  142311. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  142312. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  142313. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  142314. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  142315. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  142316. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  142317. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  142318. 18, 0,19, 0, 0, 0, 0, 0, 0,
  142319. };
  142320. static float _vq_quantthresh__16u0__p6_0[] = {
  142321. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  142322. 12.5, 17.5, 22.5, 27.5,
  142323. };
  142324. static long _vq_quantmap__16u0__p6_0[] = {
  142325. 11, 9, 7, 5, 3, 1, 0, 2,
  142326. 4, 6, 8, 10, 12,
  142327. };
  142328. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  142329. _vq_quantthresh__16u0__p6_0,
  142330. _vq_quantmap__16u0__p6_0,
  142331. 13,
  142332. 13
  142333. };
  142334. static static_codebook _16u0__p6_0 = {
  142335. 2, 169,
  142336. _vq_lengthlist__16u0__p6_0,
  142337. 1, -526516224, 1616117760, 4, 0,
  142338. _vq_quantlist__16u0__p6_0,
  142339. NULL,
  142340. &_vq_auxt__16u0__p6_0,
  142341. NULL,
  142342. 0
  142343. };
  142344. static long _vq_quantlist__16u0__p6_1[] = {
  142345. 2,
  142346. 1,
  142347. 3,
  142348. 0,
  142349. 4,
  142350. };
  142351. static long _vq_lengthlist__16u0__p6_1[] = {
  142352. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  142353. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  142354. };
  142355. static float _vq_quantthresh__16u0__p6_1[] = {
  142356. -1.5, -0.5, 0.5, 1.5,
  142357. };
  142358. static long _vq_quantmap__16u0__p6_1[] = {
  142359. 3, 1, 0, 2, 4,
  142360. };
  142361. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  142362. _vq_quantthresh__16u0__p6_1,
  142363. _vq_quantmap__16u0__p6_1,
  142364. 5,
  142365. 5
  142366. };
  142367. static static_codebook _16u0__p6_1 = {
  142368. 2, 25,
  142369. _vq_lengthlist__16u0__p6_1,
  142370. 1, -533725184, 1611661312, 3, 0,
  142371. _vq_quantlist__16u0__p6_1,
  142372. NULL,
  142373. &_vq_auxt__16u0__p6_1,
  142374. NULL,
  142375. 0
  142376. };
  142377. static long _vq_quantlist__16u0__p7_0[] = {
  142378. 1,
  142379. 0,
  142380. 2,
  142381. };
  142382. static long _vq_lengthlist__16u0__p7_0[] = {
  142383. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  142384. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  142385. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  142386. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  142387. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  142388. 7,
  142389. };
  142390. static float _vq_quantthresh__16u0__p7_0[] = {
  142391. -157.5, 157.5,
  142392. };
  142393. static long _vq_quantmap__16u0__p7_0[] = {
  142394. 1, 0, 2,
  142395. };
  142396. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  142397. _vq_quantthresh__16u0__p7_0,
  142398. _vq_quantmap__16u0__p7_0,
  142399. 3,
  142400. 3
  142401. };
  142402. static static_codebook _16u0__p7_0 = {
  142403. 4, 81,
  142404. _vq_lengthlist__16u0__p7_0,
  142405. 1, -518803456, 1628680192, 2, 0,
  142406. _vq_quantlist__16u0__p7_0,
  142407. NULL,
  142408. &_vq_auxt__16u0__p7_0,
  142409. NULL,
  142410. 0
  142411. };
  142412. static long _vq_quantlist__16u0__p7_1[] = {
  142413. 7,
  142414. 6,
  142415. 8,
  142416. 5,
  142417. 9,
  142418. 4,
  142419. 10,
  142420. 3,
  142421. 11,
  142422. 2,
  142423. 12,
  142424. 1,
  142425. 13,
  142426. 0,
  142427. 14,
  142428. };
  142429. static long _vq_lengthlist__16u0__p7_1[] = {
  142430. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  142431. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  142432. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  142433. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  142434. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  142435. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  142436. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142437. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142438. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142439. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142440. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142441. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142442. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142443. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142444. 10,
  142445. };
  142446. static float _vq_quantthresh__16u0__p7_1[] = {
  142447. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  142448. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  142449. };
  142450. static long _vq_quantmap__16u0__p7_1[] = {
  142451. 13, 11, 9, 7, 5, 3, 1, 0,
  142452. 2, 4, 6, 8, 10, 12, 14,
  142453. };
  142454. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  142455. _vq_quantthresh__16u0__p7_1,
  142456. _vq_quantmap__16u0__p7_1,
  142457. 15,
  142458. 15
  142459. };
  142460. static static_codebook _16u0__p7_1 = {
  142461. 2, 225,
  142462. _vq_lengthlist__16u0__p7_1,
  142463. 1, -520986624, 1620377600, 4, 0,
  142464. _vq_quantlist__16u0__p7_1,
  142465. NULL,
  142466. &_vq_auxt__16u0__p7_1,
  142467. NULL,
  142468. 0
  142469. };
  142470. static long _vq_quantlist__16u0__p7_2[] = {
  142471. 10,
  142472. 9,
  142473. 11,
  142474. 8,
  142475. 12,
  142476. 7,
  142477. 13,
  142478. 6,
  142479. 14,
  142480. 5,
  142481. 15,
  142482. 4,
  142483. 16,
  142484. 3,
  142485. 17,
  142486. 2,
  142487. 18,
  142488. 1,
  142489. 19,
  142490. 0,
  142491. 20,
  142492. };
  142493. static long _vq_lengthlist__16u0__p7_2[] = {
  142494. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  142495. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  142496. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  142497. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  142498. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  142499. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  142500. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  142501. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  142502. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  142503. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  142504. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  142505. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  142506. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  142507. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  142508. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  142509. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  142510. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  142511. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  142512. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  142513. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  142514. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  142515. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  142516. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  142517. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  142518. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  142519. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  142520. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  142521. 10,10,12,11,10,11,11,11,10,
  142522. };
  142523. static float _vq_quantthresh__16u0__p7_2[] = {
  142524. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  142525. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  142526. 6.5, 7.5, 8.5, 9.5,
  142527. };
  142528. static long _vq_quantmap__16u0__p7_2[] = {
  142529. 19, 17, 15, 13, 11, 9, 7, 5,
  142530. 3, 1, 0, 2, 4, 6, 8, 10,
  142531. 12, 14, 16, 18, 20,
  142532. };
  142533. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  142534. _vq_quantthresh__16u0__p7_2,
  142535. _vq_quantmap__16u0__p7_2,
  142536. 21,
  142537. 21
  142538. };
  142539. static static_codebook _16u0__p7_2 = {
  142540. 2, 441,
  142541. _vq_lengthlist__16u0__p7_2,
  142542. 1, -529268736, 1611661312, 5, 0,
  142543. _vq_quantlist__16u0__p7_2,
  142544. NULL,
  142545. &_vq_auxt__16u0__p7_2,
  142546. NULL,
  142547. 0
  142548. };
  142549. static long _huff_lengthlist__16u0__single[] = {
  142550. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  142551. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  142552. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  142553. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  142554. };
  142555. static static_codebook _huff_book__16u0__single = {
  142556. 2, 64,
  142557. _huff_lengthlist__16u0__single,
  142558. 0, 0, 0, 0, 0,
  142559. NULL,
  142560. NULL,
  142561. NULL,
  142562. NULL,
  142563. 0
  142564. };
  142565. static long _huff_lengthlist__16u1__long[] = {
  142566. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  142567. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  142568. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  142569. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  142570. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  142571. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  142572. 16,13,16,18,
  142573. };
  142574. static static_codebook _huff_book__16u1__long = {
  142575. 2, 100,
  142576. _huff_lengthlist__16u1__long,
  142577. 0, 0, 0, 0, 0,
  142578. NULL,
  142579. NULL,
  142580. NULL,
  142581. NULL,
  142582. 0
  142583. };
  142584. static long _vq_quantlist__16u1__p1_0[] = {
  142585. 1,
  142586. 0,
  142587. 2,
  142588. };
  142589. static long _vq_lengthlist__16u1__p1_0[] = {
  142590. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  142591. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  142592. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  142593. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  142594. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  142595. 11,
  142596. };
  142597. static float _vq_quantthresh__16u1__p1_0[] = {
  142598. -0.5, 0.5,
  142599. };
  142600. static long _vq_quantmap__16u1__p1_0[] = {
  142601. 1, 0, 2,
  142602. };
  142603. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  142604. _vq_quantthresh__16u1__p1_0,
  142605. _vq_quantmap__16u1__p1_0,
  142606. 3,
  142607. 3
  142608. };
  142609. static static_codebook _16u1__p1_0 = {
  142610. 4, 81,
  142611. _vq_lengthlist__16u1__p1_0,
  142612. 1, -535822336, 1611661312, 2, 0,
  142613. _vq_quantlist__16u1__p1_0,
  142614. NULL,
  142615. &_vq_auxt__16u1__p1_0,
  142616. NULL,
  142617. 0
  142618. };
  142619. static long _vq_quantlist__16u1__p2_0[] = {
  142620. 1,
  142621. 0,
  142622. 2,
  142623. };
  142624. static long _vq_lengthlist__16u1__p2_0[] = {
  142625. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  142626. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  142627. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  142628. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  142629. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  142630. 8,
  142631. };
  142632. static float _vq_quantthresh__16u1__p2_0[] = {
  142633. -0.5, 0.5,
  142634. };
  142635. static long _vq_quantmap__16u1__p2_0[] = {
  142636. 1, 0, 2,
  142637. };
  142638. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  142639. _vq_quantthresh__16u1__p2_0,
  142640. _vq_quantmap__16u1__p2_0,
  142641. 3,
  142642. 3
  142643. };
  142644. static static_codebook _16u1__p2_0 = {
  142645. 4, 81,
  142646. _vq_lengthlist__16u1__p2_0,
  142647. 1, -535822336, 1611661312, 2, 0,
  142648. _vq_quantlist__16u1__p2_0,
  142649. NULL,
  142650. &_vq_auxt__16u1__p2_0,
  142651. NULL,
  142652. 0
  142653. };
  142654. static long _vq_quantlist__16u1__p3_0[] = {
  142655. 2,
  142656. 1,
  142657. 3,
  142658. 0,
  142659. 4,
  142660. };
  142661. static long _vq_lengthlist__16u1__p3_0[] = {
  142662. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  142663. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  142664. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  142665. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  142666. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  142667. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  142668. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  142669. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  142670. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  142671. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  142672. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  142673. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  142674. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  142675. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  142676. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  142677. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  142678. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  142679. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  142680. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  142681. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  142682. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  142683. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  142684. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  142685. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  142686. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  142687. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  142688. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  142689. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  142690. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  142691. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  142692. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  142693. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  142694. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  142695. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  142696. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  142697. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  142698. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  142699. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  142700. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  142701. 16,
  142702. };
  142703. static float _vq_quantthresh__16u1__p3_0[] = {
  142704. -1.5, -0.5, 0.5, 1.5,
  142705. };
  142706. static long _vq_quantmap__16u1__p3_0[] = {
  142707. 3, 1, 0, 2, 4,
  142708. };
  142709. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  142710. _vq_quantthresh__16u1__p3_0,
  142711. _vq_quantmap__16u1__p3_0,
  142712. 5,
  142713. 5
  142714. };
  142715. static static_codebook _16u1__p3_0 = {
  142716. 4, 625,
  142717. _vq_lengthlist__16u1__p3_0,
  142718. 1, -533725184, 1611661312, 3, 0,
  142719. _vq_quantlist__16u1__p3_0,
  142720. NULL,
  142721. &_vq_auxt__16u1__p3_0,
  142722. NULL,
  142723. 0
  142724. };
  142725. static long _vq_quantlist__16u1__p4_0[] = {
  142726. 2,
  142727. 1,
  142728. 3,
  142729. 0,
  142730. 4,
  142731. };
  142732. static long _vq_lengthlist__16u1__p4_0[] = {
  142733. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  142734. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  142735. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  142736. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  142737. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  142738. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  142739. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  142740. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  142741. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  142742. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  142743. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  142744. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  142745. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  142746. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  142747. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  142748. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  142749. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  142750. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  142751. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  142752. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  142753. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  142754. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  142755. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  142756. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  142757. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  142758. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  142759. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  142760. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  142761. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  142762. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  142763. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  142764. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  142765. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  142766. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  142767. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  142768. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  142769. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  142770. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  142771. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  142772. 11,
  142773. };
  142774. static float _vq_quantthresh__16u1__p4_0[] = {
  142775. -1.5, -0.5, 0.5, 1.5,
  142776. };
  142777. static long _vq_quantmap__16u1__p4_0[] = {
  142778. 3, 1, 0, 2, 4,
  142779. };
  142780. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  142781. _vq_quantthresh__16u1__p4_0,
  142782. _vq_quantmap__16u1__p4_0,
  142783. 5,
  142784. 5
  142785. };
  142786. static static_codebook _16u1__p4_0 = {
  142787. 4, 625,
  142788. _vq_lengthlist__16u1__p4_0,
  142789. 1, -533725184, 1611661312, 3, 0,
  142790. _vq_quantlist__16u1__p4_0,
  142791. NULL,
  142792. &_vq_auxt__16u1__p4_0,
  142793. NULL,
  142794. 0
  142795. };
  142796. static long _vq_quantlist__16u1__p5_0[] = {
  142797. 4,
  142798. 3,
  142799. 5,
  142800. 2,
  142801. 6,
  142802. 1,
  142803. 7,
  142804. 0,
  142805. 8,
  142806. };
  142807. static long _vq_lengthlist__16u1__p5_0[] = {
  142808. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  142809. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  142810. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  142811. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  142812. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  142813. 13,
  142814. };
  142815. static float _vq_quantthresh__16u1__p5_0[] = {
  142816. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142817. };
  142818. static long _vq_quantmap__16u1__p5_0[] = {
  142819. 7, 5, 3, 1, 0, 2, 4, 6,
  142820. 8,
  142821. };
  142822. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  142823. _vq_quantthresh__16u1__p5_0,
  142824. _vq_quantmap__16u1__p5_0,
  142825. 9,
  142826. 9
  142827. };
  142828. static static_codebook _16u1__p5_0 = {
  142829. 2, 81,
  142830. _vq_lengthlist__16u1__p5_0,
  142831. 1, -531628032, 1611661312, 4, 0,
  142832. _vq_quantlist__16u1__p5_0,
  142833. NULL,
  142834. &_vq_auxt__16u1__p5_0,
  142835. NULL,
  142836. 0
  142837. };
  142838. static long _vq_quantlist__16u1__p6_0[] = {
  142839. 4,
  142840. 3,
  142841. 5,
  142842. 2,
  142843. 6,
  142844. 1,
  142845. 7,
  142846. 0,
  142847. 8,
  142848. };
  142849. static long _vq_lengthlist__16u1__p6_0[] = {
  142850. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  142851. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  142852. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  142853. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  142854. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  142855. 11,
  142856. };
  142857. static float _vq_quantthresh__16u1__p6_0[] = {
  142858. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142859. };
  142860. static long _vq_quantmap__16u1__p6_0[] = {
  142861. 7, 5, 3, 1, 0, 2, 4, 6,
  142862. 8,
  142863. };
  142864. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  142865. _vq_quantthresh__16u1__p6_0,
  142866. _vq_quantmap__16u1__p6_0,
  142867. 9,
  142868. 9
  142869. };
  142870. static static_codebook _16u1__p6_0 = {
  142871. 2, 81,
  142872. _vq_lengthlist__16u1__p6_0,
  142873. 1, -531628032, 1611661312, 4, 0,
  142874. _vq_quantlist__16u1__p6_0,
  142875. NULL,
  142876. &_vq_auxt__16u1__p6_0,
  142877. NULL,
  142878. 0
  142879. };
  142880. static long _vq_quantlist__16u1__p7_0[] = {
  142881. 1,
  142882. 0,
  142883. 2,
  142884. };
  142885. static long _vq_lengthlist__16u1__p7_0[] = {
  142886. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  142887. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  142888. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  142889. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  142890. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  142891. 13,
  142892. };
  142893. static float _vq_quantthresh__16u1__p7_0[] = {
  142894. -5.5, 5.5,
  142895. };
  142896. static long _vq_quantmap__16u1__p7_0[] = {
  142897. 1, 0, 2,
  142898. };
  142899. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  142900. _vq_quantthresh__16u1__p7_0,
  142901. _vq_quantmap__16u1__p7_0,
  142902. 3,
  142903. 3
  142904. };
  142905. static static_codebook _16u1__p7_0 = {
  142906. 4, 81,
  142907. _vq_lengthlist__16u1__p7_0,
  142908. 1, -529137664, 1618345984, 2, 0,
  142909. _vq_quantlist__16u1__p7_0,
  142910. NULL,
  142911. &_vq_auxt__16u1__p7_0,
  142912. NULL,
  142913. 0
  142914. };
  142915. static long _vq_quantlist__16u1__p7_1[] = {
  142916. 5,
  142917. 4,
  142918. 6,
  142919. 3,
  142920. 7,
  142921. 2,
  142922. 8,
  142923. 1,
  142924. 9,
  142925. 0,
  142926. 10,
  142927. };
  142928. static long _vq_lengthlist__16u1__p7_1[] = {
  142929. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  142930. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  142931. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  142932. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  142933. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  142934. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  142935. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  142936. 8, 9, 9,10,10,10,10,10,10,
  142937. };
  142938. static float _vq_quantthresh__16u1__p7_1[] = {
  142939. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  142940. 3.5, 4.5,
  142941. };
  142942. static long _vq_quantmap__16u1__p7_1[] = {
  142943. 9, 7, 5, 3, 1, 0, 2, 4,
  142944. 6, 8, 10,
  142945. };
  142946. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  142947. _vq_quantthresh__16u1__p7_1,
  142948. _vq_quantmap__16u1__p7_1,
  142949. 11,
  142950. 11
  142951. };
  142952. static static_codebook _16u1__p7_1 = {
  142953. 2, 121,
  142954. _vq_lengthlist__16u1__p7_1,
  142955. 1, -531365888, 1611661312, 4, 0,
  142956. _vq_quantlist__16u1__p7_1,
  142957. NULL,
  142958. &_vq_auxt__16u1__p7_1,
  142959. NULL,
  142960. 0
  142961. };
  142962. static long _vq_quantlist__16u1__p8_0[] = {
  142963. 5,
  142964. 4,
  142965. 6,
  142966. 3,
  142967. 7,
  142968. 2,
  142969. 8,
  142970. 1,
  142971. 9,
  142972. 0,
  142973. 10,
  142974. };
  142975. static long _vq_lengthlist__16u1__p8_0[] = {
  142976. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  142977. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  142978. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  142979. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  142980. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  142981. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  142982. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  142983. 13,14,14,15,15,16,16,15,16,
  142984. };
  142985. static float _vq_quantthresh__16u1__p8_0[] = {
  142986. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  142987. 38.5, 49.5,
  142988. };
  142989. static long _vq_quantmap__16u1__p8_0[] = {
  142990. 9, 7, 5, 3, 1, 0, 2, 4,
  142991. 6, 8, 10,
  142992. };
  142993. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  142994. _vq_quantthresh__16u1__p8_0,
  142995. _vq_quantmap__16u1__p8_0,
  142996. 11,
  142997. 11
  142998. };
  142999. static static_codebook _16u1__p8_0 = {
  143000. 2, 121,
  143001. _vq_lengthlist__16u1__p8_0,
  143002. 1, -524582912, 1618345984, 4, 0,
  143003. _vq_quantlist__16u1__p8_0,
  143004. NULL,
  143005. &_vq_auxt__16u1__p8_0,
  143006. NULL,
  143007. 0
  143008. };
  143009. static long _vq_quantlist__16u1__p8_1[] = {
  143010. 5,
  143011. 4,
  143012. 6,
  143013. 3,
  143014. 7,
  143015. 2,
  143016. 8,
  143017. 1,
  143018. 9,
  143019. 0,
  143020. 10,
  143021. };
  143022. static long _vq_lengthlist__16u1__p8_1[] = {
  143023. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  143024. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  143025. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  143026. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  143027. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  143028. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  143029. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  143030. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  143031. };
  143032. static float _vq_quantthresh__16u1__p8_1[] = {
  143033. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143034. 3.5, 4.5,
  143035. };
  143036. static long _vq_quantmap__16u1__p8_1[] = {
  143037. 9, 7, 5, 3, 1, 0, 2, 4,
  143038. 6, 8, 10,
  143039. };
  143040. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  143041. _vq_quantthresh__16u1__p8_1,
  143042. _vq_quantmap__16u1__p8_1,
  143043. 11,
  143044. 11
  143045. };
  143046. static static_codebook _16u1__p8_1 = {
  143047. 2, 121,
  143048. _vq_lengthlist__16u1__p8_1,
  143049. 1, -531365888, 1611661312, 4, 0,
  143050. _vq_quantlist__16u1__p8_1,
  143051. NULL,
  143052. &_vq_auxt__16u1__p8_1,
  143053. NULL,
  143054. 0
  143055. };
  143056. static long _vq_quantlist__16u1__p9_0[] = {
  143057. 7,
  143058. 6,
  143059. 8,
  143060. 5,
  143061. 9,
  143062. 4,
  143063. 10,
  143064. 3,
  143065. 11,
  143066. 2,
  143067. 12,
  143068. 1,
  143069. 13,
  143070. 0,
  143071. 14,
  143072. };
  143073. static long _vq_lengthlist__16u1__p9_0[] = {
  143074. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143075. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143076. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143077. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143078. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143079. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143080. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143081. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143082. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143083. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143084. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143085. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143086. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143087. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143088. 8,
  143089. };
  143090. static float _vq_quantthresh__16u1__p9_0[] = {
  143091. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  143092. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  143093. };
  143094. static long _vq_quantmap__16u1__p9_0[] = {
  143095. 13, 11, 9, 7, 5, 3, 1, 0,
  143096. 2, 4, 6, 8, 10, 12, 14,
  143097. };
  143098. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  143099. _vq_quantthresh__16u1__p9_0,
  143100. _vq_quantmap__16u1__p9_0,
  143101. 15,
  143102. 15
  143103. };
  143104. static static_codebook _16u1__p9_0 = {
  143105. 2, 225,
  143106. _vq_lengthlist__16u1__p9_0,
  143107. 1, -514071552, 1627381760, 4, 0,
  143108. _vq_quantlist__16u1__p9_0,
  143109. NULL,
  143110. &_vq_auxt__16u1__p9_0,
  143111. NULL,
  143112. 0
  143113. };
  143114. static long _vq_quantlist__16u1__p9_1[] = {
  143115. 7,
  143116. 6,
  143117. 8,
  143118. 5,
  143119. 9,
  143120. 4,
  143121. 10,
  143122. 3,
  143123. 11,
  143124. 2,
  143125. 12,
  143126. 1,
  143127. 13,
  143128. 0,
  143129. 14,
  143130. };
  143131. static long _vq_lengthlist__16u1__p9_1[] = {
  143132. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  143133. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  143134. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  143135. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  143136. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  143137. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  143138. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  143139. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  143140. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  143141. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143142. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  143143. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143144. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143145. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143146. 9,
  143147. };
  143148. static float _vq_quantthresh__16u1__p9_1[] = {
  143149. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  143150. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  143151. };
  143152. static long _vq_quantmap__16u1__p9_1[] = {
  143153. 13, 11, 9, 7, 5, 3, 1, 0,
  143154. 2, 4, 6, 8, 10, 12, 14,
  143155. };
  143156. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  143157. _vq_quantthresh__16u1__p9_1,
  143158. _vq_quantmap__16u1__p9_1,
  143159. 15,
  143160. 15
  143161. };
  143162. static static_codebook _16u1__p9_1 = {
  143163. 2, 225,
  143164. _vq_lengthlist__16u1__p9_1,
  143165. 1, -522338304, 1620115456, 4, 0,
  143166. _vq_quantlist__16u1__p9_1,
  143167. NULL,
  143168. &_vq_auxt__16u1__p9_1,
  143169. NULL,
  143170. 0
  143171. };
  143172. static long _vq_quantlist__16u1__p9_2[] = {
  143173. 8,
  143174. 7,
  143175. 9,
  143176. 6,
  143177. 10,
  143178. 5,
  143179. 11,
  143180. 4,
  143181. 12,
  143182. 3,
  143183. 13,
  143184. 2,
  143185. 14,
  143186. 1,
  143187. 15,
  143188. 0,
  143189. 16,
  143190. };
  143191. static long _vq_lengthlist__16u1__p9_2[] = {
  143192. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  143193. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  143194. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  143195. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  143196. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  143197. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  143198. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  143199. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  143200. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  143201. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  143202. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  143203. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  143204. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  143205. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  143206. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  143207. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  143208. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  143209. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  143210. 10,
  143211. };
  143212. static float _vq_quantthresh__16u1__p9_2[] = {
  143213. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  143214. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  143215. };
  143216. static long _vq_quantmap__16u1__p9_2[] = {
  143217. 15, 13, 11, 9, 7, 5, 3, 1,
  143218. 0, 2, 4, 6, 8, 10, 12, 14,
  143219. 16,
  143220. };
  143221. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  143222. _vq_quantthresh__16u1__p9_2,
  143223. _vq_quantmap__16u1__p9_2,
  143224. 17,
  143225. 17
  143226. };
  143227. static static_codebook _16u1__p9_2 = {
  143228. 2, 289,
  143229. _vq_lengthlist__16u1__p9_2,
  143230. 1, -529530880, 1611661312, 5, 0,
  143231. _vq_quantlist__16u1__p9_2,
  143232. NULL,
  143233. &_vq_auxt__16u1__p9_2,
  143234. NULL,
  143235. 0
  143236. };
  143237. static long _huff_lengthlist__16u1__short[] = {
  143238. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  143239. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  143240. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  143241. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  143242. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  143243. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  143244. 16,16,16,16,
  143245. };
  143246. static static_codebook _huff_book__16u1__short = {
  143247. 2, 100,
  143248. _huff_lengthlist__16u1__short,
  143249. 0, 0, 0, 0, 0,
  143250. NULL,
  143251. NULL,
  143252. NULL,
  143253. NULL,
  143254. 0
  143255. };
  143256. static long _huff_lengthlist__16u2__long[] = {
  143257. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  143258. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  143259. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  143260. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  143261. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  143262. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  143263. 13,14,18,18,
  143264. };
  143265. static static_codebook _huff_book__16u2__long = {
  143266. 2, 100,
  143267. _huff_lengthlist__16u2__long,
  143268. 0, 0, 0, 0, 0,
  143269. NULL,
  143270. NULL,
  143271. NULL,
  143272. NULL,
  143273. 0
  143274. };
  143275. static long _huff_lengthlist__16u2__short[] = {
  143276. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  143277. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  143278. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  143279. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  143280. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  143281. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  143282. 16,16,16,16,
  143283. };
  143284. static static_codebook _huff_book__16u2__short = {
  143285. 2, 100,
  143286. _huff_lengthlist__16u2__short,
  143287. 0, 0, 0, 0, 0,
  143288. NULL,
  143289. NULL,
  143290. NULL,
  143291. NULL,
  143292. 0
  143293. };
  143294. static long _vq_quantlist__16u2_p1_0[] = {
  143295. 1,
  143296. 0,
  143297. 2,
  143298. };
  143299. static long _vq_lengthlist__16u2_p1_0[] = {
  143300. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  143301. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  143302. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  143303. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  143304. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  143305. 10,
  143306. };
  143307. static float _vq_quantthresh__16u2_p1_0[] = {
  143308. -0.5, 0.5,
  143309. };
  143310. static long _vq_quantmap__16u2_p1_0[] = {
  143311. 1, 0, 2,
  143312. };
  143313. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  143314. _vq_quantthresh__16u2_p1_0,
  143315. _vq_quantmap__16u2_p1_0,
  143316. 3,
  143317. 3
  143318. };
  143319. static static_codebook _16u2_p1_0 = {
  143320. 4, 81,
  143321. _vq_lengthlist__16u2_p1_0,
  143322. 1, -535822336, 1611661312, 2, 0,
  143323. _vq_quantlist__16u2_p1_0,
  143324. NULL,
  143325. &_vq_auxt__16u2_p1_0,
  143326. NULL,
  143327. 0
  143328. };
  143329. static long _vq_quantlist__16u2_p2_0[] = {
  143330. 2,
  143331. 1,
  143332. 3,
  143333. 0,
  143334. 4,
  143335. };
  143336. static long _vq_lengthlist__16u2_p2_0[] = {
  143337. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  143338. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  143339. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  143340. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  143341. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  143342. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  143343. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  143344. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  143345. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  143346. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  143347. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  143348. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  143349. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  143350. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  143351. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  143352. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  143353. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  143354. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  143355. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  143356. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  143357. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  143358. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  143359. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  143360. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  143361. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  143362. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  143363. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  143364. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  143365. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  143366. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  143367. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  143368. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  143369. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  143370. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  143371. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  143372. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  143373. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  143374. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  143375. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  143376. 13,
  143377. };
  143378. static float _vq_quantthresh__16u2_p2_0[] = {
  143379. -1.5, -0.5, 0.5, 1.5,
  143380. };
  143381. static long _vq_quantmap__16u2_p2_0[] = {
  143382. 3, 1, 0, 2, 4,
  143383. };
  143384. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  143385. _vq_quantthresh__16u2_p2_0,
  143386. _vq_quantmap__16u2_p2_0,
  143387. 5,
  143388. 5
  143389. };
  143390. static static_codebook _16u2_p2_0 = {
  143391. 4, 625,
  143392. _vq_lengthlist__16u2_p2_0,
  143393. 1, -533725184, 1611661312, 3, 0,
  143394. _vq_quantlist__16u2_p2_0,
  143395. NULL,
  143396. &_vq_auxt__16u2_p2_0,
  143397. NULL,
  143398. 0
  143399. };
  143400. static long _vq_quantlist__16u2_p3_0[] = {
  143401. 4,
  143402. 3,
  143403. 5,
  143404. 2,
  143405. 6,
  143406. 1,
  143407. 7,
  143408. 0,
  143409. 8,
  143410. };
  143411. static long _vq_lengthlist__16u2_p3_0[] = {
  143412. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  143413. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  143414. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  143415. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  143416. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  143417. 11,
  143418. };
  143419. static float _vq_quantthresh__16u2_p3_0[] = {
  143420. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143421. };
  143422. static long _vq_quantmap__16u2_p3_0[] = {
  143423. 7, 5, 3, 1, 0, 2, 4, 6,
  143424. 8,
  143425. };
  143426. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  143427. _vq_quantthresh__16u2_p3_0,
  143428. _vq_quantmap__16u2_p3_0,
  143429. 9,
  143430. 9
  143431. };
  143432. static static_codebook _16u2_p3_0 = {
  143433. 2, 81,
  143434. _vq_lengthlist__16u2_p3_0,
  143435. 1, -531628032, 1611661312, 4, 0,
  143436. _vq_quantlist__16u2_p3_0,
  143437. NULL,
  143438. &_vq_auxt__16u2_p3_0,
  143439. NULL,
  143440. 0
  143441. };
  143442. static long _vq_quantlist__16u2_p4_0[] = {
  143443. 8,
  143444. 7,
  143445. 9,
  143446. 6,
  143447. 10,
  143448. 5,
  143449. 11,
  143450. 4,
  143451. 12,
  143452. 3,
  143453. 13,
  143454. 2,
  143455. 14,
  143456. 1,
  143457. 15,
  143458. 0,
  143459. 16,
  143460. };
  143461. static long _vq_lengthlist__16u2_p4_0[] = {
  143462. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  143463. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  143464. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  143465. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  143466. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  143467. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  143468. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  143469. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  143470. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  143471. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  143472. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  143473. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  143474. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  143475. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  143476. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  143477. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  143478. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  143479. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  143480. 14,
  143481. };
  143482. static float _vq_quantthresh__16u2_p4_0[] = {
  143483. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  143484. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  143485. };
  143486. static long _vq_quantmap__16u2_p4_0[] = {
  143487. 15, 13, 11, 9, 7, 5, 3, 1,
  143488. 0, 2, 4, 6, 8, 10, 12, 14,
  143489. 16,
  143490. };
  143491. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  143492. _vq_quantthresh__16u2_p4_0,
  143493. _vq_quantmap__16u2_p4_0,
  143494. 17,
  143495. 17
  143496. };
  143497. static static_codebook _16u2_p4_0 = {
  143498. 2, 289,
  143499. _vq_lengthlist__16u2_p4_0,
  143500. 1, -529530880, 1611661312, 5, 0,
  143501. _vq_quantlist__16u2_p4_0,
  143502. NULL,
  143503. &_vq_auxt__16u2_p4_0,
  143504. NULL,
  143505. 0
  143506. };
  143507. static long _vq_quantlist__16u2_p5_0[] = {
  143508. 1,
  143509. 0,
  143510. 2,
  143511. };
  143512. static long _vq_lengthlist__16u2_p5_0[] = {
  143513. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  143514. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  143515. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  143516. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  143517. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  143518. 10,
  143519. };
  143520. static float _vq_quantthresh__16u2_p5_0[] = {
  143521. -5.5, 5.5,
  143522. };
  143523. static long _vq_quantmap__16u2_p5_0[] = {
  143524. 1, 0, 2,
  143525. };
  143526. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  143527. _vq_quantthresh__16u2_p5_0,
  143528. _vq_quantmap__16u2_p5_0,
  143529. 3,
  143530. 3
  143531. };
  143532. static static_codebook _16u2_p5_0 = {
  143533. 4, 81,
  143534. _vq_lengthlist__16u2_p5_0,
  143535. 1, -529137664, 1618345984, 2, 0,
  143536. _vq_quantlist__16u2_p5_0,
  143537. NULL,
  143538. &_vq_auxt__16u2_p5_0,
  143539. NULL,
  143540. 0
  143541. };
  143542. static long _vq_quantlist__16u2_p5_1[] = {
  143543. 5,
  143544. 4,
  143545. 6,
  143546. 3,
  143547. 7,
  143548. 2,
  143549. 8,
  143550. 1,
  143551. 9,
  143552. 0,
  143553. 10,
  143554. };
  143555. static long _vq_lengthlist__16u2_p5_1[] = {
  143556. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  143557. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  143558. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  143559. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  143560. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  143561. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  143562. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  143563. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143564. };
  143565. static float _vq_quantthresh__16u2_p5_1[] = {
  143566. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143567. 3.5, 4.5,
  143568. };
  143569. static long _vq_quantmap__16u2_p5_1[] = {
  143570. 9, 7, 5, 3, 1, 0, 2, 4,
  143571. 6, 8, 10,
  143572. };
  143573. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  143574. _vq_quantthresh__16u2_p5_1,
  143575. _vq_quantmap__16u2_p5_1,
  143576. 11,
  143577. 11
  143578. };
  143579. static static_codebook _16u2_p5_1 = {
  143580. 2, 121,
  143581. _vq_lengthlist__16u2_p5_1,
  143582. 1, -531365888, 1611661312, 4, 0,
  143583. _vq_quantlist__16u2_p5_1,
  143584. NULL,
  143585. &_vq_auxt__16u2_p5_1,
  143586. NULL,
  143587. 0
  143588. };
  143589. static long _vq_quantlist__16u2_p6_0[] = {
  143590. 6,
  143591. 5,
  143592. 7,
  143593. 4,
  143594. 8,
  143595. 3,
  143596. 9,
  143597. 2,
  143598. 10,
  143599. 1,
  143600. 11,
  143601. 0,
  143602. 12,
  143603. };
  143604. static long _vq_lengthlist__16u2_p6_0[] = {
  143605. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  143606. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  143607. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  143608. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  143609. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  143610. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  143611. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  143612. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  143613. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  143614. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  143615. 12,13,13,14,14,14,14,15,15,
  143616. };
  143617. static float _vq_quantthresh__16u2_p6_0[] = {
  143618. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  143619. 12.5, 17.5, 22.5, 27.5,
  143620. };
  143621. static long _vq_quantmap__16u2_p6_0[] = {
  143622. 11, 9, 7, 5, 3, 1, 0, 2,
  143623. 4, 6, 8, 10, 12,
  143624. };
  143625. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  143626. _vq_quantthresh__16u2_p6_0,
  143627. _vq_quantmap__16u2_p6_0,
  143628. 13,
  143629. 13
  143630. };
  143631. static static_codebook _16u2_p6_0 = {
  143632. 2, 169,
  143633. _vq_lengthlist__16u2_p6_0,
  143634. 1, -526516224, 1616117760, 4, 0,
  143635. _vq_quantlist__16u2_p6_0,
  143636. NULL,
  143637. &_vq_auxt__16u2_p6_0,
  143638. NULL,
  143639. 0
  143640. };
  143641. static long _vq_quantlist__16u2_p6_1[] = {
  143642. 2,
  143643. 1,
  143644. 3,
  143645. 0,
  143646. 4,
  143647. };
  143648. static long _vq_lengthlist__16u2_p6_1[] = {
  143649. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  143650. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  143651. };
  143652. static float _vq_quantthresh__16u2_p6_1[] = {
  143653. -1.5, -0.5, 0.5, 1.5,
  143654. };
  143655. static long _vq_quantmap__16u2_p6_1[] = {
  143656. 3, 1, 0, 2, 4,
  143657. };
  143658. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  143659. _vq_quantthresh__16u2_p6_1,
  143660. _vq_quantmap__16u2_p6_1,
  143661. 5,
  143662. 5
  143663. };
  143664. static static_codebook _16u2_p6_1 = {
  143665. 2, 25,
  143666. _vq_lengthlist__16u2_p6_1,
  143667. 1, -533725184, 1611661312, 3, 0,
  143668. _vq_quantlist__16u2_p6_1,
  143669. NULL,
  143670. &_vq_auxt__16u2_p6_1,
  143671. NULL,
  143672. 0
  143673. };
  143674. static long _vq_quantlist__16u2_p7_0[] = {
  143675. 6,
  143676. 5,
  143677. 7,
  143678. 4,
  143679. 8,
  143680. 3,
  143681. 9,
  143682. 2,
  143683. 10,
  143684. 1,
  143685. 11,
  143686. 0,
  143687. 12,
  143688. };
  143689. static long _vq_lengthlist__16u2_p7_0[] = {
  143690. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  143691. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  143692. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  143693. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  143694. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  143695. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  143696. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  143697. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  143698. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  143699. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  143700. 12,13,13,13,14,14,14,15,14,
  143701. };
  143702. static float _vq_quantthresh__16u2_p7_0[] = {
  143703. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  143704. 27.5, 38.5, 49.5, 60.5,
  143705. };
  143706. static long _vq_quantmap__16u2_p7_0[] = {
  143707. 11, 9, 7, 5, 3, 1, 0, 2,
  143708. 4, 6, 8, 10, 12,
  143709. };
  143710. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  143711. _vq_quantthresh__16u2_p7_0,
  143712. _vq_quantmap__16u2_p7_0,
  143713. 13,
  143714. 13
  143715. };
  143716. static static_codebook _16u2_p7_0 = {
  143717. 2, 169,
  143718. _vq_lengthlist__16u2_p7_0,
  143719. 1, -523206656, 1618345984, 4, 0,
  143720. _vq_quantlist__16u2_p7_0,
  143721. NULL,
  143722. &_vq_auxt__16u2_p7_0,
  143723. NULL,
  143724. 0
  143725. };
  143726. static long _vq_quantlist__16u2_p7_1[] = {
  143727. 5,
  143728. 4,
  143729. 6,
  143730. 3,
  143731. 7,
  143732. 2,
  143733. 8,
  143734. 1,
  143735. 9,
  143736. 0,
  143737. 10,
  143738. };
  143739. static long _vq_lengthlist__16u2_p7_1[] = {
  143740. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  143741. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  143742. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  143743. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  143744. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  143745. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  143746. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  143747. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143748. };
  143749. static float _vq_quantthresh__16u2_p7_1[] = {
  143750. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143751. 3.5, 4.5,
  143752. };
  143753. static long _vq_quantmap__16u2_p7_1[] = {
  143754. 9, 7, 5, 3, 1, 0, 2, 4,
  143755. 6, 8, 10,
  143756. };
  143757. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  143758. _vq_quantthresh__16u2_p7_1,
  143759. _vq_quantmap__16u2_p7_1,
  143760. 11,
  143761. 11
  143762. };
  143763. static static_codebook _16u2_p7_1 = {
  143764. 2, 121,
  143765. _vq_lengthlist__16u2_p7_1,
  143766. 1, -531365888, 1611661312, 4, 0,
  143767. _vq_quantlist__16u2_p7_1,
  143768. NULL,
  143769. &_vq_auxt__16u2_p7_1,
  143770. NULL,
  143771. 0
  143772. };
  143773. static long _vq_quantlist__16u2_p8_0[] = {
  143774. 7,
  143775. 6,
  143776. 8,
  143777. 5,
  143778. 9,
  143779. 4,
  143780. 10,
  143781. 3,
  143782. 11,
  143783. 2,
  143784. 12,
  143785. 1,
  143786. 13,
  143787. 0,
  143788. 14,
  143789. };
  143790. static long _vq_lengthlist__16u2_p8_0[] = {
  143791. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  143792. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  143793. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  143794. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  143795. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  143796. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  143797. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  143798. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  143799. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  143800. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  143801. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  143802. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  143803. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  143804. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  143805. 14,
  143806. };
  143807. static float _vq_quantthresh__16u2_p8_0[] = {
  143808. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  143809. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  143810. };
  143811. static long _vq_quantmap__16u2_p8_0[] = {
  143812. 13, 11, 9, 7, 5, 3, 1, 0,
  143813. 2, 4, 6, 8, 10, 12, 14,
  143814. };
  143815. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  143816. _vq_quantthresh__16u2_p8_0,
  143817. _vq_quantmap__16u2_p8_0,
  143818. 15,
  143819. 15
  143820. };
  143821. static static_codebook _16u2_p8_0 = {
  143822. 2, 225,
  143823. _vq_lengthlist__16u2_p8_0,
  143824. 1, -520986624, 1620377600, 4, 0,
  143825. _vq_quantlist__16u2_p8_0,
  143826. NULL,
  143827. &_vq_auxt__16u2_p8_0,
  143828. NULL,
  143829. 0
  143830. };
  143831. static long _vq_quantlist__16u2_p8_1[] = {
  143832. 10,
  143833. 9,
  143834. 11,
  143835. 8,
  143836. 12,
  143837. 7,
  143838. 13,
  143839. 6,
  143840. 14,
  143841. 5,
  143842. 15,
  143843. 4,
  143844. 16,
  143845. 3,
  143846. 17,
  143847. 2,
  143848. 18,
  143849. 1,
  143850. 19,
  143851. 0,
  143852. 20,
  143853. };
  143854. static long _vq_lengthlist__16u2_p8_1[] = {
  143855. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  143856. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  143857. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  143858. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  143859. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  143860. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  143861. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  143862. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  143863. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  143864. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  143865. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  143866. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  143867. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  143868. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  143869. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  143870. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  143871. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  143872. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  143873. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  143874. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  143875. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  143876. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  143877. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  143878. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  143879. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  143880. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  143881. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  143882. 11,11,10,11,11,11,10,11,11,
  143883. };
  143884. static float _vq_quantthresh__16u2_p8_1[] = {
  143885. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  143886. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  143887. 6.5, 7.5, 8.5, 9.5,
  143888. };
  143889. static long _vq_quantmap__16u2_p8_1[] = {
  143890. 19, 17, 15, 13, 11, 9, 7, 5,
  143891. 3, 1, 0, 2, 4, 6, 8, 10,
  143892. 12, 14, 16, 18, 20,
  143893. };
  143894. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  143895. _vq_quantthresh__16u2_p8_1,
  143896. _vq_quantmap__16u2_p8_1,
  143897. 21,
  143898. 21
  143899. };
  143900. static static_codebook _16u2_p8_1 = {
  143901. 2, 441,
  143902. _vq_lengthlist__16u2_p8_1,
  143903. 1, -529268736, 1611661312, 5, 0,
  143904. _vq_quantlist__16u2_p8_1,
  143905. NULL,
  143906. &_vq_auxt__16u2_p8_1,
  143907. NULL,
  143908. 0
  143909. };
  143910. static long _vq_quantlist__16u2_p9_0[] = {
  143911. 5586,
  143912. 4655,
  143913. 6517,
  143914. 3724,
  143915. 7448,
  143916. 2793,
  143917. 8379,
  143918. 1862,
  143919. 9310,
  143920. 931,
  143921. 10241,
  143922. 0,
  143923. 11172,
  143924. 5521,
  143925. 5651,
  143926. };
  143927. static long _vq_lengthlist__16u2_p9_0[] = {
  143928. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  143929. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143930. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143931. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143932. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143933. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143934. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143935. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143936. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143937. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143938. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143939. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143940. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  143941. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  143942. 5,
  143943. };
  143944. static float _vq_quantthresh__16u2_p9_0[] = {
  143945. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  143946. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  143947. };
  143948. static long _vq_quantmap__16u2_p9_0[] = {
  143949. 11, 9, 7, 5, 3, 1, 13, 0,
  143950. 14, 2, 4, 6, 8, 10, 12,
  143951. };
  143952. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  143953. _vq_quantthresh__16u2_p9_0,
  143954. _vq_quantmap__16u2_p9_0,
  143955. 15,
  143956. 15
  143957. };
  143958. static static_codebook _16u2_p9_0 = {
  143959. 2, 225,
  143960. _vq_lengthlist__16u2_p9_0,
  143961. 1, -510275072, 1611661312, 14, 0,
  143962. _vq_quantlist__16u2_p9_0,
  143963. NULL,
  143964. &_vq_auxt__16u2_p9_0,
  143965. NULL,
  143966. 0
  143967. };
  143968. static long _vq_quantlist__16u2_p9_1[] = {
  143969. 392,
  143970. 343,
  143971. 441,
  143972. 294,
  143973. 490,
  143974. 245,
  143975. 539,
  143976. 196,
  143977. 588,
  143978. 147,
  143979. 637,
  143980. 98,
  143981. 686,
  143982. 49,
  143983. 735,
  143984. 0,
  143985. 784,
  143986. 388,
  143987. 396,
  143988. };
  143989. static long _vq_lengthlist__16u2_p9_1[] = {
  143990. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  143991. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  143992. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  143993. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  143994. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  143995. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  143996. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  143997. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  143998. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  143999. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144000. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144001. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144002. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144003. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144004. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  144005. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144006. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144007. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144008. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144009. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144010. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  144011. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  144012. 11,11,11,11,11,11,11, 5, 4,
  144013. };
  144014. static float _vq_quantthresh__16u2_p9_1[] = {
  144015. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  144016. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  144017. 318.5, 367.5,
  144018. };
  144019. static long _vq_quantmap__16u2_p9_1[] = {
  144020. 15, 13, 11, 9, 7, 5, 3, 1,
  144021. 17, 0, 18, 2, 4, 6, 8, 10,
  144022. 12, 14, 16,
  144023. };
  144024. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  144025. _vq_quantthresh__16u2_p9_1,
  144026. _vq_quantmap__16u2_p9_1,
  144027. 19,
  144028. 19
  144029. };
  144030. static static_codebook _16u2_p9_1 = {
  144031. 2, 361,
  144032. _vq_lengthlist__16u2_p9_1,
  144033. 1, -518488064, 1611661312, 10, 0,
  144034. _vq_quantlist__16u2_p9_1,
  144035. NULL,
  144036. &_vq_auxt__16u2_p9_1,
  144037. NULL,
  144038. 0
  144039. };
  144040. static long _vq_quantlist__16u2_p9_2[] = {
  144041. 24,
  144042. 23,
  144043. 25,
  144044. 22,
  144045. 26,
  144046. 21,
  144047. 27,
  144048. 20,
  144049. 28,
  144050. 19,
  144051. 29,
  144052. 18,
  144053. 30,
  144054. 17,
  144055. 31,
  144056. 16,
  144057. 32,
  144058. 15,
  144059. 33,
  144060. 14,
  144061. 34,
  144062. 13,
  144063. 35,
  144064. 12,
  144065. 36,
  144066. 11,
  144067. 37,
  144068. 10,
  144069. 38,
  144070. 9,
  144071. 39,
  144072. 8,
  144073. 40,
  144074. 7,
  144075. 41,
  144076. 6,
  144077. 42,
  144078. 5,
  144079. 43,
  144080. 4,
  144081. 44,
  144082. 3,
  144083. 45,
  144084. 2,
  144085. 46,
  144086. 1,
  144087. 47,
  144088. 0,
  144089. 48,
  144090. };
  144091. static long _vq_lengthlist__16u2_p9_2[] = {
  144092. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  144093. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  144094. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  144095. 11,
  144096. };
  144097. static float _vq_quantthresh__16u2_p9_2[] = {
  144098. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  144099. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  144100. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144101. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144102. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  144103. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  144104. };
  144105. static long _vq_quantmap__16u2_p9_2[] = {
  144106. 47, 45, 43, 41, 39, 37, 35, 33,
  144107. 31, 29, 27, 25, 23, 21, 19, 17,
  144108. 15, 13, 11, 9, 7, 5, 3, 1,
  144109. 0, 2, 4, 6, 8, 10, 12, 14,
  144110. 16, 18, 20, 22, 24, 26, 28, 30,
  144111. 32, 34, 36, 38, 40, 42, 44, 46,
  144112. 48,
  144113. };
  144114. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  144115. _vq_quantthresh__16u2_p9_2,
  144116. _vq_quantmap__16u2_p9_2,
  144117. 49,
  144118. 49
  144119. };
  144120. static static_codebook _16u2_p9_2 = {
  144121. 1, 49,
  144122. _vq_lengthlist__16u2_p9_2,
  144123. 1, -526909440, 1611661312, 6, 0,
  144124. _vq_quantlist__16u2_p9_2,
  144125. NULL,
  144126. &_vq_auxt__16u2_p9_2,
  144127. NULL,
  144128. 0
  144129. };
  144130. static long _vq_quantlist__8u0__p1_0[] = {
  144131. 1,
  144132. 0,
  144133. 2,
  144134. };
  144135. static long _vq_lengthlist__8u0__p1_0[] = {
  144136. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  144137. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  144138. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  144139. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  144140. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  144141. 11,
  144142. };
  144143. static float _vq_quantthresh__8u0__p1_0[] = {
  144144. -0.5, 0.5,
  144145. };
  144146. static long _vq_quantmap__8u0__p1_0[] = {
  144147. 1, 0, 2,
  144148. };
  144149. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  144150. _vq_quantthresh__8u0__p1_0,
  144151. _vq_quantmap__8u0__p1_0,
  144152. 3,
  144153. 3
  144154. };
  144155. static static_codebook _8u0__p1_0 = {
  144156. 4, 81,
  144157. _vq_lengthlist__8u0__p1_0,
  144158. 1, -535822336, 1611661312, 2, 0,
  144159. _vq_quantlist__8u0__p1_0,
  144160. NULL,
  144161. &_vq_auxt__8u0__p1_0,
  144162. NULL,
  144163. 0
  144164. };
  144165. static long _vq_quantlist__8u0__p2_0[] = {
  144166. 1,
  144167. 0,
  144168. 2,
  144169. };
  144170. static long _vq_lengthlist__8u0__p2_0[] = {
  144171. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  144172. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  144173. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  144174. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  144175. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  144176. 8,
  144177. };
  144178. static float _vq_quantthresh__8u0__p2_0[] = {
  144179. -0.5, 0.5,
  144180. };
  144181. static long _vq_quantmap__8u0__p2_0[] = {
  144182. 1, 0, 2,
  144183. };
  144184. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  144185. _vq_quantthresh__8u0__p2_0,
  144186. _vq_quantmap__8u0__p2_0,
  144187. 3,
  144188. 3
  144189. };
  144190. static static_codebook _8u0__p2_0 = {
  144191. 4, 81,
  144192. _vq_lengthlist__8u0__p2_0,
  144193. 1, -535822336, 1611661312, 2, 0,
  144194. _vq_quantlist__8u0__p2_0,
  144195. NULL,
  144196. &_vq_auxt__8u0__p2_0,
  144197. NULL,
  144198. 0
  144199. };
  144200. static long _vq_quantlist__8u0__p3_0[] = {
  144201. 2,
  144202. 1,
  144203. 3,
  144204. 0,
  144205. 4,
  144206. };
  144207. static long _vq_lengthlist__8u0__p3_0[] = {
  144208. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  144209. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  144210. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  144211. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  144212. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  144213. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  144214. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  144215. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  144216. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  144217. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  144218. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  144219. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  144220. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  144221. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  144222. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  144223. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  144224. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  144225. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  144226. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  144227. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  144228. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  144229. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  144230. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  144231. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  144232. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  144233. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  144234. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  144235. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  144236. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  144237. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  144238. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  144239. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  144240. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  144241. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  144242. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  144243. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  144244. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  144245. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  144246. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  144247. 16,
  144248. };
  144249. static float _vq_quantthresh__8u0__p3_0[] = {
  144250. -1.5, -0.5, 0.5, 1.5,
  144251. };
  144252. static long _vq_quantmap__8u0__p3_0[] = {
  144253. 3, 1, 0, 2, 4,
  144254. };
  144255. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  144256. _vq_quantthresh__8u0__p3_0,
  144257. _vq_quantmap__8u0__p3_0,
  144258. 5,
  144259. 5
  144260. };
  144261. static static_codebook _8u0__p3_0 = {
  144262. 4, 625,
  144263. _vq_lengthlist__8u0__p3_0,
  144264. 1, -533725184, 1611661312, 3, 0,
  144265. _vq_quantlist__8u0__p3_0,
  144266. NULL,
  144267. &_vq_auxt__8u0__p3_0,
  144268. NULL,
  144269. 0
  144270. };
  144271. static long _vq_quantlist__8u0__p4_0[] = {
  144272. 2,
  144273. 1,
  144274. 3,
  144275. 0,
  144276. 4,
  144277. };
  144278. static long _vq_lengthlist__8u0__p4_0[] = {
  144279. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  144280. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  144281. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  144282. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  144283. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  144284. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  144285. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  144286. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  144287. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  144288. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  144289. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  144290. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  144291. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  144292. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  144293. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  144294. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  144295. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  144296. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  144297. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  144298. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  144299. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  144300. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  144301. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  144302. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  144303. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  144304. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  144305. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  144306. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  144307. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  144308. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  144309. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  144310. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  144311. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  144312. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  144313. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  144314. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  144315. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  144316. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  144317. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  144318. 12,
  144319. };
  144320. static float _vq_quantthresh__8u0__p4_0[] = {
  144321. -1.5, -0.5, 0.5, 1.5,
  144322. };
  144323. static long _vq_quantmap__8u0__p4_0[] = {
  144324. 3, 1, 0, 2, 4,
  144325. };
  144326. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  144327. _vq_quantthresh__8u0__p4_0,
  144328. _vq_quantmap__8u0__p4_0,
  144329. 5,
  144330. 5
  144331. };
  144332. static static_codebook _8u0__p4_0 = {
  144333. 4, 625,
  144334. _vq_lengthlist__8u0__p4_0,
  144335. 1, -533725184, 1611661312, 3, 0,
  144336. _vq_quantlist__8u0__p4_0,
  144337. NULL,
  144338. &_vq_auxt__8u0__p4_0,
  144339. NULL,
  144340. 0
  144341. };
  144342. static long _vq_quantlist__8u0__p5_0[] = {
  144343. 4,
  144344. 3,
  144345. 5,
  144346. 2,
  144347. 6,
  144348. 1,
  144349. 7,
  144350. 0,
  144351. 8,
  144352. };
  144353. static long _vq_lengthlist__8u0__p5_0[] = {
  144354. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  144355. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  144356. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  144357. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  144358. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  144359. 12,
  144360. };
  144361. static float _vq_quantthresh__8u0__p5_0[] = {
  144362. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144363. };
  144364. static long _vq_quantmap__8u0__p5_0[] = {
  144365. 7, 5, 3, 1, 0, 2, 4, 6,
  144366. 8,
  144367. };
  144368. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  144369. _vq_quantthresh__8u0__p5_0,
  144370. _vq_quantmap__8u0__p5_0,
  144371. 9,
  144372. 9
  144373. };
  144374. static static_codebook _8u0__p5_0 = {
  144375. 2, 81,
  144376. _vq_lengthlist__8u0__p5_0,
  144377. 1, -531628032, 1611661312, 4, 0,
  144378. _vq_quantlist__8u0__p5_0,
  144379. NULL,
  144380. &_vq_auxt__8u0__p5_0,
  144381. NULL,
  144382. 0
  144383. };
  144384. static long _vq_quantlist__8u0__p6_0[] = {
  144385. 6,
  144386. 5,
  144387. 7,
  144388. 4,
  144389. 8,
  144390. 3,
  144391. 9,
  144392. 2,
  144393. 10,
  144394. 1,
  144395. 11,
  144396. 0,
  144397. 12,
  144398. };
  144399. static long _vq_lengthlist__8u0__p6_0[] = {
  144400. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  144401. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  144402. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  144403. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  144404. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  144405. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  144406. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  144407. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  144408. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  144409. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  144410. 16, 0,15, 0,17, 0, 0, 0, 0,
  144411. };
  144412. static float _vq_quantthresh__8u0__p6_0[] = {
  144413. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144414. 12.5, 17.5, 22.5, 27.5,
  144415. };
  144416. static long _vq_quantmap__8u0__p6_0[] = {
  144417. 11, 9, 7, 5, 3, 1, 0, 2,
  144418. 4, 6, 8, 10, 12,
  144419. };
  144420. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  144421. _vq_quantthresh__8u0__p6_0,
  144422. _vq_quantmap__8u0__p6_0,
  144423. 13,
  144424. 13
  144425. };
  144426. static static_codebook _8u0__p6_0 = {
  144427. 2, 169,
  144428. _vq_lengthlist__8u0__p6_0,
  144429. 1, -526516224, 1616117760, 4, 0,
  144430. _vq_quantlist__8u0__p6_0,
  144431. NULL,
  144432. &_vq_auxt__8u0__p6_0,
  144433. NULL,
  144434. 0
  144435. };
  144436. static long _vq_quantlist__8u0__p6_1[] = {
  144437. 2,
  144438. 1,
  144439. 3,
  144440. 0,
  144441. 4,
  144442. };
  144443. static long _vq_lengthlist__8u0__p6_1[] = {
  144444. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  144445. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  144446. };
  144447. static float _vq_quantthresh__8u0__p6_1[] = {
  144448. -1.5, -0.5, 0.5, 1.5,
  144449. };
  144450. static long _vq_quantmap__8u0__p6_1[] = {
  144451. 3, 1, 0, 2, 4,
  144452. };
  144453. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  144454. _vq_quantthresh__8u0__p6_1,
  144455. _vq_quantmap__8u0__p6_1,
  144456. 5,
  144457. 5
  144458. };
  144459. static static_codebook _8u0__p6_1 = {
  144460. 2, 25,
  144461. _vq_lengthlist__8u0__p6_1,
  144462. 1, -533725184, 1611661312, 3, 0,
  144463. _vq_quantlist__8u0__p6_1,
  144464. NULL,
  144465. &_vq_auxt__8u0__p6_1,
  144466. NULL,
  144467. 0
  144468. };
  144469. static long _vq_quantlist__8u0__p7_0[] = {
  144470. 1,
  144471. 0,
  144472. 2,
  144473. };
  144474. static long _vq_lengthlist__8u0__p7_0[] = {
  144475. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144476. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144477. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  144478. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  144479. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  144480. 7,
  144481. };
  144482. static float _vq_quantthresh__8u0__p7_0[] = {
  144483. -157.5, 157.5,
  144484. };
  144485. static long _vq_quantmap__8u0__p7_0[] = {
  144486. 1, 0, 2,
  144487. };
  144488. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  144489. _vq_quantthresh__8u0__p7_0,
  144490. _vq_quantmap__8u0__p7_0,
  144491. 3,
  144492. 3
  144493. };
  144494. static static_codebook _8u0__p7_0 = {
  144495. 4, 81,
  144496. _vq_lengthlist__8u0__p7_0,
  144497. 1, -518803456, 1628680192, 2, 0,
  144498. _vq_quantlist__8u0__p7_0,
  144499. NULL,
  144500. &_vq_auxt__8u0__p7_0,
  144501. NULL,
  144502. 0
  144503. };
  144504. static long _vq_quantlist__8u0__p7_1[] = {
  144505. 7,
  144506. 6,
  144507. 8,
  144508. 5,
  144509. 9,
  144510. 4,
  144511. 10,
  144512. 3,
  144513. 11,
  144514. 2,
  144515. 12,
  144516. 1,
  144517. 13,
  144518. 0,
  144519. 14,
  144520. };
  144521. static long _vq_lengthlist__8u0__p7_1[] = {
  144522. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  144523. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  144524. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  144525. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  144526. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  144527. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  144528. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144529. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144530. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144531. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144532. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144533. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144534. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  144535. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144536. 10,
  144537. };
  144538. static float _vq_quantthresh__8u0__p7_1[] = {
  144539. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  144540. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  144541. };
  144542. static long _vq_quantmap__8u0__p7_1[] = {
  144543. 13, 11, 9, 7, 5, 3, 1, 0,
  144544. 2, 4, 6, 8, 10, 12, 14,
  144545. };
  144546. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  144547. _vq_quantthresh__8u0__p7_1,
  144548. _vq_quantmap__8u0__p7_1,
  144549. 15,
  144550. 15
  144551. };
  144552. static static_codebook _8u0__p7_1 = {
  144553. 2, 225,
  144554. _vq_lengthlist__8u0__p7_1,
  144555. 1, -520986624, 1620377600, 4, 0,
  144556. _vq_quantlist__8u0__p7_1,
  144557. NULL,
  144558. &_vq_auxt__8u0__p7_1,
  144559. NULL,
  144560. 0
  144561. };
  144562. static long _vq_quantlist__8u0__p7_2[] = {
  144563. 10,
  144564. 9,
  144565. 11,
  144566. 8,
  144567. 12,
  144568. 7,
  144569. 13,
  144570. 6,
  144571. 14,
  144572. 5,
  144573. 15,
  144574. 4,
  144575. 16,
  144576. 3,
  144577. 17,
  144578. 2,
  144579. 18,
  144580. 1,
  144581. 19,
  144582. 0,
  144583. 20,
  144584. };
  144585. static long _vq_lengthlist__8u0__p7_2[] = {
  144586. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  144587. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  144588. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  144589. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  144590. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  144591. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  144592. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  144593. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  144594. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  144595. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  144596. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  144597. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  144598. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  144599. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  144600. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  144601. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  144602. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  144603. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  144604. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  144605. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  144606. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  144607. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  144608. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  144609. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  144610. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  144611. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  144612. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  144613. 11,12,11,11,11,10,10,11,11,
  144614. };
  144615. static float _vq_quantthresh__8u0__p7_2[] = {
  144616. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  144617. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  144618. 6.5, 7.5, 8.5, 9.5,
  144619. };
  144620. static long _vq_quantmap__8u0__p7_2[] = {
  144621. 19, 17, 15, 13, 11, 9, 7, 5,
  144622. 3, 1, 0, 2, 4, 6, 8, 10,
  144623. 12, 14, 16, 18, 20,
  144624. };
  144625. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  144626. _vq_quantthresh__8u0__p7_2,
  144627. _vq_quantmap__8u0__p7_2,
  144628. 21,
  144629. 21
  144630. };
  144631. static static_codebook _8u0__p7_2 = {
  144632. 2, 441,
  144633. _vq_lengthlist__8u0__p7_2,
  144634. 1, -529268736, 1611661312, 5, 0,
  144635. _vq_quantlist__8u0__p7_2,
  144636. NULL,
  144637. &_vq_auxt__8u0__p7_2,
  144638. NULL,
  144639. 0
  144640. };
  144641. static long _huff_lengthlist__8u0__single[] = {
  144642. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  144643. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  144644. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  144645. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  144646. };
  144647. static static_codebook _huff_book__8u0__single = {
  144648. 2, 64,
  144649. _huff_lengthlist__8u0__single,
  144650. 0, 0, 0, 0, 0,
  144651. NULL,
  144652. NULL,
  144653. NULL,
  144654. NULL,
  144655. 0
  144656. };
  144657. static long _vq_quantlist__8u1__p1_0[] = {
  144658. 1,
  144659. 0,
  144660. 2,
  144661. };
  144662. static long _vq_lengthlist__8u1__p1_0[] = {
  144663. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  144664. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  144665. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  144666. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  144667. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  144668. 10,
  144669. };
  144670. static float _vq_quantthresh__8u1__p1_0[] = {
  144671. -0.5, 0.5,
  144672. };
  144673. static long _vq_quantmap__8u1__p1_0[] = {
  144674. 1, 0, 2,
  144675. };
  144676. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  144677. _vq_quantthresh__8u1__p1_0,
  144678. _vq_quantmap__8u1__p1_0,
  144679. 3,
  144680. 3
  144681. };
  144682. static static_codebook _8u1__p1_0 = {
  144683. 4, 81,
  144684. _vq_lengthlist__8u1__p1_0,
  144685. 1, -535822336, 1611661312, 2, 0,
  144686. _vq_quantlist__8u1__p1_0,
  144687. NULL,
  144688. &_vq_auxt__8u1__p1_0,
  144689. NULL,
  144690. 0
  144691. };
  144692. static long _vq_quantlist__8u1__p2_0[] = {
  144693. 1,
  144694. 0,
  144695. 2,
  144696. };
  144697. static long _vq_lengthlist__8u1__p2_0[] = {
  144698. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  144699. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  144700. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  144701. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  144702. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  144703. 7,
  144704. };
  144705. static float _vq_quantthresh__8u1__p2_0[] = {
  144706. -0.5, 0.5,
  144707. };
  144708. static long _vq_quantmap__8u1__p2_0[] = {
  144709. 1, 0, 2,
  144710. };
  144711. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  144712. _vq_quantthresh__8u1__p2_0,
  144713. _vq_quantmap__8u1__p2_0,
  144714. 3,
  144715. 3
  144716. };
  144717. static static_codebook _8u1__p2_0 = {
  144718. 4, 81,
  144719. _vq_lengthlist__8u1__p2_0,
  144720. 1, -535822336, 1611661312, 2, 0,
  144721. _vq_quantlist__8u1__p2_0,
  144722. NULL,
  144723. &_vq_auxt__8u1__p2_0,
  144724. NULL,
  144725. 0
  144726. };
  144727. static long _vq_quantlist__8u1__p3_0[] = {
  144728. 2,
  144729. 1,
  144730. 3,
  144731. 0,
  144732. 4,
  144733. };
  144734. static long _vq_lengthlist__8u1__p3_0[] = {
  144735. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  144736. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  144737. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  144738. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  144739. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  144740. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  144741. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  144742. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  144743. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  144744. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  144745. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  144746. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  144747. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  144748. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  144749. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  144750. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  144751. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  144752. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  144753. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  144754. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  144755. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  144756. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  144757. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  144758. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  144759. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  144760. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  144761. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  144762. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  144763. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  144764. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  144765. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  144766. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  144767. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  144768. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  144769. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  144770. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  144771. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  144772. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  144773. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  144774. 16,
  144775. };
  144776. static float _vq_quantthresh__8u1__p3_0[] = {
  144777. -1.5, -0.5, 0.5, 1.5,
  144778. };
  144779. static long _vq_quantmap__8u1__p3_0[] = {
  144780. 3, 1, 0, 2, 4,
  144781. };
  144782. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  144783. _vq_quantthresh__8u1__p3_0,
  144784. _vq_quantmap__8u1__p3_0,
  144785. 5,
  144786. 5
  144787. };
  144788. static static_codebook _8u1__p3_0 = {
  144789. 4, 625,
  144790. _vq_lengthlist__8u1__p3_0,
  144791. 1, -533725184, 1611661312, 3, 0,
  144792. _vq_quantlist__8u1__p3_0,
  144793. NULL,
  144794. &_vq_auxt__8u1__p3_0,
  144795. NULL,
  144796. 0
  144797. };
  144798. static long _vq_quantlist__8u1__p4_0[] = {
  144799. 2,
  144800. 1,
  144801. 3,
  144802. 0,
  144803. 4,
  144804. };
  144805. static long _vq_lengthlist__8u1__p4_0[] = {
  144806. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  144807. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  144808. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  144809. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  144810. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  144811. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  144812. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  144813. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  144814. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  144815. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  144816. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  144817. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  144818. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  144819. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  144820. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  144821. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  144822. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  144823. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  144824. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  144825. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  144826. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  144827. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  144828. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  144829. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  144830. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  144831. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  144832. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  144833. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  144834. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  144835. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  144836. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  144837. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  144838. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  144839. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  144840. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  144841. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  144842. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  144843. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  144844. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  144845. 10,
  144846. };
  144847. static float _vq_quantthresh__8u1__p4_0[] = {
  144848. -1.5, -0.5, 0.5, 1.5,
  144849. };
  144850. static long _vq_quantmap__8u1__p4_0[] = {
  144851. 3, 1, 0, 2, 4,
  144852. };
  144853. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  144854. _vq_quantthresh__8u1__p4_0,
  144855. _vq_quantmap__8u1__p4_0,
  144856. 5,
  144857. 5
  144858. };
  144859. static static_codebook _8u1__p4_0 = {
  144860. 4, 625,
  144861. _vq_lengthlist__8u1__p4_0,
  144862. 1, -533725184, 1611661312, 3, 0,
  144863. _vq_quantlist__8u1__p4_0,
  144864. NULL,
  144865. &_vq_auxt__8u1__p4_0,
  144866. NULL,
  144867. 0
  144868. };
  144869. static long _vq_quantlist__8u1__p5_0[] = {
  144870. 4,
  144871. 3,
  144872. 5,
  144873. 2,
  144874. 6,
  144875. 1,
  144876. 7,
  144877. 0,
  144878. 8,
  144879. };
  144880. static long _vq_lengthlist__8u1__p5_0[] = {
  144881. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  144882. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  144883. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  144884. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  144885. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  144886. 13,
  144887. };
  144888. static float _vq_quantthresh__8u1__p5_0[] = {
  144889. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144890. };
  144891. static long _vq_quantmap__8u1__p5_0[] = {
  144892. 7, 5, 3, 1, 0, 2, 4, 6,
  144893. 8,
  144894. };
  144895. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  144896. _vq_quantthresh__8u1__p5_0,
  144897. _vq_quantmap__8u1__p5_0,
  144898. 9,
  144899. 9
  144900. };
  144901. static static_codebook _8u1__p5_0 = {
  144902. 2, 81,
  144903. _vq_lengthlist__8u1__p5_0,
  144904. 1, -531628032, 1611661312, 4, 0,
  144905. _vq_quantlist__8u1__p5_0,
  144906. NULL,
  144907. &_vq_auxt__8u1__p5_0,
  144908. NULL,
  144909. 0
  144910. };
  144911. static long _vq_quantlist__8u1__p6_0[] = {
  144912. 4,
  144913. 3,
  144914. 5,
  144915. 2,
  144916. 6,
  144917. 1,
  144918. 7,
  144919. 0,
  144920. 8,
  144921. };
  144922. static long _vq_lengthlist__8u1__p6_0[] = {
  144923. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  144924. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  144925. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  144926. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  144927. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  144928. 10,
  144929. };
  144930. static float _vq_quantthresh__8u1__p6_0[] = {
  144931. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144932. };
  144933. static long _vq_quantmap__8u1__p6_0[] = {
  144934. 7, 5, 3, 1, 0, 2, 4, 6,
  144935. 8,
  144936. };
  144937. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  144938. _vq_quantthresh__8u1__p6_0,
  144939. _vq_quantmap__8u1__p6_0,
  144940. 9,
  144941. 9
  144942. };
  144943. static static_codebook _8u1__p6_0 = {
  144944. 2, 81,
  144945. _vq_lengthlist__8u1__p6_0,
  144946. 1, -531628032, 1611661312, 4, 0,
  144947. _vq_quantlist__8u1__p6_0,
  144948. NULL,
  144949. &_vq_auxt__8u1__p6_0,
  144950. NULL,
  144951. 0
  144952. };
  144953. static long _vq_quantlist__8u1__p7_0[] = {
  144954. 1,
  144955. 0,
  144956. 2,
  144957. };
  144958. static long _vq_lengthlist__8u1__p7_0[] = {
  144959. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  144960. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  144961. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  144962. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  144963. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  144964. 11,
  144965. };
  144966. static float _vq_quantthresh__8u1__p7_0[] = {
  144967. -5.5, 5.5,
  144968. };
  144969. static long _vq_quantmap__8u1__p7_0[] = {
  144970. 1, 0, 2,
  144971. };
  144972. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  144973. _vq_quantthresh__8u1__p7_0,
  144974. _vq_quantmap__8u1__p7_0,
  144975. 3,
  144976. 3
  144977. };
  144978. static static_codebook _8u1__p7_0 = {
  144979. 4, 81,
  144980. _vq_lengthlist__8u1__p7_0,
  144981. 1, -529137664, 1618345984, 2, 0,
  144982. _vq_quantlist__8u1__p7_0,
  144983. NULL,
  144984. &_vq_auxt__8u1__p7_0,
  144985. NULL,
  144986. 0
  144987. };
  144988. static long _vq_quantlist__8u1__p7_1[] = {
  144989. 5,
  144990. 4,
  144991. 6,
  144992. 3,
  144993. 7,
  144994. 2,
  144995. 8,
  144996. 1,
  144997. 9,
  144998. 0,
  144999. 10,
  145000. };
  145001. static long _vq_lengthlist__8u1__p7_1[] = {
  145002. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  145003. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  145004. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  145005. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145006. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  145007. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  145008. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  145009. 9, 9, 9, 9, 9,10,10,10,10,
  145010. };
  145011. static float _vq_quantthresh__8u1__p7_1[] = {
  145012. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145013. 3.5, 4.5,
  145014. };
  145015. static long _vq_quantmap__8u1__p7_1[] = {
  145016. 9, 7, 5, 3, 1, 0, 2, 4,
  145017. 6, 8, 10,
  145018. };
  145019. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  145020. _vq_quantthresh__8u1__p7_1,
  145021. _vq_quantmap__8u1__p7_1,
  145022. 11,
  145023. 11
  145024. };
  145025. static static_codebook _8u1__p7_1 = {
  145026. 2, 121,
  145027. _vq_lengthlist__8u1__p7_1,
  145028. 1, -531365888, 1611661312, 4, 0,
  145029. _vq_quantlist__8u1__p7_1,
  145030. NULL,
  145031. &_vq_auxt__8u1__p7_1,
  145032. NULL,
  145033. 0
  145034. };
  145035. static long _vq_quantlist__8u1__p8_0[] = {
  145036. 5,
  145037. 4,
  145038. 6,
  145039. 3,
  145040. 7,
  145041. 2,
  145042. 8,
  145043. 1,
  145044. 9,
  145045. 0,
  145046. 10,
  145047. };
  145048. static long _vq_lengthlist__8u1__p8_0[] = {
  145049. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  145050. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  145051. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  145052. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  145053. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  145054. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  145055. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  145056. 12,13,13,14,14,15,15,15,15,
  145057. };
  145058. static float _vq_quantthresh__8u1__p8_0[] = {
  145059. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  145060. 38.5, 49.5,
  145061. };
  145062. static long _vq_quantmap__8u1__p8_0[] = {
  145063. 9, 7, 5, 3, 1, 0, 2, 4,
  145064. 6, 8, 10,
  145065. };
  145066. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  145067. _vq_quantthresh__8u1__p8_0,
  145068. _vq_quantmap__8u1__p8_0,
  145069. 11,
  145070. 11
  145071. };
  145072. static static_codebook _8u1__p8_0 = {
  145073. 2, 121,
  145074. _vq_lengthlist__8u1__p8_0,
  145075. 1, -524582912, 1618345984, 4, 0,
  145076. _vq_quantlist__8u1__p8_0,
  145077. NULL,
  145078. &_vq_auxt__8u1__p8_0,
  145079. NULL,
  145080. 0
  145081. };
  145082. static long _vq_quantlist__8u1__p8_1[] = {
  145083. 5,
  145084. 4,
  145085. 6,
  145086. 3,
  145087. 7,
  145088. 2,
  145089. 8,
  145090. 1,
  145091. 9,
  145092. 0,
  145093. 10,
  145094. };
  145095. static long _vq_lengthlist__8u1__p8_1[] = {
  145096. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  145097. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  145098. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  145099. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  145100. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145101. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  145102. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  145103. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145104. };
  145105. static float _vq_quantthresh__8u1__p8_1[] = {
  145106. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145107. 3.5, 4.5,
  145108. };
  145109. static long _vq_quantmap__8u1__p8_1[] = {
  145110. 9, 7, 5, 3, 1, 0, 2, 4,
  145111. 6, 8, 10,
  145112. };
  145113. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  145114. _vq_quantthresh__8u1__p8_1,
  145115. _vq_quantmap__8u1__p8_1,
  145116. 11,
  145117. 11
  145118. };
  145119. static static_codebook _8u1__p8_1 = {
  145120. 2, 121,
  145121. _vq_lengthlist__8u1__p8_1,
  145122. 1, -531365888, 1611661312, 4, 0,
  145123. _vq_quantlist__8u1__p8_1,
  145124. NULL,
  145125. &_vq_auxt__8u1__p8_1,
  145126. NULL,
  145127. 0
  145128. };
  145129. static long _vq_quantlist__8u1__p9_0[] = {
  145130. 7,
  145131. 6,
  145132. 8,
  145133. 5,
  145134. 9,
  145135. 4,
  145136. 10,
  145137. 3,
  145138. 11,
  145139. 2,
  145140. 12,
  145141. 1,
  145142. 13,
  145143. 0,
  145144. 14,
  145145. };
  145146. static long _vq_lengthlist__8u1__p9_0[] = {
  145147. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  145148. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  145149. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145150. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145151. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145152. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145153. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145154. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145155. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145156. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145157. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145158. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145159. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  145160. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145161. 10,
  145162. };
  145163. static float _vq_quantthresh__8u1__p9_0[] = {
  145164. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  145165. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  145166. };
  145167. static long _vq_quantmap__8u1__p9_0[] = {
  145168. 13, 11, 9, 7, 5, 3, 1, 0,
  145169. 2, 4, 6, 8, 10, 12, 14,
  145170. };
  145171. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  145172. _vq_quantthresh__8u1__p9_0,
  145173. _vq_quantmap__8u1__p9_0,
  145174. 15,
  145175. 15
  145176. };
  145177. static static_codebook _8u1__p9_0 = {
  145178. 2, 225,
  145179. _vq_lengthlist__8u1__p9_0,
  145180. 1, -514071552, 1627381760, 4, 0,
  145181. _vq_quantlist__8u1__p9_0,
  145182. NULL,
  145183. &_vq_auxt__8u1__p9_0,
  145184. NULL,
  145185. 0
  145186. };
  145187. static long _vq_quantlist__8u1__p9_1[] = {
  145188. 7,
  145189. 6,
  145190. 8,
  145191. 5,
  145192. 9,
  145193. 4,
  145194. 10,
  145195. 3,
  145196. 11,
  145197. 2,
  145198. 12,
  145199. 1,
  145200. 13,
  145201. 0,
  145202. 14,
  145203. };
  145204. static long _vq_lengthlist__8u1__p9_1[] = {
  145205. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  145206. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  145207. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  145208. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  145209. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  145210. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  145211. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  145212. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  145213. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  145214. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  145215. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  145216. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  145217. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  145218. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  145219. 13,
  145220. };
  145221. static float _vq_quantthresh__8u1__p9_1[] = {
  145222. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  145223. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  145224. };
  145225. static long _vq_quantmap__8u1__p9_1[] = {
  145226. 13, 11, 9, 7, 5, 3, 1, 0,
  145227. 2, 4, 6, 8, 10, 12, 14,
  145228. };
  145229. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  145230. _vq_quantthresh__8u1__p9_1,
  145231. _vq_quantmap__8u1__p9_1,
  145232. 15,
  145233. 15
  145234. };
  145235. static static_codebook _8u1__p9_1 = {
  145236. 2, 225,
  145237. _vq_lengthlist__8u1__p9_1,
  145238. 1, -522338304, 1620115456, 4, 0,
  145239. _vq_quantlist__8u1__p9_1,
  145240. NULL,
  145241. &_vq_auxt__8u1__p9_1,
  145242. NULL,
  145243. 0
  145244. };
  145245. static long _vq_quantlist__8u1__p9_2[] = {
  145246. 8,
  145247. 7,
  145248. 9,
  145249. 6,
  145250. 10,
  145251. 5,
  145252. 11,
  145253. 4,
  145254. 12,
  145255. 3,
  145256. 13,
  145257. 2,
  145258. 14,
  145259. 1,
  145260. 15,
  145261. 0,
  145262. 16,
  145263. };
  145264. static long _vq_lengthlist__8u1__p9_2[] = {
  145265. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145266. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  145267. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145268. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  145269. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  145270. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  145271. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  145272. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  145273. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  145274. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  145275. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  145276. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  145277. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  145278. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  145279. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  145280. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  145281. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145282. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145283. 10,
  145284. };
  145285. static float _vq_quantthresh__8u1__p9_2[] = {
  145286. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145287. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145288. };
  145289. static long _vq_quantmap__8u1__p9_2[] = {
  145290. 15, 13, 11, 9, 7, 5, 3, 1,
  145291. 0, 2, 4, 6, 8, 10, 12, 14,
  145292. 16,
  145293. };
  145294. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  145295. _vq_quantthresh__8u1__p9_2,
  145296. _vq_quantmap__8u1__p9_2,
  145297. 17,
  145298. 17
  145299. };
  145300. static static_codebook _8u1__p9_2 = {
  145301. 2, 289,
  145302. _vq_lengthlist__8u1__p9_2,
  145303. 1, -529530880, 1611661312, 5, 0,
  145304. _vq_quantlist__8u1__p9_2,
  145305. NULL,
  145306. &_vq_auxt__8u1__p9_2,
  145307. NULL,
  145308. 0
  145309. };
  145310. static long _huff_lengthlist__8u1__single[] = {
  145311. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  145312. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  145313. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  145314. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  145315. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  145316. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  145317. 13, 8, 8,15,
  145318. };
  145319. static static_codebook _huff_book__8u1__single = {
  145320. 2, 100,
  145321. _huff_lengthlist__8u1__single,
  145322. 0, 0, 0, 0, 0,
  145323. NULL,
  145324. NULL,
  145325. NULL,
  145326. NULL,
  145327. 0
  145328. };
  145329. static long _huff_lengthlist__44u0__long[] = {
  145330. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  145331. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  145332. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  145333. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  145334. };
  145335. static static_codebook _huff_book__44u0__long = {
  145336. 2, 64,
  145337. _huff_lengthlist__44u0__long,
  145338. 0, 0, 0, 0, 0,
  145339. NULL,
  145340. NULL,
  145341. NULL,
  145342. NULL,
  145343. 0
  145344. };
  145345. static long _vq_quantlist__44u0__p1_0[] = {
  145346. 1,
  145347. 0,
  145348. 2,
  145349. };
  145350. static long _vq_lengthlist__44u0__p1_0[] = {
  145351. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  145352. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  145353. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  145354. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  145355. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  145356. 13,
  145357. };
  145358. static float _vq_quantthresh__44u0__p1_0[] = {
  145359. -0.5, 0.5,
  145360. };
  145361. static long _vq_quantmap__44u0__p1_0[] = {
  145362. 1, 0, 2,
  145363. };
  145364. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  145365. _vq_quantthresh__44u0__p1_0,
  145366. _vq_quantmap__44u0__p1_0,
  145367. 3,
  145368. 3
  145369. };
  145370. static static_codebook _44u0__p1_0 = {
  145371. 4, 81,
  145372. _vq_lengthlist__44u0__p1_0,
  145373. 1, -535822336, 1611661312, 2, 0,
  145374. _vq_quantlist__44u0__p1_0,
  145375. NULL,
  145376. &_vq_auxt__44u0__p1_0,
  145377. NULL,
  145378. 0
  145379. };
  145380. static long _vq_quantlist__44u0__p2_0[] = {
  145381. 1,
  145382. 0,
  145383. 2,
  145384. };
  145385. static long _vq_lengthlist__44u0__p2_0[] = {
  145386. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  145387. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  145388. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  145389. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  145390. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  145391. 9,
  145392. };
  145393. static float _vq_quantthresh__44u0__p2_0[] = {
  145394. -0.5, 0.5,
  145395. };
  145396. static long _vq_quantmap__44u0__p2_0[] = {
  145397. 1, 0, 2,
  145398. };
  145399. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  145400. _vq_quantthresh__44u0__p2_0,
  145401. _vq_quantmap__44u0__p2_0,
  145402. 3,
  145403. 3
  145404. };
  145405. static static_codebook _44u0__p2_0 = {
  145406. 4, 81,
  145407. _vq_lengthlist__44u0__p2_0,
  145408. 1, -535822336, 1611661312, 2, 0,
  145409. _vq_quantlist__44u0__p2_0,
  145410. NULL,
  145411. &_vq_auxt__44u0__p2_0,
  145412. NULL,
  145413. 0
  145414. };
  145415. static long _vq_quantlist__44u0__p3_0[] = {
  145416. 2,
  145417. 1,
  145418. 3,
  145419. 0,
  145420. 4,
  145421. };
  145422. static long _vq_lengthlist__44u0__p3_0[] = {
  145423. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  145424. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  145425. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  145426. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  145427. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  145428. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  145429. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  145430. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  145431. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  145432. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  145433. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  145434. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  145435. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  145436. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  145437. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  145438. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  145439. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  145440. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  145441. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  145442. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  145443. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  145444. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  145445. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  145446. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  145447. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  145448. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  145449. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  145450. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  145451. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  145452. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  145453. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  145454. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  145455. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  145456. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  145457. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  145458. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  145459. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  145460. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  145461. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  145462. 19,
  145463. };
  145464. static float _vq_quantthresh__44u0__p3_0[] = {
  145465. -1.5, -0.5, 0.5, 1.5,
  145466. };
  145467. static long _vq_quantmap__44u0__p3_0[] = {
  145468. 3, 1, 0, 2, 4,
  145469. };
  145470. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  145471. _vq_quantthresh__44u0__p3_0,
  145472. _vq_quantmap__44u0__p3_0,
  145473. 5,
  145474. 5
  145475. };
  145476. static static_codebook _44u0__p3_0 = {
  145477. 4, 625,
  145478. _vq_lengthlist__44u0__p3_0,
  145479. 1, -533725184, 1611661312, 3, 0,
  145480. _vq_quantlist__44u0__p3_0,
  145481. NULL,
  145482. &_vq_auxt__44u0__p3_0,
  145483. NULL,
  145484. 0
  145485. };
  145486. static long _vq_quantlist__44u0__p4_0[] = {
  145487. 2,
  145488. 1,
  145489. 3,
  145490. 0,
  145491. 4,
  145492. };
  145493. static long _vq_lengthlist__44u0__p4_0[] = {
  145494. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  145495. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  145496. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  145497. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  145498. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  145499. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  145500. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  145501. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  145502. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  145503. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  145504. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  145505. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  145506. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  145507. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  145508. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  145509. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  145510. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  145511. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  145512. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  145513. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  145514. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  145515. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  145516. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  145517. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  145518. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  145519. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  145520. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  145521. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  145522. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  145523. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  145524. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  145525. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  145526. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  145527. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  145528. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  145529. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  145530. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  145531. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  145532. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  145533. 12,
  145534. };
  145535. static float _vq_quantthresh__44u0__p4_0[] = {
  145536. -1.5, -0.5, 0.5, 1.5,
  145537. };
  145538. static long _vq_quantmap__44u0__p4_0[] = {
  145539. 3, 1, 0, 2, 4,
  145540. };
  145541. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  145542. _vq_quantthresh__44u0__p4_0,
  145543. _vq_quantmap__44u0__p4_0,
  145544. 5,
  145545. 5
  145546. };
  145547. static static_codebook _44u0__p4_0 = {
  145548. 4, 625,
  145549. _vq_lengthlist__44u0__p4_0,
  145550. 1, -533725184, 1611661312, 3, 0,
  145551. _vq_quantlist__44u0__p4_0,
  145552. NULL,
  145553. &_vq_auxt__44u0__p4_0,
  145554. NULL,
  145555. 0
  145556. };
  145557. static long _vq_quantlist__44u0__p5_0[] = {
  145558. 4,
  145559. 3,
  145560. 5,
  145561. 2,
  145562. 6,
  145563. 1,
  145564. 7,
  145565. 0,
  145566. 8,
  145567. };
  145568. static long _vq_lengthlist__44u0__p5_0[] = {
  145569. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  145570. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  145571. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  145572. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  145573. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  145574. 12,
  145575. };
  145576. static float _vq_quantthresh__44u0__p5_0[] = {
  145577. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145578. };
  145579. static long _vq_quantmap__44u0__p5_0[] = {
  145580. 7, 5, 3, 1, 0, 2, 4, 6,
  145581. 8,
  145582. };
  145583. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  145584. _vq_quantthresh__44u0__p5_0,
  145585. _vq_quantmap__44u0__p5_0,
  145586. 9,
  145587. 9
  145588. };
  145589. static static_codebook _44u0__p5_0 = {
  145590. 2, 81,
  145591. _vq_lengthlist__44u0__p5_0,
  145592. 1, -531628032, 1611661312, 4, 0,
  145593. _vq_quantlist__44u0__p5_0,
  145594. NULL,
  145595. &_vq_auxt__44u0__p5_0,
  145596. NULL,
  145597. 0
  145598. };
  145599. static long _vq_quantlist__44u0__p6_0[] = {
  145600. 6,
  145601. 5,
  145602. 7,
  145603. 4,
  145604. 8,
  145605. 3,
  145606. 9,
  145607. 2,
  145608. 10,
  145609. 1,
  145610. 11,
  145611. 0,
  145612. 12,
  145613. };
  145614. static long _vq_lengthlist__44u0__p6_0[] = {
  145615. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  145616. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  145617. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  145618. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  145619. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  145620. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  145621. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  145622. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  145623. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  145624. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  145625. 15,17,16,17,18,17,17,18, 0,
  145626. };
  145627. static float _vq_quantthresh__44u0__p6_0[] = {
  145628. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  145629. 12.5, 17.5, 22.5, 27.5,
  145630. };
  145631. static long _vq_quantmap__44u0__p6_0[] = {
  145632. 11, 9, 7, 5, 3, 1, 0, 2,
  145633. 4, 6, 8, 10, 12,
  145634. };
  145635. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  145636. _vq_quantthresh__44u0__p6_0,
  145637. _vq_quantmap__44u0__p6_0,
  145638. 13,
  145639. 13
  145640. };
  145641. static static_codebook _44u0__p6_0 = {
  145642. 2, 169,
  145643. _vq_lengthlist__44u0__p6_0,
  145644. 1, -526516224, 1616117760, 4, 0,
  145645. _vq_quantlist__44u0__p6_0,
  145646. NULL,
  145647. &_vq_auxt__44u0__p6_0,
  145648. NULL,
  145649. 0
  145650. };
  145651. static long _vq_quantlist__44u0__p6_1[] = {
  145652. 2,
  145653. 1,
  145654. 3,
  145655. 0,
  145656. 4,
  145657. };
  145658. static long _vq_lengthlist__44u0__p6_1[] = {
  145659. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  145660. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  145661. };
  145662. static float _vq_quantthresh__44u0__p6_1[] = {
  145663. -1.5, -0.5, 0.5, 1.5,
  145664. };
  145665. static long _vq_quantmap__44u0__p6_1[] = {
  145666. 3, 1, 0, 2, 4,
  145667. };
  145668. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  145669. _vq_quantthresh__44u0__p6_1,
  145670. _vq_quantmap__44u0__p6_1,
  145671. 5,
  145672. 5
  145673. };
  145674. static static_codebook _44u0__p6_1 = {
  145675. 2, 25,
  145676. _vq_lengthlist__44u0__p6_1,
  145677. 1, -533725184, 1611661312, 3, 0,
  145678. _vq_quantlist__44u0__p6_1,
  145679. NULL,
  145680. &_vq_auxt__44u0__p6_1,
  145681. NULL,
  145682. 0
  145683. };
  145684. static long _vq_quantlist__44u0__p7_0[] = {
  145685. 2,
  145686. 1,
  145687. 3,
  145688. 0,
  145689. 4,
  145690. };
  145691. static long _vq_lengthlist__44u0__p7_0[] = {
  145692. 1, 4, 4,11,11, 9,11,11,11,11,11,11,11,11,11,11,
  145693. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145694. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145695. 11,11, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145696. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145697. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145698. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145699. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  145700. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145701. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145702. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145703. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145704. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145705. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145706. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145707. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145708. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145709. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145710. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145711. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145712. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145713. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145714. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145715. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145716. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145717. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145718. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145719. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145720. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145721. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145722. 11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
  145723. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145724. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145725. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145726. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145727. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145728. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145729. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145730. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145731. 10,
  145732. };
  145733. static float _vq_quantthresh__44u0__p7_0[] = {
  145734. -253.5, -84.5, 84.5, 253.5,
  145735. };
  145736. static long _vq_quantmap__44u0__p7_0[] = {
  145737. 3, 1, 0, 2, 4,
  145738. };
  145739. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  145740. _vq_quantthresh__44u0__p7_0,
  145741. _vq_quantmap__44u0__p7_0,
  145742. 5,
  145743. 5
  145744. };
  145745. static static_codebook _44u0__p7_0 = {
  145746. 4, 625,
  145747. _vq_lengthlist__44u0__p7_0,
  145748. 1, -518709248, 1626677248, 3, 0,
  145749. _vq_quantlist__44u0__p7_0,
  145750. NULL,
  145751. &_vq_auxt__44u0__p7_0,
  145752. NULL,
  145753. 0
  145754. };
  145755. static long _vq_quantlist__44u0__p7_1[] = {
  145756. 6,
  145757. 5,
  145758. 7,
  145759. 4,
  145760. 8,
  145761. 3,
  145762. 9,
  145763. 2,
  145764. 10,
  145765. 1,
  145766. 11,
  145767. 0,
  145768. 12,
  145769. };
  145770. static long _vq_lengthlist__44u0__p7_1[] = {
  145771. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  145772. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  145773. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  145774. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  145775. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  145776. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  145777. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  145778. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  145779. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  145780. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  145781. 15,15,15,15,15,15,15,15,15,
  145782. };
  145783. static float _vq_quantthresh__44u0__p7_1[] = {
  145784. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  145785. 32.5, 45.5, 58.5, 71.5,
  145786. };
  145787. static long _vq_quantmap__44u0__p7_1[] = {
  145788. 11, 9, 7, 5, 3, 1, 0, 2,
  145789. 4, 6, 8, 10, 12,
  145790. };
  145791. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  145792. _vq_quantthresh__44u0__p7_1,
  145793. _vq_quantmap__44u0__p7_1,
  145794. 13,
  145795. 13
  145796. };
  145797. static static_codebook _44u0__p7_1 = {
  145798. 2, 169,
  145799. _vq_lengthlist__44u0__p7_1,
  145800. 1, -523010048, 1618608128, 4, 0,
  145801. _vq_quantlist__44u0__p7_1,
  145802. NULL,
  145803. &_vq_auxt__44u0__p7_1,
  145804. NULL,
  145805. 0
  145806. };
  145807. static long _vq_quantlist__44u0__p7_2[] = {
  145808. 6,
  145809. 5,
  145810. 7,
  145811. 4,
  145812. 8,
  145813. 3,
  145814. 9,
  145815. 2,
  145816. 10,
  145817. 1,
  145818. 11,
  145819. 0,
  145820. 12,
  145821. };
  145822. static long _vq_lengthlist__44u0__p7_2[] = {
  145823. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  145824. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  145825. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  145826. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  145827. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  145828. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  145829. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  145830. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  145831. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  145832. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  145833. 9, 9, 9,10, 9, 9,10,10, 9,
  145834. };
  145835. static float _vq_quantthresh__44u0__p7_2[] = {
  145836. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  145837. 2.5, 3.5, 4.5, 5.5,
  145838. };
  145839. static long _vq_quantmap__44u0__p7_2[] = {
  145840. 11, 9, 7, 5, 3, 1, 0, 2,
  145841. 4, 6, 8, 10, 12,
  145842. };
  145843. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  145844. _vq_quantthresh__44u0__p7_2,
  145845. _vq_quantmap__44u0__p7_2,
  145846. 13,
  145847. 13
  145848. };
  145849. static static_codebook _44u0__p7_2 = {
  145850. 2, 169,
  145851. _vq_lengthlist__44u0__p7_2,
  145852. 1, -531103744, 1611661312, 4, 0,
  145853. _vq_quantlist__44u0__p7_2,
  145854. NULL,
  145855. &_vq_auxt__44u0__p7_2,
  145856. NULL,
  145857. 0
  145858. };
  145859. static long _huff_lengthlist__44u0__short[] = {
  145860. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  145861. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  145862. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  145863. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  145864. };
  145865. static static_codebook _huff_book__44u0__short = {
  145866. 2, 64,
  145867. _huff_lengthlist__44u0__short,
  145868. 0, 0, 0, 0, 0,
  145869. NULL,
  145870. NULL,
  145871. NULL,
  145872. NULL,
  145873. 0
  145874. };
  145875. static long _huff_lengthlist__44u1__long[] = {
  145876. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  145877. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  145878. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  145879. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  145880. };
  145881. static static_codebook _huff_book__44u1__long = {
  145882. 2, 64,
  145883. _huff_lengthlist__44u1__long,
  145884. 0, 0, 0, 0, 0,
  145885. NULL,
  145886. NULL,
  145887. NULL,
  145888. NULL,
  145889. 0
  145890. };
  145891. static long _vq_quantlist__44u1__p1_0[] = {
  145892. 1,
  145893. 0,
  145894. 2,
  145895. };
  145896. static long _vq_lengthlist__44u1__p1_0[] = {
  145897. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  145898. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  145899. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  145900. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  145901. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  145902. 13,
  145903. };
  145904. static float _vq_quantthresh__44u1__p1_0[] = {
  145905. -0.5, 0.5,
  145906. };
  145907. static long _vq_quantmap__44u1__p1_0[] = {
  145908. 1, 0, 2,
  145909. };
  145910. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  145911. _vq_quantthresh__44u1__p1_0,
  145912. _vq_quantmap__44u1__p1_0,
  145913. 3,
  145914. 3
  145915. };
  145916. static static_codebook _44u1__p1_0 = {
  145917. 4, 81,
  145918. _vq_lengthlist__44u1__p1_0,
  145919. 1, -535822336, 1611661312, 2, 0,
  145920. _vq_quantlist__44u1__p1_0,
  145921. NULL,
  145922. &_vq_auxt__44u1__p1_0,
  145923. NULL,
  145924. 0
  145925. };
  145926. static long _vq_quantlist__44u1__p2_0[] = {
  145927. 1,
  145928. 0,
  145929. 2,
  145930. };
  145931. static long _vq_lengthlist__44u1__p2_0[] = {
  145932. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  145933. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  145934. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  145935. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  145936. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  145937. 9,
  145938. };
  145939. static float _vq_quantthresh__44u1__p2_0[] = {
  145940. -0.5, 0.5,
  145941. };
  145942. static long _vq_quantmap__44u1__p2_0[] = {
  145943. 1, 0, 2,
  145944. };
  145945. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  145946. _vq_quantthresh__44u1__p2_0,
  145947. _vq_quantmap__44u1__p2_0,
  145948. 3,
  145949. 3
  145950. };
  145951. static static_codebook _44u1__p2_0 = {
  145952. 4, 81,
  145953. _vq_lengthlist__44u1__p2_0,
  145954. 1, -535822336, 1611661312, 2, 0,
  145955. _vq_quantlist__44u1__p2_0,
  145956. NULL,
  145957. &_vq_auxt__44u1__p2_0,
  145958. NULL,
  145959. 0
  145960. };
  145961. static long _vq_quantlist__44u1__p3_0[] = {
  145962. 2,
  145963. 1,
  145964. 3,
  145965. 0,
  145966. 4,
  145967. };
  145968. static long _vq_lengthlist__44u1__p3_0[] = {
  145969. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  145970. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  145971. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  145972. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  145973. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  145974. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  145975. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  145976. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  145977. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  145978. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  145979. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  145980. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  145981. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  145982. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  145983. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  145984. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  145985. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  145986. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  145987. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  145988. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  145989. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  145990. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  145991. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  145992. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  145993. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  145994. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  145995. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  145996. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  145997. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  145998. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  145999. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  146000. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  146001. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  146002. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  146003. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  146004. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  146005. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  146006. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  146007. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  146008. 19,
  146009. };
  146010. static float _vq_quantthresh__44u1__p3_0[] = {
  146011. -1.5, -0.5, 0.5, 1.5,
  146012. };
  146013. static long _vq_quantmap__44u1__p3_0[] = {
  146014. 3, 1, 0, 2, 4,
  146015. };
  146016. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  146017. _vq_quantthresh__44u1__p3_0,
  146018. _vq_quantmap__44u1__p3_0,
  146019. 5,
  146020. 5
  146021. };
  146022. static static_codebook _44u1__p3_0 = {
  146023. 4, 625,
  146024. _vq_lengthlist__44u1__p3_0,
  146025. 1, -533725184, 1611661312, 3, 0,
  146026. _vq_quantlist__44u1__p3_0,
  146027. NULL,
  146028. &_vq_auxt__44u1__p3_0,
  146029. NULL,
  146030. 0
  146031. };
  146032. static long _vq_quantlist__44u1__p4_0[] = {
  146033. 2,
  146034. 1,
  146035. 3,
  146036. 0,
  146037. 4,
  146038. };
  146039. static long _vq_lengthlist__44u1__p4_0[] = {
  146040. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  146041. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  146042. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  146043. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  146044. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  146045. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  146046. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  146047. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  146048. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  146049. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  146050. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  146051. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146052. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  146053. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  146054. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  146055. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  146056. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  146057. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  146058. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  146059. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  146060. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  146061. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  146062. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  146063. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  146064. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  146065. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  146066. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  146067. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  146068. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  146069. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  146070. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  146071. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  146072. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  146073. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  146074. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  146075. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  146076. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  146077. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  146078. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  146079. 12,
  146080. };
  146081. static float _vq_quantthresh__44u1__p4_0[] = {
  146082. -1.5, -0.5, 0.5, 1.5,
  146083. };
  146084. static long _vq_quantmap__44u1__p4_0[] = {
  146085. 3, 1, 0, 2, 4,
  146086. };
  146087. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  146088. _vq_quantthresh__44u1__p4_0,
  146089. _vq_quantmap__44u1__p4_0,
  146090. 5,
  146091. 5
  146092. };
  146093. static static_codebook _44u1__p4_0 = {
  146094. 4, 625,
  146095. _vq_lengthlist__44u1__p4_0,
  146096. 1, -533725184, 1611661312, 3, 0,
  146097. _vq_quantlist__44u1__p4_0,
  146098. NULL,
  146099. &_vq_auxt__44u1__p4_0,
  146100. NULL,
  146101. 0
  146102. };
  146103. static long _vq_quantlist__44u1__p5_0[] = {
  146104. 4,
  146105. 3,
  146106. 5,
  146107. 2,
  146108. 6,
  146109. 1,
  146110. 7,
  146111. 0,
  146112. 8,
  146113. };
  146114. static long _vq_lengthlist__44u1__p5_0[] = {
  146115. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  146116. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  146117. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  146118. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  146119. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  146120. 12,
  146121. };
  146122. static float _vq_quantthresh__44u1__p5_0[] = {
  146123. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146124. };
  146125. static long _vq_quantmap__44u1__p5_0[] = {
  146126. 7, 5, 3, 1, 0, 2, 4, 6,
  146127. 8,
  146128. };
  146129. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  146130. _vq_quantthresh__44u1__p5_0,
  146131. _vq_quantmap__44u1__p5_0,
  146132. 9,
  146133. 9
  146134. };
  146135. static static_codebook _44u1__p5_0 = {
  146136. 2, 81,
  146137. _vq_lengthlist__44u1__p5_0,
  146138. 1, -531628032, 1611661312, 4, 0,
  146139. _vq_quantlist__44u1__p5_0,
  146140. NULL,
  146141. &_vq_auxt__44u1__p5_0,
  146142. NULL,
  146143. 0
  146144. };
  146145. static long _vq_quantlist__44u1__p6_0[] = {
  146146. 6,
  146147. 5,
  146148. 7,
  146149. 4,
  146150. 8,
  146151. 3,
  146152. 9,
  146153. 2,
  146154. 10,
  146155. 1,
  146156. 11,
  146157. 0,
  146158. 12,
  146159. };
  146160. static long _vq_lengthlist__44u1__p6_0[] = {
  146161. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  146162. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  146163. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  146164. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  146165. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  146166. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  146167. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  146168. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  146169. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  146170. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  146171. 15,17,16,17,18,17,17,18, 0,
  146172. };
  146173. static float _vq_quantthresh__44u1__p6_0[] = {
  146174. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146175. 12.5, 17.5, 22.5, 27.5,
  146176. };
  146177. static long _vq_quantmap__44u1__p6_0[] = {
  146178. 11, 9, 7, 5, 3, 1, 0, 2,
  146179. 4, 6, 8, 10, 12,
  146180. };
  146181. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  146182. _vq_quantthresh__44u1__p6_0,
  146183. _vq_quantmap__44u1__p6_0,
  146184. 13,
  146185. 13
  146186. };
  146187. static static_codebook _44u1__p6_0 = {
  146188. 2, 169,
  146189. _vq_lengthlist__44u1__p6_0,
  146190. 1, -526516224, 1616117760, 4, 0,
  146191. _vq_quantlist__44u1__p6_0,
  146192. NULL,
  146193. &_vq_auxt__44u1__p6_0,
  146194. NULL,
  146195. 0
  146196. };
  146197. static long _vq_quantlist__44u1__p6_1[] = {
  146198. 2,
  146199. 1,
  146200. 3,
  146201. 0,
  146202. 4,
  146203. };
  146204. static long _vq_lengthlist__44u1__p6_1[] = {
  146205. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  146206. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  146207. };
  146208. static float _vq_quantthresh__44u1__p6_1[] = {
  146209. -1.5, -0.5, 0.5, 1.5,
  146210. };
  146211. static long _vq_quantmap__44u1__p6_1[] = {
  146212. 3, 1, 0, 2, 4,
  146213. };
  146214. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  146215. _vq_quantthresh__44u1__p6_1,
  146216. _vq_quantmap__44u1__p6_1,
  146217. 5,
  146218. 5
  146219. };
  146220. static static_codebook _44u1__p6_1 = {
  146221. 2, 25,
  146222. _vq_lengthlist__44u1__p6_1,
  146223. 1, -533725184, 1611661312, 3, 0,
  146224. _vq_quantlist__44u1__p6_1,
  146225. NULL,
  146226. &_vq_auxt__44u1__p6_1,
  146227. NULL,
  146228. 0
  146229. };
  146230. static long _vq_quantlist__44u1__p7_0[] = {
  146231. 3,
  146232. 2,
  146233. 4,
  146234. 1,
  146235. 5,
  146236. 0,
  146237. 6,
  146238. };
  146239. static long _vq_lengthlist__44u1__p7_0[] = {
  146240. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146241. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146242. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  146243. 8,
  146244. };
  146245. static float _vq_quantthresh__44u1__p7_0[] = {
  146246. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  146247. };
  146248. static long _vq_quantmap__44u1__p7_0[] = {
  146249. 5, 3, 1, 0, 2, 4, 6,
  146250. };
  146251. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  146252. _vq_quantthresh__44u1__p7_0,
  146253. _vq_quantmap__44u1__p7_0,
  146254. 7,
  146255. 7
  146256. };
  146257. static static_codebook _44u1__p7_0 = {
  146258. 2, 49,
  146259. _vq_lengthlist__44u1__p7_0,
  146260. 1, -518017024, 1626677248, 3, 0,
  146261. _vq_quantlist__44u1__p7_0,
  146262. NULL,
  146263. &_vq_auxt__44u1__p7_0,
  146264. NULL,
  146265. 0
  146266. };
  146267. static long _vq_quantlist__44u1__p7_1[] = {
  146268. 6,
  146269. 5,
  146270. 7,
  146271. 4,
  146272. 8,
  146273. 3,
  146274. 9,
  146275. 2,
  146276. 10,
  146277. 1,
  146278. 11,
  146279. 0,
  146280. 12,
  146281. };
  146282. static long _vq_lengthlist__44u1__p7_1[] = {
  146283. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  146284. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  146285. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  146286. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  146287. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  146288. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  146289. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  146290. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  146291. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  146292. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  146293. 15,15,15,15,15,15,15,15,15,
  146294. };
  146295. static float _vq_quantthresh__44u1__p7_1[] = {
  146296. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  146297. 32.5, 45.5, 58.5, 71.5,
  146298. };
  146299. static long _vq_quantmap__44u1__p7_1[] = {
  146300. 11, 9, 7, 5, 3, 1, 0, 2,
  146301. 4, 6, 8, 10, 12,
  146302. };
  146303. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  146304. _vq_quantthresh__44u1__p7_1,
  146305. _vq_quantmap__44u1__p7_1,
  146306. 13,
  146307. 13
  146308. };
  146309. static static_codebook _44u1__p7_1 = {
  146310. 2, 169,
  146311. _vq_lengthlist__44u1__p7_1,
  146312. 1, -523010048, 1618608128, 4, 0,
  146313. _vq_quantlist__44u1__p7_1,
  146314. NULL,
  146315. &_vq_auxt__44u1__p7_1,
  146316. NULL,
  146317. 0
  146318. };
  146319. static long _vq_quantlist__44u1__p7_2[] = {
  146320. 6,
  146321. 5,
  146322. 7,
  146323. 4,
  146324. 8,
  146325. 3,
  146326. 9,
  146327. 2,
  146328. 10,
  146329. 1,
  146330. 11,
  146331. 0,
  146332. 12,
  146333. };
  146334. static long _vq_lengthlist__44u1__p7_2[] = {
  146335. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  146336. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  146337. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  146338. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  146339. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  146340. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  146341. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  146342. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146343. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146344. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  146345. 9, 9, 9,10, 9, 9,10,10, 9,
  146346. };
  146347. static float _vq_quantthresh__44u1__p7_2[] = {
  146348. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  146349. 2.5, 3.5, 4.5, 5.5,
  146350. };
  146351. static long _vq_quantmap__44u1__p7_2[] = {
  146352. 11, 9, 7, 5, 3, 1, 0, 2,
  146353. 4, 6, 8, 10, 12,
  146354. };
  146355. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  146356. _vq_quantthresh__44u1__p7_2,
  146357. _vq_quantmap__44u1__p7_2,
  146358. 13,
  146359. 13
  146360. };
  146361. static static_codebook _44u1__p7_2 = {
  146362. 2, 169,
  146363. _vq_lengthlist__44u1__p7_2,
  146364. 1, -531103744, 1611661312, 4, 0,
  146365. _vq_quantlist__44u1__p7_2,
  146366. NULL,
  146367. &_vq_auxt__44u1__p7_2,
  146368. NULL,
  146369. 0
  146370. };
  146371. static long _huff_lengthlist__44u1__short[] = {
  146372. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  146373. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  146374. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  146375. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  146376. };
  146377. static static_codebook _huff_book__44u1__short = {
  146378. 2, 64,
  146379. _huff_lengthlist__44u1__short,
  146380. 0, 0, 0, 0, 0,
  146381. NULL,
  146382. NULL,
  146383. NULL,
  146384. NULL,
  146385. 0
  146386. };
  146387. static long _huff_lengthlist__44u2__long[] = {
  146388. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  146389. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  146390. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  146391. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  146392. };
  146393. static static_codebook _huff_book__44u2__long = {
  146394. 2, 64,
  146395. _huff_lengthlist__44u2__long,
  146396. 0, 0, 0, 0, 0,
  146397. NULL,
  146398. NULL,
  146399. NULL,
  146400. NULL,
  146401. 0
  146402. };
  146403. static long _vq_quantlist__44u2__p1_0[] = {
  146404. 1,
  146405. 0,
  146406. 2,
  146407. };
  146408. static long _vq_lengthlist__44u2__p1_0[] = {
  146409. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146410. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146411. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  146412. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  146413. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  146414. 13,
  146415. };
  146416. static float _vq_quantthresh__44u2__p1_0[] = {
  146417. -0.5, 0.5,
  146418. };
  146419. static long _vq_quantmap__44u2__p1_0[] = {
  146420. 1, 0, 2,
  146421. };
  146422. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  146423. _vq_quantthresh__44u2__p1_0,
  146424. _vq_quantmap__44u2__p1_0,
  146425. 3,
  146426. 3
  146427. };
  146428. static static_codebook _44u2__p1_0 = {
  146429. 4, 81,
  146430. _vq_lengthlist__44u2__p1_0,
  146431. 1, -535822336, 1611661312, 2, 0,
  146432. _vq_quantlist__44u2__p1_0,
  146433. NULL,
  146434. &_vq_auxt__44u2__p1_0,
  146435. NULL,
  146436. 0
  146437. };
  146438. static long _vq_quantlist__44u2__p2_0[] = {
  146439. 1,
  146440. 0,
  146441. 2,
  146442. };
  146443. static long _vq_lengthlist__44u2__p2_0[] = {
  146444. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  146445. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  146446. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146447. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  146448. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146449. 9,
  146450. };
  146451. static float _vq_quantthresh__44u2__p2_0[] = {
  146452. -0.5, 0.5,
  146453. };
  146454. static long _vq_quantmap__44u2__p2_0[] = {
  146455. 1, 0, 2,
  146456. };
  146457. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  146458. _vq_quantthresh__44u2__p2_0,
  146459. _vq_quantmap__44u2__p2_0,
  146460. 3,
  146461. 3
  146462. };
  146463. static static_codebook _44u2__p2_0 = {
  146464. 4, 81,
  146465. _vq_lengthlist__44u2__p2_0,
  146466. 1, -535822336, 1611661312, 2, 0,
  146467. _vq_quantlist__44u2__p2_0,
  146468. NULL,
  146469. &_vq_auxt__44u2__p2_0,
  146470. NULL,
  146471. 0
  146472. };
  146473. static long _vq_quantlist__44u2__p3_0[] = {
  146474. 2,
  146475. 1,
  146476. 3,
  146477. 0,
  146478. 4,
  146479. };
  146480. static long _vq_lengthlist__44u2__p3_0[] = {
  146481. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  146482. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  146483. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  146484. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  146485. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  146486. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  146487. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  146488. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  146489. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  146490. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  146491. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  146492. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  146493. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  146494. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  146495. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  146496. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  146497. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  146498. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  146499. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  146500. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  146501. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  146502. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  146503. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  146504. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  146505. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  146506. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  146507. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  146508. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  146509. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  146510. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  146511. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  146512. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  146513. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  146514. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  146515. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  146516. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  146517. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  146518. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  146519. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  146520. 0,
  146521. };
  146522. static float _vq_quantthresh__44u2__p3_0[] = {
  146523. -1.5, -0.5, 0.5, 1.5,
  146524. };
  146525. static long _vq_quantmap__44u2__p3_0[] = {
  146526. 3, 1, 0, 2, 4,
  146527. };
  146528. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  146529. _vq_quantthresh__44u2__p3_0,
  146530. _vq_quantmap__44u2__p3_0,
  146531. 5,
  146532. 5
  146533. };
  146534. static static_codebook _44u2__p3_0 = {
  146535. 4, 625,
  146536. _vq_lengthlist__44u2__p3_0,
  146537. 1, -533725184, 1611661312, 3, 0,
  146538. _vq_quantlist__44u2__p3_0,
  146539. NULL,
  146540. &_vq_auxt__44u2__p3_0,
  146541. NULL,
  146542. 0
  146543. };
  146544. static long _vq_quantlist__44u2__p4_0[] = {
  146545. 2,
  146546. 1,
  146547. 3,
  146548. 0,
  146549. 4,
  146550. };
  146551. static long _vq_lengthlist__44u2__p4_0[] = {
  146552. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  146553. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  146554. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  146555. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  146556. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  146557. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  146558. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  146559. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  146560. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  146561. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  146562. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  146563. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146564. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  146565. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  146566. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  146567. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  146568. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  146569. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  146570. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  146571. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  146572. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  146573. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  146574. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  146575. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  146576. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  146577. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  146578. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  146579. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  146580. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  146581. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  146582. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  146583. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  146584. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  146585. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  146586. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  146587. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  146588. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  146589. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  146590. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  146591. 13,
  146592. };
  146593. static float _vq_quantthresh__44u2__p4_0[] = {
  146594. -1.5, -0.5, 0.5, 1.5,
  146595. };
  146596. static long _vq_quantmap__44u2__p4_0[] = {
  146597. 3, 1, 0, 2, 4,
  146598. };
  146599. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  146600. _vq_quantthresh__44u2__p4_0,
  146601. _vq_quantmap__44u2__p4_0,
  146602. 5,
  146603. 5
  146604. };
  146605. static static_codebook _44u2__p4_0 = {
  146606. 4, 625,
  146607. _vq_lengthlist__44u2__p4_0,
  146608. 1, -533725184, 1611661312, 3, 0,
  146609. _vq_quantlist__44u2__p4_0,
  146610. NULL,
  146611. &_vq_auxt__44u2__p4_0,
  146612. NULL,
  146613. 0
  146614. };
  146615. static long _vq_quantlist__44u2__p5_0[] = {
  146616. 4,
  146617. 3,
  146618. 5,
  146619. 2,
  146620. 6,
  146621. 1,
  146622. 7,
  146623. 0,
  146624. 8,
  146625. };
  146626. static long _vq_lengthlist__44u2__p5_0[] = {
  146627. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  146628. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  146629. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  146630. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  146631. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  146632. 13,
  146633. };
  146634. static float _vq_quantthresh__44u2__p5_0[] = {
  146635. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146636. };
  146637. static long _vq_quantmap__44u2__p5_0[] = {
  146638. 7, 5, 3, 1, 0, 2, 4, 6,
  146639. 8,
  146640. };
  146641. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  146642. _vq_quantthresh__44u2__p5_0,
  146643. _vq_quantmap__44u2__p5_0,
  146644. 9,
  146645. 9
  146646. };
  146647. static static_codebook _44u2__p5_0 = {
  146648. 2, 81,
  146649. _vq_lengthlist__44u2__p5_0,
  146650. 1, -531628032, 1611661312, 4, 0,
  146651. _vq_quantlist__44u2__p5_0,
  146652. NULL,
  146653. &_vq_auxt__44u2__p5_0,
  146654. NULL,
  146655. 0
  146656. };
  146657. static long _vq_quantlist__44u2__p6_0[] = {
  146658. 6,
  146659. 5,
  146660. 7,
  146661. 4,
  146662. 8,
  146663. 3,
  146664. 9,
  146665. 2,
  146666. 10,
  146667. 1,
  146668. 11,
  146669. 0,
  146670. 12,
  146671. };
  146672. static long _vq_lengthlist__44u2__p6_0[] = {
  146673. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  146674. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  146675. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  146676. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  146677. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  146678. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  146679. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  146680. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  146681. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  146682. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  146683. 15,17,17,16,18,17,18, 0, 0,
  146684. };
  146685. static float _vq_quantthresh__44u2__p6_0[] = {
  146686. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146687. 12.5, 17.5, 22.5, 27.5,
  146688. };
  146689. static long _vq_quantmap__44u2__p6_0[] = {
  146690. 11, 9, 7, 5, 3, 1, 0, 2,
  146691. 4, 6, 8, 10, 12,
  146692. };
  146693. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  146694. _vq_quantthresh__44u2__p6_0,
  146695. _vq_quantmap__44u2__p6_0,
  146696. 13,
  146697. 13
  146698. };
  146699. static static_codebook _44u2__p6_0 = {
  146700. 2, 169,
  146701. _vq_lengthlist__44u2__p6_0,
  146702. 1, -526516224, 1616117760, 4, 0,
  146703. _vq_quantlist__44u2__p6_0,
  146704. NULL,
  146705. &_vq_auxt__44u2__p6_0,
  146706. NULL,
  146707. 0
  146708. };
  146709. static long _vq_quantlist__44u2__p6_1[] = {
  146710. 2,
  146711. 1,
  146712. 3,
  146713. 0,
  146714. 4,
  146715. };
  146716. static long _vq_lengthlist__44u2__p6_1[] = {
  146717. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  146718. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  146719. };
  146720. static float _vq_quantthresh__44u2__p6_1[] = {
  146721. -1.5, -0.5, 0.5, 1.5,
  146722. };
  146723. static long _vq_quantmap__44u2__p6_1[] = {
  146724. 3, 1, 0, 2, 4,
  146725. };
  146726. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  146727. _vq_quantthresh__44u2__p6_1,
  146728. _vq_quantmap__44u2__p6_1,
  146729. 5,
  146730. 5
  146731. };
  146732. static static_codebook _44u2__p6_1 = {
  146733. 2, 25,
  146734. _vq_lengthlist__44u2__p6_1,
  146735. 1, -533725184, 1611661312, 3, 0,
  146736. _vq_quantlist__44u2__p6_1,
  146737. NULL,
  146738. &_vq_auxt__44u2__p6_1,
  146739. NULL,
  146740. 0
  146741. };
  146742. static long _vq_quantlist__44u2__p7_0[] = {
  146743. 4,
  146744. 3,
  146745. 5,
  146746. 2,
  146747. 6,
  146748. 1,
  146749. 7,
  146750. 0,
  146751. 8,
  146752. };
  146753. static long _vq_lengthlist__44u2__p7_0[] = {
  146754. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  146755. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  146756. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146757. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146758. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146759. 11,
  146760. };
  146761. static float _vq_quantthresh__44u2__p7_0[] = {
  146762. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  146763. };
  146764. static long _vq_quantmap__44u2__p7_0[] = {
  146765. 7, 5, 3, 1, 0, 2, 4, 6,
  146766. 8,
  146767. };
  146768. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  146769. _vq_quantthresh__44u2__p7_0,
  146770. _vq_quantmap__44u2__p7_0,
  146771. 9,
  146772. 9
  146773. };
  146774. static static_codebook _44u2__p7_0 = {
  146775. 2, 81,
  146776. _vq_lengthlist__44u2__p7_0,
  146777. 1, -516612096, 1626677248, 4, 0,
  146778. _vq_quantlist__44u2__p7_0,
  146779. NULL,
  146780. &_vq_auxt__44u2__p7_0,
  146781. NULL,
  146782. 0
  146783. };
  146784. static long _vq_quantlist__44u2__p7_1[] = {
  146785. 6,
  146786. 5,
  146787. 7,
  146788. 4,
  146789. 8,
  146790. 3,
  146791. 9,
  146792. 2,
  146793. 10,
  146794. 1,
  146795. 11,
  146796. 0,
  146797. 12,
  146798. };
  146799. static long _vq_lengthlist__44u2__p7_1[] = {
  146800. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  146801. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  146802. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  146803. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  146804. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  146805. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  146806. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  146807. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  146808. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  146809. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  146810. 14,14,14,17,15,17,17,17,17,
  146811. };
  146812. static float _vq_quantthresh__44u2__p7_1[] = {
  146813. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  146814. 32.5, 45.5, 58.5, 71.5,
  146815. };
  146816. static long _vq_quantmap__44u2__p7_1[] = {
  146817. 11, 9, 7, 5, 3, 1, 0, 2,
  146818. 4, 6, 8, 10, 12,
  146819. };
  146820. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  146821. _vq_quantthresh__44u2__p7_1,
  146822. _vq_quantmap__44u2__p7_1,
  146823. 13,
  146824. 13
  146825. };
  146826. static static_codebook _44u2__p7_1 = {
  146827. 2, 169,
  146828. _vq_lengthlist__44u2__p7_1,
  146829. 1, -523010048, 1618608128, 4, 0,
  146830. _vq_quantlist__44u2__p7_1,
  146831. NULL,
  146832. &_vq_auxt__44u2__p7_1,
  146833. NULL,
  146834. 0
  146835. };
  146836. static long _vq_quantlist__44u2__p7_2[] = {
  146837. 6,
  146838. 5,
  146839. 7,
  146840. 4,
  146841. 8,
  146842. 3,
  146843. 9,
  146844. 2,
  146845. 10,
  146846. 1,
  146847. 11,
  146848. 0,
  146849. 12,
  146850. };
  146851. static long _vq_lengthlist__44u2__p7_2[] = {
  146852. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  146853. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  146854. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  146855. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  146856. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  146857. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  146858. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  146859. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146860. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  146861. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  146862. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146863. };
  146864. static float _vq_quantthresh__44u2__p7_2[] = {
  146865. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  146866. 2.5, 3.5, 4.5, 5.5,
  146867. };
  146868. static long _vq_quantmap__44u2__p7_2[] = {
  146869. 11, 9, 7, 5, 3, 1, 0, 2,
  146870. 4, 6, 8, 10, 12,
  146871. };
  146872. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  146873. _vq_quantthresh__44u2__p7_2,
  146874. _vq_quantmap__44u2__p7_2,
  146875. 13,
  146876. 13
  146877. };
  146878. static static_codebook _44u2__p7_2 = {
  146879. 2, 169,
  146880. _vq_lengthlist__44u2__p7_2,
  146881. 1, -531103744, 1611661312, 4, 0,
  146882. _vq_quantlist__44u2__p7_2,
  146883. NULL,
  146884. &_vq_auxt__44u2__p7_2,
  146885. NULL,
  146886. 0
  146887. };
  146888. static long _huff_lengthlist__44u2__short[] = {
  146889. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  146890. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  146891. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  146892. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  146893. };
  146894. static static_codebook _huff_book__44u2__short = {
  146895. 2, 64,
  146896. _huff_lengthlist__44u2__short,
  146897. 0, 0, 0, 0, 0,
  146898. NULL,
  146899. NULL,
  146900. NULL,
  146901. NULL,
  146902. 0
  146903. };
  146904. static long _huff_lengthlist__44u3__long[] = {
  146905. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  146906. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  146907. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  146908. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  146909. };
  146910. static static_codebook _huff_book__44u3__long = {
  146911. 2, 64,
  146912. _huff_lengthlist__44u3__long,
  146913. 0, 0, 0, 0, 0,
  146914. NULL,
  146915. NULL,
  146916. NULL,
  146917. NULL,
  146918. 0
  146919. };
  146920. static long _vq_quantlist__44u3__p1_0[] = {
  146921. 1,
  146922. 0,
  146923. 2,
  146924. };
  146925. static long _vq_lengthlist__44u3__p1_0[] = {
  146926. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  146927. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146928. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  146929. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  146930. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  146931. 13,
  146932. };
  146933. static float _vq_quantthresh__44u3__p1_0[] = {
  146934. -0.5, 0.5,
  146935. };
  146936. static long _vq_quantmap__44u3__p1_0[] = {
  146937. 1, 0, 2,
  146938. };
  146939. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  146940. _vq_quantthresh__44u3__p1_0,
  146941. _vq_quantmap__44u3__p1_0,
  146942. 3,
  146943. 3
  146944. };
  146945. static static_codebook _44u3__p1_0 = {
  146946. 4, 81,
  146947. _vq_lengthlist__44u3__p1_0,
  146948. 1, -535822336, 1611661312, 2, 0,
  146949. _vq_quantlist__44u3__p1_0,
  146950. NULL,
  146951. &_vq_auxt__44u3__p1_0,
  146952. NULL,
  146953. 0
  146954. };
  146955. static long _vq_quantlist__44u3__p2_0[] = {
  146956. 1,
  146957. 0,
  146958. 2,
  146959. };
  146960. static long _vq_lengthlist__44u3__p2_0[] = {
  146961. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  146962. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  146963. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146964. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  146965. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  146966. 9,
  146967. };
  146968. static float _vq_quantthresh__44u3__p2_0[] = {
  146969. -0.5, 0.5,
  146970. };
  146971. static long _vq_quantmap__44u3__p2_0[] = {
  146972. 1, 0, 2,
  146973. };
  146974. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  146975. _vq_quantthresh__44u3__p2_0,
  146976. _vq_quantmap__44u3__p2_0,
  146977. 3,
  146978. 3
  146979. };
  146980. static static_codebook _44u3__p2_0 = {
  146981. 4, 81,
  146982. _vq_lengthlist__44u3__p2_0,
  146983. 1, -535822336, 1611661312, 2, 0,
  146984. _vq_quantlist__44u3__p2_0,
  146985. NULL,
  146986. &_vq_auxt__44u3__p2_0,
  146987. NULL,
  146988. 0
  146989. };
  146990. static long _vq_quantlist__44u3__p3_0[] = {
  146991. 2,
  146992. 1,
  146993. 3,
  146994. 0,
  146995. 4,
  146996. };
  146997. static long _vq_lengthlist__44u3__p3_0[] = {
  146998. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  146999. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  147000. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  147001. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  147002. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  147003. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  147004. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  147005. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  147006. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  147007. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147008. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  147009. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147010. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  147011. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  147012. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  147013. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  147014. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  147015. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  147016. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  147017. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  147018. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  147019. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  147020. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  147021. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  147022. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  147023. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  147024. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  147025. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  147026. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  147027. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  147028. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  147029. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  147030. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  147031. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  147032. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  147033. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  147034. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  147035. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  147036. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  147037. 0,
  147038. };
  147039. static float _vq_quantthresh__44u3__p3_0[] = {
  147040. -1.5, -0.5, 0.5, 1.5,
  147041. };
  147042. static long _vq_quantmap__44u3__p3_0[] = {
  147043. 3, 1, 0, 2, 4,
  147044. };
  147045. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  147046. _vq_quantthresh__44u3__p3_0,
  147047. _vq_quantmap__44u3__p3_0,
  147048. 5,
  147049. 5
  147050. };
  147051. static static_codebook _44u3__p3_0 = {
  147052. 4, 625,
  147053. _vq_lengthlist__44u3__p3_0,
  147054. 1, -533725184, 1611661312, 3, 0,
  147055. _vq_quantlist__44u3__p3_0,
  147056. NULL,
  147057. &_vq_auxt__44u3__p3_0,
  147058. NULL,
  147059. 0
  147060. };
  147061. static long _vq_quantlist__44u3__p4_0[] = {
  147062. 2,
  147063. 1,
  147064. 3,
  147065. 0,
  147066. 4,
  147067. };
  147068. static long _vq_lengthlist__44u3__p4_0[] = {
  147069. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147070. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147071. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  147072. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  147073. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  147074. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  147075. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  147076. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  147077. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147078. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147079. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  147080. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147081. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  147082. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  147083. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  147084. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  147085. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  147086. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147087. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147088. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  147089. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147090. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  147091. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  147092. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147093. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  147094. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  147095. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  147096. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  147097. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  147098. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  147099. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  147100. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  147101. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  147102. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  147103. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  147104. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  147105. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  147106. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  147107. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  147108. 13,
  147109. };
  147110. static float _vq_quantthresh__44u3__p4_0[] = {
  147111. -1.5, -0.5, 0.5, 1.5,
  147112. };
  147113. static long _vq_quantmap__44u3__p4_0[] = {
  147114. 3, 1, 0, 2, 4,
  147115. };
  147116. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  147117. _vq_quantthresh__44u3__p4_0,
  147118. _vq_quantmap__44u3__p4_0,
  147119. 5,
  147120. 5
  147121. };
  147122. static static_codebook _44u3__p4_0 = {
  147123. 4, 625,
  147124. _vq_lengthlist__44u3__p4_0,
  147125. 1, -533725184, 1611661312, 3, 0,
  147126. _vq_quantlist__44u3__p4_0,
  147127. NULL,
  147128. &_vq_auxt__44u3__p4_0,
  147129. NULL,
  147130. 0
  147131. };
  147132. static long _vq_quantlist__44u3__p5_0[] = {
  147133. 4,
  147134. 3,
  147135. 5,
  147136. 2,
  147137. 6,
  147138. 1,
  147139. 7,
  147140. 0,
  147141. 8,
  147142. };
  147143. static long _vq_lengthlist__44u3__p5_0[] = {
  147144. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  147145. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  147146. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  147147. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  147148. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  147149. 12,
  147150. };
  147151. static float _vq_quantthresh__44u3__p5_0[] = {
  147152. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147153. };
  147154. static long _vq_quantmap__44u3__p5_0[] = {
  147155. 7, 5, 3, 1, 0, 2, 4, 6,
  147156. 8,
  147157. };
  147158. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  147159. _vq_quantthresh__44u3__p5_0,
  147160. _vq_quantmap__44u3__p5_0,
  147161. 9,
  147162. 9
  147163. };
  147164. static static_codebook _44u3__p5_0 = {
  147165. 2, 81,
  147166. _vq_lengthlist__44u3__p5_0,
  147167. 1, -531628032, 1611661312, 4, 0,
  147168. _vq_quantlist__44u3__p5_0,
  147169. NULL,
  147170. &_vq_auxt__44u3__p5_0,
  147171. NULL,
  147172. 0
  147173. };
  147174. static long _vq_quantlist__44u3__p6_0[] = {
  147175. 6,
  147176. 5,
  147177. 7,
  147178. 4,
  147179. 8,
  147180. 3,
  147181. 9,
  147182. 2,
  147183. 10,
  147184. 1,
  147185. 11,
  147186. 0,
  147187. 12,
  147188. };
  147189. static long _vq_lengthlist__44u3__p6_0[] = {
  147190. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  147191. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  147192. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  147193. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  147194. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  147195. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  147196. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  147197. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  147198. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  147199. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  147200. 15,16,16,16,17,18,16,20,18,
  147201. };
  147202. static float _vq_quantthresh__44u3__p6_0[] = {
  147203. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147204. 12.5, 17.5, 22.5, 27.5,
  147205. };
  147206. static long _vq_quantmap__44u3__p6_0[] = {
  147207. 11, 9, 7, 5, 3, 1, 0, 2,
  147208. 4, 6, 8, 10, 12,
  147209. };
  147210. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  147211. _vq_quantthresh__44u3__p6_0,
  147212. _vq_quantmap__44u3__p6_0,
  147213. 13,
  147214. 13
  147215. };
  147216. static static_codebook _44u3__p6_0 = {
  147217. 2, 169,
  147218. _vq_lengthlist__44u3__p6_0,
  147219. 1, -526516224, 1616117760, 4, 0,
  147220. _vq_quantlist__44u3__p6_0,
  147221. NULL,
  147222. &_vq_auxt__44u3__p6_0,
  147223. NULL,
  147224. 0
  147225. };
  147226. static long _vq_quantlist__44u3__p6_1[] = {
  147227. 2,
  147228. 1,
  147229. 3,
  147230. 0,
  147231. 4,
  147232. };
  147233. static long _vq_lengthlist__44u3__p6_1[] = {
  147234. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  147235. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  147236. };
  147237. static float _vq_quantthresh__44u3__p6_1[] = {
  147238. -1.5, -0.5, 0.5, 1.5,
  147239. };
  147240. static long _vq_quantmap__44u3__p6_1[] = {
  147241. 3, 1, 0, 2, 4,
  147242. };
  147243. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  147244. _vq_quantthresh__44u3__p6_1,
  147245. _vq_quantmap__44u3__p6_1,
  147246. 5,
  147247. 5
  147248. };
  147249. static static_codebook _44u3__p6_1 = {
  147250. 2, 25,
  147251. _vq_lengthlist__44u3__p6_1,
  147252. 1, -533725184, 1611661312, 3, 0,
  147253. _vq_quantlist__44u3__p6_1,
  147254. NULL,
  147255. &_vq_auxt__44u3__p6_1,
  147256. NULL,
  147257. 0
  147258. };
  147259. static long _vq_quantlist__44u3__p7_0[] = {
  147260. 4,
  147261. 3,
  147262. 5,
  147263. 2,
  147264. 6,
  147265. 1,
  147266. 7,
  147267. 0,
  147268. 8,
  147269. };
  147270. static long _vq_lengthlist__44u3__p7_0[] = {
  147271. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  147272. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  147273. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147274. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147275. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147276. 9,
  147277. };
  147278. static float _vq_quantthresh__44u3__p7_0[] = {
  147279. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  147280. };
  147281. static long _vq_quantmap__44u3__p7_0[] = {
  147282. 7, 5, 3, 1, 0, 2, 4, 6,
  147283. 8,
  147284. };
  147285. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  147286. _vq_quantthresh__44u3__p7_0,
  147287. _vq_quantmap__44u3__p7_0,
  147288. 9,
  147289. 9
  147290. };
  147291. static static_codebook _44u3__p7_0 = {
  147292. 2, 81,
  147293. _vq_lengthlist__44u3__p7_0,
  147294. 1, -515907584, 1627381760, 4, 0,
  147295. _vq_quantlist__44u3__p7_0,
  147296. NULL,
  147297. &_vq_auxt__44u3__p7_0,
  147298. NULL,
  147299. 0
  147300. };
  147301. static long _vq_quantlist__44u3__p7_1[] = {
  147302. 7,
  147303. 6,
  147304. 8,
  147305. 5,
  147306. 9,
  147307. 4,
  147308. 10,
  147309. 3,
  147310. 11,
  147311. 2,
  147312. 12,
  147313. 1,
  147314. 13,
  147315. 0,
  147316. 14,
  147317. };
  147318. static long _vq_lengthlist__44u3__p7_1[] = {
  147319. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  147320. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  147321. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  147322. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  147323. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  147324. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  147325. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  147326. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  147327. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  147328. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  147329. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  147330. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  147331. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  147332. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  147333. 17,
  147334. };
  147335. static float _vq_quantthresh__44u3__p7_1[] = {
  147336. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  147337. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  147338. };
  147339. static long _vq_quantmap__44u3__p7_1[] = {
  147340. 13, 11, 9, 7, 5, 3, 1, 0,
  147341. 2, 4, 6, 8, 10, 12, 14,
  147342. };
  147343. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  147344. _vq_quantthresh__44u3__p7_1,
  147345. _vq_quantmap__44u3__p7_1,
  147346. 15,
  147347. 15
  147348. };
  147349. static static_codebook _44u3__p7_1 = {
  147350. 2, 225,
  147351. _vq_lengthlist__44u3__p7_1,
  147352. 1, -522338304, 1620115456, 4, 0,
  147353. _vq_quantlist__44u3__p7_1,
  147354. NULL,
  147355. &_vq_auxt__44u3__p7_1,
  147356. NULL,
  147357. 0
  147358. };
  147359. static long _vq_quantlist__44u3__p7_2[] = {
  147360. 8,
  147361. 7,
  147362. 9,
  147363. 6,
  147364. 10,
  147365. 5,
  147366. 11,
  147367. 4,
  147368. 12,
  147369. 3,
  147370. 13,
  147371. 2,
  147372. 14,
  147373. 1,
  147374. 15,
  147375. 0,
  147376. 16,
  147377. };
  147378. static long _vq_lengthlist__44u3__p7_2[] = {
  147379. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  147380. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147381. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  147382. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147383. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  147384. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147385. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  147386. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147387. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  147388. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  147389. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  147390. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  147391. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  147392. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  147393. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  147394. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  147395. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147396. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  147397. 11,
  147398. };
  147399. static float _vq_quantthresh__44u3__p7_2[] = {
  147400. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  147401. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  147402. };
  147403. static long _vq_quantmap__44u3__p7_2[] = {
  147404. 15, 13, 11, 9, 7, 5, 3, 1,
  147405. 0, 2, 4, 6, 8, 10, 12, 14,
  147406. 16,
  147407. };
  147408. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  147409. _vq_quantthresh__44u3__p7_2,
  147410. _vq_quantmap__44u3__p7_2,
  147411. 17,
  147412. 17
  147413. };
  147414. static static_codebook _44u3__p7_2 = {
  147415. 2, 289,
  147416. _vq_lengthlist__44u3__p7_2,
  147417. 1, -529530880, 1611661312, 5, 0,
  147418. _vq_quantlist__44u3__p7_2,
  147419. NULL,
  147420. &_vq_auxt__44u3__p7_2,
  147421. NULL,
  147422. 0
  147423. };
  147424. static long _huff_lengthlist__44u3__short[] = {
  147425. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  147426. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  147427. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  147428. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  147429. };
  147430. static static_codebook _huff_book__44u3__short = {
  147431. 2, 64,
  147432. _huff_lengthlist__44u3__short,
  147433. 0, 0, 0, 0, 0,
  147434. NULL,
  147435. NULL,
  147436. NULL,
  147437. NULL,
  147438. 0
  147439. };
  147440. static long _huff_lengthlist__44u4__long[] = {
  147441. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  147442. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  147443. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  147444. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  147445. };
  147446. static static_codebook _huff_book__44u4__long = {
  147447. 2, 64,
  147448. _huff_lengthlist__44u4__long,
  147449. 0, 0, 0, 0, 0,
  147450. NULL,
  147451. NULL,
  147452. NULL,
  147453. NULL,
  147454. 0
  147455. };
  147456. static long _vq_quantlist__44u4__p1_0[] = {
  147457. 1,
  147458. 0,
  147459. 2,
  147460. };
  147461. static long _vq_lengthlist__44u4__p1_0[] = {
  147462. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  147463. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147464. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  147465. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  147466. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  147467. 13,
  147468. };
  147469. static float _vq_quantthresh__44u4__p1_0[] = {
  147470. -0.5, 0.5,
  147471. };
  147472. static long _vq_quantmap__44u4__p1_0[] = {
  147473. 1, 0, 2,
  147474. };
  147475. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  147476. _vq_quantthresh__44u4__p1_0,
  147477. _vq_quantmap__44u4__p1_0,
  147478. 3,
  147479. 3
  147480. };
  147481. static static_codebook _44u4__p1_0 = {
  147482. 4, 81,
  147483. _vq_lengthlist__44u4__p1_0,
  147484. 1, -535822336, 1611661312, 2, 0,
  147485. _vq_quantlist__44u4__p1_0,
  147486. NULL,
  147487. &_vq_auxt__44u4__p1_0,
  147488. NULL,
  147489. 0
  147490. };
  147491. static long _vq_quantlist__44u4__p2_0[] = {
  147492. 1,
  147493. 0,
  147494. 2,
  147495. };
  147496. static long _vq_lengthlist__44u4__p2_0[] = {
  147497. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147498. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  147499. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147500. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  147501. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  147502. 9,
  147503. };
  147504. static float _vq_quantthresh__44u4__p2_0[] = {
  147505. -0.5, 0.5,
  147506. };
  147507. static long _vq_quantmap__44u4__p2_0[] = {
  147508. 1, 0, 2,
  147509. };
  147510. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  147511. _vq_quantthresh__44u4__p2_0,
  147512. _vq_quantmap__44u4__p2_0,
  147513. 3,
  147514. 3
  147515. };
  147516. static static_codebook _44u4__p2_0 = {
  147517. 4, 81,
  147518. _vq_lengthlist__44u4__p2_0,
  147519. 1, -535822336, 1611661312, 2, 0,
  147520. _vq_quantlist__44u4__p2_0,
  147521. NULL,
  147522. &_vq_auxt__44u4__p2_0,
  147523. NULL,
  147524. 0
  147525. };
  147526. static long _vq_quantlist__44u4__p3_0[] = {
  147527. 2,
  147528. 1,
  147529. 3,
  147530. 0,
  147531. 4,
  147532. };
  147533. static long _vq_lengthlist__44u4__p3_0[] = {
  147534. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147535. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  147536. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  147537. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  147538. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  147539. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  147540. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  147541. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  147542. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  147543. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  147544. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  147545. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  147546. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  147547. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  147548. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  147549. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  147550. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  147551. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  147552. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  147553. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  147554. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  147555. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  147556. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  147557. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  147558. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  147559. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  147560. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  147561. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  147562. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  147563. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  147564. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  147565. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  147566. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  147567. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  147568. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  147569. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  147570. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  147571. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  147572. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  147573. 0,
  147574. };
  147575. static float _vq_quantthresh__44u4__p3_0[] = {
  147576. -1.5, -0.5, 0.5, 1.5,
  147577. };
  147578. static long _vq_quantmap__44u4__p3_0[] = {
  147579. 3, 1, 0, 2, 4,
  147580. };
  147581. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  147582. _vq_quantthresh__44u4__p3_0,
  147583. _vq_quantmap__44u4__p3_0,
  147584. 5,
  147585. 5
  147586. };
  147587. static static_codebook _44u4__p3_0 = {
  147588. 4, 625,
  147589. _vq_lengthlist__44u4__p3_0,
  147590. 1, -533725184, 1611661312, 3, 0,
  147591. _vq_quantlist__44u4__p3_0,
  147592. NULL,
  147593. &_vq_auxt__44u4__p3_0,
  147594. NULL,
  147595. 0
  147596. };
  147597. static long _vq_quantlist__44u4__p4_0[] = {
  147598. 2,
  147599. 1,
  147600. 3,
  147601. 0,
  147602. 4,
  147603. };
  147604. static long _vq_lengthlist__44u4__p4_0[] = {
  147605. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147606. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147607. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  147608. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  147609. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  147610. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  147611. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  147612. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  147613. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147614. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147615. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  147616. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147617. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  147618. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  147619. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  147620. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  147621. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  147622. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147623. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147624. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  147625. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147626. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  147627. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  147628. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147629. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  147630. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  147631. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  147632. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  147633. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  147634. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  147635. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  147636. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  147637. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  147638. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  147639. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  147640. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  147641. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  147642. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  147643. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  147644. 13,
  147645. };
  147646. static float _vq_quantthresh__44u4__p4_0[] = {
  147647. -1.5, -0.5, 0.5, 1.5,
  147648. };
  147649. static long _vq_quantmap__44u4__p4_0[] = {
  147650. 3, 1, 0, 2, 4,
  147651. };
  147652. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  147653. _vq_quantthresh__44u4__p4_0,
  147654. _vq_quantmap__44u4__p4_0,
  147655. 5,
  147656. 5
  147657. };
  147658. static static_codebook _44u4__p4_0 = {
  147659. 4, 625,
  147660. _vq_lengthlist__44u4__p4_0,
  147661. 1, -533725184, 1611661312, 3, 0,
  147662. _vq_quantlist__44u4__p4_0,
  147663. NULL,
  147664. &_vq_auxt__44u4__p4_0,
  147665. NULL,
  147666. 0
  147667. };
  147668. static long _vq_quantlist__44u4__p5_0[] = {
  147669. 4,
  147670. 3,
  147671. 5,
  147672. 2,
  147673. 6,
  147674. 1,
  147675. 7,
  147676. 0,
  147677. 8,
  147678. };
  147679. static long _vq_lengthlist__44u4__p5_0[] = {
  147680. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  147681. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  147682. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  147683. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  147684. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  147685. 12,
  147686. };
  147687. static float _vq_quantthresh__44u4__p5_0[] = {
  147688. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147689. };
  147690. static long _vq_quantmap__44u4__p5_0[] = {
  147691. 7, 5, 3, 1, 0, 2, 4, 6,
  147692. 8,
  147693. };
  147694. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  147695. _vq_quantthresh__44u4__p5_0,
  147696. _vq_quantmap__44u4__p5_0,
  147697. 9,
  147698. 9
  147699. };
  147700. static static_codebook _44u4__p5_0 = {
  147701. 2, 81,
  147702. _vq_lengthlist__44u4__p5_0,
  147703. 1, -531628032, 1611661312, 4, 0,
  147704. _vq_quantlist__44u4__p5_0,
  147705. NULL,
  147706. &_vq_auxt__44u4__p5_0,
  147707. NULL,
  147708. 0
  147709. };
  147710. static long _vq_quantlist__44u4__p6_0[] = {
  147711. 6,
  147712. 5,
  147713. 7,
  147714. 4,
  147715. 8,
  147716. 3,
  147717. 9,
  147718. 2,
  147719. 10,
  147720. 1,
  147721. 11,
  147722. 0,
  147723. 12,
  147724. };
  147725. static long _vq_lengthlist__44u4__p6_0[] = {
  147726. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  147727. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  147728. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  147729. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  147730. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  147731. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  147732. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  147733. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  147734. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  147735. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  147736. 16,16,16,17,17,18,17,20,21,
  147737. };
  147738. static float _vq_quantthresh__44u4__p6_0[] = {
  147739. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147740. 12.5, 17.5, 22.5, 27.5,
  147741. };
  147742. static long _vq_quantmap__44u4__p6_0[] = {
  147743. 11, 9, 7, 5, 3, 1, 0, 2,
  147744. 4, 6, 8, 10, 12,
  147745. };
  147746. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  147747. _vq_quantthresh__44u4__p6_0,
  147748. _vq_quantmap__44u4__p6_0,
  147749. 13,
  147750. 13
  147751. };
  147752. static static_codebook _44u4__p6_0 = {
  147753. 2, 169,
  147754. _vq_lengthlist__44u4__p6_0,
  147755. 1, -526516224, 1616117760, 4, 0,
  147756. _vq_quantlist__44u4__p6_0,
  147757. NULL,
  147758. &_vq_auxt__44u4__p6_0,
  147759. NULL,
  147760. 0
  147761. };
  147762. static long _vq_quantlist__44u4__p6_1[] = {
  147763. 2,
  147764. 1,
  147765. 3,
  147766. 0,
  147767. 4,
  147768. };
  147769. static long _vq_lengthlist__44u4__p6_1[] = {
  147770. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  147771. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  147772. };
  147773. static float _vq_quantthresh__44u4__p6_1[] = {
  147774. -1.5, -0.5, 0.5, 1.5,
  147775. };
  147776. static long _vq_quantmap__44u4__p6_1[] = {
  147777. 3, 1, 0, 2, 4,
  147778. };
  147779. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  147780. _vq_quantthresh__44u4__p6_1,
  147781. _vq_quantmap__44u4__p6_1,
  147782. 5,
  147783. 5
  147784. };
  147785. static static_codebook _44u4__p6_1 = {
  147786. 2, 25,
  147787. _vq_lengthlist__44u4__p6_1,
  147788. 1, -533725184, 1611661312, 3, 0,
  147789. _vq_quantlist__44u4__p6_1,
  147790. NULL,
  147791. &_vq_auxt__44u4__p6_1,
  147792. NULL,
  147793. 0
  147794. };
  147795. static long _vq_quantlist__44u4__p7_0[] = {
  147796. 6,
  147797. 5,
  147798. 7,
  147799. 4,
  147800. 8,
  147801. 3,
  147802. 9,
  147803. 2,
  147804. 10,
  147805. 1,
  147806. 11,
  147807. 0,
  147808. 12,
  147809. };
  147810. static long _vq_lengthlist__44u4__p7_0[] = {
  147811. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  147812. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  147813. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  147814. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  147815. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  147816. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147817. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147818. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147819. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147820. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147821. 11,11,11,11,11,11,11,11,11,
  147822. };
  147823. static float _vq_quantthresh__44u4__p7_0[] = {
  147824. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  147825. 637.5, 892.5, 1147.5, 1402.5,
  147826. };
  147827. static long _vq_quantmap__44u4__p7_0[] = {
  147828. 11, 9, 7, 5, 3, 1, 0, 2,
  147829. 4, 6, 8, 10, 12,
  147830. };
  147831. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  147832. _vq_quantthresh__44u4__p7_0,
  147833. _vq_quantmap__44u4__p7_0,
  147834. 13,
  147835. 13
  147836. };
  147837. static static_codebook _44u4__p7_0 = {
  147838. 2, 169,
  147839. _vq_lengthlist__44u4__p7_0,
  147840. 1, -514332672, 1627381760, 4, 0,
  147841. _vq_quantlist__44u4__p7_0,
  147842. NULL,
  147843. &_vq_auxt__44u4__p7_0,
  147844. NULL,
  147845. 0
  147846. };
  147847. static long _vq_quantlist__44u4__p7_1[] = {
  147848. 7,
  147849. 6,
  147850. 8,
  147851. 5,
  147852. 9,
  147853. 4,
  147854. 10,
  147855. 3,
  147856. 11,
  147857. 2,
  147858. 12,
  147859. 1,
  147860. 13,
  147861. 0,
  147862. 14,
  147863. };
  147864. static long _vq_lengthlist__44u4__p7_1[] = {
  147865. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  147866. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  147867. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  147868. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  147869. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  147870. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  147871. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  147872. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  147873. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  147874. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  147875. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  147876. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  147877. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  147878. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  147879. 16,
  147880. };
  147881. static float _vq_quantthresh__44u4__p7_1[] = {
  147882. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  147883. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  147884. };
  147885. static long _vq_quantmap__44u4__p7_1[] = {
  147886. 13, 11, 9, 7, 5, 3, 1, 0,
  147887. 2, 4, 6, 8, 10, 12, 14,
  147888. };
  147889. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  147890. _vq_quantthresh__44u4__p7_1,
  147891. _vq_quantmap__44u4__p7_1,
  147892. 15,
  147893. 15
  147894. };
  147895. static static_codebook _44u4__p7_1 = {
  147896. 2, 225,
  147897. _vq_lengthlist__44u4__p7_1,
  147898. 1, -522338304, 1620115456, 4, 0,
  147899. _vq_quantlist__44u4__p7_1,
  147900. NULL,
  147901. &_vq_auxt__44u4__p7_1,
  147902. NULL,
  147903. 0
  147904. };
  147905. static long _vq_quantlist__44u4__p7_2[] = {
  147906. 8,
  147907. 7,
  147908. 9,
  147909. 6,
  147910. 10,
  147911. 5,
  147912. 11,
  147913. 4,
  147914. 12,
  147915. 3,
  147916. 13,
  147917. 2,
  147918. 14,
  147919. 1,
  147920. 15,
  147921. 0,
  147922. 16,
  147923. };
  147924. static long _vq_lengthlist__44u4__p7_2[] = {
  147925. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  147926. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147927. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  147928. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147929. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  147930. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147931. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  147932. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  147933. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  147934. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  147935. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  147936. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  147937. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  147938. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  147939. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  147940. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  147941. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147942. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  147943. 10,
  147944. };
  147945. static float _vq_quantthresh__44u4__p7_2[] = {
  147946. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  147947. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  147948. };
  147949. static long _vq_quantmap__44u4__p7_2[] = {
  147950. 15, 13, 11, 9, 7, 5, 3, 1,
  147951. 0, 2, 4, 6, 8, 10, 12, 14,
  147952. 16,
  147953. };
  147954. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  147955. _vq_quantthresh__44u4__p7_2,
  147956. _vq_quantmap__44u4__p7_2,
  147957. 17,
  147958. 17
  147959. };
  147960. static static_codebook _44u4__p7_2 = {
  147961. 2, 289,
  147962. _vq_lengthlist__44u4__p7_2,
  147963. 1, -529530880, 1611661312, 5, 0,
  147964. _vq_quantlist__44u4__p7_2,
  147965. NULL,
  147966. &_vq_auxt__44u4__p7_2,
  147967. NULL,
  147968. 0
  147969. };
  147970. static long _huff_lengthlist__44u4__short[] = {
  147971. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  147972. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  147973. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  147974. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  147975. };
  147976. static static_codebook _huff_book__44u4__short = {
  147977. 2, 64,
  147978. _huff_lengthlist__44u4__short,
  147979. 0, 0, 0, 0, 0,
  147980. NULL,
  147981. NULL,
  147982. NULL,
  147983. NULL,
  147984. 0
  147985. };
  147986. static long _huff_lengthlist__44u5__long[] = {
  147987. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  147988. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  147989. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  147990. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  147991. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  147992. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  147993. 14, 8, 7, 8,
  147994. };
  147995. static static_codebook _huff_book__44u5__long = {
  147996. 2, 100,
  147997. _huff_lengthlist__44u5__long,
  147998. 0, 0, 0, 0, 0,
  147999. NULL,
  148000. NULL,
  148001. NULL,
  148002. NULL,
  148003. 0
  148004. };
  148005. static long _vq_quantlist__44u5__p1_0[] = {
  148006. 1,
  148007. 0,
  148008. 2,
  148009. };
  148010. static long _vq_lengthlist__44u5__p1_0[] = {
  148011. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  148012. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  148013. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  148014. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  148015. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  148016. 12,
  148017. };
  148018. static float _vq_quantthresh__44u5__p1_0[] = {
  148019. -0.5, 0.5,
  148020. };
  148021. static long _vq_quantmap__44u5__p1_0[] = {
  148022. 1, 0, 2,
  148023. };
  148024. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  148025. _vq_quantthresh__44u5__p1_0,
  148026. _vq_quantmap__44u5__p1_0,
  148027. 3,
  148028. 3
  148029. };
  148030. static static_codebook _44u5__p1_0 = {
  148031. 4, 81,
  148032. _vq_lengthlist__44u5__p1_0,
  148033. 1, -535822336, 1611661312, 2, 0,
  148034. _vq_quantlist__44u5__p1_0,
  148035. NULL,
  148036. &_vq_auxt__44u5__p1_0,
  148037. NULL,
  148038. 0
  148039. };
  148040. static long _vq_quantlist__44u5__p2_0[] = {
  148041. 1,
  148042. 0,
  148043. 2,
  148044. };
  148045. static long _vq_lengthlist__44u5__p2_0[] = {
  148046. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  148047. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  148048. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  148049. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  148050. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  148051. 9,
  148052. };
  148053. static float _vq_quantthresh__44u5__p2_0[] = {
  148054. -0.5, 0.5,
  148055. };
  148056. static long _vq_quantmap__44u5__p2_0[] = {
  148057. 1, 0, 2,
  148058. };
  148059. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  148060. _vq_quantthresh__44u5__p2_0,
  148061. _vq_quantmap__44u5__p2_0,
  148062. 3,
  148063. 3
  148064. };
  148065. static static_codebook _44u5__p2_0 = {
  148066. 4, 81,
  148067. _vq_lengthlist__44u5__p2_0,
  148068. 1, -535822336, 1611661312, 2, 0,
  148069. _vq_quantlist__44u5__p2_0,
  148070. NULL,
  148071. &_vq_auxt__44u5__p2_0,
  148072. NULL,
  148073. 0
  148074. };
  148075. static long _vq_quantlist__44u5__p3_0[] = {
  148076. 2,
  148077. 1,
  148078. 3,
  148079. 0,
  148080. 4,
  148081. };
  148082. static long _vq_lengthlist__44u5__p3_0[] = {
  148083. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  148084. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  148085. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  148086. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  148087. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  148088. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  148089. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  148090. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  148091. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  148092. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  148093. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  148094. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  148095. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  148096. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  148097. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  148098. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  148099. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  148100. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  148101. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  148102. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  148103. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  148104. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  148105. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  148106. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  148107. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  148108. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  148109. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  148110. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  148111. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  148112. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  148113. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  148114. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  148115. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  148116. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  148117. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  148118. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  148119. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  148120. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  148121. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  148122. 0,
  148123. };
  148124. static float _vq_quantthresh__44u5__p3_0[] = {
  148125. -1.5, -0.5, 0.5, 1.5,
  148126. };
  148127. static long _vq_quantmap__44u5__p3_0[] = {
  148128. 3, 1, 0, 2, 4,
  148129. };
  148130. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  148131. _vq_quantthresh__44u5__p3_0,
  148132. _vq_quantmap__44u5__p3_0,
  148133. 5,
  148134. 5
  148135. };
  148136. static static_codebook _44u5__p3_0 = {
  148137. 4, 625,
  148138. _vq_lengthlist__44u5__p3_0,
  148139. 1, -533725184, 1611661312, 3, 0,
  148140. _vq_quantlist__44u5__p3_0,
  148141. NULL,
  148142. &_vq_auxt__44u5__p3_0,
  148143. NULL,
  148144. 0
  148145. };
  148146. static long _vq_quantlist__44u5__p4_0[] = {
  148147. 2,
  148148. 1,
  148149. 3,
  148150. 0,
  148151. 4,
  148152. };
  148153. static long _vq_lengthlist__44u5__p4_0[] = {
  148154. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  148155. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  148156. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  148157. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  148158. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  148159. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  148160. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  148161. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  148162. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  148163. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  148164. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  148165. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148166. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  148167. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  148168. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  148169. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  148170. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  148171. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148172. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  148173. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  148174. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  148175. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  148176. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  148177. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  148178. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  148179. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  148180. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  148181. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  148182. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  148183. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  148184. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  148185. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  148186. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  148187. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  148188. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  148189. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  148190. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  148191. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  148192. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  148193. 12,
  148194. };
  148195. static float _vq_quantthresh__44u5__p4_0[] = {
  148196. -1.5, -0.5, 0.5, 1.5,
  148197. };
  148198. static long _vq_quantmap__44u5__p4_0[] = {
  148199. 3, 1, 0, 2, 4,
  148200. };
  148201. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  148202. _vq_quantthresh__44u5__p4_0,
  148203. _vq_quantmap__44u5__p4_0,
  148204. 5,
  148205. 5
  148206. };
  148207. static static_codebook _44u5__p4_0 = {
  148208. 4, 625,
  148209. _vq_lengthlist__44u5__p4_0,
  148210. 1, -533725184, 1611661312, 3, 0,
  148211. _vq_quantlist__44u5__p4_0,
  148212. NULL,
  148213. &_vq_auxt__44u5__p4_0,
  148214. NULL,
  148215. 0
  148216. };
  148217. static long _vq_quantlist__44u5__p5_0[] = {
  148218. 4,
  148219. 3,
  148220. 5,
  148221. 2,
  148222. 6,
  148223. 1,
  148224. 7,
  148225. 0,
  148226. 8,
  148227. };
  148228. static long _vq_lengthlist__44u5__p5_0[] = {
  148229. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  148230. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  148231. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  148232. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  148233. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  148234. 14,
  148235. };
  148236. static float _vq_quantthresh__44u5__p5_0[] = {
  148237. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148238. };
  148239. static long _vq_quantmap__44u5__p5_0[] = {
  148240. 7, 5, 3, 1, 0, 2, 4, 6,
  148241. 8,
  148242. };
  148243. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  148244. _vq_quantthresh__44u5__p5_0,
  148245. _vq_quantmap__44u5__p5_0,
  148246. 9,
  148247. 9
  148248. };
  148249. static static_codebook _44u5__p5_0 = {
  148250. 2, 81,
  148251. _vq_lengthlist__44u5__p5_0,
  148252. 1, -531628032, 1611661312, 4, 0,
  148253. _vq_quantlist__44u5__p5_0,
  148254. NULL,
  148255. &_vq_auxt__44u5__p5_0,
  148256. NULL,
  148257. 0
  148258. };
  148259. static long _vq_quantlist__44u5__p6_0[] = {
  148260. 4,
  148261. 3,
  148262. 5,
  148263. 2,
  148264. 6,
  148265. 1,
  148266. 7,
  148267. 0,
  148268. 8,
  148269. };
  148270. static long _vq_lengthlist__44u5__p6_0[] = {
  148271. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  148272. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  148273. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  148274. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  148275. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  148276. 11,
  148277. };
  148278. static float _vq_quantthresh__44u5__p6_0[] = {
  148279. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148280. };
  148281. static long _vq_quantmap__44u5__p6_0[] = {
  148282. 7, 5, 3, 1, 0, 2, 4, 6,
  148283. 8,
  148284. };
  148285. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  148286. _vq_quantthresh__44u5__p6_0,
  148287. _vq_quantmap__44u5__p6_0,
  148288. 9,
  148289. 9
  148290. };
  148291. static static_codebook _44u5__p6_0 = {
  148292. 2, 81,
  148293. _vq_lengthlist__44u5__p6_0,
  148294. 1, -531628032, 1611661312, 4, 0,
  148295. _vq_quantlist__44u5__p6_0,
  148296. NULL,
  148297. &_vq_auxt__44u5__p6_0,
  148298. NULL,
  148299. 0
  148300. };
  148301. static long _vq_quantlist__44u5__p7_0[] = {
  148302. 1,
  148303. 0,
  148304. 2,
  148305. };
  148306. static long _vq_lengthlist__44u5__p7_0[] = {
  148307. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  148308. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  148309. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  148310. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  148311. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  148312. 12,
  148313. };
  148314. static float _vq_quantthresh__44u5__p7_0[] = {
  148315. -5.5, 5.5,
  148316. };
  148317. static long _vq_quantmap__44u5__p7_0[] = {
  148318. 1, 0, 2,
  148319. };
  148320. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  148321. _vq_quantthresh__44u5__p7_0,
  148322. _vq_quantmap__44u5__p7_0,
  148323. 3,
  148324. 3
  148325. };
  148326. static static_codebook _44u5__p7_0 = {
  148327. 4, 81,
  148328. _vq_lengthlist__44u5__p7_0,
  148329. 1, -529137664, 1618345984, 2, 0,
  148330. _vq_quantlist__44u5__p7_0,
  148331. NULL,
  148332. &_vq_auxt__44u5__p7_0,
  148333. NULL,
  148334. 0
  148335. };
  148336. static long _vq_quantlist__44u5__p7_1[] = {
  148337. 5,
  148338. 4,
  148339. 6,
  148340. 3,
  148341. 7,
  148342. 2,
  148343. 8,
  148344. 1,
  148345. 9,
  148346. 0,
  148347. 10,
  148348. };
  148349. static long _vq_lengthlist__44u5__p7_1[] = {
  148350. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  148351. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  148352. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  148353. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  148354. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  148355. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  148356. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  148357. 9, 9, 9, 9, 9,10,10,10,10,
  148358. };
  148359. static float _vq_quantthresh__44u5__p7_1[] = {
  148360. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  148361. 3.5, 4.5,
  148362. };
  148363. static long _vq_quantmap__44u5__p7_1[] = {
  148364. 9, 7, 5, 3, 1, 0, 2, 4,
  148365. 6, 8, 10,
  148366. };
  148367. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  148368. _vq_quantthresh__44u5__p7_1,
  148369. _vq_quantmap__44u5__p7_1,
  148370. 11,
  148371. 11
  148372. };
  148373. static static_codebook _44u5__p7_1 = {
  148374. 2, 121,
  148375. _vq_lengthlist__44u5__p7_1,
  148376. 1, -531365888, 1611661312, 4, 0,
  148377. _vq_quantlist__44u5__p7_1,
  148378. NULL,
  148379. &_vq_auxt__44u5__p7_1,
  148380. NULL,
  148381. 0
  148382. };
  148383. static long _vq_quantlist__44u5__p8_0[] = {
  148384. 5,
  148385. 4,
  148386. 6,
  148387. 3,
  148388. 7,
  148389. 2,
  148390. 8,
  148391. 1,
  148392. 9,
  148393. 0,
  148394. 10,
  148395. };
  148396. static long _vq_lengthlist__44u5__p8_0[] = {
  148397. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  148398. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  148399. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  148400. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  148401. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  148402. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  148403. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  148404. 12,13,13,14,14,14,14,15,15,
  148405. };
  148406. static float _vq_quantthresh__44u5__p8_0[] = {
  148407. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  148408. 38.5, 49.5,
  148409. };
  148410. static long _vq_quantmap__44u5__p8_0[] = {
  148411. 9, 7, 5, 3, 1, 0, 2, 4,
  148412. 6, 8, 10,
  148413. };
  148414. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  148415. _vq_quantthresh__44u5__p8_0,
  148416. _vq_quantmap__44u5__p8_0,
  148417. 11,
  148418. 11
  148419. };
  148420. static static_codebook _44u5__p8_0 = {
  148421. 2, 121,
  148422. _vq_lengthlist__44u5__p8_0,
  148423. 1, -524582912, 1618345984, 4, 0,
  148424. _vq_quantlist__44u5__p8_0,
  148425. NULL,
  148426. &_vq_auxt__44u5__p8_0,
  148427. NULL,
  148428. 0
  148429. };
  148430. static long _vq_quantlist__44u5__p8_1[] = {
  148431. 5,
  148432. 4,
  148433. 6,
  148434. 3,
  148435. 7,
  148436. 2,
  148437. 8,
  148438. 1,
  148439. 9,
  148440. 0,
  148441. 10,
  148442. };
  148443. static long _vq_lengthlist__44u5__p8_1[] = {
  148444. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  148445. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  148446. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  148447. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  148448. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  148449. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  148450. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  148451. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  148452. };
  148453. static float _vq_quantthresh__44u5__p8_1[] = {
  148454. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  148455. 3.5, 4.5,
  148456. };
  148457. static long _vq_quantmap__44u5__p8_1[] = {
  148458. 9, 7, 5, 3, 1, 0, 2, 4,
  148459. 6, 8, 10,
  148460. };
  148461. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  148462. _vq_quantthresh__44u5__p8_1,
  148463. _vq_quantmap__44u5__p8_1,
  148464. 11,
  148465. 11
  148466. };
  148467. static static_codebook _44u5__p8_1 = {
  148468. 2, 121,
  148469. _vq_lengthlist__44u5__p8_1,
  148470. 1, -531365888, 1611661312, 4, 0,
  148471. _vq_quantlist__44u5__p8_1,
  148472. NULL,
  148473. &_vq_auxt__44u5__p8_1,
  148474. NULL,
  148475. 0
  148476. };
  148477. static long _vq_quantlist__44u5__p9_0[] = {
  148478. 6,
  148479. 5,
  148480. 7,
  148481. 4,
  148482. 8,
  148483. 3,
  148484. 9,
  148485. 2,
  148486. 10,
  148487. 1,
  148488. 11,
  148489. 0,
  148490. 12,
  148491. };
  148492. static long _vq_lengthlist__44u5__p9_0[] = {
  148493. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  148494. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  148495. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  148496. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  148497. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  148498. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  148499. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  148500. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  148501. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  148502. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148503. 12,12,12,12,12,12,12,12,12,
  148504. };
  148505. static float _vq_quantthresh__44u5__p9_0[] = {
  148506. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  148507. 637.5, 892.5, 1147.5, 1402.5,
  148508. };
  148509. static long _vq_quantmap__44u5__p9_0[] = {
  148510. 11, 9, 7, 5, 3, 1, 0, 2,
  148511. 4, 6, 8, 10, 12,
  148512. };
  148513. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  148514. _vq_quantthresh__44u5__p9_0,
  148515. _vq_quantmap__44u5__p9_0,
  148516. 13,
  148517. 13
  148518. };
  148519. static static_codebook _44u5__p9_0 = {
  148520. 2, 169,
  148521. _vq_lengthlist__44u5__p9_0,
  148522. 1, -514332672, 1627381760, 4, 0,
  148523. _vq_quantlist__44u5__p9_0,
  148524. NULL,
  148525. &_vq_auxt__44u5__p9_0,
  148526. NULL,
  148527. 0
  148528. };
  148529. static long _vq_quantlist__44u5__p9_1[] = {
  148530. 7,
  148531. 6,
  148532. 8,
  148533. 5,
  148534. 9,
  148535. 4,
  148536. 10,
  148537. 3,
  148538. 11,
  148539. 2,
  148540. 12,
  148541. 1,
  148542. 13,
  148543. 0,
  148544. 14,
  148545. };
  148546. static long _vq_lengthlist__44u5__p9_1[] = {
  148547. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  148548. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  148549. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  148550. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  148551. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  148552. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  148553. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  148554. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  148555. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  148556. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  148557. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  148558. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  148559. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  148560. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  148561. 14,
  148562. };
  148563. static float _vq_quantthresh__44u5__p9_1[] = {
  148564. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148565. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148566. };
  148567. static long _vq_quantmap__44u5__p9_1[] = {
  148568. 13, 11, 9, 7, 5, 3, 1, 0,
  148569. 2, 4, 6, 8, 10, 12, 14,
  148570. };
  148571. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  148572. _vq_quantthresh__44u5__p9_1,
  148573. _vq_quantmap__44u5__p9_1,
  148574. 15,
  148575. 15
  148576. };
  148577. static static_codebook _44u5__p9_1 = {
  148578. 2, 225,
  148579. _vq_lengthlist__44u5__p9_1,
  148580. 1, -522338304, 1620115456, 4, 0,
  148581. _vq_quantlist__44u5__p9_1,
  148582. NULL,
  148583. &_vq_auxt__44u5__p9_1,
  148584. NULL,
  148585. 0
  148586. };
  148587. static long _vq_quantlist__44u5__p9_2[] = {
  148588. 8,
  148589. 7,
  148590. 9,
  148591. 6,
  148592. 10,
  148593. 5,
  148594. 11,
  148595. 4,
  148596. 12,
  148597. 3,
  148598. 13,
  148599. 2,
  148600. 14,
  148601. 1,
  148602. 15,
  148603. 0,
  148604. 16,
  148605. };
  148606. static long _vq_lengthlist__44u5__p9_2[] = {
  148607. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148608. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  148609. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  148610. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  148611. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  148612. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  148613. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  148614. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  148615. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  148616. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  148617. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  148618. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  148619. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  148620. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148621. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  148622. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  148623. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  148624. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  148625. 10,
  148626. };
  148627. static float _vq_quantthresh__44u5__p9_2[] = {
  148628. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148629. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148630. };
  148631. static long _vq_quantmap__44u5__p9_2[] = {
  148632. 15, 13, 11, 9, 7, 5, 3, 1,
  148633. 0, 2, 4, 6, 8, 10, 12, 14,
  148634. 16,
  148635. };
  148636. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  148637. _vq_quantthresh__44u5__p9_2,
  148638. _vq_quantmap__44u5__p9_2,
  148639. 17,
  148640. 17
  148641. };
  148642. static static_codebook _44u5__p9_2 = {
  148643. 2, 289,
  148644. _vq_lengthlist__44u5__p9_2,
  148645. 1, -529530880, 1611661312, 5, 0,
  148646. _vq_quantlist__44u5__p9_2,
  148647. NULL,
  148648. &_vq_auxt__44u5__p9_2,
  148649. NULL,
  148650. 0
  148651. };
  148652. static long _huff_lengthlist__44u5__short[] = {
  148653. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  148654. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  148655. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  148656. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  148657. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  148658. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  148659. 6, 8,15,17,
  148660. };
  148661. static static_codebook _huff_book__44u5__short = {
  148662. 2, 100,
  148663. _huff_lengthlist__44u5__short,
  148664. 0, 0, 0, 0, 0,
  148665. NULL,
  148666. NULL,
  148667. NULL,
  148668. NULL,
  148669. 0
  148670. };
  148671. static long _huff_lengthlist__44u6__long[] = {
  148672. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  148673. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  148674. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  148675. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  148676. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  148677. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  148678. 13, 8, 7, 7,
  148679. };
  148680. static static_codebook _huff_book__44u6__long = {
  148681. 2, 100,
  148682. _huff_lengthlist__44u6__long,
  148683. 0, 0, 0, 0, 0,
  148684. NULL,
  148685. NULL,
  148686. NULL,
  148687. NULL,
  148688. 0
  148689. };
  148690. static long _vq_quantlist__44u6__p1_0[] = {
  148691. 1,
  148692. 0,
  148693. 2,
  148694. };
  148695. static long _vq_lengthlist__44u6__p1_0[] = {
  148696. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  148697. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  148698. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  148699. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  148700. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  148701. 12,
  148702. };
  148703. static float _vq_quantthresh__44u6__p1_0[] = {
  148704. -0.5, 0.5,
  148705. };
  148706. static long _vq_quantmap__44u6__p1_0[] = {
  148707. 1, 0, 2,
  148708. };
  148709. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  148710. _vq_quantthresh__44u6__p1_0,
  148711. _vq_quantmap__44u6__p1_0,
  148712. 3,
  148713. 3
  148714. };
  148715. static static_codebook _44u6__p1_0 = {
  148716. 4, 81,
  148717. _vq_lengthlist__44u6__p1_0,
  148718. 1, -535822336, 1611661312, 2, 0,
  148719. _vq_quantlist__44u6__p1_0,
  148720. NULL,
  148721. &_vq_auxt__44u6__p1_0,
  148722. NULL,
  148723. 0
  148724. };
  148725. static long _vq_quantlist__44u6__p2_0[] = {
  148726. 1,
  148727. 0,
  148728. 2,
  148729. };
  148730. static long _vq_lengthlist__44u6__p2_0[] = {
  148731. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  148732. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  148733. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  148734. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  148735. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  148736. 9,
  148737. };
  148738. static float _vq_quantthresh__44u6__p2_0[] = {
  148739. -0.5, 0.5,
  148740. };
  148741. static long _vq_quantmap__44u6__p2_0[] = {
  148742. 1, 0, 2,
  148743. };
  148744. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  148745. _vq_quantthresh__44u6__p2_0,
  148746. _vq_quantmap__44u6__p2_0,
  148747. 3,
  148748. 3
  148749. };
  148750. static static_codebook _44u6__p2_0 = {
  148751. 4, 81,
  148752. _vq_lengthlist__44u6__p2_0,
  148753. 1, -535822336, 1611661312, 2, 0,
  148754. _vq_quantlist__44u6__p2_0,
  148755. NULL,
  148756. &_vq_auxt__44u6__p2_0,
  148757. NULL,
  148758. 0
  148759. };
  148760. static long _vq_quantlist__44u6__p3_0[] = {
  148761. 2,
  148762. 1,
  148763. 3,
  148764. 0,
  148765. 4,
  148766. };
  148767. static long _vq_lengthlist__44u6__p3_0[] = {
  148768. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  148769. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  148770. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  148771. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  148772. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  148773. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  148774. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  148775. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  148776. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  148777. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  148778. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  148779. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  148780. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  148781. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  148782. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  148783. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  148784. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  148785. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  148786. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  148787. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  148788. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  148789. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  148790. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  148791. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  148792. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  148793. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  148794. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  148795. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  148796. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  148797. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  148798. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  148799. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  148800. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  148801. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  148802. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  148803. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  148804. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  148805. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  148806. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  148807. 19,
  148808. };
  148809. static float _vq_quantthresh__44u6__p3_0[] = {
  148810. -1.5, -0.5, 0.5, 1.5,
  148811. };
  148812. static long _vq_quantmap__44u6__p3_0[] = {
  148813. 3, 1, 0, 2, 4,
  148814. };
  148815. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  148816. _vq_quantthresh__44u6__p3_0,
  148817. _vq_quantmap__44u6__p3_0,
  148818. 5,
  148819. 5
  148820. };
  148821. static static_codebook _44u6__p3_0 = {
  148822. 4, 625,
  148823. _vq_lengthlist__44u6__p3_0,
  148824. 1, -533725184, 1611661312, 3, 0,
  148825. _vq_quantlist__44u6__p3_0,
  148826. NULL,
  148827. &_vq_auxt__44u6__p3_0,
  148828. NULL,
  148829. 0
  148830. };
  148831. static long _vq_quantlist__44u6__p4_0[] = {
  148832. 2,
  148833. 1,
  148834. 3,
  148835. 0,
  148836. 4,
  148837. };
  148838. static long _vq_lengthlist__44u6__p4_0[] = {
  148839. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  148840. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  148841. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  148842. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  148843. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  148844. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  148845. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  148846. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  148847. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  148848. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  148849. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  148850. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  148851. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  148852. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  148853. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  148854. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  148855. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  148856. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  148857. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  148858. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  148859. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  148860. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  148861. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  148862. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  148863. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  148864. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  148865. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  148866. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  148867. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  148868. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  148869. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  148870. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  148871. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  148872. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  148873. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  148874. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  148875. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  148876. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  148877. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  148878. 13,
  148879. };
  148880. static float _vq_quantthresh__44u6__p4_0[] = {
  148881. -1.5, -0.5, 0.5, 1.5,
  148882. };
  148883. static long _vq_quantmap__44u6__p4_0[] = {
  148884. 3, 1, 0, 2, 4,
  148885. };
  148886. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  148887. _vq_quantthresh__44u6__p4_0,
  148888. _vq_quantmap__44u6__p4_0,
  148889. 5,
  148890. 5
  148891. };
  148892. static static_codebook _44u6__p4_0 = {
  148893. 4, 625,
  148894. _vq_lengthlist__44u6__p4_0,
  148895. 1, -533725184, 1611661312, 3, 0,
  148896. _vq_quantlist__44u6__p4_0,
  148897. NULL,
  148898. &_vq_auxt__44u6__p4_0,
  148899. NULL,
  148900. 0
  148901. };
  148902. static long _vq_quantlist__44u6__p5_0[] = {
  148903. 4,
  148904. 3,
  148905. 5,
  148906. 2,
  148907. 6,
  148908. 1,
  148909. 7,
  148910. 0,
  148911. 8,
  148912. };
  148913. static long _vq_lengthlist__44u6__p5_0[] = {
  148914. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  148915. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  148916. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  148917. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  148918. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  148919. 14,
  148920. };
  148921. static float _vq_quantthresh__44u6__p5_0[] = {
  148922. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148923. };
  148924. static long _vq_quantmap__44u6__p5_0[] = {
  148925. 7, 5, 3, 1, 0, 2, 4, 6,
  148926. 8,
  148927. };
  148928. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  148929. _vq_quantthresh__44u6__p5_0,
  148930. _vq_quantmap__44u6__p5_0,
  148931. 9,
  148932. 9
  148933. };
  148934. static static_codebook _44u6__p5_0 = {
  148935. 2, 81,
  148936. _vq_lengthlist__44u6__p5_0,
  148937. 1, -531628032, 1611661312, 4, 0,
  148938. _vq_quantlist__44u6__p5_0,
  148939. NULL,
  148940. &_vq_auxt__44u6__p5_0,
  148941. NULL,
  148942. 0
  148943. };
  148944. static long _vq_quantlist__44u6__p6_0[] = {
  148945. 4,
  148946. 3,
  148947. 5,
  148948. 2,
  148949. 6,
  148950. 1,
  148951. 7,
  148952. 0,
  148953. 8,
  148954. };
  148955. static long _vq_lengthlist__44u6__p6_0[] = {
  148956. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  148957. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  148958. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  148959. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  148960. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  148961. 12,
  148962. };
  148963. static float _vq_quantthresh__44u6__p6_0[] = {
  148964. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148965. };
  148966. static long _vq_quantmap__44u6__p6_0[] = {
  148967. 7, 5, 3, 1, 0, 2, 4, 6,
  148968. 8,
  148969. };
  148970. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  148971. _vq_quantthresh__44u6__p6_0,
  148972. _vq_quantmap__44u6__p6_0,
  148973. 9,
  148974. 9
  148975. };
  148976. static static_codebook _44u6__p6_0 = {
  148977. 2, 81,
  148978. _vq_lengthlist__44u6__p6_0,
  148979. 1, -531628032, 1611661312, 4, 0,
  148980. _vq_quantlist__44u6__p6_0,
  148981. NULL,
  148982. &_vq_auxt__44u6__p6_0,
  148983. NULL,
  148984. 0
  148985. };
  148986. static long _vq_quantlist__44u6__p7_0[] = {
  148987. 1,
  148988. 0,
  148989. 2,
  148990. };
  148991. static long _vq_lengthlist__44u6__p7_0[] = {
  148992. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  148993. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  148994. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  148995. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  148996. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  148997. 10,
  148998. };
  148999. static float _vq_quantthresh__44u6__p7_0[] = {
  149000. -5.5, 5.5,
  149001. };
  149002. static long _vq_quantmap__44u6__p7_0[] = {
  149003. 1, 0, 2,
  149004. };
  149005. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  149006. _vq_quantthresh__44u6__p7_0,
  149007. _vq_quantmap__44u6__p7_0,
  149008. 3,
  149009. 3
  149010. };
  149011. static static_codebook _44u6__p7_0 = {
  149012. 4, 81,
  149013. _vq_lengthlist__44u6__p7_0,
  149014. 1, -529137664, 1618345984, 2, 0,
  149015. _vq_quantlist__44u6__p7_0,
  149016. NULL,
  149017. &_vq_auxt__44u6__p7_0,
  149018. NULL,
  149019. 0
  149020. };
  149021. static long _vq_quantlist__44u6__p7_1[] = {
  149022. 5,
  149023. 4,
  149024. 6,
  149025. 3,
  149026. 7,
  149027. 2,
  149028. 8,
  149029. 1,
  149030. 9,
  149031. 0,
  149032. 10,
  149033. };
  149034. static long _vq_lengthlist__44u6__p7_1[] = {
  149035. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  149036. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  149037. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  149038. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  149039. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  149040. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  149041. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  149042. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149043. };
  149044. static float _vq_quantthresh__44u6__p7_1[] = {
  149045. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149046. 3.5, 4.5,
  149047. };
  149048. static long _vq_quantmap__44u6__p7_1[] = {
  149049. 9, 7, 5, 3, 1, 0, 2, 4,
  149050. 6, 8, 10,
  149051. };
  149052. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  149053. _vq_quantthresh__44u6__p7_1,
  149054. _vq_quantmap__44u6__p7_1,
  149055. 11,
  149056. 11
  149057. };
  149058. static static_codebook _44u6__p7_1 = {
  149059. 2, 121,
  149060. _vq_lengthlist__44u6__p7_1,
  149061. 1, -531365888, 1611661312, 4, 0,
  149062. _vq_quantlist__44u6__p7_1,
  149063. NULL,
  149064. &_vq_auxt__44u6__p7_1,
  149065. NULL,
  149066. 0
  149067. };
  149068. static long _vq_quantlist__44u6__p8_0[] = {
  149069. 5,
  149070. 4,
  149071. 6,
  149072. 3,
  149073. 7,
  149074. 2,
  149075. 8,
  149076. 1,
  149077. 9,
  149078. 0,
  149079. 10,
  149080. };
  149081. static long _vq_lengthlist__44u6__p8_0[] = {
  149082. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  149083. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  149084. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  149085. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  149086. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  149087. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  149088. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  149089. 12,13,13,14,14,14,15,15,15,
  149090. };
  149091. static float _vq_quantthresh__44u6__p8_0[] = {
  149092. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  149093. 38.5, 49.5,
  149094. };
  149095. static long _vq_quantmap__44u6__p8_0[] = {
  149096. 9, 7, 5, 3, 1, 0, 2, 4,
  149097. 6, 8, 10,
  149098. };
  149099. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  149100. _vq_quantthresh__44u6__p8_0,
  149101. _vq_quantmap__44u6__p8_0,
  149102. 11,
  149103. 11
  149104. };
  149105. static static_codebook _44u6__p8_0 = {
  149106. 2, 121,
  149107. _vq_lengthlist__44u6__p8_0,
  149108. 1, -524582912, 1618345984, 4, 0,
  149109. _vq_quantlist__44u6__p8_0,
  149110. NULL,
  149111. &_vq_auxt__44u6__p8_0,
  149112. NULL,
  149113. 0
  149114. };
  149115. static long _vq_quantlist__44u6__p8_1[] = {
  149116. 5,
  149117. 4,
  149118. 6,
  149119. 3,
  149120. 7,
  149121. 2,
  149122. 8,
  149123. 1,
  149124. 9,
  149125. 0,
  149126. 10,
  149127. };
  149128. static long _vq_lengthlist__44u6__p8_1[] = {
  149129. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  149130. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  149131. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  149132. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  149133. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  149134. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  149135. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  149136. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149137. };
  149138. static float _vq_quantthresh__44u6__p8_1[] = {
  149139. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149140. 3.5, 4.5,
  149141. };
  149142. static long _vq_quantmap__44u6__p8_1[] = {
  149143. 9, 7, 5, 3, 1, 0, 2, 4,
  149144. 6, 8, 10,
  149145. };
  149146. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  149147. _vq_quantthresh__44u6__p8_1,
  149148. _vq_quantmap__44u6__p8_1,
  149149. 11,
  149150. 11
  149151. };
  149152. static static_codebook _44u6__p8_1 = {
  149153. 2, 121,
  149154. _vq_lengthlist__44u6__p8_1,
  149155. 1, -531365888, 1611661312, 4, 0,
  149156. _vq_quantlist__44u6__p8_1,
  149157. NULL,
  149158. &_vq_auxt__44u6__p8_1,
  149159. NULL,
  149160. 0
  149161. };
  149162. static long _vq_quantlist__44u6__p9_0[] = {
  149163. 7,
  149164. 6,
  149165. 8,
  149166. 5,
  149167. 9,
  149168. 4,
  149169. 10,
  149170. 3,
  149171. 11,
  149172. 2,
  149173. 12,
  149174. 1,
  149175. 13,
  149176. 0,
  149177. 14,
  149178. };
  149179. static long _vq_lengthlist__44u6__p9_0[] = {
  149180. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  149181. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  149182. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  149183. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  149184. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149185. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149186. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149187. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149188. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149189. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149190. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149191. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149192. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149193. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149194. 14,
  149195. };
  149196. static float _vq_quantthresh__44u6__p9_0[] = {
  149197. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  149198. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  149199. };
  149200. static long _vq_quantmap__44u6__p9_0[] = {
  149201. 13, 11, 9, 7, 5, 3, 1, 0,
  149202. 2, 4, 6, 8, 10, 12, 14,
  149203. };
  149204. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  149205. _vq_quantthresh__44u6__p9_0,
  149206. _vq_quantmap__44u6__p9_0,
  149207. 15,
  149208. 15
  149209. };
  149210. static static_codebook _44u6__p9_0 = {
  149211. 2, 225,
  149212. _vq_lengthlist__44u6__p9_0,
  149213. 1, -514071552, 1627381760, 4, 0,
  149214. _vq_quantlist__44u6__p9_0,
  149215. NULL,
  149216. &_vq_auxt__44u6__p9_0,
  149217. NULL,
  149218. 0
  149219. };
  149220. static long _vq_quantlist__44u6__p9_1[] = {
  149221. 7,
  149222. 6,
  149223. 8,
  149224. 5,
  149225. 9,
  149226. 4,
  149227. 10,
  149228. 3,
  149229. 11,
  149230. 2,
  149231. 12,
  149232. 1,
  149233. 13,
  149234. 0,
  149235. 14,
  149236. };
  149237. static long _vq_lengthlist__44u6__p9_1[] = {
  149238. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  149239. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  149240. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  149241. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  149242. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  149243. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  149244. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  149245. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  149246. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  149247. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  149248. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  149249. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  149250. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  149251. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  149252. 13,
  149253. };
  149254. static float _vq_quantthresh__44u6__p9_1[] = {
  149255. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  149256. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  149257. };
  149258. static long _vq_quantmap__44u6__p9_1[] = {
  149259. 13, 11, 9, 7, 5, 3, 1, 0,
  149260. 2, 4, 6, 8, 10, 12, 14,
  149261. };
  149262. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  149263. _vq_quantthresh__44u6__p9_1,
  149264. _vq_quantmap__44u6__p9_1,
  149265. 15,
  149266. 15
  149267. };
  149268. static static_codebook _44u6__p9_1 = {
  149269. 2, 225,
  149270. _vq_lengthlist__44u6__p9_1,
  149271. 1, -522338304, 1620115456, 4, 0,
  149272. _vq_quantlist__44u6__p9_1,
  149273. NULL,
  149274. &_vq_auxt__44u6__p9_1,
  149275. NULL,
  149276. 0
  149277. };
  149278. static long _vq_quantlist__44u6__p9_2[] = {
  149279. 8,
  149280. 7,
  149281. 9,
  149282. 6,
  149283. 10,
  149284. 5,
  149285. 11,
  149286. 4,
  149287. 12,
  149288. 3,
  149289. 13,
  149290. 2,
  149291. 14,
  149292. 1,
  149293. 15,
  149294. 0,
  149295. 16,
  149296. };
  149297. static long _vq_lengthlist__44u6__p9_2[] = {
  149298. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  149299. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  149300. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  149301. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149302. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149303. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149304. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149305. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149306. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  149307. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  149308. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  149309. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  149310. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  149311. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  149312. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  149313. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  149314. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  149315. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  149316. 10,
  149317. };
  149318. static float _vq_quantthresh__44u6__p9_2[] = {
  149319. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149320. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149321. };
  149322. static long _vq_quantmap__44u6__p9_2[] = {
  149323. 15, 13, 11, 9, 7, 5, 3, 1,
  149324. 0, 2, 4, 6, 8, 10, 12, 14,
  149325. 16,
  149326. };
  149327. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  149328. _vq_quantthresh__44u6__p9_2,
  149329. _vq_quantmap__44u6__p9_2,
  149330. 17,
  149331. 17
  149332. };
  149333. static static_codebook _44u6__p9_2 = {
  149334. 2, 289,
  149335. _vq_lengthlist__44u6__p9_2,
  149336. 1, -529530880, 1611661312, 5, 0,
  149337. _vq_quantlist__44u6__p9_2,
  149338. NULL,
  149339. &_vq_auxt__44u6__p9_2,
  149340. NULL,
  149341. 0
  149342. };
  149343. static long _huff_lengthlist__44u6__short[] = {
  149344. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  149345. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  149346. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  149347. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  149348. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  149349. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  149350. 7, 6, 9,16,
  149351. };
  149352. static static_codebook _huff_book__44u6__short = {
  149353. 2, 100,
  149354. _huff_lengthlist__44u6__short,
  149355. 0, 0, 0, 0, 0,
  149356. NULL,
  149357. NULL,
  149358. NULL,
  149359. NULL,
  149360. 0
  149361. };
  149362. static long _huff_lengthlist__44u7__long[] = {
  149363. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  149364. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  149365. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  149366. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  149367. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  149368. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  149369. 12, 8, 6, 7,
  149370. };
  149371. static static_codebook _huff_book__44u7__long = {
  149372. 2, 100,
  149373. _huff_lengthlist__44u7__long,
  149374. 0, 0, 0, 0, 0,
  149375. NULL,
  149376. NULL,
  149377. NULL,
  149378. NULL,
  149379. 0
  149380. };
  149381. static long _vq_quantlist__44u7__p1_0[] = {
  149382. 1,
  149383. 0,
  149384. 2,
  149385. };
  149386. static long _vq_lengthlist__44u7__p1_0[] = {
  149387. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149388. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  149389. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149390. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  149391. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  149392. 12,
  149393. };
  149394. static float _vq_quantthresh__44u7__p1_0[] = {
  149395. -0.5, 0.5,
  149396. };
  149397. static long _vq_quantmap__44u7__p1_0[] = {
  149398. 1, 0, 2,
  149399. };
  149400. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  149401. _vq_quantthresh__44u7__p1_0,
  149402. _vq_quantmap__44u7__p1_0,
  149403. 3,
  149404. 3
  149405. };
  149406. static static_codebook _44u7__p1_0 = {
  149407. 4, 81,
  149408. _vq_lengthlist__44u7__p1_0,
  149409. 1, -535822336, 1611661312, 2, 0,
  149410. _vq_quantlist__44u7__p1_0,
  149411. NULL,
  149412. &_vq_auxt__44u7__p1_0,
  149413. NULL,
  149414. 0
  149415. };
  149416. static long _vq_quantlist__44u7__p2_0[] = {
  149417. 1,
  149418. 0,
  149419. 2,
  149420. };
  149421. static long _vq_lengthlist__44u7__p2_0[] = {
  149422. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149423. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149424. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  149425. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149426. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149427. 9,
  149428. };
  149429. static float _vq_quantthresh__44u7__p2_0[] = {
  149430. -0.5, 0.5,
  149431. };
  149432. static long _vq_quantmap__44u7__p2_0[] = {
  149433. 1, 0, 2,
  149434. };
  149435. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  149436. _vq_quantthresh__44u7__p2_0,
  149437. _vq_quantmap__44u7__p2_0,
  149438. 3,
  149439. 3
  149440. };
  149441. static static_codebook _44u7__p2_0 = {
  149442. 4, 81,
  149443. _vq_lengthlist__44u7__p2_0,
  149444. 1, -535822336, 1611661312, 2, 0,
  149445. _vq_quantlist__44u7__p2_0,
  149446. NULL,
  149447. &_vq_auxt__44u7__p2_0,
  149448. NULL,
  149449. 0
  149450. };
  149451. static long _vq_quantlist__44u7__p3_0[] = {
  149452. 2,
  149453. 1,
  149454. 3,
  149455. 0,
  149456. 4,
  149457. };
  149458. static long _vq_lengthlist__44u7__p3_0[] = {
  149459. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149460. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  149461. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149462. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  149463. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  149464. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  149465. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  149466. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  149467. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  149468. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  149469. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  149470. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  149471. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  149472. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  149473. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  149474. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  149475. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  149476. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  149477. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  149478. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  149479. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  149480. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  149481. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  149482. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  149483. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  149484. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  149485. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  149486. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  149487. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  149488. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  149489. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  149490. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  149491. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  149492. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  149493. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  149494. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  149495. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  149496. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  149497. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  149498. 0,
  149499. };
  149500. static float _vq_quantthresh__44u7__p3_0[] = {
  149501. -1.5, -0.5, 0.5, 1.5,
  149502. };
  149503. static long _vq_quantmap__44u7__p3_0[] = {
  149504. 3, 1, 0, 2, 4,
  149505. };
  149506. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  149507. _vq_quantthresh__44u7__p3_0,
  149508. _vq_quantmap__44u7__p3_0,
  149509. 5,
  149510. 5
  149511. };
  149512. static static_codebook _44u7__p3_0 = {
  149513. 4, 625,
  149514. _vq_lengthlist__44u7__p3_0,
  149515. 1, -533725184, 1611661312, 3, 0,
  149516. _vq_quantlist__44u7__p3_0,
  149517. NULL,
  149518. &_vq_auxt__44u7__p3_0,
  149519. NULL,
  149520. 0
  149521. };
  149522. static long _vq_quantlist__44u7__p4_0[] = {
  149523. 2,
  149524. 1,
  149525. 3,
  149526. 0,
  149527. 4,
  149528. };
  149529. static long _vq_lengthlist__44u7__p4_0[] = {
  149530. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149531. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  149532. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  149533. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  149534. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  149535. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  149536. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  149537. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  149538. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  149539. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  149540. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  149541. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  149542. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149543. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  149544. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  149545. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  149546. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  149547. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  149548. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  149549. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  149550. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  149551. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  149552. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  149553. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  149554. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  149555. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  149556. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  149557. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  149558. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  149559. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  149560. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  149561. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149562. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  149563. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  149564. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  149565. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  149566. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  149567. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  149568. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  149569. 14,
  149570. };
  149571. static float _vq_quantthresh__44u7__p4_0[] = {
  149572. -1.5, -0.5, 0.5, 1.5,
  149573. };
  149574. static long _vq_quantmap__44u7__p4_0[] = {
  149575. 3, 1, 0, 2, 4,
  149576. };
  149577. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  149578. _vq_quantthresh__44u7__p4_0,
  149579. _vq_quantmap__44u7__p4_0,
  149580. 5,
  149581. 5
  149582. };
  149583. static static_codebook _44u7__p4_0 = {
  149584. 4, 625,
  149585. _vq_lengthlist__44u7__p4_0,
  149586. 1, -533725184, 1611661312, 3, 0,
  149587. _vq_quantlist__44u7__p4_0,
  149588. NULL,
  149589. &_vq_auxt__44u7__p4_0,
  149590. NULL,
  149591. 0
  149592. };
  149593. static long _vq_quantlist__44u7__p5_0[] = {
  149594. 4,
  149595. 3,
  149596. 5,
  149597. 2,
  149598. 6,
  149599. 1,
  149600. 7,
  149601. 0,
  149602. 8,
  149603. };
  149604. static long _vq_lengthlist__44u7__p5_0[] = {
  149605. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149606. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  149607. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  149608. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  149609. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  149610. 14,
  149611. };
  149612. static float _vq_quantthresh__44u7__p5_0[] = {
  149613. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149614. };
  149615. static long _vq_quantmap__44u7__p5_0[] = {
  149616. 7, 5, 3, 1, 0, 2, 4, 6,
  149617. 8,
  149618. };
  149619. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  149620. _vq_quantthresh__44u7__p5_0,
  149621. _vq_quantmap__44u7__p5_0,
  149622. 9,
  149623. 9
  149624. };
  149625. static static_codebook _44u7__p5_0 = {
  149626. 2, 81,
  149627. _vq_lengthlist__44u7__p5_0,
  149628. 1, -531628032, 1611661312, 4, 0,
  149629. _vq_quantlist__44u7__p5_0,
  149630. NULL,
  149631. &_vq_auxt__44u7__p5_0,
  149632. NULL,
  149633. 0
  149634. };
  149635. static long _vq_quantlist__44u7__p6_0[] = {
  149636. 4,
  149637. 3,
  149638. 5,
  149639. 2,
  149640. 6,
  149641. 1,
  149642. 7,
  149643. 0,
  149644. 8,
  149645. };
  149646. static long _vq_lengthlist__44u7__p6_0[] = {
  149647. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  149648. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  149649. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  149650. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  149651. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  149652. 12,
  149653. };
  149654. static float _vq_quantthresh__44u7__p6_0[] = {
  149655. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149656. };
  149657. static long _vq_quantmap__44u7__p6_0[] = {
  149658. 7, 5, 3, 1, 0, 2, 4, 6,
  149659. 8,
  149660. };
  149661. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  149662. _vq_quantthresh__44u7__p6_0,
  149663. _vq_quantmap__44u7__p6_0,
  149664. 9,
  149665. 9
  149666. };
  149667. static static_codebook _44u7__p6_0 = {
  149668. 2, 81,
  149669. _vq_lengthlist__44u7__p6_0,
  149670. 1, -531628032, 1611661312, 4, 0,
  149671. _vq_quantlist__44u7__p6_0,
  149672. NULL,
  149673. &_vq_auxt__44u7__p6_0,
  149674. NULL,
  149675. 0
  149676. };
  149677. static long _vq_quantlist__44u7__p7_0[] = {
  149678. 1,
  149679. 0,
  149680. 2,
  149681. };
  149682. static long _vq_lengthlist__44u7__p7_0[] = {
  149683. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  149684. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  149685. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  149686. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  149687. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  149688. 10,
  149689. };
  149690. static float _vq_quantthresh__44u7__p7_0[] = {
  149691. -5.5, 5.5,
  149692. };
  149693. static long _vq_quantmap__44u7__p7_0[] = {
  149694. 1, 0, 2,
  149695. };
  149696. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  149697. _vq_quantthresh__44u7__p7_0,
  149698. _vq_quantmap__44u7__p7_0,
  149699. 3,
  149700. 3
  149701. };
  149702. static static_codebook _44u7__p7_0 = {
  149703. 4, 81,
  149704. _vq_lengthlist__44u7__p7_0,
  149705. 1, -529137664, 1618345984, 2, 0,
  149706. _vq_quantlist__44u7__p7_0,
  149707. NULL,
  149708. &_vq_auxt__44u7__p7_0,
  149709. NULL,
  149710. 0
  149711. };
  149712. static long _vq_quantlist__44u7__p7_1[] = {
  149713. 5,
  149714. 4,
  149715. 6,
  149716. 3,
  149717. 7,
  149718. 2,
  149719. 8,
  149720. 1,
  149721. 9,
  149722. 0,
  149723. 10,
  149724. };
  149725. static long _vq_lengthlist__44u7__p7_1[] = {
  149726. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  149727. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  149728. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  149729. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  149730. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  149731. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  149732. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  149733. 8, 9, 9, 9, 9, 9,10,10,10,
  149734. };
  149735. static float _vq_quantthresh__44u7__p7_1[] = {
  149736. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149737. 3.5, 4.5,
  149738. };
  149739. static long _vq_quantmap__44u7__p7_1[] = {
  149740. 9, 7, 5, 3, 1, 0, 2, 4,
  149741. 6, 8, 10,
  149742. };
  149743. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  149744. _vq_quantthresh__44u7__p7_1,
  149745. _vq_quantmap__44u7__p7_1,
  149746. 11,
  149747. 11
  149748. };
  149749. static static_codebook _44u7__p7_1 = {
  149750. 2, 121,
  149751. _vq_lengthlist__44u7__p7_1,
  149752. 1, -531365888, 1611661312, 4, 0,
  149753. _vq_quantlist__44u7__p7_1,
  149754. NULL,
  149755. &_vq_auxt__44u7__p7_1,
  149756. NULL,
  149757. 0
  149758. };
  149759. static long _vq_quantlist__44u7__p8_0[] = {
  149760. 5,
  149761. 4,
  149762. 6,
  149763. 3,
  149764. 7,
  149765. 2,
  149766. 8,
  149767. 1,
  149768. 9,
  149769. 0,
  149770. 10,
  149771. };
  149772. static long _vq_lengthlist__44u7__p8_0[] = {
  149773. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  149774. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  149775. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  149776. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  149777. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  149778. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  149779. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  149780. 12,13,13,14,14,15,15,15,16,
  149781. };
  149782. static float _vq_quantthresh__44u7__p8_0[] = {
  149783. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  149784. 38.5, 49.5,
  149785. };
  149786. static long _vq_quantmap__44u7__p8_0[] = {
  149787. 9, 7, 5, 3, 1, 0, 2, 4,
  149788. 6, 8, 10,
  149789. };
  149790. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  149791. _vq_quantthresh__44u7__p8_0,
  149792. _vq_quantmap__44u7__p8_0,
  149793. 11,
  149794. 11
  149795. };
  149796. static static_codebook _44u7__p8_0 = {
  149797. 2, 121,
  149798. _vq_lengthlist__44u7__p8_0,
  149799. 1, -524582912, 1618345984, 4, 0,
  149800. _vq_quantlist__44u7__p8_0,
  149801. NULL,
  149802. &_vq_auxt__44u7__p8_0,
  149803. NULL,
  149804. 0
  149805. };
  149806. static long _vq_quantlist__44u7__p8_1[] = {
  149807. 5,
  149808. 4,
  149809. 6,
  149810. 3,
  149811. 7,
  149812. 2,
  149813. 8,
  149814. 1,
  149815. 9,
  149816. 0,
  149817. 10,
  149818. };
  149819. static long _vq_lengthlist__44u7__p8_1[] = {
  149820. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  149821. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  149822. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  149823. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  149824. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  149825. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  149826. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  149827. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  149828. };
  149829. static float _vq_quantthresh__44u7__p8_1[] = {
  149830. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149831. 3.5, 4.5,
  149832. };
  149833. static long _vq_quantmap__44u7__p8_1[] = {
  149834. 9, 7, 5, 3, 1, 0, 2, 4,
  149835. 6, 8, 10,
  149836. };
  149837. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  149838. _vq_quantthresh__44u7__p8_1,
  149839. _vq_quantmap__44u7__p8_1,
  149840. 11,
  149841. 11
  149842. };
  149843. static static_codebook _44u7__p8_1 = {
  149844. 2, 121,
  149845. _vq_lengthlist__44u7__p8_1,
  149846. 1, -531365888, 1611661312, 4, 0,
  149847. _vq_quantlist__44u7__p8_1,
  149848. NULL,
  149849. &_vq_auxt__44u7__p8_1,
  149850. NULL,
  149851. 0
  149852. };
  149853. static long _vq_quantlist__44u7__p9_0[] = {
  149854. 5,
  149855. 4,
  149856. 6,
  149857. 3,
  149858. 7,
  149859. 2,
  149860. 8,
  149861. 1,
  149862. 9,
  149863. 0,
  149864. 10,
  149865. };
  149866. static long _vq_lengthlist__44u7__p9_0[] = {
  149867. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  149868. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  149869. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  149870. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  149871. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  149872. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  149873. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  149874. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  149875. };
  149876. static float _vq_quantthresh__44u7__p9_0[] = {
  149877. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  149878. 2229.5, 2866.5,
  149879. };
  149880. static long _vq_quantmap__44u7__p9_0[] = {
  149881. 9, 7, 5, 3, 1, 0, 2, 4,
  149882. 6, 8, 10,
  149883. };
  149884. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  149885. _vq_quantthresh__44u7__p9_0,
  149886. _vq_quantmap__44u7__p9_0,
  149887. 11,
  149888. 11
  149889. };
  149890. static static_codebook _44u7__p9_0 = {
  149891. 2, 121,
  149892. _vq_lengthlist__44u7__p9_0,
  149893. 1, -512171520, 1630791680, 4, 0,
  149894. _vq_quantlist__44u7__p9_0,
  149895. NULL,
  149896. &_vq_auxt__44u7__p9_0,
  149897. NULL,
  149898. 0
  149899. };
  149900. static long _vq_quantlist__44u7__p9_1[] = {
  149901. 6,
  149902. 5,
  149903. 7,
  149904. 4,
  149905. 8,
  149906. 3,
  149907. 9,
  149908. 2,
  149909. 10,
  149910. 1,
  149911. 11,
  149912. 0,
  149913. 12,
  149914. };
  149915. static long _vq_lengthlist__44u7__p9_1[] = {
  149916. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  149917. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  149918. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  149919. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  149920. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  149921. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  149922. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  149923. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  149924. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  149925. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  149926. 15,15,15,15,17,17,16,17,16,
  149927. };
  149928. static float _vq_quantthresh__44u7__p9_1[] = {
  149929. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  149930. 122.5, 171.5, 220.5, 269.5,
  149931. };
  149932. static long _vq_quantmap__44u7__p9_1[] = {
  149933. 11, 9, 7, 5, 3, 1, 0, 2,
  149934. 4, 6, 8, 10, 12,
  149935. };
  149936. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  149937. _vq_quantthresh__44u7__p9_1,
  149938. _vq_quantmap__44u7__p9_1,
  149939. 13,
  149940. 13
  149941. };
  149942. static static_codebook _44u7__p9_1 = {
  149943. 2, 169,
  149944. _vq_lengthlist__44u7__p9_1,
  149945. 1, -518889472, 1622704128, 4, 0,
  149946. _vq_quantlist__44u7__p9_1,
  149947. NULL,
  149948. &_vq_auxt__44u7__p9_1,
  149949. NULL,
  149950. 0
  149951. };
  149952. static long _vq_quantlist__44u7__p9_2[] = {
  149953. 24,
  149954. 23,
  149955. 25,
  149956. 22,
  149957. 26,
  149958. 21,
  149959. 27,
  149960. 20,
  149961. 28,
  149962. 19,
  149963. 29,
  149964. 18,
  149965. 30,
  149966. 17,
  149967. 31,
  149968. 16,
  149969. 32,
  149970. 15,
  149971. 33,
  149972. 14,
  149973. 34,
  149974. 13,
  149975. 35,
  149976. 12,
  149977. 36,
  149978. 11,
  149979. 37,
  149980. 10,
  149981. 38,
  149982. 9,
  149983. 39,
  149984. 8,
  149985. 40,
  149986. 7,
  149987. 41,
  149988. 6,
  149989. 42,
  149990. 5,
  149991. 43,
  149992. 4,
  149993. 44,
  149994. 3,
  149995. 45,
  149996. 2,
  149997. 46,
  149998. 1,
  149999. 47,
  150000. 0,
  150001. 48,
  150002. };
  150003. static long _vq_lengthlist__44u7__p9_2[] = {
  150004. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  150005. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  150006. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  150007. 8,
  150008. };
  150009. static float _vq_quantthresh__44u7__p9_2[] = {
  150010. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  150011. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  150012. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150013. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150014. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  150015. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  150016. };
  150017. static long _vq_quantmap__44u7__p9_2[] = {
  150018. 47, 45, 43, 41, 39, 37, 35, 33,
  150019. 31, 29, 27, 25, 23, 21, 19, 17,
  150020. 15, 13, 11, 9, 7, 5, 3, 1,
  150021. 0, 2, 4, 6, 8, 10, 12, 14,
  150022. 16, 18, 20, 22, 24, 26, 28, 30,
  150023. 32, 34, 36, 38, 40, 42, 44, 46,
  150024. 48,
  150025. };
  150026. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  150027. _vq_quantthresh__44u7__p9_2,
  150028. _vq_quantmap__44u7__p9_2,
  150029. 49,
  150030. 49
  150031. };
  150032. static static_codebook _44u7__p9_2 = {
  150033. 1, 49,
  150034. _vq_lengthlist__44u7__p9_2,
  150035. 1, -526909440, 1611661312, 6, 0,
  150036. _vq_quantlist__44u7__p9_2,
  150037. NULL,
  150038. &_vq_auxt__44u7__p9_2,
  150039. NULL,
  150040. 0
  150041. };
  150042. static long _huff_lengthlist__44u7__short[] = {
  150043. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  150044. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  150045. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  150046. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  150047. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  150048. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  150049. 6, 8, 5, 9,
  150050. };
  150051. static static_codebook _huff_book__44u7__short = {
  150052. 2, 100,
  150053. _huff_lengthlist__44u7__short,
  150054. 0, 0, 0, 0, 0,
  150055. NULL,
  150056. NULL,
  150057. NULL,
  150058. NULL,
  150059. 0
  150060. };
  150061. static long _huff_lengthlist__44u8__long[] = {
  150062. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  150063. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  150064. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  150065. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  150066. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  150067. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  150068. 10, 8, 8, 9,
  150069. };
  150070. static static_codebook _huff_book__44u8__long = {
  150071. 2, 100,
  150072. _huff_lengthlist__44u8__long,
  150073. 0, 0, 0, 0, 0,
  150074. NULL,
  150075. NULL,
  150076. NULL,
  150077. NULL,
  150078. 0
  150079. };
  150080. static long _huff_lengthlist__44u8__short[] = {
  150081. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  150082. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  150083. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  150084. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  150085. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  150086. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  150087. 10,10,15,17,
  150088. };
  150089. static static_codebook _huff_book__44u8__short = {
  150090. 2, 100,
  150091. _huff_lengthlist__44u8__short,
  150092. 0, 0, 0, 0, 0,
  150093. NULL,
  150094. NULL,
  150095. NULL,
  150096. NULL,
  150097. 0
  150098. };
  150099. static long _vq_quantlist__44u8_p1_0[] = {
  150100. 1,
  150101. 0,
  150102. 2,
  150103. };
  150104. static long _vq_lengthlist__44u8_p1_0[] = {
  150105. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  150106. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  150107. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  150108. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  150109. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  150110. 10,
  150111. };
  150112. static float _vq_quantthresh__44u8_p1_0[] = {
  150113. -0.5, 0.5,
  150114. };
  150115. static long _vq_quantmap__44u8_p1_0[] = {
  150116. 1, 0, 2,
  150117. };
  150118. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  150119. _vq_quantthresh__44u8_p1_0,
  150120. _vq_quantmap__44u8_p1_0,
  150121. 3,
  150122. 3
  150123. };
  150124. static static_codebook _44u8_p1_0 = {
  150125. 4, 81,
  150126. _vq_lengthlist__44u8_p1_0,
  150127. 1, -535822336, 1611661312, 2, 0,
  150128. _vq_quantlist__44u8_p1_0,
  150129. NULL,
  150130. &_vq_auxt__44u8_p1_0,
  150131. NULL,
  150132. 0
  150133. };
  150134. static long _vq_quantlist__44u8_p2_0[] = {
  150135. 2,
  150136. 1,
  150137. 3,
  150138. 0,
  150139. 4,
  150140. };
  150141. static long _vq_lengthlist__44u8_p2_0[] = {
  150142. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  150143. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  150144. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  150145. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  150146. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  150147. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  150148. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150149. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  150150. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  150151. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  150152. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  150153. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  150154. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  150155. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  150156. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  150157. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  150158. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  150159. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  150160. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  150161. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  150162. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  150163. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  150164. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  150165. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  150166. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  150167. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  150168. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  150169. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  150170. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  150171. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  150172. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  150173. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150174. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  150175. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  150176. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  150177. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  150178. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  150179. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  150180. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  150181. 14,
  150182. };
  150183. static float _vq_quantthresh__44u8_p2_0[] = {
  150184. -1.5, -0.5, 0.5, 1.5,
  150185. };
  150186. static long _vq_quantmap__44u8_p2_0[] = {
  150187. 3, 1, 0, 2, 4,
  150188. };
  150189. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  150190. _vq_quantthresh__44u8_p2_0,
  150191. _vq_quantmap__44u8_p2_0,
  150192. 5,
  150193. 5
  150194. };
  150195. static static_codebook _44u8_p2_0 = {
  150196. 4, 625,
  150197. _vq_lengthlist__44u8_p2_0,
  150198. 1, -533725184, 1611661312, 3, 0,
  150199. _vq_quantlist__44u8_p2_0,
  150200. NULL,
  150201. &_vq_auxt__44u8_p2_0,
  150202. NULL,
  150203. 0
  150204. };
  150205. static long _vq_quantlist__44u8_p3_0[] = {
  150206. 4,
  150207. 3,
  150208. 5,
  150209. 2,
  150210. 6,
  150211. 1,
  150212. 7,
  150213. 0,
  150214. 8,
  150215. };
  150216. static long _vq_lengthlist__44u8_p3_0[] = {
  150217. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  150218. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  150219. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  150220. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  150221. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  150222. 12,
  150223. };
  150224. static float _vq_quantthresh__44u8_p3_0[] = {
  150225. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150226. };
  150227. static long _vq_quantmap__44u8_p3_0[] = {
  150228. 7, 5, 3, 1, 0, 2, 4, 6,
  150229. 8,
  150230. };
  150231. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  150232. _vq_quantthresh__44u8_p3_0,
  150233. _vq_quantmap__44u8_p3_0,
  150234. 9,
  150235. 9
  150236. };
  150237. static static_codebook _44u8_p3_0 = {
  150238. 2, 81,
  150239. _vq_lengthlist__44u8_p3_0,
  150240. 1, -531628032, 1611661312, 4, 0,
  150241. _vq_quantlist__44u8_p3_0,
  150242. NULL,
  150243. &_vq_auxt__44u8_p3_0,
  150244. NULL,
  150245. 0
  150246. };
  150247. static long _vq_quantlist__44u8_p4_0[] = {
  150248. 8,
  150249. 7,
  150250. 9,
  150251. 6,
  150252. 10,
  150253. 5,
  150254. 11,
  150255. 4,
  150256. 12,
  150257. 3,
  150258. 13,
  150259. 2,
  150260. 14,
  150261. 1,
  150262. 15,
  150263. 0,
  150264. 16,
  150265. };
  150266. static long _vq_lengthlist__44u8_p4_0[] = {
  150267. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  150268. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  150269. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  150270. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  150271. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  150272. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  150273. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  150274. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  150275. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  150276. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  150277. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  150278. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  150279. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  150280. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  150281. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  150282. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  150283. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  150284. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  150285. 14,
  150286. };
  150287. static float _vq_quantthresh__44u8_p4_0[] = {
  150288. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150289. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150290. };
  150291. static long _vq_quantmap__44u8_p4_0[] = {
  150292. 15, 13, 11, 9, 7, 5, 3, 1,
  150293. 0, 2, 4, 6, 8, 10, 12, 14,
  150294. 16,
  150295. };
  150296. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  150297. _vq_quantthresh__44u8_p4_0,
  150298. _vq_quantmap__44u8_p4_0,
  150299. 17,
  150300. 17
  150301. };
  150302. static static_codebook _44u8_p4_0 = {
  150303. 2, 289,
  150304. _vq_lengthlist__44u8_p4_0,
  150305. 1, -529530880, 1611661312, 5, 0,
  150306. _vq_quantlist__44u8_p4_0,
  150307. NULL,
  150308. &_vq_auxt__44u8_p4_0,
  150309. NULL,
  150310. 0
  150311. };
  150312. static long _vq_quantlist__44u8_p5_0[] = {
  150313. 1,
  150314. 0,
  150315. 2,
  150316. };
  150317. static long _vq_lengthlist__44u8_p5_0[] = {
  150318. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  150319. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  150320. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  150321. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  150322. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  150323. 10,
  150324. };
  150325. static float _vq_quantthresh__44u8_p5_0[] = {
  150326. -5.5, 5.5,
  150327. };
  150328. static long _vq_quantmap__44u8_p5_0[] = {
  150329. 1, 0, 2,
  150330. };
  150331. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  150332. _vq_quantthresh__44u8_p5_0,
  150333. _vq_quantmap__44u8_p5_0,
  150334. 3,
  150335. 3
  150336. };
  150337. static static_codebook _44u8_p5_0 = {
  150338. 4, 81,
  150339. _vq_lengthlist__44u8_p5_0,
  150340. 1, -529137664, 1618345984, 2, 0,
  150341. _vq_quantlist__44u8_p5_0,
  150342. NULL,
  150343. &_vq_auxt__44u8_p5_0,
  150344. NULL,
  150345. 0
  150346. };
  150347. static long _vq_quantlist__44u8_p5_1[] = {
  150348. 5,
  150349. 4,
  150350. 6,
  150351. 3,
  150352. 7,
  150353. 2,
  150354. 8,
  150355. 1,
  150356. 9,
  150357. 0,
  150358. 10,
  150359. };
  150360. static long _vq_lengthlist__44u8_p5_1[] = {
  150361. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  150362. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  150363. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  150364. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  150365. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  150366. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  150367. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  150368. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  150369. };
  150370. static float _vq_quantthresh__44u8_p5_1[] = {
  150371. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150372. 3.5, 4.5,
  150373. };
  150374. static long _vq_quantmap__44u8_p5_1[] = {
  150375. 9, 7, 5, 3, 1, 0, 2, 4,
  150376. 6, 8, 10,
  150377. };
  150378. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  150379. _vq_quantthresh__44u8_p5_1,
  150380. _vq_quantmap__44u8_p5_1,
  150381. 11,
  150382. 11
  150383. };
  150384. static static_codebook _44u8_p5_1 = {
  150385. 2, 121,
  150386. _vq_lengthlist__44u8_p5_1,
  150387. 1, -531365888, 1611661312, 4, 0,
  150388. _vq_quantlist__44u8_p5_1,
  150389. NULL,
  150390. &_vq_auxt__44u8_p5_1,
  150391. NULL,
  150392. 0
  150393. };
  150394. static long _vq_quantlist__44u8_p6_0[] = {
  150395. 6,
  150396. 5,
  150397. 7,
  150398. 4,
  150399. 8,
  150400. 3,
  150401. 9,
  150402. 2,
  150403. 10,
  150404. 1,
  150405. 11,
  150406. 0,
  150407. 12,
  150408. };
  150409. static long _vq_lengthlist__44u8_p6_0[] = {
  150410. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  150411. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  150412. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  150413. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  150414. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  150415. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  150416. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  150417. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  150418. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  150419. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  150420. 11,11,11,11,11,12,11,12,12,
  150421. };
  150422. static float _vq_quantthresh__44u8_p6_0[] = {
  150423. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  150424. 12.5, 17.5, 22.5, 27.5,
  150425. };
  150426. static long _vq_quantmap__44u8_p6_0[] = {
  150427. 11, 9, 7, 5, 3, 1, 0, 2,
  150428. 4, 6, 8, 10, 12,
  150429. };
  150430. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  150431. _vq_quantthresh__44u8_p6_0,
  150432. _vq_quantmap__44u8_p6_0,
  150433. 13,
  150434. 13
  150435. };
  150436. static static_codebook _44u8_p6_0 = {
  150437. 2, 169,
  150438. _vq_lengthlist__44u8_p6_0,
  150439. 1, -526516224, 1616117760, 4, 0,
  150440. _vq_quantlist__44u8_p6_0,
  150441. NULL,
  150442. &_vq_auxt__44u8_p6_0,
  150443. NULL,
  150444. 0
  150445. };
  150446. static long _vq_quantlist__44u8_p6_1[] = {
  150447. 2,
  150448. 1,
  150449. 3,
  150450. 0,
  150451. 4,
  150452. };
  150453. static long _vq_lengthlist__44u8_p6_1[] = {
  150454. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  150455. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  150456. };
  150457. static float _vq_quantthresh__44u8_p6_1[] = {
  150458. -1.5, -0.5, 0.5, 1.5,
  150459. };
  150460. static long _vq_quantmap__44u8_p6_1[] = {
  150461. 3, 1, 0, 2, 4,
  150462. };
  150463. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  150464. _vq_quantthresh__44u8_p6_1,
  150465. _vq_quantmap__44u8_p6_1,
  150466. 5,
  150467. 5
  150468. };
  150469. static static_codebook _44u8_p6_1 = {
  150470. 2, 25,
  150471. _vq_lengthlist__44u8_p6_1,
  150472. 1, -533725184, 1611661312, 3, 0,
  150473. _vq_quantlist__44u8_p6_1,
  150474. NULL,
  150475. &_vq_auxt__44u8_p6_1,
  150476. NULL,
  150477. 0
  150478. };
  150479. static long _vq_quantlist__44u8_p7_0[] = {
  150480. 6,
  150481. 5,
  150482. 7,
  150483. 4,
  150484. 8,
  150485. 3,
  150486. 9,
  150487. 2,
  150488. 10,
  150489. 1,
  150490. 11,
  150491. 0,
  150492. 12,
  150493. };
  150494. static long _vq_lengthlist__44u8_p7_0[] = {
  150495. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  150496. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  150497. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  150498. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  150499. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  150500. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  150501. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  150502. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  150503. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  150504. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  150505. 13,13,14,14,14,15,15,15,16,
  150506. };
  150507. static float _vq_quantthresh__44u8_p7_0[] = {
  150508. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  150509. 27.5, 38.5, 49.5, 60.5,
  150510. };
  150511. static long _vq_quantmap__44u8_p7_0[] = {
  150512. 11, 9, 7, 5, 3, 1, 0, 2,
  150513. 4, 6, 8, 10, 12,
  150514. };
  150515. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  150516. _vq_quantthresh__44u8_p7_0,
  150517. _vq_quantmap__44u8_p7_0,
  150518. 13,
  150519. 13
  150520. };
  150521. static static_codebook _44u8_p7_0 = {
  150522. 2, 169,
  150523. _vq_lengthlist__44u8_p7_0,
  150524. 1, -523206656, 1618345984, 4, 0,
  150525. _vq_quantlist__44u8_p7_0,
  150526. NULL,
  150527. &_vq_auxt__44u8_p7_0,
  150528. NULL,
  150529. 0
  150530. };
  150531. static long _vq_quantlist__44u8_p7_1[] = {
  150532. 5,
  150533. 4,
  150534. 6,
  150535. 3,
  150536. 7,
  150537. 2,
  150538. 8,
  150539. 1,
  150540. 9,
  150541. 0,
  150542. 10,
  150543. };
  150544. static long _vq_lengthlist__44u8_p7_1[] = {
  150545. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  150546. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  150547. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  150548. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  150549. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  150550. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  150551. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  150552. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  150553. };
  150554. static float _vq_quantthresh__44u8_p7_1[] = {
  150555. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150556. 3.5, 4.5,
  150557. };
  150558. static long _vq_quantmap__44u8_p7_1[] = {
  150559. 9, 7, 5, 3, 1, 0, 2, 4,
  150560. 6, 8, 10,
  150561. };
  150562. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  150563. _vq_quantthresh__44u8_p7_1,
  150564. _vq_quantmap__44u8_p7_1,
  150565. 11,
  150566. 11
  150567. };
  150568. static static_codebook _44u8_p7_1 = {
  150569. 2, 121,
  150570. _vq_lengthlist__44u8_p7_1,
  150571. 1, -531365888, 1611661312, 4, 0,
  150572. _vq_quantlist__44u8_p7_1,
  150573. NULL,
  150574. &_vq_auxt__44u8_p7_1,
  150575. NULL,
  150576. 0
  150577. };
  150578. static long _vq_quantlist__44u8_p8_0[] = {
  150579. 7,
  150580. 6,
  150581. 8,
  150582. 5,
  150583. 9,
  150584. 4,
  150585. 10,
  150586. 3,
  150587. 11,
  150588. 2,
  150589. 12,
  150590. 1,
  150591. 13,
  150592. 0,
  150593. 14,
  150594. };
  150595. static long _vq_lengthlist__44u8_p8_0[] = {
  150596. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  150597. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  150598. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  150599. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  150600. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  150601. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  150602. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  150603. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  150604. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  150605. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  150606. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  150607. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  150608. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  150609. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  150610. 17,
  150611. };
  150612. static float _vq_quantthresh__44u8_p8_0[] = {
  150613. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  150614. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  150615. };
  150616. static long _vq_quantmap__44u8_p8_0[] = {
  150617. 13, 11, 9, 7, 5, 3, 1, 0,
  150618. 2, 4, 6, 8, 10, 12, 14,
  150619. };
  150620. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  150621. _vq_quantthresh__44u8_p8_0,
  150622. _vq_quantmap__44u8_p8_0,
  150623. 15,
  150624. 15
  150625. };
  150626. static static_codebook _44u8_p8_0 = {
  150627. 2, 225,
  150628. _vq_lengthlist__44u8_p8_0,
  150629. 1, -520986624, 1620377600, 4, 0,
  150630. _vq_quantlist__44u8_p8_0,
  150631. NULL,
  150632. &_vq_auxt__44u8_p8_0,
  150633. NULL,
  150634. 0
  150635. };
  150636. static long _vq_quantlist__44u8_p8_1[] = {
  150637. 10,
  150638. 9,
  150639. 11,
  150640. 8,
  150641. 12,
  150642. 7,
  150643. 13,
  150644. 6,
  150645. 14,
  150646. 5,
  150647. 15,
  150648. 4,
  150649. 16,
  150650. 3,
  150651. 17,
  150652. 2,
  150653. 18,
  150654. 1,
  150655. 19,
  150656. 0,
  150657. 20,
  150658. };
  150659. static long _vq_lengthlist__44u8_p8_1[] = {
  150660. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  150661. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  150662. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  150663. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  150664. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150665. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150666. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  150667. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  150668. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  150669. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  150670. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  150671. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  150672. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  150673. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  150674. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  150675. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  150676. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  150677. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  150678. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  150679. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  150680. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150681. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  150682. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  150683. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  150684. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  150685. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  150686. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  150687. 10,10,10,10,10,10,10,10,10,
  150688. };
  150689. static float _vq_quantthresh__44u8_p8_1[] = {
  150690. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  150691. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  150692. 6.5, 7.5, 8.5, 9.5,
  150693. };
  150694. static long _vq_quantmap__44u8_p8_1[] = {
  150695. 19, 17, 15, 13, 11, 9, 7, 5,
  150696. 3, 1, 0, 2, 4, 6, 8, 10,
  150697. 12, 14, 16, 18, 20,
  150698. };
  150699. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  150700. _vq_quantthresh__44u8_p8_1,
  150701. _vq_quantmap__44u8_p8_1,
  150702. 21,
  150703. 21
  150704. };
  150705. static static_codebook _44u8_p8_1 = {
  150706. 2, 441,
  150707. _vq_lengthlist__44u8_p8_1,
  150708. 1, -529268736, 1611661312, 5, 0,
  150709. _vq_quantlist__44u8_p8_1,
  150710. NULL,
  150711. &_vq_auxt__44u8_p8_1,
  150712. NULL,
  150713. 0
  150714. };
  150715. static long _vq_quantlist__44u8_p9_0[] = {
  150716. 4,
  150717. 3,
  150718. 5,
  150719. 2,
  150720. 6,
  150721. 1,
  150722. 7,
  150723. 0,
  150724. 8,
  150725. };
  150726. static long _vq_lengthlist__44u8_p9_0[] = {
  150727. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  150728. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150729. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150730. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150731. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  150732. 8,
  150733. };
  150734. static float _vq_quantthresh__44u8_p9_0[] = {
  150735. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  150736. };
  150737. static long _vq_quantmap__44u8_p9_0[] = {
  150738. 7, 5, 3, 1, 0, 2, 4, 6,
  150739. 8,
  150740. };
  150741. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  150742. _vq_quantthresh__44u8_p9_0,
  150743. _vq_quantmap__44u8_p9_0,
  150744. 9,
  150745. 9
  150746. };
  150747. static static_codebook _44u8_p9_0 = {
  150748. 2, 81,
  150749. _vq_lengthlist__44u8_p9_0,
  150750. 1, -511895552, 1631393792, 4, 0,
  150751. _vq_quantlist__44u8_p9_0,
  150752. NULL,
  150753. &_vq_auxt__44u8_p9_0,
  150754. NULL,
  150755. 0
  150756. };
  150757. static long _vq_quantlist__44u8_p9_1[] = {
  150758. 9,
  150759. 8,
  150760. 10,
  150761. 7,
  150762. 11,
  150763. 6,
  150764. 12,
  150765. 5,
  150766. 13,
  150767. 4,
  150768. 14,
  150769. 3,
  150770. 15,
  150771. 2,
  150772. 16,
  150773. 1,
  150774. 17,
  150775. 0,
  150776. 18,
  150777. };
  150778. static long _vq_lengthlist__44u8_p9_1[] = {
  150779. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  150780. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  150781. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  150782. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  150783. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  150784. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  150785. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  150786. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  150787. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  150788. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  150789. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  150790. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  150791. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  150792. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  150793. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  150794. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  150795. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  150796. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  150797. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  150798. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  150799. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  150800. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  150801. 16,15,16,16,16,16,16,16,16,
  150802. };
  150803. static float _vq_quantthresh__44u8_p9_1[] = {
  150804. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  150805. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  150806. 367.5, 416.5,
  150807. };
  150808. static long _vq_quantmap__44u8_p9_1[] = {
  150809. 17, 15, 13, 11, 9, 7, 5, 3,
  150810. 1, 0, 2, 4, 6, 8, 10, 12,
  150811. 14, 16, 18,
  150812. };
  150813. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  150814. _vq_quantthresh__44u8_p9_1,
  150815. _vq_quantmap__44u8_p9_1,
  150816. 19,
  150817. 19
  150818. };
  150819. static static_codebook _44u8_p9_1 = {
  150820. 2, 361,
  150821. _vq_lengthlist__44u8_p9_1,
  150822. 1, -518287360, 1622704128, 5, 0,
  150823. _vq_quantlist__44u8_p9_1,
  150824. NULL,
  150825. &_vq_auxt__44u8_p9_1,
  150826. NULL,
  150827. 0
  150828. };
  150829. static long _vq_quantlist__44u8_p9_2[] = {
  150830. 24,
  150831. 23,
  150832. 25,
  150833. 22,
  150834. 26,
  150835. 21,
  150836. 27,
  150837. 20,
  150838. 28,
  150839. 19,
  150840. 29,
  150841. 18,
  150842. 30,
  150843. 17,
  150844. 31,
  150845. 16,
  150846. 32,
  150847. 15,
  150848. 33,
  150849. 14,
  150850. 34,
  150851. 13,
  150852. 35,
  150853. 12,
  150854. 36,
  150855. 11,
  150856. 37,
  150857. 10,
  150858. 38,
  150859. 9,
  150860. 39,
  150861. 8,
  150862. 40,
  150863. 7,
  150864. 41,
  150865. 6,
  150866. 42,
  150867. 5,
  150868. 43,
  150869. 4,
  150870. 44,
  150871. 3,
  150872. 45,
  150873. 2,
  150874. 46,
  150875. 1,
  150876. 47,
  150877. 0,
  150878. 48,
  150879. };
  150880. static long _vq_lengthlist__44u8_p9_2[] = {
  150881. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  150882. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  150883. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  150884. 7,
  150885. };
  150886. static float _vq_quantthresh__44u8_p9_2[] = {
  150887. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  150888. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  150889. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150890. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150891. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  150892. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  150893. };
  150894. static long _vq_quantmap__44u8_p9_2[] = {
  150895. 47, 45, 43, 41, 39, 37, 35, 33,
  150896. 31, 29, 27, 25, 23, 21, 19, 17,
  150897. 15, 13, 11, 9, 7, 5, 3, 1,
  150898. 0, 2, 4, 6, 8, 10, 12, 14,
  150899. 16, 18, 20, 22, 24, 26, 28, 30,
  150900. 32, 34, 36, 38, 40, 42, 44, 46,
  150901. 48,
  150902. };
  150903. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  150904. _vq_quantthresh__44u8_p9_2,
  150905. _vq_quantmap__44u8_p9_2,
  150906. 49,
  150907. 49
  150908. };
  150909. static static_codebook _44u8_p9_2 = {
  150910. 1, 49,
  150911. _vq_lengthlist__44u8_p9_2,
  150912. 1, -526909440, 1611661312, 6, 0,
  150913. _vq_quantlist__44u8_p9_2,
  150914. NULL,
  150915. &_vq_auxt__44u8_p9_2,
  150916. NULL,
  150917. 0
  150918. };
  150919. static long _huff_lengthlist__44u9__long[] = {
  150920. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  150921. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  150922. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  150923. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  150924. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  150925. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  150926. 10, 8, 8, 9,
  150927. };
  150928. static static_codebook _huff_book__44u9__long = {
  150929. 2, 100,
  150930. _huff_lengthlist__44u9__long,
  150931. 0, 0, 0, 0, 0,
  150932. NULL,
  150933. NULL,
  150934. NULL,
  150935. NULL,
  150936. 0
  150937. };
  150938. static long _huff_lengthlist__44u9__short[] = {
  150939. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  150940. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  150941. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  150942. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  150943. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  150944. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  150945. 9, 9,12,15,
  150946. };
  150947. static static_codebook _huff_book__44u9__short = {
  150948. 2, 100,
  150949. _huff_lengthlist__44u9__short,
  150950. 0, 0, 0, 0, 0,
  150951. NULL,
  150952. NULL,
  150953. NULL,
  150954. NULL,
  150955. 0
  150956. };
  150957. static long _vq_quantlist__44u9_p1_0[] = {
  150958. 1,
  150959. 0,
  150960. 2,
  150961. };
  150962. static long _vq_lengthlist__44u9_p1_0[] = {
  150963. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  150964. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  150965. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  150966. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  150967. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  150968. 10,
  150969. };
  150970. static float _vq_quantthresh__44u9_p1_0[] = {
  150971. -0.5, 0.5,
  150972. };
  150973. static long _vq_quantmap__44u9_p1_0[] = {
  150974. 1, 0, 2,
  150975. };
  150976. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  150977. _vq_quantthresh__44u9_p1_0,
  150978. _vq_quantmap__44u9_p1_0,
  150979. 3,
  150980. 3
  150981. };
  150982. static static_codebook _44u9_p1_0 = {
  150983. 4, 81,
  150984. _vq_lengthlist__44u9_p1_0,
  150985. 1, -535822336, 1611661312, 2, 0,
  150986. _vq_quantlist__44u9_p1_0,
  150987. NULL,
  150988. &_vq_auxt__44u9_p1_0,
  150989. NULL,
  150990. 0
  150991. };
  150992. static long _vq_quantlist__44u9_p2_0[] = {
  150993. 2,
  150994. 1,
  150995. 3,
  150996. 0,
  150997. 4,
  150998. };
  150999. static long _vq_lengthlist__44u9_p2_0[] = {
  151000. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  151001. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  151002. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  151003. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  151004. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  151005. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  151006. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  151007. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  151008. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  151009. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  151010. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  151011. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  151012. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  151013. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  151014. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  151015. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  151016. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  151017. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  151018. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  151019. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  151020. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  151021. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  151022. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  151023. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  151024. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  151025. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  151026. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  151027. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  151028. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  151029. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  151030. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  151031. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  151032. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  151033. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  151034. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  151035. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  151036. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  151037. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  151038. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  151039. 14,
  151040. };
  151041. static float _vq_quantthresh__44u9_p2_0[] = {
  151042. -1.5, -0.5, 0.5, 1.5,
  151043. };
  151044. static long _vq_quantmap__44u9_p2_0[] = {
  151045. 3, 1, 0, 2, 4,
  151046. };
  151047. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  151048. _vq_quantthresh__44u9_p2_0,
  151049. _vq_quantmap__44u9_p2_0,
  151050. 5,
  151051. 5
  151052. };
  151053. static static_codebook _44u9_p2_0 = {
  151054. 4, 625,
  151055. _vq_lengthlist__44u9_p2_0,
  151056. 1, -533725184, 1611661312, 3, 0,
  151057. _vq_quantlist__44u9_p2_0,
  151058. NULL,
  151059. &_vq_auxt__44u9_p2_0,
  151060. NULL,
  151061. 0
  151062. };
  151063. static long _vq_quantlist__44u9_p3_0[] = {
  151064. 4,
  151065. 3,
  151066. 5,
  151067. 2,
  151068. 6,
  151069. 1,
  151070. 7,
  151071. 0,
  151072. 8,
  151073. };
  151074. static long _vq_lengthlist__44u9_p3_0[] = {
  151075. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  151076. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  151077. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  151078. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  151079. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  151080. 11,
  151081. };
  151082. static float _vq_quantthresh__44u9_p3_0[] = {
  151083. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  151084. };
  151085. static long _vq_quantmap__44u9_p3_0[] = {
  151086. 7, 5, 3, 1, 0, 2, 4, 6,
  151087. 8,
  151088. };
  151089. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  151090. _vq_quantthresh__44u9_p3_0,
  151091. _vq_quantmap__44u9_p3_0,
  151092. 9,
  151093. 9
  151094. };
  151095. static static_codebook _44u9_p3_0 = {
  151096. 2, 81,
  151097. _vq_lengthlist__44u9_p3_0,
  151098. 1, -531628032, 1611661312, 4, 0,
  151099. _vq_quantlist__44u9_p3_0,
  151100. NULL,
  151101. &_vq_auxt__44u9_p3_0,
  151102. NULL,
  151103. 0
  151104. };
  151105. static long _vq_quantlist__44u9_p4_0[] = {
  151106. 8,
  151107. 7,
  151108. 9,
  151109. 6,
  151110. 10,
  151111. 5,
  151112. 11,
  151113. 4,
  151114. 12,
  151115. 3,
  151116. 13,
  151117. 2,
  151118. 14,
  151119. 1,
  151120. 15,
  151121. 0,
  151122. 16,
  151123. };
  151124. static long _vq_lengthlist__44u9_p4_0[] = {
  151125. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  151126. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  151127. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  151128. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  151129. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  151130. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  151131. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  151132. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  151133. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  151134. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  151135. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  151136. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  151137. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  151138. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  151139. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  151140. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  151141. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  151142. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  151143. 14,
  151144. };
  151145. static float _vq_quantthresh__44u9_p4_0[] = {
  151146. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151147. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151148. };
  151149. static long _vq_quantmap__44u9_p4_0[] = {
  151150. 15, 13, 11, 9, 7, 5, 3, 1,
  151151. 0, 2, 4, 6, 8, 10, 12, 14,
  151152. 16,
  151153. };
  151154. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  151155. _vq_quantthresh__44u9_p4_0,
  151156. _vq_quantmap__44u9_p4_0,
  151157. 17,
  151158. 17
  151159. };
  151160. static static_codebook _44u9_p4_0 = {
  151161. 2, 289,
  151162. _vq_lengthlist__44u9_p4_0,
  151163. 1, -529530880, 1611661312, 5, 0,
  151164. _vq_quantlist__44u9_p4_0,
  151165. NULL,
  151166. &_vq_auxt__44u9_p4_0,
  151167. NULL,
  151168. 0
  151169. };
  151170. static long _vq_quantlist__44u9_p5_0[] = {
  151171. 1,
  151172. 0,
  151173. 2,
  151174. };
  151175. static long _vq_lengthlist__44u9_p5_0[] = {
  151176. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  151177. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  151178. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  151179. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  151180. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  151181. 10,
  151182. };
  151183. static float _vq_quantthresh__44u9_p5_0[] = {
  151184. -5.5, 5.5,
  151185. };
  151186. static long _vq_quantmap__44u9_p5_0[] = {
  151187. 1, 0, 2,
  151188. };
  151189. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  151190. _vq_quantthresh__44u9_p5_0,
  151191. _vq_quantmap__44u9_p5_0,
  151192. 3,
  151193. 3
  151194. };
  151195. static static_codebook _44u9_p5_0 = {
  151196. 4, 81,
  151197. _vq_lengthlist__44u9_p5_0,
  151198. 1, -529137664, 1618345984, 2, 0,
  151199. _vq_quantlist__44u9_p5_0,
  151200. NULL,
  151201. &_vq_auxt__44u9_p5_0,
  151202. NULL,
  151203. 0
  151204. };
  151205. static long _vq_quantlist__44u9_p5_1[] = {
  151206. 5,
  151207. 4,
  151208. 6,
  151209. 3,
  151210. 7,
  151211. 2,
  151212. 8,
  151213. 1,
  151214. 9,
  151215. 0,
  151216. 10,
  151217. };
  151218. static long _vq_lengthlist__44u9_p5_1[] = {
  151219. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  151220. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  151221. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  151222. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  151223. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  151224. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  151225. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  151226. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  151227. };
  151228. static float _vq_quantthresh__44u9_p5_1[] = {
  151229. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151230. 3.5, 4.5,
  151231. };
  151232. static long _vq_quantmap__44u9_p5_1[] = {
  151233. 9, 7, 5, 3, 1, 0, 2, 4,
  151234. 6, 8, 10,
  151235. };
  151236. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  151237. _vq_quantthresh__44u9_p5_1,
  151238. _vq_quantmap__44u9_p5_1,
  151239. 11,
  151240. 11
  151241. };
  151242. static static_codebook _44u9_p5_1 = {
  151243. 2, 121,
  151244. _vq_lengthlist__44u9_p5_1,
  151245. 1, -531365888, 1611661312, 4, 0,
  151246. _vq_quantlist__44u9_p5_1,
  151247. NULL,
  151248. &_vq_auxt__44u9_p5_1,
  151249. NULL,
  151250. 0
  151251. };
  151252. static long _vq_quantlist__44u9_p6_0[] = {
  151253. 6,
  151254. 5,
  151255. 7,
  151256. 4,
  151257. 8,
  151258. 3,
  151259. 9,
  151260. 2,
  151261. 10,
  151262. 1,
  151263. 11,
  151264. 0,
  151265. 12,
  151266. };
  151267. static long _vq_lengthlist__44u9_p6_0[] = {
  151268. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  151269. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  151270. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  151271. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  151272. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  151273. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  151274. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  151275. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  151276. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  151277. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  151278. 10,11,11,11,11,12,11,12,12,
  151279. };
  151280. static float _vq_quantthresh__44u9_p6_0[] = {
  151281. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  151282. 12.5, 17.5, 22.5, 27.5,
  151283. };
  151284. static long _vq_quantmap__44u9_p6_0[] = {
  151285. 11, 9, 7, 5, 3, 1, 0, 2,
  151286. 4, 6, 8, 10, 12,
  151287. };
  151288. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  151289. _vq_quantthresh__44u9_p6_0,
  151290. _vq_quantmap__44u9_p6_0,
  151291. 13,
  151292. 13
  151293. };
  151294. static static_codebook _44u9_p6_0 = {
  151295. 2, 169,
  151296. _vq_lengthlist__44u9_p6_0,
  151297. 1, -526516224, 1616117760, 4, 0,
  151298. _vq_quantlist__44u9_p6_0,
  151299. NULL,
  151300. &_vq_auxt__44u9_p6_0,
  151301. NULL,
  151302. 0
  151303. };
  151304. static long _vq_quantlist__44u9_p6_1[] = {
  151305. 2,
  151306. 1,
  151307. 3,
  151308. 0,
  151309. 4,
  151310. };
  151311. static long _vq_lengthlist__44u9_p6_1[] = {
  151312. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  151313. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  151314. };
  151315. static float _vq_quantthresh__44u9_p6_1[] = {
  151316. -1.5, -0.5, 0.5, 1.5,
  151317. };
  151318. static long _vq_quantmap__44u9_p6_1[] = {
  151319. 3, 1, 0, 2, 4,
  151320. };
  151321. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  151322. _vq_quantthresh__44u9_p6_1,
  151323. _vq_quantmap__44u9_p6_1,
  151324. 5,
  151325. 5
  151326. };
  151327. static static_codebook _44u9_p6_1 = {
  151328. 2, 25,
  151329. _vq_lengthlist__44u9_p6_1,
  151330. 1, -533725184, 1611661312, 3, 0,
  151331. _vq_quantlist__44u9_p6_1,
  151332. NULL,
  151333. &_vq_auxt__44u9_p6_1,
  151334. NULL,
  151335. 0
  151336. };
  151337. static long _vq_quantlist__44u9_p7_0[] = {
  151338. 6,
  151339. 5,
  151340. 7,
  151341. 4,
  151342. 8,
  151343. 3,
  151344. 9,
  151345. 2,
  151346. 10,
  151347. 1,
  151348. 11,
  151349. 0,
  151350. 12,
  151351. };
  151352. static long _vq_lengthlist__44u9_p7_0[] = {
  151353. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  151354. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  151355. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  151356. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  151357. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  151358. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  151359. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  151360. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  151361. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  151362. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  151363. 12,13,13,14,14,14,15,15,15,
  151364. };
  151365. static float _vq_quantthresh__44u9_p7_0[] = {
  151366. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  151367. 27.5, 38.5, 49.5, 60.5,
  151368. };
  151369. static long _vq_quantmap__44u9_p7_0[] = {
  151370. 11, 9, 7, 5, 3, 1, 0, 2,
  151371. 4, 6, 8, 10, 12,
  151372. };
  151373. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  151374. _vq_quantthresh__44u9_p7_0,
  151375. _vq_quantmap__44u9_p7_0,
  151376. 13,
  151377. 13
  151378. };
  151379. static static_codebook _44u9_p7_0 = {
  151380. 2, 169,
  151381. _vq_lengthlist__44u9_p7_0,
  151382. 1, -523206656, 1618345984, 4, 0,
  151383. _vq_quantlist__44u9_p7_0,
  151384. NULL,
  151385. &_vq_auxt__44u9_p7_0,
  151386. NULL,
  151387. 0
  151388. };
  151389. static long _vq_quantlist__44u9_p7_1[] = {
  151390. 5,
  151391. 4,
  151392. 6,
  151393. 3,
  151394. 7,
  151395. 2,
  151396. 8,
  151397. 1,
  151398. 9,
  151399. 0,
  151400. 10,
  151401. };
  151402. static long _vq_lengthlist__44u9_p7_1[] = {
  151403. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  151404. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  151405. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  151406. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151407. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151408. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151409. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  151410. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  151411. };
  151412. static float _vq_quantthresh__44u9_p7_1[] = {
  151413. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151414. 3.5, 4.5,
  151415. };
  151416. static long _vq_quantmap__44u9_p7_1[] = {
  151417. 9, 7, 5, 3, 1, 0, 2, 4,
  151418. 6, 8, 10,
  151419. };
  151420. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  151421. _vq_quantthresh__44u9_p7_1,
  151422. _vq_quantmap__44u9_p7_1,
  151423. 11,
  151424. 11
  151425. };
  151426. static static_codebook _44u9_p7_1 = {
  151427. 2, 121,
  151428. _vq_lengthlist__44u9_p7_1,
  151429. 1, -531365888, 1611661312, 4, 0,
  151430. _vq_quantlist__44u9_p7_1,
  151431. NULL,
  151432. &_vq_auxt__44u9_p7_1,
  151433. NULL,
  151434. 0
  151435. };
  151436. static long _vq_quantlist__44u9_p8_0[] = {
  151437. 7,
  151438. 6,
  151439. 8,
  151440. 5,
  151441. 9,
  151442. 4,
  151443. 10,
  151444. 3,
  151445. 11,
  151446. 2,
  151447. 12,
  151448. 1,
  151449. 13,
  151450. 0,
  151451. 14,
  151452. };
  151453. static long _vq_lengthlist__44u9_p8_0[] = {
  151454. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  151455. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  151456. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  151457. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  151458. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  151459. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  151460. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  151461. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  151462. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  151463. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  151464. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  151465. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  151466. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  151467. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  151468. 15,
  151469. };
  151470. static float _vq_quantthresh__44u9_p8_0[] = {
  151471. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  151472. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  151473. };
  151474. static long _vq_quantmap__44u9_p8_0[] = {
  151475. 13, 11, 9, 7, 5, 3, 1, 0,
  151476. 2, 4, 6, 8, 10, 12, 14,
  151477. };
  151478. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  151479. _vq_quantthresh__44u9_p8_0,
  151480. _vq_quantmap__44u9_p8_0,
  151481. 15,
  151482. 15
  151483. };
  151484. static static_codebook _44u9_p8_0 = {
  151485. 2, 225,
  151486. _vq_lengthlist__44u9_p8_0,
  151487. 1, -520986624, 1620377600, 4, 0,
  151488. _vq_quantlist__44u9_p8_0,
  151489. NULL,
  151490. &_vq_auxt__44u9_p8_0,
  151491. NULL,
  151492. 0
  151493. };
  151494. static long _vq_quantlist__44u9_p8_1[] = {
  151495. 10,
  151496. 9,
  151497. 11,
  151498. 8,
  151499. 12,
  151500. 7,
  151501. 13,
  151502. 6,
  151503. 14,
  151504. 5,
  151505. 15,
  151506. 4,
  151507. 16,
  151508. 3,
  151509. 17,
  151510. 2,
  151511. 18,
  151512. 1,
  151513. 19,
  151514. 0,
  151515. 20,
  151516. };
  151517. static long _vq_lengthlist__44u9_p8_1[] = {
  151518. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  151519. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  151520. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  151521. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  151522. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  151523. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  151524. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  151525. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  151526. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151527. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151528. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  151529. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  151530. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151531. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  151532. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151533. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  151534. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  151535. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151536. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  151537. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  151538. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151539. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  151540. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  151541. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  151542. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  151543. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  151544. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  151545. 10,10,10,10,10,10,10,10,10,
  151546. };
  151547. static float _vq_quantthresh__44u9_p8_1[] = {
  151548. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  151549. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  151550. 6.5, 7.5, 8.5, 9.5,
  151551. };
  151552. static long _vq_quantmap__44u9_p8_1[] = {
  151553. 19, 17, 15, 13, 11, 9, 7, 5,
  151554. 3, 1, 0, 2, 4, 6, 8, 10,
  151555. 12, 14, 16, 18, 20,
  151556. };
  151557. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  151558. _vq_quantthresh__44u9_p8_1,
  151559. _vq_quantmap__44u9_p8_1,
  151560. 21,
  151561. 21
  151562. };
  151563. static static_codebook _44u9_p8_1 = {
  151564. 2, 441,
  151565. _vq_lengthlist__44u9_p8_1,
  151566. 1, -529268736, 1611661312, 5, 0,
  151567. _vq_quantlist__44u9_p8_1,
  151568. NULL,
  151569. &_vq_auxt__44u9_p8_1,
  151570. NULL,
  151571. 0
  151572. };
  151573. static long _vq_quantlist__44u9_p9_0[] = {
  151574. 7,
  151575. 6,
  151576. 8,
  151577. 5,
  151578. 9,
  151579. 4,
  151580. 10,
  151581. 3,
  151582. 11,
  151583. 2,
  151584. 12,
  151585. 1,
  151586. 13,
  151587. 0,
  151588. 14,
  151589. };
  151590. static long _vq_lengthlist__44u9_p9_0[] = {
  151591. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  151592. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  151593. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151594. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151595. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151596. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151597. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151598. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151599. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151600. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151601. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151602. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  151603. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151604. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151605. 10,
  151606. };
  151607. static float _vq_quantthresh__44u9_p9_0[] = {
  151608. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  151609. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  151610. };
  151611. static long _vq_quantmap__44u9_p9_0[] = {
  151612. 13, 11, 9, 7, 5, 3, 1, 0,
  151613. 2, 4, 6, 8, 10, 12, 14,
  151614. };
  151615. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  151616. _vq_quantthresh__44u9_p9_0,
  151617. _vq_quantmap__44u9_p9_0,
  151618. 15,
  151619. 15
  151620. };
  151621. static static_codebook _44u9_p9_0 = {
  151622. 2, 225,
  151623. _vq_lengthlist__44u9_p9_0,
  151624. 1, -510036736, 1631393792, 4, 0,
  151625. _vq_quantlist__44u9_p9_0,
  151626. NULL,
  151627. &_vq_auxt__44u9_p9_0,
  151628. NULL,
  151629. 0
  151630. };
  151631. static long _vq_quantlist__44u9_p9_1[] = {
  151632. 9,
  151633. 8,
  151634. 10,
  151635. 7,
  151636. 11,
  151637. 6,
  151638. 12,
  151639. 5,
  151640. 13,
  151641. 4,
  151642. 14,
  151643. 3,
  151644. 15,
  151645. 2,
  151646. 16,
  151647. 1,
  151648. 17,
  151649. 0,
  151650. 18,
  151651. };
  151652. static long _vq_lengthlist__44u9_p9_1[] = {
  151653. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  151654. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  151655. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  151656. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  151657. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  151658. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  151659. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  151660. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  151661. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  151662. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  151663. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  151664. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  151665. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  151666. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  151667. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  151668. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  151669. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  151670. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  151671. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  151672. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  151673. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  151674. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  151675. 17,17,15,17,15,17,16,16,17,
  151676. };
  151677. static float _vq_quantthresh__44u9_p9_1[] = {
  151678. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  151679. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  151680. 367.5, 416.5,
  151681. };
  151682. static long _vq_quantmap__44u9_p9_1[] = {
  151683. 17, 15, 13, 11, 9, 7, 5, 3,
  151684. 1, 0, 2, 4, 6, 8, 10, 12,
  151685. 14, 16, 18,
  151686. };
  151687. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  151688. _vq_quantthresh__44u9_p9_1,
  151689. _vq_quantmap__44u9_p9_1,
  151690. 19,
  151691. 19
  151692. };
  151693. static static_codebook _44u9_p9_1 = {
  151694. 2, 361,
  151695. _vq_lengthlist__44u9_p9_1,
  151696. 1, -518287360, 1622704128, 5, 0,
  151697. _vq_quantlist__44u9_p9_1,
  151698. NULL,
  151699. &_vq_auxt__44u9_p9_1,
  151700. NULL,
  151701. 0
  151702. };
  151703. static long _vq_quantlist__44u9_p9_2[] = {
  151704. 24,
  151705. 23,
  151706. 25,
  151707. 22,
  151708. 26,
  151709. 21,
  151710. 27,
  151711. 20,
  151712. 28,
  151713. 19,
  151714. 29,
  151715. 18,
  151716. 30,
  151717. 17,
  151718. 31,
  151719. 16,
  151720. 32,
  151721. 15,
  151722. 33,
  151723. 14,
  151724. 34,
  151725. 13,
  151726. 35,
  151727. 12,
  151728. 36,
  151729. 11,
  151730. 37,
  151731. 10,
  151732. 38,
  151733. 9,
  151734. 39,
  151735. 8,
  151736. 40,
  151737. 7,
  151738. 41,
  151739. 6,
  151740. 42,
  151741. 5,
  151742. 43,
  151743. 4,
  151744. 44,
  151745. 3,
  151746. 45,
  151747. 2,
  151748. 46,
  151749. 1,
  151750. 47,
  151751. 0,
  151752. 48,
  151753. };
  151754. static long _vq_lengthlist__44u9_p9_2[] = {
  151755. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  151756. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151757. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151758. 7,
  151759. };
  151760. static float _vq_quantthresh__44u9_p9_2[] = {
  151761. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  151762. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  151763. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151764. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151765. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  151766. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  151767. };
  151768. static long _vq_quantmap__44u9_p9_2[] = {
  151769. 47, 45, 43, 41, 39, 37, 35, 33,
  151770. 31, 29, 27, 25, 23, 21, 19, 17,
  151771. 15, 13, 11, 9, 7, 5, 3, 1,
  151772. 0, 2, 4, 6, 8, 10, 12, 14,
  151773. 16, 18, 20, 22, 24, 26, 28, 30,
  151774. 32, 34, 36, 38, 40, 42, 44, 46,
  151775. 48,
  151776. };
  151777. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  151778. _vq_quantthresh__44u9_p9_2,
  151779. _vq_quantmap__44u9_p9_2,
  151780. 49,
  151781. 49
  151782. };
  151783. static static_codebook _44u9_p9_2 = {
  151784. 1, 49,
  151785. _vq_lengthlist__44u9_p9_2,
  151786. 1, -526909440, 1611661312, 6, 0,
  151787. _vq_quantlist__44u9_p9_2,
  151788. NULL,
  151789. &_vq_auxt__44u9_p9_2,
  151790. NULL,
  151791. 0
  151792. };
  151793. static long _huff_lengthlist__44un1__long[] = {
  151794. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  151795. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  151796. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  151797. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  151798. };
  151799. static static_codebook _huff_book__44un1__long = {
  151800. 2, 64,
  151801. _huff_lengthlist__44un1__long,
  151802. 0, 0, 0, 0, 0,
  151803. NULL,
  151804. NULL,
  151805. NULL,
  151806. NULL,
  151807. 0
  151808. };
  151809. static long _vq_quantlist__44un1__p1_0[] = {
  151810. 1,
  151811. 0,
  151812. 2,
  151813. };
  151814. static long _vq_lengthlist__44un1__p1_0[] = {
  151815. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  151816. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  151817. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  151818. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  151819. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  151820. 12,
  151821. };
  151822. static float _vq_quantthresh__44un1__p1_0[] = {
  151823. -0.5, 0.5,
  151824. };
  151825. static long _vq_quantmap__44un1__p1_0[] = {
  151826. 1, 0, 2,
  151827. };
  151828. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  151829. _vq_quantthresh__44un1__p1_0,
  151830. _vq_quantmap__44un1__p1_0,
  151831. 3,
  151832. 3
  151833. };
  151834. static static_codebook _44un1__p1_0 = {
  151835. 4, 81,
  151836. _vq_lengthlist__44un1__p1_0,
  151837. 1, -535822336, 1611661312, 2, 0,
  151838. _vq_quantlist__44un1__p1_0,
  151839. NULL,
  151840. &_vq_auxt__44un1__p1_0,
  151841. NULL,
  151842. 0
  151843. };
  151844. static long _vq_quantlist__44un1__p2_0[] = {
  151845. 1,
  151846. 0,
  151847. 2,
  151848. };
  151849. static long _vq_lengthlist__44un1__p2_0[] = {
  151850. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  151851. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  151852. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  151853. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  151854. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  151855. 8,
  151856. };
  151857. static float _vq_quantthresh__44un1__p2_0[] = {
  151858. -0.5, 0.5,
  151859. };
  151860. static long _vq_quantmap__44un1__p2_0[] = {
  151861. 1, 0, 2,
  151862. };
  151863. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  151864. _vq_quantthresh__44un1__p2_0,
  151865. _vq_quantmap__44un1__p2_0,
  151866. 3,
  151867. 3
  151868. };
  151869. static static_codebook _44un1__p2_0 = {
  151870. 4, 81,
  151871. _vq_lengthlist__44un1__p2_0,
  151872. 1, -535822336, 1611661312, 2, 0,
  151873. _vq_quantlist__44un1__p2_0,
  151874. NULL,
  151875. &_vq_auxt__44un1__p2_0,
  151876. NULL,
  151877. 0
  151878. };
  151879. static long _vq_quantlist__44un1__p3_0[] = {
  151880. 2,
  151881. 1,
  151882. 3,
  151883. 0,
  151884. 4,
  151885. };
  151886. static long _vq_lengthlist__44un1__p3_0[] = {
  151887. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  151888. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  151889. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  151890. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  151891. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  151892. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  151893. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  151894. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  151895. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  151896. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  151897. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  151898. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  151899. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  151900. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  151901. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  151902. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  151903. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  151904. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  151905. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  151906. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  151907. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  151908. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  151909. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  151910. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  151911. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  151912. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  151913. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  151914. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  151915. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  151916. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  151917. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  151918. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  151919. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  151920. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  151921. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  151922. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  151923. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  151924. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  151925. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  151926. 17,
  151927. };
  151928. static float _vq_quantthresh__44un1__p3_0[] = {
  151929. -1.5, -0.5, 0.5, 1.5,
  151930. };
  151931. static long _vq_quantmap__44un1__p3_0[] = {
  151932. 3, 1, 0, 2, 4,
  151933. };
  151934. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  151935. _vq_quantthresh__44un1__p3_0,
  151936. _vq_quantmap__44un1__p3_0,
  151937. 5,
  151938. 5
  151939. };
  151940. static static_codebook _44un1__p3_0 = {
  151941. 4, 625,
  151942. _vq_lengthlist__44un1__p3_0,
  151943. 1, -533725184, 1611661312, 3, 0,
  151944. _vq_quantlist__44un1__p3_0,
  151945. NULL,
  151946. &_vq_auxt__44un1__p3_0,
  151947. NULL,
  151948. 0
  151949. };
  151950. static long _vq_quantlist__44un1__p4_0[] = {
  151951. 2,
  151952. 1,
  151953. 3,
  151954. 0,
  151955. 4,
  151956. };
  151957. static long _vq_lengthlist__44un1__p4_0[] = {
  151958. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  151959. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  151960. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  151961. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  151962. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  151963. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  151964. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  151965. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  151966. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  151967. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  151968. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  151969. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  151970. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  151971. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  151972. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  151973. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  151974. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  151975. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  151976. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  151977. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  151978. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  151979. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  151980. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  151981. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  151982. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  151983. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  151984. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  151985. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  151986. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  151987. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  151988. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  151989. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  151990. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  151991. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  151992. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  151993. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  151994. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  151995. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  151996. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  151997. 12,
  151998. };
  151999. static float _vq_quantthresh__44un1__p4_0[] = {
  152000. -1.5, -0.5, 0.5, 1.5,
  152001. };
  152002. static long _vq_quantmap__44un1__p4_0[] = {
  152003. 3, 1, 0, 2, 4,
  152004. };
  152005. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  152006. _vq_quantthresh__44un1__p4_0,
  152007. _vq_quantmap__44un1__p4_0,
  152008. 5,
  152009. 5
  152010. };
  152011. static static_codebook _44un1__p4_0 = {
  152012. 4, 625,
  152013. _vq_lengthlist__44un1__p4_0,
  152014. 1, -533725184, 1611661312, 3, 0,
  152015. _vq_quantlist__44un1__p4_0,
  152016. NULL,
  152017. &_vq_auxt__44un1__p4_0,
  152018. NULL,
  152019. 0
  152020. };
  152021. static long _vq_quantlist__44un1__p5_0[] = {
  152022. 4,
  152023. 3,
  152024. 5,
  152025. 2,
  152026. 6,
  152027. 1,
  152028. 7,
  152029. 0,
  152030. 8,
  152031. };
  152032. static long _vq_lengthlist__44un1__p5_0[] = {
  152033. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  152034. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  152035. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  152036. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  152037. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  152038. 12,
  152039. };
  152040. static float _vq_quantthresh__44un1__p5_0[] = {
  152041. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  152042. };
  152043. static long _vq_quantmap__44un1__p5_0[] = {
  152044. 7, 5, 3, 1, 0, 2, 4, 6,
  152045. 8,
  152046. };
  152047. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  152048. _vq_quantthresh__44un1__p5_0,
  152049. _vq_quantmap__44un1__p5_0,
  152050. 9,
  152051. 9
  152052. };
  152053. static static_codebook _44un1__p5_0 = {
  152054. 2, 81,
  152055. _vq_lengthlist__44un1__p5_0,
  152056. 1, -531628032, 1611661312, 4, 0,
  152057. _vq_quantlist__44un1__p5_0,
  152058. NULL,
  152059. &_vq_auxt__44un1__p5_0,
  152060. NULL,
  152061. 0
  152062. };
  152063. static long _vq_quantlist__44un1__p6_0[] = {
  152064. 6,
  152065. 5,
  152066. 7,
  152067. 4,
  152068. 8,
  152069. 3,
  152070. 9,
  152071. 2,
  152072. 10,
  152073. 1,
  152074. 11,
  152075. 0,
  152076. 12,
  152077. };
  152078. static long _vq_lengthlist__44un1__p6_0[] = {
  152079. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  152080. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  152081. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  152082. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  152083. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  152084. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  152085. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  152086. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  152087. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  152088. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  152089. 16, 0,15,18,18, 0,16, 0, 0,
  152090. };
  152091. static float _vq_quantthresh__44un1__p6_0[] = {
  152092. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  152093. 12.5, 17.5, 22.5, 27.5,
  152094. };
  152095. static long _vq_quantmap__44un1__p6_0[] = {
  152096. 11, 9, 7, 5, 3, 1, 0, 2,
  152097. 4, 6, 8, 10, 12,
  152098. };
  152099. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  152100. _vq_quantthresh__44un1__p6_0,
  152101. _vq_quantmap__44un1__p6_0,
  152102. 13,
  152103. 13
  152104. };
  152105. static static_codebook _44un1__p6_0 = {
  152106. 2, 169,
  152107. _vq_lengthlist__44un1__p6_0,
  152108. 1, -526516224, 1616117760, 4, 0,
  152109. _vq_quantlist__44un1__p6_0,
  152110. NULL,
  152111. &_vq_auxt__44un1__p6_0,
  152112. NULL,
  152113. 0
  152114. };
  152115. static long _vq_quantlist__44un1__p6_1[] = {
  152116. 2,
  152117. 1,
  152118. 3,
  152119. 0,
  152120. 4,
  152121. };
  152122. static long _vq_lengthlist__44un1__p6_1[] = {
  152123. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  152124. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  152125. };
  152126. static float _vq_quantthresh__44un1__p6_1[] = {
  152127. -1.5, -0.5, 0.5, 1.5,
  152128. };
  152129. static long _vq_quantmap__44un1__p6_1[] = {
  152130. 3, 1, 0, 2, 4,
  152131. };
  152132. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  152133. _vq_quantthresh__44un1__p6_1,
  152134. _vq_quantmap__44un1__p6_1,
  152135. 5,
  152136. 5
  152137. };
  152138. static static_codebook _44un1__p6_1 = {
  152139. 2, 25,
  152140. _vq_lengthlist__44un1__p6_1,
  152141. 1, -533725184, 1611661312, 3, 0,
  152142. _vq_quantlist__44un1__p6_1,
  152143. NULL,
  152144. &_vq_auxt__44un1__p6_1,
  152145. NULL,
  152146. 0
  152147. };
  152148. static long _vq_quantlist__44un1__p7_0[] = {
  152149. 2,
  152150. 1,
  152151. 3,
  152152. 0,
  152153. 4,
  152154. };
  152155. static long _vq_lengthlist__44un1__p7_0[] = {
  152156. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  152157. 11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,
  152158. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152159. 11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152160. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152161. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152162. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152163. 11,11,11,11,11,11,11,11,11,11,11,11,11, 8,11,11,
  152164. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152165. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152166. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  152167. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152168. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152169. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152170. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152171. 11,11,11,11,11,11,11,11,11,11, 7,11,11,11,11,11,
  152172. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152173. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  152174. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152175. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152176. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152177. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152178. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152179. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152180. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152181. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152182. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152183. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152184. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152185. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152186. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152187. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152188. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152189. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152190. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152191. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152192. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152193. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152194. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152195. 10,
  152196. };
  152197. static float _vq_quantthresh__44un1__p7_0[] = {
  152198. -253.5, -84.5, 84.5, 253.5,
  152199. };
  152200. static long _vq_quantmap__44un1__p7_0[] = {
  152201. 3, 1, 0, 2, 4,
  152202. };
  152203. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  152204. _vq_quantthresh__44un1__p7_0,
  152205. _vq_quantmap__44un1__p7_0,
  152206. 5,
  152207. 5
  152208. };
  152209. static static_codebook _44un1__p7_0 = {
  152210. 4, 625,
  152211. _vq_lengthlist__44un1__p7_0,
  152212. 1, -518709248, 1626677248, 3, 0,
  152213. _vq_quantlist__44un1__p7_0,
  152214. NULL,
  152215. &_vq_auxt__44un1__p7_0,
  152216. NULL,
  152217. 0
  152218. };
  152219. static long _vq_quantlist__44un1__p7_1[] = {
  152220. 6,
  152221. 5,
  152222. 7,
  152223. 4,
  152224. 8,
  152225. 3,
  152226. 9,
  152227. 2,
  152228. 10,
  152229. 1,
  152230. 11,
  152231. 0,
  152232. 12,
  152233. };
  152234. static long _vq_lengthlist__44un1__p7_1[] = {
  152235. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  152236. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  152237. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  152238. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  152239. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  152240. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  152241. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  152242. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  152243. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  152244. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  152245. 12,13,13,12,13,13,14,14,14,
  152246. };
  152247. static float _vq_quantthresh__44un1__p7_1[] = {
  152248. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  152249. 32.5, 45.5, 58.5, 71.5,
  152250. };
  152251. static long _vq_quantmap__44un1__p7_1[] = {
  152252. 11, 9, 7, 5, 3, 1, 0, 2,
  152253. 4, 6, 8, 10, 12,
  152254. };
  152255. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  152256. _vq_quantthresh__44un1__p7_1,
  152257. _vq_quantmap__44un1__p7_1,
  152258. 13,
  152259. 13
  152260. };
  152261. static static_codebook _44un1__p7_1 = {
  152262. 2, 169,
  152263. _vq_lengthlist__44un1__p7_1,
  152264. 1, -523010048, 1618608128, 4, 0,
  152265. _vq_quantlist__44un1__p7_1,
  152266. NULL,
  152267. &_vq_auxt__44un1__p7_1,
  152268. NULL,
  152269. 0
  152270. };
  152271. static long _vq_quantlist__44un1__p7_2[] = {
  152272. 6,
  152273. 5,
  152274. 7,
  152275. 4,
  152276. 8,
  152277. 3,
  152278. 9,
  152279. 2,
  152280. 10,
  152281. 1,
  152282. 11,
  152283. 0,
  152284. 12,
  152285. };
  152286. static long _vq_lengthlist__44un1__p7_2[] = {
  152287. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  152288. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  152289. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  152290. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  152291. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  152292. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  152293. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  152294. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  152295. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  152296. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  152297. 9, 9, 9,10,10,10,10,10,10,
  152298. };
  152299. static float _vq_quantthresh__44un1__p7_2[] = {
  152300. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  152301. 2.5, 3.5, 4.5, 5.5,
  152302. };
  152303. static long _vq_quantmap__44un1__p7_2[] = {
  152304. 11, 9, 7, 5, 3, 1, 0, 2,
  152305. 4, 6, 8, 10, 12,
  152306. };
  152307. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  152308. _vq_quantthresh__44un1__p7_2,
  152309. _vq_quantmap__44un1__p7_2,
  152310. 13,
  152311. 13
  152312. };
  152313. static static_codebook _44un1__p7_2 = {
  152314. 2, 169,
  152315. _vq_lengthlist__44un1__p7_2,
  152316. 1, -531103744, 1611661312, 4, 0,
  152317. _vq_quantlist__44un1__p7_2,
  152318. NULL,
  152319. &_vq_auxt__44un1__p7_2,
  152320. NULL,
  152321. 0
  152322. };
  152323. static long _huff_lengthlist__44un1__short[] = {
  152324. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  152325. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  152326. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  152327. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  152328. };
  152329. static static_codebook _huff_book__44un1__short = {
  152330. 2, 64,
  152331. _huff_lengthlist__44un1__short,
  152332. 0, 0, 0, 0, 0,
  152333. NULL,
  152334. NULL,
  152335. NULL,
  152336. NULL,
  152337. 0
  152338. };
  152339. /*** End of inlined file: res_books_uncoupled.h ***/
  152340. /***** residue backends *********************************************/
  152341. static vorbis_info_residue0 _residue_44_low_un={
  152342. 0,-1, -1, 8,-1,
  152343. {0},
  152344. {-1},
  152345. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  152346. { -1, 25, -1, 45, -1, -1, -1}
  152347. };
  152348. static vorbis_info_residue0 _residue_44_mid_un={
  152349. 0,-1, -1, 10,-1,
  152350. /* 0 1 2 3 4 5 6 7 8 9 */
  152351. {0},
  152352. {-1},
  152353. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  152354. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  152355. };
  152356. static vorbis_info_residue0 _residue_44_hi_un={
  152357. 0,-1, -1, 10,-1,
  152358. /* 0 1 2 3 4 5 6 7 8 9 */
  152359. {0},
  152360. {-1},
  152361. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  152362. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  152363. };
  152364. /* mapping conventions:
  152365. only one submap (this would change for efficient 5.1 support for example)*/
  152366. /* Four psychoacoustic profiles are used, one for each blocktype */
  152367. static vorbis_info_mapping0 _map_nominal_u[2]={
  152368. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  152369. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  152370. };
  152371. static static_bookblock _resbook_44u_n1={
  152372. {
  152373. {0},
  152374. {0,0,&_44un1__p1_0},
  152375. {0,0,&_44un1__p2_0},
  152376. {0,0,&_44un1__p3_0},
  152377. {0,0,&_44un1__p4_0},
  152378. {0,0,&_44un1__p5_0},
  152379. {&_44un1__p6_0,&_44un1__p6_1},
  152380. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  152381. }
  152382. };
  152383. static static_bookblock _resbook_44u_0={
  152384. {
  152385. {0},
  152386. {0,0,&_44u0__p1_0},
  152387. {0,0,&_44u0__p2_0},
  152388. {0,0,&_44u0__p3_0},
  152389. {0,0,&_44u0__p4_0},
  152390. {0,0,&_44u0__p5_0},
  152391. {&_44u0__p6_0,&_44u0__p6_1},
  152392. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  152393. }
  152394. };
  152395. static static_bookblock _resbook_44u_1={
  152396. {
  152397. {0},
  152398. {0,0,&_44u1__p1_0},
  152399. {0,0,&_44u1__p2_0},
  152400. {0,0,&_44u1__p3_0},
  152401. {0,0,&_44u1__p4_0},
  152402. {0,0,&_44u1__p5_0},
  152403. {&_44u1__p6_0,&_44u1__p6_1},
  152404. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  152405. }
  152406. };
  152407. static static_bookblock _resbook_44u_2={
  152408. {
  152409. {0},
  152410. {0,0,&_44u2__p1_0},
  152411. {0,0,&_44u2__p2_0},
  152412. {0,0,&_44u2__p3_0},
  152413. {0,0,&_44u2__p4_0},
  152414. {0,0,&_44u2__p5_0},
  152415. {&_44u2__p6_0,&_44u2__p6_1},
  152416. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  152417. }
  152418. };
  152419. static static_bookblock _resbook_44u_3={
  152420. {
  152421. {0},
  152422. {0,0,&_44u3__p1_0},
  152423. {0,0,&_44u3__p2_0},
  152424. {0,0,&_44u3__p3_0},
  152425. {0,0,&_44u3__p4_0},
  152426. {0,0,&_44u3__p5_0},
  152427. {&_44u3__p6_0,&_44u3__p6_1},
  152428. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  152429. }
  152430. };
  152431. static static_bookblock _resbook_44u_4={
  152432. {
  152433. {0},
  152434. {0,0,&_44u4__p1_0},
  152435. {0,0,&_44u4__p2_0},
  152436. {0,0,&_44u4__p3_0},
  152437. {0,0,&_44u4__p4_0},
  152438. {0,0,&_44u4__p5_0},
  152439. {&_44u4__p6_0,&_44u4__p6_1},
  152440. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  152441. }
  152442. };
  152443. static static_bookblock _resbook_44u_5={
  152444. {
  152445. {0},
  152446. {0,0,&_44u5__p1_0},
  152447. {0,0,&_44u5__p2_0},
  152448. {0,0,&_44u5__p3_0},
  152449. {0,0,&_44u5__p4_0},
  152450. {0,0,&_44u5__p5_0},
  152451. {0,0,&_44u5__p6_0},
  152452. {&_44u5__p7_0,&_44u5__p7_1},
  152453. {&_44u5__p8_0,&_44u5__p8_1},
  152454. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  152455. }
  152456. };
  152457. static static_bookblock _resbook_44u_6={
  152458. {
  152459. {0},
  152460. {0,0,&_44u6__p1_0},
  152461. {0,0,&_44u6__p2_0},
  152462. {0,0,&_44u6__p3_0},
  152463. {0,0,&_44u6__p4_0},
  152464. {0,0,&_44u6__p5_0},
  152465. {0,0,&_44u6__p6_0},
  152466. {&_44u6__p7_0,&_44u6__p7_1},
  152467. {&_44u6__p8_0,&_44u6__p8_1},
  152468. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  152469. }
  152470. };
  152471. static static_bookblock _resbook_44u_7={
  152472. {
  152473. {0},
  152474. {0,0,&_44u7__p1_0},
  152475. {0,0,&_44u7__p2_0},
  152476. {0,0,&_44u7__p3_0},
  152477. {0,0,&_44u7__p4_0},
  152478. {0,0,&_44u7__p5_0},
  152479. {0,0,&_44u7__p6_0},
  152480. {&_44u7__p7_0,&_44u7__p7_1},
  152481. {&_44u7__p8_0,&_44u7__p8_1},
  152482. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  152483. }
  152484. };
  152485. static static_bookblock _resbook_44u_8={
  152486. {
  152487. {0},
  152488. {0,0,&_44u8_p1_0},
  152489. {0,0,&_44u8_p2_0},
  152490. {0,0,&_44u8_p3_0},
  152491. {0,0,&_44u8_p4_0},
  152492. {&_44u8_p5_0,&_44u8_p5_1},
  152493. {&_44u8_p6_0,&_44u8_p6_1},
  152494. {&_44u8_p7_0,&_44u8_p7_1},
  152495. {&_44u8_p8_0,&_44u8_p8_1},
  152496. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  152497. }
  152498. };
  152499. static static_bookblock _resbook_44u_9={
  152500. {
  152501. {0},
  152502. {0,0,&_44u9_p1_0},
  152503. {0,0,&_44u9_p2_0},
  152504. {0,0,&_44u9_p3_0},
  152505. {0,0,&_44u9_p4_0},
  152506. {&_44u9_p5_0,&_44u9_p5_1},
  152507. {&_44u9_p6_0,&_44u9_p6_1},
  152508. {&_44u9_p7_0,&_44u9_p7_1},
  152509. {&_44u9_p8_0,&_44u9_p8_1},
  152510. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  152511. }
  152512. };
  152513. static vorbis_residue_template _res_44u_n1[]={
  152514. {1,0, &_residue_44_low_un,
  152515. &_huff_book__44un1__short,&_huff_book__44un1__short,
  152516. &_resbook_44u_n1,&_resbook_44u_n1},
  152517. {1,0, &_residue_44_low_un,
  152518. &_huff_book__44un1__long,&_huff_book__44un1__long,
  152519. &_resbook_44u_n1,&_resbook_44u_n1}
  152520. };
  152521. static vorbis_residue_template _res_44u_0[]={
  152522. {1,0, &_residue_44_low_un,
  152523. &_huff_book__44u0__short,&_huff_book__44u0__short,
  152524. &_resbook_44u_0,&_resbook_44u_0},
  152525. {1,0, &_residue_44_low_un,
  152526. &_huff_book__44u0__long,&_huff_book__44u0__long,
  152527. &_resbook_44u_0,&_resbook_44u_0}
  152528. };
  152529. static vorbis_residue_template _res_44u_1[]={
  152530. {1,0, &_residue_44_low_un,
  152531. &_huff_book__44u1__short,&_huff_book__44u1__short,
  152532. &_resbook_44u_1,&_resbook_44u_1},
  152533. {1,0, &_residue_44_low_un,
  152534. &_huff_book__44u1__long,&_huff_book__44u1__long,
  152535. &_resbook_44u_1,&_resbook_44u_1}
  152536. };
  152537. static vorbis_residue_template _res_44u_2[]={
  152538. {1,0, &_residue_44_low_un,
  152539. &_huff_book__44u2__short,&_huff_book__44u2__short,
  152540. &_resbook_44u_2,&_resbook_44u_2},
  152541. {1,0, &_residue_44_low_un,
  152542. &_huff_book__44u2__long,&_huff_book__44u2__long,
  152543. &_resbook_44u_2,&_resbook_44u_2}
  152544. };
  152545. static vorbis_residue_template _res_44u_3[]={
  152546. {1,0, &_residue_44_low_un,
  152547. &_huff_book__44u3__short,&_huff_book__44u3__short,
  152548. &_resbook_44u_3,&_resbook_44u_3},
  152549. {1,0, &_residue_44_low_un,
  152550. &_huff_book__44u3__long,&_huff_book__44u3__long,
  152551. &_resbook_44u_3,&_resbook_44u_3}
  152552. };
  152553. static vorbis_residue_template _res_44u_4[]={
  152554. {1,0, &_residue_44_low_un,
  152555. &_huff_book__44u4__short,&_huff_book__44u4__short,
  152556. &_resbook_44u_4,&_resbook_44u_4},
  152557. {1,0, &_residue_44_low_un,
  152558. &_huff_book__44u4__long,&_huff_book__44u4__long,
  152559. &_resbook_44u_4,&_resbook_44u_4}
  152560. };
  152561. static vorbis_residue_template _res_44u_5[]={
  152562. {1,0, &_residue_44_mid_un,
  152563. &_huff_book__44u5__short,&_huff_book__44u5__short,
  152564. &_resbook_44u_5,&_resbook_44u_5},
  152565. {1,0, &_residue_44_mid_un,
  152566. &_huff_book__44u5__long,&_huff_book__44u5__long,
  152567. &_resbook_44u_5,&_resbook_44u_5}
  152568. };
  152569. static vorbis_residue_template _res_44u_6[]={
  152570. {1,0, &_residue_44_mid_un,
  152571. &_huff_book__44u6__short,&_huff_book__44u6__short,
  152572. &_resbook_44u_6,&_resbook_44u_6},
  152573. {1,0, &_residue_44_mid_un,
  152574. &_huff_book__44u6__long,&_huff_book__44u6__long,
  152575. &_resbook_44u_6,&_resbook_44u_6}
  152576. };
  152577. static vorbis_residue_template _res_44u_7[]={
  152578. {1,0, &_residue_44_mid_un,
  152579. &_huff_book__44u7__short,&_huff_book__44u7__short,
  152580. &_resbook_44u_7,&_resbook_44u_7},
  152581. {1,0, &_residue_44_mid_un,
  152582. &_huff_book__44u7__long,&_huff_book__44u7__long,
  152583. &_resbook_44u_7,&_resbook_44u_7}
  152584. };
  152585. static vorbis_residue_template _res_44u_8[]={
  152586. {1,0, &_residue_44_hi_un,
  152587. &_huff_book__44u8__short,&_huff_book__44u8__short,
  152588. &_resbook_44u_8,&_resbook_44u_8},
  152589. {1,0, &_residue_44_hi_un,
  152590. &_huff_book__44u8__long,&_huff_book__44u8__long,
  152591. &_resbook_44u_8,&_resbook_44u_8}
  152592. };
  152593. static vorbis_residue_template _res_44u_9[]={
  152594. {1,0, &_residue_44_hi_un,
  152595. &_huff_book__44u9__short,&_huff_book__44u9__short,
  152596. &_resbook_44u_9,&_resbook_44u_9},
  152597. {1,0, &_residue_44_hi_un,
  152598. &_huff_book__44u9__long,&_huff_book__44u9__long,
  152599. &_resbook_44u_9,&_resbook_44u_9}
  152600. };
  152601. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  152602. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  152603. { _map_nominal_u, _res_44u_0 }, /* 0 */
  152604. { _map_nominal_u, _res_44u_1 }, /* 1 */
  152605. { _map_nominal_u, _res_44u_2 }, /* 2 */
  152606. { _map_nominal_u, _res_44u_3 }, /* 3 */
  152607. { _map_nominal_u, _res_44u_4 }, /* 4 */
  152608. { _map_nominal_u, _res_44u_5 }, /* 5 */
  152609. { _map_nominal_u, _res_44u_6 }, /* 6 */
  152610. { _map_nominal_u, _res_44u_7 }, /* 7 */
  152611. { _map_nominal_u, _res_44u_8 }, /* 8 */
  152612. { _map_nominal_u, _res_44u_9 }, /* 9 */
  152613. };
  152614. /*** End of inlined file: residue_44u.h ***/
  152615. static double rate_mapping_44_un[12]={
  152616. 32000.,48000.,60000.,70000.,80000.,86000.,
  152617. 96000.,110000.,120000.,140000.,160000.,240001.
  152618. };
  152619. ve_setup_data_template ve_setup_44_uncoupled={
  152620. 11,
  152621. rate_mapping_44_un,
  152622. quality_mapping_44,
  152623. -1,
  152624. 40000,
  152625. 50000,
  152626. blocksize_short_44,
  152627. blocksize_long_44,
  152628. _psy_tone_masteratt_44,
  152629. _psy_tone_0dB,
  152630. _psy_tone_suppress,
  152631. _vp_tonemask_adj_otherblock,
  152632. _vp_tonemask_adj_longblock,
  152633. _vp_tonemask_adj_otherblock,
  152634. _psy_noiseguards_44,
  152635. _psy_noisebias_impulse,
  152636. _psy_noisebias_padding,
  152637. _psy_noisebias_trans,
  152638. _psy_noisebias_long,
  152639. _psy_noise_suppress,
  152640. _psy_compand_44,
  152641. _psy_compand_short_mapping,
  152642. _psy_compand_long_mapping,
  152643. {_noise_start_short_44,_noise_start_long_44},
  152644. {_noise_part_short_44,_noise_part_long_44},
  152645. _noise_thresh_44,
  152646. _psy_ath_floater,
  152647. _psy_ath_abs,
  152648. _psy_lowpass_44,
  152649. _psy_global_44,
  152650. _global_mapping_44,
  152651. NULL,
  152652. _floor_books,
  152653. _floor,
  152654. _floor_short_mapping_44,
  152655. _floor_long_mapping_44,
  152656. _mapres_template_44_uncoupled
  152657. };
  152658. /*** End of inlined file: setup_44u.h ***/
  152659. /*** Start of inlined file: setup_32.h ***/
  152660. static double rate_mapping_32[12]={
  152661. 18000.,28000.,35000.,45000.,56000.,60000.,
  152662. 75000.,90000.,100000.,115000.,150000.,190000.,
  152663. };
  152664. static double rate_mapping_32_un[12]={
  152665. 30000.,42000.,52000.,64000.,72000.,78000.,
  152666. 86000.,92000.,110000.,120000.,140000.,190000.,
  152667. };
  152668. static double _psy_lowpass_32[12]={
  152669. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  152670. };
  152671. ve_setup_data_template ve_setup_32_stereo={
  152672. 11,
  152673. rate_mapping_32,
  152674. quality_mapping_44,
  152675. 2,
  152676. 26000,
  152677. 40000,
  152678. blocksize_short_44,
  152679. blocksize_long_44,
  152680. _psy_tone_masteratt_44,
  152681. _psy_tone_0dB,
  152682. _psy_tone_suppress,
  152683. _vp_tonemask_adj_otherblock,
  152684. _vp_tonemask_adj_longblock,
  152685. _vp_tonemask_adj_otherblock,
  152686. _psy_noiseguards_44,
  152687. _psy_noisebias_impulse,
  152688. _psy_noisebias_padding,
  152689. _psy_noisebias_trans,
  152690. _psy_noisebias_long,
  152691. _psy_noise_suppress,
  152692. _psy_compand_44,
  152693. _psy_compand_short_mapping,
  152694. _psy_compand_long_mapping,
  152695. {_noise_start_short_44,_noise_start_long_44},
  152696. {_noise_part_short_44,_noise_part_long_44},
  152697. _noise_thresh_44,
  152698. _psy_ath_floater,
  152699. _psy_ath_abs,
  152700. _psy_lowpass_32,
  152701. _psy_global_44,
  152702. _global_mapping_44,
  152703. _psy_stereo_modes_44,
  152704. _floor_books,
  152705. _floor,
  152706. _floor_short_mapping_44,
  152707. _floor_long_mapping_44,
  152708. _mapres_template_44_stereo
  152709. };
  152710. ve_setup_data_template ve_setup_32_uncoupled={
  152711. 11,
  152712. rate_mapping_32_un,
  152713. quality_mapping_44,
  152714. -1,
  152715. 26000,
  152716. 40000,
  152717. blocksize_short_44,
  152718. blocksize_long_44,
  152719. _psy_tone_masteratt_44,
  152720. _psy_tone_0dB,
  152721. _psy_tone_suppress,
  152722. _vp_tonemask_adj_otherblock,
  152723. _vp_tonemask_adj_longblock,
  152724. _vp_tonemask_adj_otherblock,
  152725. _psy_noiseguards_44,
  152726. _psy_noisebias_impulse,
  152727. _psy_noisebias_padding,
  152728. _psy_noisebias_trans,
  152729. _psy_noisebias_long,
  152730. _psy_noise_suppress,
  152731. _psy_compand_44,
  152732. _psy_compand_short_mapping,
  152733. _psy_compand_long_mapping,
  152734. {_noise_start_short_44,_noise_start_long_44},
  152735. {_noise_part_short_44,_noise_part_long_44},
  152736. _noise_thresh_44,
  152737. _psy_ath_floater,
  152738. _psy_ath_abs,
  152739. _psy_lowpass_32,
  152740. _psy_global_44,
  152741. _global_mapping_44,
  152742. NULL,
  152743. _floor_books,
  152744. _floor,
  152745. _floor_short_mapping_44,
  152746. _floor_long_mapping_44,
  152747. _mapres_template_44_uncoupled
  152748. };
  152749. /*** End of inlined file: setup_32.h ***/
  152750. /*** Start of inlined file: setup_8.h ***/
  152751. /*** Start of inlined file: psych_8.h ***/
  152752. static att3 _psy_tone_masteratt_8[3]={
  152753. {{ 32, 25, 12}, 0, 0}, /* 0 */
  152754. {{ 30, 25, 12}, 0, 0}, /* 0 */
  152755. {{ 20, 0, -14}, 0, 0}, /* 0 */
  152756. };
  152757. static vp_adjblock _vp_tonemask_adj_8[3]={
  152758. /* adjust for mode zero */
  152759. /* 63 125 250 500 1 2 4 8 16 */
  152760. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  152761. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  152762. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  152763. };
  152764. static noise3 _psy_noisebias_8[3]={
  152765. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  152766. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  152767. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  152768. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  152769. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  152770. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  152771. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  152772. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  152773. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  152774. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  152775. };
  152776. /* stereo mode by base quality level */
  152777. static adj_stereo _psy_stereo_modes_8[3]={
  152778. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  152779. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  152780. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  152781. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  152782. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  152783. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  152784. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  152785. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  152786. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  152787. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  152788. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  152789. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  152790. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  152791. };
  152792. static noiseguard _psy_noiseguards_8[2]={
  152793. {10,10,-1},
  152794. {10,10,-1},
  152795. };
  152796. static compandblock _psy_compand_8[2]={
  152797. {{
  152798. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  152799. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  152800. 12,12,13,13,14,14,15, 15, /* 23dB */
  152801. 16,16,17,17,17,18,18, 19, /* 31dB */
  152802. 19,19,20,21,22,23,24, 25, /* 39dB */
  152803. }},
  152804. {{
  152805. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  152806. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  152807. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  152808. 9,10,11,12,13,14,15, 16, /* 31dB */
  152809. 17,18,19,20,21,22,23, 24, /* 39dB */
  152810. }},
  152811. };
  152812. static double _psy_lowpass_8[3]={3.,4.,4.};
  152813. static int _noise_start_8[2]={
  152814. 64,64,
  152815. };
  152816. static int _noise_part_8[2]={
  152817. 8,8,
  152818. };
  152819. static int _psy_ath_floater_8[3]={
  152820. -100,-100,-105,
  152821. };
  152822. static int _psy_ath_abs_8[3]={
  152823. -130,-130,-140,
  152824. };
  152825. /*** End of inlined file: psych_8.h ***/
  152826. /*** Start of inlined file: residue_8.h ***/
  152827. /***** residue backends *********************************************/
  152828. static static_bookblock _resbook_8s_0={
  152829. {
  152830. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  152831. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  152832. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  152833. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  152834. }
  152835. };
  152836. static static_bookblock _resbook_8s_1={
  152837. {
  152838. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  152839. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  152840. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  152841. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  152842. }
  152843. };
  152844. static vorbis_residue_template _res_8s_0[]={
  152845. {2,0, &_residue_44_mid,
  152846. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  152847. &_resbook_8s_0,&_resbook_8s_0},
  152848. };
  152849. static vorbis_residue_template _res_8s_1[]={
  152850. {2,0, &_residue_44_mid,
  152851. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  152852. &_resbook_8s_1,&_resbook_8s_1},
  152853. };
  152854. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  152855. { _map_nominal, _res_8s_0 }, /* 0 */
  152856. { _map_nominal, _res_8s_1 }, /* 1 */
  152857. };
  152858. static static_bookblock _resbook_8u_0={
  152859. {
  152860. {0},
  152861. {0,0,&_8u0__p1_0},
  152862. {0,0,&_8u0__p2_0},
  152863. {0,0,&_8u0__p3_0},
  152864. {0,0,&_8u0__p4_0},
  152865. {0,0,&_8u0__p5_0},
  152866. {&_8u0__p6_0,&_8u0__p6_1},
  152867. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  152868. }
  152869. };
  152870. static static_bookblock _resbook_8u_1={
  152871. {
  152872. {0},
  152873. {0,0,&_8u1__p1_0},
  152874. {0,0,&_8u1__p2_0},
  152875. {0,0,&_8u1__p3_0},
  152876. {0,0,&_8u1__p4_0},
  152877. {0,0,&_8u1__p5_0},
  152878. {0,0,&_8u1__p6_0},
  152879. {&_8u1__p7_0,&_8u1__p7_1},
  152880. {&_8u1__p8_0,&_8u1__p8_1},
  152881. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  152882. }
  152883. };
  152884. static vorbis_residue_template _res_8u_0[]={
  152885. {1,0, &_residue_44_low_un,
  152886. &_huff_book__8u0__single,&_huff_book__8u0__single,
  152887. &_resbook_8u_0,&_resbook_8u_0},
  152888. };
  152889. static vorbis_residue_template _res_8u_1[]={
  152890. {1,0, &_residue_44_mid_un,
  152891. &_huff_book__8u1__single,&_huff_book__8u1__single,
  152892. &_resbook_8u_1,&_resbook_8u_1},
  152893. };
  152894. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  152895. { _map_nominal_u, _res_8u_0 }, /* 0 */
  152896. { _map_nominal_u, _res_8u_1 }, /* 1 */
  152897. };
  152898. /*** End of inlined file: residue_8.h ***/
  152899. static int blocksize_8[2]={
  152900. 512,512
  152901. };
  152902. static int _floor_mapping_8[2]={
  152903. 6,6,
  152904. };
  152905. static double rate_mapping_8[3]={
  152906. 6000.,9000.,32000.,
  152907. };
  152908. static double rate_mapping_8_uncoupled[3]={
  152909. 8000.,14000.,42000.,
  152910. };
  152911. static double quality_mapping_8[3]={
  152912. -.1,.0,1.
  152913. };
  152914. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  152915. static double _global_mapping_8[3]={ 1., 2., 3. };
  152916. ve_setup_data_template ve_setup_8_stereo={
  152917. 2,
  152918. rate_mapping_8,
  152919. quality_mapping_8,
  152920. 2,
  152921. 8000,
  152922. 9000,
  152923. blocksize_8,
  152924. blocksize_8,
  152925. _psy_tone_masteratt_8,
  152926. _psy_tone_0dB,
  152927. _psy_tone_suppress,
  152928. _vp_tonemask_adj_8,
  152929. NULL,
  152930. _vp_tonemask_adj_8,
  152931. _psy_noiseguards_8,
  152932. _psy_noisebias_8,
  152933. _psy_noisebias_8,
  152934. NULL,
  152935. NULL,
  152936. _psy_noise_suppress,
  152937. _psy_compand_8,
  152938. _psy_compand_8_mapping,
  152939. NULL,
  152940. {_noise_start_8,_noise_start_8},
  152941. {_noise_part_8,_noise_part_8},
  152942. _noise_thresh_5only,
  152943. _psy_ath_floater_8,
  152944. _psy_ath_abs_8,
  152945. _psy_lowpass_8,
  152946. _psy_global_44,
  152947. _global_mapping_8,
  152948. _psy_stereo_modes_8,
  152949. _floor_books,
  152950. _floor,
  152951. _floor_mapping_8,
  152952. NULL,
  152953. _mapres_template_8_stereo
  152954. };
  152955. ve_setup_data_template ve_setup_8_uncoupled={
  152956. 2,
  152957. rate_mapping_8_uncoupled,
  152958. quality_mapping_8,
  152959. -1,
  152960. 8000,
  152961. 9000,
  152962. blocksize_8,
  152963. blocksize_8,
  152964. _psy_tone_masteratt_8,
  152965. _psy_tone_0dB,
  152966. _psy_tone_suppress,
  152967. _vp_tonemask_adj_8,
  152968. NULL,
  152969. _vp_tonemask_adj_8,
  152970. _psy_noiseguards_8,
  152971. _psy_noisebias_8,
  152972. _psy_noisebias_8,
  152973. NULL,
  152974. NULL,
  152975. _psy_noise_suppress,
  152976. _psy_compand_8,
  152977. _psy_compand_8_mapping,
  152978. NULL,
  152979. {_noise_start_8,_noise_start_8},
  152980. {_noise_part_8,_noise_part_8},
  152981. _noise_thresh_5only,
  152982. _psy_ath_floater_8,
  152983. _psy_ath_abs_8,
  152984. _psy_lowpass_8,
  152985. _psy_global_44,
  152986. _global_mapping_8,
  152987. _psy_stereo_modes_8,
  152988. _floor_books,
  152989. _floor,
  152990. _floor_mapping_8,
  152991. NULL,
  152992. _mapres_template_8_uncoupled
  152993. };
  152994. /*** End of inlined file: setup_8.h ***/
  152995. /*** Start of inlined file: setup_11.h ***/
  152996. /*** Start of inlined file: psych_11.h ***/
  152997. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  152998. static att3 _psy_tone_masteratt_11[3]={
  152999. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153000. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153001. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153002. };
  153003. static vp_adjblock _vp_tonemask_adj_11[3]={
  153004. /* adjust for mode zero */
  153005. /* 63 125 250 500 1 2 4 8 16 */
  153006. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  153007. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  153008. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  153009. };
  153010. static noise3 _psy_noisebias_11[3]={
  153011. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153012. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  153013. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  153014. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153015. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  153016. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153017. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153018. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153019. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153020. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153021. };
  153022. static double _noise_thresh_11[3]={ .3,.5,.5 };
  153023. /*** End of inlined file: psych_11.h ***/
  153024. static int blocksize_11[2]={
  153025. 512,512
  153026. };
  153027. static int _floor_mapping_11[2]={
  153028. 6,6,
  153029. };
  153030. static double rate_mapping_11[3]={
  153031. 8000.,13000.,44000.,
  153032. };
  153033. static double rate_mapping_11_uncoupled[3]={
  153034. 12000.,20000.,50000.,
  153035. };
  153036. static double quality_mapping_11[3]={
  153037. -.1,.0,1.
  153038. };
  153039. ve_setup_data_template ve_setup_11_stereo={
  153040. 2,
  153041. rate_mapping_11,
  153042. quality_mapping_11,
  153043. 2,
  153044. 9000,
  153045. 15000,
  153046. blocksize_11,
  153047. blocksize_11,
  153048. _psy_tone_masteratt_11,
  153049. _psy_tone_0dB,
  153050. _psy_tone_suppress,
  153051. _vp_tonemask_adj_11,
  153052. NULL,
  153053. _vp_tonemask_adj_11,
  153054. _psy_noiseguards_8,
  153055. _psy_noisebias_11,
  153056. _psy_noisebias_11,
  153057. NULL,
  153058. NULL,
  153059. _psy_noise_suppress,
  153060. _psy_compand_8,
  153061. _psy_compand_8_mapping,
  153062. NULL,
  153063. {_noise_start_8,_noise_start_8},
  153064. {_noise_part_8,_noise_part_8},
  153065. _noise_thresh_11,
  153066. _psy_ath_floater_8,
  153067. _psy_ath_abs_8,
  153068. _psy_lowpass_11,
  153069. _psy_global_44,
  153070. _global_mapping_8,
  153071. _psy_stereo_modes_8,
  153072. _floor_books,
  153073. _floor,
  153074. _floor_mapping_11,
  153075. NULL,
  153076. _mapres_template_8_stereo
  153077. };
  153078. ve_setup_data_template ve_setup_11_uncoupled={
  153079. 2,
  153080. rate_mapping_11_uncoupled,
  153081. quality_mapping_11,
  153082. -1,
  153083. 9000,
  153084. 15000,
  153085. blocksize_11,
  153086. blocksize_11,
  153087. _psy_tone_masteratt_11,
  153088. _psy_tone_0dB,
  153089. _psy_tone_suppress,
  153090. _vp_tonemask_adj_11,
  153091. NULL,
  153092. _vp_tonemask_adj_11,
  153093. _psy_noiseguards_8,
  153094. _psy_noisebias_11,
  153095. _psy_noisebias_11,
  153096. NULL,
  153097. NULL,
  153098. _psy_noise_suppress,
  153099. _psy_compand_8,
  153100. _psy_compand_8_mapping,
  153101. NULL,
  153102. {_noise_start_8,_noise_start_8},
  153103. {_noise_part_8,_noise_part_8},
  153104. _noise_thresh_11,
  153105. _psy_ath_floater_8,
  153106. _psy_ath_abs_8,
  153107. _psy_lowpass_11,
  153108. _psy_global_44,
  153109. _global_mapping_8,
  153110. _psy_stereo_modes_8,
  153111. _floor_books,
  153112. _floor,
  153113. _floor_mapping_11,
  153114. NULL,
  153115. _mapres_template_8_uncoupled
  153116. };
  153117. /*** End of inlined file: setup_11.h ***/
  153118. /*** Start of inlined file: setup_16.h ***/
  153119. /*** Start of inlined file: psych_16.h ***/
  153120. /* stereo mode by base quality level */
  153121. static adj_stereo _psy_stereo_modes_16[4]={
  153122. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  153123. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153124. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153125. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  153126. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153127. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153128. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153129. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  153130. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153131. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153132. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153133. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153134. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153135. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  153136. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  153137. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  153138. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153139. };
  153140. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  153141. static att3 _psy_tone_masteratt_16[4]={
  153142. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153143. {{ 25, 22, 12}, 0, 0}, /* 0 */
  153144. {{ 20, 12, 0}, 0, 0}, /* 0 */
  153145. {{ 15, 0, -14}, 0, 0}, /* 0 */
  153146. };
  153147. static vp_adjblock _vp_tonemask_adj_16[4]={
  153148. /* adjust for mode zero */
  153149. /* 63 125 250 500 1 2 4 8 16 */
  153150. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  153151. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  153152. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  153153. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  153154. };
  153155. static noise3 _psy_noisebias_16_short[4]={
  153156. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153157. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  153158. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  153159. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153160. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  153161. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  153162. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  153163. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  153164. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  153165. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153166. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153167. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  153168. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153169. };
  153170. static noise3 _psy_noisebias_16_impulse[4]={
  153171. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153172. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  153173. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  153174. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153175. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  153176. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  153177. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  153178. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  153179. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  153180. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153181. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153182. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  153183. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153184. };
  153185. static noise3 _psy_noisebias_16[4]={
  153186. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153187. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  153188. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  153189. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153190. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  153191. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  153192. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153193. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  153194. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  153195. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153196. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153197. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  153198. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153199. };
  153200. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  153201. static int _noise_start_16[3]={ 256,256,9999 };
  153202. static int _noise_part_16[4]={ 8,8,8,8 };
  153203. static int _psy_ath_floater_16[4]={
  153204. -100,-100,-100,-105,
  153205. };
  153206. static int _psy_ath_abs_16[4]={
  153207. -130,-130,-130,-140,
  153208. };
  153209. /*** End of inlined file: psych_16.h ***/
  153210. /*** Start of inlined file: residue_16.h ***/
  153211. /***** residue backends *********************************************/
  153212. static static_bookblock _resbook_16s_0={
  153213. {
  153214. {0},
  153215. {0,0,&_16c0_s_p1_0},
  153216. {0,0,&_16c0_s_p2_0},
  153217. {0,0,&_16c0_s_p3_0},
  153218. {0,0,&_16c0_s_p4_0},
  153219. {0,0,&_16c0_s_p5_0},
  153220. {0,0,&_16c0_s_p6_0},
  153221. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  153222. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  153223. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  153224. }
  153225. };
  153226. static static_bookblock _resbook_16s_1={
  153227. {
  153228. {0},
  153229. {0,0,&_16c1_s_p1_0},
  153230. {0,0,&_16c1_s_p2_0},
  153231. {0,0,&_16c1_s_p3_0},
  153232. {0,0,&_16c1_s_p4_0},
  153233. {0,0,&_16c1_s_p5_0},
  153234. {0,0,&_16c1_s_p6_0},
  153235. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  153236. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  153237. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  153238. }
  153239. };
  153240. static static_bookblock _resbook_16s_2={
  153241. {
  153242. {0},
  153243. {0,0,&_16c2_s_p1_0},
  153244. {0,0,&_16c2_s_p2_0},
  153245. {0,0,&_16c2_s_p3_0},
  153246. {0,0,&_16c2_s_p4_0},
  153247. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  153248. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  153249. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  153250. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  153251. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  153252. }
  153253. };
  153254. static vorbis_residue_template _res_16s_0[]={
  153255. {2,0, &_residue_44_mid,
  153256. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  153257. &_resbook_16s_0,&_resbook_16s_0},
  153258. };
  153259. static vorbis_residue_template _res_16s_1[]={
  153260. {2,0, &_residue_44_mid,
  153261. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  153262. &_resbook_16s_1,&_resbook_16s_1},
  153263. {2,0, &_residue_44_mid,
  153264. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  153265. &_resbook_16s_1,&_resbook_16s_1}
  153266. };
  153267. static vorbis_residue_template _res_16s_2[]={
  153268. {2,0, &_residue_44_high,
  153269. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  153270. &_resbook_16s_2,&_resbook_16s_2},
  153271. {2,0, &_residue_44_high,
  153272. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  153273. &_resbook_16s_2,&_resbook_16s_2}
  153274. };
  153275. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  153276. { _map_nominal, _res_16s_0 }, /* 0 */
  153277. { _map_nominal, _res_16s_1 }, /* 1 */
  153278. { _map_nominal, _res_16s_2 }, /* 2 */
  153279. };
  153280. static static_bookblock _resbook_16u_0={
  153281. {
  153282. {0},
  153283. {0,0,&_16u0__p1_0},
  153284. {0,0,&_16u0__p2_0},
  153285. {0,0,&_16u0__p3_0},
  153286. {0,0,&_16u0__p4_0},
  153287. {0,0,&_16u0__p5_0},
  153288. {&_16u0__p6_0,&_16u0__p6_1},
  153289. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  153290. }
  153291. };
  153292. static static_bookblock _resbook_16u_1={
  153293. {
  153294. {0},
  153295. {0,0,&_16u1__p1_0},
  153296. {0,0,&_16u1__p2_0},
  153297. {0,0,&_16u1__p3_0},
  153298. {0,0,&_16u1__p4_0},
  153299. {0,0,&_16u1__p5_0},
  153300. {0,0,&_16u1__p6_0},
  153301. {&_16u1__p7_0,&_16u1__p7_1},
  153302. {&_16u1__p8_0,&_16u1__p8_1},
  153303. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  153304. }
  153305. };
  153306. static static_bookblock _resbook_16u_2={
  153307. {
  153308. {0},
  153309. {0,0,&_16u2_p1_0},
  153310. {0,0,&_16u2_p2_0},
  153311. {0,0,&_16u2_p3_0},
  153312. {0,0,&_16u2_p4_0},
  153313. {&_16u2_p5_0,&_16u2_p5_1},
  153314. {&_16u2_p6_0,&_16u2_p6_1},
  153315. {&_16u2_p7_0,&_16u2_p7_1},
  153316. {&_16u2_p8_0,&_16u2_p8_1},
  153317. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  153318. }
  153319. };
  153320. static vorbis_residue_template _res_16u_0[]={
  153321. {1,0, &_residue_44_low_un,
  153322. &_huff_book__16u0__single,&_huff_book__16u0__single,
  153323. &_resbook_16u_0,&_resbook_16u_0},
  153324. };
  153325. static vorbis_residue_template _res_16u_1[]={
  153326. {1,0, &_residue_44_mid_un,
  153327. &_huff_book__16u1__short,&_huff_book__16u1__short,
  153328. &_resbook_16u_1,&_resbook_16u_1},
  153329. {1,0, &_residue_44_mid_un,
  153330. &_huff_book__16u1__long,&_huff_book__16u1__long,
  153331. &_resbook_16u_1,&_resbook_16u_1}
  153332. };
  153333. static vorbis_residue_template _res_16u_2[]={
  153334. {1,0, &_residue_44_hi_un,
  153335. &_huff_book__16u2__short,&_huff_book__16u2__short,
  153336. &_resbook_16u_2,&_resbook_16u_2},
  153337. {1,0, &_residue_44_hi_un,
  153338. &_huff_book__16u2__long,&_huff_book__16u2__long,
  153339. &_resbook_16u_2,&_resbook_16u_2}
  153340. };
  153341. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  153342. { _map_nominal_u, _res_16u_0 }, /* 0 */
  153343. { _map_nominal_u, _res_16u_1 }, /* 1 */
  153344. { _map_nominal_u, _res_16u_2 }, /* 2 */
  153345. };
  153346. /*** End of inlined file: residue_16.h ***/
  153347. static int blocksize_16_short[3]={
  153348. 1024,512,512
  153349. };
  153350. static int blocksize_16_long[3]={
  153351. 1024,1024,1024
  153352. };
  153353. static int _floor_mapping_16_short[3]={
  153354. 9,3,3
  153355. };
  153356. static int _floor_mapping_16[3]={
  153357. 9,9,9
  153358. };
  153359. static double rate_mapping_16[4]={
  153360. 12000.,20000.,44000.,86000.
  153361. };
  153362. static double rate_mapping_16_uncoupled[4]={
  153363. 16000.,28000.,64000.,100000.
  153364. };
  153365. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  153366. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  153367. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  153368. ve_setup_data_template ve_setup_16_stereo={
  153369. 3,
  153370. rate_mapping_16,
  153371. quality_mapping_16,
  153372. 2,
  153373. 15000,
  153374. 19000,
  153375. blocksize_16_short,
  153376. blocksize_16_long,
  153377. _psy_tone_masteratt_16,
  153378. _psy_tone_0dB,
  153379. _psy_tone_suppress,
  153380. _vp_tonemask_adj_16,
  153381. _vp_tonemask_adj_16,
  153382. _vp_tonemask_adj_16,
  153383. _psy_noiseguards_8,
  153384. _psy_noisebias_16_impulse,
  153385. _psy_noisebias_16_short,
  153386. _psy_noisebias_16_short,
  153387. _psy_noisebias_16,
  153388. _psy_noise_suppress,
  153389. _psy_compand_8,
  153390. _psy_compand_16_mapping,
  153391. _psy_compand_16_mapping,
  153392. {_noise_start_16,_noise_start_16},
  153393. { _noise_part_16, _noise_part_16},
  153394. _noise_thresh_16,
  153395. _psy_ath_floater_16,
  153396. _psy_ath_abs_16,
  153397. _psy_lowpass_16,
  153398. _psy_global_44,
  153399. _global_mapping_16,
  153400. _psy_stereo_modes_16,
  153401. _floor_books,
  153402. _floor,
  153403. _floor_mapping_16_short,
  153404. _floor_mapping_16,
  153405. _mapres_template_16_stereo
  153406. };
  153407. ve_setup_data_template ve_setup_16_uncoupled={
  153408. 3,
  153409. rate_mapping_16_uncoupled,
  153410. quality_mapping_16,
  153411. -1,
  153412. 15000,
  153413. 19000,
  153414. blocksize_16_short,
  153415. blocksize_16_long,
  153416. _psy_tone_masteratt_16,
  153417. _psy_tone_0dB,
  153418. _psy_tone_suppress,
  153419. _vp_tonemask_adj_16,
  153420. _vp_tonemask_adj_16,
  153421. _vp_tonemask_adj_16,
  153422. _psy_noiseguards_8,
  153423. _psy_noisebias_16_impulse,
  153424. _psy_noisebias_16_short,
  153425. _psy_noisebias_16_short,
  153426. _psy_noisebias_16,
  153427. _psy_noise_suppress,
  153428. _psy_compand_8,
  153429. _psy_compand_16_mapping,
  153430. _psy_compand_16_mapping,
  153431. {_noise_start_16,_noise_start_16},
  153432. { _noise_part_16, _noise_part_16},
  153433. _noise_thresh_16,
  153434. _psy_ath_floater_16,
  153435. _psy_ath_abs_16,
  153436. _psy_lowpass_16,
  153437. _psy_global_44,
  153438. _global_mapping_16,
  153439. _psy_stereo_modes_16,
  153440. _floor_books,
  153441. _floor,
  153442. _floor_mapping_16_short,
  153443. _floor_mapping_16,
  153444. _mapres_template_16_uncoupled
  153445. };
  153446. /*** End of inlined file: setup_16.h ***/
  153447. /*** Start of inlined file: setup_22.h ***/
  153448. static double rate_mapping_22[4]={
  153449. 15000.,20000.,44000.,86000.
  153450. };
  153451. static double rate_mapping_22_uncoupled[4]={
  153452. 16000.,28000.,50000.,90000.
  153453. };
  153454. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  153455. ve_setup_data_template ve_setup_22_stereo={
  153456. 3,
  153457. rate_mapping_22,
  153458. quality_mapping_16,
  153459. 2,
  153460. 19000,
  153461. 26000,
  153462. blocksize_16_short,
  153463. blocksize_16_long,
  153464. _psy_tone_masteratt_16,
  153465. _psy_tone_0dB,
  153466. _psy_tone_suppress,
  153467. _vp_tonemask_adj_16,
  153468. _vp_tonemask_adj_16,
  153469. _vp_tonemask_adj_16,
  153470. _psy_noiseguards_8,
  153471. _psy_noisebias_16_impulse,
  153472. _psy_noisebias_16_short,
  153473. _psy_noisebias_16_short,
  153474. _psy_noisebias_16,
  153475. _psy_noise_suppress,
  153476. _psy_compand_8,
  153477. _psy_compand_8_mapping,
  153478. _psy_compand_8_mapping,
  153479. {_noise_start_16,_noise_start_16},
  153480. { _noise_part_16, _noise_part_16},
  153481. _noise_thresh_16,
  153482. _psy_ath_floater_16,
  153483. _psy_ath_abs_16,
  153484. _psy_lowpass_22,
  153485. _psy_global_44,
  153486. _global_mapping_16,
  153487. _psy_stereo_modes_16,
  153488. _floor_books,
  153489. _floor,
  153490. _floor_mapping_16_short,
  153491. _floor_mapping_16,
  153492. _mapres_template_16_stereo
  153493. };
  153494. ve_setup_data_template ve_setup_22_uncoupled={
  153495. 3,
  153496. rate_mapping_22_uncoupled,
  153497. quality_mapping_16,
  153498. -1,
  153499. 19000,
  153500. 26000,
  153501. blocksize_16_short,
  153502. blocksize_16_long,
  153503. _psy_tone_masteratt_16,
  153504. _psy_tone_0dB,
  153505. _psy_tone_suppress,
  153506. _vp_tonemask_adj_16,
  153507. _vp_tonemask_adj_16,
  153508. _vp_tonemask_adj_16,
  153509. _psy_noiseguards_8,
  153510. _psy_noisebias_16_impulse,
  153511. _psy_noisebias_16_short,
  153512. _psy_noisebias_16_short,
  153513. _psy_noisebias_16,
  153514. _psy_noise_suppress,
  153515. _psy_compand_8,
  153516. _psy_compand_8_mapping,
  153517. _psy_compand_8_mapping,
  153518. {_noise_start_16,_noise_start_16},
  153519. { _noise_part_16, _noise_part_16},
  153520. _noise_thresh_16,
  153521. _psy_ath_floater_16,
  153522. _psy_ath_abs_16,
  153523. _psy_lowpass_22,
  153524. _psy_global_44,
  153525. _global_mapping_16,
  153526. _psy_stereo_modes_16,
  153527. _floor_books,
  153528. _floor,
  153529. _floor_mapping_16_short,
  153530. _floor_mapping_16,
  153531. _mapres_template_16_uncoupled
  153532. };
  153533. /*** End of inlined file: setup_22.h ***/
  153534. /*** Start of inlined file: setup_X.h ***/
  153535. static double rate_mapping_X[12]={
  153536. -1.,-1.,-1.,-1.,-1.,-1.,
  153537. -1.,-1.,-1.,-1.,-1.,-1.
  153538. };
  153539. ve_setup_data_template ve_setup_X_stereo={
  153540. 11,
  153541. rate_mapping_X,
  153542. quality_mapping_44,
  153543. 2,
  153544. 50000,
  153545. 200000,
  153546. blocksize_short_44,
  153547. blocksize_long_44,
  153548. _psy_tone_masteratt_44,
  153549. _psy_tone_0dB,
  153550. _psy_tone_suppress,
  153551. _vp_tonemask_adj_otherblock,
  153552. _vp_tonemask_adj_longblock,
  153553. _vp_tonemask_adj_otherblock,
  153554. _psy_noiseguards_44,
  153555. _psy_noisebias_impulse,
  153556. _psy_noisebias_padding,
  153557. _psy_noisebias_trans,
  153558. _psy_noisebias_long,
  153559. _psy_noise_suppress,
  153560. _psy_compand_44,
  153561. _psy_compand_short_mapping,
  153562. _psy_compand_long_mapping,
  153563. {_noise_start_short_44,_noise_start_long_44},
  153564. {_noise_part_short_44,_noise_part_long_44},
  153565. _noise_thresh_44,
  153566. _psy_ath_floater,
  153567. _psy_ath_abs,
  153568. _psy_lowpass_44,
  153569. _psy_global_44,
  153570. _global_mapping_44,
  153571. _psy_stereo_modes_44,
  153572. _floor_books,
  153573. _floor,
  153574. _floor_short_mapping_44,
  153575. _floor_long_mapping_44,
  153576. _mapres_template_44_stereo
  153577. };
  153578. ve_setup_data_template ve_setup_X_uncoupled={
  153579. 11,
  153580. rate_mapping_X,
  153581. quality_mapping_44,
  153582. -1,
  153583. 50000,
  153584. 200000,
  153585. blocksize_short_44,
  153586. blocksize_long_44,
  153587. _psy_tone_masteratt_44,
  153588. _psy_tone_0dB,
  153589. _psy_tone_suppress,
  153590. _vp_tonemask_adj_otherblock,
  153591. _vp_tonemask_adj_longblock,
  153592. _vp_tonemask_adj_otherblock,
  153593. _psy_noiseguards_44,
  153594. _psy_noisebias_impulse,
  153595. _psy_noisebias_padding,
  153596. _psy_noisebias_trans,
  153597. _psy_noisebias_long,
  153598. _psy_noise_suppress,
  153599. _psy_compand_44,
  153600. _psy_compand_short_mapping,
  153601. _psy_compand_long_mapping,
  153602. {_noise_start_short_44,_noise_start_long_44},
  153603. {_noise_part_short_44,_noise_part_long_44},
  153604. _noise_thresh_44,
  153605. _psy_ath_floater,
  153606. _psy_ath_abs,
  153607. _psy_lowpass_44,
  153608. _psy_global_44,
  153609. _global_mapping_44,
  153610. NULL,
  153611. _floor_books,
  153612. _floor,
  153613. _floor_short_mapping_44,
  153614. _floor_long_mapping_44,
  153615. _mapres_template_44_uncoupled
  153616. };
  153617. ve_setup_data_template ve_setup_XX_stereo={
  153618. 2,
  153619. rate_mapping_X,
  153620. quality_mapping_8,
  153621. 2,
  153622. 0,
  153623. 8000,
  153624. blocksize_8,
  153625. blocksize_8,
  153626. _psy_tone_masteratt_8,
  153627. _psy_tone_0dB,
  153628. _psy_tone_suppress,
  153629. _vp_tonemask_adj_8,
  153630. NULL,
  153631. _vp_tonemask_adj_8,
  153632. _psy_noiseguards_8,
  153633. _psy_noisebias_8,
  153634. _psy_noisebias_8,
  153635. NULL,
  153636. NULL,
  153637. _psy_noise_suppress,
  153638. _psy_compand_8,
  153639. _psy_compand_8_mapping,
  153640. NULL,
  153641. {_noise_start_8,_noise_start_8},
  153642. {_noise_part_8,_noise_part_8},
  153643. _noise_thresh_5only,
  153644. _psy_ath_floater_8,
  153645. _psy_ath_abs_8,
  153646. _psy_lowpass_8,
  153647. _psy_global_44,
  153648. _global_mapping_8,
  153649. _psy_stereo_modes_8,
  153650. _floor_books,
  153651. _floor,
  153652. _floor_mapping_8,
  153653. NULL,
  153654. _mapres_template_8_stereo
  153655. };
  153656. ve_setup_data_template ve_setup_XX_uncoupled={
  153657. 2,
  153658. rate_mapping_X,
  153659. quality_mapping_8,
  153660. -1,
  153661. 0,
  153662. 8000,
  153663. blocksize_8,
  153664. blocksize_8,
  153665. _psy_tone_masteratt_8,
  153666. _psy_tone_0dB,
  153667. _psy_tone_suppress,
  153668. _vp_tonemask_adj_8,
  153669. NULL,
  153670. _vp_tonemask_adj_8,
  153671. _psy_noiseguards_8,
  153672. _psy_noisebias_8,
  153673. _psy_noisebias_8,
  153674. NULL,
  153675. NULL,
  153676. _psy_noise_suppress,
  153677. _psy_compand_8,
  153678. _psy_compand_8_mapping,
  153679. NULL,
  153680. {_noise_start_8,_noise_start_8},
  153681. {_noise_part_8,_noise_part_8},
  153682. _noise_thresh_5only,
  153683. _psy_ath_floater_8,
  153684. _psy_ath_abs_8,
  153685. _psy_lowpass_8,
  153686. _psy_global_44,
  153687. _global_mapping_8,
  153688. _psy_stereo_modes_8,
  153689. _floor_books,
  153690. _floor,
  153691. _floor_mapping_8,
  153692. NULL,
  153693. _mapres_template_8_uncoupled
  153694. };
  153695. /*** End of inlined file: setup_X.h ***/
  153696. static ve_setup_data_template *setup_list[]={
  153697. &ve_setup_44_stereo,
  153698. &ve_setup_44_uncoupled,
  153699. &ve_setup_32_stereo,
  153700. &ve_setup_32_uncoupled,
  153701. &ve_setup_22_stereo,
  153702. &ve_setup_22_uncoupled,
  153703. &ve_setup_16_stereo,
  153704. &ve_setup_16_uncoupled,
  153705. &ve_setup_11_stereo,
  153706. &ve_setup_11_uncoupled,
  153707. &ve_setup_8_stereo,
  153708. &ve_setup_8_uncoupled,
  153709. &ve_setup_X_stereo,
  153710. &ve_setup_X_uncoupled,
  153711. &ve_setup_XX_stereo,
  153712. &ve_setup_XX_uncoupled,
  153713. 0
  153714. };
  153715. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  153716. if(vi && vi->codec_setup){
  153717. vi->version=0;
  153718. vi->channels=ch;
  153719. vi->rate=rate;
  153720. return(0);
  153721. }
  153722. return(OV_EINVAL);
  153723. }
  153724. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  153725. static_codebook ***books,
  153726. vorbis_info_floor1 *in,
  153727. int *x){
  153728. int i,k,is=s;
  153729. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  153730. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  153731. memcpy(f,in+x[is],sizeof(*f));
  153732. /* fill in the lowpass field, even if it's temporary */
  153733. f->n=ci->blocksizes[block]>>1;
  153734. /* books */
  153735. {
  153736. int partitions=f->partitions;
  153737. int maxclass=-1;
  153738. int maxbook=-1;
  153739. for(i=0;i<partitions;i++)
  153740. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  153741. for(i=0;i<=maxclass;i++){
  153742. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  153743. f->class_book[i]+=ci->books;
  153744. for(k=0;k<(1<<f->class_subs[i]);k++){
  153745. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  153746. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  153747. }
  153748. }
  153749. for(i=0;i<=maxbook;i++)
  153750. ci->book_param[ci->books++]=books[x[is]][i];
  153751. }
  153752. /* for now, we're only using floor 1 */
  153753. ci->floor_type[ci->floors]=1;
  153754. ci->floor_param[ci->floors]=f;
  153755. ci->floors++;
  153756. return;
  153757. }
  153758. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  153759. vorbis_info_psy_global *in,
  153760. double *x){
  153761. int i,is=s;
  153762. double ds=s-is;
  153763. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  153764. vorbis_info_psy_global *g=&ci->psy_g_param;
  153765. memcpy(g,in+(int)x[is],sizeof(*g));
  153766. ds=x[is]*(1.-ds)+x[is+1]*ds;
  153767. is=(int)ds;
  153768. ds-=is;
  153769. if(ds==0 && is>0){
  153770. is--;
  153771. ds=1.;
  153772. }
  153773. /* interpolate the trigger threshholds */
  153774. for(i=0;i<4;i++){
  153775. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  153776. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  153777. }
  153778. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  153779. return;
  153780. }
  153781. static void vorbis_encode_global_stereo(vorbis_info *vi,
  153782. highlevel_encode_setup *hi,
  153783. adj_stereo *p){
  153784. float s=hi->stereo_point_setting;
  153785. int i,is=s;
  153786. double ds=s-is;
  153787. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  153788. vorbis_info_psy_global *g=&ci->psy_g_param;
  153789. if(p){
  153790. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  153791. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  153792. if(hi->managed){
  153793. /* interpolate the kHz threshholds */
  153794. for(i=0;i<PACKETBLOBS;i++){
  153795. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  153796. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  153797. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  153798. g->coupling_pkHz[i]=kHz;
  153799. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  153800. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  153801. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  153802. }
  153803. }else{
  153804. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  153805. for(i=0;i<PACKETBLOBS;i++){
  153806. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  153807. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  153808. g->coupling_pkHz[i]=kHz;
  153809. }
  153810. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  153811. for(i=0;i<PACKETBLOBS;i++){
  153812. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  153813. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  153814. }
  153815. }
  153816. }else{
  153817. for(i=0;i<PACKETBLOBS;i++){
  153818. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  153819. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  153820. }
  153821. }
  153822. return;
  153823. }
  153824. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  153825. int *nn_start,
  153826. int *nn_partition,
  153827. double *nn_thresh,
  153828. int block){
  153829. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  153830. vorbis_info_psy *p=ci->psy_param[block];
  153831. highlevel_encode_setup *hi=&ci->hi;
  153832. int is=s;
  153833. if(block>=ci->psys)
  153834. ci->psys=block+1;
  153835. if(!p){
  153836. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  153837. ci->psy_param[block]=p;
  153838. }
  153839. memcpy(p,&_psy_info_template,sizeof(*p));
  153840. p->blockflag=block>>1;
  153841. if(hi->noise_normalize_p){
  153842. p->normal_channel_p=1;
  153843. p->normal_point_p=1;
  153844. p->normal_start=nn_start[is];
  153845. p->normal_partition=nn_partition[is];
  153846. p->normal_thresh=nn_thresh[is];
  153847. }
  153848. return;
  153849. }
  153850. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  153851. att3 *att,
  153852. int *max,
  153853. vp_adjblock *in){
  153854. int i,is=s;
  153855. double ds=s-is;
  153856. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  153857. vorbis_info_psy *p=ci->psy_param[block];
  153858. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  153859. filling the values in here */
  153860. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  153861. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  153862. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  153863. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  153864. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  153865. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  153866. for(i=0;i<P_BANDS;i++)
  153867. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  153868. return;
  153869. }
  153870. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  153871. compandblock *in, double *x){
  153872. int i,is=s;
  153873. double ds=s-is;
  153874. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  153875. vorbis_info_psy *p=ci->psy_param[block];
  153876. ds=x[is]*(1.-ds)+x[is+1]*ds;
  153877. is=(int)ds;
  153878. ds-=is;
  153879. if(ds==0 && is>0){
  153880. is--;
  153881. ds=1.;
  153882. }
  153883. /* interpolate the compander settings */
  153884. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  153885. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  153886. return;
  153887. }
  153888. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  153889. int *suppress){
  153890. int is=s;
  153891. double ds=s-is;
  153892. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  153893. vorbis_info_psy *p=ci->psy_param[block];
  153894. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  153895. return;
  153896. }
  153897. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  153898. int *suppress,
  153899. noise3 *in,
  153900. noiseguard *guard,
  153901. double userbias){
  153902. int i,is=s,j;
  153903. double ds=s-is;
  153904. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  153905. vorbis_info_psy *p=ci->psy_param[block];
  153906. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  153907. p->noisewindowlomin=guard[block].lo;
  153908. p->noisewindowhimin=guard[block].hi;
  153909. p->noisewindowfixed=guard[block].fixed;
  153910. for(j=0;j<P_NOISECURVES;j++)
  153911. for(i=0;i<P_BANDS;i++)
  153912. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  153913. /* impulse blocks may take a user specified bias to boost the
  153914. nominal/high noise encoding depth */
  153915. for(j=0;j<P_NOISECURVES;j++){
  153916. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  153917. for(i=0;i<P_BANDS;i++){
  153918. p->noiseoff[j][i]+=userbias;
  153919. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  153920. }
  153921. }
  153922. return;
  153923. }
  153924. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  153925. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  153926. vorbis_info_psy *p=ci->psy_param[block];
  153927. p->ath_adjatt=ci->hi.ath_floating_dB;
  153928. p->ath_maxatt=ci->hi.ath_absolute_dB;
  153929. return;
  153930. }
  153931. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  153932. int i;
  153933. for(i=0;i<ci->books;i++)
  153934. if(ci->book_param[i]==book)return(i);
  153935. return(ci->books++);
  153936. }
  153937. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  153938. int *shortb,int *longb){
  153939. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  153940. int is=s;
  153941. int blockshort=shortb[is];
  153942. int blocklong=longb[is];
  153943. ci->blocksizes[0]=blockshort;
  153944. ci->blocksizes[1]=blocklong;
  153945. }
  153946. static void vorbis_encode_residue_setup(vorbis_info *vi,
  153947. int number, int block,
  153948. vorbis_residue_template *res){
  153949. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  153950. int i,n;
  153951. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  153952. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  153953. memcpy(r,res->res,sizeof(*r));
  153954. if(ci->residues<=number)ci->residues=number+1;
  153955. switch(ci->blocksizes[block]){
  153956. case 64:case 128:case 256:
  153957. r->grouping=16;
  153958. break;
  153959. default:
  153960. r->grouping=32;
  153961. break;
  153962. }
  153963. ci->residue_type[number]=res->res_type;
  153964. /* to be adjusted by lowpass/pointlimit later */
  153965. n=r->end=ci->blocksizes[block]>>1;
  153966. if(res->res_type==2)
  153967. n=r->end*=vi->channels;
  153968. /* fill in all the books */
  153969. {
  153970. int booklist=0,k;
  153971. if(ci->hi.managed){
  153972. for(i=0;i<r->partitions;i++)
  153973. for(k=0;k<3;k++)
  153974. if(res->books_base_managed->books[i][k])
  153975. r->secondstages[i]|=(1<<k);
  153976. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  153977. ci->book_param[r->groupbook]=res->book_aux_managed;
  153978. for(i=0;i<r->partitions;i++){
  153979. for(k=0;k<3;k++){
  153980. if(res->books_base_managed->books[i][k]){
  153981. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  153982. r->booklist[booklist++]=bookid;
  153983. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  153984. }
  153985. }
  153986. }
  153987. }else{
  153988. for(i=0;i<r->partitions;i++)
  153989. for(k=0;k<3;k++)
  153990. if(res->books_base->books[i][k])
  153991. r->secondstages[i]|=(1<<k);
  153992. r->groupbook=book_dup_or_new(ci,res->book_aux);
  153993. ci->book_param[r->groupbook]=res->book_aux;
  153994. for(i=0;i<r->partitions;i++){
  153995. for(k=0;k<3;k++){
  153996. if(res->books_base->books[i][k]){
  153997. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  153998. r->booklist[booklist++]=bookid;
  153999. ci->book_param[bookid]=res->books_base->books[i][k];
  154000. }
  154001. }
  154002. }
  154003. }
  154004. }
  154005. /* lowpass setup/pointlimit */
  154006. {
  154007. double freq=ci->hi.lowpass_kHz*1000.;
  154008. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  154009. double nyq=vi->rate/2.;
  154010. long blocksize=ci->blocksizes[block]>>1;
  154011. /* lowpass needs to be set in the floor and the residue. */
  154012. if(freq>nyq)freq=nyq;
  154013. /* in the floor, the granularity can be very fine; it doesn't alter
  154014. the encoding structure, only the samples used to fit the floor
  154015. approximation */
  154016. f->n=freq/nyq*blocksize;
  154017. /* this res may by limited by the maximum pointlimit of the mode,
  154018. not the lowpass. the floor is always lowpass limited. */
  154019. if(res->limit_type){
  154020. if(ci->hi.managed)
  154021. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  154022. else
  154023. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  154024. if(freq>nyq)freq=nyq;
  154025. }
  154026. /* in the residue, we're constrained, physically, by partition
  154027. boundaries. We still lowpass 'wherever', but we have to round up
  154028. here to next boundary, or the vorbis spec will round it *down* to
  154029. previous boundary in encode/decode */
  154030. if(ci->residue_type[block]==2)
  154031. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  154032. r->grouping;
  154033. else
  154034. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  154035. r->grouping;
  154036. }
  154037. }
  154038. /* we assume two maps in this encoder */
  154039. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  154040. vorbis_mapping_template *maps){
  154041. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154042. int i,j,is=s,modes=2;
  154043. vorbis_info_mapping0 *map=maps[is].map;
  154044. vorbis_info_mode *mode=_mode_template;
  154045. vorbis_residue_template *res=maps[is].res;
  154046. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  154047. for(i=0;i<modes;i++){
  154048. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  154049. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  154050. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  154051. if(i>=ci->modes)ci->modes=i+1;
  154052. ci->map_type[i]=0;
  154053. memcpy(ci->map_param[i],map+i,sizeof(*map));
  154054. if(i>=ci->maps)ci->maps=i+1;
  154055. for(j=0;j<map[i].submaps;j++)
  154056. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  154057. ,res+map[i].residuesubmap[j]);
  154058. }
  154059. }
  154060. static double setting_to_approx_bitrate(vorbis_info *vi){
  154061. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154062. highlevel_encode_setup *hi=&ci->hi;
  154063. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  154064. int is=hi->base_setting;
  154065. double ds=hi->base_setting-is;
  154066. int ch=vi->channels;
  154067. double *r=setup->rate_mapping;
  154068. if(r==NULL)
  154069. return(-1);
  154070. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  154071. }
  154072. static void get_setup_template(vorbis_info *vi,
  154073. long ch,long srate,
  154074. double req,int q_or_bitrate){
  154075. int i=0,j;
  154076. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154077. highlevel_encode_setup *hi=&ci->hi;
  154078. if(q_or_bitrate)req/=ch;
  154079. while(setup_list[i]){
  154080. if(setup_list[i]->coupling_restriction==-1 ||
  154081. setup_list[i]->coupling_restriction==ch){
  154082. if(srate>=setup_list[i]->samplerate_min_restriction &&
  154083. srate<=setup_list[i]->samplerate_max_restriction){
  154084. int mappings=setup_list[i]->mappings;
  154085. double *map=(q_or_bitrate?
  154086. setup_list[i]->rate_mapping:
  154087. setup_list[i]->quality_mapping);
  154088. /* the template matches. Does the requested quality mode
  154089. fall within this template's modes? */
  154090. if(req<map[0]){++i;continue;}
  154091. if(req>map[setup_list[i]->mappings]){++i;continue;}
  154092. for(j=0;j<mappings;j++)
  154093. if(req>=map[j] && req<map[j+1])break;
  154094. /* an all-points match */
  154095. hi->setup=setup_list[i];
  154096. if(j==mappings)
  154097. hi->base_setting=j-.001;
  154098. else{
  154099. float low=map[j];
  154100. float high=map[j+1];
  154101. float del=(req-low)/(high-low);
  154102. hi->base_setting=j+del;
  154103. }
  154104. return;
  154105. }
  154106. }
  154107. i++;
  154108. }
  154109. hi->setup=NULL;
  154110. }
  154111. /* encoders will need to use vorbis_info_init beforehand and call
  154112. vorbis_info clear when all done */
  154113. /* two interfaces; this, more detailed one, and later a convenience
  154114. layer on top */
  154115. /* the final setup call */
  154116. int vorbis_encode_setup_init(vorbis_info *vi){
  154117. int i0=0,singleblock=0;
  154118. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154119. ve_setup_data_template *setup=NULL;
  154120. highlevel_encode_setup *hi=&ci->hi;
  154121. if(ci==NULL)return(OV_EINVAL);
  154122. if(!hi->impulse_block_p)i0=1;
  154123. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  154124. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  154125. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  154126. /* again, bound this to avoid the app shooting itself int he foot
  154127. too badly */
  154128. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  154129. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  154130. /* get the appropriate setup template; matches the fetch in previous
  154131. stages */
  154132. setup=(ve_setup_data_template *)hi->setup;
  154133. if(setup==NULL)return(OV_EINVAL);
  154134. hi->set_in_stone=1;
  154135. /* choose block sizes from configured sizes as well as paying
  154136. attention to long_block_p and short_block_p. If the configured
  154137. short and long blocks are the same length, we set long_block_p
  154138. and unset short_block_p */
  154139. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  154140. setup->blocksize_short,
  154141. setup->blocksize_long);
  154142. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  154143. /* floor setup; choose proper floor params. Allocated on the floor
  154144. stack in order; if we alloc only long floor, it's 0 */
  154145. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  154146. setup->floor_books,
  154147. setup->floor_params,
  154148. setup->floor_short_mapping);
  154149. if(!singleblock)
  154150. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  154151. setup->floor_books,
  154152. setup->floor_params,
  154153. setup->floor_long_mapping);
  154154. /* setup of [mostly] short block detection and stereo*/
  154155. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  154156. setup->global_params,
  154157. setup->global_mapping);
  154158. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  154159. /* basic psych setup and noise normalization */
  154160. vorbis_encode_psyset_setup(vi,hi->short_setting,
  154161. setup->psy_noise_normal_start[0],
  154162. setup->psy_noise_normal_partition[0],
  154163. setup->psy_noise_normal_thresh,
  154164. 0);
  154165. vorbis_encode_psyset_setup(vi,hi->short_setting,
  154166. setup->psy_noise_normal_start[0],
  154167. setup->psy_noise_normal_partition[0],
  154168. setup->psy_noise_normal_thresh,
  154169. 1);
  154170. if(!singleblock){
  154171. vorbis_encode_psyset_setup(vi,hi->long_setting,
  154172. setup->psy_noise_normal_start[1],
  154173. setup->psy_noise_normal_partition[1],
  154174. setup->psy_noise_normal_thresh,
  154175. 2);
  154176. vorbis_encode_psyset_setup(vi,hi->long_setting,
  154177. setup->psy_noise_normal_start[1],
  154178. setup->psy_noise_normal_partition[1],
  154179. setup->psy_noise_normal_thresh,
  154180. 3);
  154181. }
  154182. /* tone masking setup */
  154183. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  154184. setup->psy_tone_masteratt,
  154185. setup->psy_tone_0dB,
  154186. setup->psy_tone_adj_impulse);
  154187. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  154188. setup->psy_tone_masteratt,
  154189. setup->psy_tone_0dB,
  154190. setup->psy_tone_adj_other);
  154191. if(!singleblock){
  154192. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  154193. setup->psy_tone_masteratt,
  154194. setup->psy_tone_0dB,
  154195. setup->psy_tone_adj_other);
  154196. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  154197. setup->psy_tone_masteratt,
  154198. setup->psy_tone_0dB,
  154199. setup->psy_tone_adj_long);
  154200. }
  154201. /* noise companding setup */
  154202. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  154203. setup->psy_noise_compand,
  154204. setup->psy_noise_compand_short_mapping);
  154205. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  154206. setup->psy_noise_compand,
  154207. setup->psy_noise_compand_short_mapping);
  154208. if(!singleblock){
  154209. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  154210. setup->psy_noise_compand,
  154211. setup->psy_noise_compand_long_mapping);
  154212. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  154213. setup->psy_noise_compand,
  154214. setup->psy_noise_compand_long_mapping);
  154215. }
  154216. /* peak guarding setup */
  154217. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  154218. setup->psy_tone_dBsuppress);
  154219. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  154220. setup->psy_tone_dBsuppress);
  154221. if(!singleblock){
  154222. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  154223. setup->psy_tone_dBsuppress);
  154224. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  154225. setup->psy_tone_dBsuppress);
  154226. }
  154227. /* noise bias setup */
  154228. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  154229. setup->psy_noise_dBsuppress,
  154230. setup->psy_noise_bias_impulse,
  154231. setup->psy_noiseguards,
  154232. (i0==0?hi->impulse_noisetune:0.));
  154233. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  154234. setup->psy_noise_dBsuppress,
  154235. setup->psy_noise_bias_padding,
  154236. setup->psy_noiseguards,0.);
  154237. if(!singleblock){
  154238. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  154239. setup->psy_noise_dBsuppress,
  154240. setup->psy_noise_bias_trans,
  154241. setup->psy_noiseguards,0.);
  154242. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  154243. setup->psy_noise_dBsuppress,
  154244. setup->psy_noise_bias_long,
  154245. setup->psy_noiseguards,0.);
  154246. }
  154247. vorbis_encode_ath_setup(vi,0);
  154248. vorbis_encode_ath_setup(vi,1);
  154249. if(!singleblock){
  154250. vorbis_encode_ath_setup(vi,2);
  154251. vorbis_encode_ath_setup(vi,3);
  154252. }
  154253. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  154254. /* set bitrate readonlies and management */
  154255. if(hi->bitrate_av>0)
  154256. vi->bitrate_nominal=hi->bitrate_av;
  154257. else{
  154258. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  154259. }
  154260. vi->bitrate_lower=hi->bitrate_min;
  154261. vi->bitrate_upper=hi->bitrate_max;
  154262. if(hi->bitrate_av)
  154263. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  154264. else
  154265. vi->bitrate_window=0.;
  154266. if(hi->managed){
  154267. ci->bi.avg_rate=hi->bitrate_av;
  154268. ci->bi.min_rate=hi->bitrate_min;
  154269. ci->bi.max_rate=hi->bitrate_max;
  154270. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  154271. ci->bi.reservoir_bias=
  154272. hi->bitrate_reservoir_bias;
  154273. ci->bi.slew_damp=hi->bitrate_av_damp;
  154274. }
  154275. return(0);
  154276. }
  154277. static int vorbis_encode_setup_setting(vorbis_info *vi,
  154278. long channels,
  154279. long rate){
  154280. int ret=0,i,is;
  154281. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154282. highlevel_encode_setup *hi=&ci->hi;
  154283. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  154284. double ds;
  154285. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  154286. if(ret)return(ret);
  154287. is=hi->base_setting;
  154288. ds=hi->base_setting-is;
  154289. hi->short_setting=hi->base_setting;
  154290. hi->long_setting=hi->base_setting;
  154291. hi->managed=0;
  154292. hi->impulse_block_p=1;
  154293. hi->noise_normalize_p=1;
  154294. hi->stereo_point_setting=hi->base_setting;
  154295. hi->lowpass_kHz=
  154296. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  154297. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  154298. setup->psy_ath_float[is+1]*ds;
  154299. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  154300. setup->psy_ath_abs[is+1]*ds;
  154301. hi->amplitude_track_dBpersec=-6.;
  154302. hi->trigger_setting=hi->base_setting;
  154303. for(i=0;i<4;i++){
  154304. hi->block[i].tone_mask_setting=hi->base_setting;
  154305. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  154306. hi->block[i].noise_bias_setting=hi->base_setting;
  154307. hi->block[i].noise_compand_setting=hi->base_setting;
  154308. }
  154309. return(ret);
  154310. }
  154311. int vorbis_encode_setup_vbr(vorbis_info *vi,
  154312. long channels,
  154313. long rate,
  154314. float quality){
  154315. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154316. highlevel_encode_setup *hi=&ci->hi;
  154317. quality+=.0000001;
  154318. if(quality>=1.)quality=.9999;
  154319. get_setup_template(vi,channels,rate,quality,0);
  154320. if(!hi->setup)return OV_EIMPL;
  154321. return vorbis_encode_setup_setting(vi,channels,rate);
  154322. }
  154323. int vorbis_encode_init_vbr(vorbis_info *vi,
  154324. long channels,
  154325. long rate,
  154326. float base_quality /* 0. to 1. */
  154327. ){
  154328. int ret=0;
  154329. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  154330. if(ret){
  154331. vorbis_info_clear(vi);
  154332. return ret;
  154333. }
  154334. ret=vorbis_encode_setup_init(vi);
  154335. if(ret)
  154336. vorbis_info_clear(vi);
  154337. return(ret);
  154338. }
  154339. int vorbis_encode_setup_managed(vorbis_info *vi,
  154340. long channels,
  154341. long rate,
  154342. long max_bitrate,
  154343. long nominal_bitrate,
  154344. long min_bitrate){
  154345. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154346. highlevel_encode_setup *hi=&ci->hi;
  154347. double tnominal=nominal_bitrate;
  154348. int ret=0;
  154349. if(nominal_bitrate<=0.){
  154350. if(max_bitrate>0.){
  154351. if(min_bitrate>0.)
  154352. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  154353. else
  154354. nominal_bitrate=max_bitrate*.875;
  154355. }else{
  154356. if(min_bitrate>0.){
  154357. nominal_bitrate=min_bitrate;
  154358. }else{
  154359. return(OV_EINVAL);
  154360. }
  154361. }
  154362. }
  154363. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  154364. if(!hi->setup)return OV_EIMPL;
  154365. ret=vorbis_encode_setup_setting(vi,channels,rate);
  154366. if(ret){
  154367. vorbis_info_clear(vi);
  154368. return ret;
  154369. }
  154370. /* initialize management with sane defaults */
  154371. hi->managed=1;
  154372. hi->bitrate_min=min_bitrate;
  154373. hi->bitrate_max=max_bitrate;
  154374. hi->bitrate_av=tnominal;
  154375. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  154376. hi->bitrate_reservoir=nominal_bitrate*2;
  154377. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  154378. return(ret);
  154379. }
  154380. int vorbis_encode_init(vorbis_info *vi,
  154381. long channels,
  154382. long rate,
  154383. long max_bitrate,
  154384. long nominal_bitrate,
  154385. long min_bitrate){
  154386. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  154387. max_bitrate,
  154388. nominal_bitrate,
  154389. min_bitrate);
  154390. if(ret){
  154391. vorbis_info_clear(vi);
  154392. return(ret);
  154393. }
  154394. ret=vorbis_encode_setup_init(vi);
  154395. if(ret)
  154396. vorbis_info_clear(vi);
  154397. return(ret);
  154398. }
  154399. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  154400. if(vi){
  154401. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154402. highlevel_encode_setup *hi=&ci->hi;
  154403. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  154404. if(setp && hi->set_in_stone)return(OV_EINVAL);
  154405. switch(number){
  154406. /* now deprecated *****************/
  154407. case OV_ECTL_RATEMANAGE_GET:
  154408. {
  154409. struct ovectl_ratemanage_arg *ai=
  154410. (struct ovectl_ratemanage_arg *)arg;
  154411. ai->management_active=hi->managed;
  154412. ai->bitrate_hard_window=ai->bitrate_av_window=
  154413. (double)hi->bitrate_reservoir/vi->rate;
  154414. ai->bitrate_av_window_center=1.;
  154415. ai->bitrate_hard_min=hi->bitrate_min;
  154416. ai->bitrate_hard_max=hi->bitrate_max;
  154417. ai->bitrate_av_lo=hi->bitrate_av;
  154418. ai->bitrate_av_hi=hi->bitrate_av;
  154419. }
  154420. return(0);
  154421. /* now deprecated *****************/
  154422. case OV_ECTL_RATEMANAGE_SET:
  154423. {
  154424. struct ovectl_ratemanage_arg *ai=
  154425. (struct ovectl_ratemanage_arg *)arg;
  154426. if(ai==NULL){
  154427. hi->managed=0;
  154428. }else{
  154429. hi->managed=ai->management_active;
  154430. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  154431. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  154432. }
  154433. }
  154434. return 0;
  154435. /* now deprecated *****************/
  154436. case OV_ECTL_RATEMANAGE_AVG:
  154437. {
  154438. struct ovectl_ratemanage_arg *ai=
  154439. (struct ovectl_ratemanage_arg *)arg;
  154440. if(ai==NULL){
  154441. hi->bitrate_av=0;
  154442. }else{
  154443. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  154444. }
  154445. }
  154446. return(0);
  154447. /* now deprecated *****************/
  154448. case OV_ECTL_RATEMANAGE_HARD:
  154449. {
  154450. struct ovectl_ratemanage_arg *ai=
  154451. (struct ovectl_ratemanage_arg *)arg;
  154452. if(ai==NULL){
  154453. hi->bitrate_min=0;
  154454. hi->bitrate_max=0;
  154455. }else{
  154456. hi->bitrate_min=ai->bitrate_hard_min;
  154457. hi->bitrate_max=ai->bitrate_hard_max;
  154458. hi->bitrate_reservoir=ai->bitrate_hard_window*
  154459. (hi->bitrate_max+hi->bitrate_min)*.5;
  154460. }
  154461. if(hi->bitrate_reservoir<128.)
  154462. hi->bitrate_reservoir=128.;
  154463. }
  154464. return(0);
  154465. /* replacement ratemanage interface */
  154466. case OV_ECTL_RATEMANAGE2_GET:
  154467. {
  154468. struct ovectl_ratemanage2_arg *ai=
  154469. (struct ovectl_ratemanage2_arg *)arg;
  154470. if(ai==NULL)return OV_EINVAL;
  154471. ai->management_active=hi->managed;
  154472. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  154473. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  154474. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  154475. ai->bitrate_average_damping=hi->bitrate_av_damp;
  154476. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  154477. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  154478. }
  154479. return (0);
  154480. case OV_ECTL_RATEMANAGE2_SET:
  154481. {
  154482. struct ovectl_ratemanage2_arg *ai=
  154483. (struct ovectl_ratemanage2_arg *)arg;
  154484. if(ai==NULL){
  154485. hi->managed=0;
  154486. }else{
  154487. /* sanity check; only catch invariant violations */
  154488. if(ai->bitrate_limit_min_kbps>0 &&
  154489. ai->bitrate_average_kbps>0 &&
  154490. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  154491. return OV_EINVAL;
  154492. if(ai->bitrate_limit_max_kbps>0 &&
  154493. ai->bitrate_average_kbps>0 &&
  154494. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  154495. return OV_EINVAL;
  154496. if(ai->bitrate_limit_min_kbps>0 &&
  154497. ai->bitrate_limit_max_kbps>0 &&
  154498. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  154499. return OV_EINVAL;
  154500. if(ai->bitrate_average_damping <= 0.)
  154501. return OV_EINVAL;
  154502. if(ai->bitrate_limit_reservoir_bits < 0)
  154503. return OV_EINVAL;
  154504. if(ai->bitrate_limit_reservoir_bias < 0.)
  154505. return OV_EINVAL;
  154506. if(ai->bitrate_limit_reservoir_bias > 1.)
  154507. return OV_EINVAL;
  154508. hi->managed=ai->management_active;
  154509. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  154510. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  154511. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  154512. hi->bitrate_av_damp=ai->bitrate_average_damping;
  154513. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  154514. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  154515. }
  154516. }
  154517. return 0;
  154518. case OV_ECTL_LOWPASS_GET:
  154519. {
  154520. double *farg=(double *)arg;
  154521. *farg=hi->lowpass_kHz;
  154522. }
  154523. return(0);
  154524. case OV_ECTL_LOWPASS_SET:
  154525. {
  154526. double *farg=(double *)arg;
  154527. hi->lowpass_kHz=*farg;
  154528. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  154529. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  154530. }
  154531. return(0);
  154532. case OV_ECTL_IBLOCK_GET:
  154533. {
  154534. double *farg=(double *)arg;
  154535. *farg=hi->impulse_noisetune;
  154536. }
  154537. return(0);
  154538. case OV_ECTL_IBLOCK_SET:
  154539. {
  154540. double *farg=(double *)arg;
  154541. hi->impulse_noisetune=*farg;
  154542. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  154543. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  154544. }
  154545. return(0);
  154546. }
  154547. return(OV_EIMPL);
  154548. }
  154549. return(OV_EINVAL);
  154550. }
  154551. #endif
  154552. /*** End of inlined file: vorbisenc.c ***/
  154553. /*** Start of inlined file: vorbisfile.c ***/
  154554. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  154555. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  154556. // tasks..
  154557. #if JUCE_MSVC
  154558. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  154559. #endif
  154560. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  154561. #if JUCE_USE_OGGVORBIS
  154562. #include <stdlib.h>
  154563. #include <stdio.h>
  154564. #include <errno.h>
  154565. #include <string.h>
  154566. #include <math.h>
  154567. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  154568. one logical bitstream arranged end to end (the only form of Ogg
  154569. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  154570. multiplexing] is not allowed in Vorbis) */
  154571. /* A Vorbis file can be played beginning to end (streamed) without
  154572. worrying ahead of time about chaining (see decoder_example.c). If
  154573. we have the whole file, however, and want random access
  154574. (seeking/scrubbing) or desire to know the total length/time of a
  154575. file, we need to account for the possibility of chaining. */
  154576. /* We can handle things a number of ways; we can determine the entire
  154577. bitstream structure right off the bat, or find pieces on demand.
  154578. This example determines and caches structure for the entire
  154579. bitstream, but builds a virtual decoder on the fly when moving
  154580. between links in the chain. */
  154581. /* There are also different ways to implement seeking. Enough
  154582. information exists in an Ogg bitstream to seek to
  154583. sample-granularity positions in the output. Or, one can seek by
  154584. picking some portion of the stream roughly in the desired area if
  154585. we only want coarse navigation through the stream. */
  154586. /*************************************************************************
  154587. * Many, many internal helpers. The intention is not to be confusing;
  154588. * rampant duplication and monolithic function implementation would be
  154589. * harder to understand anyway. The high level functions are last. Begin
  154590. * grokking near the end of the file */
  154591. /* read a little more data from the file/pipe into the ogg_sync framer
  154592. */
  154593. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  154594. over 8k gets what they deserve */
  154595. static long _get_data(OggVorbis_File *vf){
  154596. errno=0;
  154597. if(vf->datasource){
  154598. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  154599. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  154600. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  154601. if(bytes==0 && errno)return(-1);
  154602. return(bytes);
  154603. }else
  154604. return(0);
  154605. }
  154606. /* save a tiny smidge of verbosity to make the code more readable */
  154607. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  154608. if(vf->datasource){
  154609. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  154610. vf->offset=offset;
  154611. ogg_sync_reset(&vf->oy);
  154612. }else{
  154613. /* shouldn't happen unless someone writes a broken callback */
  154614. return;
  154615. }
  154616. }
  154617. /* The read/seek functions track absolute position within the stream */
  154618. /* from the head of the stream, get the next page. boundary specifies
  154619. if the function is allowed to fetch more data from the stream (and
  154620. how much) or only use internally buffered data.
  154621. boundary: -1) unbounded search
  154622. 0) read no additional data; use cached only
  154623. n) search for a new page beginning for n bytes
  154624. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  154625. n) found a page at absolute offset n */
  154626. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  154627. ogg_int64_t boundary){
  154628. if(boundary>0)boundary+=vf->offset;
  154629. while(1){
  154630. long more;
  154631. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  154632. more=ogg_sync_pageseek(&vf->oy,og);
  154633. if(more<0){
  154634. /* skipped n bytes */
  154635. vf->offset-=more;
  154636. }else{
  154637. if(more==0){
  154638. /* send more paramedics */
  154639. if(!boundary)return(OV_FALSE);
  154640. {
  154641. long ret=_get_data(vf);
  154642. if(ret==0)return(OV_EOF);
  154643. if(ret<0)return(OV_EREAD);
  154644. }
  154645. }else{
  154646. /* got a page. Return the offset at the page beginning,
  154647. advance the internal offset past the page end */
  154648. ogg_int64_t ret=vf->offset;
  154649. vf->offset+=more;
  154650. return(ret);
  154651. }
  154652. }
  154653. }
  154654. }
  154655. /* find the latest page beginning before the current stream cursor
  154656. position. Much dirtier than the above as Ogg doesn't have any
  154657. backward search linkage. no 'readp' as it will certainly have to
  154658. read. */
  154659. /* returns offset or OV_EREAD, OV_FAULT */
  154660. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  154661. ogg_int64_t begin=vf->offset;
  154662. ogg_int64_t end=begin;
  154663. ogg_int64_t ret;
  154664. ogg_int64_t offset=-1;
  154665. while(offset==-1){
  154666. begin-=CHUNKSIZE;
  154667. if(begin<0)
  154668. begin=0;
  154669. _seek_helper(vf,begin);
  154670. while(vf->offset<end){
  154671. ret=_get_next_page(vf,og,end-vf->offset);
  154672. if(ret==OV_EREAD)return(OV_EREAD);
  154673. if(ret<0){
  154674. break;
  154675. }else{
  154676. offset=ret;
  154677. }
  154678. }
  154679. }
  154680. /* we have the offset. Actually snork and hold the page now */
  154681. _seek_helper(vf,offset);
  154682. ret=_get_next_page(vf,og,CHUNKSIZE);
  154683. if(ret<0)
  154684. /* this shouldn't be possible */
  154685. return(OV_EFAULT);
  154686. return(offset);
  154687. }
  154688. /* finds each bitstream link one at a time using a bisection search
  154689. (has to begin by knowing the offset of the lb's initial page).
  154690. Recurses for each link so it can alloc the link storage after
  154691. finding them all, then unroll and fill the cache at the same time */
  154692. static int _bisect_forward_serialno(OggVorbis_File *vf,
  154693. ogg_int64_t begin,
  154694. ogg_int64_t searched,
  154695. ogg_int64_t end,
  154696. long currentno,
  154697. long m){
  154698. ogg_int64_t endsearched=end;
  154699. ogg_int64_t next=end;
  154700. ogg_page og;
  154701. ogg_int64_t ret;
  154702. /* the below guards against garbage seperating the last and
  154703. first pages of two links. */
  154704. while(searched<endsearched){
  154705. ogg_int64_t bisect;
  154706. if(endsearched-searched<CHUNKSIZE){
  154707. bisect=searched;
  154708. }else{
  154709. bisect=(searched+endsearched)/2;
  154710. }
  154711. _seek_helper(vf,bisect);
  154712. ret=_get_next_page(vf,&og,-1);
  154713. if(ret==OV_EREAD)return(OV_EREAD);
  154714. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  154715. endsearched=bisect;
  154716. if(ret>=0)next=ret;
  154717. }else{
  154718. searched=ret+og.header_len+og.body_len;
  154719. }
  154720. }
  154721. _seek_helper(vf,next);
  154722. ret=_get_next_page(vf,&og,-1);
  154723. if(ret==OV_EREAD)return(OV_EREAD);
  154724. if(searched>=end || ret<0){
  154725. vf->links=m+1;
  154726. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  154727. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  154728. vf->offsets[m+1]=searched;
  154729. }else{
  154730. ret=_bisect_forward_serialno(vf,next,vf->offset,
  154731. end,ogg_page_serialno(&og),m+1);
  154732. if(ret==OV_EREAD)return(OV_EREAD);
  154733. }
  154734. vf->offsets[m]=begin;
  154735. vf->serialnos[m]=currentno;
  154736. return(0);
  154737. }
  154738. /* uses the local ogg_stream storage in vf; this is important for
  154739. non-streaming input sources */
  154740. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  154741. long *serialno,ogg_page *og_ptr){
  154742. ogg_page og;
  154743. ogg_packet op;
  154744. int i,ret;
  154745. if(!og_ptr){
  154746. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  154747. if(llret==OV_EREAD)return(OV_EREAD);
  154748. if(llret<0)return OV_ENOTVORBIS;
  154749. og_ptr=&og;
  154750. }
  154751. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  154752. if(serialno)*serialno=vf->os.serialno;
  154753. vf->ready_state=STREAMSET;
  154754. /* extract the initial header from the first page and verify that the
  154755. Ogg bitstream is in fact Vorbis data */
  154756. vorbis_info_init(vi);
  154757. vorbis_comment_init(vc);
  154758. i=0;
  154759. while(i<3){
  154760. ogg_stream_pagein(&vf->os,og_ptr);
  154761. while(i<3){
  154762. int result=ogg_stream_packetout(&vf->os,&op);
  154763. if(result==0)break;
  154764. if(result==-1){
  154765. ret=OV_EBADHEADER;
  154766. goto bail_header;
  154767. }
  154768. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  154769. goto bail_header;
  154770. }
  154771. i++;
  154772. }
  154773. if(i<3)
  154774. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  154775. ret=OV_EBADHEADER;
  154776. goto bail_header;
  154777. }
  154778. }
  154779. return 0;
  154780. bail_header:
  154781. vorbis_info_clear(vi);
  154782. vorbis_comment_clear(vc);
  154783. vf->ready_state=OPENED;
  154784. return ret;
  154785. }
  154786. /* last step of the OggVorbis_File initialization; get all the
  154787. vorbis_info structs and PCM positions. Only called by the seekable
  154788. initialization (local stream storage is hacked slightly; pay
  154789. attention to how that's done) */
  154790. /* this is void and does not propogate errors up because we want to be
  154791. able to open and use damaged bitstreams as well as we can. Just
  154792. watch out for missing information for links in the OggVorbis_File
  154793. struct */
  154794. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  154795. ogg_page og;
  154796. int i;
  154797. ogg_int64_t ret;
  154798. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  154799. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  154800. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  154801. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  154802. for(i=0;i<vf->links;i++){
  154803. if(i==0){
  154804. /* we already grabbed the initial header earlier. Just set the offset */
  154805. vf->dataoffsets[i]=dataoffset;
  154806. _seek_helper(vf,dataoffset);
  154807. }else{
  154808. /* seek to the location of the initial header */
  154809. _seek_helper(vf,vf->offsets[i]);
  154810. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  154811. vf->dataoffsets[i]=-1;
  154812. }else{
  154813. vf->dataoffsets[i]=vf->offset;
  154814. }
  154815. }
  154816. /* fetch beginning PCM offset */
  154817. if(vf->dataoffsets[i]!=-1){
  154818. ogg_int64_t accumulated=0;
  154819. long lastblock=-1;
  154820. int result;
  154821. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  154822. while(1){
  154823. ogg_packet op;
  154824. ret=_get_next_page(vf,&og,-1);
  154825. if(ret<0)
  154826. /* this should not be possible unless the file is
  154827. truncated/mangled */
  154828. break;
  154829. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  154830. break;
  154831. /* count blocksizes of all frames in the page */
  154832. ogg_stream_pagein(&vf->os,&og);
  154833. while((result=ogg_stream_packetout(&vf->os,&op))){
  154834. if(result>0){ /* ignore holes */
  154835. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  154836. if(lastblock!=-1)
  154837. accumulated+=(lastblock+thisblock)>>2;
  154838. lastblock=thisblock;
  154839. }
  154840. }
  154841. if(ogg_page_granulepos(&og)!=-1){
  154842. /* pcm offset of last packet on the first audio page */
  154843. accumulated= ogg_page_granulepos(&og)-accumulated;
  154844. break;
  154845. }
  154846. }
  154847. /* less than zero? This is a stream with samples trimmed off
  154848. the beginning, a normal occurrence; set the offset to zero */
  154849. if(accumulated<0)accumulated=0;
  154850. vf->pcmlengths[i*2]=accumulated;
  154851. }
  154852. /* get the PCM length of this link. To do this,
  154853. get the last page of the stream */
  154854. {
  154855. ogg_int64_t end=vf->offsets[i+1];
  154856. _seek_helper(vf,end);
  154857. while(1){
  154858. ret=_get_prev_page(vf,&og);
  154859. if(ret<0){
  154860. /* this should not be possible */
  154861. vorbis_info_clear(vf->vi+i);
  154862. vorbis_comment_clear(vf->vc+i);
  154863. break;
  154864. }
  154865. if(ogg_page_granulepos(&og)!=-1){
  154866. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  154867. break;
  154868. }
  154869. vf->offset=ret;
  154870. }
  154871. }
  154872. }
  154873. }
  154874. static int _make_decode_ready(OggVorbis_File *vf){
  154875. if(vf->ready_state>STREAMSET)return 0;
  154876. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  154877. if(vf->seekable){
  154878. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  154879. return OV_EBADLINK;
  154880. }else{
  154881. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  154882. return OV_EBADLINK;
  154883. }
  154884. vorbis_block_init(&vf->vd,&vf->vb);
  154885. vf->ready_state=INITSET;
  154886. vf->bittrack=0.f;
  154887. vf->samptrack=0.f;
  154888. return 0;
  154889. }
  154890. static int _open_seekable2(OggVorbis_File *vf){
  154891. long serialno=vf->current_serialno;
  154892. ogg_int64_t dataoffset=vf->offset, end;
  154893. ogg_page og;
  154894. /* we're partially open and have a first link header state in
  154895. storage in vf */
  154896. /* we can seek, so set out learning all about this file */
  154897. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  154898. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  154899. /* We get the offset for the last page of the physical bitstream.
  154900. Most OggVorbis files will contain a single logical bitstream */
  154901. end=_get_prev_page(vf,&og);
  154902. if(end<0)return(end);
  154903. /* more than one logical bitstream? */
  154904. if(ogg_page_serialno(&og)!=serialno){
  154905. /* Chained bitstream. Bisect-search each logical bitstream
  154906. section. Do so based on serial number only */
  154907. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  154908. }else{
  154909. /* Only one logical bitstream */
  154910. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  154911. }
  154912. /* the initial header memory is referenced by vf after; don't free it */
  154913. _prefetch_all_headers(vf,dataoffset);
  154914. return(ov_raw_seek(vf,0));
  154915. }
  154916. /* clear out the current logical bitstream decoder */
  154917. static void _decode_clear(OggVorbis_File *vf){
  154918. vorbis_dsp_clear(&vf->vd);
  154919. vorbis_block_clear(&vf->vb);
  154920. vf->ready_state=OPENED;
  154921. }
  154922. /* fetch and process a packet. Handles the case where we're at a
  154923. bitstream boundary and dumps the decoding machine. If the decoding
  154924. machine is unloaded, it loads it. It also keeps pcm_offset up to
  154925. date (seek and read both use this. seek uses a special hack with
  154926. readp).
  154927. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  154928. 0) need more data (only if readp==0)
  154929. 1) got a packet
  154930. */
  154931. static int _fetch_and_process_packet(OggVorbis_File *vf,
  154932. ogg_packet *op_in,
  154933. int readp,
  154934. int spanp){
  154935. ogg_page og;
  154936. /* handle one packet. Try to fetch it from current stream state */
  154937. /* extract packets from page */
  154938. while(1){
  154939. /* process a packet if we can. If the machine isn't loaded,
  154940. neither is a page */
  154941. if(vf->ready_state==INITSET){
  154942. while(1) {
  154943. ogg_packet op;
  154944. ogg_packet *op_ptr=(op_in?op_in:&op);
  154945. int result=ogg_stream_packetout(&vf->os,op_ptr);
  154946. ogg_int64_t granulepos;
  154947. op_in=NULL;
  154948. if(result==-1)return(OV_HOLE); /* hole in the data. */
  154949. if(result>0){
  154950. /* got a packet. process it */
  154951. granulepos=op_ptr->granulepos;
  154952. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  154953. header handling. The
  154954. header packets aren't
  154955. audio, so if/when we
  154956. submit them,
  154957. vorbis_synthesis will
  154958. reject them */
  154959. /* suck in the synthesis data and track bitrate */
  154960. {
  154961. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  154962. /* for proper use of libvorbis within libvorbisfile,
  154963. oldsamples will always be zero. */
  154964. if(oldsamples)return(OV_EFAULT);
  154965. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  154966. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  154967. vf->bittrack+=op_ptr->bytes*8;
  154968. }
  154969. /* update the pcm offset. */
  154970. if(granulepos!=-1 && !op_ptr->e_o_s){
  154971. int link=(vf->seekable?vf->current_link:0);
  154972. int i,samples;
  154973. /* this packet has a pcm_offset on it (the last packet
  154974. completed on a page carries the offset) After processing
  154975. (above), we know the pcm position of the *last* sample
  154976. ready to be returned. Find the offset of the *first*
  154977. As an aside, this trick is inaccurate if we begin
  154978. reading anew right at the last page; the end-of-stream
  154979. granulepos declares the last frame in the stream, and the
  154980. last packet of the last page may be a partial frame.
  154981. So, we need a previous granulepos from an in-sequence page
  154982. to have a reference point. Thus the !op_ptr->e_o_s clause
  154983. above */
  154984. if(vf->seekable && link>0)
  154985. granulepos-=vf->pcmlengths[link*2];
  154986. if(granulepos<0)granulepos=0; /* actually, this
  154987. shouldn't be possible
  154988. here unless the stream
  154989. is very broken */
  154990. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  154991. granulepos-=samples;
  154992. for(i=0;i<link;i++)
  154993. granulepos+=vf->pcmlengths[i*2+1];
  154994. vf->pcm_offset=granulepos;
  154995. }
  154996. return(1);
  154997. }
  154998. }
  154999. else
  155000. break;
  155001. }
  155002. }
  155003. if(vf->ready_state>=OPENED){
  155004. ogg_int64_t ret;
  155005. if(!readp)return(0);
  155006. if((ret=_get_next_page(vf,&og,-1))<0){
  155007. return(OV_EOF); /* eof.
  155008. leave unitialized */
  155009. }
  155010. /* bitrate tracking; add the header's bytes here, the body bytes
  155011. are done by packet above */
  155012. vf->bittrack+=og.header_len*8;
  155013. /* has our decoding just traversed a bitstream boundary? */
  155014. if(vf->ready_state==INITSET){
  155015. if(vf->current_serialno!=ogg_page_serialno(&og)){
  155016. if(!spanp)
  155017. return(OV_EOF);
  155018. _decode_clear(vf);
  155019. if(!vf->seekable){
  155020. vorbis_info_clear(vf->vi);
  155021. vorbis_comment_clear(vf->vc);
  155022. }
  155023. }
  155024. }
  155025. }
  155026. /* Do we need to load a new machine before submitting the page? */
  155027. /* This is different in the seekable and non-seekable cases.
  155028. In the seekable case, we already have all the header
  155029. information loaded and cached; we just initialize the machine
  155030. with it and continue on our merry way.
  155031. In the non-seekable (streaming) case, we'll only be at a
  155032. boundary if we just left the previous logical bitstream and
  155033. we're now nominally at the header of the next bitstream
  155034. */
  155035. if(vf->ready_state!=INITSET){
  155036. int link;
  155037. if(vf->ready_state<STREAMSET){
  155038. if(vf->seekable){
  155039. vf->current_serialno=ogg_page_serialno(&og);
  155040. /* match the serialno to bitstream section. We use this rather than
  155041. offset positions to avoid problems near logical bitstream
  155042. boundaries */
  155043. for(link=0;link<vf->links;link++)
  155044. if(vf->serialnos[link]==vf->current_serialno)break;
  155045. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  155046. stream. error out,
  155047. leave machine
  155048. uninitialized */
  155049. vf->current_link=link;
  155050. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  155051. vf->ready_state=STREAMSET;
  155052. }else{
  155053. /* we're streaming */
  155054. /* fetch the three header packets, build the info struct */
  155055. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  155056. if(ret)return(ret);
  155057. vf->current_link++;
  155058. link=0;
  155059. }
  155060. }
  155061. {
  155062. int ret=_make_decode_ready(vf);
  155063. if(ret<0)return ret;
  155064. }
  155065. }
  155066. ogg_stream_pagein(&vf->os,&og);
  155067. }
  155068. }
  155069. /* if, eg, 64 bit stdio is configured by default, this will build with
  155070. fseek64 */
  155071. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  155072. if(f==NULL)return(-1);
  155073. return fseek(f,off,whence);
  155074. }
  155075. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  155076. long ibytes, ov_callbacks callbacks){
  155077. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  155078. int ret;
  155079. memset(vf,0,sizeof(*vf));
  155080. vf->datasource=f;
  155081. vf->callbacks = callbacks;
  155082. /* init the framing state */
  155083. ogg_sync_init(&vf->oy);
  155084. /* perhaps some data was previously read into a buffer for testing
  155085. against other stream types. Allow initialization from this
  155086. previously read data (as we may be reading from a non-seekable
  155087. stream) */
  155088. if(initial){
  155089. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  155090. memcpy(buffer,initial,ibytes);
  155091. ogg_sync_wrote(&vf->oy,ibytes);
  155092. }
  155093. /* can we seek? Stevens suggests the seek test was portable */
  155094. if(offsettest!=-1)vf->seekable=1;
  155095. /* No seeking yet; Set up a 'single' (current) logical bitstream
  155096. entry for partial open */
  155097. vf->links=1;
  155098. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  155099. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  155100. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  155101. /* Try to fetch the headers, maintaining all the storage */
  155102. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  155103. vf->datasource=NULL;
  155104. ov_clear(vf);
  155105. }else
  155106. vf->ready_state=PARTOPEN;
  155107. return(ret);
  155108. }
  155109. static int _ov_open2(OggVorbis_File *vf){
  155110. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  155111. vf->ready_state=OPENED;
  155112. if(vf->seekable){
  155113. int ret=_open_seekable2(vf);
  155114. if(ret){
  155115. vf->datasource=NULL;
  155116. ov_clear(vf);
  155117. }
  155118. return(ret);
  155119. }else
  155120. vf->ready_state=STREAMSET;
  155121. return 0;
  155122. }
  155123. /* clear out the OggVorbis_File struct */
  155124. int ov_clear(OggVorbis_File *vf){
  155125. if(vf){
  155126. vorbis_block_clear(&vf->vb);
  155127. vorbis_dsp_clear(&vf->vd);
  155128. ogg_stream_clear(&vf->os);
  155129. if(vf->vi && vf->links){
  155130. int i;
  155131. for(i=0;i<vf->links;i++){
  155132. vorbis_info_clear(vf->vi+i);
  155133. vorbis_comment_clear(vf->vc+i);
  155134. }
  155135. _ogg_free(vf->vi);
  155136. _ogg_free(vf->vc);
  155137. }
  155138. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  155139. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  155140. if(vf->serialnos)_ogg_free(vf->serialnos);
  155141. if(vf->offsets)_ogg_free(vf->offsets);
  155142. ogg_sync_clear(&vf->oy);
  155143. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  155144. memset(vf,0,sizeof(*vf));
  155145. }
  155146. #ifdef DEBUG_LEAKS
  155147. _VDBG_dump();
  155148. #endif
  155149. return(0);
  155150. }
  155151. /* inspects the OggVorbis file and finds/documents all the logical
  155152. bitstreams contained in it. Tries to be tolerant of logical
  155153. bitstream sections that are truncated/woogie.
  155154. return: -1) error
  155155. 0) OK
  155156. */
  155157. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  155158. ov_callbacks callbacks){
  155159. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  155160. if(ret)return ret;
  155161. return _ov_open2(vf);
  155162. }
  155163. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  155164. ov_callbacks callbacks = {
  155165. (size_t (*)(void *, size_t, size_t, void *)) fread,
  155166. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  155167. (int (*)(void *)) fclose,
  155168. (long (*)(void *)) ftell
  155169. };
  155170. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  155171. }
  155172. /* cheap hack for game usage where downsampling is desirable; there's
  155173. no need for SRC as we can just do it cheaply in libvorbis. */
  155174. int ov_halfrate(OggVorbis_File *vf,int flag){
  155175. int i;
  155176. if(vf->vi==NULL)return OV_EINVAL;
  155177. if(!vf->seekable)return OV_EINVAL;
  155178. if(vf->ready_state>=STREAMSET)
  155179. _decode_clear(vf); /* clear out stream state; later on libvorbis
  155180. will be able to swap this on the fly, but
  155181. for now dumping the decode machine is needed
  155182. to reinit the MDCT lookups. 1.1 libvorbis
  155183. is planned to be able to switch on the fly */
  155184. for(i=0;i<vf->links;i++){
  155185. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  155186. ov_halfrate(vf,0);
  155187. return OV_EINVAL;
  155188. }
  155189. }
  155190. return 0;
  155191. }
  155192. int ov_halfrate_p(OggVorbis_File *vf){
  155193. if(vf->vi==NULL)return OV_EINVAL;
  155194. return vorbis_synthesis_halfrate_p(vf->vi);
  155195. }
  155196. /* Only partially open the vorbis file; test for Vorbisness, and load
  155197. the headers for the first chain. Do not seek (although test for
  155198. seekability). Use ov_test_open to finish opening the file, else
  155199. ov_clear to close/free it. Same return codes as open. */
  155200. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  155201. ov_callbacks callbacks)
  155202. {
  155203. return _ov_open1(f,vf,initial,ibytes,callbacks);
  155204. }
  155205. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  155206. ov_callbacks callbacks = {
  155207. (size_t (*)(void *, size_t, size_t, void *)) fread,
  155208. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  155209. (int (*)(void *)) fclose,
  155210. (long (*)(void *)) ftell
  155211. };
  155212. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  155213. }
  155214. int ov_test_open(OggVorbis_File *vf){
  155215. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  155216. return _ov_open2(vf);
  155217. }
  155218. /* How many logical bitstreams in this physical bitstream? */
  155219. long ov_streams(OggVorbis_File *vf){
  155220. return vf->links;
  155221. }
  155222. /* Is the FILE * associated with vf seekable? */
  155223. long ov_seekable(OggVorbis_File *vf){
  155224. return vf->seekable;
  155225. }
  155226. /* returns the bitrate for a given logical bitstream or the entire
  155227. physical bitstream. If the file is open for random access, it will
  155228. find the *actual* average bitrate. If the file is streaming, it
  155229. returns the nominal bitrate (if set) else the average of the
  155230. upper/lower bounds (if set) else -1 (unset).
  155231. If you want the actual bitrate field settings, get them from the
  155232. vorbis_info structs */
  155233. long ov_bitrate(OggVorbis_File *vf,int i){
  155234. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155235. if(i>=vf->links)return(OV_EINVAL);
  155236. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  155237. if(i<0){
  155238. ogg_int64_t bits=0;
  155239. int i;
  155240. float br;
  155241. for(i=0;i<vf->links;i++)
  155242. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  155243. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  155244. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  155245. * so this is slightly transformed to make it work.
  155246. */
  155247. br = bits/ov_time_total(vf,-1);
  155248. return(rint(br));
  155249. }else{
  155250. if(vf->seekable){
  155251. /* return the actual bitrate */
  155252. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  155253. }else{
  155254. /* return nominal if set */
  155255. if(vf->vi[i].bitrate_nominal>0){
  155256. return vf->vi[i].bitrate_nominal;
  155257. }else{
  155258. if(vf->vi[i].bitrate_upper>0){
  155259. if(vf->vi[i].bitrate_lower>0){
  155260. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  155261. }else{
  155262. return vf->vi[i].bitrate_upper;
  155263. }
  155264. }
  155265. return(OV_FALSE);
  155266. }
  155267. }
  155268. }
  155269. }
  155270. /* returns the actual bitrate since last call. returns -1 if no
  155271. additional data to offer since last call (or at beginning of stream),
  155272. EINVAL if stream is only partially open
  155273. */
  155274. long ov_bitrate_instant(OggVorbis_File *vf){
  155275. int link=(vf->seekable?vf->current_link:0);
  155276. long ret;
  155277. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155278. if(vf->samptrack==0)return(OV_FALSE);
  155279. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  155280. vf->bittrack=0.f;
  155281. vf->samptrack=0.f;
  155282. return(ret);
  155283. }
  155284. /* Guess */
  155285. long ov_serialnumber(OggVorbis_File *vf,int i){
  155286. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  155287. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  155288. if(i<0){
  155289. return(vf->current_serialno);
  155290. }else{
  155291. return(vf->serialnos[i]);
  155292. }
  155293. }
  155294. /* returns: total raw (compressed) length of content if i==-1
  155295. raw (compressed) length of that logical bitstream for i==0 to n
  155296. OV_EINVAL if the stream is not seekable (we can't know the length)
  155297. or if stream is only partially open
  155298. */
  155299. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  155300. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155301. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  155302. if(i<0){
  155303. ogg_int64_t acc=0;
  155304. int i;
  155305. for(i=0;i<vf->links;i++)
  155306. acc+=ov_raw_total(vf,i);
  155307. return(acc);
  155308. }else{
  155309. return(vf->offsets[i+1]-vf->offsets[i]);
  155310. }
  155311. }
  155312. /* returns: total PCM length (samples) of content if i==-1 PCM length
  155313. (samples) of that logical bitstream for i==0 to n
  155314. OV_EINVAL if the stream is not seekable (we can't know the
  155315. length) or only partially open
  155316. */
  155317. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  155318. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155319. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  155320. if(i<0){
  155321. ogg_int64_t acc=0;
  155322. int i;
  155323. for(i=0;i<vf->links;i++)
  155324. acc+=ov_pcm_total(vf,i);
  155325. return(acc);
  155326. }else{
  155327. return(vf->pcmlengths[i*2+1]);
  155328. }
  155329. }
  155330. /* returns: total seconds of content if i==-1
  155331. seconds in that logical bitstream for i==0 to n
  155332. OV_EINVAL if the stream is not seekable (we can't know the
  155333. length) or only partially open
  155334. */
  155335. double ov_time_total(OggVorbis_File *vf,int i){
  155336. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155337. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  155338. if(i<0){
  155339. double acc=0;
  155340. int i;
  155341. for(i=0;i<vf->links;i++)
  155342. acc+=ov_time_total(vf,i);
  155343. return(acc);
  155344. }else{
  155345. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  155346. }
  155347. }
  155348. /* seek to an offset relative to the *compressed* data. This also
  155349. scans packets to update the PCM cursor. It will cross a logical
  155350. bitstream boundary, but only if it can't get any packets out of the
  155351. tail of the bitstream we seek to (so no surprises).
  155352. returns zero on success, nonzero on failure */
  155353. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  155354. ogg_stream_state work_os;
  155355. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155356. if(!vf->seekable)
  155357. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  155358. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  155359. /* don't yet clear out decoding machine (if it's initialized), in
  155360. the case we're in the same link. Restart the decode lapping, and
  155361. let _fetch_and_process_packet deal with a potential bitstream
  155362. boundary */
  155363. vf->pcm_offset=-1;
  155364. ogg_stream_reset_serialno(&vf->os,
  155365. vf->current_serialno); /* must set serialno */
  155366. vorbis_synthesis_restart(&vf->vd);
  155367. _seek_helper(vf,pos);
  155368. /* we need to make sure the pcm_offset is set, but we don't want to
  155369. advance the raw cursor past good packets just to get to the first
  155370. with a granulepos. That's not equivalent behavior to beginning
  155371. decoding as immediately after the seek position as possible.
  155372. So, a hack. We use two stream states; a local scratch state and
  155373. the shared vf->os stream state. We use the local state to
  155374. scan, and the shared state as a buffer for later decode.
  155375. Unfortuantely, on the last page we still advance to last packet
  155376. because the granulepos on the last page is not necessarily on a
  155377. packet boundary, and we need to make sure the granpos is
  155378. correct.
  155379. */
  155380. {
  155381. ogg_page og;
  155382. ogg_packet op;
  155383. int lastblock=0;
  155384. int accblock=0;
  155385. int thisblock;
  155386. int eosflag;
  155387. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  155388. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  155389. return from not necessarily
  155390. starting from the beginning */
  155391. while(1){
  155392. if(vf->ready_state>=STREAMSET){
  155393. /* snarf/scan a packet if we can */
  155394. int result=ogg_stream_packetout(&work_os,&op);
  155395. if(result>0){
  155396. if(vf->vi[vf->current_link].codec_setup){
  155397. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  155398. if(thisblock<0){
  155399. ogg_stream_packetout(&vf->os,NULL);
  155400. thisblock=0;
  155401. }else{
  155402. if(eosflag)
  155403. ogg_stream_packetout(&vf->os,NULL);
  155404. else
  155405. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  155406. }
  155407. if(op.granulepos!=-1){
  155408. int i,link=vf->current_link;
  155409. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  155410. if(granulepos<0)granulepos=0;
  155411. for(i=0;i<link;i++)
  155412. granulepos+=vf->pcmlengths[i*2+1];
  155413. vf->pcm_offset=granulepos-accblock;
  155414. break;
  155415. }
  155416. lastblock=thisblock;
  155417. continue;
  155418. }else
  155419. ogg_stream_packetout(&vf->os,NULL);
  155420. }
  155421. }
  155422. if(!lastblock){
  155423. if(_get_next_page(vf,&og,-1)<0){
  155424. vf->pcm_offset=ov_pcm_total(vf,-1);
  155425. break;
  155426. }
  155427. }else{
  155428. /* huh? Bogus stream with packets but no granulepos */
  155429. vf->pcm_offset=-1;
  155430. break;
  155431. }
  155432. /* has our decoding just traversed a bitstream boundary? */
  155433. if(vf->ready_state>=STREAMSET)
  155434. if(vf->current_serialno!=ogg_page_serialno(&og)){
  155435. _decode_clear(vf); /* clear out stream state */
  155436. ogg_stream_clear(&work_os);
  155437. }
  155438. if(vf->ready_state<STREAMSET){
  155439. int link;
  155440. vf->current_serialno=ogg_page_serialno(&og);
  155441. for(link=0;link<vf->links;link++)
  155442. if(vf->serialnos[link]==vf->current_serialno)break;
  155443. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  155444. error out, leave
  155445. machine uninitialized */
  155446. vf->current_link=link;
  155447. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  155448. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  155449. vf->ready_state=STREAMSET;
  155450. }
  155451. ogg_stream_pagein(&vf->os,&og);
  155452. ogg_stream_pagein(&work_os,&og);
  155453. eosflag=ogg_page_eos(&og);
  155454. }
  155455. }
  155456. ogg_stream_clear(&work_os);
  155457. vf->bittrack=0.f;
  155458. vf->samptrack=0.f;
  155459. return(0);
  155460. seek_error:
  155461. /* dump the machine so we're in a known state */
  155462. vf->pcm_offset=-1;
  155463. ogg_stream_clear(&work_os);
  155464. _decode_clear(vf);
  155465. return OV_EBADLINK;
  155466. }
  155467. /* Page granularity seek (faster than sample granularity because we
  155468. don't do the last bit of decode to find a specific sample).
  155469. Seek to the last [granule marked] page preceeding the specified pos
  155470. location, such that decoding past the returned point will quickly
  155471. arrive at the requested position. */
  155472. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  155473. int link=-1;
  155474. ogg_int64_t result=0;
  155475. ogg_int64_t total=ov_pcm_total(vf,-1);
  155476. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155477. if(!vf->seekable)return(OV_ENOSEEK);
  155478. if(pos<0 || pos>total)return(OV_EINVAL);
  155479. /* which bitstream section does this pcm offset occur in? */
  155480. for(link=vf->links-1;link>=0;link--){
  155481. total-=vf->pcmlengths[link*2+1];
  155482. if(pos>=total)break;
  155483. }
  155484. /* search within the logical bitstream for the page with the highest
  155485. pcm_pos preceeding (or equal to) pos. There is a danger here;
  155486. missing pages or incorrect frame number information in the
  155487. bitstream could make our task impossible. Account for that (it
  155488. would be an error condition) */
  155489. /* new search algorithm by HB (Nicholas Vinen) */
  155490. {
  155491. ogg_int64_t end=vf->offsets[link+1];
  155492. ogg_int64_t begin=vf->offsets[link];
  155493. ogg_int64_t begintime = vf->pcmlengths[link*2];
  155494. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  155495. ogg_int64_t target=pos-total+begintime;
  155496. ogg_int64_t best=begin;
  155497. ogg_page og;
  155498. while(begin<end){
  155499. ogg_int64_t bisect;
  155500. if(end-begin<CHUNKSIZE){
  155501. bisect=begin;
  155502. }else{
  155503. /* take a (pretty decent) guess. */
  155504. bisect=begin +
  155505. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  155506. if(bisect<=begin)
  155507. bisect=begin+1;
  155508. }
  155509. _seek_helper(vf,bisect);
  155510. while(begin<end){
  155511. result=_get_next_page(vf,&og,end-vf->offset);
  155512. if(result==OV_EREAD) goto seek_error;
  155513. if(result<0){
  155514. if(bisect<=begin+1)
  155515. end=begin; /* found it */
  155516. else{
  155517. if(bisect==0) goto seek_error;
  155518. bisect-=CHUNKSIZE;
  155519. if(bisect<=begin)bisect=begin+1;
  155520. _seek_helper(vf,bisect);
  155521. }
  155522. }else{
  155523. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  155524. if(granulepos==-1)continue;
  155525. if(granulepos<target){
  155526. best=result; /* raw offset of packet with granulepos */
  155527. begin=vf->offset; /* raw offset of next page */
  155528. begintime=granulepos;
  155529. if(target-begintime>44100)break;
  155530. bisect=begin; /* *not* begin + 1 */
  155531. }else{
  155532. if(bisect<=begin+1)
  155533. end=begin; /* found it */
  155534. else{
  155535. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  155536. end=result;
  155537. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  155538. if(bisect<=begin)bisect=begin+1;
  155539. _seek_helper(vf,bisect);
  155540. }else{
  155541. end=result;
  155542. endtime=granulepos;
  155543. break;
  155544. }
  155545. }
  155546. }
  155547. }
  155548. }
  155549. }
  155550. /* found our page. seek to it, update pcm offset. Easier case than
  155551. raw_seek, don't keep packets preceeding granulepos. */
  155552. {
  155553. ogg_page og;
  155554. ogg_packet op;
  155555. /* seek */
  155556. _seek_helper(vf,best);
  155557. vf->pcm_offset=-1;
  155558. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  155559. if(link!=vf->current_link){
  155560. /* Different link; dump entire decode machine */
  155561. _decode_clear(vf);
  155562. vf->current_link=link;
  155563. vf->current_serialno=ogg_page_serialno(&og);
  155564. vf->ready_state=STREAMSET;
  155565. }else{
  155566. vorbis_synthesis_restart(&vf->vd);
  155567. }
  155568. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  155569. ogg_stream_pagein(&vf->os,&og);
  155570. /* pull out all but last packet; the one with granulepos */
  155571. while(1){
  155572. result=ogg_stream_packetpeek(&vf->os,&op);
  155573. if(result==0){
  155574. /* !!! the packet finishing this page originated on a
  155575. preceeding page. Keep fetching previous pages until we
  155576. get one with a granulepos or without the 'continued' flag
  155577. set. Then just use raw_seek for simplicity. */
  155578. _seek_helper(vf,best);
  155579. while(1){
  155580. result=_get_prev_page(vf,&og);
  155581. if(result<0) goto seek_error;
  155582. if(ogg_page_granulepos(&og)>-1 ||
  155583. !ogg_page_continued(&og)){
  155584. return ov_raw_seek(vf,result);
  155585. }
  155586. vf->offset=result;
  155587. }
  155588. }
  155589. if(result<0){
  155590. result = OV_EBADPACKET;
  155591. goto seek_error;
  155592. }
  155593. if(op.granulepos!=-1){
  155594. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  155595. if(vf->pcm_offset<0)vf->pcm_offset=0;
  155596. vf->pcm_offset+=total;
  155597. break;
  155598. }else
  155599. result=ogg_stream_packetout(&vf->os,NULL);
  155600. }
  155601. }
  155602. }
  155603. /* verify result */
  155604. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  155605. result=OV_EFAULT;
  155606. goto seek_error;
  155607. }
  155608. vf->bittrack=0.f;
  155609. vf->samptrack=0.f;
  155610. return(0);
  155611. seek_error:
  155612. /* dump machine so we're in a known state */
  155613. vf->pcm_offset=-1;
  155614. _decode_clear(vf);
  155615. return (int)result;
  155616. }
  155617. /* seek to a sample offset relative to the decompressed pcm stream
  155618. returns zero on success, nonzero on failure */
  155619. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  155620. int thisblock,lastblock=0;
  155621. int ret=ov_pcm_seek_page(vf,pos);
  155622. if(ret<0)return(ret);
  155623. if((ret=_make_decode_ready(vf)))return ret;
  155624. /* discard leading packets we don't need for the lapping of the
  155625. position we want; don't decode them */
  155626. while(1){
  155627. ogg_packet op;
  155628. ogg_page og;
  155629. int ret=ogg_stream_packetpeek(&vf->os,&op);
  155630. if(ret>0){
  155631. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  155632. if(thisblock<0){
  155633. ogg_stream_packetout(&vf->os,NULL);
  155634. continue; /* non audio packet */
  155635. }
  155636. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  155637. if(vf->pcm_offset+((thisblock+
  155638. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  155639. /* remove the packet from packet queue and track its granulepos */
  155640. ogg_stream_packetout(&vf->os,NULL);
  155641. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  155642. only tracking, no
  155643. pcm_decode */
  155644. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  155645. /* end of logical stream case is hard, especially with exact
  155646. length positioning. */
  155647. if(op.granulepos>-1){
  155648. int i;
  155649. /* always believe the stream markers */
  155650. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  155651. if(vf->pcm_offset<0)vf->pcm_offset=0;
  155652. for(i=0;i<vf->current_link;i++)
  155653. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  155654. }
  155655. lastblock=thisblock;
  155656. }else{
  155657. if(ret<0 && ret!=OV_HOLE)break;
  155658. /* suck in a new page */
  155659. if(_get_next_page(vf,&og,-1)<0)break;
  155660. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  155661. if(vf->ready_state<STREAMSET){
  155662. int link;
  155663. vf->current_serialno=ogg_page_serialno(&og);
  155664. for(link=0;link<vf->links;link++)
  155665. if(vf->serialnos[link]==vf->current_serialno)break;
  155666. if(link==vf->links)return(OV_EBADLINK);
  155667. vf->current_link=link;
  155668. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  155669. vf->ready_state=STREAMSET;
  155670. ret=_make_decode_ready(vf);
  155671. if(ret)return ret;
  155672. lastblock=0;
  155673. }
  155674. ogg_stream_pagein(&vf->os,&og);
  155675. }
  155676. }
  155677. vf->bittrack=0.f;
  155678. vf->samptrack=0.f;
  155679. /* discard samples until we reach the desired position. Crossing a
  155680. logical bitstream boundary with abandon is OK. */
  155681. while(vf->pcm_offset<pos){
  155682. ogg_int64_t target=pos-vf->pcm_offset;
  155683. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155684. if(samples>target)samples=target;
  155685. vorbis_synthesis_read(&vf->vd,samples);
  155686. vf->pcm_offset+=samples;
  155687. if(samples<target)
  155688. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  155689. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  155690. }
  155691. return 0;
  155692. }
  155693. /* seek to a playback time relative to the decompressed pcm stream
  155694. returns zero on success, nonzero on failure */
  155695. int ov_time_seek(OggVorbis_File *vf,double seconds){
  155696. /* translate time to PCM position and call ov_pcm_seek */
  155697. int link=-1;
  155698. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  155699. double time_total=ov_time_total(vf,-1);
  155700. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155701. if(!vf->seekable)return(OV_ENOSEEK);
  155702. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  155703. /* which bitstream section does this time offset occur in? */
  155704. for(link=vf->links-1;link>=0;link--){
  155705. pcm_total-=vf->pcmlengths[link*2+1];
  155706. time_total-=ov_time_total(vf,link);
  155707. if(seconds>=time_total)break;
  155708. }
  155709. /* enough information to convert time offset to pcm offset */
  155710. {
  155711. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  155712. return(ov_pcm_seek(vf,target));
  155713. }
  155714. }
  155715. /* page-granularity version of ov_time_seek
  155716. returns zero on success, nonzero on failure */
  155717. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  155718. /* translate time to PCM position and call ov_pcm_seek */
  155719. int link=-1;
  155720. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  155721. double time_total=ov_time_total(vf,-1);
  155722. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155723. if(!vf->seekable)return(OV_ENOSEEK);
  155724. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  155725. /* which bitstream section does this time offset occur in? */
  155726. for(link=vf->links-1;link>=0;link--){
  155727. pcm_total-=vf->pcmlengths[link*2+1];
  155728. time_total-=ov_time_total(vf,link);
  155729. if(seconds>=time_total)break;
  155730. }
  155731. /* enough information to convert time offset to pcm offset */
  155732. {
  155733. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  155734. return(ov_pcm_seek_page(vf,target));
  155735. }
  155736. }
  155737. /* tell the current stream offset cursor. Note that seek followed by
  155738. tell will likely not give the set offset due to caching */
  155739. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  155740. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155741. return(vf->offset);
  155742. }
  155743. /* return PCM offset (sample) of next PCM sample to be read */
  155744. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  155745. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155746. return(vf->pcm_offset);
  155747. }
  155748. /* return time offset (seconds) of next PCM sample to be read */
  155749. double ov_time_tell(OggVorbis_File *vf){
  155750. int link=0;
  155751. ogg_int64_t pcm_total=0;
  155752. double time_total=0.f;
  155753. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155754. if(vf->seekable){
  155755. pcm_total=ov_pcm_total(vf,-1);
  155756. time_total=ov_time_total(vf,-1);
  155757. /* which bitstream section does this time offset occur in? */
  155758. for(link=vf->links-1;link>=0;link--){
  155759. pcm_total-=vf->pcmlengths[link*2+1];
  155760. time_total-=ov_time_total(vf,link);
  155761. if(vf->pcm_offset>=pcm_total)break;
  155762. }
  155763. }
  155764. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  155765. }
  155766. /* link: -1) return the vorbis_info struct for the bitstream section
  155767. currently being decoded
  155768. 0-n) to request information for a specific bitstream section
  155769. In the case of a non-seekable bitstream, any call returns the
  155770. current bitstream. NULL in the case that the machine is not
  155771. initialized */
  155772. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  155773. if(vf->seekable){
  155774. if(link<0)
  155775. if(vf->ready_state>=STREAMSET)
  155776. return vf->vi+vf->current_link;
  155777. else
  155778. return vf->vi;
  155779. else
  155780. if(link>=vf->links)
  155781. return NULL;
  155782. else
  155783. return vf->vi+link;
  155784. }else{
  155785. return vf->vi;
  155786. }
  155787. }
  155788. /* grr, strong typing, grr, no templates/inheritence, grr */
  155789. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  155790. if(vf->seekable){
  155791. if(link<0)
  155792. if(vf->ready_state>=STREAMSET)
  155793. return vf->vc+vf->current_link;
  155794. else
  155795. return vf->vc;
  155796. else
  155797. if(link>=vf->links)
  155798. return NULL;
  155799. else
  155800. return vf->vc+link;
  155801. }else{
  155802. return vf->vc;
  155803. }
  155804. }
  155805. static int host_is_big_endian() {
  155806. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  155807. unsigned char *bytewise = (unsigned char *)&pattern;
  155808. if (bytewise[0] == 0xfe) return 1;
  155809. return 0;
  155810. }
  155811. /* up to this point, everything could more or less hide the multiple
  155812. logical bitstream nature of chaining from the toplevel application
  155813. if the toplevel application didn't particularly care. However, at
  155814. the point that we actually read audio back, the multiple-section
  155815. nature must surface: Multiple bitstream sections do not necessarily
  155816. have to have the same number of channels or sampling rate.
  155817. ov_read returns the sequential logical bitstream number currently
  155818. being decoded along with the PCM data in order that the toplevel
  155819. application can take action on channel/sample rate changes. This
  155820. number will be incremented even for streamed (non-seekable) streams
  155821. (for seekable streams, it represents the actual logical bitstream
  155822. index within the physical bitstream. Note that the accessor
  155823. functions above are aware of this dichotomy).
  155824. input values: buffer) a buffer to hold packed PCM data for return
  155825. length) the byte length requested to be placed into buffer
  155826. bigendianp) should the data be packed LSB first (0) or
  155827. MSB first (1)
  155828. word) word size for output. currently 1 (byte) or
  155829. 2 (16 bit short)
  155830. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  155831. 0) EOF
  155832. n) number of bytes of PCM actually returned. The
  155833. below works on a packet-by-packet basis, so the
  155834. return length is not related to the 'length' passed
  155835. in, just guaranteed to fit.
  155836. *section) set to the logical bitstream number */
  155837. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  155838. int bigendianp,int word,int sgned,int *bitstream){
  155839. int i,j;
  155840. int host_endian = host_is_big_endian();
  155841. float **pcm;
  155842. long samples;
  155843. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155844. while(1){
  155845. if(vf->ready_state==INITSET){
  155846. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  155847. if(samples)break;
  155848. }
  155849. /* suck in another packet */
  155850. {
  155851. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  155852. if(ret==OV_EOF)
  155853. return(0);
  155854. if(ret<=0)
  155855. return(ret);
  155856. }
  155857. }
  155858. if(samples>0){
  155859. /* yay! proceed to pack data into the byte buffer */
  155860. long channels=ov_info(vf,-1)->channels;
  155861. long bytespersample=word * channels;
  155862. vorbis_fpu_control fpu;
  155863. (void) fpu; // (to avoid a warning about it being unused)
  155864. if(samples>length/bytespersample)samples=length/bytespersample;
  155865. if(samples <= 0)
  155866. return OV_EINVAL;
  155867. /* a tight loop to pack each size */
  155868. {
  155869. int val;
  155870. if(word==1){
  155871. int off=(sgned?0:128);
  155872. vorbis_fpu_setround(&fpu);
  155873. for(j=0;j<samples;j++)
  155874. for(i=0;i<channels;i++){
  155875. val=vorbis_ftoi(pcm[i][j]*128.f);
  155876. if(val>127)val=127;
  155877. else if(val<-128)val=-128;
  155878. *buffer++=val+off;
  155879. }
  155880. vorbis_fpu_restore(fpu);
  155881. }else{
  155882. int off=(sgned?0:32768);
  155883. if(host_endian==bigendianp){
  155884. if(sgned){
  155885. vorbis_fpu_setround(&fpu);
  155886. for(i=0;i<channels;i++) { /* It's faster in this order */
  155887. float *src=pcm[i];
  155888. short *dest=((short *)buffer)+i;
  155889. for(j=0;j<samples;j++) {
  155890. val=vorbis_ftoi(src[j]*32768.f);
  155891. if(val>32767)val=32767;
  155892. else if(val<-32768)val=-32768;
  155893. *dest=val;
  155894. dest+=channels;
  155895. }
  155896. }
  155897. vorbis_fpu_restore(fpu);
  155898. }else{
  155899. vorbis_fpu_setround(&fpu);
  155900. for(i=0;i<channels;i++) {
  155901. float *src=pcm[i];
  155902. short *dest=((short *)buffer)+i;
  155903. for(j=0;j<samples;j++) {
  155904. val=vorbis_ftoi(src[j]*32768.f);
  155905. if(val>32767)val=32767;
  155906. else if(val<-32768)val=-32768;
  155907. *dest=val+off;
  155908. dest+=channels;
  155909. }
  155910. }
  155911. vorbis_fpu_restore(fpu);
  155912. }
  155913. }else if(bigendianp){
  155914. vorbis_fpu_setround(&fpu);
  155915. for(j=0;j<samples;j++)
  155916. for(i=0;i<channels;i++){
  155917. val=vorbis_ftoi(pcm[i][j]*32768.f);
  155918. if(val>32767)val=32767;
  155919. else if(val<-32768)val=-32768;
  155920. val+=off;
  155921. *buffer++=(val>>8);
  155922. *buffer++=(val&0xff);
  155923. }
  155924. vorbis_fpu_restore(fpu);
  155925. }else{
  155926. int val;
  155927. vorbis_fpu_setround(&fpu);
  155928. for(j=0;j<samples;j++)
  155929. for(i=0;i<channels;i++){
  155930. val=vorbis_ftoi(pcm[i][j]*32768.f);
  155931. if(val>32767)val=32767;
  155932. else if(val<-32768)val=-32768;
  155933. val+=off;
  155934. *buffer++=(val&0xff);
  155935. *buffer++=(val>>8);
  155936. }
  155937. vorbis_fpu_restore(fpu);
  155938. }
  155939. }
  155940. }
  155941. vorbis_synthesis_read(&vf->vd,samples);
  155942. vf->pcm_offset+=samples;
  155943. if(bitstream)*bitstream=vf->current_link;
  155944. return(samples*bytespersample);
  155945. }else{
  155946. return(samples);
  155947. }
  155948. }
  155949. /* input values: pcm_channels) a float vector per channel of output
  155950. length) the sample length being read by the app
  155951. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  155952. 0) EOF
  155953. n) number of samples of PCM actually returned. The
  155954. below works on a packet-by-packet basis, so the
  155955. return length is not related to the 'length' passed
  155956. in, just guaranteed to fit.
  155957. *section) set to the logical bitstream number */
  155958. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  155959. int *bitstream){
  155960. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155961. while(1){
  155962. if(vf->ready_state==INITSET){
  155963. float **pcm;
  155964. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  155965. if(samples){
  155966. if(pcm_channels)*pcm_channels=pcm;
  155967. if(samples>length)samples=length;
  155968. vorbis_synthesis_read(&vf->vd,samples);
  155969. vf->pcm_offset+=samples;
  155970. if(bitstream)*bitstream=vf->current_link;
  155971. return samples;
  155972. }
  155973. }
  155974. /* suck in another packet */
  155975. {
  155976. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  155977. if(ret==OV_EOF)return(0);
  155978. if(ret<=0)return(ret);
  155979. }
  155980. }
  155981. }
  155982. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  155983. extern void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,
  155984. ogg_int64_t off);
  155985. static void _ov_splice(float **pcm,float **lappcm,
  155986. int n1, int n2,
  155987. int ch1, int ch2,
  155988. float *w1, float *w2){
  155989. int i,j;
  155990. float *w=w1;
  155991. int n=n1;
  155992. if(n1>n2){
  155993. n=n2;
  155994. w=w2;
  155995. }
  155996. /* splice */
  155997. for(j=0;j<ch1 && j<ch2;j++){
  155998. float *s=lappcm[j];
  155999. float *d=pcm[j];
  156000. for(i=0;i<n;i++){
  156001. float wd=w[i]*w[i];
  156002. float ws=1.-wd;
  156003. d[i]=d[i]*wd + s[i]*ws;
  156004. }
  156005. }
  156006. /* window from zero */
  156007. for(;j<ch2;j++){
  156008. float *d=pcm[j];
  156009. for(i=0;i<n;i++){
  156010. float wd=w[i]*w[i];
  156011. d[i]=d[i]*wd;
  156012. }
  156013. }
  156014. }
  156015. /* make sure vf is INITSET */
  156016. static int _ov_initset(OggVorbis_File *vf){
  156017. while(1){
  156018. if(vf->ready_state==INITSET)break;
  156019. /* suck in another packet */
  156020. {
  156021. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  156022. if(ret<0 && ret!=OV_HOLE)return(ret);
  156023. }
  156024. }
  156025. return 0;
  156026. }
  156027. /* make sure vf is INITSET and that we have a primed buffer; if
  156028. we're crosslapping at a stream section boundary, this also makes
  156029. sure we're sanity checking against the right stream information */
  156030. static int _ov_initprime(OggVorbis_File *vf){
  156031. vorbis_dsp_state *vd=&vf->vd;
  156032. while(1){
  156033. if(vf->ready_state==INITSET)
  156034. if(vorbis_synthesis_pcmout(vd,NULL))break;
  156035. /* suck in another packet */
  156036. {
  156037. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  156038. if(ret<0 && ret!=OV_HOLE)return(ret);
  156039. }
  156040. }
  156041. return 0;
  156042. }
  156043. /* grab enough data for lapping from vf; this may be in the form of
  156044. unreturned, already-decoded pcm, remaining PCM we will need to
  156045. decode, or synthetic postextrapolation from last packets. */
  156046. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  156047. float **lappcm,int lapsize){
  156048. int lapcount=0,i;
  156049. float **pcm;
  156050. /* try first to decode the lapping data */
  156051. while(lapcount<lapsize){
  156052. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  156053. if(samples){
  156054. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  156055. for(i=0;i<vi->channels;i++)
  156056. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  156057. lapcount+=samples;
  156058. vorbis_synthesis_read(vd,samples);
  156059. }else{
  156060. /* suck in another packet */
  156061. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  156062. if(ret==OV_EOF)break;
  156063. }
  156064. }
  156065. if(lapcount<lapsize){
  156066. /* failed to get lapping data from normal decode; pry it from the
  156067. postextrapolation buffering, or the second half of the MDCT
  156068. from the last packet */
  156069. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  156070. if(samples==0){
  156071. for(i=0;i<vi->channels;i++)
  156072. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  156073. lapcount=lapsize;
  156074. }else{
  156075. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  156076. for(i=0;i<vi->channels;i++)
  156077. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  156078. lapcount+=samples;
  156079. }
  156080. }
  156081. }
  156082. /* this sets up crosslapping of a sample by using trailing data from
  156083. sample 1 and lapping it into the windowing buffer of sample 2 */
  156084. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  156085. vorbis_info *vi1,*vi2;
  156086. float **lappcm;
  156087. float **pcm;
  156088. float *w1,*w2;
  156089. int n1,n2,i,ret,hs1,hs2;
  156090. if(vf1==vf2)return(0); /* degenerate case */
  156091. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  156092. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  156093. /* the relevant overlap buffers must be pre-checked and pre-primed
  156094. before looking at settings in the event that priming would cross
  156095. a bitstream boundary. So, do it now */
  156096. ret=_ov_initset(vf1);
  156097. if(ret)return(ret);
  156098. ret=_ov_initprime(vf2);
  156099. if(ret)return(ret);
  156100. vi1=ov_info(vf1,-1);
  156101. vi2=ov_info(vf2,-1);
  156102. hs1=ov_halfrate_p(vf1);
  156103. hs2=ov_halfrate_p(vf2);
  156104. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  156105. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  156106. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  156107. w1=vorbis_window(&vf1->vd,0);
  156108. w2=vorbis_window(&vf2->vd,0);
  156109. for(i=0;i<vi1->channels;i++)
  156110. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156111. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  156112. /* have a lapping buffer from vf1; now to splice it into the lapping
  156113. buffer of vf2 */
  156114. /* consolidate and expose the buffer. */
  156115. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  156116. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  156117. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  156118. /* splice */
  156119. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  156120. /* done */
  156121. return(0);
  156122. }
  156123. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  156124. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  156125. vorbis_info *vi;
  156126. float **lappcm;
  156127. float **pcm;
  156128. float *w1,*w2;
  156129. int n1,n2,ch1,ch2,hs;
  156130. int i,ret;
  156131. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156132. ret=_ov_initset(vf);
  156133. if(ret)return(ret);
  156134. vi=ov_info(vf,-1);
  156135. hs=ov_halfrate_p(vf);
  156136. ch1=vi->channels;
  156137. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  156138. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  156139. persistent; even if the decode state
  156140. from this link gets dumped, this
  156141. window array continues to exist */
  156142. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  156143. for(i=0;i<ch1;i++)
  156144. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156145. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  156146. /* have lapping data; seek and prime the buffer */
  156147. ret=localseek(vf,pos);
  156148. if(ret)return ret;
  156149. ret=_ov_initprime(vf);
  156150. if(ret)return(ret);
  156151. /* Guard against cross-link changes; they're perfectly legal */
  156152. vi=ov_info(vf,-1);
  156153. ch2=vi->channels;
  156154. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  156155. w2=vorbis_window(&vf->vd,0);
  156156. /* consolidate and expose the buffer. */
  156157. vorbis_synthesis_lapout(&vf->vd,&pcm);
  156158. /* splice */
  156159. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  156160. /* done */
  156161. return(0);
  156162. }
  156163. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156164. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  156165. }
  156166. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156167. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  156168. }
  156169. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156170. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  156171. }
  156172. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  156173. int (*localseek)(OggVorbis_File *,double)){
  156174. vorbis_info *vi;
  156175. float **lappcm;
  156176. float **pcm;
  156177. float *w1,*w2;
  156178. int n1,n2,ch1,ch2,hs;
  156179. int i,ret;
  156180. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156181. ret=_ov_initset(vf);
  156182. if(ret)return(ret);
  156183. vi=ov_info(vf,-1);
  156184. hs=ov_halfrate_p(vf);
  156185. ch1=vi->channels;
  156186. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  156187. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  156188. persistent; even if the decode state
  156189. from this link gets dumped, this
  156190. window array continues to exist */
  156191. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  156192. for(i=0;i<ch1;i++)
  156193. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156194. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  156195. /* have lapping data; seek and prime the buffer */
  156196. ret=localseek(vf,pos);
  156197. if(ret)return ret;
  156198. ret=_ov_initprime(vf);
  156199. if(ret)return(ret);
  156200. /* Guard against cross-link changes; they're perfectly legal */
  156201. vi=ov_info(vf,-1);
  156202. ch2=vi->channels;
  156203. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  156204. w2=vorbis_window(&vf->vd,0);
  156205. /* consolidate and expose the buffer. */
  156206. vorbis_synthesis_lapout(&vf->vd,&pcm);
  156207. /* splice */
  156208. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  156209. /* done */
  156210. return(0);
  156211. }
  156212. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  156213. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  156214. }
  156215. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  156216. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  156217. }
  156218. #endif
  156219. /*** End of inlined file: vorbisfile.c ***/
  156220. /*** Start of inlined file: window.c ***/
  156221. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  156222. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  156223. // tasks..
  156224. #if JUCE_MSVC
  156225. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  156226. #endif
  156227. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  156228. #if JUCE_USE_OGGVORBIS
  156229. #include <stdlib.h>
  156230. #include <math.h>
  156231. static float vwin64[32] = {
  156232. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  156233. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  156234. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  156235. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  156236. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  156237. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  156238. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  156239. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  156240. };
  156241. static float vwin128[64] = {
  156242. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  156243. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  156244. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  156245. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  156246. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  156247. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  156248. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  156249. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  156250. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  156251. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  156252. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  156253. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  156254. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  156255. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  156256. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  156257. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  156258. };
  156259. static float vwin256[128] = {
  156260. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  156261. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  156262. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  156263. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  156264. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  156265. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  156266. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  156267. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  156268. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  156269. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  156270. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  156271. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  156272. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  156273. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  156274. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  156275. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  156276. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  156277. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  156278. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  156279. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  156280. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  156281. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  156282. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  156283. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  156284. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  156285. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  156286. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  156287. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  156288. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  156289. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  156290. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  156291. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  156292. };
  156293. static float vwin512[256] = {
  156294. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  156295. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  156296. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  156297. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  156298. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  156299. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  156300. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  156301. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  156302. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  156303. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  156304. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  156305. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  156306. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  156307. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  156308. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  156309. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  156310. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  156311. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  156312. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  156313. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  156314. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  156315. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  156316. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  156317. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  156318. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  156319. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  156320. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  156321. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  156322. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  156323. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  156324. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  156325. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  156326. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  156327. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  156328. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  156329. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  156330. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  156331. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  156332. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  156333. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  156334. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  156335. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  156336. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  156337. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  156338. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  156339. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  156340. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  156341. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  156342. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  156343. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  156344. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  156345. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  156346. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  156347. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  156348. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  156349. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  156350. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  156351. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  156352. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  156353. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  156354. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  156355. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  156356. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  156357. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  156358. };
  156359. static float vwin1024[512] = {
  156360. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  156361. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  156362. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  156363. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  156364. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  156365. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  156366. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  156367. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  156368. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  156369. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  156370. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  156371. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  156372. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  156373. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  156374. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  156375. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  156376. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  156377. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  156378. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  156379. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  156380. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  156381. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  156382. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  156383. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  156384. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  156385. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  156386. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  156387. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  156388. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  156389. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  156390. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  156391. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  156392. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  156393. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  156394. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  156395. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  156396. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  156397. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  156398. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  156399. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  156400. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  156401. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  156402. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  156403. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  156404. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  156405. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  156406. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  156407. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  156408. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  156409. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  156410. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  156411. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  156412. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  156413. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  156414. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  156415. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  156416. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  156417. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  156418. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  156419. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  156420. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  156421. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  156422. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  156423. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  156424. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  156425. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  156426. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  156427. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  156428. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  156429. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  156430. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  156431. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  156432. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  156433. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  156434. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  156435. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  156436. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  156437. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  156438. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  156439. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  156440. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  156441. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  156442. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  156443. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  156444. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  156445. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  156446. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  156447. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  156448. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  156449. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  156450. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  156451. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  156452. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  156453. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  156454. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  156455. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  156456. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  156457. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  156458. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  156459. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  156460. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  156461. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  156462. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  156463. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  156464. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  156465. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  156466. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  156467. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  156468. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  156469. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  156470. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  156471. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  156472. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  156473. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  156474. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  156475. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  156476. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  156477. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  156478. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  156479. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  156480. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  156481. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  156482. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  156483. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  156484. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  156485. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  156486. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  156487. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  156488. };
  156489. static float vwin2048[1024] = {
  156490. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  156491. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  156492. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  156493. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  156494. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  156495. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  156496. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  156497. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  156498. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  156499. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  156500. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  156501. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  156502. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  156503. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  156504. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  156505. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  156506. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  156507. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  156508. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  156509. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  156510. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  156511. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  156512. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  156513. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  156514. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  156515. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  156516. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  156517. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  156518. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  156519. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  156520. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  156521. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  156522. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  156523. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  156524. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  156525. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  156526. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  156527. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  156528. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  156529. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  156530. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  156531. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  156532. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  156533. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  156534. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  156535. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  156536. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  156537. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  156538. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  156539. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  156540. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  156541. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  156542. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  156543. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  156544. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  156545. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  156546. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  156547. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  156548. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  156549. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  156550. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  156551. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  156552. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  156553. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  156554. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  156555. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  156556. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  156557. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  156558. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  156559. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  156560. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  156561. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  156562. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  156563. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  156564. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  156565. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  156566. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  156567. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  156568. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  156569. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  156570. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  156571. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  156572. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  156573. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  156574. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  156575. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  156576. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  156577. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  156578. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  156579. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  156580. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  156581. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  156582. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  156583. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  156584. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  156585. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  156586. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  156587. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  156588. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  156589. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  156590. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  156591. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  156592. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  156593. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  156594. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  156595. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  156596. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  156597. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  156598. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  156599. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  156600. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  156601. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  156602. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  156603. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  156604. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  156605. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  156606. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  156607. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  156608. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  156609. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  156610. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  156611. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  156612. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  156613. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  156614. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  156615. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  156616. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  156617. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  156618. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  156619. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  156620. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  156621. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  156622. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  156623. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  156624. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  156625. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  156626. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  156627. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  156628. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  156629. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  156630. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  156631. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  156632. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  156633. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  156634. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  156635. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  156636. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  156637. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  156638. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  156639. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  156640. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  156641. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  156642. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  156643. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  156644. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  156645. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  156646. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  156647. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  156648. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  156649. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  156650. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  156651. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  156652. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  156653. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  156654. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  156655. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  156656. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  156657. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  156658. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  156659. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  156660. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  156661. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  156662. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  156663. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  156664. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  156665. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  156666. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  156667. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  156668. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  156669. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  156670. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  156671. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  156672. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  156673. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  156674. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  156675. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  156676. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  156677. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  156678. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  156679. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  156680. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  156681. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  156682. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  156683. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  156684. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  156685. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  156686. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  156687. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  156688. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  156689. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  156690. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  156691. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  156692. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  156693. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  156694. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  156695. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  156696. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  156697. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  156698. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  156699. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  156700. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  156701. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  156702. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  156703. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  156704. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  156705. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  156706. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  156707. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  156708. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  156709. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  156710. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  156711. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  156712. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  156713. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  156714. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  156715. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  156716. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  156717. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  156718. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  156719. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  156720. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  156721. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  156722. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  156723. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  156724. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  156725. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  156726. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  156727. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  156728. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  156729. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  156730. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  156731. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  156732. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  156733. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  156734. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  156735. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  156736. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  156737. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  156738. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  156739. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  156740. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  156741. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  156742. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  156743. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  156744. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  156745. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  156746. };
  156747. static float vwin4096[2048] = {
  156748. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  156749. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  156750. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  156751. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  156752. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  156753. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  156754. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  156755. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  156756. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  156757. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  156758. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  156759. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  156760. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  156761. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  156762. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  156763. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  156764. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  156765. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  156766. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  156767. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  156768. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  156769. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  156770. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  156771. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  156772. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  156773. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  156774. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  156775. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  156776. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  156777. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  156778. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  156779. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  156780. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  156781. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  156782. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  156783. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  156784. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  156785. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  156786. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  156787. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  156788. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  156789. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  156790. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  156791. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  156792. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  156793. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  156794. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  156795. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  156796. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  156797. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  156798. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  156799. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  156800. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  156801. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  156802. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  156803. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  156804. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  156805. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  156806. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  156807. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  156808. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  156809. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  156810. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  156811. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  156812. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  156813. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  156814. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  156815. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  156816. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  156817. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  156818. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  156819. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  156820. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  156821. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  156822. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  156823. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  156824. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  156825. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  156826. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  156827. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  156828. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  156829. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  156830. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  156831. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  156832. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  156833. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  156834. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  156835. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  156836. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  156837. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  156838. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  156839. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  156840. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  156841. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  156842. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  156843. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  156844. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  156845. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  156846. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  156847. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  156848. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  156849. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  156850. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  156851. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  156852. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  156853. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  156854. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  156855. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  156856. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  156857. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  156858. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  156859. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  156860. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  156861. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  156862. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  156863. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  156864. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  156865. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  156866. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  156867. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  156868. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  156869. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  156870. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  156871. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  156872. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  156873. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  156874. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  156875. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  156876. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  156877. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  156878. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  156879. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  156880. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  156881. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  156882. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  156883. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  156884. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  156885. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  156886. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  156887. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  156888. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  156889. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  156890. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  156891. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  156892. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  156893. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  156894. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  156895. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  156896. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  156897. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  156898. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  156899. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  156900. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  156901. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  156902. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  156903. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  156904. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  156905. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  156906. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  156907. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  156908. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  156909. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  156910. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  156911. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  156912. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  156913. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  156914. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  156915. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  156916. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  156917. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  156918. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  156919. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  156920. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  156921. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  156922. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  156923. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  156924. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  156925. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  156926. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  156927. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  156928. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  156929. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  156930. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  156931. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  156932. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  156933. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  156934. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  156935. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  156936. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  156937. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  156938. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  156939. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  156940. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  156941. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  156942. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  156943. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  156944. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  156945. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  156946. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  156947. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  156948. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  156949. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  156950. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  156951. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  156952. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  156953. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  156954. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  156955. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  156956. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  156957. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  156958. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  156959. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  156960. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  156961. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  156962. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  156963. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  156964. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  156965. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  156966. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  156967. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  156968. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  156969. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  156970. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  156971. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  156972. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  156973. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  156974. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  156975. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  156976. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  156977. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  156978. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  156979. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  156980. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  156981. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  156982. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  156983. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  156984. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  156985. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  156986. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  156987. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  156988. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  156989. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  156990. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  156991. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  156992. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  156993. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  156994. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  156995. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  156996. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  156997. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  156998. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  156999. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  157000. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  157001. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  157002. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  157003. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  157004. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  157005. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  157006. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  157007. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  157008. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  157009. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  157010. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  157011. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  157012. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  157013. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  157014. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  157015. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  157016. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  157017. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  157018. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  157019. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  157020. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  157021. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  157022. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  157023. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  157024. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  157025. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  157026. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  157027. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  157028. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  157029. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  157030. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  157031. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  157032. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  157033. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  157034. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  157035. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  157036. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  157037. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  157038. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  157039. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  157040. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  157041. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  157042. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  157043. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  157044. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  157045. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  157046. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  157047. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  157048. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  157049. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  157050. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  157051. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  157052. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  157053. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  157054. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  157055. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  157056. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  157057. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  157058. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  157059. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  157060. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  157061. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  157062. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  157063. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  157064. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  157065. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  157066. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  157067. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  157068. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  157069. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  157070. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  157071. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  157072. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  157073. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  157074. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  157075. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  157076. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  157077. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  157078. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  157079. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  157080. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  157081. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  157082. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  157083. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  157084. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  157085. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  157086. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  157087. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  157088. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  157089. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  157090. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  157091. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  157092. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  157093. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  157094. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  157095. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  157096. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  157097. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  157098. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  157099. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  157100. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  157101. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  157102. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  157103. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  157104. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  157105. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  157106. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  157107. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  157108. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  157109. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  157110. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  157111. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  157112. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  157113. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  157114. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  157115. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  157116. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  157117. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  157118. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  157119. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  157120. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  157121. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  157122. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  157123. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  157124. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  157125. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  157126. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  157127. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  157128. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  157129. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  157130. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  157131. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  157132. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  157133. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  157134. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  157135. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  157136. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  157137. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  157138. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  157139. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  157140. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  157141. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  157142. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  157143. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  157144. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  157145. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  157146. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  157147. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  157148. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  157149. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  157150. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  157151. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  157152. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  157153. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  157154. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  157155. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  157156. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  157157. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  157158. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  157159. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  157160. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  157161. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  157162. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  157163. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  157164. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  157165. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  157166. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  157167. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  157168. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  157169. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  157170. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  157171. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  157172. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  157173. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  157174. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  157175. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  157176. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  157177. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  157178. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  157179. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  157180. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  157181. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  157182. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  157183. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  157184. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  157185. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  157186. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  157187. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  157188. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  157189. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  157190. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  157191. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  157192. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  157193. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  157194. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  157195. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  157196. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  157197. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  157198. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  157199. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  157200. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  157201. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  157202. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  157203. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  157204. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  157205. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  157206. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  157207. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  157208. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  157209. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  157210. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  157211. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  157212. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  157213. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  157214. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  157215. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  157216. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  157217. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  157218. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  157219. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  157220. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  157221. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  157222. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  157223. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  157224. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  157225. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  157226. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  157227. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  157228. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  157229. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  157230. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  157231. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  157232. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  157233. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  157234. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  157235. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  157236. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  157237. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  157238. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  157239. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  157240. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  157241. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  157242. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  157243. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  157244. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  157245. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  157246. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  157247. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  157248. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  157249. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  157250. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  157251. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  157252. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  157253. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  157254. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  157255. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  157256. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  157257. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  157258. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  157259. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  157260. };
  157261. static float vwin8192[4096] = {
  157262. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  157263. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  157264. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  157265. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  157266. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  157267. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  157268. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  157269. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  157270. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  157271. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  157272. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  157273. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  157274. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  157275. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  157276. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  157277. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  157278. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  157279. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  157280. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  157281. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  157282. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  157283. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  157284. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  157285. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  157286. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  157287. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  157288. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  157289. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  157290. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  157291. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  157292. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  157293. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  157294. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  157295. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  157296. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  157297. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  157298. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  157299. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  157300. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  157301. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  157302. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  157303. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  157304. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  157305. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  157306. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  157307. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  157308. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  157309. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  157310. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  157311. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  157312. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  157313. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  157314. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  157315. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  157316. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  157317. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  157318. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  157319. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  157320. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  157321. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  157322. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  157323. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  157324. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  157325. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  157326. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  157327. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  157328. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  157329. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  157330. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  157331. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  157332. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  157333. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  157334. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  157335. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  157336. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  157337. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  157338. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  157339. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  157340. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  157341. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  157342. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  157343. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  157344. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  157345. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  157346. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  157347. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  157348. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  157349. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  157350. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  157351. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  157352. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  157353. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  157354. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  157355. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  157356. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  157357. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  157358. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  157359. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  157360. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  157361. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  157362. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  157363. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  157364. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  157365. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  157366. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  157367. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  157368. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  157369. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  157370. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  157371. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  157372. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  157373. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  157374. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  157375. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  157376. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  157377. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  157378. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  157379. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  157380. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  157381. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  157382. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  157383. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  157384. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  157385. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  157386. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  157387. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  157388. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  157389. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  157390. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  157391. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  157392. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  157393. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  157394. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  157395. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  157396. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  157397. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  157398. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  157399. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  157400. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  157401. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  157402. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  157403. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  157404. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  157405. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  157406. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  157407. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  157408. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  157409. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  157410. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  157411. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  157412. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  157413. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  157414. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  157415. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  157416. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  157417. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  157418. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  157419. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  157420. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  157421. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  157422. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  157423. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  157424. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  157425. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  157426. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  157427. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  157428. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  157429. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  157430. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  157431. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  157432. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  157433. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  157434. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  157435. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  157436. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  157437. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  157438. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  157439. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  157440. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  157441. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  157442. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  157443. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  157444. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  157445. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  157446. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  157447. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  157448. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  157449. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  157450. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  157451. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  157452. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  157453. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  157454. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  157455. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  157456. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  157457. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  157458. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  157459. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  157460. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  157461. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  157462. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  157463. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  157464. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  157465. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  157466. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  157467. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  157468. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  157469. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  157470. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  157471. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  157472. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  157473. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  157474. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  157475. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  157476. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  157477. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  157478. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  157479. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  157480. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  157481. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  157482. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  157483. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  157484. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  157485. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  157486. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  157487. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  157488. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  157489. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  157490. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  157491. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  157492. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  157493. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  157494. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  157495. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  157496. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  157497. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  157498. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  157499. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  157500. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  157501. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  157502. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  157503. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  157504. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  157505. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  157506. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  157507. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  157508. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  157509. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  157510. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  157511. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  157512. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  157513. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  157514. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  157515. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  157516. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  157517. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  157518. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  157519. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  157520. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  157521. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  157522. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  157523. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  157524. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  157525. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  157526. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  157527. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  157528. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  157529. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  157530. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  157531. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  157532. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  157533. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  157534. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  157535. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  157536. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  157537. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  157538. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  157539. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  157540. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  157541. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  157542. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  157543. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  157544. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  157545. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  157546. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  157547. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  157548. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  157549. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  157550. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  157551. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  157552. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  157553. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  157554. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  157555. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  157556. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  157557. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  157558. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  157559. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  157560. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  157561. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  157562. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  157563. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  157564. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  157565. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  157566. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  157567. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  157568. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  157569. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  157570. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  157571. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  157572. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  157573. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  157574. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  157575. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  157576. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  157577. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  157578. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  157579. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  157580. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  157581. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  157582. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  157583. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  157584. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  157585. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  157586. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  157587. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  157588. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  157589. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  157590. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  157591. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  157592. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  157593. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  157594. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  157595. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  157596. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  157597. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  157598. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  157599. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  157600. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  157601. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  157602. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  157603. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  157604. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  157605. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  157606. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  157607. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  157608. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  157609. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  157610. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  157611. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  157612. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  157613. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  157614. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  157615. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  157616. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  157617. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  157618. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  157619. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  157620. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  157621. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  157622. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  157623. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  157624. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  157625. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  157626. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  157627. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  157628. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  157629. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  157630. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  157631. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  157632. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  157633. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  157634. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  157635. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  157636. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  157637. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  157638. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  157639. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  157640. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  157641. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  157642. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  157643. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  157644. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  157645. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  157646. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  157647. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  157648. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  157649. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  157650. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  157651. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  157652. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  157653. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  157654. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  157655. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  157656. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  157657. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  157658. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  157659. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  157660. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  157661. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  157662. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  157663. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  157664. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  157665. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  157666. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  157667. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  157668. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  157669. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  157670. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  157671. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  157672. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  157673. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  157674. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  157675. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  157676. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  157677. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  157678. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  157679. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  157680. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  157681. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  157682. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  157683. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  157684. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  157685. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  157686. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  157687. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  157688. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  157689. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  157690. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  157691. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  157692. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  157693. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  157694. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  157695. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  157696. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  157697. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  157698. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  157699. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  157700. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  157701. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  157702. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  157703. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  157704. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  157705. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  157706. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  157707. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  157708. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  157709. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  157710. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  157711. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  157712. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  157713. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  157714. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  157715. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  157716. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  157717. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  157718. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  157719. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  157720. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  157721. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  157722. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  157723. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  157724. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  157725. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  157726. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  157727. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  157728. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  157729. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  157730. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  157731. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  157732. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  157733. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  157734. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  157735. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  157736. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  157737. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  157738. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  157739. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  157740. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  157741. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  157742. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  157743. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  157744. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  157745. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  157746. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  157747. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  157748. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  157749. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  157750. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  157751. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  157752. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  157753. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  157754. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  157755. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  157756. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  157757. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  157758. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  157759. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  157760. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  157761. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  157762. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  157763. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  157764. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  157765. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  157766. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  157767. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  157768. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  157769. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  157770. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  157771. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  157772. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  157773. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  157774. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  157775. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  157776. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  157777. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  157778. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  157779. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  157780. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  157781. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  157782. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  157783. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  157784. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  157785. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  157786. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  157787. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  157788. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  157789. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  157790. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  157791. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  157792. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  157793. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  157794. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  157795. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  157796. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  157797. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  157798. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  157799. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  157800. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  157801. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  157802. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  157803. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  157804. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  157805. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  157806. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  157807. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  157808. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  157809. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  157810. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  157811. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  157812. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  157813. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  157814. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  157815. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  157816. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  157817. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  157818. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  157819. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  157820. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  157821. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  157822. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  157823. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  157824. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  157825. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  157826. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  157827. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  157828. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  157829. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  157830. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  157831. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  157832. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  157833. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  157834. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  157835. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  157836. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  157837. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  157838. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  157839. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  157840. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  157841. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  157842. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  157843. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  157844. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  157845. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  157846. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  157847. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  157848. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  157849. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  157850. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  157851. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  157852. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  157853. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  157854. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  157855. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  157856. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  157857. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  157858. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  157859. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  157860. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  157861. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  157862. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  157863. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  157864. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  157865. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  157866. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  157867. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  157868. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  157869. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  157870. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  157871. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  157872. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  157873. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  157874. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  157875. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  157876. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  157877. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  157878. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  157879. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  157880. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  157881. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  157882. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  157883. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  157884. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  157885. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  157886. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  157887. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  157888. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  157889. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  157890. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  157891. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  157892. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  157893. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  157894. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  157895. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  157896. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  157897. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  157898. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  157899. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  157900. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  157901. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  157902. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  157903. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  157904. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  157905. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  157906. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  157907. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  157908. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  157909. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  157910. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  157911. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  157912. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  157913. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  157914. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  157915. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  157916. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  157917. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  157918. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  157919. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  157920. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  157921. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  157922. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  157923. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  157924. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  157925. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  157926. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  157927. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  157928. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  157929. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  157930. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  157931. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  157932. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  157933. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  157934. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  157935. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  157936. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  157937. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  157938. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  157939. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  157940. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  157941. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  157942. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  157943. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  157944. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  157945. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  157946. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  157947. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  157948. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  157949. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  157950. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  157951. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  157952. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  157953. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  157954. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  157955. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  157956. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  157957. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  157958. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  157959. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  157960. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  157961. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  157962. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  157963. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  157964. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  157965. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  157966. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  157967. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  157968. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  157969. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  157970. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  157971. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  157972. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  157973. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  157974. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  157975. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  157976. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  157977. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  157978. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  157979. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  157980. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  157981. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  157982. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  157983. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  157984. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  157985. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  157986. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  157987. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  157988. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  157989. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  157990. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  157991. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  157992. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  157993. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  157994. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  157995. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  157996. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  157997. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  157998. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  157999. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  158000. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  158001. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  158002. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  158003. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  158004. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  158005. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  158006. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  158007. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  158008. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  158009. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  158010. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  158011. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  158012. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  158013. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  158014. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  158015. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  158016. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  158017. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  158018. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  158019. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  158020. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  158021. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  158022. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  158023. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  158024. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  158025. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  158026. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  158027. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  158028. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  158029. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  158030. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  158031. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  158032. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  158033. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  158034. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  158035. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  158036. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  158037. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  158038. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  158039. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  158040. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  158041. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  158042. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  158043. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  158044. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  158045. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  158046. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  158047. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  158048. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  158049. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  158050. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  158051. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  158052. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  158053. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  158054. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  158055. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  158056. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  158057. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  158058. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  158059. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  158060. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  158061. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  158062. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  158063. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  158064. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  158065. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  158066. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  158067. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  158068. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  158069. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  158070. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  158071. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  158072. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  158073. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  158074. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  158075. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  158076. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  158077. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  158078. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  158079. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  158080. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  158081. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  158082. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  158083. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  158084. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  158085. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  158086. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  158087. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  158088. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  158089. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  158090. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  158091. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  158092. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  158093. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  158094. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  158095. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  158096. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  158097. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  158098. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  158099. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  158100. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  158101. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  158102. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  158103. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  158104. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  158105. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  158106. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  158107. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  158108. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  158109. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  158110. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  158111. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  158112. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  158113. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  158114. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  158115. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  158116. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  158117. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  158118. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  158119. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  158120. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  158121. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  158122. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  158123. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  158124. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  158125. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  158126. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  158127. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  158128. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  158129. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  158130. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  158131. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  158132. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  158133. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  158134. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  158135. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  158136. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  158137. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  158138. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  158139. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  158140. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  158141. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  158142. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  158143. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  158144. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  158145. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  158146. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  158147. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  158148. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  158149. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  158150. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  158151. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  158152. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  158153. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  158154. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  158155. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  158156. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  158157. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  158158. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  158159. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  158160. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  158161. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  158162. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  158163. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  158164. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  158165. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  158166. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  158167. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  158168. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  158169. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  158170. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  158171. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  158172. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  158173. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  158174. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  158175. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  158176. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  158177. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  158178. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  158179. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  158180. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  158181. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  158182. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  158183. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  158184. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  158185. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  158186. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  158187. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  158188. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  158189. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  158190. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  158191. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  158192. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  158193. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  158194. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  158195. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  158196. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  158197. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  158198. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  158199. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  158200. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  158201. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  158202. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  158203. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  158204. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  158205. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  158206. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  158207. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  158208. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  158209. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  158210. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  158211. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  158212. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  158213. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  158214. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  158215. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  158216. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  158217. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  158218. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  158219. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  158220. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  158221. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  158222. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  158223. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  158224. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  158225. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  158226. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  158227. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  158228. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  158229. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  158230. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  158231. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  158232. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  158233. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  158234. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  158235. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  158236. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  158237. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  158238. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  158239. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  158240. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  158241. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  158242. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  158243. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  158244. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  158245. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  158246. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  158247. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  158248. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  158249. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  158250. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  158251. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  158252. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  158253. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  158254. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  158255. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  158256. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  158257. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  158258. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  158259. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  158260. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  158261. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  158262. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  158263. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  158264. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  158265. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  158266. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  158267. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  158268. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  158269. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  158270. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  158271. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  158272. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  158273. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  158274. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  158275. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  158276. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  158277. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  158278. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  158279. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  158280. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  158281. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  158282. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  158283. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  158284. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  158285. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  158286. };
  158287. static float *vwin[8] = {
  158288. vwin64,
  158289. vwin128,
  158290. vwin256,
  158291. vwin512,
  158292. vwin1024,
  158293. vwin2048,
  158294. vwin4096,
  158295. vwin8192,
  158296. };
  158297. float *_vorbis_window_get(int n){
  158298. return vwin[n];
  158299. }
  158300. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  158301. int lW,int W,int nW){
  158302. lW=(W?lW:0);
  158303. nW=(W?nW:0);
  158304. {
  158305. float *windowLW=vwin[winno[lW]];
  158306. float *windowNW=vwin[winno[nW]];
  158307. long n=blocksizes[W];
  158308. long ln=blocksizes[lW];
  158309. long rn=blocksizes[nW];
  158310. long leftbegin=n/4-ln/4;
  158311. long leftend=leftbegin+ln/2;
  158312. long rightbegin=n/2+n/4-rn/4;
  158313. long rightend=rightbegin+rn/2;
  158314. int i,p;
  158315. for(i=0;i<leftbegin;i++)
  158316. d[i]=0.f;
  158317. for(p=0;i<leftend;i++,p++)
  158318. d[i]*=windowLW[p];
  158319. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  158320. d[i]*=windowNW[p];
  158321. for(;i<n;i++)
  158322. d[i]=0.f;
  158323. }
  158324. }
  158325. #endif
  158326. /*** End of inlined file: window.c ***/
  158327. #else
  158328. #include <vorbis/vorbisenc.h>
  158329. #include <vorbis/codec.h>
  158330. #include <vorbis/vorbisfile.h>
  158331. #endif
  158332. }
  158333. #undef max
  158334. #undef min
  158335. BEGIN_JUCE_NAMESPACE
  158336. static const char* const oggFormatName = "Ogg-Vorbis file";
  158337. static const char* const oggExtensions[] = { ".ogg", 0 };
  158338. class OggReader : public AudioFormatReader
  158339. {
  158340. OggVorbisNamespace::OggVorbis_File ovFile;
  158341. OggVorbisNamespace::ov_callbacks callbacks;
  158342. AudioSampleBuffer reservoir;
  158343. int reservoirStart, samplesInReservoir;
  158344. public:
  158345. OggReader (InputStream* const inp)
  158346. : AudioFormatReader (inp, TRANS (oggFormatName)),
  158347. reservoir (2, 4096),
  158348. reservoirStart (0),
  158349. samplesInReservoir (0)
  158350. {
  158351. using namespace OggVorbisNamespace;
  158352. sampleRate = 0;
  158353. usesFloatingPointData = true;
  158354. callbacks.read_func = &oggReadCallback;
  158355. callbacks.seek_func = &oggSeekCallback;
  158356. callbacks.close_func = &oggCloseCallback;
  158357. callbacks.tell_func = &oggTellCallback;
  158358. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  158359. if (err == 0)
  158360. {
  158361. vorbis_info* info = ov_info (&ovFile, -1);
  158362. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  158363. numChannels = info->channels;
  158364. bitsPerSample = 16;
  158365. sampleRate = info->rate;
  158366. reservoir.setSize (numChannels,
  158367. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  158368. }
  158369. }
  158370. ~OggReader()
  158371. {
  158372. OggVorbisNamespace::ov_clear (&ovFile);
  158373. }
  158374. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  158375. int64 startSampleInFile, int numSamples)
  158376. {
  158377. while (numSamples > 0)
  158378. {
  158379. const int numAvailable = reservoirStart + samplesInReservoir - startSampleInFile;
  158380. if (startSampleInFile >= reservoirStart && numAvailable > 0)
  158381. {
  158382. // got a few samples overlapping, so use them before seeking..
  158383. const int numToUse = jmin (numSamples, numAvailable);
  158384. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  158385. if (destSamples[i] != 0)
  158386. memcpy (destSamples[i] + startOffsetInDestBuffer,
  158387. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  158388. sizeof (float) * numToUse);
  158389. startSampleInFile += numToUse;
  158390. numSamples -= numToUse;
  158391. startOffsetInDestBuffer += numToUse;
  158392. if (numSamples == 0)
  158393. break;
  158394. }
  158395. if (startSampleInFile < reservoirStart
  158396. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  158397. {
  158398. // buffer miss, so refill the reservoir
  158399. int bitStream = 0;
  158400. reservoirStart = jmax (0, (int) startSampleInFile);
  158401. samplesInReservoir = reservoir.getNumSamples();
  158402. if (reservoirStart != (int) OggVorbisNamespace::ov_pcm_tell (&ovFile))
  158403. OggVorbisNamespace::ov_pcm_seek (&ovFile, reservoirStart);
  158404. int offset = 0;
  158405. int numToRead = samplesInReservoir;
  158406. while (numToRead > 0)
  158407. {
  158408. float** dataIn = 0;
  158409. const int samps = OggVorbisNamespace::ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  158410. if (samps <= 0)
  158411. break;
  158412. jassert (samps <= numToRead);
  158413. for (int i = jmin ((int) numChannels, reservoir.getNumChannels()); --i >= 0;)
  158414. {
  158415. memcpy (reservoir.getSampleData (i, offset),
  158416. dataIn[i],
  158417. sizeof (float) * samps);
  158418. }
  158419. numToRead -= samps;
  158420. offset += samps;
  158421. }
  158422. if (numToRead > 0)
  158423. reservoir.clear (offset, numToRead);
  158424. }
  158425. }
  158426. if (numSamples > 0)
  158427. {
  158428. for (int i = numDestChannels; --i >= 0;)
  158429. if (destSamples[i] != 0)
  158430. zeromem (destSamples[i] + startOffsetInDestBuffer,
  158431. sizeof (int) * numSamples);
  158432. }
  158433. return true;
  158434. }
  158435. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  158436. {
  158437. return (size_t) (static_cast <InputStream*> (datasource)->read (ptr, (int) (size * nmemb)) / size);
  158438. }
  158439. static int oggSeekCallback (void* datasource, OggVorbisNamespace::ogg_int64_t offset, int whence)
  158440. {
  158441. InputStream* const in = static_cast <InputStream*> (datasource);
  158442. if (whence == SEEK_CUR)
  158443. offset += in->getPosition();
  158444. else if (whence == SEEK_END)
  158445. offset += in->getTotalLength();
  158446. in->setPosition (offset);
  158447. return 0;
  158448. }
  158449. static int oggCloseCallback (void*)
  158450. {
  158451. return 0;
  158452. }
  158453. static long oggTellCallback (void* datasource)
  158454. {
  158455. return (long) static_cast <InputStream*> (datasource)->getPosition();
  158456. }
  158457. juce_UseDebuggingNewOperator
  158458. };
  158459. class OggWriter : public AudioFormatWriter
  158460. {
  158461. OggVorbisNamespace::ogg_stream_state os;
  158462. OggVorbisNamespace::ogg_page og;
  158463. OggVorbisNamespace::ogg_packet op;
  158464. OggVorbisNamespace::vorbis_info vi;
  158465. OggVorbisNamespace::vorbis_comment vc;
  158466. OggVorbisNamespace::vorbis_dsp_state vd;
  158467. OggVorbisNamespace::vorbis_block vb;
  158468. public:
  158469. bool ok;
  158470. OggWriter (OutputStream* const out,
  158471. const double sampleRate,
  158472. const int numChannels,
  158473. const int bitsPerSample,
  158474. const int qualityIndex)
  158475. : AudioFormatWriter (out, TRANS (oggFormatName),
  158476. sampleRate,
  158477. numChannels,
  158478. bitsPerSample)
  158479. {
  158480. using namespace OggVorbisNamespace;
  158481. ok = false;
  158482. vorbis_info_init (&vi);
  158483. if (vorbis_encode_init_vbr (&vi,
  158484. numChannels,
  158485. (int) sampleRate,
  158486. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  158487. {
  158488. vorbis_comment_init (&vc);
  158489. if (JUCEApplication::getInstance() != 0)
  158490. vorbis_comment_add_tag (&vc, "ENCODER", const_cast <char*> (JUCEApplication::getInstance()->getApplicationName().toUTF8()));
  158491. vorbis_analysis_init (&vd, &vi);
  158492. vorbis_block_init (&vd, &vb);
  158493. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  158494. ogg_packet header;
  158495. ogg_packet header_comm;
  158496. ogg_packet header_code;
  158497. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  158498. ogg_stream_packetin (&os, &header);
  158499. ogg_stream_packetin (&os, &header_comm);
  158500. ogg_stream_packetin (&os, &header_code);
  158501. for (;;)
  158502. {
  158503. if (ogg_stream_flush (&os, &og) == 0)
  158504. break;
  158505. output->write (og.header, og.header_len);
  158506. output->write (og.body, og.body_len);
  158507. }
  158508. ok = true;
  158509. }
  158510. }
  158511. ~OggWriter()
  158512. {
  158513. using namespace OggVorbisNamespace;
  158514. if (ok)
  158515. {
  158516. // write a zero-length packet to show ogg that we're finished..
  158517. write (0, 0);
  158518. ogg_stream_clear (&os);
  158519. vorbis_block_clear (&vb);
  158520. vorbis_dsp_clear (&vd);
  158521. vorbis_comment_clear (&vc);
  158522. vorbis_info_clear (&vi);
  158523. output->flush();
  158524. }
  158525. else
  158526. {
  158527. vorbis_info_clear (&vi);
  158528. output = 0; // to stop the base class deleting this, as it needs to be returned
  158529. // to the caller of createWriter()
  158530. }
  158531. }
  158532. bool write (const int** samplesToWrite, int numSamples)
  158533. {
  158534. using namespace OggVorbisNamespace;
  158535. if (! ok)
  158536. return false;
  158537. if (numSamples > 0)
  158538. {
  158539. const double gain = 1.0 / 0x80000000u;
  158540. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  158541. for (int i = numChannels; --i >= 0;)
  158542. {
  158543. float* const dst = vorbisBuffer[i];
  158544. const int* const src = samplesToWrite [i];
  158545. if (src != 0 && dst != 0)
  158546. {
  158547. for (int j = 0; j < numSamples; ++j)
  158548. dst[j] = (float) (src[j] * gain);
  158549. }
  158550. }
  158551. }
  158552. vorbis_analysis_wrote (&vd, numSamples);
  158553. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  158554. {
  158555. vorbis_analysis (&vb, 0);
  158556. vorbis_bitrate_addblock (&vb);
  158557. while (vorbis_bitrate_flushpacket (&vd, &op))
  158558. {
  158559. ogg_stream_packetin (&os, &op);
  158560. for (;;)
  158561. {
  158562. if (ogg_stream_pageout (&os, &og) == 0)
  158563. break;
  158564. output->write (og.header, og.header_len);
  158565. output->write (og.body, og.body_len);
  158566. if (ogg_page_eos (&og))
  158567. break;
  158568. }
  158569. }
  158570. }
  158571. return true;
  158572. }
  158573. juce_UseDebuggingNewOperator
  158574. };
  158575. OggVorbisAudioFormat::OggVorbisAudioFormat()
  158576. : AudioFormat (TRANS (oggFormatName), StringArray (oggExtensions))
  158577. {
  158578. }
  158579. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  158580. {
  158581. }
  158582. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  158583. {
  158584. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  158585. return Array <int> (rates);
  158586. }
  158587. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  158588. {
  158589. Array <int> depths;
  158590. depths.add (32);
  158591. return depths;
  158592. }
  158593. bool OggVorbisAudioFormat::canDoStereo()
  158594. {
  158595. return true;
  158596. }
  158597. bool OggVorbisAudioFormat::canDoMono()
  158598. {
  158599. return true;
  158600. }
  158601. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  158602. const bool deleteStreamIfOpeningFails)
  158603. {
  158604. ScopedPointer <OggReader> r (new OggReader (in));
  158605. if (r->sampleRate != 0)
  158606. return r.release();
  158607. if (! deleteStreamIfOpeningFails)
  158608. r->input = 0;
  158609. return 0;
  158610. }
  158611. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  158612. double sampleRate,
  158613. unsigned int numChannels,
  158614. int bitsPerSample,
  158615. const StringPairArray& /*metadataValues*/,
  158616. int qualityOptionIndex)
  158617. {
  158618. ScopedPointer <OggWriter> w (new OggWriter (out,
  158619. sampleRate,
  158620. numChannels,
  158621. bitsPerSample,
  158622. qualityOptionIndex));
  158623. return w->ok ? w.release() : 0;
  158624. }
  158625. bool OggVorbisAudioFormat::isCompressed()
  158626. {
  158627. return true;
  158628. }
  158629. const StringArray OggVorbisAudioFormat::getQualityOptions()
  158630. {
  158631. StringArray s;
  158632. s.add ("Low Quality");
  158633. s.add ("Medium Quality");
  158634. s.add ("High Quality");
  158635. return s;
  158636. }
  158637. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  158638. {
  158639. FileInputStream* const in = source.createInputStream();
  158640. if (in != 0)
  158641. {
  158642. ScopedPointer <AudioFormatReader> r (createReaderFor (in, true));
  158643. if (r != 0)
  158644. {
  158645. const int64 numSamps = r->lengthInSamples;
  158646. r = 0;
  158647. const int64 fileNumSamps = source.getSize() / 4;
  158648. const double ratio = numSamps / (double) fileNumSamps;
  158649. if (ratio > 12.0)
  158650. return 0;
  158651. else if (ratio > 6.0)
  158652. return 1;
  158653. else
  158654. return 2;
  158655. }
  158656. }
  158657. return 1;
  158658. }
  158659. END_JUCE_NAMESPACE
  158660. #endif
  158661. /*** End of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  158662. #endif
  158663. #if JUCE_BUILD_CORE && ! JUCE_ONLY_BUILD_CORE_LIBRARY // do these in the core section to help balance the sizes
  158664. /*** Start of inlined file: juce_JPEGLoader.cpp ***/
  158665. #if JUCE_MSVC
  158666. #pragma warning (push)
  158667. #endif
  158668. namespace jpeglibNamespace
  158669. {
  158670. #if JUCE_INCLUDE_JPEGLIB_CODE
  158671. #if JUCE_MINGW
  158672. typedef unsigned char boolean;
  158673. #endif
  158674. extern "C"
  158675. {
  158676. #define JPEG_INTERNALS
  158677. #undef FAR
  158678. /*** Start of inlined file: jpeglib.h ***/
  158679. #ifndef JPEGLIB_H
  158680. #define JPEGLIB_H
  158681. /*
  158682. * First we include the configuration files that record how this
  158683. * installation of the JPEG library is set up. jconfig.h can be
  158684. * generated automatically for many systems. jmorecfg.h contains
  158685. * manual configuration options that most people need not worry about.
  158686. */
  158687. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  158688. /*** Start of inlined file: jconfig.h ***/
  158689. /* see jconfig.doc for explanations */
  158690. // disable all the warnings under MSVC
  158691. #ifdef _MSC_VER
  158692. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  158693. #endif
  158694. #ifdef __BORLANDC__
  158695. #pragma warn -8057
  158696. #pragma warn -8019
  158697. #pragma warn -8004
  158698. #pragma warn -8008
  158699. #endif
  158700. #define HAVE_PROTOTYPES
  158701. #define HAVE_UNSIGNED_CHAR
  158702. #define HAVE_UNSIGNED_SHORT
  158703. /* #define void char */
  158704. /* #define const */
  158705. #undef CHAR_IS_UNSIGNED
  158706. #define HAVE_STDDEF_H
  158707. #define HAVE_STDLIB_H
  158708. #undef NEED_BSD_STRINGS
  158709. #undef NEED_SYS_TYPES_H
  158710. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  158711. #undef NEED_SHORT_EXTERNAL_NAMES
  158712. #undef INCOMPLETE_TYPES_BROKEN
  158713. /* Define "boolean" as unsigned char, not int, per Windows custom */
  158714. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  158715. typedef unsigned char boolean;
  158716. #endif
  158717. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  158718. #ifdef JPEG_INTERNALS
  158719. #undef RIGHT_SHIFT_IS_UNSIGNED
  158720. #endif /* JPEG_INTERNALS */
  158721. #ifdef JPEG_CJPEG_DJPEG
  158722. #define BMP_SUPPORTED /* BMP image file format */
  158723. #define GIF_SUPPORTED /* GIF image file format */
  158724. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  158725. #undef RLE_SUPPORTED /* Utah RLE image file format */
  158726. #define TARGA_SUPPORTED /* Targa image file format */
  158727. #define TWO_FILE_COMMANDLINE /* optional */
  158728. #define USE_SETMODE /* Microsoft has setmode() */
  158729. #undef NEED_SIGNAL_CATCHER
  158730. #undef DONT_USE_B_MODE
  158731. #undef PROGRESS_REPORT /* optional */
  158732. #endif /* JPEG_CJPEG_DJPEG */
  158733. /*** End of inlined file: jconfig.h ***/
  158734. /* widely used configuration options */
  158735. #endif
  158736. /*** Start of inlined file: jmorecfg.h ***/
  158737. /*
  158738. * Define BITS_IN_JSAMPLE as either
  158739. * 8 for 8-bit sample values (the usual setting)
  158740. * 12 for 12-bit sample values
  158741. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  158742. * JPEG standard, and the IJG code does not support anything else!
  158743. * We do not support run-time selection of data precision, sorry.
  158744. */
  158745. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  158746. /*
  158747. * Maximum number of components (color channels) allowed in JPEG image.
  158748. * To meet the letter of the JPEG spec, set this to 255. However, darn
  158749. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  158750. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  158751. * really short on memory. (Each allowed component costs a hundred or so
  158752. * bytes of storage, whether actually used in an image or not.)
  158753. */
  158754. #define MAX_COMPONENTS 10 /* maximum number of image components */
  158755. /*
  158756. * Basic data types.
  158757. * You may need to change these if you have a machine with unusual data
  158758. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  158759. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  158760. * but it had better be at least 16.
  158761. */
  158762. /* Representation of a single sample (pixel element value).
  158763. * We frequently allocate large arrays of these, so it's important to keep
  158764. * them small. But if you have memory to burn and access to char or short
  158765. * arrays is very slow on your hardware, you might want to change these.
  158766. */
  158767. #if BITS_IN_JSAMPLE == 8
  158768. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  158769. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  158770. */
  158771. #ifdef HAVE_UNSIGNED_CHAR
  158772. typedef unsigned char JSAMPLE;
  158773. #define GETJSAMPLE(value) ((int) (value))
  158774. #else /* not HAVE_UNSIGNED_CHAR */
  158775. typedef char JSAMPLE;
  158776. #ifdef CHAR_IS_UNSIGNED
  158777. #define GETJSAMPLE(value) ((int) (value))
  158778. #else
  158779. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  158780. #endif /* CHAR_IS_UNSIGNED */
  158781. #endif /* HAVE_UNSIGNED_CHAR */
  158782. #define MAXJSAMPLE 255
  158783. #define CENTERJSAMPLE 128
  158784. #endif /* BITS_IN_JSAMPLE == 8 */
  158785. #if BITS_IN_JSAMPLE == 12
  158786. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  158787. * On nearly all machines "short" will do nicely.
  158788. */
  158789. typedef short JSAMPLE;
  158790. #define GETJSAMPLE(value) ((int) (value))
  158791. #define MAXJSAMPLE 4095
  158792. #define CENTERJSAMPLE 2048
  158793. #endif /* BITS_IN_JSAMPLE == 12 */
  158794. /* Representation of a DCT frequency coefficient.
  158795. * This should be a signed value of at least 16 bits; "short" is usually OK.
  158796. * Again, we allocate large arrays of these, but you can change to int
  158797. * if you have memory to burn and "short" is really slow.
  158798. */
  158799. typedef short JCOEF;
  158800. /* Compressed datastreams are represented as arrays of JOCTET.
  158801. * These must be EXACTLY 8 bits wide, at least once they are written to
  158802. * external storage. Note that when using the stdio data source/destination
  158803. * managers, this is also the data type passed to fread/fwrite.
  158804. */
  158805. #ifdef HAVE_UNSIGNED_CHAR
  158806. typedef unsigned char JOCTET;
  158807. #define GETJOCTET(value) (value)
  158808. #else /* not HAVE_UNSIGNED_CHAR */
  158809. typedef char JOCTET;
  158810. #ifdef CHAR_IS_UNSIGNED
  158811. #define GETJOCTET(value) (value)
  158812. #else
  158813. #define GETJOCTET(value) ((value) & 0xFF)
  158814. #endif /* CHAR_IS_UNSIGNED */
  158815. #endif /* HAVE_UNSIGNED_CHAR */
  158816. /* These typedefs are used for various table entries and so forth.
  158817. * They must be at least as wide as specified; but making them too big
  158818. * won't cost a huge amount of memory, so we don't provide special
  158819. * extraction code like we did for JSAMPLE. (In other words, these
  158820. * typedefs live at a different point on the speed/space tradeoff curve.)
  158821. */
  158822. /* UINT8 must hold at least the values 0..255. */
  158823. #ifdef HAVE_UNSIGNED_CHAR
  158824. typedef unsigned char UINT8;
  158825. #else /* not HAVE_UNSIGNED_CHAR */
  158826. #ifdef CHAR_IS_UNSIGNED
  158827. typedef char UINT8;
  158828. #else /* not CHAR_IS_UNSIGNED */
  158829. typedef short UINT8;
  158830. #endif /* CHAR_IS_UNSIGNED */
  158831. #endif /* HAVE_UNSIGNED_CHAR */
  158832. /* UINT16 must hold at least the values 0..65535. */
  158833. #ifdef HAVE_UNSIGNED_SHORT
  158834. typedef unsigned short UINT16;
  158835. #else /* not HAVE_UNSIGNED_SHORT */
  158836. typedef unsigned int UINT16;
  158837. #endif /* HAVE_UNSIGNED_SHORT */
  158838. /* INT16 must hold at least the values -32768..32767. */
  158839. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  158840. typedef short INT16;
  158841. #endif
  158842. /* INT32 must hold at least signed 32-bit values. */
  158843. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  158844. typedef long INT32;
  158845. #endif
  158846. /* Datatype used for image dimensions. The JPEG standard only supports
  158847. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  158848. * "unsigned int" is sufficient on all machines. However, if you need to
  158849. * handle larger images and you don't mind deviating from the spec, you
  158850. * can change this datatype.
  158851. */
  158852. typedef unsigned int JDIMENSION;
  158853. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  158854. /* These macros are used in all function definitions and extern declarations.
  158855. * You could modify them if you need to change function linkage conventions;
  158856. * in particular, you'll need to do that to make the library a Windows DLL.
  158857. * Another application is to make all functions global for use with debuggers
  158858. * or code profilers that require it.
  158859. */
  158860. /* a function called through method pointers: */
  158861. #define METHODDEF(type) static type
  158862. /* a function used only in its module: */
  158863. #define LOCAL(type) static type
  158864. /* a function referenced thru EXTERNs: */
  158865. #define GLOBAL(type) type
  158866. /* a reference to a GLOBAL function: */
  158867. #define EXTERN(type) extern type
  158868. /* This macro is used to declare a "method", that is, a function pointer.
  158869. * We want to supply prototype parameters if the compiler can cope.
  158870. * Note that the arglist parameter must be parenthesized!
  158871. * Again, you can customize this if you need special linkage keywords.
  158872. */
  158873. #ifdef HAVE_PROTOTYPES
  158874. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  158875. #else
  158876. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  158877. #endif
  158878. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  158879. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  158880. * by just saying "FAR *" where such a pointer is needed. In a few places
  158881. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  158882. */
  158883. #ifdef NEED_FAR_POINTERS
  158884. #define FAR far
  158885. #else
  158886. #define FAR
  158887. #endif
  158888. /*
  158889. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  158890. * in standard header files. Or you may have conflicts with application-
  158891. * specific header files that you want to include together with these files.
  158892. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  158893. */
  158894. #ifndef HAVE_BOOLEAN
  158895. typedef int boolean;
  158896. #endif
  158897. #ifndef FALSE /* in case these macros already exist */
  158898. #define FALSE 0 /* values of boolean */
  158899. #endif
  158900. #ifndef TRUE
  158901. #define TRUE 1
  158902. #endif
  158903. /*
  158904. * The remaining options affect code selection within the JPEG library,
  158905. * but they don't need to be visible to most applications using the library.
  158906. * To minimize application namespace pollution, the symbols won't be
  158907. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  158908. */
  158909. #ifdef JPEG_INTERNALS
  158910. #define JPEG_INTERNAL_OPTIONS
  158911. #endif
  158912. #ifdef JPEG_INTERNAL_OPTIONS
  158913. /*
  158914. * These defines indicate whether to include various optional functions.
  158915. * Undefining some of these symbols will produce a smaller but less capable
  158916. * library. Note that you can leave certain source files out of the
  158917. * compilation/linking process if you've #undef'd the corresponding symbols.
  158918. * (You may HAVE to do that if your compiler doesn't like null source files.)
  158919. */
  158920. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  158921. /* Capability options common to encoder and decoder: */
  158922. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  158923. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  158924. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  158925. /* Encoder capability options: */
  158926. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  158927. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  158928. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  158929. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  158930. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  158931. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  158932. * precision, so jchuff.c normally uses entropy optimization to compute
  158933. * usable tables for higher precision. If you don't want to do optimization,
  158934. * you'll have to supply different default Huffman tables.
  158935. * The exact same statements apply for progressive JPEG: the default tables
  158936. * don't work for progressive mode. (This may get fixed, however.)
  158937. */
  158938. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  158939. /* Decoder capability options: */
  158940. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  158941. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  158942. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  158943. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  158944. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  158945. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  158946. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  158947. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  158948. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  158949. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  158950. /* more capability options later, no doubt */
  158951. /*
  158952. * Ordering of RGB data in scanlines passed to or from the application.
  158953. * If your application wants to deal with data in the order B,G,R, just
  158954. * change these macros. You can also deal with formats such as R,G,B,X
  158955. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  158956. * the offsets will also change the order in which colormap data is organized.
  158957. * RESTRICTIONS:
  158958. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  158959. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  158960. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  158961. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  158962. * is not 3 (they don't understand about dummy color components!). So you
  158963. * can't use color quantization if you change that value.
  158964. */
  158965. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  158966. #define RGB_GREEN 1 /* Offset of Green */
  158967. #define RGB_BLUE 2 /* Offset of Blue */
  158968. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  158969. /* Definitions for speed-related optimizations. */
  158970. /* If your compiler supports inline functions, define INLINE
  158971. * as the inline keyword; otherwise define it as empty.
  158972. */
  158973. #ifndef INLINE
  158974. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  158975. #define INLINE __inline__
  158976. #endif
  158977. #ifndef INLINE
  158978. #define INLINE /* default is to define it as empty */
  158979. #endif
  158980. #endif
  158981. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  158982. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  158983. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  158984. */
  158985. #ifndef MULTIPLIER
  158986. #define MULTIPLIER int /* type for fastest integer multiply */
  158987. #endif
  158988. /* FAST_FLOAT should be either float or double, whichever is done faster
  158989. * by your compiler. (Note that this type is only used in the floating point
  158990. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  158991. * Typically, float is faster in ANSI C compilers, while double is faster in
  158992. * pre-ANSI compilers (because they insist on converting to double anyway).
  158993. * The code below therefore chooses float if we have ANSI-style prototypes.
  158994. */
  158995. #ifndef FAST_FLOAT
  158996. #ifdef HAVE_PROTOTYPES
  158997. #define FAST_FLOAT float
  158998. #else
  158999. #define FAST_FLOAT double
  159000. #endif
  159001. #endif
  159002. #endif /* JPEG_INTERNAL_OPTIONS */
  159003. /*** End of inlined file: jmorecfg.h ***/
  159004. /* seldom changed options */
  159005. /* Version ID for the JPEG library.
  159006. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  159007. */
  159008. #define JPEG_LIB_VERSION 62 /* Version 6b */
  159009. /* Various constants determining the sizes of things.
  159010. * All of these are specified by the JPEG standard, so don't change them
  159011. * if you want to be compatible.
  159012. */
  159013. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  159014. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  159015. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  159016. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  159017. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  159018. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  159019. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  159020. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  159021. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  159022. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  159023. * to handle it. We even let you do this from the jconfig.h file. However,
  159024. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  159025. * sometimes emits noncompliant files doesn't mean you should too.
  159026. */
  159027. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  159028. #ifndef D_MAX_BLOCKS_IN_MCU
  159029. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  159030. #endif
  159031. /* Data structures for images (arrays of samples and of DCT coefficients).
  159032. * On 80x86 machines, the image arrays are too big for near pointers,
  159033. * but the pointer arrays can fit in near memory.
  159034. */
  159035. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  159036. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  159037. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  159038. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  159039. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  159040. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  159041. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  159042. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  159043. /* Types for JPEG compression parameters and working tables. */
  159044. /* DCT coefficient quantization tables. */
  159045. typedef struct {
  159046. /* This array gives the coefficient quantizers in natural array order
  159047. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  159048. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  159049. */
  159050. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  159051. /* This field is used only during compression. It's initialized FALSE when
  159052. * the table is created, and set TRUE when it's been output to the file.
  159053. * You could suppress output of a table by setting this to TRUE.
  159054. * (See jpeg_suppress_tables for an example.)
  159055. */
  159056. boolean sent_table; /* TRUE when table has been output */
  159057. } JQUANT_TBL;
  159058. /* Huffman coding tables. */
  159059. typedef struct {
  159060. /* These two fields directly represent the contents of a JPEG DHT marker */
  159061. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  159062. /* length k bits; bits[0] is unused */
  159063. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  159064. /* This field is used only during compression. It's initialized FALSE when
  159065. * the table is created, and set TRUE when it's been output to the file.
  159066. * You could suppress output of a table by setting this to TRUE.
  159067. * (See jpeg_suppress_tables for an example.)
  159068. */
  159069. boolean sent_table; /* TRUE when table has been output */
  159070. } JHUFF_TBL;
  159071. /* Basic info about one component (color channel). */
  159072. typedef struct {
  159073. /* These values are fixed over the whole image. */
  159074. /* For compression, they must be supplied by parameter setup; */
  159075. /* for decompression, they are read from the SOF marker. */
  159076. int component_id; /* identifier for this component (0..255) */
  159077. int component_index; /* its index in SOF or cinfo->comp_info[] */
  159078. int h_samp_factor; /* horizontal sampling factor (1..4) */
  159079. int v_samp_factor; /* vertical sampling factor (1..4) */
  159080. int quant_tbl_no; /* quantization table selector (0..3) */
  159081. /* These values may vary between scans. */
  159082. /* For compression, they must be supplied by parameter setup; */
  159083. /* for decompression, they are read from the SOS marker. */
  159084. /* The decompressor output side may not use these variables. */
  159085. int dc_tbl_no; /* DC entropy table selector (0..3) */
  159086. int ac_tbl_no; /* AC entropy table selector (0..3) */
  159087. /* Remaining fields should be treated as private by applications. */
  159088. /* These values are computed during compression or decompression startup: */
  159089. /* Component's size in DCT blocks.
  159090. * Any dummy blocks added to complete an MCU are not counted; therefore
  159091. * these values do not depend on whether a scan is interleaved or not.
  159092. */
  159093. JDIMENSION width_in_blocks;
  159094. JDIMENSION height_in_blocks;
  159095. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  159096. * For decompression this is the size of the output from one DCT block,
  159097. * reflecting any scaling we choose to apply during the IDCT step.
  159098. * Values of 1,2,4,8 are likely to be supported. Note that different
  159099. * components may receive different IDCT scalings.
  159100. */
  159101. int DCT_scaled_size;
  159102. /* The downsampled dimensions are the component's actual, unpadded number
  159103. * of samples at the main buffer (preprocessing/compression interface), thus
  159104. * downsampled_width = ceil(image_width * Hi/Hmax)
  159105. * and similarly for height. For decompression, IDCT scaling is included, so
  159106. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  159107. */
  159108. JDIMENSION downsampled_width; /* actual width in samples */
  159109. JDIMENSION downsampled_height; /* actual height in samples */
  159110. /* This flag is used only for decompression. In cases where some of the
  159111. * components will be ignored (eg grayscale output from YCbCr image),
  159112. * we can skip most computations for the unused components.
  159113. */
  159114. boolean component_needed; /* do we need the value of this component? */
  159115. /* These values are computed before starting a scan of the component. */
  159116. /* The decompressor output side may not use these variables. */
  159117. int MCU_width; /* number of blocks per MCU, horizontally */
  159118. int MCU_height; /* number of blocks per MCU, vertically */
  159119. int MCU_blocks; /* MCU_width * MCU_height */
  159120. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  159121. int last_col_width; /* # of non-dummy blocks across in last MCU */
  159122. int last_row_height; /* # of non-dummy blocks down in last MCU */
  159123. /* Saved quantization table for component; NULL if none yet saved.
  159124. * See jdinput.c comments about the need for this information.
  159125. * This field is currently used only for decompression.
  159126. */
  159127. JQUANT_TBL * quant_table;
  159128. /* Private per-component storage for DCT or IDCT subsystem. */
  159129. void * dct_table;
  159130. } jpeg_component_info;
  159131. /* The script for encoding a multiple-scan file is an array of these: */
  159132. typedef struct {
  159133. int comps_in_scan; /* number of components encoded in this scan */
  159134. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  159135. int Ss, Se; /* progressive JPEG spectral selection parms */
  159136. int Ah, Al; /* progressive JPEG successive approx. parms */
  159137. } jpeg_scan_info;
  159138. /* The decompressor can save APPn and COM markers in a list of these: */
  159139. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  159140. struct jpeg_marker_struct {
  159141. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  159142. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  159143. unsigned int original_length; /* # bytes of data in the file */
  159144. unsigned int data_length; /* # bytes of data saved at data[] */
  159145. JOCTET FAR * data; /* the data contained in the marker */
  159146. /* the marker length word is not counted in data_length or original_length */
  159147. };
  159148. /* Known color spaces. */
  159149. typedef enum {
  159150. JCS_UNKNOWN, /* error/unspecified */
  159151. JCS_GRAYSCALE, /* monochrome */
  159152. JCS_RGB, /* red/green/blue */
  159153. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  159154. JCS_CMYK, /* C/M/Y/K */
  159155. JCS_YCCK /* Y/Cb/Cr/K */
  159156. } J_COLOR_SPACE;
  159157. /* DCT/IDCT algorithm options. */
  159158. typedef enum {
  159159. JDCT_ISLOW, /* slow but accurate integer algorithm */
  159160. JDCT_IFAST, /* faster, less accurate integer method */
  159161. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  159162. } J_DCT_METHOD;
  159163. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  159164. #define JDCT_DEFAULT JDCT_ISLOW
  159165. #endif
  159166. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  159167. #define JDCT_FASTEST JDCT_IFAST
  159168. #endif
  159169. /* Dithering options for decompression. */
  159170. typedef enum {
  159171. JDITHER_NONE, /* no dithering */
  159172. JDITHER_ORDERED, /* simple ordered dither */
  159173. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  159174. } J_DITHER_MODE;
  159175. /* Common fields between JPEG compression and decompression master structs. */
  159176. #define jpeg_common_fields \
  159177. struct jpeg_error_mgr * err; /* Error handler module */\
  159178. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  159179. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  159180. void * client_data; /* Available for use by application */\
  159181. boolean is_decompressor; /* So common code can tell which is which */\
  159182. int global_state /* For checking call sequence validity */
  159183. /* Routines that are to be used by both halves of the library are declared
  159184. * to receive a pointer to this structure. There are no actual instances of
  159185. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  159186. */
  159187. struct jpeg_common_struct {
  159188. jpeg_common_fields; /* Fields common to both master struct types */
  159189. /* Additional fields follow in an actual jpeg_compress_struct or
  159190. * jpeg_decompress_struct. All three structs must agree on these
  159191. * initial fields! (This would be a lot cleaner in C++.)
  159192. */
  159193. };
  159194. typedef struct jpeg_common_struct * j_common_ptr;
  159195. typedef struct jpeg_compress_struct * j_compress_ptr;
  159196. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  159197. /* Master record for a compression instance */
  159198. struct jpeg_compress_struct {
  159199. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  159200. /* Destination for compressed data */
  159201. struct jpeg_destination_mgr * dest;
  159202. /* Description of source image --- these fields must be filled in by
  159203. * outer application before starting compression. in_color_space must
  159204. * be correct before you can even call jpeg_set_defaults().
  159205. */
  159206. JDIMENSION image_width; /* input image width */
  159207. JDIMENSION image_height; /* input image height */
  159208. int input_components; /* # of color components in input image */
  159209. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  159210. double input_gamma; /* image gamma of input image */
  159211. /* Compression parameters --- these fields must be set before calling
  159212. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  159213. * initialize everything to reasonable defaults, then changing anything
  159214. * the application specifically wants to change. That way you won't get
  159215. * burnt when new parameters are added. Also note that there are several
  159216. * helper routines to simplify changing parameters.
  159217. */
  159218. int data_precision; /* bits of precision in image data */
  159219. int num_components; /* # of color components in JPEG image */
  159220. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  159221. jpeg_component_info * comp_info;
  159222. /* comp_info[i] describes component that appears i'th in SOF */
  159223. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  159224. /* ptrs to coefficient quantization tables, or NULL if not defined */
  159225. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159226. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159227. /* ptrs to Huffman coding tables, or NULL if not defined */
  159228. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  159229. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  159230. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  159231. int num_scans; /* # of entries in scan_info array */
  159232. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  159233. /* The default value of scan_info is NULL, which causes a single-scan
  159234. * sequential JPEG file to be emitted. To create a multi-scan file,
  159235. * set num_scans and scan_info to point to an array of scan definitions.
  159236. */
  159237. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  159238. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  159239. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  159240. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  159241. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  159242. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  159243. /* The restart interval can be specified in absolute MCUs by setting
  159244. * restart_interval, or in MCU rows by setting restart_in_rows
  159245. * (in which case the correct restart_interval will be figured
  159246. * for each scan).
  159247. */
  159248. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  159249. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  159250. /* Parameters controlling emission of special markers. */
  159251. boolean write_JFIF_header; /* should a JFIF marker be written? */
  159252. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  159253. UINT8 JFIF_minor_version;
  159254. /* These three values are not used by the JPEG code, merely copied */
  159255. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  159256. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  159257. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  159258. UINT8 density_unit; /* JFIF code for pixel size units */
  159259. UINT16 X_density; /* Horizontal pixel density */
  159260. UINT16 Y_density; /* Vertical pixel density */
  159261. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  159262. /* State variable: index of next scanline to be written to
  159263. * jpeg_write_scanlines(). Application may use this to control its
  159264. * processing loop, e.g., "while (next_scanline < image_height)".
  159265. */
  159266. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  159267. /* Remaining fields are known throughout compressor, but generally
  159268. * should not be touched by a surrounding application.
  159269. */
  159270. /*
  159271. * These fields are computed during compression startup
  159272. */
  159273. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  159274. int max_h_samp_factor; /* largest h_samp_factor */
  159275. int max_v_samp_factor; /* largest v_samp_factor */
  159276. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  159277. /* The coefficient controller receives data in units of MCU rows as defined
  159278. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  159279. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  159280. * "iMCU" (interleaved MCU) row.
  159281. */
  159282. /*
  159283. * These fields are valid during any one scan.
  159284. * They describe the components and MCUs actually appearing in the scan.
  159285. */
  159286. int comps_in_scan; /* # of JPEG components in this scan */
  159287. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  159288. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  159289. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  159290. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  159291. int blocks_in_MCU; /* # of DCT blocks per MCU */
  159292. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  159293. /* MCU_membership[i] is index in cur_comp_info of component owning */
  159294. /* i'th block in an MCU */
  159295. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  159296. /*
  159297. * Links to compression subobjects (methods and private variables of modules)
  159298. */
  159299. struct jpeg_comp_master * master;
  159300. struct jpeg_c_main_controller * main;
  159301. struct jpeg_c_prep_controller * prep;
  159302. struct jpeg_c_coef_controller * coef;
  159303. struct jpeg_marker_writer * marker;
  159304. struct jpeg_color_converter * cconvert;
  159305. struct jpeg_downsampler * downsample;
  159306. struct jpeg_forward_dct * fdct;
  159307. struct jpeg_entropy_encoder * entropy;
  159308. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  159309. int script_space_size;
  159310. };
  159311. /* Master record for a decompression instance */
  159312. struct jpeg_decompress_struct {
  159313. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  159314. /* Source of compressed data */
  159315. struct jpeg_source_mgr * src;
  159316. /* Basic description of image --- filled in by jpeg_read_header(). */
  159317. /* Application may inspect these values to decide how to process image. */
  159318. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  159319. JDIMENSION image_height; /* nominal image height */
  159320. int num_components; /* # of color components in JPEG image */
  159321. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  159322. /* Decompression processing parameters --- these fields must be set before
  159323. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  159324. * them to default values.
  159325. */
  159326. J_COLOR_SPACE out_color_space; /* colorspace for output */
  159327. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  159328. double output_gamma; /* image gamma wanted in output */
  159329. boolean buffered_image; /* TRUE=multiple output passes */
  159330. boolean raw_data_out; /* TRUE=downsampled data wanted */
  159331. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  159332. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  159333. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  159334. boolean quantize_colors; /* TRUE=colormapped output wanted */
  159335. /* the following are ignored if not quantize_colors: */
  159336. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  159337. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  159338. int desired_number_of_colors; /* max # colors to use in created colormap */
  159339. /* these are significant only in buffered-image mode: */
  159340. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  159341. boolean enable_external_quant;/* enable future use of external colormap */
  159342. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  159343. /* Description of actual output image that will be returned to application.
  159344. * These fields are computed by jpeg_start_decompress().
  159345. * You can also use jpeg_calc_output_dimensions() to determine these values
  159346. * in advance of calling jpeg_start_decompress().
  159347. */
  159348. JDIMENSION output_width; /* scaled image width */
  159349. JDIMENSION output_height; /* scaled image height */
  159350. int out_color_components; /* # of color components in out_color_space */
  159351. int output_components; /* # of color components returned */
  159352. /* output_components is 1 (a colormap index) when quantizing colors;
  159353. * otherwise it equals out_color_components.
  159354. */
  159355. int rec_outbuf_height; /* min recommended height of scanline buffer */
  159356. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  159357. * high, space and time will be wasted due to unnecessary data copying.
  159358. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  159359. */
  159360. /* When quantizing colors, the output colormap is described by these fields.
  159361. * The application can supply a colormap by setting colormap non-NULL before
  159362. * calling jpeg_start_decompress; otherwise a colormap is created during
  159363. * jpeg_start_decompress or jpeg_start_output.
  159364. * The map has out_color_components rows and actual_number_of_colors columns.
  159365. */
  159366. int actual_number_of_colors; /* number of entries in use */
  159367. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  159368. /* State variables: these variables indicate the progress of decompression.
  159369. * The application may examine these but must not modify them.
  159370. */
  159371. /* Row index of next scanline to be read from jpeg_read_scanlines().
  159372. * Application may use this to control its processing loop, e.g.,
  159373. * "while (output_scanline < output_height)".
  159374. */
  159375. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  159376. /* Current input scan number and number of iMCU rows completed in scan.
  159377. * These indicate the progress of the decompressor input side.
  159378. */
  159379. int input_scan_number; /* Number of SOS markers seen so far */
  159380. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  159381. /* The "output scan number" is the notional scan being displayed by the
  159382. * output side. The decompressor will not allow output scan/row number
  159383. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  159384. */
  159385. int output_scan_number; /* Nominal scan number being displayed */
  159386. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  159387. /* Current progression status. coef_bits[c][i] indicates the precision
  159388. * with which component c's DCT coefficient i (in zigzag order) is known.
  159389. * It is -1 when no data has yet been received, otherwise it is the point
  159390. * transform (shift) value for the most recent scan of the coefficient
  159391. * (thus, 0 at completion of the progression).
  159392. * This pointer is NULL when reading a non-progressive file.
  159393. */
  159394. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  159395. /* Internal JPEG parameters --- the application usually need not look at
  159396. * these fields. Note that the decompressor output side may not use
  159397. * any parameters that can change between scans.
  159398. */
  159399. /* Quantization and Huffman tables are carried forward across input
  159400. * datastreams when processing abbreviated JPEG datastreams.
  159401. */
  159402. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  159403. /* ptrs to coefficient quantization tables, or NULL if not defined */
  159404. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159405. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159406. /* ptrs to Huffman coding tables, or NULL if not defined */
  159407. /* These parameters are never carried across datastreams, since they
  159408. * are given in SOF/SOS markers or defined to be reset by SOI.
  159409. */
  159410. int data_precision; /* bits of precision in image data */
  159411. jpeg_component_info * comp_info;
  159412. /* comp_info[i] describes component that appears i'th in SOF */
  159413. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  159414. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  159415. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  159416. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  159417. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  159418. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  159419. /* These fields record data obtained from optional markers recognized by
  159420. * the JPEG library.
  159421. */
  159422. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  159423. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  159424. UINT8 JFIF_major_version; /* JFIF version number */
  159425. UINT8 JFIF_minor_version;
  159426. UINT8 density_unit; /* JFIF code for pixel size units */
  159427. UINT16 X_density; /* Horizontal pixel density */
  159428. UINT16 Y_density; /* Vertical pixel density */
  159429. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  159430. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  159431. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  159432. /* Aside from the specific data retained from APPn markers known to the
  159433. * library, the uninterpreted contents of any or all APPn and COM markers
  159434. * can be saved in a list for examination by the application.
  159435. */
  159436. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  159437. /* Remaining fields are known throughout decompressor, but generally
  159438. * should not be touched by a surrounding application.
  159439. */
  159440. /*
  159441. * These fields are computed during decompression startup
  159442. */
  159443. int max_h_samp_factor; /* largest h_samp_factor */
  159444. int max_v_samp_factor; /* largest v_samp_factor */
  159445. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  159446. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  159447. /* The coefficient controller's input and output progress is measured in
  159448. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  159449. * in fully interleaved JPEG scans, but are used whether the scan is
  159450. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  159451. * rows of each component. Therefore, the IDCT output contains
  159452. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  159453. */
  159454. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  159455. /*
  159456. * These fields are valid during any one scan.
  159457. * They describe the components and MCUs actually appearing in the scan.
  159458. * Note that the decompressor output side must not use these fields.
  159459. */
  159460. int comps_in_scan; /* # of JPEG components in this scan */
  159461. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  159462. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  159463. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  159464. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  159465. int blocks_in_MCU; /* # of DCT blocks per MCU */
  159466. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  159467. /* MCU_membership[i] is index in cur_comp_info of component owning */
  159468. /* i'th block in an MCU */
  159469. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  159470. /* This field is shared between entropy decoder and marker parser.
  159471. * It is either zero or the code of a JPEG marker that has been
  159472. * read from the data source, but has not yet been processed.
  159473. */
  159474. int unread_marker;
  159475. /*
  159476. * Links to decompression subobjects (methods, private variables of modules)
  159477. */
  159478. struct jpeg_decomp_master * master;
  159479. struct jpeg_d_main_controller * main;
  159480. struct jpeg_d_coef_controller * coef;
  159481. struct jpeg_d_post_controller * post;
  159482. struct jpeg_input_controller * inputctl;
  159483. struct jpeg_marker_reader * marker;
  159484. struct jpeg_entropy_decoder * entropy;
  159485. struct jpeg_inverse_dct * idct;
  159486. struct jpeg_upsampler * upsample;
  159487. struct jpeg_color_deconverter * cconvert;
  159488. struct jpeg_color_quantizer * cquantize;
  159489. };
  159490. /* "Object" declarations for JPEG modules that may be supplied or called
  159491. * directly by the surrounding application.
  159492. * As with all objects in the JPEG library, these structs only define the
  159493. * publicly visible methods and state variables of a module. Additional
  159494. * private fields may exist after the public ones.
  159495. */
  159496. /* Error handler object */
  159497. struct jpeg_error_mgr {
  159498. /* Error exit handler: does not return to caller */
  159499. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  159500. /* Conditionally emit a trace or warning message */
  159501. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  159502. /* Routine that actually outputs a trace or error message */
  159503. JMETHOD(void, output_message, (j_common_ptr cinfo));
  159504. /* Format a message string for the most recent JPEG error or message */
  159505. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  159506. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  159507. /* Reset error state variables at start of a new image */
  159508. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  159509. /* The message ID code and any parameters are saved here.
  159510. * A message can have one string parameter or up to 8 int parameters.
  159511. */
  159512. int msg_code;
  159513. #define JMSG_STR_PARM_MAX 80
  159514. union {
  159515. int i[8];
  159516. char s[JMSG_STR_PARM_MAX];
  159517. } msg_parm;
  159518. /* Standard state variables for error facility */
  159519. int trace_level; /* max msg_level that will be displayed */
  159520. /* For recoverable corrupt-data errors, we emit a warning message,
  159521. * but keep going unless emit_message chooses to abort. emit_message
  159522. * should count warnings in num_warnings. The surrounding application
  159523. * can check for bad data by seeing if num_warnings is nonzero at the
  159524. * end of processing.
  159525. */
  159526. long num_warnings; /* number of corrupt-data warnings */
  159527. /* These fields point to the table(s) of error message strings.
  159528. * An application can change the table pointer to switch to a different
  159529. * message list (typically, to change the language in which errors are
  159530. * reported). Some applications may wish to add additional error codes
  159531. * that will be handled by the JPEG library error mechanism; the second
  159532. * table pointer is used for this purpose.
  159533. *
  159534. * First table includes all errors generated by JPEG library itself.
  159535. * Error code 0 is reserved for a "no such error string" message.
  159536. */
  159537. const char * const * jpeg_message_table; /* Library errors */
  159538. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  159539. /* Second table can be added by application (see cjpeg/djpeg for example).
  159540. * It contains strings numbered first_addon_message..last_addon_message.
  159541. */
  159542. const char * const * addon_message_table; /* Non-library errors */
  159543. int first_addon_message; /* code for first string in addon table */
  159544. int last_addon_message; /* code for last string in addon table */
  159545. };
  159546. /* Progress monitor object */
  159547. struct jpeg_progress_mgr {
  159548. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  159549. long pass_counter; /* work units completed in this pass */
  159550. long pass_limit; /* total number of work units in this pass */
  159551. int completed_passes; /* passes completed so far */
  159552. int total_passes; /* total number of passes expected */
  159553. };
  159554. /* Data destination object for compression */
  159555. struct jpeg_destination_mgr {
  159556. JOCTET * next_output_byte; /* => next byte to write in buffer */
  159557. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  159558. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  159559. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  159560. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  159561. };
  159562. /* Data source object for decompression */
  159563. struct jpeg_source_mgr {
  159564. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  159565. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  159566. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  159567. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  159568. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  159569. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  159570. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  159571. };
  159572. /* Memory manager object.
  159573. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  159574. * and "really big" objects (virtual arrays with backing store if needed).
  159575. * The memory manager does not allow individual objects to be freed; rather,
  159576. * each created object is assigned to a pool, and whole pools can be freed
  159577. * at once. This is faster and more convenient than remembering exactly what
  159578. * to free, especially where malloc()/free() are not too speedy.
  159579. * NB: alloc routines never return NULL. They exit to error_exit if not
  159580. * successful.
  159581. */
  159582. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  159583. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  159584. #define JPOOL_NUMPOOLS 2
  159585. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  159586. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  159587. struct jpeg_memory_mgr {
  159588. /* Method pointers */
  159589. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  159590. size_t sizeofobject));
  159591. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  159592. size_t sizeofobject));
  159593. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  159594. JDIMENSION samplesperrow,
  159595. JDIMENSION numrows));
  159596. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  159597. JDIMENSION blocksperrow,
  159598. JDIMENSION numrows));
  159599. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  159600. int pool_id,
  159601. boolean pre_zero,
  159602. JDIMENSION samplesperrow,
  159603. JDIMENSION numrows,
  159604. JDIMENSION maxaccess));
  159605. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  159606. int pool_id,
  159607. boolean pre_zero,
  159608. JDIMENSION blocksperrow,
  159609. JDIMENSION numrows,
  159610. JDIMENSION maxaccess));
  159611. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  159612. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  159613. jvirt_sarray_ptr ptr,
  159614. JDIMENSION start_row,
  159615. JDIMENSION num_rows,
  159616. boolean writable));
  159617. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  159618. jvirt_barray_ptr ptr,
  159619. JDIMENSION start_row,
  159620. JDIMENSION num_rows,
  159621. boolean writable));
  159622. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  159623. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  159624. /* Limit on memory allocation for this JPEG object. (Note that this is
  159625. * merely advisory, not a guaranteed maximum; it only affects the space
  159626. * used for virtual-array buffers.) May be changed by outer application
  159627. * after creating the JPEG object.
  159628. */
  159629. long max_memory_to_use;
  159630. /* Maximum allocation request accepted by alloc_large. */
  159631. long max_alloc_chunk;
  159632. };
  159633. /* Routine signature for application-supplied marker processing methods.
  159634. * Need not pass marker code since it is stored in cinfo->unread_marker.
  159635. */
  159636. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  159637. /* Declarations for routines called by application.
  159638. * The JPP macro hides prototype parameters from compilers that can't cope.
  159639. * Note JPP requires double parentheses.
  159640. */
  159641. #ifdef HAVE_PROTOTYPES
  159642. #define JPP(arglist) arglist
  159643. #else
  159644. #define JPP(arglist) ()
  159645. #endif
  159646. /* Short forms of external names for systems with brain-damaged linkers.
  159647. * We shorten external names to be unique in the first six letters, which
  159648. * is good enough for all known systems.
  159649. * (If your compiler itself needs names to be unique in less than 15
  159650. * characters, you are out of luck. Get a better compiler.)
  159651. */
  159652. #ifdef NEED_SHORT_EXTERNAL_NAMES
  159653. #define jpeg_std_error jStdError
  159654. #define jpeg_CreateCompress jCreaCompress
  159655. #define jpeg_CreateDecompress jCreaDecompress
  159656. #define jpeg_destroy_compress jDestCompress
  159657. #define jpeg_destroy_decompress jDestDecompress
  159658. #define jpeg_stdio_dest jStdDest
  159659. #define jpeg_stdio_src jStdSrc
  159660. #define jpeg_set_defaults jSetDefaults
  159661. #define jpeg_set_colorspace jSetColorspace
  159662. #define jpeg_default_colorspace jDefColorspace
  159663. #define jpeg_set_quality jSetQuality
  159664. #define jpeg_set_linear_quality jSetLQuality
  159665. #define jpeg_add_quant_table jAddQuantTable
  159666. #define jpeg_quality_scaling jQualityScaling
  159667. #define jpeg_simple_progression jSimProgress
  159668. #define jpeg_suppress_tables jSuppressTables
  159669. #define jpeg_alloc_quant_table jAlcQTable
  159670. #define jpeg_alloc_huff_table jAlcHTable
  159671. #define jpeg_start_compress jStrtCompress
  159672. #define jpeg_write_scanlines jWrtScanlines
  159673. #define jpeg_finish_compress jFinCompress
  159674. #define jpeg_write_raw_data jWrtRawData
  159675. #define jpeg_write_marker jWrtMarker
  159676. #define jpeg_write_m_header jWrtMHeader
  159677. #define jpeg_write_m_byte jWrtMByte
  159678. #define jpeg_write_tables jWrtTables
  159679. #define jpeg_read_header jReadHeader
  159680. #define jpeg_start_decompress jStrtDecompress
  159681. #define jpeg_read_scanlines jReadScanlines
  159682. #define jpeg_finish_decompress jFinDecompress
  159683. #define jpeg_read_raw_data jReadRawData
  159684. #define jpeg_has_multiple_scans jHasMultScn
  159685. #define jpeg_start_output jStrtOutput
  159686. #define jpeg_finish_output jFinOutput
  159687. #define jpeg_input_complete jInComplete
  159688. #define jpeg_new_colormap jNewCMap
  159689. #define jpeg_consume_input jConsumeInput
  159690. #define jpeg_calc_output_dimensions jCalcDimensions
  159691. #define jpeg_save_markers jSaveMarkers
  159692. #define jpeg_set_marker_processor jSetMarker
  159693. #define jpeg_read_coefficients jReadCoefs
  159694. #define jpeg_write_coefficients jWrtCoefs
  159695. #define jpeg_copy_critical_parameters jCopyCrit
  159696. #define jpeg_abort_compress jAbrtCompress
  159697. #define jpeg_abort_decompress jAbrtDecompress
  159698. #define jpeg_abort jAbort
  159699. #define jpeg_destroy jDestroy
  159700. #define jpeg_resync_to_restart jResyncRestart
  159701. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  159702. /* Default error-management setup */
  159703. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  159704. JPP((struct jpeg_error_mgr * err));
  159705. /* Initialization of JPEG compression objects.
  159706. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  159707. * names that applications should call. These expand to calls on
  159708. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  159709. * passed for version mismatch checking.
  159710. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  159711. */
  159712. #define jpeg_create_compress(cinfo) \
  159713. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  159714. (size_t) sizeof(struct jpeg_compress_struct))
  159715. #define jpeg_create_decompress(cinfo) \
  159716. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  159717. (size_t) sizeof(struct jpeg_decompress_struct))
  159718. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  159719. int version, size_t structsize));
  159720. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  159721. int version, size_t structsize));
  159722. /* Destruction of JPEG compression objects */
  159723. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  159724. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  159725. /* Standard data source and destination managers: stdio streams. */
  159726. /* Caller is responsible for opening the file before and closing after. */
  159727. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  159728. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  159729. /* Default parameter setup for compression */
  159730. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  159731. /* Compression parameter setup aids */
  159732. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  159733. J_COLOR_SPACE colorspace));
  159734. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  159735. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  159736. boolean force_baseline));
  159737. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  159738. int scale_factor,
  159739. boolean force_baseline));
  159740. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  159741. const unsigned int *basic_table,
  159742. int scale_factor,
  159743. boolean force_baseline));
  159744. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  159745. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  159746. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  159747. boolean suppress));
  159748. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  159749. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  159750. /* Main entry points for compression */
  159751. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  159752. boolean write_all_tables));
  159753. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  159754. JSAMPARRAY scanlines,
  159755. JDIMENSION num_lines));
  159756. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  159757. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  159758. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  159759. JSAMPIMAGE data,
  159760. JDIMENSION num_lines));
  159761. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  159762. EXTERN(void) jpeg_write_marker
  159763. JPP((j_compress_ptr cinfo, int marker,
  159764. const JOCTET * dataptr, unsigned int datalen));
  159765. /* Same, but piecemeal. */
  159766. EXTERN(void) jpeg_write_m_header
  159767. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  159768. EXTERN(void) jpeg_write_m_byte
  159769. JPP((j_compress_ptr cinfo, int val));
  159770. /* Alternate compression function: just write an abbreviated table file */
  159771. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  159772. /* Decompression startup: read start of JPEG datastream to see what's there */
  159773. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  159774. boolean require_image));
  159775. /* Return value is one of: */
  159776. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  159777. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  159778. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  159779. /* If you pass require_image = TRUE (normal case), you need not check for
  159780. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  159781. * JPEG_SUSPENDED is only possible if you use a data source module that can
  159782. * give a suspension return (the stdio source module doesn't).
  159783. */
  159784. /* Main entry points for decompression */
  159785. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  159786. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  159787. JSAMPARRAY scanlines,
  159788. JDIMENSION max_lines));
  159789. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  159790. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  159791. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  159792. JSAMPIMAGE data,
  159793. JDIMENSION max_lines));
  159794. /* Additional entry points for buffered-image mode. */
  159795. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  159796. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  159797. int scan_number));
  159798. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  159799. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  159800. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  159801. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  159802. /* Return value is one of: */
  159803. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  159804. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  159805. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  159806. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  159807. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  159808. /* Precalculate output dimensions for current decompression parameters. */
  159809. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  159810. /* Control saving of COM and APPn markers into marker_list. */
  159811. EXTERN(void) jpeg_save_markers
  159812. JPP((j_decompress_ptr cinfo, int marker_code,
  159813. unsigned int length_limit));
  159814. /* Install a special processing method for COM or APPn markers. */
  159815. EXTERN(void) jpeg_set_marker_processor
  159816. JPP((j_decompress_ptr cinfo, int marker_code,
  159817. jpeg_marker_parser_method routine));
  159818. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  159819. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  159820. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  159821. jvirt_barray_ptr * coef_arrays));
  159822. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  159823. j_compress_ptr dstinfo));
  159824. /* If you choose to abort compression or decompression before completing
  159825. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  159826. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  159827. * if you're done with the JPEG object, but if you want to clean it up and
  159828. * reuse it, call this:
  159829. */
  159830. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  159831. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  159832. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  159833. * flavor of JPEG object. These may be more convenient in some places.
  159834. */
  159835. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  159836. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  159837. /* Default restart-marker-resync procedure for use by data source modules */
  159838. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  159839. int desired));
  159840. /* These marker codes are exported since applications and data source modules
  159841. * are likely to want to use them.
  159842. */
  159843. #define JPEG_RST0 0xD0 /* RST0 marker code */
  159844. #define JPEG_EOI 0xD9 /* EOI marker code */
  159845. #define JPEG_APP0 0xE0 /* APP0 marker code */
  159846. #define JPEG_COM 0xFE /* COM marker code */
  159847. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  159848. * for structure definitions that are never filled in, keep it quiet by
  159849. * supplying dummy definitions for the various substructures.
  159850. */
  159851. #ifdef INCOMPLETE_TYPES_BROKEN
  159852. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  159853. struct jvirt_sarray_control { long dummy; };
  159854. struct jvirt_barray_control { long dummy; };
  159855. struct jpeg_comp_master { long dummy; };
  159856. struct jpeg_c_main_controller { long dummy; };
  159857. struct jpeg_c_prep_controller { long dummy; };
  159858. struct jpeg_c_coef_controller { long dummy; };
  159859. struct jpeg_marker_writer { long dummy; };
  159860. struct jpeg_color_converter { long dummy; };
  159861. struct jpeg_downsampler { long dummy; };
  159862. struct jpeg_forward_dct { long dummy; };
  159863. struct jpeg_entropy_encoder { long dummy; };
  159864. struct jpeg_decomp_master { long dummy; };
  159865. struct jpeg_d_main_controller { long dummy; };
  159866. struct jpeg_d_coef_controller { long dummy; };
  159867. struct jpeg_d_post_controller { long dummy; };
  159868. struct jpeg_input_controller { long dummy; };
  159869. struct jpeg_marker_reader { long dummy; };
  159870. struct jpeg_entropy_decoder { long dummy; };
  159871. struct jpeg_inverse_dct { long dummy; };
  159872. struct jpeg_upsampler { long dummy; };
  159873. struct jpeg_color_deconverter { long dummy; };
  159874. struct jpeg_color_quantizer { long dummy; };
  159875. #endif /* JPEG_INTERNALS */
  159876. #endif /* INCOMPLETE_TYPES_BROKEN */
  159877. /*
  159878. * The JPEG library modules define JPEG_INTERNALS before including this file.
  159879. * The internal structure declarations are read only when that is true.
  159880. * Applications using the library should not include jpegint.h, but may wish
  159881. * to include jerror.h.
  159882. */
  159883. #ifdef JPEG_INTERNALS
  159884. /*** Start of inlined file: jpegint.h ***/
  159885. /* Declarations for both compression & decompression */
  159886. typedef enum { /* Operating modes for buffer controllers */
  159887. JBUF_PASS_THRU, /* Plain stripwise operation */
  159888. /* Remaining modes require a full-image buffer to have been created */
  159889. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  159890. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  159891. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  159892. } J_BUF_MODE;
  159893. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  159894. #define CSTATE_START 100 /* after create_compress */
  159895. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  159896. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  159897. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  159898. #define DSTATE_START 200 /* after create_decompress */
  159899. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  159900. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  159901. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  159902. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  159903. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  159904. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  159905. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  159906. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  159907. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  159908. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  159909. /* Declarations for compression modules */
  159910. /* Master control module */
  159911. struct jpeg_comp_master {
  159912. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  159913. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  159914. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  159915. /* State variables made visible to other modules */
  159916. boolean call_pass_startup; /* True if pass_startup must be called */
  159917. boolean is_last_pass; /* True during last pass */
  159918. };
  159919. /* Main buffer control (downsampled-data buffer) */
  159920. struct jpeg_c_main_controller {
  159921. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  159922. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  159923. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  159924. JDIMENSION in_rows_avail));
  159925. };
  159926. /* Compression preprocessing (downsampling input buffer control) */
  159927. struct jpeg_c_prep_controller {
  159928. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  159929. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  159930. JSAMPARRAY input_buf,
  159931. JDIMENSION *in_row_ctr,
  159932. JDIMENSION in_rows_avail,
  159933. JSAMPIMAGE output_buf,
  159934. JDIMENSION *out_row_group_ctr,
  159935. JDIMENSION out_row_groups_avail));
  159936. };
  159937. /* Coefficient buffer control */
  159938. struct jpeg_c_coef_controller {
  159939. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  159940. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  159941. JSAMPIMAGE input_buf));
  159942. };
  159943. /* Colorspace conversion */
  159944. struct jpeg_color_converter {
  159945. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  159946. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  159947. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  159948. JDIMENSION output_row, int num_rows));
  159949. };
  159950. /* Downsampling */
  159951. struct jpeg_downsampler {
  159952. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  159953. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  159954. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  159955. JSAMPIMAGE output_buf,
  159956. JDIMENSION out_row_group_index));
  159957. boolean need_context_rows; /* TRUE if need rows above & below */
  159958. };
  159959. /* Forward DCT (also controls coefficient quantization) */
  159960. struct jpeg_forward_dct {
  159961. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  159962. /* perhaps this should be an array??? */
  159963. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  159964. jpeg_component_info * compptr,
  159965. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  159966. JDIMENSION start_row, JDIMENSION start_col,
  159967. JDIMENSION num_blocks));
  159968. };
  159969. /* Entropy encoding */
  159970. struct jpeg_entropy_encoder {
  159971. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  159972. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  159973. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  159974. };
  159975. /* Marker writing */
  159976. struct jpeg_marker_writer {
  159977. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  159978. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  159979. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  159980. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  159981. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  159982. /* These routines are exported to allow insertion of extra markers */
  159983. /* Probably only COM and APPn markers should be written this way */
  159984. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  159985. unsigned int datalen));
  159986. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  159987. };
  159988. /* Declarations for decompression modules */
  159989. /* Master control module */
  159990. struct jpeg_decomp_master {
  159991. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  159992. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  159993. /* State variables made visible to other modules */
  159994. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  159995. };
  159996. /* Input control module */
  159997. struct jpeg_input_controller {
  159998. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  159999. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  160000. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  160001. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  160002. /* State variables made visible to other modules */
  160003. boolean has_multiple_scans; /* True if file has multiple scans */
  160004. boolean eoi_reached; /* True when EOI has been consumed */
  160005. };
  160006. /* Main buffer control (downsampled-data buffer) */
  160007. struct jpeg_d_main_controller {
  160008. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  160009. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  160010. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  160011. JDIMENSION out_rows_avail));
  160012. };
  160013. /* Coefficient buffer control */
  160014. struct jpeg_d_coef_controller {
  160015. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  160016. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  160017. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  160018. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  160019. JSAMPIMAGE output_buf));
  160020. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  160021. jvirt_barray_ptr *coef_arrays;
  160022. };
  160023. /* Decompression postprocessing (color quantization buffer control) */
  160024. struct jpeg_d_post_controller {
  160025. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  160026. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  160027. JSAMPIMAGE input_buf,
  160028. JDIMENSION *in_row_group_ctr,
  160029. JDIMENSION in_row_groups_avail,
  160030. JSAMPARRAY output_buf,
  160031. JDIMENSION *out_row_ctr,
  160032. JDIMENSION out_rows_avail));
  160033. };
  160034. /* Marker reading & parsing */
  160035. struct jpeg_marker_reader {
  160036. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  160037. /* Read markers until SOS or EOI.
  160038. * Returns same codes as are defined for jpeg_consume_input:
  160039. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  160040. */
  160041. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  160042. /* Read a restart marker --- exported for use by entropy decoder only */
  160043. jpeg_marker_parser_method read_restart_marker;
  160044. /* State of marker reader --- nominally internal, but applications
  160045. * supplying COM or APPn handlers might like to know the state.
  160046. */
  160047. boolean saw_SOI; /* found SOI? */
  160048. boolean saw_SOF; /* found SOF? */
  160049. int next_restart_num; /* next restart number expected (0-7) */
  160050. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  160051. };
  160052. /* Entropy decoding */
  160053. struct jpeg_entropy_decoder {
  160054. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160055. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  160056. JBLOCKROW *MCU_data));
  160057. /* This is here to share code between baseline and progressive decoders; */
  160058. /* other modules probably should not use it */
  160059. boolean insufficient_data; /* set TRUE after emitting warning */
  160060. };
  160061. /* Inverse DCT (also performs dequantization) */
  160062. typedef JMETHOD(void, inverse_DCT_method_ptr,
  160063. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  160064. JCOEFPTR coef_block,
  160065. JSAMPARRAY output_buf, JDIMENSION output_col));
  160066. struct jpeg_inverse_dct {
  160067. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160068. /* It is useful to allow each component to have a separate IDCT method. */
  160069. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  160070. };
  160071. /* Upsampling (note that upsampler must also call color converter) */
  160072. struct jpeg_upsampler {
  160073. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160074. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  160075. JSAMPIMAGE input_buf,
  160076. JDIMENSION *in_row_group_ctr,
  160077. JDIMENSION in_row_groups_avail,
  160078. JSAMPARRAY output_buf,
  160079. JDIMENSION *out_row_ctr,
  160080. JDIMENSION out_rows_avail));
  160081. boolean need_context_rows; /* TRUE if need rows above & below */
  160082. };
  160083. /* Colorspace conversion */
  160084. struct jpeg_color_deconverter {
  160085. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160086. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  160087. JSAMPIMAGE input_buf, JDIMENSION input_row,
  160088. JSAMPARRAY output_buf, int num_rows));
  160089. };
  160090. /* Color quantization or color precision reduction */
  160091. struct jpeg_color_quantizer {
  160092. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  160093. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  160094. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  160095. int num_rows));
  160096. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  160097. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  160098. };
  160099. /* Miscellaneous useful macros */
  160100. #undef MAX
  160101. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  160102. #undef MIN
  160103. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  160104. /* We assume that right shift corresponds to signed division by 2 with
  160105. * rounding towards minus infinity. This is correct for typical "arithmetic
  160106. * shift" instructions that shift in copies of the sign bit. But some
  160107. * C compilers implement >> with an unsigned shift. For these machines you
  160108. * must define RIGHT_SHIFT_IS_UNSIGNED.
  160109. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  160110. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  160111. * included in the variables of any routine using RIGHT_SHIFT.
  160112. */
  160113. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  160114. #define SHIFT_TEMPS INT32 shift_temp;
  160115. #define RIGHT_SHIFT(x,shft) \
  160116. ((shift_temp = (x)) < 0 ? \
  160117. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  160118. (shift_temp >> (shft)))
  160119. #else
  160120. #define SHIFT_TEMPS
  160121. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  160122. #endif
  160123. /* Short forms of external names for systems with brain-damaged linkers. */
  160124. #ifdef NEED_SHORT_EXTERNAL_NAMES
  160125. #define jinit_compress_master jICompress
  160126. #define jinit_c_master_control jICMaster
  160127. #define jinit_c_main_controller jICMainC
  160128. #define jinit_c_prep_controller jICPrepC
  160129. #define jinit_c_coef_controller jICCoefC
  160130. #define jinit_color_converter jICColor
  160131. #define jinit_downsampler jIDownsampler
  160132. #define jinit_forward_dct jIFDCT
  160133. #define jinit_huff_encoder jIHEncoder
  160134. #define jinit_phuff_encoder jIPHEncoder
  160135. #define jinit_marker_writer jIMWriter
  160136. #define jinit_master_decompress jIDMaster
  160137. #define jinit_d_main_controller jIDMainC
  160138. #define jinit_d_coef_controller jIDCoefC
  160139. #define jinit_d_post_controller jIDPostC
  160140. #define jinit_input_controller jIInCtlr
  160141. #define jinit_marker_reader jIMReader
  160142. #define jinit_huff_decoder jIHDecoder
  160143. #define jinit_phuff_decoder jIPHDecoder
  160144. #define jinit_inverse_dct jIIDCT
  160145. #define jinit_upsampler jIUpsampler
  160146. #define jinit_color_deconverter jIDColor
  160147. #define jinit_1pass_quantizer jI1Quant
  160148. #define jinit_2pass_quantizer jI2Quant
  160149. #define jinit_merged_upsampler jIMUpsampler
  160150. #define jinit_memory_mgr jIMemMgr
  160151. #define jdiv_round_up jDivRound
  160152. #define jround_up jRound
  160153. #define jcopy_sample_rows jCopySamples
  160154. #define jcopy_block_row jCopyBlocks
  160155. #define jzero_far jZeroFar
  160156. #define jpeg_zigzag_order jZIGTable
  160157. #define jpeg_natural_order jZAGTable
  160158. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  160159. /* Compression module initialization routines */
  160160. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  160161. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  160162. boolean transcode_only));
  160163. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  160164. boolean need_full_buffer));
  160165. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  160166. boolean need_full_buffer));
  160167. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  160168. boolean need_full_buffer));
  160169. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  160170. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  160171. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  160172. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  160173. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  160174. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  160175. /* Decompression module initialization routines */
  160176. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  160177. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  160178. boolean need_full_buffer));
  160179. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  160180. boolean need_full_buffer));
  160181. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  160182. boolean need_full_buffer));
  160183. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  160184. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  160185. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  160186. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  160187. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  160188. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  160189. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  160190. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  160191. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  160192. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  160193. /* Memory manager initialization */
  160194. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  160195. /* Utility routines in jutils.c */
  160196. EXTERN(long) jdiv_round_up JPP((long a, long b));
  160197. EXTERN(long) jround_up JPP((long a, long b));
  160198. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  160199. JSAMPARRAY output_array, int dest_row,
  160200. int num_rows, JDIMENSION num_cols));
  160201. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  160202. JDIMENSION num_blocks));
  160203. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  160204. /* Constant tables in jutils.c */
  160205. #if 0 /* This table is not actually needed in v6a */
  160206. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  160207. #endif
  160208. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  160209. /* Suppress undefined-structure complaints if necessary. */
  160210. #ifdef INCOMPLETE_TYPES_BROKEN
  160211. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  160212. struct jvirt_sarray_control { long dummy; };
  160213. struct jvirt_barray_control { long dummy; };
  160214. #endif
  160215. #endif /* INCOMPLETE_TYPES_BROKEN */
  160216. /*** End of inlined file: jpegint.h ***/
  160217. /* fetch private declarations */
  160218. /*** Start of inlined file: jerror.h ***/
  160219. /*
  160220. * To define the enum list of message codes, include this file without
  160221. * defining macro JMESSAGE. To create a message string table, include it
  160222. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  160223. */
  160224. #ifndef JMESSAGE
  160225. #ifndef JERROR_H
  160226. /* First time through, define the enum list */
  160227. #define JMAKE_ENUM_LIST
  160228. #else
  160229. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  160230. #define JMESSAGE(code,string)
  160231. #endif /* JERROR_H */
  160232. #endif /* JMESSAGE */
  160233. #ifdef JMAKE_ENUM_LIST
  160234. typedef enum {
  160235. #define JMESSAGE(code,string) code ,
  160236. #endif /* JMAKE_ENUM_LIST */
  160237. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  160238. /* For maintenance convenience, list is alphabetical by message code name */
  160239. JMESSAGE(JERR_ARITH_NOTIMPL,
  160240. "Sorry, there are legal restrictions on arithmetic coding")
  160241. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  160242. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  160243. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  160244. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  160245. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  160246. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  160247. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  160248. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  160249. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  160250. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  160251. JMESSAGE(JERR_BAD_LIB_VERSION,
  160252. "Wrong JPEG library version: library is %d, caller expects %d")
  160253. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  160254. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  160255. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  160256. JMESSAGE(JERR_BAD_PROGRESSION,
  160257. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  160258. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  160259. "Invalid progressive parameters at scan script entry %d")
  160260. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  160261. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  160262. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  160263. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  160264. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  160265. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  160266. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  160267. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  160268. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  160269. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  160270. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  160271. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  160272. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  160273. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  160274. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  160275. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  160276. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  160277. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  160278. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  160279. JMESSAGE(JERR_FILE_READ, "Input file read error")
  160280. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  160281. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  160282. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  160283. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  160284. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  160285. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  160286. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  160287. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  160288. "Cannot transcode due to multiple use of quantization table %d")
  160289. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  160290. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  160291. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  160292. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  160293. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  160294. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  160295. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  160296. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  160297. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  160298. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  160299. JMESSAGE(JERR_QUANT_COMPONENTS,
  160300. "Cannot quantize more than %d color components")
  160301. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  160302. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  160303. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  160304. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  160305. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  160306. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  160307. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  160308. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  160309. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  160310. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  160311. JMESSAGE(JERR_TFILE_WRITE,
  160312. "Write failed on temporary file --- out of disk space?")
  160313. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  160314. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  160315. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  160316. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  160317. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  160318. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  160319. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  160320. JMESSAGE(JMSG_VERSION, JVERSION)
  160321. JMESSAGE(JTRC_16BIT_TABLES,
  160322. "Caution: quantization tables are too coarse for baseline JPEG")
  160323. JMESSAGE(JTRC_ADOBE,
  160324. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  160325. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  160326. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  160327. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  160328. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  160329. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  160330. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  160331. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  160332. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  160333. JMESSAGE(JTRC_EOI, "End Of Image")
  160334. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  160335. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  160336. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  160337. "Warning: thumbnail image size does not match data length %u")
  160338. JMESSAGE(JTRC_JFIF_EXTENSION,
  160339. "JFIF extension marker: type 0x%02x, length %u")
  160340. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  160341. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  160342. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  160343. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  160344. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  160345. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  160346. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  160347. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  160348. JMESSAGE(JTRC_RST, "RST%d")
  160349. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  160350. "Smoothing not supported with nonstandard sampling ratios")
  160351. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  160352. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  160353. JMESSAGE(JTRC_SOI, "Start of Image")
  160354. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  160355. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  160356. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  160357. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  160358. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  160359. JMESSAGE(JTRC_THUMB_JPEG,
  160360. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  160361. JMESSAGE(JTRC_THUMB_PALETTE,
  160362. "JFIF extension marker: palette thumbnail image, length %u")
  160363. JMESSAGE(JTRC_THUMB_RGB,
  160364. "JFIF extension marker: RGB thumbnail image, length %u")
  160365. JMESSAGE(JTRC_UNKNOWN_IDS,
  160366. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  160367. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  160368. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  160369. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  160370. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  160371. "Inconsistent progression sequence for component %d coefficient %d")
  160372. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  160373. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  160374. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  160375. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  160376. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  160377. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  160378. JMESSAGE(JWRN_MUST_RESYNC,
  160379. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  160380. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  160381. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  160382. #ifdef JMAKE_ENUM_LIST
  160383. JMSG_LASTMSGCODE
  160384. } J_MESSAGE_CODE;
  160385. #undef JMAKE_ENUM_LIST
  160386. #endif /* JMAKE_ENUM_LIST */
  160387. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  160388. #undef JMESSAGE
  160389. #ifndef JERROR_H
  160390. #define JERROR_H
  160391. /* Macros to simplify using the error and trace message stuff */
  160392. /* The first parameter is either type of cinfo pointer */
  160393. /* Fatal errors (print message and exit) */
  160394. #define ERREXIT(cinfo,code) \
  160395. ((cinfo)->err->msg_code = (code), \
  160396. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160397. #define ERREXIT1(cinfo,code,p1) \
  160398. ((cinfo)->err->msg_code = (code), \
  160399. (cinfo)->err->msg_parm.i[0] = (p1), \
  160400. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160401. #define ERREXIT2(cinfo,code,p1,p2) \
  160402. ((cinfo)->err->msg_code = (code), \
  160403. (cinfo)->err->msg_parm.i[0] = (p1), \
  160404. (cinfo)->err->msg_parm.i[1] = (p2), \
  160405. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160406. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  160407. ((cinfo)->err->msg_code = (code), \
  160408. (cinfo)->err->msg_parm.i[0] = (p1), \
  160409. (cinfo)->err->msg_parm.i[1] = (p2), \
  160410. (cinfo)->err->msg_parm.i[2] = (p3), \
  160411. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160412. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  160413. ((cinfo)->err->msg_code = (code), \
  160414. (cinfo)->err->msg_parm.i[0] = (p1), \
  160415. (cinfo)->err->msg_parm.i[1] = (p2), \
  160416. (cinfo)->err->msg_parm.i[2] = (p3), \
  160417. (cinfo)->err->msg_parm.i[3] = (p4), \
  160418. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160419. #define ERREXITS(cinfo,code,str) \
  160420. ((cinfo)->err->msg_code = (code), \
  160421. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  160422. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160423. #define MAKESTMT(stuff) do { stuff } while (0)
  160424. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  160425. #define WARNMS(cinfo,code) \
  160426. ((cinfo)->err->msg_code = (code), \
  160427. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  160428. #define WARNMS1(cinfo,code,p1) \
  160429. ((cinfo)->err->msg_code = (code), \
  160430. (cinfo)->err->msg_parm.i[0] = (p1), \
  160431. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  160432. #define WARNMS2(cinfo,code,p1,p2) \
  160433. ((cinfo)->err->msg_code = (code), \
  160434. (cinfo)->err->msg_parm.i[0] = (p1), \
  160435. (cinfo)->err->msg_parm.i[1] = (p2), \
  160436. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  160437. /* Informational/debugging messages */
  160438. #define TRACEMS(cinfo,lvl,code) \
  160439. ((cinfo)->err->msg_code = (code), \
  160440. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  160441. #define TRACEMS1(cinfo,lvl,code,p1) \
  160442. ((cinfo)->err->msg_code = (code), \
  160443. (cinfo)->err->msg_parm.i[0] = (p1), \
  160444. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  160445. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  160446. ((cinfo)->err->msg_code = (code), \
  160447. (cinfo)->err->msg_parm.i[0] = (p1), \
  160448. (cinfo)->err->msg_parm.i[1] = (p2), \
  160449. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  160450. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  160451. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  160452. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  160453. (cinfo)->err->msg_code = (code); \
  160454. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  160455. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  160456. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  160457. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  160458. (cinfo)->err->msg_code = (code); \
  160459. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  160460. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  160461. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  160462. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  160463. _mp[4] = (p5); \
  160464. (cinfo)->err->msg_code = (code); \
  160465. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  160466. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  160467. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  160468. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  160469. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  160470. (cinfo)->err->msg_code = (code); \
  160471. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  160472. #define TRACEMSS(cinfo,lvl,code,str) \
  160473. ((cinfo)->err->msg_code = (code), \
  160474. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  160475. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  160476. #endif /* JERROR_H */
  160477. /*** End of inlined file: jerror.h ***/
  160478. /* fetch error codes too */
  160479. #endif
  160480. #endif /* JPEGLIB_H */
  160481. /*** End of inlined file: jpeglib.h ***/
  160482. /*** Start of inlined file: jcapimin.c ***/
  160483. #define JPEG_INTERNALS
  160484. /*** Start of inlined file: jinclude.h ***/
  160485. /* Include auto-config file to find out which system include files we need. */
  160486. #ifndef __jinclude_h__
  160487. #define __jinclude_h__
  160488. /*** Start of inlined file: jconfig.h ***/
  160489. /* see jconfig.doc for explanations */
  160490. // disable all the warnings under MSVC
  160491. #ifdef _MSC_VER
  160492. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  160493. #endif
  160494. #ifdef __BORLANDC__
  160495. #pragma warn -8057
  160496. #pragma warn -8019
  160497. #pragma warn -8004
  160498. #pragma warn -8008
  160499. #endif
  160500. #define HAVE_PROTOTYPES
  160501. #define HAVE_UNSIGNED_CHAR
  160502. #define HAVE_UNSIGNED_SHORT
  160503. /* #define void char */
  160504. /* #define const */
  160505. #undef CHAR_IS_UNSIGNED
  160506. #define HAVE_STDDEF_H
  160507. #define HAVE_STDLIB_H
  160508. #undef NEED_BSD_STRINGS
  160509. #undef NEED_SYS_TYPES_H
  160510. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  160511. #undef NEED_SHORT_EXTERNAL_NAMES
  160512. #undef INCOMPLETE_TYPES_BROKEN
  160513. /* Define "boolean" as unsigned char, not int, per Windows custom */
  160514. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  160515. typedef unsigned char boolean;
  160516. #endif
  160517. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  160518. #ifdef JPEG_INTERNALS
  160519. #undef RIGHT_SHIFT_IS_UNSIGNED
  160520. #endif /* JPEG_INTERNALS */
  160521. #ifdef JPEG_CJPEG_DJPEG
  160522. #define BMP_SUPPORTED /* BMP image file format */
  160523. #define GIF_SUPPORTED /* GIF image file format */
  160524. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  160525. #undef RLE_SUPPORTED /* Utah RLE image file format */
  160526. #define TARGA_SUPPORTED /* Targa image file format */
  160527. #define TWO_FILE_COMMANDLINE /* optional */
  160528. #define USE_SETMODE /* Microsoft has setmode() */
  160529. #undef NEED_SIGNAL_CATCHER
  160530. #undef DONT_USE_B_MODE
  160531. #undef PROGRESS_REPORT /* optional */
  160532. #endif /* JPEG_CJPEG_DJPEG */
  160533. /*** End of inlined file: jconfig.h ***/
  160534. /* auto configuration options */
  160535. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  160536. /*
  160537. * We need the NULL macro and size_t typedef.
  160538. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  160539. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  160540. * pull in <sys/types.h> as well.
  160541. * Note that the core JPEG library does not require <stdio.h>;
  160542. * only the default error handler and data source/destination modules do.
  160543. * But we must pull it in because of the references to FILE in jpeglib.h.
  160544. * You can remove those references if you want to compile without <stdio.h>.
  160545. */
  160546. #ifdef HAVE_STDDEF_H
  160547. #include <stddef.h>
  160548. #endif
  160549. #ifdef HAVE_STDLIB_H
  160550. #include <stdlib.h>
  160551. #endif
  160552. #ifdef NEED_SYS_TYPES_H
  160553. #include <sys/types.h>
  160554. #endif
  160555. #include <stdio.h>
  160556. /*
  160557. * We need memory copying and zeroing functions, plus strncpy().
  160558. * ANSI and System V implementations declare these in <string.h>.
  160559. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  160560. * Some systems may declare memset and memcpy in <memory.h>.
  160561. *
  160562. * NOTE: we assume the size parameters to these functions are of type size_t.
  160563. * Change the casts in these macros if not!
  160564. */
  160565. #ifdef NEED_BSD_STRINGS
  160566. #include <strings.h>
  160567. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  160568. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  160569. #else /* not BSD, assume ANSI/SysV string lib */
  160570. #include <string.h>
  160571. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  160572. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  160573. #endif
  160574. /*
  160575. * In ANSI C, and indeed any rational implementation, size_t is also the
  160576. * type returned by sizeof(). However, it seems there are some irrational
  160577. * implementations out there, in which sizeof() returns an int even though
  160578. * size_t is defined as long or unsigned long. To ensure consistent results
  160579. * we always use this SIZEOF() macro in place of using sizeof() directly.
  160580. */
  160581. #define SIZEOF(object) ((size_t) sizeof(object))
  160582. /*
  160583. * The modules that use fread() and fwrite() always invoke them through
  160584. * these macros. On some systems you may need to twiddle the argument casts.
  160585. * CAUTION: argument order is different from underlying functions!
  160586. */
  160587. #define JFREAD(file,buf,sizeofbuf) \
  160588. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  160589. #define JFWRITE(file,buf,sizeofbuf) \
  160590. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  160591. typedef enum { /* JPEG marker codes */
  160592. M_SOF0 = 0xc0,
  160593. M_SOF1 = 0xc1,
  160594. M_SOF2 = 0xc2,
  160595. M_SOF3 = 0xc3,
  160596. M_SOF5 = 0xc5,
  160597. M_SOF6 = 0xc6,
  160598. M_SOF7 = 0xc7,
  160599. M_JPG = 0xc8,
  160600. M_SOF9 = 0xc9,
  160601. M_SOF10 = 0xca,
  160602. M_SOF11 = 0xcb,
  160603. M_SOF13 = 0xcd,
  160604. M_SOF14 = 0xce,
  160605. M_SOF15 = 0xcf,
  160606. M_DHT = 0xc4,
  160607. M_DAC = 0xcc,
  160608. M_RST0 = 0xd0,
  160609. M_RST1 = 0xd1,
  160610. M_RST2 = 0xd2,
  160611. M_RST3 = 0xd3,
  160612. M_RST4 = 0xd4,
  160613. M_RST5 = 0xd5,
  160614. M_RST6 = 0xd6,
  160615. M_RST7 = 0xd7,
  160616. M_SOI = 0xd8,
  160617. M_EOI = 0xd9,
  160618. M_SOS = 0xda,
  160619. M_DQT = 0xdb,
  160620. M_DNL = 0xdc,
  160621. M_DRI = 0xdd,
  160622. M_DHP = 0xde,
  160623. M_EXP = 0xdf,
  160624. M_APP0 = 0xe0,
  160625. M_APP1 = 0xe1,
  160626. M_APP2 = 0xe2,
  160627. M_APP3 = 0xe3,
  160628. M_APP4 = 0xe4,
  160629. M_APP5 = 0xe5,
  160630. M_APP6 = 0xe6,
  160631. M_APP7 = 0xe7,
  160632. M_APP8 = 0xe8,
  160633. M_APP9 = 0xe9,
  160634. M_APP10 = 0xea,
  160635. M_APP11 = 0xeb,
  160636. M_APP12 = 0xec,
  160637. M_APP13 = 0xed,
  160638. M_APP14 = 0xee,
  160639. M_APP15 = 0xef,
  160640. M_JPG0 = 0xf0,
  160641. M_JPG13 = 0xfd,
  160642. M_COM = 0xfe,
  160643. M_TEM = 0x01,
  160644. M_ERROR = 0x100
  160645. } JPEG_MARKER;
  160646. /*
  160647. * Figure F.12: extend sign bit.
  160648. * On some machines, a shift and add will be faster than a table lookup.
  160649. */
  160650. #ifdef AVOID_TABLES
  160651. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  160652. #else
  160653. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  160654. static const int extend_test[16] = /* entry n is 2**(n-1) */
  160655. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  160656. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  160657. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  160658. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  160659. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  160660. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  160661. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  160662. #endif /* AVOID_TABLES */
  160663. #endif
  160664. /*** End of inlined file: jinclude.h ***/
  160665. /*
  160666. * Initialization of a JPEG compression object.
  160667. * The error manager must already be set up (in case memory manager fails).
  160668. */
  160669. GLOBAL(void)
  160670. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  160671. {
  160672. int i;
  160673. /* Guard against version mismatches between library and caller. */
  160674. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  160675. if (version != JPEG_LIB_VERSION)
  160676. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  160677. if (structsize != SIZEOF(struct jpeg_compress_struct))
  160678. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  160679. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  160680. /* For debugging purposes, we zero the whole master structure.
  160681. * But the application has already set the err pointer, and may have set
  160682. * client_data, so we have to save and restore those fields.
  160683. * Note: if application hasn't set client_data, tools like Purify may
  160684. * complain here.
  160685. */
  160686. {
  160687. struct jpeg_error_mgr * err = cinfo->err;
  160688. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  160689. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  160690. cinfo->err = err;
  160691. cinfo->client_data = client_data;
  160692. }
  160693. cinfo->is_decompressor = FALSE;
  160694. /* Initialize a memory manager instance for this object */
  160695. jinit_memory_mgr((j_common_ptr) cinfo);
  160696. /* Zero out pointers to permanent structures. */
  160697. cinfo->progress = NULL;
  160698. cinfo->dest = NULL;
  160699. cinfo->comp_info = NULL;
  160700. for (i = 0; i < NUM_QUANT_TBLS; i++)
  160701. cinfo->quant_tbl_ptrs[i] = NULL;
  160702. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  160703. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  160704. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  160705. }
  160706. cinfo->script_space = NULL;
  160707. cinfo->input_gamma = 1.0; /* in case application forgets */
  160708. /* OK, I'm ready */
  160709. cinfo->global_state = CSTATE_START;
  160710. }
  160711. /*
  160712. * Destruction of a JPEG compression object
  160713. */
  160714. GLOBAL(void)
  160715. jpeg_destroy_compress (j_compress_ptr cinfo)
  160716. {
  160717. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  160718. }
  160719. /*
  160720. * Abort processing of a JPEG compression operation,
  160721. * but don't destroy the object itself.
  160722. */
  160723. GLOBAL(void)
  160724. jpeg_abort_compress (j_compress_ptr cinfo)
  160725. {
  160726. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  160727. }
  160728. /*
  160729. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  160730. * Marks all currently defined tables as already written (if suppress)
  160731. * or not written (if !suppress). This will control whether they get emitted
  160732. * by a subsequent jpeg_start_compress call.
  160733. *
  160734. * This routine is exported for use by applications that want to produce
  160735. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  160736. * since it is called by jpeg_start_compress, we put it here --- otherwise
  160737. * jcparam.o would be linked whether the application used it or not.
  160738. */
  160739. GLOBAL(void)
  160740. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  160741. {
  160742. int i;
  160743. JQUANT_TBL * qtbl;
  160744. JHUFF_TBL * htbl;
  160745. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  160746. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  160747. qtbl->sent_table = suppress;
  160748. }
  160749. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  160750. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  160751. htbl->sent_table = suppress;
  160752. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  160753. htbl->sent_table = suppress;
  160754. }
  160755. }
  160756. /*
  160757. * Finish JPEG compression.
  160758. *
  160759. * If a multipass operating mode was selected, this may do a great deal of
  160760. * work including most of the actual output.
  160761. */
  160762. GLOBAL(void)
  160763. jpeg_finish_compress (j_compress_ptr cinfo)
  160764. {
  160765. JDIMENSION iMCU_row;
  160766. if (cinfo->global_state == CSTATE_SCANNING ||
  160767. cinfo->global_state == CSTATE_RAW_OK) {
  160768. /* Terminate first pass */
  160769. if (cinfo->next_scanline < cinfo->image_height)
  160770. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  160771. (*cinfo->master->finish_pass) (cinfo);
  160772. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  160773. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160774. /* Perform any remaining passes */
  160775. while (! cinfo->master->is_last_pass) {
  160776. (*cinfo->master->prepare_for_pass) (cinfo);
  160777. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  160778. if (cinfo->progress != NULL) {
  160779. cinfo->progress->pass_counter = (long) iMCU_row;
  160780. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  160781. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  160782. }
  160783. /* We bypass the main controller and invoke coef controller directly;
  160784. * all work is being done from the coefficient buffer.
  160785. */
  160786. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  160787. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  160788. }
  160789. (*cinfo->master->finish_pass) (cinfo);
  160790. }
  160791. /* Write EOI, do final cleanup */
  160792. (*cinfo->marker->write_file_trailer) (cinfo);
  160793. (*cinfo->dest->term_destination) (cinfo);
  160794. /* We can use jpeg_abort to release memory and reset global_state */
  160795. jpeg_abort((j_common_ptr) cinfo);
  160796. }
  160797. /*
  160798. * Write a special marker.
  160799. * This is only recommended for writing COM or APPn markers.
  160800. * Must be called after jpeg_start_compress() and before
  160801. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  160802. */
  160803. GLOBAL(void)
  160804. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  160805. const JOCTET *dataptr, unsigned int datalen)
  160806. {
  160807. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  160808. if (cinfo->next_scanline != 0 ||
  160809. (cinfo->global_state != CSTATE_SCANNING &&
  160810. cinfo->global_state != CSTATE_RAW_OK &&
  160811. cinfo->global_state != CSTATE_WRCOEFS))
  160812. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160813. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  160814. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  160815. while (datalen--) {
  160816. (*write_marker_byte) (cinfo, *dataptr);
  160817. dataptr++;
  160818. }
  160819. }
  160820. /* Same, but piecemeal. */
  160821. GLOBAL(void)
  160822. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  160823. {
  160824. if (cinfo->next_scanline != 0 ||
  160825. (cinfo->global_state != CSTATE_SCANNING &&
  160826. cinfo->global_state != CSTATE_RAW_OK &&
  160827. cinfo->global_state != CSTATE_WRCOEFS))
  160828. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160829. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  160830. }
  160831. GLOBAL(void)
  160832. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  160833. {
  160834. (*cinfo->marker->write_marker_byte) (cinfo, val);
  160835. }
  160836. /*
  160837. * Alternate compression function: just write an abbreviated table file.
  160838. * Before calling this, all parameters and a data destination must be set up.
  160839. *
  160840. * To produce a pair of files containing abbreviated tables and abbreviated
  160841. * image data, one would proceed as follows:
  160842. *
  160843. * initialize JPEG object
  160844. * set JPEG parameters
  160845. * set destination to table file
  160846. * jpeg_write_tables(cinfo);
  160847. * set destination to image file
  160848. * jpeg_start_compress(cinfo, FALSE);
  160849. * write data...
  160850. * jpeg_finish_compress(cinfo);
  160851. *
  160852. * jpeg_write_tables has the side effect of marking all tables written
  160853. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  160854. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  160855. */
  160856. GLOBAL(void)
  160857. jpeg_write_tables (j_compress_ptr cinfo)
  160858. {
  160859. if (cinfo->global_state != CSTATE_START)
  160860. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160861. /* (Re)initialize error mgr and destination modules */
  160862. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  160863. (*cinfo->dest->init_destination) (cinfo);
  160864. /* Initialize the marker writer ... bit of a crock to do it here. */
  160865. jinit_marker_writer(cinfo);
  160866. /* Write them tables! */
  160867. (*cinfo->marker->write_tables_only) (cinfo);
  160868. /* And clean up. */
  160869. (*cinfo->dest->term_destination) (cinfo);
  160870. /*
  160871. * In library releases up through v6a, we called jpeg_abort() here to free
  160872. * any working memory allocated by the destination manager and marker
  160873. * writer. Some applications had a problem with that: they allocated space
  160874. * of their own from the library memory manager, and didn't want it to go
  160875. * away during write_tables. So now we do nothing. This will cause a
  160876. * memory leak if an app calls write_tables repeatedly without doing a full
  160877. * compression cycle or otherwise resetting the JPEG object. However, that
  160878. * seems less bad than unexpectedly freeing memory in the normal case.
  160879. * An app that prefers the old behavior can call jpeg_abort for itself after
  160880. * each call to jpeg_write_tables().
  160881. */
  160882. }
  160883. /*** End of inlined file: jcapimin.c ***/
  160884. /*** Start of inlined file: jcapistd.c ***/
  160885. #define JPEG_INTERNALS
  160886. /*
  160887. * Compression initialization.
  160888. * Before calling this, all parameters and a data destination must be set up.
  160889. *
  160890. * We require a write_all_tables parameter as a failsafe check when writing
  160891. * multiple datastreams from the same compression object. Since prior runs
  160892. * will have left all the tables marked sent_table=TRUE, a subsequent run
  160893. * would emit an abbreviated stream (no tables) by default. This may be what
  160894. * is wanted, but for safety's sake it should not be the default behavior:
  160895. * programmers should have to make a deliberate choice to emit abbreviated
  160896. * images. Therefore the documentation and examples should encourage people
  160897. * to pass write_all_tables=TRUE; then it will take active thought to do the
  160898. * wrong thing.
  160899. */
  160900. GLOBAL(void)
  160901. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  160902. {
  160903. if (cinfo->global_state != CSTATE_START)
  160904. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160905. if (write_all_tables)
  160906. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  160907. /* (Re)initialize error mgr and destination modules */
  160908. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  160909. (*cinfo->dest->init_destination) (cinfo);
  160910. /* Perform master selection of active modules */
  160911. jinit_compress_master(cinfo);
  160912. /* Set up for the first pass */
  160913. (*cinfo->master->prepare_for_pass) (cinfo);
  160914. /* Ready for application to drive first pass through jpeg_write_scanlines
  160915. * or jpeg_write_raw_data.
  160916. */
  160917. cinfo->next_scanline = 0;
  160918. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  160919. }
  160920. /*
  160921. * Write some scanlines of data to the JPEG compressor.
  160922. *
  160923. * The return value will be the number of lines actually written.
  160924. * This should be less than the supplied num_lines only in case that
  160925. * the data destination module has requested suspension of the compressor,
  160926. * or if more than image_height scanlines are passed in.
  160927. *
  160928. * Note: we warn about excess calls to jpeg_write_scanlines() since
  160929. * this likely signals an application programmer error. However,
  160930. * excess scanlines passed in the last valid call are *silently* ignored,
  160931. * so that the application need not adjust num_lines for end-of-image
  160932. * when using a multiple-scanline buffer.
  160933. */
  160934. GLOBAL(JDIMENSION)
  160935. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  160936. JDIMENSION num_lines)
  160937. {
  160938. JDIMENSION row_ctr, rows_left;
  160939. if (cinfo->global_state != CSTATE_SCANNING)
  160940. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160941. if (cinfo->next_scanline >= cinfo->image_height)
  160942. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  160943. /* Call progress monitor hook if present */
  160944. if (cinfo->progress != NULL) {
  160945. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  160946. cinfo->progress->pass_limit = (long) cinfo->image_height;
  160947. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  160948. }
  160949. /* Give master control module another chance if this is first call to
  160950. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  160951. * delayed so that application can write COM, etc, markers between
  160952. * jpeg_start_compress and jpeg_write_scanlines.
  160953. */
  160954. if (cinfo->master->call_pass_startup)
  160955. (*cinfo->master->pass_startup) (cinfo);
  160956. /* Ignore any extra scanlines at bottom of image. */
  160957. rows_left = cinfo->image_height - cinfo->next_scanline;
  160958. if (num_lines > rows_left)
  160959. num_lines = rows_left;
  160960. row_ctr = 0;
  160961. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  160962. cinfo->next_scanline += row_ctr;
  160963. return row_ctr;
  160964. }
  160965. /*
  160966. * Alternate entry point to write raw data.
  160967. * Processes exactly one iMCU row per call, unless suspended.
  160968. */
  160969. GLOBAL(JDIMENSION)
  160970. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  160971. JDIMENSION num_lines)
  160972. {
  160973. JDIMENSION lines_per_iMCU_row;
  160974. if (cinfo->global_state != CSTATE_RAW_OK)
  160975. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160976. if (cinfo->next_scanline >= cinfo->image_height) {
  160977. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  160978. return 0;
  160979. }
  160980. /* Call progress monitor hook if present */
  160981. if (cinfo->progress != NULL) {
  160982. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  160983. cinfo->progress->pass_limit = (long) cinfo->image_height;
  160984. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  160985. }
  160986. /* Give master control module another chance if this is first call to
  160987. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  160988. * delayed so that application can write COM, etc, markers between
  160989. * jpeg_start_compress and jpeg_write_raw_data.
  160990. */
  160991. if (cinfo->master->call_pass_startup)
  160992. (*cinfo->master->pass_startup) (cinfo);
  160993. /* Verify that at least one iMCU row has been passed. */
  160994. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  160995. if (num_lines < lines_per_iMCU_row)
  160996. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  160997. /* Directly compress the row. */
  160998. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  160999. /* If compressor did not consume the whole row, suspend processing. */
  161000. return 0;
  161001. }
  161002. /* OK, we processed one iMCU row. */
  161003. cinfo->next_scanline += lines_per_iMCU_row;
  161004. return lines_per_iMCU_row;
  161005. }
  161006. /*** End of inlined file: jcapistd.c ***/
  161007. /*** Start of inlined file: jccoefct.c ***/
  161008. #define JPEG_INTERNALS
  161009. /* We use a full-image coefficient buffer when doing Huffman optimization,
  161010. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  161011. * step is run during the first pass, and subsequent passes need only read
  161012. * the buffered coefficients.
  161013. */
  161014. #ifdef ENTROPY_OPT_SUPPORTED
  161015. #define FULL_COEF_BUFFER_SUPPORTED
  161016. #else
  161017. #ifdef C_MULTISCAN_FILES_SUPPORTED
  161018. #define FULL_COEF_BUFFER_SUPPORTED
  161019. #endif
  161020. #endif
  161021. /* Private buffer controller object */
  161022. typedef struct {
  161023. struct jpeg_c_coef_controller pub; /* public fields */
  161024. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  161025. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  161026. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  161027. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  161028. /* For single-pass compression, it's sufficient to buffer just one MCU
  161029. * (although this may prove a bit slow in practice). We allocate a
  161030. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  161031. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  161032. * it's not really very big; this is to keep the module interfaces unchanged
  161033. * when a large coefficient buffer is necessary.)
  161034. * In multi-pass modes, this array points to the current MCU's blocks
  161035. * within the virtual arrays.
  161036. */
  161037. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  161038. /* In multi-pass modes, we need a virtual block array for each component. */
  161039. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  161040. } my_coef_controller;
  161041. typedef my_coef_controller * my_coef_ptr;
  161042. /* Forward declarations */
  161043. METHODDEF(boolean) compress_data
  161044. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161045. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161046. METHODDEF(boolean) compress_first_pass
  161047. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161048. METHODDEF(boolean) compress_output
  161049. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161050. #endif
  161051. LOCAL(void)
  161052. start_iMCU_row (j_compress_ptr cinfo)
  161053. /* Reset within-iMCU-row counters for a new row */
  161054. {
  161055. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161056. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  161057. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  161058. * But at the bottom of the image, process only what's left.
  161059. */
  161060. if (cinfo->comps_in_scan > 1) {
  161061. coef->MCU_rows_per_iMCU_row = 1;
  161062. } else {
  161063. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  161064. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  161065. else
  161066. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  161067. }
  161068. coef->mcu_ctr = 0;
  161069. coef->MCU_vert_offset = 0;
  161070. }
  161071. /*
  161072. * Initialize for a processing pass.
  161073. */
  161074. METHODDEF(void)
  161075. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  161076. {
  161077. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161078. coef->iMCU_row_num = 0;
  161079. start_iMCU_row(cinfo);
  161080. switch (pass_mode) {
  161081. case JBUF_PASS_THRU:
  161082. if (coef->whole_image[0] != NULL)
  161083. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161084. coef->pub.compress_data = compress_data;
  161085. break;
  161086. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161087. case JBUF_SAVE_AND_PASS:
  161088. if (coef->whole_image[0] == NULL)
  161089. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161090. coef->pub.compress_data = compress_first_pass;
  161091. break;
  161092. case JBUF_CRANK_DEST:
  161093. if (coef->whole_image[0] == NULL)
  161094. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161095. coef->pub.compress_data = compress_output;
  161096. break;
  161097. #endif
  161098. default:
  161099. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161100. break;
  161101. }
  161102. }
  161103. /*
  161104. * Process some data in the single-pass case.
  161105. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161106. * per call, ie, v_samp_factor block rows for each component in the image.
  161107. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  161108. *
  161109. * NB: input_buf contains a plane for each component in image,
  161110. * which we index according to the component's SOF position.
  161111. */
  161112. METHODDEF(boolean)
  161113. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  161114. {
  161115. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161116. JDIMENSION MCU_col_num; /* index of current MCU within row */
  161117. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  161118. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  161119. int blkn, bi, ci, yindex, yoffset, blockcnt;
  161120. JDIMENSION ypos, xpos;
  161121. jpeg_component_info *compptr;
  161122. /* Loop to write as much as one whole iMCU row */
  161123. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  161124. yoffset++) {
  161125. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  161126. MCU_col_num++) {
  161127. /* Determine where data comes from in input_buf and do the DCT thing.
  161128. * Each call on forward_DCT processes a horizontal row of DCT blocks
  161129. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  161130. * sequentially. Dummy blocks at the right or bottom edge are filled in
  161131. * specially. The data in them does not matter for image reconstruction,
  161132. * so we fill them with values that will encode to the smallest amount of
  161133. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  161134. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  161135. */
  161136. blkn = 0;
  161137. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161138. compptr = cinfo->cur_comp_info[ci];
  161139. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  161140. : compptr->last_col_width;
  161141. xpos = MCU_col_num * compptr->MCU_sample_width;
  161142. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  161143. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  161144. if (coef->iMCU_row_num < last_iMCU_row ||
  161145. yoffset+yindex < compptr->last_row_height) {
  161146. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  161147. input_buf[compptr->component_index],
  161148. coef->MCU_buffer[blkn],
  161149. ypos, xpos, (JDIMENSION) blockcnt);
  161150. if (blockcnt < compptr->MCU_width) {
  161151. /* Create some dummy blocks at the right edge of the image. */
  161152. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  161153. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  161154. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  161155. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  161156. }
  161157. }
  161158. } else {
  161159. /* Create a row of dummy blocks at the bottom of the image. */
  161160. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  161161. compptr->MCU_width * SIZEOF(JBLOCK));
  161162. for (bi = 0; bi < compptr->MCU_width; bi++) {
  161163. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  161164. }
  161165. }
  161166. blkn += compptr->MCU_width;
  161167. ypos += DCTSIZE;
  161168. }
  161169. }
  161170. /* Try to write the MCU. In event of a suspension failure, we will
  161171. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  161172. */
  161173. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  161174. /* Suspension forced; update state counters and exit */
  161175. coef->MCU_vert_offset = yoffset;
  161176. coef->mcu_ctr = MCU_col_num;
  161177. return FALSE;
  161178. }
  161179. }
  161180. /* Completed an MCU row, but perhaps not an iMCU row */
  161181. coef->mcu_ctr = 0;
  161182. }
  161183. /* Completed the iMCU row, advance counters for next one */
  161184. coef->iMCU_row_num++;
  161185. start_iMCU_row(cinfo);
  161186. return TRUE;
  161187. }
  161188. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161189. /*
  161190. * Process some data in the first pass of a multi-pass case.
  161191. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161192. * per call, ie, v_samp_factor block rows for each component in the image.
  161193. * This amount of data is read from the source buffer, DCT'd and quantized,
  161194. * and saved into the virtual arrays. We also generate suitable dummy blocks
  161195. * as needed at the right and lower edges. (The dummy blocks are constructed
  161196. * in the virtual arrays, which have been padded appropriately.) This makes
  161197. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  161198. *
  161199. * We must also emit the data to the entropy encoder. This is conveniently
  161200. * done by calling compress_output() after we've loaded the current strip
  161201. * of the virtual arrays.
  161202. *
  161203. * NB: input_buf contains a plane for each component in image. All
  161204. * components are DCT'd and loaded into the virtual arrays in this pass.
  161205. * However, it may be that only a subset of the components are emitted to
  161206. * the entropy encoder during this first pass; be careful about looking
  161207. * at the scan-dependent variables (MCU dimensions, etc).
  161208. */
  161209. METHODDEF(boolean)
  161210. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  161211. {
  161212. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161213. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  161214. JDIMENSION blocks_across, MCUs_across, MCUindex;
  161215. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  161216. JCOEF lastDC;
  161217. jpeg_component_info *compptr;
  161218. JBLOCKARRAY buffer;
  161219. JBLOCKROW thisblockrow, lastblockrow;
  161220. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161221. ci++, compptr++) {
  161222. /* Align the virtual buffer for this component. */
  161223. buffer = (*cinfo->mem->access_virt_barray)
  161224. ((j_common_ptr) cinfo, coef->whole_image[ci],
  161225. coef->iMCU_row_num * compptr->v_samp_factor,
  161226. (JDIMENSION) compptr->v_samp_factor, TRUE);
  161227. /* Count non-dummy DCT block rows in this iMCU row. */
  161228. if (coef->iMCU_row_num < last_iMCU_row)
  161229. block_rows = compptr->v_samp_factor;
  161230. else {
  161231. /* NB: can't use last_row_height here, since may not be set! */
  161232. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  161233. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  161234. }
  161235. blocks_across = compptr->width_in_blocks;
  161236. h_samp_factor = compptr->h_samp_factor;
  161237. /* Count number of dummy blocks to be added at the right margin. */
  161238. ndummy = (int) (blocks_across % h_samp_factor);
  161239. if (ndummy > 0)
  161240. ndummy = h_samp_factor - ndummy;
  161241. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  161242. * on forward_DCT processes a complete horizontal row of DCT blocks.
  161243. */
  161244. for (block_row = 0; block_row < block_rows; block_row++) {
  161245. thisblockrow = buffer[block_row];
  161246. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  161247. input_buf[ci], thisblockrow,
  161248. (JDIMENSION) (block_row * DCTSIZE),
  161249. (JDIMENSION) 0, blocks_across);
  161250. if (ndummy > 0) {
  161251. /* Create dummy blocks at the right edge of the image. */
  161252. thisblockrow += blocks_across; /* => first dummy block */
  161253. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  161254. lastDC = thisblockrow[-1][0];
  161255. for (bi = 0; bi < ndummy; bi++) {
  161256. thisblockrow[bi][0] = lastDC;
  161257. }
  161258. }
  161259. }
  161260. /* If at end of image, create dummy block rows as needed.
  161261. * The tricky part here is that within each MCU, we want the DC values
  161262. * of the dummy blocks to match the last real block's DC value.
  161263. * This squeezes a few more bytes out of the resulting file...
  161264. */
  161265. if (coef->iMCU_row_num == last_iMCU_row) {
  161266. blocks_across += ndummy; /* include lower right corner */
  161267. MCUs_across = blocks_across / h_samp_factor;
  161268. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  161269. block_row++) {
  161270. thisblockrow = buffer[block_row];
  161271. lastblockrow = buffer[block_row-1];
  161272. jzero_far((void FAR *) thisblockrow,
  161273. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  161274. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  161275. lastDC = lastblockrow[h_samp_factor-1][0];
  161276. for (bi = 0; bi < h_samp_factor; bi++) {
  161277. thisblockrow[bi][0] = lastDC;
  161278. }
  161279. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  161280. lastblockrow += h_samp_factor;
  161281. }
  161282. }
  161283. }
  161284. }
  161285. /* NB: compress_output will increment iMCU_row_num if successful.
  161286. * A suspension return will result in redoing all the work above next time.
  161287. */
  161288. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  161289. return compress_output(cinfo, input_buf);
  161290. }
  161291. /*
  161292. * Process some data in subsequent passes of a multi-pass case.
  161293. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161294. * per call, ie, v_samp_factor block rows for each component in the scan.
  161295. * The data is obtained from the virtual arrays and fed to the entropy coder.
  161296. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  161297. *
  161298. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  161299. */
  161300. METHODDEF(boolean)
  161301. compress_output (j_compress_ptr cinfo, JSAMPIMAGE)
  161302. {
  161303. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161304. JDIMENSION MCU_col_num; /* index of current MCU within row */
  161305. int blkn, ci, xindex, yindex, yoffset;
  161306. JDIMENSION start_col;
  161307. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  161308. JBLOCKROW buffer_ptr;
  161309. jpeg_component_info *compptr;
  161310. /* Align the virtual buffers for the components used in this scan.
  161311. * NB: during first pass, this is safe only because the buffers will
  161312. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  161313. */
  161314. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161315. compptr = cinfo->cur_comp_info[ci];
  161316. buffer[ci] = (*cinfo->mem->access_virt_barray)
  161317. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  161318. coef->iMCU_row_num * compptr->v_samp_factor,
  161319. (JDIMENSION) compptr->v_samp_factor, FALSE);
  161320. }
  161321. /* Loop to process one whole iMCU row */
  161322. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  161323. yoffset++) {
  161324. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  161325. MCU_col_num++) {
  161326. /* Construct list of pointers to DCT blocks belonging to this MCU */
  161327. blkn = 0; /* index of current DCT block within MCU */
  161328. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161329. compptr = cinfo->cur_comp_info[ci];
  161330. start_col = MCU_col_num * compptr->MCU_width;
  161331. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  161332. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  161333. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  161334. coef->MCU_buffer[blkn++] = buffer_ptr++;
  161335. }
  161336. }
  161337. }
  161338. /* Try to write the MCU. */
  161339. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  161340. /* Suspension forced; update state counters and exit */
  161341. coef->MCU_vert_offset = yoffset;
  161342. coef->mcu_ctr = MCU_col_num;
  161343. return FALSE;
  161344. }
  161345. }
  161346. /* Completed an MCU row, but perhaps not an iMCU row */
  161347. coef->mcu_ctr = 0;
  161348. }
  161349. /* Completed the iMCU row, advance counters for next one */
  161350. coef->iMCU_row_num++;
  161351. start_iMCU_row(cinfo);
  161352. return TRUE;
  161353. }
  161354. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  161355. /*
  161356. * Initialize coefficient buffer controller.
  161357. */
  161358. GLOBAL(void)
  161359. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  161360. {
  161361. my_coef_ptr coef;
  161362. coef = (my_coef_ptr)
  161363. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161364. SIZEOF(my_coef_controller));
  161365. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  161366. coef->pub.start_pass = start_pass_coef;
  161367. /* Create the coefficient buffer. */
  161368. if (need_full_buffer) {
  161369. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161370. /* Allocate a full-image virtual array for each component, */
  161371. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  161372. int ci;
  161373. jpeg_component_info *compptr;
  161374. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161375. ci++, compptr++) {
  161376. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  161377. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  161378. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  161379. (long) compptr->h_samp_factor),
  161380. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  161381. (long) compptr->v_samp_factor),
  161382. (JDIMENSION) compptr->v_samp_factor);
  161383. }
  161384. #else
  161385. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161386. #endif
  161387. } else {
  161388. /* We only need a single-MCU buffer. */
  161389. JBLOCKROW buffer;
  161390. int i;
  161391. buffer = (JBLOCKROW)
  161392. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161393. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  161394. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  161395. coef->MCU_buffer[i] = buffer + i;
  161396. }
  161397. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  161398. }
  161399. }
  161400. /*** End of inlined file: jccoefct.c ***/
  161401. /*** Start of inlined file: jccolor.c ***/
  161402. #define JPEG_INTERNALS
  161403. /* Private subobject */
  161404. typedef struct {
  161405. struct jpeg_color_converter pub; /* public fields */
  161406. /* Private state for RGB->YCC conversion */
  161407. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  161408. } my_color_converter;
  161409. typedef my_color_converter * my_cconvert_ptr;
  161410. /**************** RGB -> YCbCr conversion: most common case **************/
  161411. /*
  161412. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  161413. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  161414. * The conversion equations to be implemented are therefore
  161415. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  161416. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  161417. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  161418. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  161419. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  161420. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  161421. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  161422. * were not represented exactly. Now we sacrifice exact representation of
  161423. * maximum red and maximum blue in order to get exact grayscales.
  161424. *
  161425. * To avoid floating-point arithmetic, we represent the fractional constants
  161426. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  161427. * the products by 2^16, with appropriate rounding, to get the correct answer.
  161428. *
  161429. * For even more speed, we avoid doing any multiplications in the inner loop
  161430. * by precalculating the constants times R,G,B for all possible values.
  161431. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  161432. * for 12-bit samples it is still acceptable. It's not very reasonable for
  161433. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  161434. * colorspace anyway.
  161435. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  161436. * in the tables to save adding them separately in the inner loop.
  161437. */
  161438. #define SCALEBITS 16 /* speediest right-shift on some machines */
  161439. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  161440. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  161441. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  161442. /* We allocate one big table and divide it up into eight parts, instead of
  161443. * doing eight alloc_small requests. This lets us use a single table base
  161444. * address, which can be held in a register in the inner loops on many
  161445. * machines (more than can hold all eight addresses, anyway).
  161446. */
  161447. #define R_Y_OFF 0 /* offset to R => Y section */
  161448. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  161449. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  161450. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  161451. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  161452. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  161453. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  161454. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  161455. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  161456. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  161457. /*
  161458. * Initialize for RGB->YCC colorspace conversion.
  161459. */
  161460. METHODDEF(void)
  161461. rgb_ycc_start (j_compress_ptr cinfo)
  161462. {
  161463. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  161464. INT32 * rgb_ycc_tab;
  161465. INT32 i;
  161466. /* Allocate and fill in the conversion tables. */
  161467. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  161468. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161469. (TABLE_SIZE * SIZEOF(INT32)));
  161470. for (i = 0; i <= MAXJSAMPLE; i++) {
  161471. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  161472. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  161473. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  161474. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  161475. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  161476. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  161477. * This ensures that the maximum output will round to MAXJSAMPLE
  161478. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  161479. */
  161480. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  161481. /* B=>Cb and R=>Cr tables are the same
  161482. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  161483. */
  161484. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  161485. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  161486. }
  161487. }
  161488. /*
  161489. * Convert some rows of samples to the JPEG colorspace.
  161490. *
  161491. * Note that we change from the application's interleaved-pixel format
  161492. * to our internal noninterleaved, one-plane-per-component format.
  161493. * The input buffer is therefore three times as wide as the output buffer.
  161494. *
  161495. * A starting row offset is provided only for the output buffer. The caller
  161496. * can easily adjust the passed input_buf value to accommodate any row
  161497. * offset required on that side.
  161498. */
  161499. METHODDEF(void)
  161500. rgb_ycc_convert (j_compress_ptr cinfo,
  161501. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161502. JDIMENSION output_row, int num_rows)
  161503. {
  161504. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  161505. register int r, g, b;
  161506. register INT32 * ctab = cconvert->rgb_ycc_tab;
  161507. register JSAMPROW inptr;
  161508. register JSAMPROW outptr0, outptr1, outptr2;
  161509. register JDIMENSION col;
  161510. JDIMENSION num_cols = cinfo->image_width;
  161511. while (--num_rows >= 0) {
  161512. inptr = *input_buf++;
  161513. outptr0 = output_buf[0][output_row];
  161514. outptr1 = output_buf[1][output_row];
  161515. outptr2 = output_buf[2][output_row];
  161516. output_row++;
  161517. for (col = 0; col < num_cols; col++) {
  161518. r = GETJSAMPLE(inptr[RGB_RED]);
  161519. g = GETJSAMPLE(inptr[RGB_GREEN]);
  161520. b = GETJSAMPLE(inptr[RGB_BLUE]);
  161521. inptr += RGB_PIXELSIZE;
  161522. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  161523. * must be too; we do not need an explicit range-limiting operation.
  161524. * Hence the value being shifted is never negative, and we don't
  161525. * need the general RIGHT_SHIFT macro.
  161526. */
  161527. /* Y */
  161528. outptr0[col] = (JSAMPLE)
  161529. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  161530. >> SCALEBITS);
  161531. /* Cb */
  161532. outptr1[col] = (JSAMPLE)
  161533. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  161534. >> SCALEBITS);
  161535. /* Cr */
  161536. outptr2[col] = (JSAMPLE)
  161537. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  161538. >> SCALEBITS);
  161539. }
  161540. }
  161541. }
  161542. /**************** Cases other than RGB -> YCbCr **************/
  161543. /*
  161544. * Convert some rows of samples to the JPEG colorspace.
  161545. * This version handles RGB->grayscale conversion, which is the same
  161546. * as the RGB->Y portion of RGB->YCbCr.
  161547. * We assume rgb_ycc_start has been called (we only use the Y tables).
  161548. */
  161549. METHODDEF(void)
  161550. rgb_gray_convert (j_compress_ptr cinfo,
  161551. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161552. JDIMENSION output_row, int num_rows)
  161553. {
  161554. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  161555. register int r, g, b;
  161556. register INT32 * ctab = cconvert->rgb_ycc_tab;
  161557. register JSAMPROW inptr;
  161558. register JSAMPROW outptr;
  161559. register JDIMENSION col;
  161560. JDIMENSION num_cols = cinfo->image_width;
  161561. while (--num_rows >= 0) {
  161562. inptr = *input_buf++;
  161563. outptr = output_buf[0][output_row];
  161564. output_row++;
  161565. for (col = 0; col < num_cols; col++) {
  161566. r = GETJSAMPLE(inptr[RGB_RED]);
  161567. g = GETJSAMPLE(inptr[RGB_GREEN]);
  161568. b = GETJSAMPLE(inptr[RGB_BLUE]);
  161569. inptr += RGB_PIXELSIZE;
  161570. /* Y */
  161571. outptr[col] = (JSAMPLE)
  161572. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  161573. >> SCALEBITS);
  161574. }
  161575. }
  161576. }
  161577. /*
  161578. * Convert some rows of samples to the JPEG colorspace.
  161579. * This version handles Adobe-style CMYK->YCCK conversion,
  161580. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  161581. * conversion as above, while passing K (black) unchanged.
  161582. * We assume rgb_ycc_start has been called.
  161583. */
  161584. METHODDEF(void)
  161585. cmyk_ycck_convert (j_compress_ptr cinfo,
  161586. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161587. JDIMENSION output_row, int num_rows)
  161588. {
  161589. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  161590. register int r, g, b;
  161591. register INT32 * ctab = cconvert->rgb_ycc_tab;
  161592. register JSAMPROW inptr;
  161593. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  161594. register JDIMENSION col;
  161595. JDIMENSION num_cols = cinfo->image_width;
  161596. while (--num_rows >= 0) {
  161597. inptr = *input_buf++;
  161598. outptr0 = output_buf[0][output_row];
  161599. outptr1 = output_buf[1][output_row];
  161600. outptr2 = output_buf[2][output_row];
  161601. outptr3 = output_buf[3][output_row];
  161602. output_row++;
  161603. for (col = 0; col < num_cols; col++) {
  161604. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  161605. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  161606. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  161607. /* K passes through as-is */
  161608. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  161609. inptr += 4;
  161610. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  161611. * must be too; we do not need an explicit range-limiting operation.
  161612. * Hence the value being shifted is never negative, and we don't
  161613. * need the general RIGHT_SHIFT macro.
  161614. */
  161615. /* Y */
  161616. outptr0[col] = (JSAMPLE)
  161617. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  161618. >> SCALEBITS);
  161619. /* Cb */
  161620. outptr1[col] = (JSAMPLE)
  161621. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  161622. >> SCALEBITS);
  161623. /* Cr */
  161624. outptr2[col] = (JSAMPLE)
  161625. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  161626. >> SCALEBITS);
  161627. }
  161628. }
  161629. }
  161630. /*
  161631. * Convert some rows of samples to the JPEG colorspace.
  161632. * This version handles grayscale output with no conversion.
  161633. * The source can be either plain grayscale or YCbCr (since Y == gray).
  161634. */
  161635. METHODDEF(void)
  161636. grayscale_convert (j_compress_ptr cinfo,
  161637. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161638. JDIMENSION output_row, int num_rows)
  161639. {
  161640. register JSAMPROW inptr;
  161641. register JSAMPROW outptr;
  161642. register JDIMENSION col;
  161643. JDIMENSION num_cols = cinfo->image_width;
  161644. int instride = cinfo->input_components;
  161645. while (--num_rows >= 0) {
  161646. inptr = *input_buf++;
  161647. outptr = output_buf[0][output_row];
  161648. output_row++;
  161649. for (col = 0; col < num_cols; col++) {
  161650. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  161651. inptr += instride;
  161652. }
  161653. }
  161654. }
  161655. /*
  161656. * Convert some rows of samples to the JPEG colorspace.
  161657. * This version handles multi-component colorspaces without conversion.
  161658. * We assume input_components == num_components.
  161659. */
  161660. METHODDEF(void)
  161661. null_convert (j_compress_ptr cinfo,
  161662. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161663. JDIMENSION output_row, int num_rows)
  161664. {
  161665. register JSAMPROW inptr;
  161666. register JSAMPROW outptr;
  161667. register JDIMENSION col;
  161668. register int ci;
  161669. int nc = cinfo->num_components;
  161670. JDIMENSION num_cols = cinfo->image_width;
  161671. while (--num_rows >= 0) {
  161672. /* It seems fastest to make a separate pass for each component. */
  161673. for (ci = 0; ci < nc; ci++) {
  161674. inptr = *input_buf;
  161675. outptr = output_buf[ci][output_row];
  161676. for (col = 0; col < num_cols; col++) {
  161677. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  161678. inptr += nc;
  161679. }
  161680. }
  161681. input_buf++;
  161682. output_row++;
  161683. }
  161684. }
  161685. /*
  161686. * Empty method for start_pass.
  161687. */
  161688. METHODDEF(void)
  161689. null_method (j_compress_ptr)
  161690. {
  161691. /* no work needed */
  161692. }
  161693. /*
  161694. * Module initialization routine for input colorspace conversion.
  161695. */
  161696. GLOBAL(void)
  161697. jinit_color_converter (j_compress_ptr cinfo)
  161698. {
  161699. my_cconvert_ptr cconvert;
  161700. cconvert = (my_cconvert_ptr)
  161701. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161702. SIZEOF(my_color_converter));
  161703. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  161704. /* set start_pass to null method until we find out differently */
  161705. cconvert->pub.start_pass = null_method;
  161706. /* Make sure input_components agrees with in_color_space */
  161707. switch (cinfo->in_color_space) {
  161708. case JCS_GRAYSCALE:
  161709. if (cinfo->input_components != 1)
  161710. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  161711. break;
  161712. case JCS_RGB:
  161713. #if RGB_PIXELSIZE != 3
  161714. if (cinfo->input_components != RGB_PIXELSIZE)
  161715. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  161716. break;
  161717. #endif /* else share code with YCbCr */
  161718. case JCS_YCbCr:
  161719. if (cinfo->input_components != 3)
  161720. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  161721. break;
  161722. case JCS_CMYK:
  161723. case JCS_YCCK:
  161724. if (cinfo->input_components != 4)
  161725. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  161726. break;
  161727. default: /* JCS_UNKNOWN can be anything */
  161728. if (cinfo->input_components < 1)
  161729. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  161730. break;
  161731. }
  161732. /* Check num_components, set conversion method based on requested space */
  161733. switch (cinfo->jpeg_color_space) {
  161734. case JCS_GRAYSCALE:
  161735. if (cinfo->num_components != 1)
  161736. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  161737. if (cinfo->in_color_space == JCS_GRAYSCALE)
  161738. cconvert->pub.color_convert = grayscale_convert;
  161739. else if (cinfo->in_color_space == JCS_RGB) {
  161740. cconvert->pub.start_pass = rgb_ycc_start;
  161741. cconvert->pub.color_convert = rgb_gray_convert;
  161742. } else if (cinfo->in_color_space == JCS_YCbCr)
  161743. cconvert->pub.color_convert = grayscale_convert;
  161744. else
  161745. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  161746. break;
  161747. case JCS_RGB:
  161748. if (cinfo->num_components != 3)
  161749. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  161750. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  161751. cconvert->pub.color_convert = null_convert;
  161752. else
  161753. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  161754. break;
  161755. case JCS_YCbCr:
  161756. if (cinfo->num_components != 3)
  161757. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  161758. if (cinfo->in_color_space == JCS_RGB) {
  161759. cconvert->pub.start_pass = rgb_ycc_start;
  161760. cconvert->pub.color_convert = rgb_ycc_convert;
  161761. } else if (cinfo->in_color_space == JCS_YCbCr)
  161762. cconvert->pub.color_convert = null_convert;
  161763. else
  161764. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  161765. break;
  161766. case JCS_CMYK:
  161767. if (cinfo->num_components != 4)
  161768. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  161769. if (cinfo->in_color_space == JCS_CMYK)
  161770. cconvert->pub.color_convert = null_convert;
  161771. else
  161772. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  161773. break;
  161774. case JCS_YCCK:
  161775. if (cinfo->num_components != 4)
  161776. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  161777. if (cinfo->in_color_space == JCS_CMYK) {
  161778. cconvert->pub.start_pass = rgb_ycc_start;
  161779. cconvert->pub.color_convert = cmyk_ycck_convert;
  161780. } else if (cinfo->in_color_space == JCS_YCCK)
  161781. cconvert->pub.color_convert = null_convert;
  161782. else
  161783. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  161784. break;
  161785. default: /* allow null conversion of JCS_UNKNOWN */
  161786. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  161787. cinfo->num_components != cinfo->input_components)
  161788. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  161789. cconvert->pub.color_convert = null_convert;
  161790. break;
  161791. }
  161792. }
  161793. /*** End of inlined file: jccolor.c ***/
  161794. #undef FIX
  161795. /*** Start of inlined file: jcdctmgr.c ***/
  161796. #define JPEG_INTERNALS
  161797. /*** Start of inlined file: jdct.h ***/
  161798. /*
  161799. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  161800. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  161801. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  161802. * implementations use an array of type FAST_FLOAT, instead.)
  161803. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  161804. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  161805. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  161806. * convention improves accuracy in integer implementations and saves some
  161807. * work in floating-point ones.
  161808. * Quantization of the output coefficients is done by jcdctmgr.c.
  161809. */
  161810. #ifndef __jdct_h__
  161811. #define __jdct_h__
  161812. #if BITS_IN_JSAMPLE == 8
  161813. typedef int DCTELEM; /* 16 or 32 bits is fine */
  161814. #else
  161815. typedef INT32 DCTELEM; /* must have 32 bits */
  161816. #endif
  161817. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  161818. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  161819. /*
  161820. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  161821. * to an output sample array. The routine must dequantize the input data as
  161822. * well as perform the IDCT; for dequantization, it uses the multiplier table
  161823. * pointed to by compptr->dct_table. The output data is to be placed into the
  161824. * sample array starting at a specified column. (Any row offset needed will
  161825. * be applied to the array pointer before it is passed to the IDCT code.)
  161826. * Note that the number of samples emitted by the IDCT routine is
  161827. * DCT_scaled_size * DCT_scaled_size.
  161828. */
  161829. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  161830. /*
  161831. * Each IDCT routine has its own ideas about the best dct_table element type.
  161832. */
  161833. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  161834. #if BITS_IN_JSAMPLE == 8
  161835. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  161836. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  161837. #else
  161838. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  161839. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  161840. #endif
  161841. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  161842. /*
  161843. * Each IDCT routine is responsible for range-limiting its results and
  161844. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  161845. * be quite far out of range if the input data is corrupt, so a bulletproof
  161846. * range-limiting step is required. We use a mask-and-table-lookup method
  161847. * to do the combined operations quickly. See the comments with
  161848. * prepare_range_limit_table (in jdmaster.c) for more info.
  161849. */
  161850. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  161851. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  161852. /* Short forms of external names for systems with brain-damaged linkers. */
  161853. #ifdef NEED_SHORT_EXTERNAL_NAMES
  161854. #define jpeg_fdct_islow jFDislow
  161855. #define jpeg_fdct_ifast jFDifast
  161856. #define jpeg_fdct_float jFDfloat
  161857. #define jpeg_idct_islow jRDislow
  161858. #define jpeg_idct_ifast jRDifast
  161859. #define jpeg_idct_float jRDfloat
  161860. #define jpeg_idct_4x4 jRD4x4
  161861. #define jpeg_idct_2x2 jRD2x2
  161862. #define jpeg_idct_1x1 jRD1x1
  161863. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  161864. /* Extern declarations for the forward and inverse DCT routines. */
  161865. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  161866. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  161867. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  161868. EXTERN(void) jpeg_idct_islow
  161869. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  161870. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  161871. EXTERN(void) jpeg_idct_ifast
  161872. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  161873. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  161874. EXTERN(void) jpeg_idct_float
  161875. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  161876. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  161877. EXTERN(void) jpeg_idct_4x4
  161878. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  161879. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  161880. EXTERN(void) jpeg_idct_2x2
  161881. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  161882. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  161883. EXTERN(void) jpeg_idct_1x1
  161884. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  161885. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  161886. /*
  161887. * Macros for handling fixed-point arithmetic; these are used by many
  161888. * but not all of the DCT/IDCT modules.
  161889. *
  161890. * All values are expected to be of type INT32.
  161891. * Fractional constants are scaled left by CONST_BITS bits.
  161892. * CONST_BITS is defined within each module using these macros,
  161893. * and may differ from one module to the next.
  161894. */
  161895. #define ONE ((INT32) 1)
  161896. #define CONST_SCALE (ONE << CONST_BITS)
  161897. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  161898. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  161899. * thus causing a lot of useless floating-point operations at run time.
  161900. */
  161901. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  161902. /* Descale and correctly round an INT32 value that's scaled by N bits.
  161903. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  161904. * the fudge factor is correct for either sign of X.
  161905. */
  161906. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  161907. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  161908. * This macro is used only when the two inputs will actually be no more than
  161909. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  161910. * full 32x32 multiply. This provides a useful speedup on many machines.
  161911. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  161912. * in C, but some C compilers will do the right thing if you provide the
  161913. * correct combination of casts.
  161914. */
  161915. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  161916. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  161917. #endif
  161918. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  161919. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  161920. #endif
  161921. #ifndef MULTIPLY16C16 /* default definition */
  161922. #define MULTIPLY16C16(var,const) ((var) * (const))
  161923. #endif
  161924. /* Same except both inputs are variables. */
  161925. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  161926. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  161927. #endif
  161928. #ifndef MULTIPLY16V16 /* default definition */
  161929. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  161930. #endif
  161931. #endif
  161932. /*** End of inlined file: jdct.h ***/
  161933. /* Private declarations for DCT subsystem */
  161934. /* Private subobject for this module */
  161935. typedef struct {
  161936. struct jpeg_forward_dct pub; /* public fields */
  161937. /* Pointer to the DCT routine actually in use */
  161938. forward_DCT_method_ptr do_dct;
  161939. /* The actual post-DCT divisors --- not identical to the quant table
  161940. * entries, because of scaling (especially for an unnormalized DCT).
  161941. * Each table is given in normal array order.
  161942. */
  161943. DCTELEM * divisors[NUM_QUANT_TBLS];
  161944. #ifdef DCT_FLOAT_SUPPORTED
  161945. /* Same as above for the floating-point case. */
  161946. float_DCT_method_ptr do_float_dct;
  161947. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  161948. #endif
  161949. } my_fdct_controller;
  161950. typedef my_fdct_controller * my_fdct_ptr;
  161951. /*
  161952. * Initialize for a processing pass.
  161953. * Verify that all referenced Q-tables are present, and set up
  161954. * the divisor table for each one.
  161955. * In the current implementation, DCT of all components is done during
  161956. * the first pass, even if only some components will be output in the
  161957. * first scan. Hence all components should be examined here.
  161958. */
  161959. METHODDEF(void)
  161960. start_pass_fdctmgr (j_compress_ptr cinfo)
  161961. {
  161962. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  161963. int ci, qtblno, i;
  161964. jpeg_component_info *compptr;
  161965. JQUANT_TBL * qtbl;
  161966. DCTELEM * dtbl;
  161967. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161968. ci++, compptr++) {
  161969. qtblno = compptr->quant_tbl_no;
  161970. /* Make sure specified quantization table is present */
  161971. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  161972. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  161973. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  161974. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  161975. /* Compute divisors for this quant table */
  161976. /* We may do this more than once for same table, but it's not a big deal */
  161977. switch (cinfo->dct_method) {
  161978. #ifdef DCT_ISLOW_SUPPORTED
  161979. case JDCT_ISLOW:
  161980. /* For LL&M IDCT method, divisors are equal to raw quantization
  161981. * coefficients multiplied by 8 (to counteract scaling).
  161982. */
  161983. if (fdct->divisors[qtblno] == NULL) {
  161984. fdct->divisors[qtblno] = (DCTELEM *)
  161985. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161986. DCTSIZE2 * SIZEOF(DCTELEM));
  161987. }
  161988. dtbl = fdct->divisors[qtblno];
  161989. for (i = 0; i < DCTSIZE2; i++) {
  161990. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  161991. }
  161992. break;
  161993. #endif
  161994. #ifdef DCT_IFAST_SUPPORTED
  161995. case JDCT_IFAST:
  161996. {
  161997. /* For AA&N IDCT method, divisors are equal to quantization
  161998. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  161999. * scalefactor[0] = 1
  162000. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162001. * We apply a further scale factor of 8.
  162002. */
  162003. #define CONST_BITS 14
  162004. static const INT16 aanscales[DCTSIZE2] = {
  162005. /* precomputed values scaled up by 14 bits */
  162006. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162007. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  162008. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  162009. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  162010. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162011. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  162012. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  162013. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  162014. };
  162015. SHIFT_TEMPS
  162016. if (fdct->divisors[qtblno] == NULL) {
  162017. fdct->divisors[qtblno] = (DCTELEM *)
  162018. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162019. DCTSIZE2 * SIZEOF(DCTELEM));
  162020. }
  162021. dtbl = fdct->divisors[qtblno];
  162022. for (i = 0; i < DCTSIZE2; i++) {
  162023. dtbl[i] = (DCTELEM)
  162024. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  162025. (INT32) aanscales[i]),
  162026. CONST_BITS-3);
  162027. }
  162028. }
  162029. break;
  162030. #endif
  162031. #ifdef DCT_FLOAT_SUPPORTED
  162032. case JDCT_FLOAT:
  162033. {
  162034. /* For float AA&N IDCT method, divisors are equal to quantization
  162035. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162036. * scalefactor[0] = 1
  162037. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162038. * We apply a further scale factor of 8.
  162039. * What's actually stored is 1/divisor so that the inner loop can
  162040. * use a multiplication rather than a division.
  162041. */
  162042. FAST_FLOAT * fdtbl;
  162043. int row, col;
  162044. static const double aanscalefactor[DCTSIZE] = {
  162045. 1.0, 1.387039845, 1.306562965, 1.175875602,
  162046. 1.0, 0.785694958, 0.541196100, 0.275899379
  162047. };
  162048. if (fdct->float_divisors[qtblno] == NULL) {
  162049. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  162050. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162051. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  162052. }
  162053. fdtbl = fdct->float_divisors[qtblno];
  162054. i = 0;
  162055. for (row = 0; row < DCTSIZE; row++) {
  162056. for (col = 0; col < DCTSIZE; col++) {
  162057. fdtbl[i] = (FAST_FLOAT)
  162058. (1.0 / (((double) qtbl->quantval[i] *
  162059. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  162060. i++;
  162061. }
  162062. }
  162063. }
  162064. break;
  162065. #endif
  162066. default:
  162067. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162068. break;
  162069. }
  162070. }
  162071. }
  162072. /*
  162073. * Perform forward DCT on one or more blocks of a component.
  162074. *
  162075. * The input samples are taken from the sample_data[] array starting at
  162076. * position start_row/start_col, and moving to the right for any additional
  162077. * blocks. The quantized coefficients are returned in coef_blocks[].
  162078. */
  162079. METHODDEF(void)
  162080. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162081. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  162082. JDIMENSION start_row, JDIMENSION start_col,
  162083. JDIMENSION num_blocks)
  162084. /* This version is used for integer DCT implementations. */
  162085. {
  162086. /* This routine is heavily used, so it's worth coding it tightly. */
  162087. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162088. forward_DCT_method_ptr do_dct = fdct->do_dct;
  162089. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  162090. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  162091. JDIMENSION bi;
  162092. sample_data += start_row; /* fold in the vertical offset once */
  162093. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  162094. /* Load data into workspace, applying unsigned->signed conversion */
  162095. { register DCTELEM *workspaceptr;
  162096. register JSAMPROW elemptr;
  162097. register int elemr;
  162098. workspaceptr = workspace;
  162099. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  162100. elemptr = sample_data[elemr] + start_col;
  162101. #if DCTSIZE == 8 /* unroll the inner loop */
  162102. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162103. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162104. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162105. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162106. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162107. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162108. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162109. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162110. #else
  162111. { register int elemc;
  162112. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  162113. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162114. }
  162115. }
  162116. #endif
  162117. }
  162118. }
  162119. /* Perform the DCT */
  162120. (*do_dct) (workspace);
  162121. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  162122. { register DCTELEM temp, qval;
  162123. register int i;
  162124. register JCOEFPTR output_ptr = coef_blocks[bi];
  162125. for (i = 0; i < DCTSIZE2; i++) {
  162126. qval = divisors[i];
  162127. temp = workspace[i];
  162128. /* Divide the coefficient value by qval, ensuring proper rounding.
  162129. * Since C does not specify the direction of rounding for negative
  162130. * quotients, we have to force the dividend positive for portability.
  162131. *
  162132. * In most files, at least half of the output values will be zero
  162133. * (at default quantization settings, more like three-quarters...)
  162134. * so we should ensure that this case is fast. On many machines,
  162135. * a comparison is enough cheaper than a divide to make a special test
  162136. * a win. Since both inputs will be nonnegative, we need only test
  162137. * for a < b to discover whether a/b is 0.
  162138. * If your machine's division is fast enough, define FAST_DIVIDE.
  162139. */
  162140. #ifdef FAST_DIVIDE
  162141. #define DIVIDE_BY(a,b) a /= b
  162142. #else
  162143. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  162144. #endif
  162145. if (temp < 0) {
  162146. temp = -temp;
  162147. temp += qval>>1; /* for rounding */
  162148. DIVIDE_BY(temp, qval);
  162149. temp = -temp;
  162150. } else {
  162151. temp += qval>>1; /* for rounding */
  162152. DIVIDE_BY(temp, qval);
  162153. }
  162154. output_ptr[i] = (JCOEF) temp;
  162155. }
  162156. }
  162157. }
  162158. }
  162159. #ifdef DCT_FLOAT_SUPPORTED
  162160. METHODDEF(void)
  162161. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162162. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  162163. JDIMENSION start_row, JDIMENSION start_col,
  162164. JDIMENSION num_blocks)
  162165. /* This version is used for floating-point DCT implementations. */
  162166. {
  162167. /* This routine is heavily used, so it's worth coding it tightly. */
  162168. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162169. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  162170. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  162171. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  162172. JDIMENSION bi;
  162173. sample_data += start_row; /* fold in the vertical offset once */
  162174. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  162175. /* Load data into workspace, applying unsigned->signed conversion */
  162176. { register FAST_FLOAT *workspaceptr;
  162177. register JSAMPROW elemptr;
  162178. register int elemr;
  162179. workspaceptr = workspace;
  162180. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  162181. elemptr = sample_data[elemr] + start_col;
  162182. #if DCTSIZE == 8 /* unroll the inner loop */
  162183. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162184. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162185. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162186. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162187. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162188. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162189. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162190. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162191. #else
  162192. { register int elemc;
  162193. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  162194. *workspaceptr++ = (FAST_FLOAT)
  162195. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162196. }
  162197. }
  162198. #endif
  162199. }
  162200. }
  162201. /* Perform the DCT */
  162202. (*do_dct) (workspace);
  162203. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  162204. { register FAST_FLOAT temp;
  162205. register int i;
  162206. register JCOEFPTR output_ptr = coef_blocks[bi];
  162207. for (i = 0; i < DCTSIZE2; i++) {
  162208. /* Apply the quantization and scaling factor */
  162209. temp = workspace[i] * divisors[i];
  162210. /* Round to nearest integer.
  162211. * Since C does not specify the direction of rounding for negative
  162212. * quotients, we have to force the dividend positive for portability.
  162213. * The maximum coefficient size is +-16K (for 12-bit data), so this
  162214. * code should work for either 16-bit or 32-bit ints.
  162215. */
  162216. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  162217. }
  162218. }
  162219. }
  162220. }
  162221. #endif /* DCT_FLOAT_SUPPORTED */
  162222. /*
  162223. * Initialize FDCT manager.
  162224. */
  162225. GLOBAL(void)
  162226. jinit_forward_dct (j_compress_ptr cinfo)
  162227. {
  162228. my_fdct_ptr fdct;
  162229. int i;
  162230. fdct = (my_fdct_ptr)
  162231. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162232. SIZEOF(my_fdct_controller));
  162233. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  162234. fdct->pub.start_pass = start_pass_fdctmgr;
  162235. switch (cinfo->dct_method) {
  162236. #ifdef DCT_ISLOW_SUPPORTED
  162237. case JDCT_ISLOW:
  162238. fdct->pub.forward_DCT = forward_DCT;
  162239. fdct->do_dct = jpeg_fdct_islow;
  162240. break;
  162241. #endif
  162242. #ifdef DCT_IFAST_SUPPORTED
  162243. case JDCT_IFAST:
  162244. fdct->pub.forward_DCT = forward_DCT;
  162245. fdct->do_dct = jpeg_fdct_ifast;
  162246. break;
  162247. #endif
  162248. #ifdef DCT_FLOAT_SUPPORTED
  162249. case JDCT_FLOAT:
  162250. fdct->pub.forward_DCT = forward_DCT_float;
  162251. fdct->do_float_dct = jpeg_fdct_float;
  162252. break;
  162253. #endif
  162254. default:
  162255. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162256. break;
  162257. }
  162258. /* Mark divisor tables unallocated */
  162259. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  162260. fdct->divisors[i] = NULL;
  162261. #ifdef DCT_FLOAT_SUPPORTED
  162262. fdct->float_divisors[i] = NULL;
  162263. #endif
  162264. }
  162265. }
  162266. /*** End of inlined file: jcdctmgr.c ***/
  162267. #undef CONST_BITS
  162268. /*** Start of inlined file: jchuff.c ***/
  162269. #define JPEG_INTERNALS
  162270. /*** Start of inlined file: jchuff.h ***/
  162271. /* The legal range of a DCT coefficient is
  162272. * -1024 .. +1023 for 8-bit data;
  162273. * -16384 .. +16383 for 12-bit data.
  162274. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  162275. */
  162276. #ifndef _jchuff_h_
  162277. #define _jchuff_h_
  162278. #if BITS_IN_JSAMPLE == 8
  162279. #define MAX_COEF_BITS 10
  162280. #else
  162281. #define MAX_COEF_BITS 14
  162282. #endif
  162283. /* Derived data constructed for each Huffman table */
  162284. typedef struct {
  162285. unsigned int ehufco[256]; /* code for each symbol */
  162286. char ehufsi[256]; /* length of code for each symbol */
  162287. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  162288. } c_derived_tbl;
  162289. /* Short forms of external names for systems with brain-damaged linkers. */
  162290. #ifdef NEED_SHORT_EXTERNAL_NAMES
  162291. #define jpeg_make_c_derived_tbl jMkCDerived
  162292. #define jpeg_gen_optimal_table jGenOptTbl
  162293. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  162294. /* Expand a Huffman table definition into the derived format */
  162295. EXTERN(void) jpeg_make_c_derived_tbl
  162296. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  162297. c_derived_tbl ** pdtbl));
  162298. /* Generate an optimal table definition given the specified counts */
  162299. EXTERN(void) jpeg_gen_optimal_table
  162300. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  162301. #endif
  162302. /*** End of inlined file: jchuff.h ***/
  162303. /* Declarations shared with jcphuff.c */
  162304. /* Expanded entropy encoder object for Huffman encoding.
  162305. *
  162306. * The savable_state subrecord contains fields that change within an MCU,
  162307. * but must not be updated permanently until we complete the MCU.
  162308. */
  162309. typedef struct {
  162310. INT32 put_buffer; /* current bit-accumulation buffer */
  162311. int put_bits; /* # of bits now in it */
  162312. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  162313. } savable_state;
  162314. /* This macro is to work around compilers with missing or broken
  162315. * structure assignment. You'll need to fix this code if you have
  162316. * such a compiler and you change MAX_COMPS_IN_SCAN.
  162317. */
  162318. #ifndef NO_STRUCT_ASSIGN
  162319. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  162320. #else
  162321. #if MAX_COMPS_IN_SCAN == 4
  162322. #define ASSIGN_STATE(dest,src) \
  162323. ((dest).put_buffer = (src).put_buffer, \
  162324. (dest).put_bits = (src).put_bits, \
  162325. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  162326. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  162327. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  162328. (dest).last_dc_val[3] = (src).last_dc_val[3])
  162329. #endif
  162330. #endif
  162331. typedef struct {
  162332. struct jpeg_entropy_encoder pub; /* public fields */
  162333. savable_state saved; /* Bit buffer & DC state at start of MCU */
  162334. /* These fields are NOT loaded into local working state. */
  162335. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  162336. int next_restart_num; /* next restart number to write (0-7) */
  162337. /* Pointers to derived tables (these workspaces have image lifespan) */
  162338. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  162339. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  162340. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  162341. long * dc_count_ptrs[NUM_HUFF_TBLS];
  162342. long * ac_count_ptrs[NUM_HUFF_TBLS];
  162343. #endif
  162344. } huff_entropy_encoder;
  162345. typedef huff_entropy_encoder * huff_entropy_ptr;
  162346. /* Working state while writing an MCU.
  162347. * This struct contains all the fields that are needed by subroutines.
  162348. */
  162349. typedef struct {
  162350. JOCTET * next_output_byte; /* => next byte to write in buffer */
  162351. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  162352. savable_state cur; /* Current bit buffer & DC state */
  162353. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  162354. } working_state;
  162355. /* Forward declarations */
  162356. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  162357. JBLOCKROW *MCU_data));
  162358. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  162359. #ifdef ENTROPY_OPT_SUPPORTED
  162360. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  162361. JBLOCKROW *MCU_data));
  162362. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  162363. #endif
  162364. /*
  162365. * Initialize for a Huffman-compressed scan.
  162366. * If gather_statistics is TRUE, we do not output anything during the scan,
  162367. * just count the Huffman symbols used and generate Huffman code tables.
  162368. */
  162369. METHODDEF(void)
  162370. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  162371. {
  162372. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  162373. int ci, dctbl, actbl;
  162374. jpeg_component_info * compptr;
  162375. if (gather_statistics) {
  162376. #ifdef ENTROPY_OPT_SUPPORTED
  162377. entropy->pub.encode_mcu = encode_mcu_gather;
  162378. entropy->pub.finish_pass = finish_pass_gather;
  162379. #else
  162380. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162381. #endif
  162382. } else {
  162383. entropy->pub.encode_mcu = encode_mcu_huff;
  162384. entropy->pub.finish_pass = finish_pass_huff;
  162385. }
  162386. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162387. compptr = cinfo->cur_comp_info[ci];
  162388. dctbl = compptr->dc_tbl_no;
  162389. actbl = compptr->ac_tbl_no;
  162390. if (gather_statistics) {
  162391. #ifdef ENTROPY_OPT_SUPPORTED
  162392. /* Check for invalid table indexes */
  162393. /* (make_c_derived_tbl does this in the other path) */
  162394. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  162395. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  162396. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  162397. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  162398. /* Allocate and zero the statistics tables */
  162399. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  162400. if (entropy->dc_count_ptrs[dctbl] == NULL)
  162401. entropy->dc_count_ptrs[dctbl] = (long *)
  162402. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162403. 257 * SIZEOF(long));
  162404. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  162405. if (entropy->ac_count_ptrs[actbl] == NULL)
  162406. entropy->ac_count_ptrs[actbl] = (long *)
  162407. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162408. 257 * SIZEOF(long));
  162409. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  162410. #endif
  162411. } else {
  162412. /* Compute derived values for Huffman tables */
  162413. /* We may do this more than once for a table, but it's not expensive */
  162414. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  162415. & entropy->dc_derived_tbls[dctbl]);
  162416. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  162417. & entropy->ac_derived_tbls[actbl]);
  162418. }
  162419. /* Initialize DC predictions to 0 */
  162420. entropy->saved.last_dc_val[ci] = 0;
  162421. }
  162422. /* Initialize bit buffer to empty */
  162423. entropy->saved.put_buffer = 0;
  162424. entropy->saved.put_bits = 0;
  162425. /* Initialize restart stuff */
  162426. entropy->restarts_to_go = cinfo->restart_interval;
  162427. entropy->next_restart_num = 0;
  162428. }
  162429. /*
  162430. * Compute the derived values for a Huffman table.
  162431. * This routine also performs some validation checks on the table.
  162432. *
  162433. * Note this is also used by jcphuff.c.
  162434. */
  162435. GLOBAL(void)
  162436. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  162437. c_derived_tbl ** pdtbl)
  162438. {
  162439. JHUFF_TBL *htbl;
  162440. c_derived_tbl *dtbl;
  162441. int p, i, l, lastp, si, maxsymbol;
  162442. char huffsize[257];
  162443. unsigned int huffcode[257];
  162444. unsigned int code;
  162445. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  162446. * paralleling the order of the symbols themselves in htbl->huffval[].
  162447. */
  162448. /* Find the input Huffman table */
  162449. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  162450. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  162451. htbl =
  162452. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  162453. if (htbl == NULL)
  162454. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  162455. /* Allocate a workspace if we haven't already done so. */
  162456. if (*pdtbl == NULL)
  162457. *pdtbl = (c_derived_tbl *)
  162458. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162459. SIZEOF(c_derived_tbl));
  162460. dtbl = *pdtbl;
  162461. /* Figure C.1: make table of Huffman code length for each symbol */
  162462. p = 0;
  162463. for (l = 1; l <= 16; l++) {
  162464. i = (int) htbl->bits[l];
  162465. if (i < 0 || p + i > 256) /* protect against table overrun */
  162466. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  162467. while (i--)
  162468. huffsize[p++] = (char) l;
  162469. }
  162470. huffsize[p] = 0;
  162471. lastp = p;
  162472. /* Figure C.2: generate the codes themselves */
  162473. /* We also validate that the counts represent a legal Huffman code tree. */
  162474. code = 0;
  162475. si = huffsize[0];
  162476. p = 0;
  162477. while (huffsize[p]) {
  162478. while (((int) huffsize[p]) == si) {
  162479. huffcode[p++] = code;
  162480. code++;
  162481. }
  162482. /* code is now 1 more than the last code used for codelength si; but
  162483. * it must still fit in si bits, since no code is allowed to be all ones.
  162484. */
  162485. if (((INT32) code) >= (((INT32) 1) << si))
  162486. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  162487. code <<= 1;
  162488. si++;
  162489. }
  162490. /* Figure C.3: generate encoding tables */
  162491. /* These are code and size indexed by symbol value */
  162492. /* Set all codeless symbols to have code length 0;
  162493. * this lets us detect duplicate VAL entries here, and later
  162494. * allows emit_bits to detect any attempt to emit such symbols.
  162495. */
  162496. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  162497. /* This is also a convenient place to check for out-of-range
  162498. * and duplicated VAL entries. We allow 0..255 for AC symbols
  162499. * but only 0..15 for DC. (We could constrain them further
  162500. * based on data depth and mode, but this seems enough.)
  162501. */
  162502. maxsymbol = isDC ? 15 : 255;
  162503. for (p = 0; p < lastp; p++) {
  162504. i = htbl->huffval[p];
  162505. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  162506. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  162507. dtbl->ehufco[i] = huffcode[p];
  162508. dtbl->ehufsi[i] = huffsize[p];
  162509. }
  162510. }
  162511. /* Outputting bytes to the file */
  162512. /* Emit a byte, taking 'action' if must suspend. */
  162513. #define emit_byte(state,val,action) \
  162514. { *(state)->next_output_byte++ = (JOCTET) (val); \
  162515. if (--(state)->free_in_buffer == 0) \
  162516. if (! dump_buffer(state)) \
  162517. { action; } }
  162518. LOCAL(boolean)
  162519. dump_buffer (working_state * state)
  162520. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  162521. {
  162522. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  162523. if (! (*dest->empty_output_buffer) (state->cinfo))
  162524. return FALSE;
  162525. /* After a successful buffer dump, must reset buffer pointers */
  162526. state->next_output_byte = dest->next_output_byte;
  162527. state->free_in_buffer = dest->free_in_buffer;
  162528. return TRUE;
  162529. }
  162530. /* Outputting bits to the file */
  162531. /* Only the right 24 bits of put_buffer are used; the valid bits are
  162532. * left-justified in this part. At most 16 bits can be passed to emit_bits
  162533. * in one call, and we never retain more than 7 bits in put_buffer
  162534. * between calls, so 24 bits are sufficient.
  162535. */
  162536. INLINE
  162537. LOCAL(boolean)
  162538. emit_bits (working_state * state, unsigned int code, int size)
  162539. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  162540. {
  162541. /* This routine is heavily used, so it's worth coding tightly. */
  162542. register INT32 put_buffer = (INT32) code;
  162543. register int put_bits = state->cur.put_bits;
  162544. /* if size is 0, caller used an invalid Huffman table entry */
  162545. if (size == 0)
  162546. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  162547. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  162548. put_bits += size; /* new number of bits in buffer */
  162549. put_buffer <<= 24 - put_bits; /* align incoming bits */
  162550. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  162551. while (put_bits >= 8) {
  162552. int c = (int) ((put_buffer >> 16) & 0xFF);
  162553. emit_byte(state, c, return FALSE);
  162554. if (c == 0xFF) { /* need to stuff a zero byte? */
  162555. emit_byte(state, 0, return FALSE);
  162556. }
  162557. put_buffer <<= 8;
  162558. put_bits -= 8;
  162559. }
  162560. state->cur.put_buffer = put_buffer; /* update state variables */
  162561. state->cur.put_bits = put_bits;
  162562. return TRUE;
  162563. }
  162564. LOCAL(boolean)
  162565. flush_bits (working_state * state)
  162566. {
  162567. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  162568. return FALSE;
  162569. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  162570. state->cur.put_bits = 0;
  162571. return TRUE;
  162572. }
  162573. /* Encode a single block's worth of coefficients */
  162574. LOCAL(boolean)
  162575. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  162576. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  162577. {
  162578. register int temp, temp2;
  162579. register int nbits;
  162580. register int k, r, i;
  162581. /* Encode the DC coefficient difference per section F.1.2.1 */
  162582. temp = temp2 = block[0] - last_dc_val;
  162583. if (temp < 0) {
  162584. temp = -temp; /* temp is abs value of input */
  162585. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  162586. /* This code assumes we are on a two's complement machine */
  162587. temp2--;
  162588. }
  162589. /* Find the number of bits needed for the magnitude of the coefficient */
  162590. nbits = 0;
  162591. while (temp) {
  162592. nbits++;
  162593. temp >>= 1;
  162594. }
  162595. /* Check for out-of-range coefficient values.
  162596. * Since we're encoding a difference, the range limit is twice as much.
  162597. */
  162598. if (nbits > MAX_COEF_BITS+1)
  162599. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  162600. /* Emit the Huffman-coded symbol for the number of bits */
  162601. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  162602. return FALSE;
  162603. /* Emit that number of bits of the value, if positive, */
  162604. /* or the complement of its magnitude, if negative. */
  162605. if (nbits) /* emit_bits rejects calls with size 0 */
  162606. if (! emit_bits(state, (unsigned int) temp2, nbits))
  162607. return FALSE;
  162608. /* Encode the AC coefficients per section F.1.2.2 */
  162609. r = 0; /* r = run length of zeros */
  162610. for (k = 1; k < DCTSIZE2; k++) {
  162611. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  162612. r++;
  162613. } else {
  162614. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  162615. while (r > 15) {
  162616. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  162617. return FALSE;
  162618. r -= 16;
  162619. }
  162620. temp2 = temp;
  162621. if (temp < 0) {
  162622. temp = -temp; /* temp is abs value of input */
  162623. /* This code assumes we are on a two's complement machine */
  162624. temp2--;
  162625. }
  162626. /* Find the number of bits needed for the magnitude of the coefficient */
  162627. nbits = 1; /* there must be at least one 1 bit */
  162628. while ((temp >>= 1))
  162629. nbits++;
  162630. /* Check for out-of-range coefficient values */
  162631. if (nbits > MAX_COEF_BITS)
  162632. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  162633. /* Emit Huffman symbol for run length / number of bits */
  162634. i = (r << 4) + nbits;
  162635. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  162636. return FALSE;
  162637. /* Emit that number of bits of the value, if positive, */
  162638. /* or the complement of its magnitude, if negative. */
  162639. if (! emit_bits(state, (unsigned int) temp2, nbits))
  162640. return FALSE;
  162641. r = 0;
  162642. }
  162643. }
  162644. /* If the last coef(s) were zero, emit an end-of-block code */
  162645. if (r > 0)
  162646. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  162647. return FALSE;
  162648. return TRUE;
  162649. }
  162650. /*
  162651. * Emit a restart marker & resynchronize predictions.
  162652. */
  162653. LOCAL(boolean)
  162654. emit_restart (working_state * state, int restart_num)
  162655. {
  162656. int ci;
  162657. if (! flush_bits(state))
  162658. return FALSE;
  162659. emit_byte(state, 0xFF, return FALSE);
  162660. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  162661. /* Re-initialize DC predictions to 0 */
  162662. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  162663. state->cur.last_dc_val[ci] = 0;
  162664. /* The restart counter is not updated until we successfully write the MCU. */
  162665. return TRUE;
  162666. }
  162667. /*
  162668. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  162669. */
  162670. METHODDEF(boolean)
  162671. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  162672. {
  162673. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  162674. working_state state;
  162675. int blkn, ci;
  162676. jpeg_component_info * compptr;
  162677. /* Load up working state */
  162678. state.next_output_byte = cinfo->dest->next_output_byte;
  162679. state.free_in_buffer = cinfo->dest->free_in_buffer;
  162680. ASSIGN_STATE(state.cur, entropy->saved);
  162681. state.cinfo = cinfo;
  162682. /* Emit restart marker if needed */
  162683. if (cinfo->restart_interval) {
  162684. if (entropy->restarts_to_go == 0)
  162685. if (! emit_restart(&state, entropy->next_restart_num))
  162686. return FALSE;
  162687. }
  162688. /* Encode the MCU data blocks */
  162689. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  162690. ci = cinfo->MCU_membership[blkn];
  162691. compptr = cinfo->cur_comp_info[ci];
  162692. if (! encode_one_block(&state,
  162693. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  162694. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  162695. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  162696. return FALSE;
  162697. /* Update last_dc_val */
  162698. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  162699. }
  162700. /* Completed MCU, so update state */
  162701. cinfo->dest->next_output_byte = state.next_output_byte;
  162702. cinfo->dest->free_in_buffer = state.free_in_buffer;
  162703. ASSIGN_STATE(entropy->saved, state.cur);
  162704. /* Update restart-interval state too */
  162705. if (cinfo->restart_interval) {
  162706. if (entropy->restarts_to_go == 0) {
  162707. entropy->restarts_to_go = cinfo->restart_interval;
  162708. entropy->next_restart_num++;
  162709. entropy->next_restart_num &= 7;
  162710. }
  162711. entropy->restarts_to_go--;
  162712. }
  162713. return TRUE;
  162714. }
  162715. /*
  162716. * Finish up at the end of a Huffman-compressed scan.
  162717. */
  162718. METHODDEF(void)
  162719. finish_pass_huff (j_compress_ptr cinfo)
  162720. {
  162721. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  162722. working_state state;
  162723. /* Load up working state ... flush_bits needs it */
  162724. state.next_output_byte = cinfo->dest->next_output_byte;
  162725. state.free_in_buffer = cinfo->dest->free_in_buffer;
  162726. ASSIGN_STATE(state.cur, entropy->saved);
  162727. state.cinfo = cinfo;
  162728. /* Flush out the last data */
  162729. if (! flush_bits(&state))
  162730. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  162731. /* Update state */
  162732. cinfo->dest->next_output_byte = state.next_output_byte;
  162733. cinfo->dest->free_in_buffer = state.free_in_buffer;
  162734. ASSIGN_STATE(entropy->saved, state.cur);
  162735. }
  162736. /*
  162737. * Huffman coding optimization.
  162738. *
  162739. * We first scan the supplied data and count the number of uses of each symbol
  162740. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  162741. * Then we build a Huffman coding tree for the observed counts.
  162742. * Symbols which are not needed at all for the particular image are not
  162743. * assigned any code, which saves space in the DHT marker as well as in
  162744. * the compressed data.
  162745. */
  162746. #ifdef ENTROPY_OPT_SUPPORTED
  162747. /* Process a single block's worth of coefficients */
  162748. LOCAL(void)
  162749. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  162750. long dc_counts[], long ac_counts[])
  162751. {
  162752. register int temp;
  162753. register int nbits;
  162754. register int k, r;
  162755. /* Encode the DC coefficient difference per section F.1.2.1 */
  162756. temp = block[0] - last_dc_val;
  162757. if (temp < 0)
  162758. temp = -temp;
  162759. /* Find the number of bits needed for the magnitude of the coefficient */
  162760. nbits = 0;
  162761. while (temp) {
  162762. nbits++;
  162763. temp >>= 1;
  162764. }
  162765. /* Check for out-of-range coefficient values.
  162766. * Since we're encoding a difference, the range limit is twice as much.
  162767. */
  162768. if (nbits > MAX_COEF_BITS+1)
  162769. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  162770. /* Count the Huffman symbol for the number of bits */
  162771. dc_counts[nbits]++;
  162772. /* Encode the AC coefficients per section F.1.2.2 */
  162773. r = 0; /* r = run length of zeros */
  162774. for (k = 1; k < DCTSIZE2; k++) {
  162775. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  162776. r++;
  162777. } else {
  162778. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  162779. while (r > 15) {
  162780. ac_counts[0xF0]++;
  162781. r -= 16;
  162782. }
  162783. /* Find the number of bits needed for the magnitude of the coefficient */
  162784. if (temp < 0)
  162785. temp = -temp;
  162786. /* Find the number of bits needed for the magnitude of the coefficient */
  162787. nbits = 1; /* there must be at least one 1 bit */
  162788. while ((temp >>= 1))
  162789. nbits++;
  162790. /* Check for out-of-range coefficient values */
  162791. if (nbits > MAX_COEF_BITS)
  162792. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  162793. /* Count Huffman symbol for run length / number of bits */
  162794. ac_counts[(r << 4) + nbits]++;
  162795. r = 0;
  162796. }
  162797. }
  162798. /* If the last coef(s) were zero, emit an end-of-block code */
  162799. if (r > 0)
  162800. ac_counts[0]++;
  162801. }
  162802. /*
  162803. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  162804. * No data is actually output, so no suspension return is possible.
  162805. */
  162806. METHODDEF(boolean)
  162807. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  162808. {
  162809. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  162810. int blkn, ci;
  162811. jpeg_component_info * compptr;
  162812. /* Take care of restart intervals if needed */
  162813. if (cinfo->restart_interval) {
  162814. if (entropy->restarts_to_go == 0) {
  162815. /* Re-initialize DC predictions to 0 */
  162816. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  162817. entropy->saved.last_dc_val[ci] = 0;
  162818. /* Update restart state */
  162819. entropy->restarts_to_go = cinfo->restart_interval;
  162820. }
  162821. entropy->restarts_to_go--;
  162822. }
  162823. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  162824. ci = cinfo->MCU_membership[blkn];
  162825. compptr = cinfo->cur_comp_info[ci];
  162826. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  162827. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  162828. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  162829. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  162830. }
  162831. return TRUE;
  162832. }
  162833. /*
  162834. * Generate the best Huffman code table for the given counts, fill htbl.
  162835. * Note this is also used by jcphuff.c.
  162836. *
  162837. * The JPEG standard requires that no symbol be assigned a codeword of all
  162838. * one bits (so that padding bits added at the end of a compressed segment
  162839. * can't look like a valid code). Because of the canonical ordering of
  162840. * codewords, this just means that there must be an unused slot in the
  162841. * longest codeword length category. Section K.2 of the JPEG spec suggests
  162842. * reserving such a slot by pretending that symbol 256 is a valid symbol
  162843. * with count 1. In theory that's not optimal; giving it count zero but
  162844. * including it in the symbol set anyway should give a better Huffman code.
  162845. * But the theoretically better code actually seems to come out worse in
  162846. * practice, because it produces more all-ones bytes (which incur stuffed
  162847. * zero bytes in the final file). In any case the difference is tiny.
  162848. *
  162849. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  162850. * If some symbols have a very small but nonzero probability, the Huffman tree
  162851. * must be adjusted to meet the code length restriction. We currently use
  162852. * the adjustment method suggested in JPEG section K.2. This method is *not*
  162853. * optimal; it may not choose the best possible limited-length code. But
  162854. * typically only very-low-frequency symbols will be given less-than-optimal
  162855. * lengths, so the code is almost optimal. Experimental comparisons against
  162856. * an optimal limited-length-code algorithm indicate that the difference is
  162857. * microscopic --- usually less than a hundredth of a percent of total size.
  162858. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  162859. */
  162860. GLOBAL(void)
  162861. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  162862. {
  162863. #define MAX_CLEN 32 /* assumed maximum initial code length */
  162864. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  162865. int codesize[257]; /* codesize[k] = code length of symbol k */
  162866. int others[257]; /* next symbol in current branch of tree */
  162867. int c1, c2;
  162868. int p, i, j;
  162869. long v;
  162870. /* This algorithm is explained in section K.2 of the JPEG standard */
  162871. MEMZERO(bits, SIZEOF(bits));
  162872. MEMZERO(codesize, SIZEOF(codesize));
  162873. for (i = 0; i < 257; i++)
  162874. others[i] = -1; /* init links to empty */
  162875. freq[256] = 1; /* make sure 256 has a nonzero count */
  162876. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  162877. * that no real symbol is given code-value of all ones, because 256
  162878. * will be placed last in the largest codeword category.
  162879. */
  162880. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  162881. for (;;) {
  162882. /* Find the smallest nonzero frequency, set c1 = its symbol */
  162883. /* In case of ties, take the larger symbol number */
  162884. c1 = -1;
  162885. v = 1000000000L;
  162886. for (i = 0; i <= 256; i++) {
  162887. if (freq[i] && freq[i] <= v) {
  162888. v = freq[i];
  162889. c1 = i;
  162890. }
  162891. }
  162892. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  162893. /* In case of ties, take the larger symbol number */
  162894. c2 = -1;
  162895. v = 1000000000L;
  162896. for (i = 0; i <= 256; i++) {
  162897. if (freq[i] && freq[i] <= v && i != c1) {
  162898. v = freq[i];
  162899. c2 = i;
  162900. }
  162901. }
  162902. /* Done if we've merged everything into one frequency */
  162903. if (c2 < 0)
  162904. break;
  162905. /* Else merge the two counts/trees */
  162906. freq[c1] += freq[c2];
  162907. freq[c2] = 0;
  162908. /* Increment the codesize of everything in c1's tree branch */
  162909. codesize[c1]++;
  162910. while (others[c1] >= 0) {
  162911. c1 = others[c1];
  162912. codesize[c1]++;
  162913. }
  162914. others[c1] = c2; /* chain c2 onto c1's tree branch */
  162915. /* Increment the codesize of everything in c2's tree branch */
  162916. codesize[c2]++;
  162917. while (others[c2] >= 0) {
  162918. c2 = others[c2];
  162919. codesize[c2]++;
  162920. }
  162921. }
  162922. /* Now count the number of symbols of each code length */
  162923. for (i = 0; i <= 256; i++) {
  162924. if (codesize[i]) {
  162925. /* The JPEG standard seems to think that this can't happen, */
  162926. /* but I'm paranoid... */
  162927. if (codesize[i] > MAX_CLEN)
  162928. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  162929. bits[codesize[i]]++;
  162930. }
  162931. }
  162932. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  162933. * Huffman procedure assigned any such lengths, we must adjust the coding.
  162934. * Here is what the JPEG spec says about how this next bit works:
  162935. * Since symbols are paired for the longest Huffman code, the symbols are
  162936. * removed from this length category two at a time. The prefix for the pair
  162937. * (which is one bit shorter) is allocated to one of the pair; then,
  162938. * skipping the BITS entry for that prefix length, a code word from the next
  162939. * shortest nonzero BITS entry is converted into a prefix for two code words
  162940. * one bit longer.
  162941. */
  162942. for (i = MAX_CLEN; i > 16; i--) {
  162943. while (bits[i] > 0) {
  162944. j = i - 2; /* find length of new prefix to be used */
  162945. while (bits[j] == 0)
  162946. j--;
  162947. bits[i] -= 2; /* remove two symbols */
  162948. bits[i-1]++; /* one goes in this length */
  162949. bits[j+1] += 2; /* two new symbols in this length */
  162950. bits[j]--; /* symbol of this length is now a prefix */
  162951. }
  162952. }
  162953. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  162954. while (bits[i] == 0) /* find largest codelength still in use */
  162955. i--;
  162956. bits[i]--;
  162957. /* Return final symbol counts (only for lengths 0..16) */
  162958. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  162959. /* Return a list of the symbols sorted by code length */
  162960. /* It's not real clear to me why we don't need to consider the codelength
  162961. * changes made above, but the JPEG spec seems to think this works.
  162962. */
  162963. p = 0;
  162964. for (i = 1; i <= MAX_CLEN; i++) {
  162965. for (j = 0; j <= 255; j++) {
  162966. if (codesize[j] == i) {
  162967. htbl->huffval[p] = (UINT8) j;
  162968. p++;
  162969. }
  162970. }
  162971. }
  162972. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  162973. htbl->sent_table = FALSE;
  162974. }
  162975. /*
  162976. * Finish up a statistics-gathering pass and create the new Huffman tables.
  162977. */
  162978. METHODDEF(void)
  162979. finish_pass_gather (j_compress_ptr cinfo)
  162980. {
  162981. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  162982. int ci, dctbl, actbl;
  162983. jpeg_component_info * compptr;
  162984. JHUFF_TBL **htblptr;
  162985. boolean did_dc[NUM_HUFF_TBLS];
  162986. boolean did_ac[NUM_HUFF_TBLS];
  162987. /* It's important not to apply jpeg_gen_optimal_table more than once
  162988. * per table, because it clobbers the input frequency counts!
  162989. */
  162990. MEMZERO(did_dc, SIZEOF(did_dc));
  162991. MEMZERO(did_ac, SIZEOF(did_ac));
  162992. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162993. compptr = cinfo->cur_comp_info[ci];
  162994. dctbl = compptr->dc_tbl_no;
  162995. actbl = compptr->ac_tbl_no;
  162996. if (! did_dc[dctbl]) {
  162997. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  162998. if (*htblptr == NULL)
  162999. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  163000. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  163001. did_dc[dctbl] = TRUE;
  163002. }
  163003. if (! did_ac[actbl]) {
  163004. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  163005. if (*htblptr == NULL)
  163006. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  163007. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  163008. did_ac[actbl] = TRUE;
  163009. }
  163010. }
  163011. }
  163012. #endif /* ENTROPY_OPT_SUPPORTED */
  163013. /*
  163014. * Module initialization routine for Huffman entropy encoding.
  163015. */
  163016. GLOBAL(void)
  163017. jinit_huff_encoder (j_compress_ptr cinfo)
  163018. {
  163019. huff_entropy_ptr entropy;
  163020. int i;
  163021. entropy = (huff_entropy_ptr)
  163022. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163023. SIZEOF(huff_entropy_encoder));
  163024. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  163025. entropy->pub.start_pass = start_pass_huff;
  163026. /* Mark tables unallocated */
  163027. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  163028. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  163029. #ifdef ENTROPY_OPT_SUPPORTED
  163030. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  163031. #endif
  163032. }
  163033. }
  163034. /*** End of inlined file: jchuff.c ***/
  163035. #undef emit_byte
  163036. /*** Start of inlined file: jcinit.c ***/
  163037. #define JPEG_INTERNALS
  163038. /*
  163039. * Master selection of compression modules.
  163040. * This is done once at the start of processing an image. We determine
  163041. * which modules will be used and give them appropriate initialization calls.
  163042. */
  163043. GLOBAL(void)
  163044. jinit_compress_master (j_compress_ptr cinfo)
  163045. {
  163046. /* Initialize master control (includes parameter checking/processing) */
  163047. jinit_c_master_control(cinfo, FALSE /* full compression */);
  163048. /* Preprocessing */
  163049. if (! cinfo->raw_data_in) {
  163050. jinit_color_converter(cinfo);
  163051. jinit_downsampler(cinfo);
  163052. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  163053. }
  163054. /* Forward DCT */
  163055. jinit_forward_dct(cinfo);
  163056. /* Entropy encoding: either Huffman or arithmetic coding. */
  163057. if (cinfo->arith_code) {
  163058. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  163059. } else {
  163060. if (cinfo->progressive_mode) {
  163061. #ifdef C_PROGRESSIVE_SUPPORTED
  163062. jinit_phuff_encoder(cinfo);
  163063. #else
  163064. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163065. #endif
  163066. } else
  163067. jinit_huff_encoder(cinfo);
  163068. }
  163069. /* Need a full-image coefficient buffer in any multi-pass mode. */
  163070. jinit_c_coef_controller(cinfo,
  163071. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  163072. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  163073. jinit_marker_writer(cinfo);
  163074. /* We can now tell the memory manager to allocate virtual arrays. */
  163075. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  163076. /* Write the datastream header (SOI) immediately.
  163077. * Frame and scan headers are postponed till later.
  163078. * This lets application insert special markers after the SOI.
  163079. */
  163080. (*cinfo->marker->write_file_header) (cinfo);
  163081. }
  163082. /*** End of inlined file: jcinit.c ***/
  163083. /*** Start of inlined file: jcmainct.c ***/
  163084. #define JPEG_INTERNALS
  163085. /* Note: currently, there is no operating mode in which a full-image buffer
  163086. * is needed at this step. If there were, that mode could not be used with
  163087. * "raw data" input, since this module is bypassed in that case. However,
  163088. * we've left the code here for possible use in special applications.
  163089. */
  163090. #undef FULL_MAIN_BUFFER_SUPPORTED
  163091. /* Private buffer controller object */
  163092. typedef struct {
  163093. struct jpeg_c_main_controller pub; /* public fields */
  163094. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  163095. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  163096. boolean suspended; /* remember if we suspended output */
  163097. J_BUF_MODE pass_mode; /* current operating mode */
  163098. /* If using just a strip buffer, this points to the entire set of buffers
  163099. * (we allocate one for each component). In the full-image case, this
  163100. * points to the currently accessible strips of the virtual arrays.
  163101. */
  163102. JSAMPARRAY buffer[MAX_COMPONENTS];
  163103. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163104. /* If using full-image storage, this array holds pointers to virtual-array
  163105. * control blocks for each component. Unused if not full-image storage.
  163106. */
  163107. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  163108. #endif
  163109. } my_main_controller;
  163110. typedef my_main_controller * my_main_ptr;
  163111. /* Forward declarations */
  163112. METHODDEF(void) process_data_simple_main
  163113. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  163114. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  163115. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163116. METHODDEF(void) process_data_buffer_main
  163117. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  163118. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  163119. #endif
  163120. /*
  163121. * Initialize for a processing pass.
  163122. */
  163123. METHODDEF(void)
  163124. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  163125. {
  163126. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  163127. /* Do nothing in raw-data mode. */
  163128. if (cinfo->raw_data_in)
  163129. return;
  163130. main_->cur_iMCU_row = 0; /* initialize counters */
  163131. main_->rowgroup_ctr = 0;
  163132. main_->suspended = FALSE;
  163133. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  163134. switch (pass_mode) {
  163135. case JBUF_PASS_THRU:
  163136. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163137. if (main_->whole_image[0] != NULL)
  163138. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163139. #endif
  163140. main_->pub.process_data = process_data_simple_main;
  163141. break;
  163142. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163143. case JBUF_SAVE_SOURCE:
  163144. case JBUF_CRANK_DEST:
  163145. case JBUF_SAVE_AND_PASS:
  163146. if (main_->whole_image[0] == NULL)
  163147. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163148. main_->pub.process_data = process_data_buffer_main;
  163149. break;
  163150. #endif
  163151. default:
  163152. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163153. break;
  163154. }
  163155. }
  163156. /*
  163157. * Process some data.
  163158. * This routine handles the simple pass-through mode,
  163159. * where we have only a strip buffer.
  163160. */
  163161. METHODDEF(void)
  163162. process_data_simple_main (j_compress_ptr cinfo,
  163163. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  163164. JDIMENSION in_rows_avail)
  163165. {
  163166. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  163167. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  163168. /* Read input data if we haven't filled the main buffer yet */
  163169. if (main_->rowgroup_ctr < DCTSIZE)
  163170. (*cinfo->prep->pre_process_data) (cinfo,
  163171. input_buf, in_row_ctr, in_rows_avail,
  163172. main_->buffer, &main_->rowgroup_ctr,
  163173. (JDIMENSION) DCTSIZE);
  163174. /* If we don't have a full iMCU row buffered, return to application for
  163175. * more data. Note that preprocessor will always pad to fill the iMCU row
  163176. * at the bottom of the image.
  163177. */
  163178. if (main_->rowgroup_ctr != DCTSIZE)
  163179. return;
  163180. /* Send the completed row to the compressor */
  163181. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  163182. /* If compressor did not consume the whole row, then we must need to
  163183. * suspend processing and return to the application. In this situation
  163184. * we pretend we didn't yet consume the last input row; otherwise, if
  163185. * it happened to be the last row of the image, the application would
  163186. * think we were done.
  163187. */
  163188. if (! main_->suspended) {
  163189. (*in_row_ctr)--;
  163190. main_->suspended = TRUE;
  163191. }
  163192. return;
  163193. }
  163194. /* We did finish the row. Undo our little suspension hack if a previous
  163195. * call suspended; then mark the main buffer empty.
  163196. */
  163197. if (main_->suspended) {
  163198. (*in_row_ctr)++;
  163199. main_->suspended = FALSE;
  163200. }
  163201. main_->rowgroup_ctr = 0;
  163202. main_->cur_iMCU_row++;
  163203. }
  163204. }
  163205. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163206. /*
  163207. * Process some data.
  163208. * This routine handles all of the modes that use a full-size buffer.
  163209. */
  163210. METHODDEF(void)
  163211. process_data_buffer_main (j_compress_ptr cinfo,
  163212. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  163213. JDIMENSION in_rows_avail)
  163214. {
  163215. my_main_ptr main = (my_main_ptr) cinfo->main;
  163216. int ci;
  163217. jpeg_component_info *compptr;
  163218. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  163219. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  163220. /* Realign the virtual buffers if at the start of an iMCU row. */
  163221. if (main->rowgroup_ctr == 0) {
  163222. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163223. ci++, compptr++) {
  163224. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  163225. ((j_common_ptr) cinfo, main->whole_image[ci],
  163226. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  163227. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  163228. }
  163229. /* In a read pass, pretend we just read some source data. */
  163230. if (! writing) {
  163231. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  163232. main->rowgroup_ctr = DCTSIZE;
  163233. }
  163234. }
  163235. /* If a write pass, read input data until the current iMCU row is full. */
  163236. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  163237. if (writing) {
  163238. (*cinfo->prep->pre_process_data) (cinfo,
  163239. input_buf, in_row_ctr, in_rows_avail,
  163240. main->buffer, &main->rowgroup_ctr,
  163241. (JDIMENSION) DCTSIZE);
  163242. /* Return to application if we need more data to fill the iMCU row. */
  163243. if (main->rowgroup_ctr < DCTSIZE)
  163244. return;
  163245. }
  163246. /* Emit data, unless this is a sink-only pass. */
  163247. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  163248. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  163249. /* If compressor did not consume the whole row, then we must need to
  163250. * suspend processing and return to the application. In this situation
  163251. * we pretend we didn't yet consume the last input row; otherwise, if
  163252. * it happened to be the last row of the image, the application would
  163253. * think we were done.
  163254. */
  163255. if (! main->suspended) {
  163256. (*in_row_ctr)--;
  163257. main->suspended = TRUE;
  163258. }
  163259. return;
  163260. }
  163261. /* We did finish the row. Undo our little suspension hack if a previous
  163262. * call suspended; then mark the main buffer empty.
  163263. */
  163264. if (main->suspended) {
  163265. (*in_row_ctr)++;
  163266. main->suspended = FALSE;
  163267. }
  163268. }
  163269. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  163270. main->rowgroup_ctr = 0;
  163271. main->cur_iMCU_row++;
  163272. }
  163273. }
  163274. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  163275. /*
  163276. * Initialize main buffer controller.
  163277. */
  163278. GLOBAL(void)
  163279. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  163280. {
  163281. my_main_ptr main_;
  163282. int ci;
  163283. jpeg_component_info *compptr;
  163284. main_ = (my_main_ptr)
  163285. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163286. SIZEOF(my_main_controller));
  163287. cinfo->main = (struct jpeg_c_main_controller *) main_;
  163288. main_->pub.start_pass = start_pass_main;
  163289. /* We don't need to create a buffer in raw-data mode. */
  163290. if (cinfo->raw_data_in)
  163291. return;
  163292. /* Create the buffer. It holds downsampled data, so each component
  163293. * may be of a different size.
  163294. */
  163295. if (need_full_buffer) {
  163296. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163297. /* Allocate a full-image virtual array for each component */
  163298. /* Note we pad the bottom to a multiple of the iMCU height */
  163299. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163300. ci++, compptr++) {
  163301. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  163302. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  163303. compptr->width_in_blocks * DCTSIZE,
  163304. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  163305. (long) compptr->v_samp_factor) * DCTSIZE,
  163306. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  163307. }
  163308. #else
  163309. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163310. #endif
  163311. } else {
  163312. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163313. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  163314. #endif
  163315. /* Allocate a strip buffer for each component */
  163316. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163317. ci++, compptr++) {
  163318. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  163319. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163320. compptr->width_in_blocks * DCTSIZE,
  163321. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  163322. }
  163323. }
  163324. }
  163325. /*** End of inlined file: jcmainct.c ***/
  163326. /*** Start of inlined file: jcmarker.c ***/
  163327. #define JPEG_INTERNALS
  163328. /* Private state */
  163329. typedef struct {
  163330. struct jpeg_marker_writer pub; /* public fields */
  163331. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  163332. } my_marker_writer;
  163333. typedef my_marker_writer * my_marker_ptr;
  163334. /*
  163335. * Basic output routines.
  163336. *
  163337. * Note that we do not support suspension while writing a marker.
  163338. * Therefore, an application using suspension must ensure that there is
  163339. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  163340. * calling jpeg_start_compress, and enough space to write the trailing EOI
  163341. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  163342. * modes are not supported at all with suspension, so those two are the only
  163343. * points where markers will be written.
  163344. */
  163345. LOCAL(void)
  163346. emit_byte (j_compress_ptr cinfo, int val)
  163347. /* Emit a byte */
  163348. {
  163349. struct jpeg_destination_mgr * dest = cinfo->dest;
  163350. *(dest->next_output_byte)++ = (JOCTET) val;
  163351. if (--dest->free_in_buffer == 0) {
  163352. if (! (*dest->empty_output_buffer) (cinfo))
  163353. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  163354. }
  163355. }
  163356. LOCAL(void)
  163357. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  163358. /* Emit a marker code */
  163359. {
  163360. emit_byte(cinfo, 0xFF);
  163361. emit_byte(cinfo, (int) mark);
  163362. }
  163363. LOCAL(void)
  163364. emit_2bytes (j_compress_ptr cinfo, int value)
  163365. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  163366. {
  163367. emit_byte(cinfo, (value >> 8) & 0xFF);
  163368. emit_byte(cinfo, value & 0xFF);
  163369. }
  163370. /*
  163371. * Routines to write specific marker types.
  163372. */
  163373. LOCAL(int)
  163374. emit_dqt (j_compress_ptr cinfo, int index)
  163375. /* Emit a DQT marker */
  163376. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  163377. {
  163378. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  163379. int prec;
  163380. int i;
  163381. if (qtbl == NULL)
  163382. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  163383. prec = 0;
  163384. for (i = 0; i < DCTSIZE2; i++) {
  163385. if (qtbl->quantval[i] > 255)
  163386. prec = 1;
  163387. }
  163388. if (! qtbl->sent_table) {
  163389. emit_marker(cinfo, M_DQT);
  163390. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  163391. emit_byte(cinfo, index + (prec<<4));
  163392. for (i = 0; i < DCTSIZE2; i++) {
  163393. /* The table entries must be emitted in zigzag order. */
  163394. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  163395. if (prec)
  163396. emit_byte(cinfo, (int) (qval >> 8));
  163397. emit_byte(cinfo, (int) (qval & 0xFF));
  163398. }
  163399. qtbl->sent_table = TRUE;
  163400. }
  163401. return prec;
  163402. }
  163403. LOCAL(void)
  163404. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  163405. /* Emit a DHT marker */
  163406. {
  163407. JHUFF_TBL * htbl;
  163408. int length, i;
  163409. if (is_ac) {
  163410. htbl = cinfo->ac_huff_tbl_ptrs[index];
  163411. index += 0x10; /* output index has AC bit set */
  163412. } else {
  163413. htbl = cinfo->dc_huff_tbl_ptrs[index];
  163414. }
  163415. if (htbl == NULL)
  163416. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  163417. if (! htbl->sent_table) {
  163418. emit_marker(cinfo, M_DHT);
  163419. length = 0;
  163420. for (i = 1; i <= 16; i++)
  163421. length += htbl->bits[i];
  163422. emit_2bytes(cinfo, length + 2 + 1 + 16);
  163423. emit_byte(cinfo, index);
  163424. for (i = 1; i <= 16; i++)
  163425. emit_byte(cinfo, htbl->bits[i]);
  163426. for (i = 0; i < length; i++)
  163427. emit_byte(cinfo, htbl->huffval[i]);
  163428. htbl->sent_table = TRUE;
  163429. }
  163430. }
  163431. LOCAL(void)
  163432. emit_dac (j_compress_ptr)
  163433. /* Emit a DAC marker */
  163434. /* Since the useful info is so small, we want to emit all the tables in */
  163435. /* one DAC marker. Therefore this routine does its own scan of the table. */
  163436. {
  163437. #ifdef C_ARITH_CODING_SUPPORTED
  163438. char dc_in_use[NUM_ARITH_TBLS];
  163439. char ac_in_use[NUM_ARITH_TBLS];
  163440. int length, i;
  163441. jpeg_component_info *compptr;
  163442. for (i = 0; i < NUM_ARITH_TBLS; i++)
  163443. dc_in_use[i] = ac_in_use[i] = 0;
  163444. for (i = 0; i < cinfo->comps_in_scan; i++) {
  163445. compptr = cinfo->cur_comp_info[i];
  163446. dc_in_use[compptr->dc_tbl_no] = 1;
  163447. ac_in_use[compptr->ac_tbl_no] = 1;
  163448. }
  163449. length = 0;
  163450. for (i = 0; i < NUM_ARITH_TBLS; i++)
  163451. length += dc_in_use[i] + ac_in_use[i];
  163452. emit_marker(cinfo, M_DAC);
  163453. emit_2bytes(cinfo, length*2 + 2);
  163454. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  163455. if (dc_in_use[i]) {
  163456. emit_byte(cinfo, i);
  163457. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  163458. }
  163459. if (ac_in_use[i]) {
  163460. emit_byte(cinfo, i + 0x10);
  163461. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  163462. }
  163463. }
  163464. #endif /* C_ARITH_CODING_SUPPORTED */
  163465. }
  163466. LOCAL(void)
  163467. emit_dri (j_compress_ptr cinfo)
  163468. /* Emit a DRI marker */
  163469. {
  163470. emit_marker(cinfo, M_DRI);
  163471. emit_2bytes(cinfo, 4); /* fixed length */
  163472. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  163473. }
  163474. LOCAL(void)
  163475. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  163476. /* Emit a SOF marker */
  163477. {
  163478. int ci;
  163479. jpeg_component_info *compptr;
  163480. emit_marker(cinfo, code);
  163481. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  163482. /* Make sure image isn't bigger than SOF field can handle */
  163483. if ((long) cinfo->image_height > 65535L ||
  163484. (long) cinfo->image_width > 65535L)
  163485. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  163486. emit_byte(cinfo, cinfo->data_precision);
  163487. emit_2bytes(cinfo, (int) cinfo->image_height);
  163488. emit_2bytes(cinfo, (int) cinfo->image_width);
  163489. emit_byte(cinfo, cinfo->num_components);
  163490. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163491. ci++, compptr++) {
  163492. emit_byte(cinfo, compptr->component_id);
  163493. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  163494. emit_byte(cinfo, compptr->quant_tbl_no);
  163495. }
  163496. }
  163497. LOCAL(void)
  163498. emit_sos (j_compress_ptr cinfo)
  163499. /* Emit a SOS marker */
  163500. {
  163501. int i, td, ta;
  163502. jpeg_component_info *compptr;
  163503. emit_marker(cinfo, M_SOS);
  163504. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  163505. emit_byte(cinfo, cinfo->comps_in_scan);
  163506. for (i = 0; i < cinfo->comps_in_scan; i++) {
  163507. compptr = cinfo->cur_comp_info[i];
  163508. emit_byte(cinfo, compptr->component_id);
  163509. td = compptr->dc_tbl_no;
  163510. ta = compptr->ac_tbl_no;
  163511. if (cinfo->progressive_mode) {
  163512. /* Progressive mode: only DC or only AC tables are used in one scan;
  163513. * furthermore, Huffman coding of DC refinement uses no table at all.
  163514. * We emit 0 for unused field(s); this is recommended by the P&M text
  163515. * but does not seem to be specified in the standard.
  163516. */
  163517. if (cinfo->Ss == 0) {
  163518. ta = 0; /* DC scan */
  163519. if (cinfo->Ah != 0 && !cinfo->arith_code)
  163520. td = 0; /* no DC table either */
  163521. } else {
  163522. td = 0; /* AC scan */
  163523. }
  163524. }
  163525. emit_byte(cinfo, (td << 4) + ta);
  163526. }
  163527. emit_byte(cinfo, cinfo->Ss);
  163528. emit_byte(cinfo, cinfo->Se);
  163529. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  163530. }
  163531. LOCAL(void)
  163532. emit_jfif_app0 (j_compress_ptr cinfo)
  163533. /* Emit a JFIF-compliant APP0 marker */
  163534. {
  163535. /*
  163536. * Length of APP0 block (2 bytes)
  163537. * Block ID (4 bytes - ASCII "JFIF")
  163538. * Zero byte (1 byte to terminate the ID string)
  163539. * Version Major, Minor (2 bytes - major first)
  163540. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  163541. * Xdpu (2 bytes - dots per unit horizontal)
  163542. * Ydpu (2 bytes - dots per unit vertical)
  163543. * Thumbnail X size (1 byte)
  163544. * Thumbnail Y size (1 byte)
  163545. */
  163546. emit_marker(cinfo, M_APP0);
  163547. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  163548. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  163549. emit_byte(cinfo, 0x46);
  163550. emit_byte(cinfo, 0x49);
  163551. emit_byte(cinfo, 0x46);
  163552. emit_byte(cinfo, 0);
  163553. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  163554. emit_byte(cinfo, cinfo->JFIF_minor_version);
  163555. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  163556. emit_2bytes(cinfo, (int) cinfo->X_density);
  163557. emit_2bytes(cinfo, (int) cinfo->Y_density);
  163558. emit_byte(cinfo, 0); /* No thumbnail image */
  163559. emit_byte(cinfo, 0);
  163560. }
  163561. LOCAL(void)
  163562. emit_adobe_app14 (j_compress_ptr cinfo)
  163563. /* Emit an Adobe APP14 marker */
  163564. {
  163565. /*
  163566. * Length of APP14 block (2 bytes)
  163567. * Block ID (5 bytes - ASCII "Adobe")
  163568. * Version Number (2 bytes - currently 100)
  163569. * Flags0 (2 bytes - currently 0)
  163570. * Flags1 (2 bytes - currently 0)
  163571. * Color transform (1 byte)
  163572. *
  163573. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  163574. * now in circulation seem to use Version = 100, so that's what we write.
  163575. *
  163576. * We write the color transform byte as 1 if the JPEG color space is
  163577. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  163578. * whether the encoder performed a transformation, which is pretty useless.
  163579. */
  163580. emit_marker(cinfo, M_APP14);
  163581. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  163582. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  163583. emit_byte(cinfo, 0x64);
  163584. emit_byte(cinfo, 0x6F);
  163585. emit_byte(cinfo, 0x62);
  163586. emit_byte(cinfo, 0x65);
  163587. emit_2bytes(cinfo, 100); /* Version */
  163588. emit_2bytes(cinfo, 0); /* Flags0 */
  163589. emit_2bytes(cinfo, 0); /* Flags1 */
  163590. switch (cinfo->jpeg_color_space) {
  163591. case JCS_YCbCr:
  163592. emit_byte(cinfo, 1); /* Color transform = 1 */
  163593. break;
  163594. case JCS_YCCK:
  163595. emit_byte(cinfo, 2); /* Color transform = 2 */
  163596. break;
  163597. default:
  163598. emit_byte(cinfo, 0); /* Color transform = 0 */
  163599. break;
  163600. }
  163601. }
  163602. /*
  163603. * These routines allow writing an arbitrary marker with parameters.
  163604. * The only intended use is to emit COM or APPn markers after calling
  163605. * write_file_header and before calling write_frame_header.
  163606. * Other uses are not guaranteed to produce desirable results.
  163607. * Counting the parameter bytes properly is the caller's responsibility.
  163608. */
  163609. METHODDEF(void)
  163610. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  163611. /* Emit an arbitrary marker header */
  163612. {
  163613. if (datalen > (unsigned int) 65533) /* safety check */
  163614. ERREXIT(cinfo, JERR_BAD_LENGTH);
  163615. emit_marker(cinfo, (JPEG_MARKER) marker);
  163616. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  163617. }
  163618. METHODDEF(void)
  163619. write_marker_byte (j_compress_ptr cinfo, int val)
  163620. /* Emit one byte of marker parameters following write_marker_header */
  163621. {
  163622. emit_byte(cinfo, val);
  163623. }
  163624. /*
  163625. * Write datastream header.
  163626. * This consists of an SOI and optional APPn markers.
  163627. * We recommend use of the JFIF marker, but not the Adobe marker,
  163628. * when using YCbCr or grayscale data. The JFIF marker should NOT
  163629. * be used for any other JPEG colorspace. The Adobe marker is helpful
  163630. * to distinguish RGB, CMYK, and YCCK colorspaces.
  163631. * Note that an application can write additional header markers after
  163632. * jpeg_start_compress returns.
  163633. */
  163634. METHODDEF(void)
  163635. write_file_header (j_compress_ptr cinfo)
  163636. {
  163637. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  163638. emit_marker(cinfo, M_SOI); /* first the SOI */
  163639. /* SOI is defined to reset restart interval to 0 */
  163640. marker->last_restart_interval = 0;
  163641. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  163642. emit_jfif_app0(cinfo);
  163643. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  163644. emit_adobe_app14(cinfo);
  163645. }
  163646. /*
  163647. * Write frame header.
  163648. * This consists of DQT and SOFn markers.
  163649. * Note that we do not emit the SOF until we have emitted the DQT(s).
  163650. * This avoids compatibility problems with incorrect implementations that
  163651. * try to error-check the quant table numbers as soon as they see the SOF.
  163652. */
  163653. METHODDEF(void)
  163654. write_frame_header (j_compress_ptr cinfo)
  163655. {
  163656. int ci, prec;
  163657. boolean is_baseline;
  163658. jpeg_component_info *compptr;
  163659. /* Emit DQT for each quantization table.
  163660. * Note that emit_dqt() suppresses any duplicate tables.
  163661. */
  163662. prec = 0;
  163663. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163664. ci++, compptr++) {
  163665. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  163666. }
  163667. /* now prec is nonzero iff there are any 16-bit quant tables. */
  163668. /* Check for a non-baseline specification.
  163669. * Note we assume that Huffman table numbers won't be changed later.
  163670. */
  163671. if (cinfo->arith_code || cinfo->progressive_mode ||
  163672. cinfo->data_precision != 8) {
  163673. is_baseline = FALSE;
  163674. } else {
  163675. is_baseline = TRUE;
  163676. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163677. ci++, compptr++) {
  163678. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  163679. is_baseline = FALSE;
  163680. }
  163681. if (prec && is_baseline) {
  163682. is_baseline = FALSE;
  163683. /* If it's baseline except for quantizer size, warn the user */
  163684. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  163685. }
  163686. }
  163687. /* Emit the proper SOF marker */
  163688. if (cinfo->arith_code) {
  163689. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  163690. } else {
  163691. if (cinfo->progressive_mode)
  163692. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  163693. else if (is_baseline)
  163694. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  163695. else
  163696. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  163697. }
  163698. }
  163699. /*
  163700. * Write scan header.
  163701. * This consists of DHT or DAC markers, optional DRI, and SOS.
  163702. * Compressed data will be written following the SOS.
  163703. */
  163704. METHODDEF(void)
  163705. write_scan_header (j_compress_ptr cinfo)
  163706. {
  163707. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  163708. int i;
  163709. jpeg_component_info *compptr;
  163710. if (cinfo->arith_code) {
  163711. /* Emit arith conditioning info. We may have some duplication
  163712. * if the file has multiple scans, but it's so small it's hardly
  163713. * worth worrying about.
  163714. */
  163715. emit_dac(cinfo);
  163716. } else {
  163717. /* Emit Huffman tables.
  163718. * Note that emit_dht() suppresses any duplicate tables.
  163719. */
  163720. for (i = 0; i < cinfo->comps_in_scan; i++) {
  163721. compptr = cinfo->cur_comp_info[i];
  163722. if (cinfo->progressive_mode) {
  163723. /* Progressive mode: only DC or only AC tables are used in one scan */
  163724. if (cinfo->Ss == 0) {
  163725. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  163726. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  163727. } else {
  163728. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  163729. }
  163730. } else {
  163731. /* Sequential mode: need both DC and AC tables */
  163732. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  163733. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  163734. }
  163735. }
  163736. }
  163737. /* Emit DRI if required --- note that DRI value could change for each scan.
  163738. * We avoid wasting space with unnecessary DRIs, however.
  163739. */
  163740. if (cinfo->restart_interval != marker->last_restart_interval) {
  163741. emit_dri(cinfo);
  163742. marker->last_restart_interval = cinfo->restart_interval;
  163743. }
  163744. emit_sos(cinfo);
  163745. }
  163746. /*
  163747. * Write datastream trailer.
  163748. */
  163749. METHODDEF(void)
  163750. write_file_trailer (j_compress_ptr cinfo)
  163751. {
  163752. emit_marker(cinfo, M_EOI);
  163753. }
  163754. /*
  163755. * Write an abbreviated table-specification datastream.
  163756. * This consists of SOI, DQT and DHT tables, and EOI.
  163757. * Any table that is defined and not marked sent_table = TRUE will be
  163758. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  163759. */
  163760. METHODDEF(void)
  163761. write_tables_only (j_compress_ptr cinfo)
  163762. {
  163763. int i;
  163764. emit_marker(cinfo, M_SOI);
  163765. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  163766. if (cinfo->quant_tbl_ptrs[i] != NULL)
  163767. (void) emit_dqt(cinfo, i);
  163768. }
  163769. if (! cinfo->arith_code) {
  163770. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  163771. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  163772. emit_dht(cinfo, i, FALSE);
  163773. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  163774. emit_dht(cinfo, i, TRUE);
  163775. }
  163776. }
  163777. emit_marker(cinfo, M_EOI);
  163778. }
  163779. /*
  163780. * Initialize the marker writer module.
  163781. */
  163782. GLOBAL(void)
  163783. jinit_marker_writer (j_compress_ptr cinfo)
  163784. {
  163785. my_marker_ptr marker;
  163786. /* Create the subobject */
  163787. marker = (my_marker_ptr)
  163788. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163789. SIZEOF(my_marker_writer));
  163790. cinfo->marker = (struct jpeg_marker_writer *) marker;
  163791. /* Initialize method pointers */
  163792. marker->pub.write_file_header = write_file_header;
  163793. marker->pub.write_frame_header = write_frame_header;
  163794. marker->pub.write_scan_header = write_scan_header;
  163795. marker->pub.write_file_trailer = write_file_trailer;
  163796. marker->pub.write_tables_only = write_tables_only;
  163797. marker->pub.write_marker_header = write_marker_header;
  163798. marker->pub.write_marker_byte = write_marker_byte;
  163799. /* Initialize private state */
  163800. marker->last_restart_interval = 0;
  163801. }
  163802. /*** End of inlined file: jcmarker.c ***/
  163803. /*** Start of inlined file: jcmaster.c ***/
  163804. #define JPEG_INTERNALS
  163805. /* Private state */
  163806. typedef enum {
  163807. main_pass, /* input data, also do first output step */
  163808. huff_opt_pass, /* Huffman code optimization pass */
  163809. output_pass /* data output pass */
  163810. } c_pass_type;
  163811. typedef struct {
  163812. struct jpeg_comp_master pub; /* public fields */
  163813. c_pass_type pass_type; /* the type of the current pass */
  163814. int pass_number; /* # of passes completed */
  163815. int total_passes; /* total # of passes needed */
  163816. int scan_number; /* current index in scan_info[] */
  163817. } my_comp_master;
  163818. typedef my_comp_master * my_master_ptr;
  163819. /*
  163820. * Support routines that do various essential calculations.
  163821. */
  163822. LOCAL(void)
  163823. initial_setup (j_compress_ptr cinfo)
  163824. /* Do computations that are needed before master selection phase */
  163825. {
  163826. int ci;
  163827. jpeg_component_info *compptr;
  163828. long samplesperrow;
  163829. JDIMENSION jd_samplesperrow;
  163830. /* Sanity check on image dimensions */
  163831. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  163832. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  163833. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  163834. /* Make sure image isn't bigger than I can handle */
  163835. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  163836. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  163837. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  163838. /* Width of an input scanline must be representable as JDIMENSION. */
  163839. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  163840. jd_samplesperrow = (JDIMENSION) samplesperrow;
  163841. if ((long) jd_samplesperrow != samplesperrow)
  163842. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  163843. /* For now, precision must match compiled-in value... */
  163844. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  163845. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  163846. /* Check that number of components won't exceed internal array sizes */
  163847. if (cinfo->num_components > MAX_COMPONENTS)
  163848. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  163849. MAX_COMPONENTS);
  163850. /* Compute maximum sampling factors; check factor validity */
  163851. cinfo->max_h_samp_factor = 1;
  163852. cinfo->max_v_samp_factor = 1;
  163853. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163854. ci++, compptr++) {
  163855. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  163856. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  163857. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  163858. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  163859. compptr->h_samp_factor);
  163860. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  163861. compptr->v_samp_factor);
  163862. }
  163863. /* Compute dimensions of components */
  163864. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163865. ci++, compptr++) {
  163866. /* Fill in the correct component_index value; don't rely on application */
  163867. compptr->component_index = ci;
  163868. /* For compression, we never do DCT scaling. */
  163869. compptr->DCT_scaled_size = DCTSIZE;
  163870. /* Size in DCT blocks */
  163871. compptr->width_in_blocks = (JDIMENSION)
  163872. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  163873. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  163874. compptr->height_in_blocks = (JDIMENSION)
  163875. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  163876. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  163877. /* Size in samples */
  163878. compptr->downsampled_width = (JDIMENSION)
  163879. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  163880. (long) cinfo->max_h_samp_factor);
  163881. compptr->downsampled_height = (JDIMENSION)
  163882. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  163883. (long) cinfo->max_v_samp_factor);
  163884. /* Mark component needed (this flag isn't actually used for compression) */
  163885. compptr->component_needed = TRUE;
  163886. }
  163887. /* Compute number of fully interleaved MCU rows (number of times that
  163888. * main controller will call coefficient controller).
  163889. */
  163890. cinfo->total_iMCU_rows = (JDIMENSION)
  163891. jdiv_round_up((long) cinfo->image_height,
  163892. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  163893. }
  163894. #ifdef C_MULTISCAN_FILES_SUPPORTED
  163895. LOCAL(void)
  163896. validate_script (j_compress_ptr cinfo)
  163897. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  163898. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  163899. */
  163900. {
  163901. const jpeg_scan_info * scanptr;
  163902. int scanno, ncomps, ci, coefi, thisi;
  163903. int Ss, Se, Ah, Al;
  163904. boolean component_sent[MAX_COMPONENTS];
  163905. #ifdef C_PROGRESSIVE_SUPPORTED
  163906. int * last_bitpos_ptr;
  163907. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  163908. /* -1 until that coefficient has been seen; then last Al for it */
  163909. #endif
  163910. if (cinfo->num_scans <= 0)
  163911. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  163912. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  163913. * for progressive JPEG, no scan can have this.
  163914. */
  163915. scanptr = cinfo->scan_info;
  163916. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  163917. #ifdef C_PROGRESSIVE_SUPPORTED
  163918. cinfo->progressive_mode = TRUE;
  163919. last_bitpos_ptr = & last_bitpos[0][0];
  163920. for (ci = 0; ci < cinfo->num_components; ci++)
  163921. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  163922. *last_bitpos_ptr++ = -1;
  163923. #else
  163924. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163925. #endif
  163926. } else {
  163927. cinfo->progressive_mode = FALSE;
  163928. for (ci = 0; ci < cinfo->num_components; ci++)
  163929. component_sent[ci] = FALSE;
  163930. }
  163931. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  163932. /* Validate component indexes */
  163933. ncomps = scanptr->comps_in_scan;
  163934. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  163935. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  163936. for (ci = 0; ci < ncomps; ci++) {
  163937. thisi = scanptr->component_index[ci];
  163938. if (thisi < 0 || thisi >= cinfo->num_components)
  163939. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  163940. /* Components must appear in SOF order within each scan */
  163941. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  163942. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  163943. }
  163944. /* Validate progression parameters */
  163945. Ss = scanptr->Ss;
  163946. Se = scanptr->Se;
  163947. Ah = scanptr->Ah;
  163948. Al = scanptr->Al;
  163949. if (cinfo->progressive_mode) {
  163950. #ifdef C_PROGRESSIVE_SUPPORTED
  163951. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  163952. * seems wrong: the upper bound ought to depend on data precision.
  163953. * Perhaps they really meant 0..N+1 for N-bit precision.
  163954. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  163955. * out-of-range reconstructed DC values during the first DC scan,
  163956. * which might cause problems for some decoders.
  163957. */
  163958. #if BITS_IN_JSAMPLE == 8
  163959. #define MAX_AH_AL 10
  163960. #else
  163961. #define MAX_AH_AL 13
  163962. #endif
  163963. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  163964. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  163965. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  163966. if (Ss == 0) {
  163967. if (Se != 0) /* DC and AC together not OK */
  163968. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  163969. } else {
  163970. if (ncomps != 1) /* AC scans must be for only one component */
  163971. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  163972. }
  163973. for (ci = 0; ci < ncomps; ci++) {
  163974. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  163975. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  163976. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  163977. for (coefi = Ss; coefi <= Se; coefi++) {
  163978. if (last_bitpos_ptr[coefi] < 0) {
  163979. /* first scan of this coefficient */
  163980. if (Ah != 0)
  163981. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  163982. } else {
  163983. /* not first scan */
  163984. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  163985. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  163986. }
  163987. last_bitpos_ptr[coefi] = Al;
  163988. }
  163989. }
  163990. #endif
  163991. } else {
  163992. /* For sequential JPEG, all progression parameters must be these: */
  163993. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  163994. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  163995. /* Make sure components are not sent twice */
  163996. for (ci = 0; ci < ncomps; ci++) {
  163997. thisi = scanptr->component_index[ci];
  163998. if (component_sent[thisi])
  163999. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164000. component_sent[thisi] = TRUE;
  164001. }
  164002. }
  164003. }
  164004. /* Now verify that everything got sent. */
  164005. if (cinfo->progressive_mode) {
  164006. #ifdef C_PROGRESSIVE_SUPPORTED
  164007. /* For progressive mode, we only check that at least some DC data
  164008. * got sent for each component; the spec does not require that all bits
  164009. * of all coefficients be transmitted. Would it be wiser to enforce
  164010. * transmission of all coefficient bits??
  164011. */
  164012. for (ci = 0; ci < cinfo->num_components; ci++) {
  164013. if (last_bitpos[ci][0] < 0)
  164014. ERREXIT(cinfo, JERR_MISSING_DATA);
  164015. }
  164016. #endif
  164017. } else {
  164018. for (ci = 0; ci < cinfo->num_components; ci++) {
  164019. if (! component_sent[ci])
  164020. ERREXIT(cinfo, JERR_MISSING_DATA);
  164021. }
  164022. }
  164023. }
  164024. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  164025. LOCAL(void)
  164026. select_scan_parameters (j_compress_ptr cinfo)
  164027. /* Set up the scan parameters for the current scan */
  164028. {
  164029. int ci;
  164030. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164031. if (cinfo->scan_info != NULL) {
  164032. /* Prepare for current scan --- the script is already validated */
  164033. my_master_ptr master = (my_master_ptr) cinfo->master;
  164034. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  164035. cinfo->comps_in_scan = scanptr->comps_in_scan;
  164036. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  164037. cinfo->cur_comp_info[ci] =
  164038. &cinfo->comp_info[scanptr->component_index[ci]];
  164039. }
  164040. cinfo->Ss = scanptr->Ss;
  164041. cinfo->Se = scanptr->Se;
  164042. cinfo->Ah = scanptr->Ah;
  164043. cinfo->Al = scanptr->Al;
  164044. }
  164045. else
  164046. #endif
  164047. {
  164048. /* Prepare for single sequential-JPEG scan containing all components */
  164049. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  164050. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164051. MAX_COMPS_IN_SCAN);
  164052. cinfo->comps_in_scan = cinfo->num_components;
  164053. for (ci = 0; ci < cinfo->num_components; ci++) {
  164054. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  164055. }
  164056. cinfo->Ss = 0;
  164057. cinfo->Se = DCTSIZE2-1;
  164058. cinfo->Ah = 0;
  164059. cinfo->Al = 0;
  164060. }
  164061. }
  164062. LOCAL(void)
  164063. per_scan_setup (j_compress_ptr cinfo)
  164064. /* Do computations that are needed before processing a JPEG scan */
  164065. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  164066. {
  164067. int ci, mcublks, tmp;
  164068. jpeg_component_info *compptr;
  164069. if (cinfo->comps_in_scan == 1) {
  164070. /* Noninterleaved (single-component) scan */
  164071. compptr = cinfo->cur_comp_info[0];
  164072. /* Overall image size in MCUs */
  164073. cinfo->MCUs_per_row = compptr->width_in_blocks;
  164074. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  164075. /* For noninterleaved scan, always one block per MCU */
  164076. compptr->MCU_width = 1;
  164077. compptr->MCU_height = 1;
  164078. compptr->MCU_blocks = 1;
  164079. compptr->MCU_sample_width = DCTSIZE;
  164080. compptr->last_col_width = 1;
  164081. /* For noninterleaved scans, it is convenient to define last_row_height
  164082. * as the number of block rows present in the last iMCU row.
  164083. */
  164084. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  164085. if (tmp == 0) tmp = compptr->v_samp_factor;
  164086. compptr->last_row_height = tmp;
  164087. /* Prepare array describing MCU composition */
  164088. cinfo->blocks_in_MCU = 1;
  164089. cinfo->MCU_membership[0] = 0;
  164090. } else {
  164091. /* Interleaved (multi-component) scan */
  164092. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  164093. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  164094. MAX_COMPS_IN_SCAN);
  164095. /* Overall image size in MCUs */
  164096. cinfo->MCUs_per_row = (JDIMENSION)
  164097. jdiv_round_up((long) cinfo->image_width,
  164098. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  164099. cinfo->MCU_rows_in_scan = (JDIMENSION)
  164100. jdiv_round_up((long) cinfo->image_height,
  164101. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164102. cinfo->blocks_in_MCU = 0;
  164103. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164104. compptr = cinfo->cur_comp_info[ci];
  164105. /* Sampling factors give # of blocks of component in each MCU */
  164106. compptr->MCU_width = compptr->h_samp_factor;
  164107. compptr->MCU_height = compptr->v_samp_factor;
  164108. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  164109. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  164110. /* Figure number of non-dummy blocks in last MCU column & row */
  164111. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  164112. if (tmp == 0) tmp = compptr->MCU_width;
  164113. compptr->last_col_width = tmp;
  164114. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  164115. if (tmp == 0) tmp = compptr->MCU_height;
  164116. compptr->last_row_height = tmp;
  164117. /* Prepare array describing MCU composition */
  164118. mcublks = compptr->MCU_blocks;
  164119. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  164120. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  164121. while (mcublks-- > 0) {
  164122. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  164123. }
  164124. }
  164125. }
  164126. /* Convert restart specified in rows to actual MCU count. */
  164127. /* Note that count must fit in 16 bits, so we provide limiting. */
  164128. if (cinfo->restart_in_rows > 0) {
  164129. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  164130. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  164131. }
  164132. }
  164133. /*
  164134. * Per-pass setup.
  164135. * This is called at the beginning of each pass. We determine which modules
  164136. * will be active during this pass and give them appropriate start_pass calls.
  164137. * We also set is_last_pass to indicate whether any more passes will be
  164138. * required.
  164139. */
  164140. METHODDEF(void)
  164141. prepare_for_pass (j_compress_ptr cinfo)
  164142. {
  164143. my_master_ptr master = (my_master_ptr) cinfo->master;
  164144. switch (master->pass_type) {
  164145. case main_pass:
  164146. /* Initial pass: will collect input data, and do either Huffman
  164147. * optimization or data output for the first scan.
  164148. */
  164149. select_scan_parameters(cinfo);
  164150. per_scan_setup(cinfo);
  164151. if (! cinfo->raw_data_in) {
  164152. (*cinfo->cconvert->start_pass) (cinfo);
  164153. (*cinfo->downsample->start_pass) (cinfo);
  164154. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  164155. }
  164156. (*cinfo->fdct->start_pass) (cinfo);
  164157. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  164158. (*cinfo->coef->start_pass) (cinfo,
  164159. (master->total_passes > 1 ?
  164160. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  164161. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  164162. if (cinfo->optimize_coding) {
  164163. /* No immediate data output; postpone writing frame/scan headers */
  164164. master->pub.call_pass_startup = FALSE;
  164165. } else {
  164166. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  164167. master->pub.call_pass_startup = TRUE;
  164168. }
  164169. break;
  164170. #ifdef ENTROPY_OPT_SUPPORTED
  164171. case huff_opt_pass:
  164172. /* Do Huffman optimization for a scan after the first one. */
  164173. select_scan_parameters(cinfo);
  164174. per_scan_setup(cinfo);
  164175. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  164176. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  164177. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  164178. master->pub.call_pass_startup = FALSE;
  164179. break;
  164180. }
  164181. /* Special case: Huffman DC refinement scans need no Huffman table
  164182. * and therefore we can skip the optimization pass for them.
  164183. */
  164184. master->pass_type = output_pass;
  164185. master->pass_number++;
  164186. /*FALLTHROUGH*/
  164187. #endif
  164188. case output_pass:
  164189. /* Do a data-output pass. */
  164190. /* We need not repeat per-scan setup if prior optimization pass did it. */
  164191. if (! cinfo->optimize_coding) {
  164192. select_scan_parameters(cinfo);
  164193. per_scan_setup(cinfo);
  164194. }
  164195. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  164196. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  164197. /* We emit frame/scan headers now */
  164198. if (master->scan_number == 0)
  164199. (*cinfo->marker->write_frame_header) (cinfo);
  164200. (*cinfo->marker->write_scan_header) (cinfo);
  164201. master->pub.call_pass_startup = FALSE;
  164202. break;
  164203. default:
  164204. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164205. }
  164206. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  164207. /* Set up progress monitor's pass info if present */
  164208. if (cinfo->progress != NULL) {
  164209. cinfo->progress->completed_passes = master->pass_number;
  164210. cinfo->progress->total_passes = master->total_passes;
  164211. }
  164212. }
  164213. /*
  164214. * Special start-of-pass hook.
  164215. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  164216. * In single-pass processing, we need this hook because we don't want to
  164217. * write frame/scan headers during jpeg_start_compress; we want to let the
  164218. * application write COM markers etc. between jpeg_start_compress and the
  164219. * jpeg_write_scanlines loop.
  164220. * In multi-pass processing, this routine is not used.
  164221. */
  164222. METHODDEF(void)
  164223. pass_startup (j_compress_ptr cinfo)
  164224. {
  164225. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  164226. (*cinfo->marker->write_frame_header) (cinfo);
  164227. (*cinfo->marker->write_scan_header) (cinfo);
  164228. }
  164229. /*
  164230. * Finish up at end of pass.
  164231. */
  164232. METHODDEF(void)
  164233. finish_pass_master (j_compress_ptr cinfo)
  164234. {
  164235. my_master_ptr master = (my_master_ptr) cinfo->master;
  164236. /* The entropy coder always needs an end-of-pass call,
  164237. * either to analyze statistics or to flush its output buffer.
  164238. */
  164239. (*cinfo->entropy->finish_pass) (cinfo);
  164240. /* Update state for next pass */
  164241. switch (master->pass_type) {
  164242. case main_pass:
  164243. /* next pass is either output of scan 0 (after optimization)
  164244. * or output of scan 1 (if no optimization).
  164245. */
  164246. master->pass_type = output_pass;
  164247. if (! cinfo->optimize_coding)
  164248. master->scan_number++;
  164249. break;
  164250. case huff_opt_pass:
  164251. /* next pass is always output of current scan */
  164252. master->pass_type = output_pass;
  164253. break;
  164254. case output_pass:
  164255. /* next pass is either optimization or output of next scan */
  164256. if (cinfo->optimize_coding)
  164257. master->pass_type = huff_opt_pass;
  164258. master->scan_number++;
  164259. break;
  164260. }
  164261. master->pass_number++;
  164262. }
  164263. /*
  164264. * Initialize master compression control.
  164265. */
  164266. GLOBAL(void)
  164267. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  164268. {
  164269. my_master_ptr master;
  164270. master = (my_master_ptr)
  164271. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164272. SIZEOF(my_comp_master));
  164273. cinfo->master = (struct jpeg_comp_master *) master;
  164274. master->pub.prepare_for_pass = prepare_for_pass;
  164275. master->pub.pass_startup = pass_startup;
  164276. master->pub.finish_pass = finish_pass_master;
  164277. master->pub.is_last_pass = FALSE;
  164278. /* Validate parameters, determine derived values */
  164279. initial_setup(cinfo);
  164280. if (cinfo->scan_info != NULL) {
  164281. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164282. validate_script(cinfo);
  164283. #else
  164284. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164285. #endif
  164286. } else {
  164287. cinfo->progressive_mode = FALSE;
  164288. cinfo->num_scans = 1;
  164289. }
  164290. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  164291. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  164292. /* Initialize my private state */
  164293. if (transcode_only) {
  164294. /* no main pass in transcoding */
  164295. if (cinfo->optimize_coding)
  164296. master->pass_type = huff_opt_pass;
  164297. else
  164298. master->pass_type = output_pass;
  164299. } else {
  164300. /* for normal compression, first pass is always this type: */
  164301. master->pass_type = main_pass;
  164302. }
  164303. master->scan_number = 0;
  164304. master->pass_number = 0;
  164305. if (cinfo->optimize_coding)
  164306. master->total_passes = cinfo->num_scans * 2;
  164307. else
  164308. master->total_passes = cinfo->num_scans;
  164309. }
  164310. /*** End of inlined file: jcmaster.c ***/
  164311. /*** Start of inlined file: jcomapi.c ***/
  164312. #define JPEG_INTERNALS
  164313. /*
  164314. * Abort processing of a JPEG compression or decompression operation,
  164315. * but don't destroy the object itself.
  164316. *
  164317. * For this, we merely clean up all the nonpermanent memory pools.
  164318. * Note that temp files (virtual arrays) are not allowed to belong to
  164319. * the permanent pool, so we will be able to close all temp files here.
  164320. * Closing a data source or destination, if necessary, is the application's
  164321. * responsibility.
  164322. */
  164323. GLOBAL(void)
  164324. jpeg_abort (j_common_ptr cinfo)
  164325. {
  164326. int pool;
  164327. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  164328. if (cinfo->mem == NULL)
  164329. return;
  164330. /* Releasing pools in reverse order might help avoid fragmentation
  164331. * with some (brain-damaged) malloc libraries.
  164332. */
  164333. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  164334. (*cinfo->mem->free_pool) (cinfo, pool);
  164335. }
  164336. /* Reset overall state for possible reuse of object */
  164337. if (cinfo->is_decompressor) {
  164338. cinfo->global_state = DSTATE_START;
  164339. /* Try to keep application from accessing now-deleted marker list.
  164340. * A bit kludgy to do it here, but this is the most central place.
  164341. */
  164342. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  164343. } else {
  164344. cinfo->global_state = CSTATE_START;
  164345. }
  164346. }
  164347. /*
  164348. * Destruction of a JPEG object.
  164349. *
  164350. * Everything gets deallocated except the master jpeg_compress_struct itself
  164351. * and the error manager struct. Both of these are supplied by the application
  164352. * and must be freed, if necessary, by the application. (Often they are on
  164353. * the stack and so don't need to be freed anyway.)
  164354. * Closing a data source or destination, if necessary, is the application's
  164355. * responsibility.
  164356. */
  164357. GLOBAL(void)
  164358. jpeg_destroy (j_common_ptr cinfo)
  164359. {
  164360. /* We need only tell the memory manager to release everything. */
  164361. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  164362. if (cinfo->mem != NULL)
  164363. (*cinfo->mem->self_destruct) (cinfo);
  164364. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  164365. cinfo->global_state = 0; /* mark it destroyed */
  164366. }
  164367. /*
  164368. * Convenience routines for allocating quantization and Huffman tables.
  164369. * (Would jutils.c be a more reasonable place to put these?)
  164370. */
  164371. GLOBAL(JQUANT_TBL *)
  164372. jpeg_alloc_quant_table (j_common_ptr cinfo)
  164373. {
  164374. JQUANT_TBL *tbl;
  164375. tbl = (JQUANT_TBL *)
  164376. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  164377. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  164378. return tbl;
  164379. }
  164380. GLOBAL(JHUFF_TBL *)
  164381. jpeg_alloc_huff_table (j_common_ptr cinfo)
  164382. {
  164383. JHUFF_TBL *tbl;
  164384. tbl = (JHUFF_TBL *)
  164385. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  164386. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  164387. return tbl;
  164388. }
  164389. /*** End of inlined file: jcomapi.c ***/
  164390. /*** Start of inlined file: jcparam.c ***/
  164391. #define JPEG_INTERNALS
  164392. /*
  164393. * Quantization table setup routines
  164394. */
  164395. GLOBAL(void)
  164396. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  164397. const unsigned int *basic_table,
  164398. int scale_factor, boolean force_baseline)
  164399. /* Define a quantization table equal to the basic_table times
  164400. * a scale factor (given as a percentage).
  164401. * If force_baseline is TRUE, the computed quantization table entries
  164402. * are limited to 1..255 for JPEG baseline compatibility.
  164403. */
  164404. {
  164405. JQUANT_TBL ** qtblptr;
  164406. int i;
  164407. long temp;
  164408. /* Safety check to ensure start_compress not called yet. */
  164409. if (cinfo->global_state != CSTATE_START)
  164410. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164411. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  164412. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  164413. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  164414. if (*qtblptr == NULL)
  164415. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  164416. for (i = 0; i < DCTSIZE2; i++) {
  164417. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  164418. /* limit the values to the valid range */
  164419. if (temp <= 0L) temp = 1L;
  164420. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  164421. if (force_baseline && temp > 255L)
  164422. temp = 255L; /* limit to baseline range if requested */
  164423. (*qtblptr)->quantval[i] = (UINT16) temp;
  164424. }
  164425. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  164426. (*qtblptr)->sent_table = FALSE;
  164427. }
  164428. GLOBAL(void)
  164429. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  164430. boolean force_baseline)
  164431. /* Set or change the 'quality' (quantization) setting, using default tables
  164432. * and a straight percentage-scaling quality scale. In most cases it's better
  164433. * to use jpeg_set_quality (below); this entry point is provided for
  164434. * applications that insist on a linear percentage scaling.
  164435. */
  164436. {
  164437. /* These are the sample quantization tables given in JPEG spec section K.1.
  164438. * The spec says that the values given produce "good" quality, and
  164439. * when divided by 2, "very good" quality.
  164440. */
  164441. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  164442. 16, 11, 10, 16, 24, 40, 51, 61,
  164443. 12, 12, 14, 19, 26, 58, 60, 55,
  164444. 14, 13, 16, 24, 40, 57, 69, 56,
  164445. 14, 17, 22, 29, 51, 87, 80, 62,
  164446. 18, 22, 37, 56, 68, 109, 103, 77,
  164447. 24, 35, 55, 64, 81, 104, 113, 92,
  164448. 49, 64, 78, 87, 103, 121, 120, 101,
  164449. 72, 92, 95, 98, 112, 100, 103, 99
  164450. };
  164451. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  164452. 17, 18, 24, 47, 99, 99, 99, 99,
  164453. 18, 21, 26, 66, 99, 99, 99, 99,
  164454. 24, 26, 56, 99, 99, 99, 99, 99,
  164455. 47, 66, 99, 99, 99, 99, 99, 99,
  164456. 99, 99, 99, 99, 99, 99, 99, 99,
  164457. 99, 99, 99, 99, 99, 99, 99, 99,
  164458. 99, 99, 99, 99, 99, 99, 99, 99,
  164459. 99, 99, 99, 99, 99, 99, 99, 99
  164460. };
  164461. /* Set up two quantization tables using the specified scaling */
  164462. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  164463. scale_factor, force_baseline);
  164464. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  164465. scale_factor, force_baseline);
  164466. }
  164467. GLOBAL(int)
  164468. jpeg_quality_scaling (int quality)
  164469. /* Convert a user-specified quality rating to a percentage scaling factor
  164470. * for an underlying quantization table, using our recommended scaling curve.
  164471. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  164472. */
  164473. {
  164474. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  164475. if (quality <= 0) quality = 1;
  164476. if (quality > 100) quality = 100;
  164477. /* The basic table is used as-is (scaling 100) for a quality of 50.
  164478. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  164479. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  164480. * to make all the table entries 1 (hence, minimum quantization loss).
  164481. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  164482. */
  164483. if (quality < 50)
  164484. quality = 5000 / quality;
  164485. else
  164486. quality = 200 - quality*2;
  164487. return quality;
  164488. }
  164489. GLOBAL(void)
  164490. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  164491. /* Set or change the 'quality' (quantization) setting, using default tables.
  164492. * This is the standard quality-adjusting entry point for typical user
  164493. * interfaces; only those who want detailed control over quantization tables
  164494. * would use the preceding three routines directly.
  164495. */
  164496. {
  164497. /* Convert user 0-100 rating to percentage scaling */
  164498. quality = jpeg_quality_scaling(quality);
  164499. /* Set up standard quality tables */
  164500. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  164501. }
  164502. /*
  164503. * Huffman table setup routines
  164504. */
  164505. LOCAL(void)
  164506. add_huff_table (j_compress_ptr cinfo,
  164507. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  164508. /* Define a Huffman table */
  164509. {
  164510. int nsymbols, len;
  164511. if (*htblptr == NULL)
  164512. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  164513. /* Copy the number-of-symbols-of-each-code-length counts */
  164514. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  164515. /* Validate the counts. We do this here mainly so we can copy the right
  164516. * number of symbols from the val[] array, without risking marching off
  164517. * the end of memory. jchuff.c will do a more thorough test later.
  164518. */
  164519. nsymbols = 0;
  164520. for (len = 1; len <= 16; len++)
  164521. nsymbols += bits[len];
  164522. if (nsymbols < 1 || nsymbols > 256)
  164523. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  164524. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  164525. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  164526. (*htblptr)->sent_table = FALSE;
  164527. }
  164528. LOCAL(void)
  164529. std_huff_tables (j_compress_ptr cinfo)
  164530. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  164531. /* IMPORTANT: these are only valid for 8-bit data precision! */
  164532. {
  164533. static const UINT8 bits_dc_luminance[17] =
  164534. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  164535. static const UINT8 val_dc_luminance[] =
  164536. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  164537. static const UINT8 bits_dc_chrominance[17] =
  164538. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  164539. static const UINT8 val_dc_chrominance[] =
  164540. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  164541. static const UINT8 bits_ac_luminance[17] =
  164542. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  164543. static const UINT8 val_ac_luminance[] =
  164544. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  164545. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  164546. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  164547. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  164548. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  164549. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  164550. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  164551. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  164552. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  164553. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  164554. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  164555. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  164556. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  164557. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  164558. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  164559. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  164560. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  164561. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  164562. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  164563. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  164564. 0xf9, 0xfa };
  164565. static const UINT8 bits_ac_chrominance[17] =
  164566. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  164567. static const UINT8 val_ac_chrominance[] =
  164568. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  164569. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  164570. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  164571. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  164572. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  164573. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  164574. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  164575. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  164576. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  164577. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  164578. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  164579. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  164580. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  164581. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  164582. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  164583. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  164584. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  164585. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  164586. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  164587. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  164588. 0xf9, 0xfa };
  164589. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  164590. bits_dc_luminance, val_dc_luminance);
  164591. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  164592. bits_ac_luminance, val_ac_luminance);
  164593. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  164594. bits_dc_chrominance, val_dc_chrominance);
  164595. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  164596. bits_ac_chrominance, val_ac_chrominance);
  164597. }
  164598. /*
  164599. * Default parameter setup for compression.
  164600. *
  164601. * Applications that don't choose to use this routine must do their
  164602. * own setup of all these parameters. Alternately, you can call this
  164603. * to establish defaults and then alter parameters selectively. This
  164604. * is the recommended approach since, if we add any new parameters,
  164605. * your code will still work (they'll be set to reasonable defaults).
  164606. */
  164607. GLOBAL(void)
  164608. jpeg_set_defaults (j_compress_ptr cinfo)
  164609. {
  164610. int i;
  164611. /* Safety check to ensure start_compress not called yet. */
  164612. if (cinfo->global_state != CSTATE_START)
  164613. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164614. /* Allocate comp_info array large enough for maximum component count.
  164615. * Array is made permanent in case application wants to compress
  164616. * multiple images at same param settings.
  164617. */
  164618. if (cinfo->comp_info == NULL)
  164619. cinfo->comp_info = (jpeg_component_info *)
  164620. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  164621. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  164622. /* Initialize everything not dependent on the color space */
  164623. cinfo->data_precision = BITS_IN_JSAMPLE;
  164624. /* Set up two quantization tables using default quality of 75 */
  164625. jpeg_set_quality(cinfo, 75, TRUE);
  164626. /* Set up two Huffman tables */
  164627. std_huff_tables(cinfo);
  164628. /* Initialize default arithmetic coding conditioning */
  164629. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  164630. cinfo->arith_dc_L[i] = 0;
  164631. cinfo->arith_dc_U[i] = 1;
  164632. cinfo->arith_ac_K[i] = 5;
  164633. }
  164634. /* Default is no multiple-scan output */
  164635. cinfo->scan_info = NULL;
  164636. cinfo->num_scans = 0;
  164637. /* Expect normal source image, not raw downsampled data */
  164638. cinfo->raw_data_in = FALSE;
  164639. /* Use Huffman coding, not arithmetic coding, by default */
  164640. cinfo->arith_code = FALSE;
  164641. /* By default, don't do extra passes to optimize entropy coding */
  164642. cinfo->optimize_coding = FALSE;
  164643. /* The standard Huffman tables are only valid for 8-bit data precision.
  164644. * If the precision is higher, force optimization on so that usable
  164645. * tables will be computed. This test can be removed if default tables
  164646. * are supplied that are valid for the desired precision.
  164647. */
  164648. if (cinfo->data_precision > 8)
  164649. cinfo->optimize_coding = TRUE;
  164650. /* By default, use the simpler non-cosited sampling alignment */
  164651. cinfo->CCIR601_sampling = FALSE;
  164652. /* No input smoothing */
  164653. cinfo->smoothing_factor = 0;
  164654. /* DCT algorithm preference */
  164655. cinfo->dct_method = JDCT_DEFAULT;
  164656. /* No restart markers */
  164657. cinfo->restart_interval = 0;
  164658. cinfo->restart_in_rows = 0;
  164659. /* Fill in default JFIF marker parameters. Note that whether the marker
  164660. * will actually be written is determined by jpeg_set_colorspace.
  164661. *
  164662. * By default, the library emits JFIF version code 1.01.
  164663. * An application that wants to emit JFIF 1.02 extension markers should set
  164664. * JFIF_minor_version to 2. We could probably get away with just defaulting
  164665. * to 1.02, but there may still be some decoders in use that will complain
  164666. * about that; saying 1.01 should minimize compatibility problems.
  164667. */
  164668. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  164669. cinfo->JFIF_minor_version = 1;
  164670. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  164671. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  164672. cinfo->Y_density = 1;
  164673. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  164674. jpeg_default_colorspace(cinfo);
  164675. }
  164676. /*
  164677. * Select an appropriate JPEG colorspace for in_color_space.
  164678. */
  164679. GLOBAL(void)
  164680. jpeg_default_colorspace (j_compress_ptr cinfo)
  164681. {
  164682. switch (cinfo->in_color_space) {
  164683. case JCS_GRAYSCALE:
  164684. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  164685. break;
  164686. case JCS_RGB:
  164687. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  164688. break;
  164689. case JCS_YCbCr:
  164690. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  164691. break;
  164692. case JCS_CMYK:
  164693. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  164694. break;
  164695. case JCS_YCCK:
  164696. jpeg_set_colorspace(cinfo, JCS_YCCK);
  164697. break;
  164698. case JCS_UNKNOWN:
  164699. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  164700. break;
  164701. default:
  164702. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  164703. }
  164704. }
  164705. /*
  164706. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  164707. */
  164708. GLOBAL(void)
  164709. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  164710. {
  164711. jpeg_component_info * compptr;
  164712. int ci;
  164713. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  164714. (compptr = &cinfo->comp_info[index], \
  164715. compptr->component_id = (id), \
  164716. compptr->h_samp_factor = (hsamp), \
  164717. compptr->v_samp_factor = (vsamp), \
  164718. compptr->quant_tbl_no = (quant), \
  164719. compptr->dc_tbl_no = (dctbl), \
  164720. compptr->ac_tbl_no = (actbl) )
  164721. /* Safety check to ensure start_compress not called yet. */
  164722. if (cinfo->global_state != CSTATE_START)
  164723. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164724. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  164725. * tables 1 for chrominance components.
  164726. */
  164727. cinfo->jpeg_color_space = colorspace;
  164728. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  164729. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  164730. switch (colorspace) {
  164731. case JCS_GRAYSCALE:
  164732. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  164733. cinfo->num_components = 1;
  164734. /* JFIF specifies component ID 1 */
  164735. SET_COMP(0, 1, 1,1, 0, 0,0);
  164736. break;
  164737. case JCS_RGB:
  164738. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  164739. cinfo->num_components = 3;
  164740. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  164741. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  164742. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  164743. break;
  164744. case JCS_YCbCr:
  164745. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  164746. cinfo->num_components = 3;
  164747. /* JFIF specifies component IDs 1,2,3 */
  164748. /* We default to 2x2 subsamples of chrominance */
  164749. SET_COMP(0, 1, 2,2, 0, 0,0);
  164750. SET_COMP(1, 2, 1,1, 1, 1,1);
  164751. SET_COMP(2, 3, 1,1, 1, 1,1);
  164752. break;
  164753. case JCS_CMYK:
  164754. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  164755. cinfo->num_components = 4;
  164756. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  164757. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  164758. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  164759. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  164760. break;
  164761. case JCS_YCCK:
  164762. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  164763. cinfo->num_components = 4;
  164764. SET_COMP(0, 1, 2,2, 0, 0,0);
  164765. SET_COMP(1, 2, 1,1, 1, 1,1);
  164766. SET_COMP(2, 3, 1,1, 1, 1,1);
  164767. SET_COMP(3, 4, 2,2, 0, 0,0);
  164768. break;
  164769. case JCS_UNKNOWN:
  164770. cinfo->num_components = cinfo->input_components;
  164771. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  164772. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164773. MAX_COMPONENTS);
  164774. for (ci = 0; ci < cinfo->num_components; ci++) {
  164775. SET_COMP(ci, ci, 1,1, 0, 0,0);
  164776. }
  164777. break;
  164778. default:
  164779. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  164780. }
  164781. }
  164782. #ifdef C_PROGRESSIVE_SUPPORTED
  164783. LOCAL(jpeg_scan_info *)
  164784. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  164785. int Ss, int Se, int Ah, int Al)
  164786. /* Support routine: generate one scan for specified component */
  164787. {
  164788. scanptr->comps_in_scan = 1;
  164789. scanptr->component_index[0] = ci;
  164790. scanptr->Ss = Ss;
  164791. scanptr->Se = Se;
  164792. scanptr->Ah = Ah;
  164793. scanptr->Al = Al;
  164794. scanptr++;
  164795. return scanptr;
  164796. }
  164797. LOCAL(jpeg_scan_info *)
  164798. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  164799. int Ss, int Se, int Ah, int Al)
  164800. /* Support routine: generate one scan for each component */
  164801. {
  164802. int ci;
  164803. for (ci = 0; ci < ncomps; ci++) {
  164804. scanptr->comps_in_scan = 1;
  164805. scanptr->component_index[0] = ci;
  164806. scanptr->Ss = Ss;
  164807. scanptr->Se = Se;
  164808. scanptr->Ah = Ah;
  164809. scanptr->Al = Al;
  164810. scanptr++;
  164811. }
  164812. return scanptr;
  164813. }
  164814. LOCAL(jpeg_scan_info *)
  164815. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  164816. /* Support routine: generate interleaved DC scan if possible, else N scans */
  164817. {
  164818. int ci;
  164819. if (ncomps <= MAX_COMPS_IN_SCAN) {
  164820. /* Single interleaved DC scan */
  164821. scanptr->comps_in_scan = ncomps;
  164822. for (ci = 0; ci < ncomps; ci++)
  164823. scanptr->component_index[ci] = ci;
  164824. scanptr->Ss = scanptr->Se = 0;
  164825. scanptr->Ah = Ah;
  164826. scanptr->Al = Al;
  164827. scanptr++;
  164828. } else {
  164829. /* Noninterleaved DC scan for each component */
  164830. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  164831. }
  164832. return scanptr;
  164833. }
  164834. /*
  164835. * Create a recommended progressive-JPEG script.
  164836. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  164837. */
  164838. GLOBAL(void)
  164839. jpeg_simple_progression (j_compress_ptr cinfo)
  164840. {
  164841. int ncomps = cinfo->num_components;
  164842. int nscans;
  164843. jpeg_scan_info * scanptr;
  164844. /* Safety check to ensure start_compress not called yet. */
  164845. if (cinfo->global_state != CSTATE_START)
  164846. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164847. /* Figure space needed for script. Calculation must match code below! */
  164848. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  164849. /* Custom script for YCbCr color images. */
  164850. nscans = 10;
  164851. } else {
  164852. /* All-purpose script for other color spaces. */
  164853. if (ncomps > MAX_COMPS_IN_SCAN)
  164854. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  164855. else
  164856. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  164857. }
  164858. /* Allocate space for script.
  164859. * We need to put it in the permanent pool in case the application performs
  164860. * multiple compressions without changing the settings. To avoid a memory
  164861. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  164862. * object, we try to re-use previously allocated space, and we allocate
  164863. * enough space to handle YCbCr even if initially asked for grayscale.
  164864. */
  164865. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  164866. cinfo->script_space_size = MAX(nscans, 10);
  164867. cinfo->script_space = (jpeg_scan_info *)
  164868. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  164869. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  164870. }
  164871. scanptr = cinfo->script_space;
  164872. cinfo->scan_info = scanptr;
  164873. cinfo->num_scans = nscans;
  164874. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  164875. /* Custom script for YCbCr color images. */
  164876. /* Initial DC scan */
  164877. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  164878. /* Initial AC scan: get some luma data out in a hurry */
  164879. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  164880. /* Chroma data is too small to be worth expending many scans on */
  164881. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  164882. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  164883. /* Complete spectral selection for luma AC */
  164884. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  164885. /* Refine next bit of luma AC */
  164886. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  164887. /* Finish DC successive approximation */
  164888. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  164889. /* Finish AC successive approximation */
  164890. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  164891. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  164892. /* Luma bottom bit comes last since it's usually largest scan */
  164893. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  164894. } else {
  164895. /* All-purpose script for other color spaces. */
  164896. /* Successive approximation first pass */
  164897. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  164898. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  164899. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  164900. /* Successive approximation second pass */
  164901. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  164902. /* Successive approximation final pass */
  164903. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  164904. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  164905. }
  164906. }
  164907. #endif /* C_PROGRESSIVE_SUPPORTED */
  164908. /*** End of inlined file: jcparam.c ***/
  164909. /*** Start of inlined file: jcphuff.c ***/
  164910. #define JPEG_INTERNALS
  164911. #ifdef C_PROGRESSIVE_SUPPORTED
  164912. /* Expanded entropy encoder object for progressive Huffman encoding. */
  164913. typedef struct {
  164914. struct jpeg_entropy_encoder pub; /* public fields */
  164915. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  164916. boolean gather_statistics;
  164917. /* Bit-level coding status.
  164918. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  164919. */
  164920. JOCTET * next_output_byte; /* => next byte to write in buffer */
  164921. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  164922. INT32 put_buffer; /* current bit-accumulation buffer */
  164923. int put_bits; /* # of bits now in it */
  164924. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  164925. /* Coding status for DC components */
  164926. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  164927. /* Coding status for AC components */
  164928. int ac_tbl_no; /* the table number of the single component */
  164929. unsigned int EOBRUN; /* run length of EOBs */
  164930. unsigned int BE; /* # of buffered correction bits before MCU */
  164931. char * bit_buffer; /* buffer for correction bits (1 per char) */
  164932. /* packing correction bits tightly would save some space but cost time... */
  164933. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  164934. int next_restart_num; /* next restart number to write (0-7) */
  164935. /* Pointers to derived tables (these workspaces have image lifespan).
  164936. * Since any one scan codes only DC or only AC, we only need one set
  164937. * of tables, not one for DC and one for AC.
  164938. */
  164939. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  164940. /* Statistics tables for optimization; again, one set is enough */
  164941. long * count_ptrs[NUM_HUFF_TBLS];
  164942. } phuff_entropy_encoder;
  164943. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  164944. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  164945. * buffer can hold. Larger sizes may slightly improve compression, but
  164946. * 1000 is already well into the realm of overkill.
  164947. * The minimum safe size is 64 bits.
  164948. */
  164949. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  164950. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  164951. * We assume that int right shift is unsigned if INT32 right shift is,
  164952. * which should be safe.
  164953. */
  164954. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  164955. #define ISHIFT_TEMPS int ishift_temp;
  164956. #define IRIGHT_SHIFT(x,shft) \
  164957. ((ishift_temp = (x)) < 0 ? \
  164958. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  164959. (ishift_temp >> (shft)))
  164960. #else
  164961. #define ISHIFT_TEMPS
  164962. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  164963. #endif
  164964. /* Forward declarations */
  164965. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  164966. JBLOCKROW *MCU_data));
  164967. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  164968. JBLOCKROW *MCU_data));
  164969. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  164970. JBLOCKROW *MCU_data));
  164971. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  164972. JBLOCKROW *MCU_data));
  164973. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  164974. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  164975. /*
  164976. * Initialize for a Huffman-compressed scan using progressive JPEG.
  164977. */
  164978. METHODDEF(void)
  164979. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  164980. {
  164981. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  164982. boolean is_DC_band;
  164983. int ci, tbl;
  164984. jpeg_component_info * compptr;
  164985. entropy->cinfo = cinfo;
  164986. entropy->gather_statistics = gather_statistics;
  164987. is_DC_band = (cinfo->Ss == 0);
  164988. /* We assume jcmaster.c already validated the scan parameters. */
  164989. /* Select execution routines */
  164990. if (cinfo->Ah == 0) {
  164991. if (is_DC_band)
  164992. entropy->pub.encode_mcu = encode_mcu_DC_first;
  164993. else
  164994. entropy->pub.encode_mcu = encode_mcu_AC_first;
  164995. } else {
  164996. if (is_DC_band)
  164997. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  164998. else {
  164999. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  165000. /* AC refinement needs a correction bit buffer */
  165001. if (entropy->bit_buffer == NULL)
  165002. entropy->bit_buffer = (char *)
  165003. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165004. MAX_CORR_BITS * SIZEOF(char));
  165005. }
  165006. }
  165007. if (gather_statistics)
  165008. entropy->pub.finish_pass = finish_pass_gather_phuff;
  165009. else
  165010. entropy->pub.finish_pass = finish_pass_phuff;
  165011. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  165012. * for AC coefficients.
  165013. */
  165014. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165015. compptr = cinfo->cur_comp_info[ci];
  165016. /* Initialize DC predictions to 0 */
  165017. entropy->last_dc_val[ci] = 0;
  165018. /* Get table index */
  165019. if (is_DC_band) {
  165020. if (cinfo->Ah != 0) /* DC refinement needs no table */
  165021. continue;
  165022. tbl = compptr->dc_tbl_no;
  165023. } else {
  165024. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  165025. }
  165026. if (gather_statistics) {
  165027. /* Check for invalid table index */
  165028. /* (make_c_derived_tbl does this in the other path) */
  165029. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  165030. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  165031. /* Allocate and zero the statistics tables */
  165032. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  165033. if (entropy->count_ptrs[tbl] == NULL)
  165034. entropy->count_ptrs[tbl] = (long *)
  165035. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165036. 257 * SIZEOF(long));
  165037. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  165038. } else {
  165039. /* Compute derived values for Huffman table */
  165040. /* We may do this more than once for a table, but it's not expensive */
  165041. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  165042. & entropy->derived_tbls[tbl]);
  165043. }
  165044. }
  165045. /* Initialize AC stuff */
  165046. entropy->EOBRUN = 0;
  165047. entropy->BE = 0;
  165048. /* Initialize bit buffer to empty */
  165049. entropy->put_buffer = 0;
  165050. entropy->put_bits = 0;
  165051. /* Initialize restart stuff */
  165052. entropy->restarts_to_go = cinfo->restart_interval;
  165053. entropy->next_restart_num = 0;
  165054. }
  165055. /* Outputting bytes to the file.
  165056. * NB: these must be called only when actually outputting,
  165057. * that is, entropy->gather_statistics == FALSE.
  165058. */
  165059. /* Emit a byte */
  165060. #define emit_byte(entropy,val) \
  165061. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  165062. if (--(entropy)->free_in_buffer == 0) \
  165063. dump_buffer_p(entropy); }
  165064. LOCAL(void)
  165065. dump_buffer_p (phuff_entropy_ptr entropy)
  165066. /* Empty the output buffer; we do not support suspension in this module. */
  165067. {
  165068. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  165069. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  165070. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  165071. /* After a successful buffer dump, must reset buffer pointers */
  165072. entropy->next_output_byte = dest->next_output_byte;
  165073. entropy->free_in_buffer = dest->free_in_buffer;
  165074. }
  165075. /* Outputting bits to the file */
  165076. /* Only the right 24 bits of put_buffer are used; the valid bits are
  165077. * left-justified in this part. At most 16 bits can be passed to emit_bits
  165078. * in one call, and we never retain more than 7 bits in put_buffer
  165079. * between calls, so 24 bits are sufficient.
  165080. */
  165081. INLINE
  165082. LOCAL(void)
  165083. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  165084. /* Emit some bits, unless we are in gather mode */
  165085. {
  165086. /* This routine is heavily used, so it's worth coding tightly. */
  165087. register INT32 put_buffer = (INT32) code;
  165088. register int put_bits = entropy->put_bits;
  165089. /* if size is 0, caller used an invalid Huffman table entry */
  165090. if (size == 0)
  165091. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  165092. if (entropy->gather_statistics)
  165093. return; /* do nothing if we're only getting stats */
  165094. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  165095. put_bits += size; /* new number of bits in buffer */
  165096. put_buffer <<= 24 - put_bits; /* align incoming bits */
  165097. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  165098. while (put_bits >= 8) {
  165099. int c = (int) ((put_buffer >> 16) & 0xFF);
  165100. emit_byte(entropy, c);
  165101. if (c == 0xFF) { /* need to stuff a zero byte? */
  165102. emit_byte(entropy, 0);
  165103. }
  165104. put_buffer <<= 8;
  165105. put_bits -= 8;
  165106. }
  165107. entropy->put_buffer = put_buffer; /* update variables */
  165108. entropy->put_bits = put_bits;
  165109. }
  165110. LOCAL(void)
  165111. flush_bits_p (phuff_entropy_ptr entropy)
  165112. {
  165113. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  165114. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  165115. entropy->put_bits = 0;
  165116. }
  165117. /*
  165118. * Emit (or just count) a Huffman symbol.
  165119. */
  165120. INLINE
  165121. LOCAL(void)
  165122. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  165123. {
  165124. if (entropy->gather_statistics)
  165125. entropy->count_ptrs[tbl_no][symbol]++;
  165126. else {
  165127. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  165128. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  165129. }
  165130. }
  165131. /*
  165132. * Emit bits from a correction bit buffer.
  165133. */
  165134. LOCAL(void)
  165135. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  165136. unsigned int nbits)
  165137. {
  165138. if (entropy->gather_statistics)
  165139. return; /* no real work */
  165140. while (nbits > 0) {
  165141. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  165142. bufstart++;
  165143. nbits--;
  165144. }
  165145. }
  165146. /*
  165147. * Emit any pending EOBRUN symbol.
  165148. */
  165149. LOCAL(void)
  165150. emit_eobrun (phuff_entropy_ptr entropy)
  165151. {
  165152. register int temp, nbits;
  165153. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  165154. temp = entropy->EOBRUN;
  165155. nbits = 0;
  165156. while ((temp >>= 1))
  165157. nbits++;
  165158. /* safety check: shouldn't happen given limited correction-bit buffer */
  165159. if (nbits > 14)
  165160. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  165161. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  165162. if (nbits)
  165163. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  165164. entropy->EOBRUN = 0;
  165165. /* Emit any buffered correction bits */
  165166. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  165167. entropy->BE = 0;
  165168. }
  165169. }
  165170. /*
  165171. * Emit a restart marker & resynchronize predictions.
  165172. */
  165173. LOCAL(void)
  165174. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  165175. {
  165176. int ci;
  165177. emit_eobrun(entropy);
  165178. if (! entropy->gather_statistics) {
  165179. flush_bits_p(entropy);
  165180. emit_byte(entropy, 0xFF);
  165181. emit_byte(entropy, JPEG_RST0 + restart_num);
  165182. }
  165183. if (entropy->cinfo->Ss == 0) {
  165184. /* Re-initialize DC predictions to 0 */
  165185. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  165186. entropy->last_dc_val[ci] = 0;
  165187. } else {
  165188. /* Re-initialize all AC-related fields to 0 */
  165189. entropy->EOBRUN = 0;
  165190. entropy->BE = 0;
  165191. }
  165192. }
  165193. /*
  165194. * MCU encoding for DC initial scan (either spectral selection,
  165195. * or first pass of successive approximation).
  165196. */
  165197. METHODDEF(boolean)
  165198. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165199. {
  165200. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165201. register int temp, temp2;
  165202. register int nbits;
  165203. int blkn, ci;
  165204. int Al = cinfo->Al;
  165205. JBLOCKROW block;
  165206. jpeg_component_info * compptr;
  165207. ISHIFT_TEMPS
  165208. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165209. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165210. /* Emit restart marker if needed */
  165211. if (cinfo->restart_interval)
  165212. if (entropy->restarts_to_go == 0)
  165213. emit_restart_p(entropy, entropy->next_restart_num);
  165214. /* Encode the MCU data blocks */
  165215. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  165216. block = MCU_data[blkn];
  165217. ci = cinfo->MCU_membership[blkn];
  165218. compptr = cinfo->cur_comp_info[ci];
  165219. /* Compute the DC value after the required point transform by Al.
  165220. * This is simply an arithmetic right shift.
  165221. */
  165222. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  165223. /* DC differences are figured on the point-transformed values. */
  165224. temp = temp2 - entropy->last_dc_val[ci];
  165225. entropy->last_dc_val[ci] = temp2;
  165226. /* Encode the DC coefficient difference per section G.1.2.1 */
  165227. temp2 = temp;
  165228. if (temp < 0) {
  165229. temp = -temp; /* temp is abs value of input */
  165230. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  165231. /* This code assumes we are on a two's complement machine */
  165232. temp2--;
  165233. }
  165234. /* Find the number of bits needed for the magnitude of the coefficient */
  165235. nbits = 0;
  165236. while (temp) {
  165237. nbits++;
  165238. temp >>= 1;
  165239. }
  165240. /* Check for out-of-range coefficient values.
  165241. * Since we're encoding a difference, the range limit is twice as much.
  165242. */
  165243. if (nbits > MAX_COEF_BITS+1)
  165244. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  165245. /* Count/emit the Huffman-coded symbol for the number of bits */
  165246. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  165247. /* Emit that number of bits of the value, if positive, */
  165248. /* or the complement of its magnitude, if negative. */
  165249. if (nbits) /* emit_bits rejects calls with size 0 */
  165250. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  165251. }
  165252. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165253. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165254. /* Update restart-interval state too */
  165255. if (cinfo->restart_interval) {
  165256. if (entropy->restarts_to_go == 0) {
  165257. entropy->restarts_to_go = cinfo->restart_interval;
  165258. entropy->next_restart_num++;
  165259. entropy->next_restart_num &= 7;
  165260. }
  165261. entropy->restarts_to_go--;
  165262. }
  165263. return TRUE;
  165264. }
  165265. /*
  165266. * MCU encoding for AC initial scan (either spectral selection,
  165267. * or first pass of successive approximation).
  165268. */
  165269. METHODDEF(boolean)
  165270. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165271. {
  165272. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165273. register int temp, temp2;
  165274. register int nbits;
  165275. register int r, k;
  165276. int Se = cinfo->Se;
  165277. int Al = cinfo->Al;
  165278. JBLOCKROW block;
  165279. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165280. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165281. /* Emit restart marker if needed */
  165282. if (cinfo->restart_interval)
  165283. if (entropy->restarts_to_go == 0)
  165284. emit_restart_p(entropy, entropy->next_restart_num);
  165285. /* Encode the MCU data block */
  165286. block = MCU_data[0];
  165287. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  165288. r = 0; /* r = run length of zeros */
  165289. for (k = cinfo->Ss; k <= Se; k++) {
  165290. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  165291. r++;
  165292. continue;
  165293. }
  165294. /* We must apply the point transform by Al. For AC coefficients this
  165295. * is an integer division with rounding towards 0. To do this portably
  165296. * in C, we shift after obtaining the absolute value; so the code is
  165297. * interwoven with finding the abs value (temp) and output bits (temp2).
  165298. */
  165299. if (temp < 0) {
  165300. temp = -temp; /* temp is abs value of input */
  165301. temp >>= Al; /* apply the point transform */
  165302. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  165303. temp2 = ~temp;
  165304. } else {
  165305. temp >>= Al; /* apply the point transform */
  165306. temp2 = temp;
  165307. }
  165308. /* Watch out for case that nonzero coef is zero after point transform */
  165309. if (temp == 0) {
  165310. r++;
  165311. continue;
  165312. }
  165313. /* Emit any pending EOBRUN */
  165314. if (entropy->EOBRUN > 0)
  165315. emit_eobrun(entropy);
  165316. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  165317. while (r > 15) {
  165318. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  165319. r -= 16;
  165320. }
  165321. /* Find the number of bits needed for the magnitude of the coefficient */
  165322. nbits = 1; /* there must be at least one 1 bit */
  165323. while ((temp >>= 1))
  165324. nbits++;
  165325. /* Check for out-of-range coefficient values */
  165326. if (nbits > MAX_COEF_BITS)
  165327. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  165328. /* Count/emit Huffman symbol for run length / number of bits */
  165329. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  165330. /* Emit that number of bits of the value, if positive, */
  165331. /* or the complement of its magnitude, if negative. */
  165332. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  165333. r = 0; /* reset zero run length */
  165334. }
  165335. if (r > 0) { /* If there are trailing zeroes, */
  165336. entropy->EOBRUN++; /* count an EOB */
  165337. if (entropy->EOBRUN == 0x7FFF)
  165338. emit_eobrun(entropy); /* force it out to avoid overflow */
  165339. }
  165340. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165341. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165342. /* Update restart-interval state too */
  165343. if (cinfo->restart_interval) {
  165344. if (entropy->restarts_to_go == 0) {
  165345. entropy->restarts_to_go = cinfo->restart_interval;
  165346. entropy->next_restart_num++;
  165347. entropy->next_restart_num &= 7;
  165348. }
  165349. entropy->restarts_to_go--;
  165350. }
  165351. return TRUE;
  165352. }
  165353. /*
  165354. * MCU encoding for DC successive approximation refinement scan.
  165355. * Note: we assume such scans can be multi-component, although the spec
  165356. * is not very clear on the point.
  165357. */
  165358. METHODDEF(boolean)
  165359. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165360. {
  165361. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165362. register int temp;
  165363. int blkn;
  165364. int Al = cinfo->Al;
  165365. JBLOCKROW block;
  165366. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165367. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165368. /* Emit restart marker if needed */
  165369. if (cinfo->restart_interval)
  165370. if (entropy->restarts_to_go == 0)
  165371. emit_restart_p(entropy, entropy->next_restart_num);
  165372. /* Encode the MCU data blocks */
  165373. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  165374. block = MCU_data[blkn];
  165375. /* We simply emit the Al'th bit of the DC coefficient value. */
  165376. temp = (*block)[0];
  165377. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  165378. }
  165379. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165380. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165381. /* Update restart-interval state too */
  165382. if (cinfo->restart_interval) {
  165383. if (entropy->restarts_to_go == 0) {
  165384. entropy->restarts_to_go = cinfo->restart_interval;
  165385. entropy->next_restart_num++;
  165386. entropy->next_restart_num &= 7;
  165387. }
  165388. entropy->restarts_to_go--;
  165389. }
  165390. return TRUE;
  165391. }
  165392. /*
  165393. * MCU encoding for AC successive approximation refinement scan.
  165394. */
  165395. METHODDEF(boolean)
  165396. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165397. {
  165398. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165399. register int temp;
  165400. register int r, k;
  165401. int EOB;
  165402. char *BR_buffer;
  165403. unsigned int BR;
  165404. int Se = cinfo->Se;
  165405. int Al = cinfo->Al;
  165406. JBLOCKROW block;
  165407. int absvalues[DCTSIZE2];
  165408. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165409. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165410. /* Emit restart marker if needed */
  165411. if (cinfo->restart_interval)
  165412. if (entropy->restarts_to_go == 0)
  165413. emit_restart_p(entropy, entropy->next_restart_num);
  165414. /* Encode the MCU data block */
  165415. block = MCU_data[0];
  165416. /* It is convenient to make a pre-pass to determine the transformed
  165417. * coefficients' absolute values and the EOB position.
  165418. */
  165419. EOB = 0;
  165420. for (k = cinfo->Ss; k <= Se; k++) {
  165421. temp = (*block)[jpeg_natural_order[k]];
  165422. /* We must apply the point transform by Al. For AC coefficients this
  165423. * is an integer division with rounding towards 0. To do this portably
  165424. * in C, we shift after obtaining the absolute value.
  165425. */
  165426. if (temp < 0)
  165427. temp = -temp; /* temp is abs value of input */
  165428. temp >>= Al; /* apply the point transform */
  165429. absvalues[k] = temp; /* save abs value for main pass */
  165430. if (temp == 1)
  165431. EOB = k; /* EOB = index of last newly-nonzero coef */
  165432. }
  165433. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  165434. r = 0; /* r = run length of zeros */
  165435. BR = 0; /* BR = count of buffered bits added now */
  165436. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  165437. for (k = cinfo->Ss; k <= Se; k++) {
  165438. if ((temp = absvalues[k]) == 0) {
  165439. r++;
  165440. continue;
  165441. }
  165442. /* Emit any required ZRLs, but not if they can be folded into EOB */
  165443. while (r > 15 && k <= EOB) {
  165444. /* emit any pending EOBRUN and the BE correction bits */
  165445. emit_eobrun(entropy);
  165446. /* Emit ZRL */
  165447. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  165448. r -= 16;
  165449. /* Emit buffered correction bits that must be associated with ZRL */
  165450. emit_buffered_bits(entropy, BR_buffer, BR);
  165451. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  165452. BR = 0;
  165453. }
  165454. /* If the coef was previously nonzero, it only needs a correction bit.
  165455. * NOTE: a straight translation of the spec's figure G.7 would suggest
  165456. * that we also need to test r > 15. But if r > 15, we can only get here
  165457. * if k > EOB, which implies that this coefficient is not 1.
  165458. */
  165459. if (temp > 1) {
  165460. /* The correction bit is the next bit of the absolute value. */
  165461. BR_buffer[BR++] = (char) (temp & 1);
  165462. continue;
  165463. }
  165464. /* Emit any pending EOBRUN and the BE correction bits */
  165465. emit_eobrun(entropy);
  165466. /* Count/emit Huffman symbol for run length / number of bits */
  165467. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  165468. /* Emit output bit for newly-nonzero coef */
  165469. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  165470. emit_bits_p(entropy, (unsigned int) temp, 1);
  165471. /* Emit buffered correction bits that must be associated with this code */
  165472. emit_buffered_bits(entropy, BR_buffer, BR);
  165473. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  165474. BR = 0;
  165475. r = 0; /* reset zero run length */
  165476. }
  165477. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  165478. entropy->EOBRUN++; /* count an EOB */
  165479. entropy->BE += BR; /* concat my correction bits to older ones */
  165480. /* We force out the EOB if we risk either:
  165481. * 1. overflow of the EOB counter;
  165482. * 2. overflow of the correction bit buffer during the next MCU.
  165483. */
  165484. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  165485. emit_eobrun(entropy);
  165486. }
  165487. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165488. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165489. /* Update restart-interval state too */
  165490. if (cinfo->restart_interval) {
  165491. if (entropy->restarts_to_go == 0) {
  165492. entropy->restarts_to_go = cinfo->restart_interval;
  165493. entropy->next_restart_num++;
  165494. entropy->next_restart_num &= 7;
  165495. }
  165496. entropy->restarts_to_go--;
  165497. }
  165498. return TRUE;
  165499. }
  165500. /*
  165501. * Finish up at the end of a Huffman-compressed progressive scan.
  165502. */
  165503. METHODDEF(void)
  165504. finish_pass_phuff (j_compress_ptr cinfo)
  165505. {
  165506. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165507. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165508. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165509. /* Flush out any buffered data */
  165510. emit_eobrun(entropy);
  165511. flush_bits_p(entropy);
  165512. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165513. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165514. }
  165515. /*
  165516. * Finish up a statistics-gathering pass and create the new Huffman tables.
  165517. */
  165518. METHODDEF(void)
  165519. finish_pass_gather_phuff (j_compress_ptr cinfo)
  165520. {
  165521. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165522. boolean is_DC_band;
  165523. int ci, tbl;
  165524. jpeg_component_info * compptr;
  165525. JHUFF_TBL **htblptr;
  165526. boolean did[NUM_HUFF_TBLS];
  165527. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  165528. emit_eobrun(entropy);
  165529. is_DC_band = (cinfo->Ss == 0);
  165530. /* It's important not to apply jpeg_gen_optimal_table more than once
  165531. * per table, because it clobbers the input frequency counts!
  165532. */
  165533. MEMZERO(did, SIZEOF(did));
  165534. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165535. compptr = cinfo->cur_comp_info[ci];
  165536. if (is_DC_band) {
  165537. if (cinfo->Ah != 0) /* DC refinement needs no table */
  165538. continue;
  165539. tbl = compptr->dc_tbl_no;
  165540. } else {
  165541. tbl = compptr->ac_tbl_no;
  165542. }
  165543. if (! did[tbl]) {
  165544. if (is_DC_band)
  165545. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  165546. else
  165547. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  165548. if (*htblptr == NULL)
  165549. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  165550. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  165551. did[tbl] = TRUE;
  165552. }
  165553. }
  165554. }
  165555. /*
  165556. * Module initialization routine for progressive Huffman entropy encoding.
  165557. */
  165558. GLOBAL(void)
  165559. jinit_phuff_encoder (j_compress_ptr cinfo)
  165560. {
  165561. phuff_entropy_ptr entropy;
  165562. int i;
  165563. entropy = (phuff_entropy_ptr)
  165564. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165565. SIZEOF(phuff_entropy_encoder));
  165566. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  165567. entropy->pub.start_pass = start_pass_phuff;
  165568. /* Mark tables unallocated */
  165569. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  165570. entropy->derived_tbls[i] = NULL;
  165571. entropy->count_ptrs[i] = NULL;
  165572. }
  165573. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  165574. }
  165575. #endif /* C_PROGRESSIVE_SUPPORTED */
  165576. /*** End of inlined file: jcphuff.c ***/
  165577. /*** Start of inlined file: jcprepct.c ***/
  165578. #define JPEG_INTERNALS
  165579. /* At present, jcsample.c can request context rows only for smoothing.
  165580. * In the future, we might also need context rows for CCIR601 sampling
  165581. * or other more-complex downsampling procedures. The code to support
  165582. * context rows should be compiled only if needed.
  165583. */
  165584. #ifdef INPUT_SMOOTHING_SUPPORTED
  165585. #define CONTEXT_ROWS_SUPPORTED
  165586. #endif
  165587. /*
  165588. * For the simple (no-context-row) case, we just need to buffer one
  165589. * row group's worth of pixels for the downsampling step. At the bottom of
  165590. * the image, we pad to a full row group by replicating the last pixel row.
  165591. * The downsampler's last output row is then replicated if needed to pad
  165592. * out to a full iMCU row.
  165593. *
  165594. * When providing context rows, we must buffer three row groups' worth of
  165595. * pixels. Three row groups are physically allocated, but the row pointer
  165596. * arrays are made five row groups high, with the extra pointers above and
  165597. * below "wrapping around" to point to the last and first real row groups.
  165598. * This allows the downsampler to access the proper context rows.
  165599. * At the top and bottom of the image, we create dummy context rows by
  165600. * copying the first or last real pixel row. This copying could be avoided
  165601. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  165602. * trouble on the compression side.
  165603. */
  165604. /* Private buffer controller object */
  165605. typedef struct {
  165606. struct jpeg_c_prep_controller pub; /* public fields */
  165607. /* Downsampling input buffer. This buffer holds color-converted data
  165608. * until we have enough to do a downsample step.
  165609. */
  165610. JSAMPARRAY color_buf[MAX_COMPONENTS];
  165611. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  165612. int next_buf_row; /* index of next row to store in color_buf */
  165613. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  165614. int this_row_group; /* starting row index of group to process */
  165615. int next_buf_stop; /* downsample when we reach this index */
  165616. #endif
  165617. } my_prep_controller;
  165618. typedef my_prep_controller * my_prep_ptr;
  165619. /*
  165620. * Initialize for a processing pass.
  165621. */
  165622. METHODDEF(void)
  165623. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  165624. {
  165625. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  165626. if (pass_mode != JBUF_PASS_THRU)
  165627. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  165628. /* Initialize total-height counter for detecting bottom of image */
  165629. prep->rows_to_go = cinfo->image_height;
  165630. /* Mark the conversion buffer empty */
  165631. prep->next_buf_row = 0;
  165632. #ifdef CONTEXT_ROWS_SUPPORTED
  165633. /* Preset additional state variables for context mode.
  165634. * These aren't used in non-context mode, so we needn't test which mode.
  165635. */
  165636. prep->this_row_group = 0;
  165637. /* Set next_buf_stop to stop after two row groups have been read in. */
  165638. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  165639. #endif
  165640. }
  165641. /*
  165642. * Expand an image vertically from height input_rows to height output_rows,
  165643. * by duplicating the bottom row.
  165644. */
  165645. LOCAL(void)
  165646. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  165647. int input_rows, int output_rows)
  165648. {
  165649. register int row;
  165650. for (row = input_rows; row < output_rows; row++) {
  165651. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  165652. 1, num_cols);
  165653. }
  165654. }
  165655. /*
  165656. * Process some data in the simple no-context case.
  165657. *
  165658. * Preprocessor output data is counted in "row groups". A row group
  165659. * is defined to be v_samp_factor sample rows of each component.
  165660. * Downsampling will produce this much data from each max_v_samp_factor
  165661. * input rows.
  165662. */
  165663. METHODDEF(void)
  165664. pre_process_data (j_compress_ptr cinfo,
  165665. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  165666. JDIMENSION in_rows_avail,
  165667. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  165668. JDIMENSION out_row_groups_avail)
  165669. {
  165670. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  165671. int numrows, ci;
  165672. JDIMENSION inrows;
  165673. jpeg_component_info * compptr;
  165674. while (*in_row_ctr < in_rows_avail &&
  165675. *out_row_group_ctr < out_row_groups_avail) {
  165676. /* Do color conversion to fill the conversion buffer. */
  165677. inrows = in_rows_avail - *in_row_ctr;
  165678. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  165679. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  165680. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  165681. prep->color_buf,
  165682. (JDIMENSION) prep->next_buf_row,
  165683. numrows);
  165684. *in_row_ctr += numrows;
  165685. prep->next_buf_row += numrows;
  165686. prep->rows_to_go -= numrows;
  165687. /* If at bottom of image, pad to fill the conversion buffer. */
  165688. if (prep->rows_to_go == 0 &&
  165689. prep->next_buf_row < cinfo->max_v_samp_factor) {
  165690. for (ci = 0; ci < cinfo->num_components; ci++) {
  165691. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  165692. prep->next_buf_row, cinfo->max_v_samp_factor);
  165693. }
  165694. prep->next_buf_row = cinfo->max_v_samp_factor;
  165695. }
  165696. /* If we've filled the conversion buffer, empty it. */
  165697. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  165698. (*cinfo->downsample->downsample) (cinfo,
  165699. prep->color_buf, (JDIMENSION) 0,
  165700. output_buf, *out_row_group_ctr);
  165701. prep->next_buf_row = 0;
  165702. (*out_row_group_ctr)++;
  165703. }
  165704. /* If at bottom of image, pad the output to a full iMCU height.
  165705. * Note we assume the caller is providing a one-iMCU-height output buffer!
  165706. */
  165707. if (prep->rows_to_go == 0 &&
  165708. *out_row_group_ctr < out_row_groups_avail) {
  165709. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165710. ci++, compptr++) {
  165711. expand_bottom_edge(output_buf[ci],
  165712. compptr->width_in_blocks * DCTSIZE,
  165713. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  165714. (int) (out_row_groups_avail * compptr->v_samp_factor));
  165715. }
  165716. *out_row_group_ctr = out_row_groups_avail;
  165717. break; /* can exit outer loop without test */
  165718. }
  165719. }
  165720. }
  165721. #ifdef CONTEXT_ROWS_SUPPORTED
  165722. /*
  165723. * Process some data in the context case.
  165724. */
  165725. METHODDEF(void)
  165726. pre_process_context (j_compress_ptr cinfo,
  165727. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  165728. JDIMENSION in_rows_avail,
  165729. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  165730. JDIMENSION out_row_groups_avail)
  165731. {
  165732. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  165733. int numrows, ci;
  165734. int buf_height = cinfo->max_v_samp_factor * 3;
  165735. JDIMENSION inrows;
  165736. while (*out_row_group_ctr < out_row_groups_avail) {
  165737. if (*in_row_ctr < in_rows_avail) {
  165738. /* Do color conversion to fill the conversion buffer. */
  165739. inrows = in_rows_avail - *in_row_ctr;
  165740. numrows = prep->next_buf_stop - prep->next_buf_row;
  165741. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  165742. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  165743. prep->color_buf,
  165744. (JDIMENSION) prep->next_buf_row,
  165745. numrows);
  165746. /* Pad at top of image, if first time through */
  165747. if (prep->rows_to_go == cinfo->image_height) {
  165748. for (ci = 0; ci < cinfo->num_components; ci++) {
  165749. int row;
  165750. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  165751. jcopy_sample_rows(prep->color_buf[ci], 0,
  165752. prep->color_buf[ci], -row,
  165753. 1, cinfo->image_width);
  165754. }
  165755. }
  165756. }
  165757. *in_row_ctr += numrows;
  165758. prep->next_buf_row += numrows;
  165759. prep->rows_to_go -= numrows;
  165760. } else {
  165761. /* Return for more data, unless we are at the bottom of the image. */
  165762. if (prep->rows_to_go != 0)
  165763. break;
  165764. /* When at bottom of image, pad to fill the conversion buffer. */
  165765. if (prep->next_buf_row < prep->next_buf_stop) {
  165766. for (ci = 0; ci < cinfo->num_components; ci++) {
  165767. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  165768. prep->next_buf_row, prep->next_buf_stop);
  165769. }
  165770. prep->next_buf_row = prep->next_buf_stop;
  165771. }
  165772. }
  165773. /* If we've gotten enough data, downsample a row group. */
  165774. if (prep->next_buf_row == prep->next_buf_stop) {
  165775. (*cinfo->downsample->downsample) (cinfo,
  165776. prep->color_buf,
  165777. (JDIMENSION) prep->this_row_group,
  165778. output_buf, *out_row_group_ctr);
  165779. (*out_row_group_ctr)++;
  165780. /* Advance pointers with wraparound as necessary. */
  165781. prep->this_row_group += cinfo->max_v_samp_factor;
  165782. if (prep->this_row_group >= buf_height)
  165783. prep->this_row_group = 0;
  165784. if (prep->next_buf_row >= buf_height)
  165785. prep->next_buf_row = 0;
  165786. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  165787. }
  165788. }
  165789. }
  165790. /*
  165791. * Create the wrapped-around downsampling input buffer needed for context mode.
  165792. */
  165793. LOCAL(void)
  165794. create_context_buffer (j_compress_ptr cinfo)
  165795. {
  165796. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  165797. int rgroup_height = cinfo->max_v_samp_factor;
  165798. int ci, i;
  165799. jpeg_component_info * compptr;
  165800. JSAMPARRAY true_buffer, fake_buffer;
  165801. /* Grab enough space for fake row pointers for all the components;
  165802. * we need five row groups' worth of pointers for each component.
  165803. */
  165804. fake_buffer = (JSAMPARRAY)
  165805. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165806. (cinfo->num_components * 5 * rgroup_height) *
  165807. SIZEOF(JSAMPROW));
  165808. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165809. ci++, compptr++) {
  165810. /* Allocate the actual buffer space (3 row groups) for this component.
  165811. * We make the buffer wide enough to allow the downsampler to edge-expand
  165812. * horizontally within the buffer, if it so chooses.
  165813. */
  165814. true_buffer = (*cinfo->mem->alloc_sarray)
  165815. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165816. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  165817. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  165818. (JDIMENSION) (3 * rgroup_height));
  165819. /* Copy true buffer row pointers into the middle of the fake row array */
  165820. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  165821. 3 * rgroup_height * SIZEOF(JSAMPROW));
  165822. /* Fill in the above and below wraparound pointers */
  165823. for (i = 0; i < rgroup_height; i++) {
  165824. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  165825. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  165826. }
  165827. prep->color_buf[ci] = fake_buffer + rgroup_height;
  165828. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  165829. }
  165830. }
  165831. #endif /* CONTEXT_ROWS_SUPPORTED */
  165832. /*
  165833. * Initialize preprocessing controller.
  165834. */
  165835. GLOBAL(void)
  165836. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  165837. {
  165838. my_prep_ptr prep;
  165839. int ci;
  165840. jpeg_component_info * compptr;
  165841. if (need_full_buffer) /* safety check */
  165842. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  165843. prep = (my_prep_ptr)
  165844. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165845. SIZEOF(my_prep_controller));
  165846. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  165847. prep->pub.start_pass = start_pass_prep;
  165848. /* Allocate the color conversion buffer.
  165849. * We make the buffer wide enough to allow the downsampler to edge-expand
  165850. * horizontally within the buffer, if it so chooses.
  165851. */
  165852. if (cinfo->downsample->need_context_rows) {
  165853. /* Set up to provide context rows */
  165854. #ifdef CONTEXT_ROWS_SUPPORTED
  165855. prep->pub.pre_process_data = pre_process_context;
  165856. create_context_buffer(cinfo);
  165857. #else
  165858. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165859. #endif
  165860. } else {
  165861. /* No context, just make it tall enough for one row group */
  165862. prep->pub.pre_process_data = pre_process_data;
  165863. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165864. ci++, compptr++) {
  165865. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  165866. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165867. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  165868. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  165869. (JDIMENSION) cinfo->max_v_samp_factor);
  165870. }
  165871. }
  165872. }
  165873. /*** End of inlined file: jcprepct.c ***/
  165874. /*** Start of inlined file: jcsample.c ***/
  165875. #define JPEG_INTERNALS
  165876. /* Pointer to routine to downsample a single component */
  165877. typedef JMETHOD(void, downsample1_ptr,
  165878. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  165879. JSAMPARRAY input_data, JSAMPARRAY output_data));
  165880. /* Private subobject */
  165881. typedef struct {
  165882. struct jpeg_downsampler pub; /* public fields */
  165883. /* Downsampling method pointers, one per component */
  165884. downsample1_ptr methods[MAX_COMPONENTS];
  165885. } my_downsampler;
  165886. typedef my_downsampler * my_downsample_ptr;
  165887. /*
  165888. * Initialize for a downsampling pass.
  165889. */
  165890. METHODDEF(void)
  165891. start_pass_downsample (j_compress_ptr)
  165892. {
  165893. /* no work for now */
  165894. }
  165895. /*
  165896. * Expand a component horizontally from width input_cols to width output_cols,
  165897. * by duplicating the rightmost samples.
  165898. */
  165899. LOCAL(void)
  165900. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  165901. JDIMENSION input_cols, JDIMENSION output_cols)
  165902. {
  165903. register JSAMPROW ptr;
  165904. register JSAMPLE pixval;
  165905. register int count;
  165906. int row;
  165907. int numcols = (int) (output_cols - input_cols);
  165908. if (numcols > 0) {
  165909. for (row = 0; row < num_rows; row++) {
  165910. ptr = image_data[row] + input_cols;
  165911. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  165912. for (count = numcols; count > 0; count--)
  165913. *ptr++ = pixval;
  165914. }
  165915. }
  165916. }
  165917. /*
  165918. * Do downsampling for a whole row group (all components).
  165919. *
  165920. * In this version we simply downsample each component independently.
  165921. */
  165922. METHODDEF(void)
  165923. sep_downsample (j_compress_ptr cinfo,
  165924. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  165925. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  165926. {
  165927. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  165928. int ci;
  165929. jpeg_component_info * compptr;
  165930. JSAMPARRAY in_ptr, out_ptr;
  165931. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165932. ci++, compptr++) {
  165933. in_ptr = input_buf[ci] + in_row_index;
  165934. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  165935. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  165936. }
  165937. }
  165938. /*
  165939. * Downsample pixel values of a single component.
  165940. * One row group is processed per call.
  165941. * This version handles arbitrary integral sampling ratios, without smoothing.
  165942. * Note that this version is not actually used for customary sampling ratios.
  165943. */
  165944. METHODDEF(void)
  165945. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  165946. JSAMPARRAY input_data, JSAMPARRAY output_data)
  165947. {
  165948. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  165949. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  165950. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  165951. JSAMPROW inptr, outptr;
  165952. INT32 outvalue;
  165953. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  165954. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  165955. numpix = h_expand * v_expand;
  165956. numpix2 = numpix/2;
  165957. /* Expand input data enough to let all the output samples be generated
  165958. * by the standard loop. Special-casing padded output would be more
  165959. * efficient.
  165960. */
  165961. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  165962. cinfo->image_width, output_cols * h_expand);
  165963. inrow = 0;
  165964. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  165965. outptr = output_data[outrow];
  165966. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  165967. outcol++, outcol_h += h_expand) {
  165968. outvalue = 0;
  165969. for (v = 0; v < v_expand; v++) {
  165970. inptr = input_data[inrow+v] + outcol_h;
  165971. for (h = 0; h < h_expand; h++) {
  165972. outvalue += (INT32) GETJSAMPLE(*inptr++);
  165973. }
  165974. }
  165975. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  165976. }
  165977. inrow += v_expand;
  165978. }
  165979. }
  165980. /*
  165981. * Downsample pixel values of a single component.
  165982. * This version handles the special case of a full-size component,
  165983. * without smoothing.
  165984. */
  165985. METHODDEF(void)
  165986. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  165987. JSAMPARRAY input_data, JSAMPARRAY output_data)
  165988. {
  165989. /* Copy the data */
  165990. jcopy_sample_rows(input_data, 0, output_data, 0,
  165991. cinfo->max_v_samp_factor, cinfo->image_width);
  165992. /* Edge-expand */
  165993. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  165994. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  165995. }
  165996. /*
  165997. * Downsample pixel values of a single component.
  165998. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  165999. * without smoothing.
  166000. *
  166001. * A note about the "bias" calculations: when rounding fractional values to
  166002. * integer, we do not want to always round 0.5 up to the next integer.
  166003. * If we did that, we'd introduce a noticeable bias towards larger values.
  166004. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  166005. * alternate pixel locations (a simple ordered dither pattern).
  166006. */
  166007. METHODDEF(void)
  166008. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166009. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166010. {
  166011. int outrow;
  166012. JDIMENSION outcol;
  166013. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166014. register JSAMPROW inptr, outptr;
  166015. register int bias;
  166016. /* Expand input data enough to let all the output samples be generated
  166017. * by the standard loop. Special-casing padded output would be more
  166018. * efficient.
  166019. */
  166020. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166021. cinfo->image_width, output_cols * 2);
  166022. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166023. outptr = output_data[outrow];
  166024. inptr = input_data[outrow];
  166025. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  166026. for (outcol = 0; outcol < output_cols; outcol++) {
  166027. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  166028. + bias) >> 1);
  166029. bias ^= 1; /* 0=>1, 1=>0 */
  166030. inptr += 2;
  166031. }
  166032. }
  166033. }
  166034. /*
  166035. * Downsample pixel values of a single component.
  166036. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  166037. * without smoothing.
  166038. */
  166039. METHODDEF(void)
  166040. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166041. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166042. {
  166043. int inrow, outrow;
  166044. JDIMENSION outcol;
  166045. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166046. register JSAMPROW inptr0, inptr1, outptr;
  166047. register int bias;
  166048. /* Expand input data enough to let all the output samples be generated
  166049. * by the standard loop. Special-casing padded output would be more
  166050. * efficient.
  166051. */
  166052. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166053. cinfo->image_width, output_cols * 2);
  166054. inrow = 0;
  166055. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166056. outptr = output_data[outrow];
  166057. inptr0 = input_data[inrow];
  166058. inptr1 = input_data[inrow+1];
  166059. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  166060. for (outcol = 0; outcol < output_cols; outcol++) {
  166061. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166062. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  166063. + bias) >> 2);
  166064. bias ^= 3; /* 1=>2, 2=>1 */
  166065. inptr0 += 2; inptr1 += 2;
  166066. }
  166067. inrow += 2;
  166068. }
  166069. }
  166070. #ifdef INPUT_SMOOTHING_SUPPORTED
  166071. /*
  166072. * Downsample pixel values of a single component.
  166073. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  166074. * with smoothing. One row of context is required.
  166075. */
  166076. METHODDEF(void)
  166077. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166078. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166079. {
  166080. int inrow, outrow;
  166081. JDIMENSION colctr;
  166082. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166083. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  166084. INT32 membersum, neighsum, memberscale, neighscale;
  166085. /* Expand input data enough to let all the output samples be generated
  166086. * by the standard loop. Special-casing padded output would be more
  166087. * efficient.
  166088. */
  166089. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  166090. cinfo->image_width, output_cols * 2);
  166091. /* We don't bother to form the individual "smoothed" input pixel values;
  166092. * we can directly compute the output which is the average of the four
  166093. * smoothed values. Each of the four member pixels contributes a fraction
  166094. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  166095. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  166096. * output. The four corner-adjacent neighbor pixels contribute a fraction
  166097. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  166098. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  166099. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  166100. * factors are scaled by 2^16 = 65536.
  166101. * Also recall that SF = smoothing_factor / 1024.
  166102. */
  166103. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  166104. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  166105. inrow = 0;
  166106. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166107. outptr = output_data[outrow];
  166108. inptr0 = input_data[inrow];
  166109. inptr1 = input_data[inrow+1];
  166110. above_ptr = input_data[inrow-1];
  166111. below_ptr = input_data[inrow+2];
  166112. /* Special case for first column: pretend column -1 is same as column 0 */
  166113. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166114. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166115. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166116. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166117. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  166118. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  166119. neighsum += neighsum;
  166120. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  166121. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  166122. membersum = membersum * memberscale + neighsum * neighscale;
  166123. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166124. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  166125. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  166126. /* sum of pixels directly mapped to this output element */
  166127. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166128. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166129. /* sum of edge-neighbor pixels */
  166130. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166131. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166132. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  166133. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  166134. /* The edge-neighbors count twice as much as corner-neighbors */
  166135. neighsum += neighsum;
  166136. /* Add in the corner-neighbors */
  166137. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  166138. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  166139. /* form final output scaled up by 2^16 */
  166140. membersum = membersum * memberscale + neighsum * neighscale;
  166141. /* round, descale and output it */
  166142. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166143. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  166144. }
  166145. /* Special case for last column */
  166146. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166147. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166148. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166149. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166150. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  166151. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  166152. neighsum += neighsum;
  166153. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  166154. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  166155. membersum = membersum * memberscale + neighsum * neighscale;
  166156. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  166157. inrow += 2;
  166158. }
  166159. }
  166160. /*
  166161. * Downsample pixel values of a single component.
  166162. * This version handles the special case of a full-size component,
  166163. * with smoothing. One row of context is required.
  166164. */
  166165. METHODDEF(void)
  166166. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  166167. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166168. {
  166169. int outrow;
  166170. JDIMENSION colctr;
  166171. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166172. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  166173. INT32 membersum, neighsum, memberscale, neighscale;
  166174. int colsum, lastcolsum, nextcolsum;
  166175. /* Expand input data enough to let all the output samples be generated
  166176. * by the standard loop. Special-casing padded output would be more
  166177. * efficient.
  166178. */
  166179. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  166180. cinfo->image_width, output_cols);
  166181. /* Each of the eight neighbor pixels contributes a fraction SF to the
  166182. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  166183. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  166184. * Also recall that SF = smoothing_factor / 1024.
  166185. */
  166186. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  166187. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  166188. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166189. outptr = output_data[outrow];
  166190. inptr = input_data[outrow];
  166191. above_ptr = input_data[outrow-1];
  166192. below_ptr = input_data[outrow+1];
  166193. /* Special case for first column */
  166194. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  166195. GETJSAMPLE(*inptr);
  166196. membersum = GETJSAMPLE(*inptr++);
  166197. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  166198. GETJSAMPLE(*inptr);
  166199. neighsum = colsum + (colsum - membersum) + nextcolsum;
  166200. membersum = membersum * memberscale + neighsum * neighscale;
  166201. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166202. lastcolsum = colsum; colsum = nextcolsum;
  166203. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  166204. membersum = GETJSAMPLE(*inptr++);
  166205. above_ptr++; below_ptr++;
  166206. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  166207. GETJSAMPLE(*inptr);
  166208. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  166209. membersum = membersum * memberscale + neighsum * neighscale;
  166210. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166211. lastcolsum = colsum; colsum = nextcolsum;
  166212. }
  166213. /* Special case for last column */
  166214. membersum = GETJSAMPLE(*inptr);
  166215. neighsum = lastcolsum + (colsum - membersum) + colsum;
  166216. membersum = membersum * memberscale + neighsum * neighscale;
  166217. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  166218. }
  166219. }
  166220. #endif /* INPUT_SMOOTHING_SUPPORTED */
  166221. /*
  166222. * Module initialization routine for downsampling.
  166223. * Note that we must select a routine for each component.
  166224. */
  166225. GLOBAL(void)
  166226. jinit_downsampler (j_compress_ptr cinfo)
  166227. {
  166228. my_downsample_ptr downsample;
  166229. int ci;
  166230. jpeg_component_info * compptr;
  166231. boolean smoothok = TRUE;
  166232. downsample = (my_downsample_ptr)
  166233. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166234. SIZEOF(my_downsampler));
  166235. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  166236. downsample->pub.start_pass = start_pass_downsample;
  166237. downsample->pub.downsample = sep_downsample;
  166238. downsample->pub.need_context_rows = FALSE;
  166239. if (cinfo->CCIR601_sampling)
  166240. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  166241. /* Verify we can handle the sampling factors, and set up method pointers */
  166242. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166243. ci++, compptr++) {
  166244. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  166245. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  166246. #ifdef INPUT_SMOOTHING_SUPPORTED
  166247. if (cinfo->smoothing_factor) {
  166248. downsample->methods[ci] = fullsize_smooth_downsample;
  166249. downsample->pub.need_context_rows = TRUE;
  166250. } else
  166251. #endif
  166252. downsample->methods[ci] = fullsize_downsample;
  166253. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  166254. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  166255. smoothok = FALSE;
  166256. downsample->methods[ci] = h2v1_downsample;
  166257. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  166258. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  166259. #ifdef INPUT_SMOOTHING_SUPPORTED
  166260. if (cinfo->smoothing_factor) {
  166261. downsample->methods[ci] = h2v2_smooth_downsample;
  166262. downsample->pub.need_context_rows = TRUE;
  166263. } else
  166264. #endif
  166265. downsample->methods[ci] = h2v2_downsample;
  166266. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  166267. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  166268. smoothok = FALSE;
  166269. downsample->methods[ci] = int_downsample;
  166270. } else
  166271. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  166272. }
  166273. #ifdef INPUT_SMOOTHING_SUPPORTED
  166274. if (cinfo->smoothing_factor && !smoothok)
  166275. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  166276. #endif
  166277. }
  166278. /*** End of inlined file: jcsample.c ***/
  166279. /*** Start of inlined file: jctrans.c ***/
  166280. #define JPEG_INTERNALS
  166281. /* Forward declarations */
  166282. LOCAL(void) transencode_master_selection
  166283. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  166284. LOCAL(void) transencode_coef_controller
  166285. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  166286. /*
  166287. * Compression initialization for writing raw-coefficient data.
  166288. * Before calling this, all parameters and a data destination must be set up.
  166289. * Call jpeg_finish_compress() to actually write the data.
  166290. *
  166291. * The number of passed virtual arrays must match cinfo->num_components.
  166292. * Note that the virtual arrays need not be filled or even realized at
  166293. * the time write_coefficients is called; indeed, if the virtual arrays
  166294. * were requested from this compression object's memory manager, they
  166295. * typically will be realized during this routine and filled afterwards.
  166296. */
  166297. GLOBAL(void)
  166298. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  166299. {
  166300. if (cinfo->global_state != CSTATE_START)
  166301. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166302. /* Mark all tables to be written */
  166303. jpeg_suppress_tables(cinfo, FALSE);
  166304. /* (Re)initialize error mgr and destination modules */
  166305. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  166306. (*cinfo->dest->init_destination) (cinfo);
  166307. /* Perform master selection of active modules */
  166308. transencode_master_selection(cinfo, coef_arrays);
  166309. /* Wait for jpeg_finish_compress() call */
  166310. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  166311. cinfo->global_state = CSTATE_WRCOEFS;
  166312. }
  166313. /*
  166314. * Initialize the compression object with default parameters,
  166315. * then copy from the source object all parameters needed for lossless
  166316. * transcoding. Parameters that can be varied without loss (such as
  166317. * scan script and Huffman optimization) are left in their default states.
  166318. */
  166319. GLOBAL(void)
  166320. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  166321. j_compress_ptr dstinfo)
  166322. {
  166323. JQUANT_TBL ** qtblptr;
  166324. jpeg_component_info *incomp, *outcomp;
  166325. JQUANT_TBL *c_quant, *slot_quant;
  166326. int tblno, ci, coefi;
  166327. /* Safety check to ensure start_compress not called yet. */
  166328. if (dstinfo->global_state != CSTATE_START)
  166329. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  166330. /* Copy fundamental image dimensions */
  166331. dstinfo->image_width = srcinfo->image_width;
  166332. dstinfo->image_height = srcinfo->image_height;
  166333. dstinfo->input_components = srcinfo->num_components;
  166334. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  166335. /* Initialize all parameters to default values */
  166336. jpeg_set_defaults(dstinfo);
  166337. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  166338. * Fix it to get the right header markers for the image colorspace.
  166339. */
  166340. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  166341. dstinfo->data_precision = srcinfo->data_precision;
  166342. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  166343. /* Copy the source's quantization tables. */
  166344. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  166345. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  166346. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  166347. if (*qtblptr == NULL)
  166348. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  166349. MEMCOPY((*qtblptr)->quantval,
  166350. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  166351. SIZEOF((*qtblptr)->quantval));
  166352. (*qtblptr)->sent_table = FALSE;
  166353. }
  166354. }
  166355. /* Copy the source's per-component info.
  166356. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  166357. */
  166358. dstinfo->num_components = srcinfo->num_components;
  166359. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  166360. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  166361. MAX_COMPONENTS);
  166362. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  166363. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  166364. outcomp->component_id = incomp->component_id;
  166365. outcomp->h_samp_factor = incomp->h_samp_factor;
  166366. outcomp->v_samp_factor = incomp->v_samp_factor;
  166367. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  166368. /* Make sure saved quantization table for component matches the qtable
  166369. * slot. If not, the input file re-used this qtable slot.
  166370. * IJG encoder currently cannot duplicate this.
  166371. */
  166372. tblno = outcomp->quant_tbl_no;
  166373. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  166374. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  166375. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  166376. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  166377. c_quant = incomp->quant_table;
  166378. if (c_quant != NULL) {
  166379. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  166380. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  166381. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  166382. }
  166383. }
  166384. /* Note: we do not copy the source's Huffman table assignments;
  166385. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  166386. */
  166387. }
  166388. /* Also copy JFIF version and resolution information, if available.
  166389. * Strictly speaking this isn't "critical" info, but it's nearly
  166390. * always appropriate to copy it if available. In particular,
  166391. * if the application chooses to copy JFIF 1.02 extension markers from
  166392. * the source file, we need to copy the version to make sure we don't
  166393. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  166394. * We will *not*, however, copy version info from mislabeled "2.01" files.
  166395. */
  166396. if (srcinfo->saw_JFIF_marker) {
  166397. if (srcinfo->JFIF_major_version == 1) {
  166398. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  166399. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  166400. }
  166401. dstinfo->density_unit = srcinfo->density_unit;
  166402. dstinfo->X_density = srcinfo->X_density;
  166403. dstinfo->Y_density = srcinfo->Y_density;
  166404. }
  166405. }
  166406. /*
  166407. * Master selection of compression modules for transcoding.
  166408. * This substitutes for jcinit.c's initialization of the full compressor.
  166409. */
  166410. LOCAL(void)
  166411. transencode_master_selection (j_compress_ptr cinfo,
  166412. jvirt_barray_ptr * coef_arrays)
  166413. {
  166414. /* Although we don't actually use input_components for transcoding,
  166415. * jcmaster.c's initial_setup will complain if input_components is 0.
  166416. */
  166417. cinfo->input_components = 1;
  166418. /* Initialize master control (includes parameter checking/processing) */
  166419. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  166420. /* Entropy encoding: either Huffman or arithmetic coding. */
  166421. if (cinfo->arith_code) {
  166422. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  166423. } else {
  166424. if (cinfo->progressive_mode) {
  166425. #ifdef C_PROGRESSIVE_SUPPORTED
  166426. jinit_phuff_encoder(cinfo);
  166427. #else
  166428. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166429. #endif
  166430. } else
  166431. jinit_huff_encoder(cinfo);
  166432. }
  166433. /* We need a special coefficient buffer controller. */
  166434. transencode_coef_controller(cinfo, coef_arrays);
  166435. jinit_marker_writer(cinfo);
  166436. /* We can now tell the memory manager to allocate virtual arrays. */
  166437. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  166438. /* Write the datastream header (SOI, JFIF) immediately.
  166439. * Frame and scan headers are postponed till later.
  166440. * This lets application insert special markers after the SOI.
  166441. */
  166442. (*cinfo->marker->write_file_header) (cinfo);
  166443. }
  166444. /*
  166445. * The rest of this file is a special implementation of the coefficient
  166446. * buffer controller. This is similar to jccoefct.c, but it handles only
  166447. * output from presupplied virtual arrays. Furthermore, we generate any
  166448. * dummy padding blocks on-the-fly rather than expecting them to be present
  166449. * in the arrays.
  166450. */
  166451. /* Private buffer controller object */
  166452. typedef struct {
  166453. struct jpeg_c_coef_controller pub; /* public fields */
  166454. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  166455. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  166456. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  166457. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  166458. /* Virtual block array for each component. */
  166459. jvirt_barray_ptr * whole_image;
  166460. /* Workspace for constructing dummy blocks at right/bottom edges. */
  166461. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  166462. } my_coef_controller2;
  166463. typedef my_coef_controller2 * my_coef_ptr2;
  166464. LOCAL(void)
  166465. start_iMCU_row2 (j_compress_ptr cinfo)
  166466. /* Reset within-iMCU-row counters for a new row */
  166467. {
  166468. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  166469. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  166470. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  166471. * But at the bottom of the image, process only what's left.
  166472. */
  166473. if (cinfo->comps_in_scan > 1) {
  166474. coef->MCU_rows_per_iMCU_row = 1;
  166475. } else {
  166476. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  166477. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  166478. else
  166479. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  166480. }
  166481. coef->mcu_ctr = 0;
  166482. coef->MCU_vert_offset = 0;
  166483. }
  166484. /*
  166485. * Initialize for a processing pass.
  166486. */
  166487. METHODDEF(void)
  166488. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  166489. {
  166490. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  166491. if (pass_mode != JBUF_CRANK_DEST)
  166492. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166493. coef->iMCU_row_num = 0;
  166494. start_iMCU_row2(cinfo);
  166495. }
  166496. /*
  166497. * Process some data.
  166498. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  166499. * per call, ie, v_samp_factor block rows for each component in the scan.
  166500. * The data is obtained from the virtual arrays and fed to the entropy coder.
  166501. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  166502. *
  166503. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  166504. */
  166505. METHODDEF(boolean)
  166506. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE)
  166507. {
  166508. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  166509. JDIMENSION MCU_col_num; /* index of current MCU within row */
  166510. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  166511. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  166512. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  166513. JDIMENSION start_col;
  166514. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  166515. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  166516. JBLOCKROW buffer_ptr;
  166517. jpeg_component_info *compptr;
  166518. /* Align the virtual buffers for the components used in this scan. */
  166519. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166520. compptr = cinfo->cur_comp_info[ci];
  166521. buffer[ci] = (*cinfo->mem->access_virt_barray)
  166522. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  166523. coef->iMCU_row_num * compptr->v_samp_factor,
  166524. (JDIMENSION) compptr->v_samp_factor, FALSE);
  166525. }
  166526. /* Loop to process one whole iMCU row */
  166527. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  166528. yoffset++) {
  166529. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  166530. MCU_col_num++) {
  166531. /* Construct list of pointers to DCT blocks belonging to this MCU */
  166532. blkn = 0; /* index of current DCT block within MCU */
  166533. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166534. compptr = cinfo->cur_comp_info[ci];
  166535. start_col = MCU_col_num * compptr->MCU_width;
  166536. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  166537. : compptr->last_col_width;
  166538. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  166539. if (coef->iMCU_row_num < last_iMCU_row ||
  166540. yindex+yoffset < compptr->last_row_height) {
  166541. /* Fill in pointers to real blocks in this row */
  166542. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  166543. for (xindex = 0; xindex < blockcnt; xindex++)
  166544. MCU_buffer[blkn++] = buffer_ptr++;
  166545. } else {
  166546. /* At bottom of image, need a whole row of dummy blocks */
  166547. xindex = 0;
  166548. }
  166549. /* Fill in any dummy blocks needed in this row.
  166550. * Dummy blocks are filled in the same way as in jccoefct.c:
  166551. * all zeroes in the AC entries, DC entries equal to previous
  166552. * block's DC value. The init routine has already zeroed the
  166553. * AC entries, so we need only set the DC entries correctly.
  166554. */
  166555. for (; xindex < compptr->MCU_width; xindex++) {
  166556. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  166557. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  166558. blkn++;
  166559. }
  166560. }
  166561. }
  166562. /* Try to write the MCU. */
  166563. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  166564. /* Suspension forced; update state counters and exit */
  166565. coef->MCU_vert_offset = yoffset;
  166566. coef->mcu_ctr = MCU_col_num;
  166567. return FALSE;
  166568. }
  166569. }
  166570. /* Completed an MCU row, but perhaps not an iMCU row */
  166571. coef->mcu_ctr = 0;
  166572. }
  166573. /* Completed the iMCU row, advance counters for next one */
  166574. coef->iMCU_row_num++;
  166575. start_iMCU_row2(cinfo);
  166576. return TRUE;
  166577. }
  166578. /*
  166579. * Initialize coefficient buffer controller.
  166580. *
  166581. * Each passed coefficient array must be the right size for that
  166582. * coefficient: width_in_blocks wide and height_in_blocks high,
  166583. * with unitheight at least v_samp_factor.
  166584. */
  166585. LOCAL(void)
  166586. transencode_coef_controller (j_compress_ptr cinfo,
  166587. jvirt_barray_ptr * coef_arrays)
  166588. {
  166589. my_coef_ptr2 coef;
  166590. JBLOCKROW buffer;
  166591. int i;
  166592. coef = (my_coef_ptr2)
  166593. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166594. SIZEOF(my_coef_controller2));
  166595. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  166596. coef->pub.start_pass = start_pass_coef2;
  166597. coef->pub.compress_data = compress_output2;
  166598. /* Save pointer to virtual arrays */
  166599. coef->whole_image = coef_arrays;
  166600. /* Allocate and pre-zero space for dummy DCT blocks. */
  166601. buffer = (JBLOCKROW)
  166602. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166603. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  166604. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  166605. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  166606. coef->dummy_buffer[i] = buffer + i;
  166607. }
  166608. }
  166609. /*** End of inlined file: jctrans.c ***/
  166610. /*** Start of inlined file: jdapistd.c ***/
  166611. #define JPEG_INTERNALS
  166612. /* Forward declarations */
  166613. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  166614. /*
  166615. * Decompression initialization.
  166616. * jpeg_read_header must be completed before calling this.
  166617. *
  166618. * If a multipass operating mode was selected, this will do all but the
  166619. * last pass, and thus may take a great deal of time.
  166620. *
  166621. * Returns FALSE if suspended. The return value need be inspected only if
  166622. * a suspending data source is used.
  166623. */
  166624. GLOBAL(boolean)
  166625. jpeg_start_decompress (j_decompress_ptr cinfo)
  166626. {
  166627. if (cinfo->global_state == DSTATE_READY) {
  166628. /* First call: initialize master control, select active modules */
  166629. jinit_master_decompress(cinfo);
  166630. if (cinfo->buffered_image) {
  166631. /* No more work here; expecting jpeg_start_output next */
  166632. cinfo->global_state = DSTATE_BUFIMAGE;
  166633. return TRUE;
  166634. }
  166635. cinfo->global_state = DSTATE_PRELOAD;
  166636. }
  166637. if (cinfo->global_state == DSTATE_PRELOAD) {
  166638. /* If file has multiple scans, absorb them all into the coef buffer */
  166639. if (cinfo->inputctl->has_multiple_scans) {
  166640. #ifdef D_MULTISCAN_FILES_SUPPORTED
  166641. for (;;) {
  166642. int retcode;
  166643. /* Call progress monitor hook if present */
  166644. if (cinfo->progress != NULL)
  166645. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  166646. /* Absorb some more input */
  166647. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  166648. if (retcode == JPEG_SUSPENDED)
  166649. return FALSE;
  166650. if (retcode == JPEG_REACHED_EOI)
  166651. break;
  166652. /* Advance progress counter if appropriate */
  166653. if (cinfo->progress != NULL &&
  166654. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  166655. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  166656. /* jdmaster underestimated number of scans; ratchet up one scan */
  166657. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  166658. }
  166659. }
  166660. }
  166661. #else
  166662. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166663. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  166664. }
  166665. cinfo->output_scan_number = cinfo->input_scan_number;
  166666. } else if (cinfo->global_state != DSTATE_PRESCAN)
  166667. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166668. /* Perform any dummy output passes, and set up for the final pass */
  166669. return output_pass_setup(cinfo);
  166670. }
  166671. /*
  166672. * Set up for an output pass, and perform any dummy pass(es) needed.
  166673. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  166674. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  166675. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  166676. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  166677. */
  166678. LOCAL(boolean)
  166679. output_pass_setup (j_decompress_ptr cinfo)
  166680. {
  166681. if (cinfo->global_state != DSTATE_PRESCAN) {
  166682. /* First call: do pass setup */
  166683. (*cinfo->master->prepare_for_output_pass) (cinfo);
  166684. cinfo->output_scanline = 0;
  166685. cinfo->global_state = DSTATE_PRESCAN;
  166686. }
  166687. /* Loop over any required dummy passes */
  166688. while (cinfo->master->is_dummy_pass) {
  166689. #ifdef QUANT_2PASS_SUPPORTED
  166690. /* Crank through the dummy pass */
  166691. while (cinfo->output_scanline < cinfo->output_height) {
  166692. JDIMENSION last_scanline;
  166693. /* Call progress monitor hook if present */
  166694. if (cinfo->progress != NULL) {
  166695. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  166696. cinfo->progress->pass_limit = (long) cinfo->output_height;
  166697. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  166698. }
  166699. /* Process some data */
  166700. last_scanline = cinfo->output_scanline;
  166701. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  166702. &cinfo->output_scanline, (JDIMENSION) 0);
  166703. if (cinfo->output_scanline == last_scanline)
  166704. return FALSE; /* No progress made, must suspend */
  166705. }
  166706. /* Finish up dummy pass, and set up for another one */
  166707. (*cinfo->master->finish_output_pass) (cinfo);
  166708. (*cinfo->master->prepare_for_output_pass) (cinfo);
  166709. cinfo->output_scanline = 0;
  166710. #else
  166711. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166712. #endif /* QUANT_2PASS_SUPPORTED */
  166713. }
  166714. /* Ready for application to drive output pass through
  166715. * jpeg_read_scanlines or jpeg_read_raw_data.
  166716. */
  166717. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  166718. return TRUE;
  166719. }
  166720. /*
  166721. * Read some scanlines of data from the JPEG decompressor.
  166722. *
  166723. * The return value will be the number of lines actually read.
  166724. * This may be less than the number requested in several cases,
  166725. * including bottom of image, data source suspension, and operating
  166726. * modes that emit multiple scanlines at a time.
  166727. *
  166728. * Note: we warn about excess calls to jpeg_read_scanlines() since
  166729. * this likely signals an application programmer error. However,
  166730. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  166731. */
  166732. GLOBAL(JDIMENSION)
  166733. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  166734. JDIMENSION max_lines)
  166735. {
  166736. JDIMENSION row_ctr;
  166737. if (cinfo->global_state != DSTATE_SCANNING)
  166738. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166739. if (cinfo->output_scanline >= cinfo->output_height) {
  166740. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  166741. return 0;
  166742. }
  166743. /* Call progress monitor hook if present */
  166744. if (cinfo->progress != NULL) {
  166745. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  166746. cinfo->progress->pass_limit = (long) cinfo->output_height;
  166747. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  166748. }
  166749. /* Process some data */
  166750. row_ctr = 0;
  166751. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  166752. cinfo->output_scanline += row_ctr;
  166753. return row_ctr;
  166754. }
  166755. /*
  166756. * Alternate entry point to read raw data.
  166757. * Processes exactly one iMCU row per call, unless suspended.
  166758. */
  166759. GLOBAL(JDIMENSION)
  166760. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  166761. JDIMENSION max_lines)
  166762. {
  166763. JDIMENSION lines_per_iMCU_row;
  166764. if (cinfo->global_state != DSTATE_RAW_OK)
  166765. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166766. if (cinfo->output_scanline >= cinfo->output_height) {
  166767. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  166768. return 0;
  166769. }
  166770. /* Call progress monitor hook if present */
  166771. if (cinfo->progress != NULL) {
  166772. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  166773. cinfo->progress->pass_limit = (long) cinfo->output_height;
  166774. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  166775. }
  166776. /* Verify that at least one iMCU row can be returned. */
  166777. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  166778. if (max_lines < lines_per_iMCU_row)
  166779. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  166780. /* Decompress directly into user's buffer. */
  166781. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  166782. return 0; /* suspension forced, can do nothing more */
  166783. /* OK, we processed one iMCU row. */
  166784. cinfo->output_scanline += lines_per_iMCU_row;
  166785. return lines_per_iMCU_row;
  166786. }
  166787. /* Additional entry points for buffered-image mode. */
  166788. #ifdef D_MULTISCAN_FILES_SUPPORTED
  166789. /*
  166790. * Initialize for an output pass in buffered-image mode.
  166791. */
  166792. GLOBAL(boolean)
  166793. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  166794. {
  166795. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  166796. cinfo->global_state != DSTATE_PRESCAN)
  166797. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166798. /* Limit scan number to valid range */
  166799. if (scan_number <= 0)
  166800. scan_number = 1;
  166801. if (cinfo->inputctl->eoi_reached &&
  166802. scan_number > cinfo->input_scan_number)
  166803. scan_number = cinfo->input_scan_number;
  166804. cinfo->output_scan_number = scan_number;
  166805. /* Perform any dummy output passes, and set up for the real pass */
  166806. return output_pass_setup(cinfo);
  166807. }
  166808. /*
  166809. * Finish up after an output pass in buffered-image mode.
  166810. *
  166811. * Returns FALSE if suspended. The return value need be inspected only if
  166812. * a suspending data source is used.
  166813. */
  166814. GLOBAL(boolean)
  166815. jpeg_finish_output (j_decompress_ptr cinfo)
  166816. {
  166817. if ((cinfo->global_state == DSTATE_SCANNING ||
  166818. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  166819. /* Terminate this pass. */
  166820. /* We do not require the whole pass to have been completed. */
  166821. (*cinfo->master->finish_output_pass) (cinfo);
  166822. cinfo->global_state = DSTATE_BUFPOST;
  166823. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  166824. /* BUFPOST = repeat call after a suspension, anything else is error */
  166825. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166826. }
  166827. /* Read markers looking for SOS or EOI */
  166828. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  166829. ! cinfo->inputctl->eoi_reached) {
  166830. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  166831. return FALSE; /* Suspend, come back later */
  166832. }
  166833. cinfo->global_state = DSTATE_BUFIMAGE;
  166834. return TRUE;
  166835. }
  166836. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  166837. /*** End of inlined file: jdapistd.c ***/
  166838. /*** Start of inlined file: jdapimin.c ***/
  166839. #define JPEG_INTERNALS
  166840. /*
  166841. * Initialization of a JPEG decompression object.
  166842. * The error manager must already be set up (in case memory manager fails).
  166843. */
  166844. GLOBAL(void)
  166845. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  166846. {
  166847. int i;
  166848. /* Guard against version mismatches between library and caller. */
  166849. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  166850. if (version != JPEG_LIB_VERSION)
  166851. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  166852. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  166853. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  166854. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  166855. /* For debugging purposes, we zero the whole master structure.
  166856. * But the application has already set the err pointer, and may have set
  166857. * client_data, so we have to save and restore those fields.
  166858. * Note: if application hasn't set client_data, tools like Purify may
  166859. * complain here.
  166860. */
  166861. {
  166862. struct jpeg_error_mgr * err = cinfo->err;
  166863. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  166864. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  166865. cinfo->err = err;
  166866. cinfo->client_data = client_data;
  166867. }
  166868. cinfo->is_decompressor = TRUE;
  166869. /* Initialize a memory manager instance for this object */
  166870. jinit_memory_mgr((j_common_ptr) cinfo);
  166871. /* Zero out pointers to permanent structures. */
  166872. cinfo->progress = NULL;
  166873. cinfo->src = NULL;
  166874. for (i = 0; i < NUM_QUANT_TBLS; i++)
  166875. cinfo->quant_tbl_ptrs[i] = NULL;
  166876. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  166877. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  166878. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  166879. }
  166880. /* Initialize marker processor so application can override methods
  166881. * for COM, APPn markers before calling jpeg_read_header.
  166882. */
  166883. cinfo->marker_list = NULL;
  166884. jinit_marker_reader(cinfo);
  166885. /* And initialize the overall input controller. */
  166886. jinit_input_controller(cinfo);
  166887. /* OK, I'm ready */
  166888. cinfo->global_state = DSTATE_START;
  166889. }
  166890. /*
  166891. * Destruction of a JPEG decompression object
  166892. */
  166893. GLOBAL(void)
  166894. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  166895. {
  166896. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  166897. }
  166898. /*
  166899. * Abort processing of a JPEG decompression operation,
  166900. * but don't destroy the object itself.
  166901. */
  166902. GLOBAL(void)
  166903. jpeg_abort_decompress (j_decompress_ptr cinfo)
  166904. {
  166905. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  166906. }
  166907. /*
  166908. * Set default decompression parameters.
  166909. */
  166910. LOCAL(void)
  166911. default_decompress_parms (j_decompress_ptr cinfo)
  166912. {
  166913. /* Guess the input colorspace, and set output colorspace accordingly. */
  166914. /* (Wish JPEG committee had provided a real way to specify this...) */
  166915. /* Note application may override our guesses. */
  166916. switch (cinfo->num_components) {
  166917. case 1:
  166918. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  166919. cinfo->out_color_space = JCS_GRAYSCALE;
  166920. break;
  166921. case 3:
  166922. if (cinfo->saw_JFIF_marker) {
  166923. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  166924. } else if (cinfo->saw_Adobe_marker) {
  166925. switch (cinfo->Adobe_transform) {
  166926. case 0:
  166927. cinfo->jpeg_color_space = JCS_RGB;
  166928. break;
  166929. case 1:
  166930. cinfo->jpeg_color_space = JCS_YCbCr;
  166931. break;
  166932. default:
  166933. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  166934. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  166935. break;
  166936. }
  166937. } else {
  166938. /* Saw no special markers, try to guess from the component IDs */
  166939. int cid0 = cinfo->comp_info[0].component_id;
  166940. int cid1 = cinfo->comp_info[1].component_id;
  166941. int cid2 = cinfo->comp_info[2].component_id;
  166942. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  166943. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  166944. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  166945. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  166946. else {
  166947. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  166948. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  166949. }
  166950. }
  166951. /* Always guess RGB is proper output colorspace. */
  166952. cinfo->out_color_space = JCS_RGB;
  166953. break;
  166954. case 4:
  166955. if (cinfo->saw_Adobe_marker) {
  166956. switch (cinfo->Adobe_transform) {
  166957. case 0:
  166958. cinfo->jpeg_color_space = JCS_CMYK;
  166959. break;
  166960. case 2:
  166961. cinfo->jpeg_color_space = JCS_YCCK;
  166962. break;
  166963. default:
  166964. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  166965. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  166966. break;
  166967. }
  166968. } else {
  166969. /* No special markers, assume straight CMYK. */
  166970. cinfo->jpeg_color_space = JCS_CMYK;
  166971. }
  166972. cinfo->out_color_space = JCS_CMYK;
  166973. break;
  166974. default:
  166975. cinfo->jpeg_color_space = JCS_UNKNOWN;
  166976. cinfo->out_color_space = JCS_UNKNOWN;
  166977. break;
  166978. }
  166979. /* Set defaults for other decompression parameters. */
  166980. cinfo->scale_num = 1; /* 1:1 scaling */
  166981. cinfo->scale_denom = 1;
  166982. cinfo->output_gamma = 1.0;
  166983. cinfo->buffered_image = FALSE;
  166984. cinfo->raw_data_out = FALSE;
  166985. cinfo->dct_method = JDCT_DEFAULT;
  166986. cinfo->do_fancy_upsampling = TRUE;
  166987. cinfo->do_block_smoothing = TRUE;
  166988. cinfo->quantize_colors = FALSE;
  166989. /* We set these in case application only sets quantize_colors. */
  166990. cinfo->dither_mode = JDITHER_FS;
  166991. #ifdef QUANT_2PASS_SUPPORTED
  166992. cinfo->two_pass_quantize = TRUE;
  166993. #else
  166994. cinfo->two_pass_quantize = FALSE;
  166995. #endif
  166996. cinfo->desired_number_of_colors = 256;
  166997. cinfo->colormap = NULL;
  166998. /* Initialize for no mode change in buffered-image mode. */
  166999. cinfo->enable_1pass_quant = FALSE;
  167000. cinfo->enable_external_quant = FALSE;
  167001. cinfo->enable_2pass_quant = FALSE;
  167002. }
  167003. /*
  167004. * Decompression startup: read start of JPEG datastream to see what's there.
  167005. * Need only initialize JPEG object and supply a data source before calling.
  167006. *
  167007. * This routine will read as far as the first SOS marker (ie, actual start of
  167008. * compressed data), and will save all tables and parameters in the JPEG
  167009. * object. It will also initialize the decompression parameters to default
  167010. * values, and finally return JPEG_HEADER_OK. On return, the application may
  167011. * adjust the decompression parameters and then call jpeg_start_decompress.
  167012. * (Or, if the application only wanted to determine the image parameters,
  167013. * the data need not be decompressed. In that case, call jpeg_abort or
  167014. * jpeg_destroy to release any temporary space.)
  167015. * If an abbreviated (tables only) datastream is presented, the routine will
  167016. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  167017. * re-use the JPEG object to read the abbreviated image datastream(s).
  167018. * It is unnecessary (but OK) to call jpeg_abort in this case.
  167019. * The JPEG_SUSPENDED return code only occurs if the data source module
  167020. * requests suspension of the decompressor. In this case the application
  167021. * should load more source data and then re-call jpeg_read_header to resume
  167022. * processing.
  167023. * If a non-suspending data source is used and require_image is TRUE, then the
  167024. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  167025. *
  167026. * This routine is now just a front end to jpeg_consume_input, with some
  167027. * extra error checking.
  167028. */
  167029. GLOBAL(int)
  167030. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  167031. {
  167032. int retcode;
  167033. if (cinfo->global_state != DSTATE_START &&
  167034. cinfo->global_state != DSTATE_INHEADER)
  167035. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167036. retcode = jpeg_consume_input(cinfo);
  167037. switch (retcode) {
  167038. case JPEG_REACHED_SOS:
  167039. retcode = JPEG_HEADER_OK;
  167040. break;
  167041. case JPEG_REACHED_EOI:
  167042. if (require_image) /* Complain if application wanted an image */
  167043. ERREXIT(cinfo, JERR_NO_IMAGE);
  167044. /* Reset to start state; it would be safer to require the application to
  167045. * call jpeg_abort, but we can't change it now for compatibility reasons.
  167046. * A side effect is to free any temporary memory (there shouldn't be any).
  167047. */
  167048. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  167049. retcode = JPEG_HEADER_TABLES_ONLY;
  167050. break;
  167051. case JPEG_SUSPENDED:
  167052. /* no work */
  167053. break;
  167054. }
  167055. return retcode;
  167056. }
  167057. /*
  167058. * Consume data in advance of what the decompressor requires.
  167059. * This can be called at any time once the decompressor object has
  167060. * been created and a data source has been set up.
  167061. *
  167062. * This routine is essentially a state machine that handles a couple
  167063. * of critical state-transition actions, namely initial setup and
  167064. * transition from header scanning to ready-for-start_decompress.
  167065. * All the actual input is done via the input controller's consume_input
  167066. * method.
  167067. */
  167068. GLOBAL(int)
  167069. jpeg_consume_input (j_decompress_ptr cinfo)
  167070. {
  167071. int retcode = JPEG_SUSPENDED;
  167072. /* NB: every possible DSTATE value should be listed in this switch */
  167073. switch (cinfo->global_state) {
  167074. case DSTATE_START:
  167075. /* Start-of-datastream actions: reset appropriate modules */
  167076. (*cinfo->inputctl->reset_input_controller) (cinfo);
  167077. /* Initialize application's data source module */
  167078. (*cinfo->src->init_source) (cinfo);
  167079. cinfo->global_state = DSTATE_INHEADER;
  167080. /*FALLTHROUGH*/
  167081. case DSTATE_INHEADER:
  167082. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167083. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  167084. /* Set up default parameters based on header data */
  167085. default_decompress_parms(cinfo);
  167086. /* Set global state: ready for start_decompress */
  167087. cinfo->global_state = DSTATE_READY;
  167088. }
  167089. break;
  167090. case DSTATE_READY:
  167091. /* Can't advance past first SOS until start_decompress is called */
  167092. retcode = JPEG_REACHED_SOS;
  167093. break;
  167094. case DSTATE_PRELOAD:
  167095. case DSTATE_PRESCAN:
  167096. case DSTATE_SCANNING:
  167097. case DSTATE_RAW_OK:
  167098. case DSTATE_BUFIMAGE:
  167099. case DSTATE_BUFPOST:
  167100. case DSTATE_STOPPING:
  167101. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167102. break;
  167103. default:
  167104. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167105. }
  167106. return retcode;
  167107. }
  167108. /*
  167109. * Have we finished reading the input file?
  167110. */
  167111. GLOBAL(boolean)
  167112. jpeg_input_complete (j_decompress_ptr cinfo)
  167113. {
  167114. /* Check for valid jpeg object */
  167115. if (cinfo->global_state < DSTATE_START ||
  167116. cinfo->global_state > DSTATE_STOPPING)
  167117. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167118. return cinfo->inputctl->eoi_reached;
  167119. }
  167120. /*
  167121. * Is there more than one scan?
  167122. */
  167123. GLOBAL(boolean)
  167124. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  167125. {
  167126. /* Only valid after jpeg_read_header completes */
  167127. if (cinfo->global_state < DSTATE_READY ||
  167128. cinfo->global_state > DSTATE_STOPPING)
  167129. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167130. return cinfo->inputctl->has_multiple_scans;
  167131. }
  167132. /*
  167133. * Finish JPEG decompression.
  167134. *
  167135. * This will normally just verify the file trailer and release temp storage.
  167136. *
  167137. * Returns FALSE if suspended. The return value need be inspected only if
  167138. * a suspending data source is used.
  167139. */
  167140. GLOBAL(boolean)
  167141. jpeg_finish_decompress (j_decompress_ptr cinfo)
  167142. {
  167143. if ((cinfo->global_state == DSTATE_SCANNING ||
  167144. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  167145. /* Terminate final pass of non-buffered mode */
  167146. if (cinfo->output_scanline < cinfo->output_height)
  167147. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  167148. (*cinfo->master->finish_output_pass) (cinfo);
  167149. cinfo->global_state = DSTATE_STOPPING;
  167150. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  167151. /* Finishing after a buffered-image operation */
  167152. cinfo->global_state = DSTATE_STOPPING;
  167153. } else if (cinfo->global_state != DSTATE_STOPPING) {
  167154. /* STOPPING = repeat call after a suspension, anything else is error */
  167155. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167156. }
  167157. /* Read until EOI */
  167158. while (! cinfo->inputctl->eoi_reached) {
  167159. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  167160. return FALSE; /* Suspend, come back later */
  167161. }
  167162. /* Do final cleanup */
  167163. (*cinfo->src->term_source) (cinfo);
  167164. /* We can use jpeg_abort to release memory and reset global_state */
  167165. jpeg_abort((j_common_ptr) cinfo);
  167166. return TRUE;
  167167. }
  167168. /*** End of inlined file: jdapimin.c ***/
  167169. /*** Start of inlined file: jdatasrc.c ***/
  167170. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  167171. /*** Start of inlined file: jerror.h ***/
  167172. /*
  167173. * To define the enum list of message codes, include this file without
  167174. * defining macro JMESSAGE. To create a message string table, include it
  167175. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  167176. */
  167177. #ifndef JMESSAGE
  167178. #ifndef JERROR_H
  167179. /* First time through, define the enum list */
  167180. #define JMAKE_ENUM_LIST
  167181. #else
  167182. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  167183. #define JMESSAGE(code,string)
  167184. #endif /* JERROR_H */
  167185. #endif /* JMESSAGE */
  167186. #ifdef JMAKE_ENUM_LIST
  167187. typedef enum {
  167188. #define JMESSAGE(code,string) code ,
  167189. #endif /* JMAKE_ENUM_LIST */
  167190. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  167191. /* For maintenance convenience, list is alphabetical by message code name */
  167192. JMESSAGE(JERR_ARITH_NOTIMPL,
  167193. "Sorry, there are legal restrictions on arithmetic coding")
  167194. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  167195. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  167196. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  167197. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  167198. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  167199. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  167200. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  167201. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  167202. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  167203. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  167204. JMESSAGE(JERR_BAD_LIB_VERSION,
  167205. "Wrong JPEG library version: library is %d, caller expects %d")
  167206. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  167207. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  167208. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  167209. JMESSAGE(JERR_BAD_PROGRESSION,
  167210. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  167211. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  167212. "Invalid progressive parameters at scan script entry %d")
  167213. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  167214. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  167215. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  167216. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  167217. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  167218. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  167219. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  167220. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  167221. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  167222. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  167223. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  167224. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  167225. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  167226. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  167227. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  167228. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  167229. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  167230. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  167231. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  167232. JMESSAGE(JERR_FILE_READ, "Input file read error")
  167233. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  167234. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  167235. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  167236. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  167237. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  167238. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  167239. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  167240. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  167241. "Cannot transcode due to multiple use of quantization table %d")
  167242. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  167243. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  167244. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  167245. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  167246. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  167247. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  167248. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  167249. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  167250. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  167251. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  167252. JMESSAGE(JERR_QUANT_COMPONENTS,
  167253. "Cannot quantize more than %d color components")
  167254. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  167255. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  167256. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  167257. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  167258. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  167259. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  167260. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  167261. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  167262. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  167263. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  167264. JMESSAGE(JERR_TFILE_WRITE,
  167265. "Write failed on temporary file --- out of disk space?")
  167266. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  167267. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  167268. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  167269. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  167270. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  167271. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  167272. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  167273. JMESSAGE(JMSG_VERSION, JVERSION)
  167274. JMESSAGE(JTRC_16BIT_TABLES,
  167275. "Caution: quantization tables are too coarse for baseline JPEG")
  167276. JMESSAGE(JTRC_ADOBE,
  167277. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  167278. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  167279. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  167280. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  167281. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  167282. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  167283. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  167284. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  167285. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  167286. JMESSAGE(JTRC_EOI, "End Of Image")
  167287. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  167288. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  167289. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  167290. "Warning: thumbnail image size does not match data length %u")
  167291. JMESSAGE(JTRC_JFIF_EXTENSION,
  167292. "JFIF extension marker: type 0x%02x, length %u")
  167293. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  167294. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  167295. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  167296. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  167297. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  167298. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  167299. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  167300. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  167301. JMESSAGE(JTRC_RST, "RST%d")
  167302. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  167303. "Smoothing not supported with nonstandard sampling ratios")
  167304. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  167305. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  167306. JMESSAGE(JTRC_SOI, "Start of Image")
  167307. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  167308. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  167309. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  167310. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  167311. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  167312. JMESSAGE(JTRC_THUMB_JPEG,
  167313. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  167314. JMESSAGE(JTRC_THUMB_PALETTE,
  167315. "JFIF extension marker: palette thumbnail image, length %u")
  167316. JMESSAGE(JTRC_THUMB_RGB,
  167317. "JFIF extension marker: RGB thumbnail image, length %u")
  167318. JMESSAGE(JTRC_UNKNOWN_IDS,
  167319. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  167320. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  167321. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  167322. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  167323. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  167324. "Inconsistent progression sequence for component %d coefficient %d")
  167325. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  167326. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  167327. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  167328. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  167329. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  167330. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  167331. JMESSAGE(JWRN_MUST_RESYNC,
  167332. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  167333. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  167334. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  167335. #ifdef JMAKE_ENUM_LIST
  167336. JMSG_LASTMSGCODE
  167337. } J_MESSAGE_CODE;
  167338. #undef JMAKE_ENUM_LIST
  167339. #endif /* JMAKE_ENUM_LIST */
  167340. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  167341. #undef JMESSAGE
  167342. #ifndef JERROR_H
  167343. #define JERROR_H
  167344. /* Macros to simplify using the error and trace message stuff */
  167345. /* The first parameter is either type of cinfo pointer */
  167346. /* Fatal errors (print message and exit) */
  167347. #define ERREXIT(cinfo,code) \
  167348. ((cinfo)->err->msg_code = (code), \
  167349. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167350. #define ERREXIT1(cinfo,code,p1) \
  167351. ((cinfo)->err->msg_code = (code), \
  167352. (cinfo)->err->msg_parm.i[0] = (p1), \
  167353. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167354. #define ERREXIT2(cinfo,code,p1,p2) \
  167355. ((cinfo)->err->msg_code = (code), \
  167356. (cinfo)->err->msg_parm.i[0] = (p1), \
  167357. (cinfo)->err->msg_parm.i[1] = (p2), \
  167358. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167359. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  167360. ((cinfo)->err->msg_code = (code), \
  167361. (cinfo)->err->msg_parm.i[0] = (p1), \
  167362. (cinfo)->err->msg_parm.i[1] = (p2), \
  167363. (cinfo)->err->msg_parm.i[2] = (p3), \
  167364. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167365. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  167366. ((cinfo)->err->msg_code = (code), \
  167367. (cinfo)->err->msg_parm.i[0] = (p1), \
  167368. (cinfo)->err->msg_parm.i[1] = (p2), \
  167369. (cinfo)->err->msg_parm.i[2] = (p3), \
  167370. (cinfo)->err->msg_parm.i[3] = (p4), \
  167371. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167372. #define ERREXITS(cinfo,code,str) \
  167373. ((cinfo)->err->msg_code = (code), \
  167374. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  167375. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167376. #define MAKESTMT(stuff) do { stuff } while (0)
  167377. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  167378. #define WARNMS(cinfo,code) \
  167379. ((cinfo)->err->msg_code = (code), \
  167380. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  167381. #define WARNMS1(cinfo,code,p1) \
  167382. ((cinfo)->err->msg_code = (code), \
  167383. (cinfo)->err->msg_parm.i[0] = (p1), \
  167384. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  167385. #define WARNMS2(cinfo,code,p1,p2) \
  167386. ((cinfo)->err->msg_code = (code), \
  167387. (cinfo)->err->msg_parm.i[0] = (p1), \
  167388. (cinfo)->err->msg_parm.i[1] = (p2), \
  167389. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  167390. /* Informational/debugging messages */
  167391. #define TRACEMS(cinfo,lvl,code) \
  167392. ((cinfo)->err->msg_code = (code), \
  167393. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167394. #define TRACEMS1(cinfo,lvl,code,p1) \
  167395. ((cinfo)->err->msg_code = (code), \
  167396. (cinfo)->err->msg_parm.i[0] = (p1), \
  167397. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167398. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  167399. ((cinfo)->err->msg_code = (code), \
  167400. (cinfo)->err->msg_parm.i[0] = (p1), \
  167401. (cinfo)->err->msg_parm.i[1] = (p2), \
  167402. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167403. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  167404. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167405. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  167406. (cinfo)->err->msg_code = (code); \
  167407. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167408. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  167409. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167410. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  167411. (cinfo)->err->msg_code = (code); \
  167412. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167413. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  167414. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167415. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  167416. _mp[4] = (p5); \
  167417. (cinfo)->err->msg_code = (code); \
  167418. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167419. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  167420. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167421. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  167422. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  167423. (cinfo)->err->msg_code = (code); \
  167424. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167425. #define TRACEMSS(cinfo,lvl,code,str) \
  167426. ((cinfo)->err->msg_code = (code), \
  167427. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  167428. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167429. #endif /* JERROR_H */
  167430. /*** End of inlined file: jerror.h ***/
  167431. /* Expanded data source object for stdio input */
  167432. typedef struct {
  167433. struct jpeg_source_mgr pub; /* public fields */
  167434. FILE * infile; /* source stream */
  167435. JOCTET * buffer; /* start of buffer */
  167436. boolean start_of_file; /* have we gotten any data yet? */
  167437. } my_source_mgr;
  167438. typedef my_source_mgr * my_src_ptr;
  167439. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  167440. /*
  167441. * Initialize source --- called by jpeg_read_header
  167442. * before any data is actually read.
  167443. */
  167444. METHODDEF(void)
  167445. init_source (j_decompress_ptr cinfo)
  167446. {
  167447. my_src_ptr src = (my_src_ptr) cinfo->src;
  167448. /* We reset the empty-input-file flag for each image,
  167449. * but we don't clear the input buffer.
  167450. * This is correct behavior for reading a series of images from one source.
  167451. */
  167452. src->start_of_file = TRUE;
  167453. }
  167454. /*
  167455. * Fill the input buffer --- called whenever buffer is emptied.
  167456. *
  167457. * In typical applications, this should read fresh data into the buffer
  167458. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  167459. * reset the pointer & count to the start of the buffer, and return TRUE
  167460. * indicating that the buffer has been reloaded. It is not necessary to
  167461. * fill the buffer entirely, only to obtain at least one more byte.
  167462. *
  167463. * There is no such thing as an EOF return. If the end of the file has been
  167464. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  167465. * the buffer. In most cases, generating a warning message and inserting a
  167466. * fake EOI marker is the best course of action --- this will allow the
  167467. * decompressor to output however much of the image is there. However,
  167468. * the resulting error message is misleading if the real problem is an empty
  167469. * input file, so we handle that case specially.
  167470. *
  167471. * In applications that need to be able to suspend compression due to input
  167472. * not being available yet, a FALSE return indicates that no more data can be
  167473. * obtained right now, but more may be forthcoming later. In this situation,
  167474. * the decompressor will return to its caller (with an indication of the
  167475. * number of scanlines it has read, if any). The application should resume
  167476. * decompression after it has loaded more data into the input buffer. Note
  167477. * that there are substantial restrictions on the use of suspension --- see
  167478. * the documentation.
  167479. *
  167480. * When suspending, the decompressor will back up to a convenient restart point
  167481. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  167482. * indicate where the restart point will be if the current call returns FALSE.
  167483. * Data beyond this point must be rescanned after resumption, so move it to
  167484. * the front of the buffer rather than discarding it.
  167485. */
  167486. METHODDEF(boolean)
  167487. fill_input_buffer (j_decompress_ptr cinfo)
  167488. {
  167489. my_src_ptr src = (my_src_ptr) cinfo->src;
  167490. size_t nbytes;
  167491. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  167492. if (nbytes <= 0) {
  167493. if (src->start_of_file) /* Treat empty input file as fatal error */
  167494. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  167495. WARNMS(cinfo, JWRN_JPEG_EOF);
  167496. /* Insert a fake EOI marker */
  167497. src->buffer[0] = (JOCTET) 0xFF;
  167498. src->buffer[1] = (JOCTET) JPEG_EOI;
  167499. nbytes = 2;
  167500. }
  167501. src->pub.next_input_byte = src->buffer;
  167502. src->pub.bytes_in_buffer = nbytes;
  167503. src->start_of_file = FALSE;
  167504. return TRUE;
  167505. }
  167506. /*
  167507. * Skip data --- used to skip over a potentially large amount of
  167508. * uninteresting data (such as an APPn marker).
  167509. *
  167510. * Writers of suspendable-input applications must note that skip_input_data
  167511. * is not granted the right to give a suspension return. If the skip extends
  167512. * beyond the data currently in the buffer, the buffer can be marked empty so
  167513. * that the next read will cause a fill_input_buffer call that can suspend.
  167514. * Arranging for additional bytes to be discarded before reloading the input
  167515. * buffer is the application writer's problem.
  167516. */
  167517. METHODDEF(void)
  167518. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  167519. {
  167520. my_src_ptr src = (my_src_ptr) cinfo->src;
  167521. /* Just a dumb implementation for now. Could use fseek() except
  167522. * it doesn't work on pipes. Not clear that being smart is worth
  167523. * any trouble anyway --- large skips are infrequent.
  167524. */
  167525. if (num_bytes > 0) {
  167526. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  167527. num_bytes -= (long) src->pub.bytes_in_buffer;
  167528. (void) fill_input_buffer(cinfo);
  167529. /* note we assume that fill_input_buffer will never return FALSE,
  167530. * so suspension need not be handled.
  167531. */
  167532. }
  167533. src->pub.next_input_byte += (size_t) num_bytes;
  167534. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  167535. }
  167536. }
  167537. /*
  167538. * An additional method that can be provided by data source modules is the
  167539. * resync_to_restart method for error recovery in the presence of RST markers.
  167540. * For the moment, this source module just uses the default resync method
  167541. * provided by the JPEG library. That method assumes that no backtracking
  167542. * is possible.
  167543. */
  167544. /*
  167545. * Terminate source --- called by jpeg_finish_decompress
  167546. * after all data has been read. Often a no-op.
  167547. *
  167548. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  167549. * application must deal with any cleanup that should happen even
  167550. * for error exit.
  167551. */
  167552. METHODDEF(void)
  167553. term_source (j_decompress_ptr)
  167554. {
  167555. /* no work necessary here */
  167556. }
  167557. /*
  167558. * Prepare for input from a stdio stream.
  167559. * The caller must have already opened the stream, and is responsible
  167560. * for closing it after finishing decompression.
  167561. */
  167562. GLOBAL(void)
  167563. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  167564. {
  167565. my_src_ptr src;
  167566. /* The source object and input buffer are made permanent so that a series
  167567. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  167568. * only before the first one. (If we discarded the buffer at the end of
  167569. * one image, we'd likely lose the start of the next one.)
  167570. * This makes it unsafe to use this manager and a different source
  167571. * manager serially with the same JPEG object. Caveat programmer.
  167572. */
  167573. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  167574. cinfo->src = (struct jpeg_source_mgr *)
  167575. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  167576. SIZEOF(my_source_mgr));
  167577. src = (my_src_ptr) cinfo->src;
  167578. src->buffer = (JOCTET *)
  167579. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  167580. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  167581. }
  167582. src = (my_src_ptr) cinfo->src;
  167583. src->pub.init_source = init_source;
  167584. src->pub.fill_input_buffer = fill_input_buffer;
  167585. src->pub.skip_input_data = skip_input_data;
  167586. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  167587. src->pub.term_source = term_source;
  167588. src->infile = infile;
  167589. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  167590. src->pub.next_input_byte = NULL; /* until buffer loaded */
  167591. }
  167592. /*** End of inlined file: jdatasrc.c ***/
  167593. /*** Start of inlined file: jdcoefct.c ***/
  167594. #define JPEG_INTERNALS
  167595. /* Block smoothing is only applicable for progressive JPEG, so: */
  167596. #ifndef D_PROGRESSIVE_SUPPORTED
  167597. #undef BLOCK_SMOOTHING_SUPPORTED
  167598. #endif
  167599. /* Private buffer controller object */
  167600. typedef struct {
  167601. struct jpeg_d_coef_controller pub; /* public fields */
  167602. /* These variables keep track of the current location of the input side. */
  167603. /* cinfo->input_iMCU_row is also used for this. */
  167604. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  167605. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  167606. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  167607. /* The output side's location is represented by cinfo->output_iMCU_row. */
  167608. /* In single-pass modes, it's sufficient to buffer just one MCU.
  167609. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  167610. * and let the entropy decoder write into that workspace each time.
  167611. * (On 80x86, the workspace is FAR even though it's not really very big;
  167612. * this is to keep the module interfaces unchanged when a large coefficient
  167613. * buffer is necessary.)
  167614. * In multi-pass modes, this array points to the current MCU's blocks
  167615. * within the virtual arrays; it is used only by the input side.
  167616. */
  167617. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  167618. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167619. /* In multi-pass modes, we need a virtual block array for each component. */
  167620. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  167621. #endif
  167622. #ifdef BLOCK_SMOOTHING_SUPPORTED
  167623. /* When doing block smoothing, we latch coefficient Al values here */
  167624. int * coef_bits_latch;
  167625. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  167626. #endif
  167627. } my_coef_controller3;
  167628. typedef my_coef_controller3 * my_coef_ptr3;
  167629. /* Forward declarations */
  167630. METHODDEF(int) decompress_onepass
  167631. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  167632. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167633. METHODDEF(int) decompress_data
  167634. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  167635. #endif
  167636. #ifdef BLOCK_SMOOTHING_SUPPORTED
  167637. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  167638. METHODDEF(int) decompress_smooth_data
  167639. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  167640. #endif
  167641. LOCAL(void)
  167642. start_iMCU_row3 (j_decompress_ptr cinfo)
  167643. /* Reset within-iMCU-row counters for a new row (input side) */
  167644. {
  167645. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  167646. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  167647. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  167648. * But at the bottom of the image, process only what's left.
  167649. */
  167650. if (cinfo->comps_in_scan > 1) {
  167651. coef->MCU_rows_per_iMCU_row = 1;
  167652. } else {
  167653. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  167654. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  167655. else
  167656. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  167657. }
  167658. coef->MCU_ctr = 0;
  167659. coef->MCU_vert_offset = 0;
  167660. }
  167661. /*
  167662. * Initialize for an input processing pass.
  167663. */
  167664. METHODDEF(void)
  167665. start_input_pass (j_decompress_ptr cinfo)
  167666. {
  167667. cinfo->input_iMCU_row = 0;
  167668. start_iMCU_row3(cinfo);
  167669. }
  167670. /*
  167671. * Initialize for an output processing pass.
  167672. */
  167673. METHODDEF(void)
  167674. start_output_pass (j_decompress_ptr cinfo)
  167675. {
  167676. #ifdef BLOCK_SMOOTHING_SUPPORTED
  167677. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  167678. /* If multipass, check to see whether to use block smoothing on this pass */
  167679. if (coef->pub.coef_arrays != NULL) {
  167680. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  167681. coef->pub.decompress_data = decompress_smooth_data;
  167682. else
  167683. coef->pub.decompress_data = decompress_data;
  167684. }
  167685. #endif
  167686. cinfo->output_iMCU_row = 0;
  167687. }
  167688. /*
  167689. * Decompress and return some data in the single-pass case.
  167690. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  167691. * Input and output must run in lockstep since we have only a one-MCU buffer.
  167692. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  167693. *
  167694. * NB: output_buf contains a plane for each component in image,
  167695. * which we index according to the component's SOF position.
  167696. */
  167697. METHODDEF(int)
  167698. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  167699. {
  167700. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  167701. JDIMENSION MCU_col_num; /* index of current MCU within row */
  167702. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  167703. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  167704. int blkn, ci, xindex, yindex, yoffset, useful_width;
  167705. JSAMPARRAY output_ptr;
  167706. JDIMENSION start_col, output_col;
  167707. jpeg_component_info *compptr;
  167708. inverse_DCT_method_ptr inverse_DCT;
  167709. /* Loop to process as much as one whole iMCU row */
  167710. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  167711. yoffset++) {
  167712. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  167713. MCU_col_num++) {
  167714. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  167715. jzero_far((void FAR *) coef->MCU_buffer[0],
  167716. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  167717. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  167718. /* Suspension forced; update state counters and exit */
  167719. coef->MCU_vert_offset = yoffset;
  167720. coef->MCU_ctr = MCU_col_num;
  167721. return JPEG_SUSPENDED;
  167722. }
  167723. /* Determine where data should go in output_buf and do the IDCT thing.
  167724. * We skip dummy blocks at the right and bottom edges (but blkn gets
  167725. * incremented past them!). Note the inner loop relies on having
  167726. * allocated the MCU_buffer[] blocks sequentially.
  167727. */
  167728. blkn = 0; /* index of current DCT block within MCU */
  167729. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167730. compptr = cinfo->cur_comp_info[ci];
  167731. /* Don't bother to IDCT an uninteresting component. */
  167732. if (! compptr->component_needed) {
  167733. blkn += compptr->MCU_blocks;
  167734. continue;
  167735. }
  167736. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  167737. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  167738. : compptr->last_col_width;
  167739. output_ptr = output_buf[compptr->component_index] +
  167740. yoffset * compptr->DCT_scaled_size;
  167741. start_col = MCU_col_num * compptr->MCU_sample_width;
  167742. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  167743. if (cinfo->input_iMCU_row < last_iMCU_row ||
  167744. yoffset+yindex < compptr->last_row_height) {
  167745. output_col = start_col;
  167746. for (xindex = 0; xindex < useful_width; xindex++) {
  167747. (*inverse_DCT) (cinfo, compptr,
  167748. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  167749. output_ptr, output_col);
  167750. output_col += compptr->DCT_scaled_size;
  167751. }
  167752. }
  167753. blkn += compptr->MCU_width;
  167754. output_ptr += compptr->DCT_scaled_size;
  167755. }
  167756. }
  167757. }
  167758. /* Completed an MCU row, but perhaps not an iMCU row */
  167759. coef->MCU_ctr = 0;
  167760. }
  167761. /* Completed the iMCU row, advance counters for next one */
  167762. cinfo->output_iMCU_row++;
  167763. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  167764. start_iMCU_row3(cinfo);
  167765. return JPEG_ROW_COMPLETED;
  167766. }
  167767. /* Completed the scan */
  167768. (*cinfo->inputctl->finish_input_pass) (cinfo);
  167769. return JPEG_SCAN_COMPLETED;
  167770. }
  167771. /*
  167772. * Dummy consume-input routine for single-pass operation.
  167773. */
  167774. METHODDEF(int)
  167775. dummy_consume_data (j_decompress_ptr)
  167776. {
  167777. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  167778. }
  167779. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167780. /*
  167781. * Consume input data and store it in the full-image coefficient buffer.
  167782. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  167783. * ie, v_samp_factor block rows for each component in the scan.
  167784. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  167785. */
  167786. METHODDEF(int)
  167787. consume_data (j_decompress_ptr cinfo)
  167788. {
  167789. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  167790. JDIMENSION MCU_col_num; /* index of current MCU within row */
  167791. int blkn, ci, xindex, yindex, yoffset;
  167792. JDIMENSION start_col;
  167793. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  167794. JBLOCKROW buffer_ptr;
  167795. jpeg_component_info *compptr;
  167796. /* Align the virtual buffers for the components used in this scan. */
  167797. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167798. compptr = cinfo->cur_comp_info[ci];
  167799. buffer[ci] = (*cinfo->mem->access_virt_barray)
  167800. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  167801. cinfo->input_iMCU_row * compptr->v_samp_factor,
  167802. (JDIMENSION) compptr->v_samp_factor, TRUE);
  167803. /* Note: entropy decoder expects buffer to be zeroed,
  167804. * but this is handled automatically by the memory manager
  167805. * because we requested a pre-zeroed array.
  167806. */
  167807. }
  167808. /* Loop to process one whole iMCU row */
  167809. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  167810. yoffset++) {
  167811. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  167812. MCU_col_num++) {
  167813. /* Construct list of pointers to DCT blocks belonging to this MCU */
  167814. blkn = 0; /* index of current DCT block within MCU */
  167815. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167816. compptr = cinfo->cur_comp_info[ci];
  167817. start_col = MCU_col_num * compptr->MCU_width;
  167818. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  167819. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  167820. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  167821. coef->MCU_buffer[blkn++] = buffer_ptr++;
  167822. }
  167823. }
  167824. }
  167825. /* Try to fetch the MCU. */
  167826. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  167827. /* Suspension forced; update state counters and exit */
  167828. coef->MCU_vert_offset = yoffset;
  167829. coef->MCU_ctr = MCU_col_num;
  167830. return JPEG_SUSPENDED;
  167831. }
  167832. }
  167833. /* Completed an MCU row, but perhaps not an iMCU row */
  167834. coef->MCU_ctr = 0;
  167835. }
  167836. /* Completed the iMCU row, advance counters for next one */
  167837. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  167838. start_iMCU_row3(cinfo);
  167839. return JPEG_ROW_COMPLETED;
  167840. }
  167841. /* Completed the scan */
  167842. (*cinfo->inputctl->finish_input_pass) (cinfo);
  167843. return JPEG_SCAN_COMPLETED;
  167844. }
  167845. /*
  167846. * Decompress and return some data in the multi-pass case.
  167847. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  167848. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  167849. *
  167850. * NB: output_buf contains a plane for each component in image.
  167851. */
  167852. METHODDEF(int)
  167853. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  167854. {
  167855. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  167856. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  167857. JDIMENSION block_num;
  167858. int ci, block_row, block_rows;
  167859. JBLOCKARRAY buffer;
  167860. JBLOCKROW buffer_ptr;
  167861. JSAMPARRAY output_ptr;
  167862. JDIMENSION output_col;
  167863. jpeg_component_info *compptr;
  167864. inverse_DCT_method_ptr inverse_DCT;
  167865. /* Force some input to be done if we are getting ahead of the input. */
  167866. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  167867. (cinfo->input_scan_number == cinfo->output_scan_number &&
  167868. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  167869. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  167870. return JPEG_SUSPENDED;
  167871. }
  167872. /* OK, output from the virtual arrays. */
  167873. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167874. ci++, compptr++) {
  167875. /* Don't bother to IDCT an uninteresting component. */
  167876. if (! compptr->component_needed)
  167877. continue;
  167878. /* Align the virtual buffer for this component. */
  167879. buffer = (*cinfo->mem->access_virt_barray)
  167880. ((j_common_ptr) cinfo, coef->whole_image[ci],
  167881. cinfo->output_iMCU_row * compptr->v_samp_factor,
  167882. (JDIMENSION) compptr->v_samp_factor, FALSE);
  167883. /* Count non-dummy DCT block rows in this iMCU row. */
  167884. if (cinfo->output_iMCU_row < last_iMCU_row)
  167885. block_rows = compptr->v_samp_factor;
  167886. else {
  167887. /* NB: can't use last_row_height here; it is input-side-dependent! */
  167888. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  167889. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  167890. }
  167891. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  167892. output_ptr = output_buf[ci];
  167893. /* Loop over all DCT blocks to be processed. */
  167894. for (block_row = 0; block_row < block_rows; block_row++) {
  167895. buffer_ptr = buffer[block_row];
  167896. output_col = 0;
  167897. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  167898. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  167899. output_ptr, output_col);
  167900. buffer_ptr++;
  167901. output_col += compptr->DCT_scaled_size;
  167902. }
  167903. output_ptr += compptr->DCT_scaled_size;
  167904. }
  167905. }
  167906. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  167907. return JPEG_ROW_COMPLETED;
  167908. return JPEG_SCAN_COMPLETED;
  167909. }
  167910. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167911. #ifdef BLOCK_SMOOTHING_SUPPORTED
  167912. /*
  167913. * This code applies interblock smoothing as described by section K.8
  167914. * of the JPEG standard: the first 5 AC coefficients are estimated from
  167915. * the DC values of a DCT block and its 8 neighboring blocks.
  167916. * We apply smoothing only for progressive JPEG decoding, and only if
  167917. * the coefficients it can estimate are not yet known to full precision.
  167918. */
  167919. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  167920. #define Q01_POS 1
  167921. #define Q10_POS 8
  167922. #define Q20_POS 16
  167923. #define Q11_POS 9
  167924. #define Q02_POS 2
  167925. /*
  167926. * Determine whether block smoothing is applicable and safe.
  167927. * We also latch the current states of the coef_bits[] entries for the
  167928. * AC coefficients; otherwise, if the input side of the decompressor
  167929. * advances into a new scan, we might think the coefficients are known
  167930. * more accurately than they really are.
  167931. */
  167932. LOCAL(boolean)
  167933. smoothing_ok (j_decompress_ptr cinfo)
  167934. {
  167935. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  167936. boolean smoothing_useful = FALSE;
  167937. int ci, coefi;
  167938. jpeg_component_info *compptr;
  167939. JQUANT_TBL * qtable;
  167940. int * coef_bits;
  167941. int * coef_bits_latch;
  167942. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  167943. return FALSE;
  167944. /* Allocate latch area if not already done */
  167945. if (coef->coef_bits_latch == NULL)
  167946. coef->coef_bits_latch = (int *)
  167947. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167948. cinfo->num_components *
  167949. (SAVED_COEFS * SIZEOF(int)));
  167950. coef_bits_latch = coef->coef_bits_latch;
  167951. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167952. ci++, compptr++) {
  167953. /* All components' quantization values must already be latched. */
  167954. if ((qtable = compptr->quant_table) == NULL)
  167955. return FALSE;
  167956. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  167957. if (qtable->quantval[0] == 0 ||
  167958. qtable->quantval[Q01_POS] == 0 ||
  167959. qtable->quantval[Q10_POS] == 0 ||
  167960. qtable->quantval[Q20_POS] == 0 ||
  167961. qtable->quantval[Q11_POS] == 0 ||
  167962. qtable->quantval[Q02_POS] == 0)
  167963. return FALSE;
  167964. /* DC values must be at least partly known for all components. */
  167965. coef_bits = cinfo->coef_bits[ci];
  167966. if (coef_bits[0] < 0)
  167967. return FALSE;
  167968. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  167969. for (coefi = 1; coefi <= 5; coefi++) {
  167970. coef_bits_latch[coefi] = coef_bits[coefi];
  167971. if (coef_bits[coefi] != 0)
  167972. smoothing_useful = TRUE;
  167973. }
  167974. coef_bits_latch += SAVED_COEFS;
  167975. }
  167976. return smoothing_useful;
  167977. }
  167978. /*
  167979. * Variant of decompress_data for use when doing block smoothing.
  167980. */
  167981. METHODDEF(int)
  167982. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  167983. {
  167984. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  167985. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  167986. JDIMENSION block_num, last_block_column;
  167987. int ci, block_row, block_rows, access_rows;
  167988. JBLOCKARRAY buffer;
  167989. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  167990. JSAMPARRAY output_ptr;
  167991. JDIMENSION output_col;
  167992. jpeg_component_info *compptr;
  167993. inverse_DCT_method_ptr inverse_DCT;
  167994. boolean first_row, last_row;
  167995. JBLOCK workspace;
  167996. int *coef_bits;
  167997. JQUANT_TBL *quanttbl;
  167998. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  167999. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  168000. int Al, pred;
  168001. /* Force some input to be done if we are getting ahead of the input. */
  168002. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  168003. ! cinfo->inputctl->eoi_reached) {
  168004. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  168005. /* If input is working on current scan, we ordinarily want it to
  168006. * have completed the current row. But if input scan is DC,
  168007. * we want it to keep one row ahead so that next block row's DC
  168008. * values are up to date.
  168009. */
  168010. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  168011. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  168012. break;
  168013. }
  168014. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168015. return JPEG_SUSPENDED;
  168016. }
  168017. /* OK, output from the virtual arrays. */
  168018. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168019. ci++, compptr++) {
  168020. /* Don't bother to IDCT an uninteresting component. */
  168021. if (! compptr->component_needed)
  168022. continue;
  168023. /* Count non-dummy DCT block rows in this iMCU row. */
  168024. if (cinfo->output_iMCU_row < last_iMCU_row) {
  168025. block_rows = compptr->v_samp_factor;
  168026. access_rows = block_rows * 2; /* this and next iMCU row */
  168027. last_row = FALSE;
  168028. } else {
  168029. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168030. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168031. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168032. access_rows = block_rows; /* this iMCU row only */
  168033. last_row = TRUE;
  168034. }
  168035. /* Align the virtual buffer for this component. */
  168036. if (cinfo->output_iMCU_row > 0) {
  168037. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  168038. buffer = (*cinfo->mem->access_virt_barray)
  168039. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168040. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  168041. (JDIMENSION) access_rows, FALSE);
  168042. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  168043. first_row = FALSE;
  168044. } else {
  168045. buffer = (*cinfo->mem->access_virt_barray)
  168046. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168047. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  168048. first_row = TRUE;
  168049. }
  168050. /* Fetch component-dependent info */
  168051. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  168052. quanttbl = compptr->quant_table;
  168053. Q00 = quanttbl->quantval[0];
  168054. Q01 = quanttbl->quantval[Q01_POS];
  168055. Q10 = quanttbl->quantval[Q10_POS];
  168056. Q20 = quanttbl->quantval[Q20_POS];
  168057. Q11 = quanttbl->quantval[Q11_POS];
  168058. Q02 = quanttbl->quantval[Q02_POS];
  168059. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168060. output_ptr = output_buf[ci];
  168061. /* Loop over all DCT blocks to be processed. */
  168062. for (block_row = 0; block_row < block_rows; block_row++) {
  168063. buffer_ptr = buffer[block_row];
  168064. if (first_row && block_row == 0)
  168065. prev_block_row = buffer_ptr;
  168066. else
  168067. prev_block_row = buffer[block_row-1];
  168068. if (last_row && block_row == block_rows-1)
  168069. next_block_row = buffer_ptr;
  168070. else
  168071. next_block_row = buffer[block_row+1];
  168072. /* We fetch the surrounding DC values using a sliding-register approach.
  168073. * Initialize all nine here so as to do the right thing on narrow pics.
  168074. */
  168075. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  168076. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  168077. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  168078. output_col = 0;
  168079. last_block_column = compptr->width_in_blocks - 1;
  168080. for (block_num = 0; block_num <= last_block_column; block_num++) {
  168081. /* Fetch current DCT block into workspace so we can modify it. */
  168082. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  168083. /* Update DC values */
  168084. if (block_num < last_block_column) {
  168085. DC3 = (int) prev_block_row[1][0];
  168086. DC6 = (int) buffer_ptr[1][0];
  168087. DC9 = (int) next_block_row[1][0];
  168088. }
  168089. /* Compute coefficient estimates per K.8.
  168090. * An estimate is applied only if coefficient is still zero,
  168091. * and is not known to be fully accurate.
  168092. */
  168093. /* AC01 */
  168094. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  168095. num = 36 * Q00 * (DC4 - DC6);
  168096. if (num >= 0) {
  168097. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  168098. if (Al > 0 && pred >= (1<<Al))
  168099. pred = (1<<Al)-1;
  168100. } else {
  168101. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  168102. if (Al > 0 && pred >= (1<<Al))
  168103. pred = (1<<Al)-1;
  168104. pred = -pred;
  168105. }
  168106. workspace[1] = (JCOEF) pred;
  168107. }
  168108. /* AC10 */
  168109. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  168110. num = 36 * Q00 * (DC2 - DC8);
  168111. if (num >= 0) {
  168112. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  168113. if (Al > 0 && pred >= (1<<Al))
  168114. pred = (1<<Al)-1;
  168115. } else {
  168116. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  168117. if (Al > 0 && pred >= (1<<Al))
  168118. pred = (1<<Al)-1;
  168119. pred = -pred;
  168120. }
  168121. workspace[8] = (JCOEF) pred;
  168122. }
  168123. /* AC20 */
  168124. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  168125. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  168126. if (num >= 0) {
  168127. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  168128. if (Al > 0 && pred >= (1<<Al))
  168129. pred = (1<<Al)-1;
  168130. } else {
  168131. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  168132. if (Al > 0 && pred >= (1<<Al))
  168133. pred = (1<<Al)-1;
  168134. pred = -pred;
  168135. }
  168136. workspace[16] = (JCOEF) pred;
  168137. }
  168138. /* AC11 */
  168139. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  168140. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  168141. if (num >= 0) {
  168142. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  168143. if (Al > 0 && pred >= (1<<Al))
  168144. pred = (1<<Al)-1;
  168145. } else {
  168146. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  168147. if (Al > 0 && pred >= (1<<Al))
  168148. pred = (1<<Al)-1;
  168149. pred = -pred;
  168150. }
  168151. workspace[9] = (JCOEF) pred;
  168152. }
  168153. /* AC02 */
  168154. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  168155. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  168156. if (num >= 0) {
  168157. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  168158. if (Al > 0 && pred >= (1<<Al))
  168159. pred = (1<<Al)-1;
  168160. } else {
  168161. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  168162. if (Al > 0 && pred >= (1<<Al))
  168163. pred = (1<<Al)-1;
  168164. pred = -pred;
  168165. }
  168166. workspace[2] = (JCOEF) pred;
  168167. }
  168168. /* OK, do the IDCT */
  168169. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  168170. output_ptr, output_col);
  168171. /* Advance for next column */
  168172. DC1 = DC2; DC2 = DC3;
  168173. DC4 = DC5; DC5 = DC6;
  168174. DC7 = DC8; DC8 = DC9;
  168175. buffer_ptr++, prev_block_row++, next_block_row++;
  168176. output_col += compptr->DCT_scaled_size;
  168177. }
  168178. output_ptr += compptr->DCT_scaled_size;
  168179. }
  168180. }
  168181. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  168182. return JPEG_ROW_COMPLETED;
  168183. return JPEG_SCAN_COMPLETED;
  168184. }
  168185. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  168186. /*
  168187. * Initialize coefficient buffer controller.
  168188. */
  168189. GLOBAL(void)
  168190. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  168191. {
  168192. my_coef_ptr3 coef;
  168193. coef = (my_coef_ptr3)
  168194. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168195. SIZEOF(my_coef_controller3));
  168196. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  168197. coef->pub.start_input_pass = start_input_pass;
  168198. coef->pub.start_output_pass = start_output_pass;
  168199. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168200. coef->coef_bits_latch = NULL;
  168201. #endif
  168202. /* Create the coefficient buffer. */
  168203. if (need_full_buffer) {
  168204. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168205. /* Allocate a full-image virtual array for each component, */
  168206. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  168207. /* Note we ask for a pre-zeroed array. */
  168208. int ci, access_rows;
  168209. jpeg_component_info *compptr;
  168210. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168211. ci++, compptr++) {
  168212. access_rows = compptr->v_samp_factor;
  168213. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168214. /* If block smoothing could be used, need a bigger window */
  168215. if (cinfo->progressive_mode)
  168216. access_rows *= 3;
  168217. #endif
  168218. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  168219. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  168220. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  168221. (long) compptr->h_samp_factor),
  168222. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  168223. (long) compptr->v_samp_factor),
  168224. (JDIMENSION) access_rows);
  168225. }
  168226. coef->pub.consume_data = consume_data;
  168227. coef->pub.decompress_data = decompress_data;
  168228. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  168229. #else
  168230. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168231. #endif
  168232. } else {
  168233. /* We only need a single-MCU buffer. */
  168234. JBLOCKROW buffer;
  168235. int i;
  168236. buffer = (JBLOCKROW)
  168237. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168238. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  168239. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  168240. coef->MCU_buffer[i] = buffer + i;
  168241. }
  168242. coef->pub.consume_data = dummy_consume_data;
  168243. coef->pub.decompress_data = decompress_onepass;
  168244. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  168245. }
  168246. }
  168247. /*** End of inlined file: jdcoefct.c ***/
  168248. #undef FIX
  168249. /*** Start of inlined file: jdcolor.c ***/
  168250. #define JPEG_INTERNALS
  168251. /* Private subobject */
  168252. typedef struct {
  168253. struct jpeg_color_deconverter pub; /* public fields */
  168254. /* Private state for YCC->RGB conversion */
  168255. int * Cr_r_tab; /* => table for Cr to R conversion */
  168256. int * Cb_b_tab; /* => table for Cb to B conversion */
  168257. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  168258. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  168259. } my_color_deconverter2;
  168260. typedef my_color_deconverter2 * my_cconvert_ptr2;
  168261. /**************** YCbCr -> RGB conversion: most common case **************/
  168262. /*
  168263. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  168264. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  168265. * The conversion equations to be implemented are therefore
  168266. * R = Y + 1.40200 * Cr
  168267. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  168268. * B = Y + 1.77200 * Cb
  168269. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  168270. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  168271. *
  168272. * To avoid floating-point arithmetic, we represent the fractional constants
  168273. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  168274. * the products by 2^16, with appropriate rounding, to get the correct answer.
  168275. * Notice that Y, being an integral input, does not contribute any fraction
  168276. * so it need not participate in the rounding.
  168277. *
  168278. * For even more speed, we avoid doing any multiplications in the inner loop
  168279. * by precalculating the constants times Cb and Cr for all possible values.
  168280. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  168281. * for 12-bit samples it is still acceptable. It's not very reasonable for
  168282. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  168283. * colorspace anyway.
  168284. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  168285. * values for the G calculation are left scaled up, since we must add them
  168286. * together before rounding.
  168287. */
  168288. #define SCALEBITS 16 /* speediest right-shift on some machines */
  168289. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  168290. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  168291. /*
  168292. * Initialize tables for YCC->RGB colorspace conversion.
  168293. */
  168294. LOCAL(void)
  168295. build_ycc_rgb_table (j_decompress_ptr cinfo)
  168296. {
  168297. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  168298. int i;
  168299. INT32 x;
  168300. SHIFT_TEMPS
  168301. cconvert->Cr_r_tab = (int *)
  168302. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168303. (MAXJSAMPLE+1) * SIZEOF(int));
  168304. cconvert->Cb_b_tab = (int *)
  168305. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168306. (MAXJSAMPLE+1) * SIZEOF(int));
  168307. cconvert->Cr_g_tab = (INT32 *)
  168308. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168309. (MAXJSAMPLE+1) * SIZEOF(INT32));
  168310. cconvert->Cb_g_tab = (INT32 *)
  168311. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168312. (MAXJSAMPLE+1) * SIZEOF(INT32));
  168313. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  168314. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  168315. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  168316. /* Cr=>R value is nearest int to 1.40200 * x */
  168317. cconvert->Cr_r_tab[i] = (int)
  168318. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  168319. /* Cb=>B value is nearest int to 1.77200 * x */
  168320. cconvert->Cb_b_tab[i] = (int)
  168321. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  168322. /* Cr=>G value is scaled-up -0.71414 * x */
  168323. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  168324. /* Cb=>G value is scaled-up -0.34414 * x */
  168325. /* We also add in ONE_HALF so that need not do it in inner loop */
  168326. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  168327. }
  168328. }
  168329. /*
  168330. * Convert some rows of samples to the output colorspace.
  168331. *
  168332. * Note that we change from noninterleaved, one-plane-per-component format
  168333. * to interleaved-pixel format. The output buffer is therefore three times
  168334. * as wide as the input buffer.
  168335. * A starting row offset is provided only for the input buffer. The caller
  168336. * can easily adjust the passed output_buf value to accommodate any row
  168337. * offset required on that side.
  168338. */
  168339. METHODDEF(void)
  168340. ycc_rgb_convert (j_decompress_ptr cinfo,
  168341. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168342. JSAMPARRAY output_buf, int num_rows)
  168343. {
  168344. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  168345. register int y, cb, cr;
  168346. register JSAMPROW outptr;
  168347. register JSAMPROW inptr0, inptr1, inptr2;
  168348. register JDIMENSION col;
  168349. JDIMENSION num_cols = cinfo->output_width;
  168350. /* copy these pointers into registers if possible */
  168351. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  168352. register int * Crrtab = cconvert->Cr_r_tab;
  168353. register int * Cbbtab = cconvert->Cb_b_tab;
  168354. register INT32 * Crgtab = cconvert->Cr_g_tab;
  168355. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  168356. SHIFT_TEMPS
  168357. while (--num_rows >= 0) {
  168358. inptr0 = input_buf[0][input_row];
  168359. inptr1 = input_buf[1][input_row];
  168360. inptr2 = input_buf[2][input_row];
  168361. input_row++;
  168362. outptr = *output_buf++;
  168363. for (col = 0; col < num_cols; col++) {
  168364. y = GETJSAMPLE(inptr0[col]);
  168365. cb = GETJSAMPLE(inptr1[col]);
  168366. cr = GETJSAMPLE(inptr2[col]);
  168367. /* Range-limiting is essential due to noise introduced by DCT losses. */
  168368. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  168369. outptr[RGB_GREEN] = range_limit[y +
  168370. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  168371. SCALEBITS))];
  168372. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  168373. outptr += RGB_PIXELSIZE;
  168374. }
  168375. }
  168376. }
  168377. /**************** Cases other than YCbCr -> RGB **************/
  168378. /*
  168379. * Color conversion for no colorspace change: just copy the data,
  168380. * converting from separate-planes to interleaved representation.
  168381. */
  168382. METHODDEF(void)
  168383. null_convert2 (j_decompress_ptr cinfo,
  168384. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168385. JSAMPARRAY output_buf, int num_rows)
  168386. {
  168387. register JSAMPROW inptr, outptr;
  168388. register JDIMENSION count;
  168389. register int num_components = cinfo->num_components;
  168390. JDIMENSION num_cols = cinfo->output_width;
  168391. int ci;
  168392. while (--num_rows >= 0) {
  168393. for (ci = 0; ci < num_components; ci++) {
  168394. inptr = input_buf[ci][input_row];
  168395. outptr = output_buf[0] + ci;
  168396. for (count = num_cols; count > 0; count--) {
  168397. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  168398. outptr += num_components;
  168399. }
  168400. }
  168401. input_row++;
  168402. output_buf++;
  168403. }
  168404. }
  168405. /*
  168406. * Color conversion for grayscale: just copy the data.
  168407. * This also works for YCbCr -> grayscale conversion, in which
  168408. * we just copy the Y (luminance) component and ignore chrominance.
  168409. */
  168410. METHODDEF(void)
  168411. grayscale_convert2 (j_decompress_ptr cinfo,
  168412. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168413. JSAMPARRAY output_buf, int num_rows)
  168414. {
  168415. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  168416. num_rows, cinfo->output_width);
  168417. }
  168418. /*
  168419. * Convert grayscale to RGB: just duplicate the graylevel three times.
  168420. * This is provided to support applications that don't want to cope
  168421. * with grayscale as a separate case.
  168422. */
  168423. METHODDEF(void)
  168424. gray_rgb_convert (j_decompress_ptr cinfo,
  168425. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168426. JSAMPARRAY output_buf, int num_rows)
  168427. {
  168428. register JSAMPROW inptr, outptr;
  168429. register JDIMENSION col;
  168430. JDIMENSION num_cols = cinfo->output_width;
  168431. while (--num_rows >= 0) {
  168432. inptr = input_buf[0][input_row++];
  168433. outptr = *output_buf++;
  168434. for (col = 0; col < num_cols; col++) {
  168435. /* We can dispense with GETJSAMPLE() here */
  168436. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  168437. outptr += RGB_PIXELSIZE;
  168438. }
  168439. }
  168440. }
  168441. /*
  168442. * Adobe-style YCCK->CMYK conversion.
  168443. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  168444. * conversion as above, while passing K (black) unchanged.
  168445. * We assume build_ycc_rgb_table has been called.
  168446. */
  168447. METHODDEF(void)
  168448. ycck_cmyk_convert (j_decompress_ptr cinfo,
  168449. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168450. JSAMPARRAY output_buf, int num_rows)
  168451. {
  168452. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  168453. register int y, cb, cr;
  168454. register JSAMPROW outptr;
  168455. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  168456. register JDIMENSION col;
  168457. JDIMENSION num_cols = cinfo->output_width;
  168458. /* copy these pointers into registers if possible */
  168459. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  168460. register int * Crrtab = cconvert->Cr_r_tab;
  168461. register int * Cbbtab = cconvert->Cb_b_tab;
  168462. register INT32 * Crgtab = cconvert->Cr_g_tab;
  168463. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  168464. SHIFT_TEMPS
  168465. while (--num_rows >= 0) {
  168466. inptr0 = input_buf[0][input_row];
  168467. inptr1 = input_buf[1][input_row];
  168468. inptr2 = input_buf[2][input_row];
  168469. inptr3 = input_buf[3][input_row];
  168470. input_row++;
  168471. outptr = *output_buf++;
  168472. for (col = 0; col < num_cols; col++) {
  168473. y = GETJSAMPLE(inptr0[col]);
  168474. cb = GETJSAMPLE(inptr1[col]);
  168475. cr = GETJSAMPLE(inptr2[col]);
  168476. /* Range-limiting is essential due to noise introduced by DCT losses. */
  168477. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  168478. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  168479. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  168480. SCALEBITS)))];
  168481. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  168482. /* K passes through unchanged */
  168483. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  168484. outptr += 4;
  168485. }
  168486. }
  168487. }
  168488. /*
  168489. * Empty method for start_pass.
  168490. */
  168491. METHODDEF(void)
  168492. start_pass_dcolor (j_decompress_ptr)
  168493. {
  168494. /* no work needed */
  168495. }
  168496. /*
  168497. * Module initialization routine for output colorspace conversion.
  168498. */
  168499. GLOBAL(void)
  168500. jinit_color_deconverter (j_decompress_ptr cinfo)
  168501. {
  168502. my_cconvert_ptr2 cconvert;
  168503. int ci;
  168504. cconvert = (my_cconvert_ptr2)
  168505. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168506. SIZEOF(my_color_deconverter2));
  168507. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  168508. cconvert->pub.start_pass = start_pass_dcolor;
  168509. /* Make sure num_components agrees with jpeg_color_space */
  168510. switch (cinfo->jpeg_color_space) {
  168511. case JCS_GRAYSCALE:
  168512. if (cinfo->num_components != 1)
  168513. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  168514. break;
  168515. case JCS_RGB:
  168516. case JCS_YCbCr:
  168517. if (cinfo->num_components != 3)
  168518. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  168519. break;
  168520. case JCS_CMYK:
  168521. case JCS_YCCK:
  168522. if (cinfo->num_components != 4)
  168523. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  168524. break;
  168525. default: /* JCS_UNKNOWN can be anything */
  168526. if (cinfo->num_components < 1)
  168527. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  168528. break;
  168529. }
  168530. /* Set out_color_components and conversion method based on requested space.
  168531. * Also clear the component_needed flags for any unused components,
  168532. * so that earlier pipeline stages can avoid useless computation.
  168533. */
  168534. switch (cinfo->out_color_space) {
  168535. case JCS_GRAYSCALE:
  168536. cinfo->out_color_components = 1;
  168537. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  168538. cinfo->jpeg_color_space == JCS_YCbCr) {
  168539. cconvert->pub.color_convert = grayscale_convert2;
  168540. /* For color->grayscale conversion, only the Y (0) component is needed */
  168541. for (ci = 1; ci < cinfo->num_components; ci++)
  168542. cinfo->comp_info[ci].component_needed = FALSE;
  168543. } else
  168544. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  168545. break;
  168546. case JCS_RGB:
  168547. cinfo->out_color_components = RGB_PIXELSIZE;
  168548. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  168549. cconvert->pub.color_convert = ycc_rgb_convert;
  168550. build_ycc_rgb_table(cinfo);
  168551. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  168552. cconvert->pub.color_convert = gray_rgb_convert;
  168553. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  168554. cconvert->pub.color_convert = null_convert2;
  168555. } else
  168556. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  168557. break;
  168558. case JCS_CMYK:
  168559. cinfo->out_color_components = 4;
  168560. if (cinfo->jpeg_color_space == JCS_YCCK) {
  168561. cconvert->pub.color_convert = ycck_cmyk_convert;
  168562. build_ycc_rgb_table(cinfo);
  168563. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  168564. cconvert->pub.color_convert = null_convert2;
  168565. } else
  168566. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  168567. break;
  168568. default:
  168569. /* Permit null conversion to same output space */
  168570. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  168571. cinfo->out_color_components = cinfo->num_components;
  168572. cconvert->pub.color_convert = null_convert2;
  168573. } else /* unsupported non-null conversion */
  168574. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  168575. break;
  168576. }
  168577. if (cinfo->quantize_colors)
  168578. cinfo->output_components = 1; /* single colormapped output component */
  168579. else
  168580. cinfo->output_components = cinfo->out_color_components;
  168581. }
  168582. /*** End of inlined file: jdcolor.c ***/
  168583. #undef FIX
  168584. /*** Start of inlined file: jddctmgr.c ***/
  168585. #define JPEG_INTERNALS
  168586. /*
  168587. * The decompressor input side (jdinput.c) saves away the appropriate
  168588. * quantization table for each component at the start of the first scan
  168589. * involving that component. (This is necessary in order to correctly
  168590. * decode files that reuse Q-table slots.)
  168591. * When we are ready to make an output pass, the saved Q-table is converted
  168592. * to a multiplier table that will actually be used by the IDCT routine.
  168593. * The multiplier table contents are IDCT-method-dependent. To support
  168594. * application changes in IDCT method between scans, we can remake the
  168595. * multiplier tables if necessary.
  168596. * In buffered-image mode, the first output pass may occur before any data
  168597. * has been seen for some components, and thus before their Q-tables have
  168598. * been saved away. To handle this case, multiplier tables are preset
  168599. * to zeroes; the result of the IDCT will be a neutral gray level.
  168600. */
  168601. /* Private subobject for this module */
  168602. typedef struct {
  168603. struct jpeg_inverse_dct pub; /* public fields */
  168604. /* This array contains the IDCT method code that each multiplier table
  168605. * is currently set up for, or -1 if it's not yet set up.
  168606. * The actual multiplier tables are pointed to by dct_table in the
  168607. * per-component comp_info structures.
  168608. */
  168609. int cur_method[MAX_COMPONENTS];
  168610. } my_idct_controller;
  168611. typedef my_idct_controller * my_idct_ptr;
  168612. /* Allocated multiplier tables: big enough for any supported variant */
  168613. typedef union {
  168614. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  168615. #ifdef DCT_IFAST_SUPPORTED
  168616. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  168617. #endif
  168618. #ifdef DCT_FLOAT_SUPPORTED
  168619. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  168620. #endif
  168621. } multiplier_table;
  168622. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  168623. * so be sure to compile that code if either ISLOW or SCALING is requested.
  168624. */
  168625. #ifdef DCT_ISLOW_SUPPORTED
  168626. #define PROVIDE_ISLOW_TABLES
  168627. #else
  168628. #ifdef IDCT_SCALING_SUPPORTED
  168629. #define PROVIDE_ISLOW_TABLES
  168630. #endif
  168631. #endif
  168632. /*
  168633. * Prepare for an output pass.
  168634. * Here we select the proper IDCT routine for each component and build
  168635. * a matching multiplier table.
  168636. */
  168637. METHODDEF(void)
  168638. start_pass (j_decompress_ptr cinfo)
  168639. {
  168640. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  168641. int ci, i;
  168642. jpeg_component_info *compptr;
  168643. int method = 0;
  168644. inverse_DCT_method_ptr method_ptr = NULL;
  168645. JQUANT_TBL * qtbl;
  168646. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168647. ci++, compptr++) {
  168648. /* Select the proper IDCT routine for this component's scaling */
  168649. switch (compptr->DCT_scaled_size) {
  168650. #ifdef IDCT_SCALING_SUPPORTED
  168651. case 1:
  168652. method_ptr = jpeg_idct_1x1;
  168653. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  168654. break;
  168655. case 2:
  168656. method_ptr = jpeg_idct_2x2;
  168657. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  168658. break;
  168659. case 4:
  168660. method_ptr = jpeg_idct_4x4;
  168661. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  168662. break;
  168663. #endif
  168664. case DCTSIZE:
  168665. switch (cinfo->dct_method) {
  168666. #ifdef DCT_ISLOW_SUPPORTED
  168667. case JDCT_ISLOW:
  168668. method_ptr = jpeg_idct_islow;
  168669. method = JDCT_ISLOW;
  168670. break;
  168671. #endif
  168672. #ifdef DCT_IFAST_SUPPORTED
  168673. case JDCT_IFAST:
  168674. method_ptr = jpeg_idct_ifast;
  168675. method = JDCT_IFAST;
  168676. break;
  168677. #endif
  168678. #ifdef DCT_FLOAT_SUPPORTED
  168679. case JDCT_FLOAT:
  168680. method_ptr = jpeg_idct_float;
  168681. method = JDCT_FLOAT;
  168682. break;
  168683. #endif
  168684. default:
  168685. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168686. break;
  168687. }
  168688. break;
  168689. default:
  168690. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  168691. break;
  168692. }
  168693. idct->pub.inverse_DCT[ci] = method_ptr;
  168694. /* Create multiplier table from quant table.
  168695. * However, we can skip this if the component is uninteresting
  168696. * or if we already built the table. Also, if no quant table
  168697. * has yet been saved for the component, we leave the
  168698. * multiplier table all-zero; we'll be reading zeroes from the
  168699. * coefficient controller's buffer anyway.
  168700. */
  168701. if (! compptr->component_needed || idct->cur_method[ci] == method)
  168702. continue;
  168703. qtbl = compptr->quant_table;
  168704. if (qtbl == NULL) /* happens if no data yet for component */
  168705. continue;
  168706. idct->cur_method[ci] = method;
  168707. switch (method) {
  168708. #ifdef PROVIDE_ISLOW_TABLES
  168709. case JDCT_ISLOW:
  168710. {
  168711. /* For LL&M IDCT method, multipliers are equal to raw quantization
  168712. * coefficients, but are stored as ints to ensure access efficiency.
  168713. */
  168714. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  168715. for (i = 0; i < DCTSIZE2; i++) {
  168716. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  168717. }
  168718. }
  168719. break;
  168720. #endif
  168721. #ifdef DCT_IFAST_SUPPORTED
  168722. case JDCT_IFAST:
  168723. {
  168724. /* For AA&N IDCT method, multipliers are equal to quantization
  168725. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  168726. * scalefactor[0] = 1
  168727. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  168728. * For integer operation, the multiplier table is to be scaled by
  168729. * IFAST_SCALE_BITS.
  168730. */
  168731. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  168732. #define CONST_BITS 14
  168733. static const INT16 aanscales[DCTSIZE2] = {
  168734. /* precomputed values scaled up by 14 bits */
  168735. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  168736. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  168737. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  168738. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  168739. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  168740. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  168741. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  168742. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  168743. };
  168744. SHIFT_TEMPS
  168745. for (i = 0; i < DCTSIZE2; i++) {
  168746. ifmtbl[i] = (IFAST_MULT_TYPE)
  168747. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  168748. (INT32) aanscales[i]),
  168749. CONST_BITS-IFAST_SCALE_BITS);
  168750. }
  168751. }
  168752. break;
  168753. #endif
  168754. #ifdef DCT_FLOAT_SUPPORTED
  168755. case JDCT_FLOAT:
  168756. {
  168757. /* For float AA&N IDCT method, multipliers are equal to quantization
  168758. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  168759. * scalefactor[0] = 1
  168760. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  168761. */
  168762. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  168763. int row, col;
  168764. static const double aanscalefactor[DCTSIZE] = {
  168765. 1.0, 1.387039845, 1.306562965, 1.175875602,
  168766. 1.0, 0.785694958, 0.541196100, 0.275899379
  168767. };
  168768. i = 0;
  168769. for (row = 0; row < DCTSIZE; row++) {
  168770. for (col = 0; col < DCTSIZE; col++) {
  168771. fmtbl[i] = (FLOAT_MULT_TYPE)
  168772. ((double) qtbl->quantval[i] *
  168773. aanscalefactor[row] * aanscalefactor[col]);
  168774. i++;
  168775. }
  168776. }
  168777. }
  168778. break;
  168779. #endif
  168780. default:
  168781. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168782. break;
  168783. }
  168784. }
  168785. }
  168786. /*
  168787. * Initialize IDCT manager.
  168788. */
  168789. GLOBAL(void)
  168790. jinit_inverse_dct (j_decompress_ptr cinfo)
  168791. {
  168792. my_idct_ptr idct;
  168793. int ci;
  168794. jpeg_component_info *compptr;
  168795. idct = (my_idct_ptr)
  168796. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168797. SIZEOF(my_idct_controller));
  168798. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  168799. idct->pub.start_pass = start_pass;
  168800. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168801. ci++, compptr++) {
  168802. /* Allocate and pre-zero a multiplier table for each component */
  168803. compptr->dct_table =
  168804. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168805. SIZEOF(multiplier_table));
  168806. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  168807. /* Mark multiplier table not yet set up for any method */
  168808. idct->cur_method[ci] = -1;
  168809. }
  168810. }
  168811. /*** End of inlined file: jddctmgr.c ***/
  168812. #undef CONST_BITS
  168813. #undef ASSIGN_STATE
  168814. /*** Start of inlined file: jdhuff.c ***/
  168815. #define JPEG_INTERNALS
  168816. /*** Start of inlined file: jdhuff.h ***/
  168817. /* Short forms of external names for systems with brain-damaged linkers. */
  168818. #ifndef __jdhuff_h__
  168819. #define __jdhuff_h__
  168820. #ifdef NEED_SHORT_EXTERNAL_NAMES
  168821. #define jpeg_make_d_derived_tbl jMkDDerived
  168822. #define jpeg_fill_bit_buffer jFilBitBuf
  168823. #define jpeg_huff_decode jHufDecode
  168824. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  168825. /* Derived data constructed for each Huffman table */
  168826. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  168827. typedef struct {
  168828. /* Basic tables: (element [0] of each array is unused) */
  168829. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  168830. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  168831. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  168832. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  168833. * the smallest code of length k; so given a code of length k, the
  168834. * corresponding symbol is huffval[code + valoffset[k]]
  168835. */
  168836. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  168837. JHUFF_TBL *pub;
  168838. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  168839. * the input data stream. If the next Huffman code is no more
  168840. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  168841. * the corresponding symbol directly from these tables.
  168842. */
  168843. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  168844. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  168845. } d_derived_tbl;
  168846. /* Expand a Huffman table definition into the derived format */
  168847. EXTERN(void) jpeg_make_d_derived_tbl
  168848. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  168849. d_derived_tbl ** pdtbl));
  168850. /*
  168851. * Fetching the next N bits from the input stream is a time-critical operation
  168852. * for the Huffman decoders. We implement it with a combination of inline
  168853. * macros and out-of-line subroutines. Note that N (the number of bits
  168854. * demanded at one time) never exceeds 15 for JPEG use.
  168855. *
  168856. * We read source bytes into get_buffer and dole out bits as needed.
  168857. * If get_buffer already contains enough bits, they are fetched in-line
  168858. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  168859. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  168860. * as full as possible (not just to the number of bits needed; this
  168861. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  168862. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  168863. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  168864. * at least the requested number of bits --- dummy zeroes are inserted if
  168865. * necessary.
  168866. */
  168867. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  168868. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  168869. /* If long is > 32 bits on your machine, and shifting/masking longs is
  168870. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  168871. * appropriately should be a win. Unfortunately we can't define the size
  168872. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  168873. * because not all machines measure sizeof in 8-bit bytes.
  168874. */
  168875. typedef struct { /* Bitreading state saved across MCUs */
  168876. bit_buf_type get_buffer; /* current bit-extraction buffer */
  168877. int bits_left; /* # of unused bits in it */
  168878. } bitread_perm_state;
  168879. typedef struct { /* Bitreading working state within an MCU */
  168880. /* Current data source location */
  168881. /* We need a copy, rather than munging the original, in case of suspension */
  168882. const JOCTET * next_input_byte; /* => next byte to read from source */
  168883. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  168884. /* Bit input buffer --- note these values are kept in register variables,
  168885. * not in this struct, inside the inner loops.
  168886. */
  168887. bit_buf_type get_buffer; /* current bit-extraction buffer */
  168888. int bits_left; /* # of unused bits in it */
  168889. /* Pointer needed by jpeg_fill_bit_buffer. */
  168890. j_decompress_ptr cinfo; /* back link to decompress master record */
  168891. } bitread_working_state;
  168892. /* Macros to declare and load/save bitread local variables. */
  168893. #define BITREAD_STATE_VARS \
  168894. register bit_buf_type get_buffer; \
  168895. register int bits_left; \
  168896. bitread_working_state br_state
  168897. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  168898. br_state.cinfo = cinfop; \
  168899. br_state.next_input_byte = cinfop->src->next_input_byte; \
  168900. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  168901. get_buffer = permstate.get_buffer; \
  168902. bits_left = permstate.bits_left;
  168903. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  168904. cinfop->src->next_input_byte = br_state.next_input_byte; \
  168905. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  168906. permstate.get_buffer = get_buffer; \
  168907. permstate.bits_left = bits_left
  168908. /*
  168909. * These macros provide the in-line portion of bit fetching.
  168910. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  168911. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  168912. * The variables get_buffer and bits_left are assumed to be locals,
  168913. * but the state struct might not be (jpeg_huff_decode needs this).
  168914. * CHECK_BIT_BUFFER(state,n,action);
  168915. * Ensure there are N bits in get_buffer; if suspend, take action.
  168916. * val = GET_BITS(n);
  168917. * Fetch next N bits.
  168918. * val = PEEK_BITS(n);
  168919. * Fetch next N bits without removing them from the buffer.
  168920. * DROP_BITS(n);
  168921. * Discard next N bits.
  168922. * The value N should be a simple variable, not an expression, because it
  168923. * is evaluated multiple times.
  168924. */
  168925. #define CHECK_BIT_BUFFER(state,nbits,action) \
  168926. { if (bits_left < (nbits)) { \
  168927. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  168928. { action; } \
  168929. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  168930. #define GET_BITS(nbits) \
  168931. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  168932. #define PEEK_BITS(nbits) \
  168933. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  168934. #define DROP_BITS(nbits) \
  168935. (bits_left -= (nbits))
  168936. /* Load up the bit buffer to a depth of at least nbits */
  168937. EXTERN(boolean) jpeg_fill_bit_buffer
  168938. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  168939. register int bits_left, int nbits));
  168940. /*
  168941. * Code for extracting next Huffman-coded symbol from input bit stream.
  168942. * Again, this is time-critical and we make the main paths be macros.
  168943. *
  168944. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  168945. * without looping. Usually, more than 95% of the Huffman codes will be 8
  168946. * or fewer bits long. The few overlength codes are handled with a loop,
  168947. * which need not be inline code.
  168948. *
  168949. * Notes about the HUFF_DECODE macro:
  168950. * 1. Near the end of the data segment, we may fail to get enough bits
  168951. * for a lookahead. In that case, we do it the hard way.
  168952. * 2. If the lookahead table contains no entry, the next code must be
  168953. * more than HUFF_LOOKAHEAD bits long.
  168954. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  168955. */
  168956. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  168957. { register int nb, look; \
  168958. if (bits_left < HUFF_LOOKAHEAD) { \
  168959. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  168960. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  168961. if (bits_left < HUFF_LOOKAHEAD) { \
  168962. nb = 1; goto slowlabel; \
  168963. } \
  168964. } \
  168965. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  168966. if ((nb = htbl->look_nbits[look]) != 0) { \
  168967. DROP_BITS(nb); \
  168968. result = htbl->look_sym[look]; \
  168969. } else { \
  168970. nb = HUFF_LOOKAHEAD+1; \
  168971. slowlabel: \
  168972. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  168973. { failaction; } \
  168974. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  168975. } \
  168976. }
  168977. /* Out-of-line case for Huffman code fetching */
  168978. EXTERN(int) jpeg_huff_decode
  168979. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  168980. register int bits_left, d_derived_tbl * htbl, int min_bits));
  168981. #endif
  168982. /*** End of inlined file: jdhuff.h ***/
  168983. /* Declarations shared with jdphuff.c */
  168984. /*
  168985. * Expanded entropy decoder object for Huffman decoding.
  168986. *
  168987. * The savable_state subrecord contains fields that change within an MCU,
  168988. * but must not be updated permanently until we complete the MCU.
  168989. */
  168990. typedef struct {
  168991. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  168992. } savable_state2;
  168993. /* This macro is to work around compilers with missing or broken
  168994. * structure assignment. You'll need to fix this code if you have
  168995. * such a compiler and you change MAX_COMPS_IN_SCAN.
  168996. */
  168997. #ifndef NO_STRUCT_ASSIGN
  168998. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  168999. #else
  169000. #if MAX_COMPS_IN_SCAN == 4
  169001. #define ASSIGN_STATE(dest,src) \
  169002. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  169003. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  169004. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  169005. (dest).last_dc_val[3] = (src).last_dc_val[3])
  169006. #endif
  169007. #endif
  169008. typedef struct {
  169009. struct jpeg_entropy_decoder pub; /* public fields */
  169010. /* These fields are loaded into local variables at start of each MCU.
  169011. * In case of suspension, we exit WITHOUT updating them.
  169012. */
  169013. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  169014. savable_state2 saved; /* Other state at start of MCU */
  169015. /* These fields are NOT loaded into local working state. */
  169016. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  169017. /* Pointers to derived tables (these workspaces have image lifespan) */
  169018. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  169019. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  169020. /* Precalculated info set up by start_pass for use in decode_mcu: */
  169021. /* Pointers to derived tables to be used for each block within an MCU */
  169022. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  169023. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  169024. /* Whether we care about the DC and AC coefficient values for each block */
  169025. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  169026. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  169027. } huff_entropy_decoder2;
  169028. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  169029. /*
  169030. * Initialize for a Huffman-compressed scan.
  169031. */
  169032. METHODDEF(void)
  169033. start_pass_huff_decoder (j_decompress_ptr cinfo)
  169034. {
  169035. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  169036. int ci, blkn, dctbl, actbl;
  169037. jpeg_component_info * compptr;
  169038. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  169039. * This ought to be an error condition, but we make it a warning because
  169040. * there are some baseline files out there with all zeroes in these bytes.
  169041. */
  169042. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  169043. cinfo->Ah != 0 || cinfo->Al != 0)
  169044. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  169045. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  169046. compptr = cinfo->cur_comp_info[ci];
  169047. dctbl = compptr->dc_tbl_no;
  169048. actbl = compptr->ac_tbl_no;
  169049. /* Compute derived values for Huffman tables */
  169050. /* We may do this more than once for a table, but it's not expensive */
  169051. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  169052. & entropy->dc_derived_tbls[dctbl]);
  169053. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  169054. & entropy->ac_derived_tbls[actbl]);
  169055. /* Initialize DC predictions to 0 */
  169056. entropy->saved.last_dc_val[ci] = 0;
  169057. }
  169058. /* Precalculate decoding info for each block in an MCU of this scan */
  169059. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  169060. ci = cinfo->MCU_membership[blkn];
  169061. compptr = cinfo->cur_comp_info[ci];
  169062. /* Precalculate which table to use for each block */
  169063. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  169064. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  169065. /* Decide whether we really care about the coefficient values */
  169066. if (compptr->component_needed) {
  169067. entropy->dc_needed[blkn] = TRUE;
  169068. /* we don't need the ACs if producing a 1/8th-size image */
  169069. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  169070. } else {
  169071. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  169072. }
  169073. }
  169074. /* Initialize bitread state variables */
  169075. entropy->bitstate.bits_left = 0;
  169076. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  169077. entropy->pub.insufficient_data = FALSE;
  169078. /* Initialize restart counter */
  169079. entropy->restarts_to_go = cinfo->restart_interval;
  169080. }
  169081. /*
  169082. * Compute the derived values for a Huffman table.
  169083. * This routine also performs some validation checks on the table.
  169084. *
  169085. * Note this is also used by jdphuff.c.
  169086. */
  169087. GLOBAL(void)
  169088. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  169089. d_derived_tbl ** pdtbl)
  169090. {
  169091. JHUFF_TBL *htbl;
  169092. d_derived_tbl *dtbl;
  169093. int p, i, l, si, numsymbols;
  169094. int lookbits, ctr;
  169095. char huffsize[257];
  169096. unsigned int huffcode[257];
  169097. unsigned int code;
  169098. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  169099. * paralleling the order of the symbols themselves in htbl->huffval[].
  169100. */
  169101. /* Find the input Huffman table */
  169102. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  169103. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  169104. htbl =
  169105. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  169106. if (htbl == NULL)
  169107. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  169108. /* Allocate a workspace if we haven't already done so. */
  169109. if (*pdtbl == NULL)
  169110. *pdtbl = (d_derived_tbl *)
  169111. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169112. SIZEOF(d_derived_tbl));
  169113. dtbl = *pdtbl;
  169114. dtbl->pub = htbl; /* fill in back link */
  169115. /* Figure C.1: make table of Huffman code length for each symbol */
  169116. p = 0;
  169117. for (l = 1; l <= 16; l++) {
  169118. i = (int) htbl->bits[l];
  169119. if (i < 0 || p + i > 256) /* protect against table overrun */
  169120. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169121. while (i--)
  169122. huffsize[p++] = (char) l;
  169123. }
  169124. huffsize[p] = 0;
  169125. numsymbols = p;
  169126. /* Figure C.2: generate the codes themselves */
  169127. /* We also validate that the counts represent a legal Huffman code tree. */
  169128. code = 0;
  169129. si = huffsize[0];
  169130. p = 0;
  169131. while (huffsize[p]) {
  169132. while (((int) huffsize[p]) == si) {
  169133. huffcode[p++] = code;
  169134. code++;
  169135. }
  169136. /* code is now 1 more than the last code used for codelength si; but
  169137. * it must still fit in si bits, since no code is allowed to be all ones.
  169138. */
  169139. if (((INT32) code) >= (((INT32) 1) << si))
  169140. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169141. code <<= 1;
  169142. si++;
  169143. }
  169144. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  169145. p = 0;
  169146. for (l = 1; l <= 16; l++) {
  169147. if (htbl->bits[l]) {
  169148. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  169149. * minus the minimum code of length l
  169150. */
  169151. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  169152. p += htbl->bits[l];
  169153. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  169154. } else {
  169155. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  169156. }
  169157. }
  169158. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  169159. /* Compute lookahead tables to speed up decoding.
  169160. * First we set all the table entries to 0, indicating "too long";
  169161. * then we iterate through the Huffman codes that are short enough and
  169162. * fill in all the entries that correspond to bit sequences starting
  169163. * with that code.
  169164. */
  169165. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  169166. p = 0;
  169167. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  169168. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  169169. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  169170. /* Generate left-justified code followed by all possible bit sequences */
  169171. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  169172. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  169173. dtbl->look_nbits[lookbits] = l;
  169174. dtbl->look_sym[lookbits] = htbl->huffval[p];
  169175. lookbits++;
  169176. }
  169177. }
  169178. }
  169179. /* Validate symbols as being reasonable.
  169180. * For AC tables, we make no check, but accept all byte values 0..255.
  169181. * For DC tables, we require the symbols to be in range 0..15.
  169182. * (Tighter bounds could be applied depending on the data depth and mode,
  169183. * but this is sufficient to ensure safe decoding.)
  169184. */
  169185. if (isDC) {
  169186. for (i = 0; i < numsymbols; i++) {
  169187. int sym = htbl->huffval[i];
  169188. if (sym < 0 || sym > 15)
  169189. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169190. }
  169191. }
  169192. }
  169193. /*
  169194. * Out-of-line code for bit fetching (shared with jdphuff.c).
  169195. * See jdhuff.h for info about usage.
  169196. * Note: current values of get_buffer and bits_left are passed as parameters,
  169197. * but are returned in the corresponding fields of the state struct.
  169198. *
  169199. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  169200. * of get_buffer to be used. (On machines with wider words, an even larger
  169201. * buffer could be used.) However, on some machines 32-bit shifts are
  169202. * quite slow and take time proportional to the number of places shifted.
  169203. * (This is true with most PC compilers, for instance.) In this case it may
  169204. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  169205. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  169206. */
  169207. #ifdef SLOW_SHIFT_32
  169208. #define MIN_GET_BITS 15 /* minimum allowable value */
  169209. #else
  169210. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  169211. #endif
  169212. GLOBAL(boolean)
  169213. jpeg_fill_bit_buffer (bitread_working_state * state,
  169214. register bit_buf_type get_buffer, register int bits_left,
  169215. int nbits)
  169216. /* Load up the bit buffer to a depth of at least nbits */
  169217. {
  169218. /* Copy heavily used state fields into locals (hopefully registers) */
  169219. register const JOCTET * next_input_byte = state->next_input_byte;
  169220. register size_t bytes_in_buffer = state->bytes_in_buffer;
  169221. j_decompress_ptr cinfo = state->cinfo;
  169222. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  169223. /* (It is assumed that no request will be for more than that many bits.) */
  169224. /* We fail to do so only if we hit a marker or are forced to suspend. */
  169225. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  169226. while (bits_left < MIN_GET_BITS) {
  169227. register int c;
  169228. /* Attempt to read a byte */
  169229. if (bytes_in_buffer == 0) {
  169230. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  169231. return FALSE;
  169232. next_input_byte = cinfo->src->next_input_byte;
  169233. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  169234. }
  169235. bytes_in_buffer--;
  169236. c = GETJOCTET(*next_input_byte++);
  169237. /* If it's 0xFF, check and discard stuffed zero byte */
  169238. if (c == 0xFF) {
  169239. /* Loop here to discard any padding FF's on terminating marker,
  169240. * so that we can save a valid unread_marker value. NOTE: we will
  169241. * accept multiple FF's followed by a 0 as meaning a single FF data
  169242. * byte. This data pattern is not valid according to the standard.
  169243. */
  169244. do {
  169245. if (bytes_in_buffer == 0) {
  169246. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  169247. return FALSE;
  169248. next_input_byte = cinfo->src->next_input_byte;
  169249. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  169250. }
  169251. bytes_in_buffer--;
  169252. c = GETJOCTET(*next_input_byte++);
  169253. } while (c == 0xFF);
  169254. if (c == 0) {
  169255. /* Found FF/00, which represents an FF data byte */
  169256. c = 0xFF;
  169257. } else {
  169258. /* Oops, it's actually a marker indicating end of compressed data.
  169259. * Save the marker code for later use.
  169260. * Fine point: it might appear that we should save the marker into
  169261. * bitread working state, not straight into permanent state. But
  169262. * once we have hit a marker, we cannot need to suspend within the
  169263. * current MCU, because we will read no more bytes from the data
  169264. * source. So it is OK to update permanent state right away.
  169265. */
  169266. cinfo->unread_marker = c;
  169267. /* See if we need to insert some fake zero bits. */
  169268. goto no_more_bytes;
  169269. }
  169270. }
  169271. /* OK, load c into get_buffer */
  169272. get_buffer = (get_buffer << 8) | c;
  169273. bits_left += 8;
  169274. } /* end while */
  169275. } else {
  169276. no_more_bytes:
  169277. /* We get here if we've read the marker that terminates the compressed
  169278. * data segment. There should be enough bits in the buffer register
  169279. * to satisfy the request; if so, no problem.
  169280. */
  169281. if (nbits > bits_left) {
  169282. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  169283. * the data stream, so that we can produce some kind of image.
  169284. * We use a nonvolatile flag to ensure that only one warning message
  169285. * appears per data segment.
  169286. */
  169287. if (! cinfo->entropy->insufficient_data) {
  169288. WARNMS(cinfo, JWRN_HIT_MARKER);
  169289. cinfo->entropy->insufficient_data = TRUE;
  169290. }
  169291. /* Fill the buffer with zero bits */
  169292. get_buffer <<= MIN_GET_BITS - bits_left;
  169293. bits_left = MIN_GET_BITS;
  169294. }
  169295. }
  169296. /* Unload the local registers */
  169297. state->next_input_byte = next_input_byte;
  169298. state->bytes_in_buffer = bytes_in_buffer;
  169299. state->get_buffer = get_buffer;
  169300. state->bits_left = bits_left;
  169301. return TRUE;
  169302. }
  169303. /*
  169304. * Out-of-line code for Huffman code decoding.
  169305. * See jdhuff.h for info about usage.
  169306. */
  169307. GLOBAL(int)
  169308. jpeg_huff_decode (bitread_working_state * state,
  169309. register bit_buf_type get_buffer, register int bits_left,
  169310. d_derived_tbl * htbl, int min_bits)
  169311. {
  169312. register int l = min_bits;
  169313. register INT32 code;
  169314. /* HUFF_DECODE has determined that the code is at least min_bits */
  169315. /* bits long, so fetch that many bits in one swoop. */
  169316. CHECK_BIT_BUFFER(*state, l, return -1);
  169317. code = GET_BITS(l);
  169318. /* Collect the rest of the Huffman code one bit at a time. */
  169319. /* This is per Figure F.16 in the JPEG spec. */
  169320. while (code > htbl->maxcode[l]) {
  169321. code <<= 1;
  169322. CHECK_BIT_BUFFER(*state, 1, return -1);
  169323. code |= GET_BITS(1);
  169324. l++;
  169325. }
  169326. /* Unload the local registers */
  169327. state->get_buffer = get_buffer;
  169328. state->bits_left = bits_left;
  169329. /* With garbage input we may reach the sentinel value l = 17. */
  169330. if (l > 16) {
  169331. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  169332. return 0; /* fake a zero as the safest result */
  169333. }
  169334. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  169335. }
  169336. /*
  169337. * Check for a restart marker & resynchronize decoder.
  169338. * Returns FALSE if must suspend.
  169339. */
  169340. LOCAL(boolean)
  169341. process_restart (j_decompress_ptr cinfo)
  169342. {
  169343. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  169344. int ci;
  169345. /* Throw away any unused bits remaining in bit buffer; */
  169346. /* include any full bytes in next_marker's count of discarded bytes */
  169347. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  169348. entropy->bitstate.bits_left = 0;
  169349. /* Advance past the RSTn marker */
  169350. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  169351. return FALSE;
  169352. /* Re-initialize DC predictions to 0 */
  169353. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  169354. entropy->saved.last_dc_val[ci] = 0;
  169355. /* Reset restart counter */
  169356. entropy->restarts_to_go = cinfo->restart_interval;
  169357. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  169358. * against a marker. In that case we will end up treating the next data
  169359. * segment as empty, and we can avoid producing bogus output pixels by
  169360. * leaving the flag set.
  169361. */
  169362. if (cinfo->unread_marker == 0)
  169363. entropy->pub.insufficient_data = FALSE;
  169364. return TRUE;
  169365. }
  169366. /*
  169367. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  169368. * The coefficients are reordered from zigzag order into natural array order,
  169369. * but are not dequantized.
  169370. *
  169371. * The i'th block of the MCU is stored into the block pointed to by
  169372. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  169373. * (Wholesale zeroing is usually a little faster than retail...)
  169374. *
  169375. * Returns FALSE if data source requested suspension. In that case no
  169376. * changes have been made to permanent state. (Exception: some output
  169377. * coefficients may already have been assigned. This is harmless for
  169378. * this module, since we'll just re-assign them on the next call.)
  169379. */
  169380. METHODDEF(boolean)
  169381. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  169382. {
  169383. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  169384. int blkn;
  169385. BITREAD_STATE_VARS;
  169386. savable_state2 state;
  169387. /* Process restart marker if needed; may have to suspend */
  169388. if (cinfo->restart_interval) {
  169389. if (entropy->restarts_to_go == 0)
  169390. if (! process_restart(cinfo))
  169391. return FALSE;
  169392. }
  169393. /* If we've run out of data, just leave the MCU set to zeroes.
  169394. * This way, we return uniform gray for the remainder of the segment.
  169395. */
  169396. if (! entropy->pub.insufficient_data) {
  169397. /* Load up working state */
  169398. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  169399. ASSIGN_STATE(state, entropy->saved);
  169400. /* Outer loop handles each block in the MCU */
  169401. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  169402. JBLOCKROW block = MCU_data[blkn];
  169403. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  169404. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  169405. register int s, k, r;
  169406. /* Decode a single block's worth of coefficients */
  169407. /* Section F.2.2.1: decode the DC coefficient difference */
  169408. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  169409. if (s) {
  169410. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  169411. r = GET_BITS(s);
  169412. s = HUFF_EXTEND(r, s);
  169413. }
  169414. if (entropy->dc_needed[blkn]) {
  169415. /* Convert DC difference to actual value, update last_dc_val */
  169416. int ci = cinfo->MCU_membership[blkn];
  169417. s += state.last_dc_val[ci];
  169418. state.last_dc_val[ci] = s;
  169419. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  169420. (*block)[0] = (JCOEF) s;
  169421. }
  169422. if (entropy->ac_needed[blkn]) {
  169423. /* Section F.2.2.2: decode the AC coefficients */
  169424. /* Since zeroes are skipped, output area must be cleared beforehand */
  169425. for (k = 1; k < DCTSIZE2; k++) {
  169426. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  169427. r = s >> 4;
  169428. s &= 15;
  169429. if (s) {
  169430. k += r;
  169431. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  169432. r = GET_BITS(s);
  169433. s = HUFF_EXTEND(r, s);
  169434. /* Output coefficient in natural (dezigzagged) order.
  169435. * Note: the extra entries in jpeg_natural_order[] will save us
  169436. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  169437. */
  169438. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  169439. } else {
  169440. if (r != 15)
  169441. break;
  169442. k += 15;
  169443. }
  169444. }
  169445. } else {
  169446. /* Section F.2.2.2: decode the AC coefficients */
  169447. /* In this path we just discard the values */
  169448. for (k = 1; k < DCTSIZE2; k++) {
  169449. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  169450. r = s >> 4;
  169451. s &= 15;
  169452. if (s) {
  169453. k += r;
  169454. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  169455. DROP_BITS(s);
  169456. } else {
  169457. if (r != 15)
  169458. break;
  169459. k += 15;
  169460. }
  169461. }
  169462. }
  169463. }
  169464. /* Completed MCU, so update state */
  169465. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  169466. ASSIGN_STATE(entropy->saved, state);
  169467. }
  169468. /* Account for restart interval (no-op if not using restarts) */
  169469. entropy->restarts_to_go--;
  169470. return TRUE;
  169471. }
  169472. /*
  169473. * Module initialization routine for Huffman entropy decoding.
  169474. */
  169475. GLOBAL(void)
  169476. jinit_huff_decoder (j_decompress_ptr cinfo)
  169477. {
  169478. huff_entropy_ptr2 entropy;
  169479. int i;
  169480. entropy = (huff_entropy_ptr2)
  169481. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169482. SIZEOF(huff_entropy_decoder2));
  169483. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  169484. entropy->pub.start_pass = start_pass_huff_decoder;
  169485. entropy->pub.decode_mcu = decode_mcu;
  169486. /* Mark tables unallocated */
  169487. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  169488. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  169489. }
  169490. }
  169491. /*** End of inlined file: jdhuff.c ***/
  169492. /*** Start of inlined file: jdinput.c ***/
  169493. #define JPEG_INTERNALS
  169494. /* Private state */
  169495. typedef struct {
  169496. struct jpeg_input_controller pub; /* public fields */
  169497. boolean inheaders; /* TRUE until first SOS is reached */
  169498. } my_input_controller;
  169499. typedef my_input_controller * my_inputctl_ptr;
  169500. /* Forward declarations */
  169501. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  169502. /*
  169503. * Routines to calculate various quantities related to the size of the image.
  169504. */
  169505. LOCAL(void)
  169506. initial_setup2 (j_decompress_ptr cinfo)
  169507. /* Called once, when first SOS marker is reached */
  169508. {
  169509. int ci;
  169510. jpeg_component_info *compptr;
  169511. /* Make sure image isn't bigger than I can handle */
  169512. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  169513. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  169514. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  169515. /* For now, precision must match compiled-in value... */
  169516. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  169517. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  169518. /* Check that number of components won't exceed internal array sizes */
  169519. if (cinfo->num_components > MAX_COMPONENTS)
  169520. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  169521. MAX_COMPONENTS);
  169522. /* Compute maximum sampling factors; check factor validity */
  169523. cinfo->max_h_samp_factor = 1;
  169524. cinfo->max_v_samp_factor = 1;
  169525. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169526. ci++, compptr++) {
  169527. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  169528. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  169529. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  169530. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  169531. compptr->h_samp_factor);
  169532. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  169533. compptr->v_samp_factor);
  169534. }
  169535. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  169536. * In the full decompressor, this will be overridden by jdmaster.c;
  169537. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  169538. */
  169539. cinfo->min_DCT_scaled_size = DCTSIZE;
  169540. /* Compute dimensions of components */
  169541. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169542. ci++, compptr++) {
  169543. compptr->DCT_scaled_size = DCTSIZE;
  169544. /* Size in DCT blocks */
  169545. compptr->width_in_blocks = (JDIMENSION)
  169546. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  169547. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  169548. compptr->height_in_blocks = (JDIMENSION)
  169549. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  169550. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  169551. /* downsampled_width and downsampled_height will also be overridden by
  169552. * jdmaster.c if we are doing full decompression. The transcoder library
  169553. * doesn't use these values, but the calling application might.
  169554. */
  169555. /* Size in samples */
  169556. compptr->downsampled_width = (JDIMENSION)
  169557. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  169558. (long) cinfo->max_h_samp_factor);
  169559. compptr->downsampled_height = (JDIMENSION)
  169560. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  169561. (long) cinfo->max_v_samp_factor);
  169562. /* Mark component needed, until color conversion says otherwise */
  169563. compptr->component_needed = TRUE;
  169564. /* Mark no quantization table yet saved for component */
  169565. compptr->quant_table = NULL;
  169566. }
  169567. /* Compute number of fully interleaved MCU rows. */
  169568. cinfo->total_iMCU_rows = (JDIMENSION)
  169569. jdiv_round_up((long) cinfo->image_height,
  169570. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  169571. /* Decide whether file contains multiple scans */
  169572. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  169573. cinfo->inputctl->has_multiple_scans = TRUE;
  169574. else
  169575. cinfo->inputctl->has_multiple_scans = FALSE;
  169576. }
  169577. LOCAL(void)
  169578. per_scan_setup2 (j_decompress_ptr cinfo)
  169579. /* Do computations that are needed before processing a JPEG scan */
  169580. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  169581. {
  169582. int ci, mcublks, tmp;
  169583. jpeg_component_info *compptr;
  169584. if (cinfo->comps_in_scan == 1) {
  169585. /* Noninterleaved (single-component) scan */
  169586. compptr = cinfo->cur_comp_info[0];
  169587. /* Overall image size in MCUs */
  169588. cinfo->MCUs_per_row = compptr->width_in_blocks;
  169589. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  169590. /* For noninterleaved scan, always one block per MCU */
  169591. compptr->MCU_width = 1;
  169592. compptr->MCU_height = 1;
  169593. compptr->MCU_blocks = 1;
  169594. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  169595. compptr->last_col_width = 1;
  169596. /* For noninterleaved scans, it is convenient to define last_row_height
  169597. * as the number of block rows present in the last iMCU row.
  169598. */
  169599. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  169600. if (tmp == 0) tmp = compptr->v_samp_factor;
  169601. compptr->last_row_height = tmp;
  169602. /* Prepare array describing MCU composition */
  169603. cinfo->blocks_in_MCU = 1;
  169604. cinfo->MCU_membership[0] = 0;
  169605. } else {
  169606. /* Interleaved (multi-component) scan */
  169607. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  169608. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  169609. MAX_COMPS_IN_SCAN);
  169610. /* Overall image size in MCUs */
  169611. cinfo->MCUs_per_row = (JDIMENSION)
  169612. jdiv_round_up((long) cinfo->image_width,
  169613. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  169614. cinfo->MCU_rows_in_scan = (JDIMENSION)
  169615. jdiv_round_up((long) cinfo->image_height,
  169616. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  169617. cinfo->blocks_in_MCU = 0;
  169618. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  169619. compptr = cinfo->cur_comp_info[ci];
  169620. /* Sampling factors give # of blocks of component in each MCU */
  169621. compptr->MCU_width = compptr->h_samp_factor;
  169622. compptr->MCU_height = compptr->v_samp_factor;
  169623. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  169624. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  169625. /* Figure number of non-dummy blocks in last MCU column & row */
  169626. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  169627. if (tmp == 0) tmp = compptr->MCU_width;
  169628. compptr->last_col_width = tmp;
  169629. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  169630. if (tmp == 0) tmp = compptr->MCU_height;
  169631. compptr->last_row_height = tmp;
  169632. /* Prepare array describing MCU composition */
  169633. mcublks = compptr->MCU_blocks;
  169634. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  169635. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  169636. while (mcublks-- > 0) {
  169637. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  169638. }
  169639. }
  169640. }
  169641. }
  169642. /*
  169643. * Save away a copy of the Q-table referenced by each component present
  169644. * in the current scan, unless already saved during a prior scan.
  169645. *
  169646. * In a multiple-scan JPEG file, the encoder could assign different components
  169647. * the same Q-table slot number, but change table definitions between scans
  169648. * so that each component uses a different Q-table. (The IJG encoder is not
  169649. * currently capable of doing this, but other encoders might.) Since we want
  169650. * to be able to dequantize all the components at the end of the file, this
  169651. * means that we have to save away the table actually used for each component.
  169652. * We do this by copying the table at the start of the first scan containing
  169653. * the component.
  169654. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  169655. * slot between scans of a component using that slot. If the encoder does so
  169656. * anyway, this decoder will simply use the Q-table values that were current
  169657. * at the start of the first scan for the component.
  169658. *
  169659. * The decompressor output side looks only at the saved quant tables,
  169660. * not at the current Q-table slots.
  169661. */
  169662. LOCAL(void)
  169663. latch_quant_tables (j_decompress_ptr cinfo)
  169664. {
  169665. int ci, qtblno;
  169666. jpeg_component_info *compptr;
  169667. JQUANT_TBL * qtbl;
  169668. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  169669. compptr = cinfo->cur_comp_info[ci];
  169670. /* No work if we already saved Q-table for this component */
  169671. if (compptr->quant_table != NULL)
  169672. continue;
  169673. /* Make sure specified quantization table is present */
  169674. qtblno = compptr->quant_tbl_no;
  169675. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  169676. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  169677. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  169678. /* OK, save away the quantization table */
  169679. qtbl = (JQUANT_TBL *)
  169680. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169681. SIZEOF(JQUANT_TBL));
  169682. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  169683. compptr->quant_table = qtbl;
  169684. }
  169685. }
  169686. /*
  169687. * Initialize the input modules to read a scan of compressed data.
  169688. * The first call to this is done by jdmaster.c after initializing
  169689. * the entire decompressor (during jpeg_start_decompress).
  169690. * Subsequent calls come from consume_markers, below.
  169691. */
  169692. METHODDEF(void)
  169693. start_input_pass2 (j_decompress_ptr cinfo)
  169694. {
  169695. per_scan_setup2(cinfo);
  169696. latch_quant_tables(cinfo);
  169697. (*cinfo->entropy->start_pass) (cinfo);
  169698. (*cinfo->coef->start_input_pass) (cinfo);
  169699. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  169700. }
  169701. /*
  169702. * Finish up after inputting a compressed-data scan.
  169703. * This is called by the coefficient controller after it's read all
  169704. * the expected data of the scan.
  169705. */
  169706. METHODDEF(void)
  169707. finish_input_pass (j_decompress_ptr cinfo)
  169708. {
  169709. cinfo->inputctl->consume_input = consume_markers;
  169710. }
  169711. /*
  169712. * Read JPEG markers before, between, or after compressed-data scans.
  169713. * Change state as necessary when a new scan is reached.
  169714. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  169715. *
  169716. * The consume_input method pointer points either here or to the
  169717. * coefficient controller's consume_data routine, depending on whether
  169718. * we are reading a compressed data segment or inter-segment markers.
  169719. */
  169720. METHODDEF(int)
  169721. consume_markers (j_decompress_ptr cinfo)
  169722. {
  169723. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  169724. int val;
  169725. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  169726. return JPEG_REACHED_EOI;
  169727. val = (*cinfo->marker->read_markers) (cinfo);
  169728. switch (val) {
  169729. case JPEG_REACHED_SOS: /* Found SOS */
  169730. if (inputctl->inheaders) { /* 1st SOS */
  169731. initial_setup2(cinfo);
  169732. inputctl->inheaders = FALSE;
  169733. /* Note: start_input_pass must be called by jdmaster.c
  169734. * before any more input can be consumed. jdapimin.c is
  169735. * responsible for enforcing this sequencing.
  169736. */
  169737. } else { /* 2nd or later SOS marker */
  169738. if (! inputctl->pub.has_multiple_scans)
  169739. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  169740. start_input_pass2(cinfo);
  169741. }
  169742. break;
  169743. case JPEG_REACHED_EOI: /* Found EOI */
  169744. inputctl->pub.eoi_reached = TRUE;
  169745. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  169746. if (cinfo->marker->saw_SOF)
  169747. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  169748. } else {
  169749. /* Prevent infinite loop in coef ctlr's decompress_data routine
  169750. * if user set output_scan_number larger than number of scans.
  169751. */
  169752. if (cinfo->output_scan_number > cinfo->input_scan_number)
  169753. cinfo->output_scan_number = cinfo->input_scan_number;
  169754. }
  169755. break;
  169756. case JPEG_SUSPENDED:
  169757. break;
  169758. }
  169759. return val;
  169760. }
  169761. /*
  169762. * Reset state to begin a fresh datastream.
  169763. */
  169764. METHODDEF(void)
  169765. reset_input_controller (j_decompress_ptr cinfo)
  169766. {
  169767. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  169768. inputctl->pub.consume_input = consume_markers;
  169769. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  169770. inputctl->pub.eoi_reached = FALSE;
  169771. inputctl->inheaders = TRUE;
  169772. /* Reset other modules */
  169773. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  169774. (*cinfo->marker->reset_marker_reader) (cinfo);
  169775. /* Reset progression state -- would be cleaner if entropy decoder did this */
  169776. cinfo->coef_bits = NULL;
  169777. }
  169778. /*
  169779. * Initialize the input controller module.
  169780. * This is called only once, when the decompression object is created.
  169781. */
  169782. GLOBAL(void)
  169783. jinit_input_controller (j_decompress_ptr cinfo)
  169784. {
  169785. my_inputctl_ptr inputctl;
  169786. /* Create subobject in permanent pool */
  169787. inputctl = (my_inputctl_ptr)
  169788. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  169789. SIZEOF(my_input_controller));
  169790. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  169791. /* Initialize method pointers */
  169792. inputctl->pub.consume_input = consume_markers;
  169793. inputctl->pub.reset_input_controller = reset_input_controller;
  169794. inputctl->pub.start_input_pass = start_input_pass2;
  169795. inputctl->pub.finish_input_pass = finish_input_pass;
  169796. /* Initialize state: can't use reset_input_controller since we don't
  169797. * want to try to reset other modules yet.
  169798. */
  169799. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  169800. inputctl->pub.eoi_reached = FALSE;
  169801. inputctl->inheaders = TRUE;
  169802. }
  169803. /*** End of inlined file: jdinput.c ***/
  169804. /*** Start of inlined file: jdmainct.c ***/
  169805. #define JPEG_INTERNALS
  169806. /*
  169807. * In the current system design, the main buffer need never be a full-image
  169808. * buffer; any full-height buffers will be found inside the coefficient or
  169809. * postprocessing controllers. Nonetheless, the main controller is not
  169810. * trivial. Its responsibility is to provide context rows for upsampling/
  169811. * rescaling, and doing this in an efficient fashion is a bit tricky.
  169812. *
  169813. * Postprocessor input data is counted in "row groups". A row group
  169814. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  169815. * sample rows of each component. (We require DCT_scaled_size values to be
  169816. * chosen such that these numbers are integers. In practice DCT_scaled_size
  169817. * values will likely be powers of two, so we actually have the stronger
  169818. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  169819. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  169820. * row group (times any additional scale factor that the upsampler is
  169821. * applying).
  169822. *
  169823. * The coefficient controller will deliver data to us one iMCU row at a time;
  169824. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  169825. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  169826. * to one row of MCUs when the image is fully interleaved.) Note that the
  169827. * number of sample rows varies across components, but the number of row
  169828. * groups does not. Some garbage sample rows may be included in the last iMCU
  169829. * row at the bottom of the image.
  169830. *
  169831. * Depending on the vertical scaling algorithm used, the upsampler may need
  169832. * access to the sample row(s) above and below its current input row group.
  169833. * The upsampler is required to set need_context_rows TRUE at global selection
  169834. * time if so. When need_context_rows is FALSE, this controller can simply
  169835. * obtain one iMCU row at a time from the coefficient controller and dole it
  169836. * out as row groups to the postprocessor.
  169837. *
  169838. * When need_context_rows is TRUE, this controller guarantees that the buffer
  169839. * passed to postprocessing contains at least one row group's worth of samples
  169840. * above and below the row group(s) being processed. Note that the context
  169841. * rows "above" the first passed row group appear at negative row offsets in
  169842. * the passed buffer. At the top and bottom of the image, the required
  169843. * context rows are manufactured by duplicating the first or last real sample
  169844. * row; this avoids having special cases in the upsampling inner loops.
  169845. *
  169846. * The amount of context is fixed at one row group just because that's a
  169847. * convenient number for this controller to work with. The existing
  169848. * upsamplers really only need one sample row of context. An upsampler
  169849. * supporting arbitrary output rescaling might wish for more than one row
  169850. * group of context when shrinking the image; tough, we don't handle that.
  169851. * (This is justified by the assumption that downsizing will be handled mostly
  169852. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  169853. * the upsample step needn't be much less than one.)
  169854. *
  169855. * To provide the desired context, we have to retain the last two row groups
  169856. * of one iMCU row while reading in the next iMCU row. (The last row group
  169857. * can't be processed until we have another row group for its below-context,
  169858. * and so we have to save the next-to-last group too for its above-context.)
  169859. * We could do this most simply by copying data around in our buffer, but
  169860. * that'd be very slow. We can avoid copying any data by creating a rather
  169861. * strange pointer structure. Here's how it works. We allocate a workspace
  169862. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  169863. * of row groups per iMCU row). We create two sets of redundant pointers to
  169864. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  169865. * pointer lists look like this:
  169866. * M+1 M-1
  169867. * master pointer --> 0 master pointer --> 0
  169868. * 1 1
  169869. * ... ...
  169870. * M-3 M-3
  169871. * M-2 M
  169872. * M-1 M+1
  169873. * M M-2
  169874. * M+1 M-1
  169875. * 0 0
  169876. * We read alternate iMCU rows using each master pointer; thus the last two
  169877. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  169878. * The pointer lists are set up so that the required context rows appear to
  169879. * be adjacent to the proper places when we pass the pointer lists to the
  169880. * upsampler.
  169881. *
  169882. * The above pictures describe the normal state of the pointer lists.
  169883. * At top and bottom of the image, we diddle the pointer lists to duplicate
  169884. * the first or last sample row as necessary (this is cheaper than copying
  169885. * sample rows around).
  169886. *
  169887. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  169888. * situation each iMCU row provides only one row group so the buffering logic
  169889. * must be different (eg, we must read two iMCU rows before we can emit the
  169890. * first row group). For now, we simply do not support providing context
  169891. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  169892. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  169893. * want it quick and dirty, so a context-free upsampler is sufficient.
  169894. */
  169895. /* Private buffer controller object */
  169896. typedef struct {
  169897. struct jpeg_d_main_controller pub; /* public fields */
  169898. /* Pointer to allocated workspace (M or M+2 row groups). */
  169899. JSAMPARRAY buffer[MAX_COMPONENTS];
  169900. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  169901. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  169902. /* Remaining fields are only used in the context case. */
  169903. /* These are the master pointers to the funny-order pointer lists. */
  169904. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  169905. int whichptr; /* indicates which pointer set is now in use */
  169906. int context_state; /* process_data state machine status */
  169907. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  169908. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  169909. } my_main_controller4;
  169910. typedef my_main_controller4 * my_main_ptr4;
  169911. /* context_state values: */
  169912. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  169913. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  169914. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  169915. /* Forward declarations */
  169916. METHODDEF(void) process_data_simple_main2
  169917. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  169918. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  169919. METHODDEF(void) process_data_context_main
  169920. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  169921. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  169922. #ifdef QUANT_2PASS_SUPPORTED
  169923. METHODDEF(void) process_data_crank_post
  169924. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  169925. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  169926. #endif
  169927. LOCAL(void)
  169928. alloc_funny_pointers (j_decompress_ptr cinfo)
  169929. /* Allocate space for the funny pointer lists.
  169930. * This is done only once, not once per pass.
  169931. */
  169932. {
  169933. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  169934. int ci, rgroup;
  169935. int M = cinfo->min_DCT_scaled_size;
  169936. jpeg_component_info *compptr;
  169937. JSAMPARRAY xbuf;
  169938. /* Get top-level space for component array pointers.
  169939. * We alloc both arrays with one call to save a few cycles.
  169940. */
  169941. main_->xbuffer[0] = (JSAMPIMAGE)
  169942. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169943. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  169944. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  169945. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169946. ci++, compptr++) {
  169947. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  169948. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  169949. /* Get space for pointer lists --- M+4 row groups in each list.
  169950. * We alloc both pointer lists with one call to save a few cycles.
  169951. */
  169952. xbuf = (JSAMPARRAY)
  169953. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169954. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  169955. xbuf += rgroup; /* want one row group at negative offsets */
  169956. main_->xbuffer[0][ci] = xbuf;
  169957. xbuf += rgroup * (M + 4);
  169958. main_->xbuffer[1][ci] = xbuf;
  169959. }
  169960. }
  169961. LOCAL(void)
  169962. make_funny_pointers (j_decompress_ptr cinfo)
  169963. /* Create the funny pointer lists discussed in the comments above.
  169964. * The actual workspace is already allocated (in main->buffer),
  169965. * and the space for the pointer lists is allocated too.
  169966. * This routine just fills in the curiously ordered lists.
  169967. * This will be repeated at the beginning of each pass.
  169968. */
  169969. {
  169970. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  169971. int ci, i, rgroup;
  169972. int M = cinfo->min_DCT_scaled_size;
  169973. jpeg_component_info *compptr;
  169974. JSAMPARRAY buf, xbuf0, xbuf1;
  169975. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169976. ci++, compptr++) {
  169977. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  169978. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  169979. xbuf0 = main_->xbuffer[0][ci];
  169980. xbuf1 = main_->xbuffer[1][ci];
  169981. /* First copy the workspace pointers as-is */
  169982. buf = main_->buffer[ci];
  169983. for (i = 0; i < rgroup * (M + 2); i++) {
  169984. xbuf0[i] = xbuf1[i] = buf[i];
  169985. }
  169986. /* In the second list, put the last four row groups in swapped order */
  169987. for (i = 0; i < rgroup * 2; i++) {
  169988. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  169989. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  169990. }
  169991. /* The wraparound pointers at top and bottom will be filled later
  169992. * (see set_wraparound_pointers, below). Initially we want the "above"
  169993. * pointers to duplicate the first actual data line. This only needs
  169994. * to happen in xbuffer[0].
  169995. */
  169996. for (i = 0; i < rgroup; i++) {
  169997. xbuf0[i - rgroup] = xbuf0[0];
  169998. }
  169999. }
  170000. }
  170001. LOCAL(void)
  170002. set_wraparound_pointers (j_decompress_ptr cinfo)
  170003. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  170004. * This changes the pointer list state from top-of-image to the normal state.
  170005. */
  170006. {
  170007. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170008. int ci, i, rgroup;
  170009. int M = cinfo->min_DCT_scaled_size;
  170010. jpeg_component_info *compptr;
  170011. JSAMPARRAY xbuf0, xbuf1;
  170012. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170013. ci++, compptr++) {
  170014. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170015. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170016. xbuf0 = main_->xbuffer[0][ci];
  170017. xbuf1 = main_->xbuffer[1][ci];
  170018. for (i = 0; i < rgroup; i++) {
  170019. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  170020. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  170021. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  170022. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  170023. }
  170024. }
  170025. }
  170026. LOCAL(void)
  170027. set_bottom_pointers (j_decompress_ptr cinfo)
  170028. /* Change the pointer lists to duplicate the last sample row at the bottom
  170029. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  170030. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  170031. */
  170032. {
  170033. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170034. int ci, i, rgroup, iMCUheight, rows_left;
  170035. jpeg_component_info *compptr;
  170036. JSAMPARRAY xbuf;
  170037. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170038. ci++, compptr++) {
  170039. /* Count sample rows in one iMCU row and in one row group */
  170040. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  170041. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  170042. /* Count nondummy sample rows remaining for this component */
  170043. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  170044. if (rows_left == 0) rows_left = iMCUheight;
  170045. /* Count nondummy row groups. Should get same answer for each component,
  170046. * so we need only do it once.
  170047. */
  170048. if (ci == 0) {
  170049. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  170050. }
  170051. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  170052. * last partial rowgroup and ensures at least one full rowgroup of context.
  170053. */
  170054. xbuf = main_->xbuffer[main_->whichptr][ci];
  170055. for (i = 0; i < rgroup * 2; i++) {
  170056. xbuf[rows_left + i] = xbuf[rows_left-1];
  170057. }
  170058. }
  170059. }
  170060. /*
  170061. * Initialize for a processing pass.
  170062. */
  170063. METHODDEF(void)
  170064. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  170065. {
  170066. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170067. switch (pass_mode) {
  170068. case JBUF_PASS_THRU:
  170069. if (cinfo->upsample->need_context_rows) {
  170070. main_->pub.process_data = process_data_context_main;
  170071. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  170072. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  170073. main_->context_state = CTX_PREPARE_FOR_IMCU;
  170074. main_->iMCU_row_ctr = 0;
  170075. } else {
  170076. /* Simple case with no context needed */
  170077. main_->pub.process_data = process_data_simple_main2;
  170078. }
  170079. main_->buffer_full = FALSE; /* Mark buffer empty */
  170080. main_->rowgroup_ctr = 0;
  170081. break;
  170082. #ifdef QUANT_2PASS_SUPPORTED
  170083. case JBUF_CRANK_DEST:
  170084. /* For last pass of 2-pass quantization, just crank the postprocessor */
  170085. main_->pub.process_data = process_data_crank_post;
  170086. break;
  170087. #endif
  170088. default:
  170089. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170090. break;
  170091. }
  170092. }
  170093. /*
  170094. * Process some data.
  170095. * This handles the simple case where no context is required.
  170096. */
  170097. METHODDEF(void)
  170098. process_data_simple_main2 (j_decompress_ptr cinfo,
  170099. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170100. JDIMENSION out_rows_avail)
  170101. {
  170102. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170103. JDIMENSION rowgroups_avail;
  170104. /* Read input data if we haven't filled the main buffer yet */
  170105. if (! main_->buffer_full) {
  170106. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  170107. return; /* suspension forced, can do nothing more */
  170108. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  170109. }
  170110. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  170111. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  170112. /* Note: at the bottom of the image, we may pass extra garbage row groups
  170113. * to the postprocessor. The postprocessor has to check for bottom
  170114. * of image anyway (at row resolution), so no point in us doing it too.
  170115. */
  170116. /* Feed the postprocessor */
  170117. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  170118. &main_->rowgroup_ctr, rowgroups_avail,
  170119. output_buf, out_row_ctr, out_rows_avail);
  170120. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  170121. if (main_->rowgroup_ctr >= rowgroups_avail) {
  170122. main_->buffer_full = FALSE;
  170123. main_->rowgroup_ctr = 0;
  170124. }
  170125. }
  170126. /*
  170127. * Process some data.
  170128. * This handles the case where context rows must be provided.
  170129. */
  170130. METHODDEF(void)
  170131. process_data_context_main (j_decompress_ptr cinfo,
  170132. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170133. JDIMENSION out_rows_avail)
  170134. {
  170135. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170136. /* Read input data if we haven't filled the main buffer yet */
  170137. if (! main_->buffer_full) {
  170138. if (! (*cinfo->coef->decompress_data) (cinfo,
  170139. main_->xbuffer[main_->whichptr]))
  170140. return; /* suspension forced, can do nothing more */
  170141. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  170142. main_->iMCU_row_ctr++; /* count rows received */
  170143. }
  170144. /* Postprocessor typically will not swallow all the input data it is handed
  170145. * in one call (due to filling the output buffer first). Must be prepared
  170146. * to exit and restart. This switch lets us keep track of how far we got.
  170147. * Note that each case falls through to the next on successful completion.
  170148. */
  170149. switch (main_->context_state) {
  170150. case CTX_POSTPONED_ROW:
  170151. /* Call postprocessor using previously set pointers for postponed row */
  170152. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  170153. &main_->rowgroup_ctr, main_->rowgroups_avail,
  170154. output_buf, out_row_ctr, out_rows_avail);
  170155. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  170156. return; /* Need to suspend */
  170157. main_->context_state = CTX_PREPARE_FOR_IMCU;
  170158. if (*out_row_ctr >= out_rows_avail)
  170159. return; /* Postprocessor exactly filled output buf */
  170160. /*FALLTHROUGH*/
  170161. case CTX_PREPARE_FOR_IMCU:
  170162. /* Prepare to process first M-1 row groups of this iMCU row */
  170163. main_->rowgroup_ctr = 0;
  170164. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  170165. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  170166. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  170167. */
  170168. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  170169. set_bottom_pointers(cinfo);
  170170. main_->context_state = CTX_PROCESS_IMCU;
  170171. /*FALLTHROUGH*/
  170172. case CTX_PROCESS_IMCU:
  170173. /* Call postprocessor using previously set pointers */
  170174. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  170175. &main_->rowgroup_ctr, main_->rowgroups_avail,
  170176. output_buf, out_row_ctr, out_rows_avail);
  170177. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  170178. return; /* Need to suspend */
  170179. /* After the first iMCU, change wraparound pointers to normal state */
  170180. if (main_->iMCU_row_ctr == 1)
  170181. set_wraparound_pointers(cinfo);
  170182. /* Prepare to load new iMCU row using other xbuffer list */
  170183. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  170184. main_->buffer_full = FALSE;
  170185. /* Still need to process last row group of this iMCU row, */
  170186. /* which is saved at index M+1 of the other xbuffer */
  170187. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  170188. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  170189. main_->context_state = CTX_POSTPONED_ROW;
  170190. }
  170191. }
  170192. /*
  170193. * Process some data.
  170194. * Final pass of two-pass quantization: just call the postprocessor.
  170195. * Source data will be the postprocessor controller's internal buffer.
  170196. */
  170197. #ifdef QUANT_2PASS_SUPPORTED
  170198. METHODDEF(void)
  170199. process_data_crank_post (j_decompress_ptr cinfo,
  170200. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170201. JDIMENSION out_rows_avail)
  170202. {
  170203. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  170204. (JDIMENSION *) NULL, (JDIMENSION) 0,
  170205. output_buf, out_row_ctr, out_rows_avail);
  170206. }
  170207. #endif /* QUANT_2PASS_SUPPORTED */
  170208. /*
  170209. * Initialize main buffer controller.
  170210. */
  170211. GLOBAL(void)
  170212. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  170213. {
  170214. my_main_ptr4 main_;
  170215. int ci, rgroup, ngroups;
  170216. jpeg_component_info *compptr;
  170217. main_ = (my_main_ptr4)
  170218. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170219. SIZEOF(my_main_controller4));
  170220. cinfo->main = (struct jpeg_d_main_controller *) main_;
  170221. main_->pub.start_pass = start_pass_main2;
  170222. if (need_full_buffer) /* shouldn't happen */
  170223. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170224. /* Allocate the workspace.
  170225. * ngroups is the number of row groups we need.
  170226. */
  170227. if (cinfo->upsample->need_context_rows) {
  170228. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  170229. ERREXIT(cinfo, JERR_NOTIMPL);
  170230. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  170231. ngroups = cinfo->min_DCT_scaled_size + 2;
  170232. } else {
  170233. ngroups = cinfo->min_DCT_scaled_size;
  170234. }
  170235. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170236. ci++, compptr++) {
  170237. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170238. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170239. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  170240. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170241. compptr->width_in_blocks * compptr->DCT_scaled_size,
  170242. (JDIMENSION) (rgroup * ngroups));
  170243. }
  170244. }
  170245. /*** End of inlined file: jdmainct.c ***/
  170246. /*** Start of inlined file: jdmarker.c ***/
  170247. #define JPEG_INTERNALS
  170248. /* Private state */
  170249. typedef struct {
  170250. struct jpeg_marker_reader pub; /* public fields */
  170251. /* Application-overridable marker processing methods */
  170252. jpeg_marker_parser_method process_COM;
  170253. jpeg_marker_parser_method process_APPn[16];
  170254. /* Limit on marker data length to save for each marker type */
  170255. unsigned int length_limit_COM;
  170256. unsigned int length_limit_APPn[16];
  170257. /* Status of COM/APPn marker saving */
  170258. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  170259. unsigned int bytes_read; /* data bytes read so far in marker */
  170260. /* Note: cur_marker is not linked into marker_list until it's all read. */
  170261. } my_marker_reader;
  170262. typedef my_marker_reader * my_marker_ptr2;
  170263. /*
  170264. * Macros for fetching data from the data source module.
  170265. *
  170266. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  170267. * the current restart point; we update them only when we have reached a
  170268. * suitable place to restart if a suspension occurs.
  170269. */
  170270. /* Declare and initialize local copies of input pointer/count */
  170271. #define INPUT_VARS(cinfo) \
  170272. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  170273. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  170274. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  170275. /* Unload the local copies --- do this only at a restart boundary */
  170276. #define INPUT_SYNC(cinfo) \
  170277. ( datasrc->next_input_byte = next_input_byte, \
  170278. datasrc->bytes_in_buffer = bytes_in_buffer )
  170279. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  170280. #define INPUT_RELOAD(cinfo) \
  170281. ( next_input_byte = datasrc->next_input_byte, \
  170282. bytes_in_buffer = datasrc->bytes_in_buffer )
  170283. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  170284. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  170285. * but we must reload the local copies after a successful fill.
  170286. */
  170287. #define MAKE_BYTE_AVAIL(cinfo,action) \
  170288. if (bytes_in_buffer == 0) { \
  170289. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  170290. { action; } \
  170291. INPUT_RELOAD(cinfo); \
  170292. }
  170293. /* Read a byte into variable V.
  170294. * If must suspend, take the specified action (typically "return FALSE").
  170295. */
  170296. #define INPUT_BYTE(cinfo,V,action) \
  170297. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  170298. bytes_in_buffer--; \
  170299. V = GETJOCTET(*next_input_byte++); )
  170300. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  170301. * V should be declared unsigned int or perhaps INT32.
  170302. */
  170303. #define INPUT_2BYTES(cinfo,V,action) \
  170304. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  170305. bytes_in_buffer--; \
  170306. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  170307. MAKE_BYTE_AVAIL(cinfo,action); \
  170308. bytes_in_buffer--; \
  170309. V += GETJOCTET(*next_input_byte++); )
  170310. /*
  170311. * Routines to process JPEG markers.
  170312. *
  170313. * Entry condition: JPEG marker itself has been read and its code saved
  170314. * in cinfo->unread_marker; input restart point is just after the marker.
  170315. *
  170316. * Exit: if return TRUE, have read and processed any parameters, and have
  170317. * updated the restart point to point after the parameters.
  170318. * If return FALSE, was forced to suspend before reaching end of
  170319. * marker parameters; restart point has not been moved. Same routine
  170320. * will be called again after application supplies more input data.
  170321. *
  170322. * This approach to suspension assumes that all of a marker's parameters
  170323. * can fit into a single input bufferload. This should hold for "normal"
  170324. * markers. Some COM/APPn markers might have large parameter segments
  170325. * that might not fit. If we are simply dropping such a marker, we use
  170326. * skip_input_data to get past it, and thereby put the problem on the
  170327. * source manager's shoulders. If we are saving the marker's contents
  170328. * into memory, we use a slightly different convention: when forced to
  170329. * suspend, the marker processor updates the restart point to the end of
  170330. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  170331. * On resumption, cinfo->unread_marker still contains the marker code,
  170332. * but the data source will point to the next chunk of marker data.
  170333. * The marker processor must retain internal state to deal with this.
  170334. *
  170335. * Note that we don't bother to avoid duplicate trace messages if a
  170336. * suspension occurs within marker parameters. Other side effects
  170337. * require more care.
  170338. */
  170339. LOCAL(boolean)
  170340. get_soi (j_decompress_ptr cinfo)
  170341. /* Process an SOI marker */
  170342. {
  170343. int i;
  170344. TRACEMS(cinfo, 1, JTRC_SOI);
  170345. if (cinfo->marker->saw_SOI)
  170346. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  170347. /* Reset all parameters that are defined to be reset by SOI */
  170348. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  170349. cinfo->arith_dc_L[i] = 0;
  170350. cinfo->arith_dc_U[i] = 1;
  170351. cinfo->arith_ac_K[i] = 5;
  170352. }
  170353. cinfo->restart_interval = 0;
  170354. /* Set initial assumptions for colorspace etc */
  170355. cinfo->jpeg_color_space = JCS_UNKNOWN;
  170356. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  170357. cinfo->saw_JFIF_marker = FALSE;
  170358. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  170359. cinfo->JFIF_minor_version = 1;
  170360. cinfo->density_unit = 0;
  170361. cinfo->X_density = 1;
  170362. cinfo->Y_density = 1;
  170363. cinfo->saw_Adobe_marker = FALSE;
  170364. cinfo->Adobe_transform = 0;
  170365. cinfo->marker->saw_SOI = TRUE;
  170366. return TRUE;
  170367. }
  170368. LOCAL(boolean)
  170369. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  170370. /* Process a SOFn marker */
  170371. {
  170372. INT32 length;
  170373. int c, ci;
  170374. jpeg_component_info * compptr;
  170375. INPUT_VARS(cinfo);
  170376. cinfo->progressive_mode = is_prog;
  170377. cinfo->arith_code = is_arith;
  170378. INPUT_2BYTES(cinfo, length, return FALSE);
  170379. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  170380. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  170381. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  170382. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  170383. length -= 8;
  170384. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  170385. (int) cinfo->image_width, (int) cinfo->image_height,
  170386. cinfo->num_components);
  170387. if (cinfo->marker->saw_SOF)
  170388. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  170389. /* We don't support files in which the image height is initially specified */
  170390. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  170391. /* might as well have a general sanity check. */
  170392. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  170393. || cinfo->num_components <= 0)
  170394. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  170395. if (length != (cinfo->num_components * 3))
  170396. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170397. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  170398. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  170399. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170400. cinfo->num_components * SIZEOF(jpeg_component_info));
  170401. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170402. ci++, compptr++) {
  170403. compptr->component_index = ci;
  170404. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  170405. INPUT_BYTE(cinfo, c, return FALSE);
  170406. compptr->h_samp_factor = (c >> 4) & 15;
  170407. compptr->v_samp_factor = (c ) & 15;
  170408. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  170409. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  170410. compptr->component_id, compptr->h_samp_factor,
  170411. compptr->v_samp_factor, compptr->quant_tbl_no);
  170412. }
  170413. cinfo->marker->saw_SOF = TRUE;
  170414. INPUT_SYNC(cinfo);
  170415. return TRUE;
  170416. }
  170417. LOCAL(boolean)
  170418. get_sos (j_decompress_ptr cinfo)
  170419. /* Process a SOS marker */
  170420. {
  170421. INT32 length;
  170422. int i, ci, n, c, cc;
  170423. jpeg_component_info * compptr;
  170424. INPUT_VARS(cinfo);
  170425. if (! cinfo->marker->saw_SOF)
  170426. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  170427. INPUT_2BYTES(cinfo, length, return FALSE);
  170428. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  170429. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  170430. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  170431. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170432. cinfo->comps_in_scan = n;
  170433. /* Collect the component-spec parameters */
  170434. for (i = 0; i < n; i++) {
  170435. INPUT_BYTE(cinfo, cc, return FALSE);
  170436. INPUT_BYTE(cinfo, c, return FALSE);
  170437. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170438. ci++, compptr++) {
  170439. if (cc == compptr->component_id)
  170440. goto id_found;
  170441. }
  170442. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  170443. id_found:
  170444. cinfo->cur_comp_info[i] = compptr;
  170445. compptr->dc_tbl_no = (c >> 4) & 15;
  170446. compptr->ac_tbl_no = (c ) & 15;
  170447. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  170448. compptr->dc_tbl_no, compptr->ac_tbl_no);
  170449. }
  170450. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  170451. INPUT_BYTE(cinfo, c, return FALSE);
  170452. cinfo->Ss = c;
  170453. INPUT_BYTE(cinfo, c, return FALSE);
  170454. cinfo->Se = c;
  170455. INPUT_BYTE(cinfo, c, return FALSE);
  170456. cinfo->Ah = (c >> 4) & 15;
  170457. cinfo->Al = (c ) & 15;
  170458. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  170459. cinfo->Ah, cinfo->Al);
  170460. /* Prepare to scan data & restart markers */
  170461. cinfo->marker->next_restart_num = 0;
  170462. /* Count another SOS marker */
  170463. cinfo->input_scan_number++;
  170464. INPUT_SYNC(cinfo);
  170465. return TRUE;
  170466. }
  170467. #ifdef D_ARITH_CODING_SUPPORTED
  170468. LOCAL(boolean)
  170469. get_dac (j_decompress_ptr cinfo)
  170470. /* Process a DAC marker */
  170471. {
  170472. INT32 length;
  170473. int index, val;
  170474. INPUT_VARS(cinfo);
  170475. INPUT_2BYTES(cinfo, length, return FALSE);
  170476. length -= 2;
  170477. while (length > 0) {
  170478. INPUT_BYTE(cinfo, index, return FALSE);
  170479. INPUT_BYTE(cinfo, val, return FALSE);
  170480. length -= 2;
  170481. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  170482. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  170483. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  170484. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  170485. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  170486. } else { /* define DC table */
  170487. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  170488. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  170489. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  170490. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  170491. }
  170492. }
  170493. if (length != 0)
  170494. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170495. INPUT_SYNC(cinfo);
  170496. return TRUE;
  170497. }
  170498. #else /* ! D_ARITH_CODING_SUPPORTED */
  170499. #define get_dac(cinfo) skip_variable(cinfo)
  170500. #endif /* D_ARITH_CODING_SUPPORTED */
  170501. LOCAL(boolean)
  170502. get_dht (j_decompress_ptr cinfo)
  170503. /* Process a DHT marker */
  170504. {
  170505. INT32 length;
  170506. UINT8 bits[17];
  170507. UINT8 huffval[256];
  170508. int i, index, count;
  170509. JHUFF_TBL **htblptr;
  170510. INPUT_VARS(cinfo);
  170511. INPUT_2BYTES(cinfo, length, return FALSE);
  170512. length -= 2;
  170513. while (length > 16) {
  170514. INPUT_BYTE(cinfo, index, return FALSE);
  170515. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  170516. bits[0] = 0;
  170517. count = 0;
  170518. for (i = 1; i <= 16; i++) {
  170519. INPUT_BYTE(cinfo, bits[i], return FALSE);
  170520. count += bits[i];
  170521. }
  170522. length -= 1 + 16;
  170523. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  170524. bits[1], bits[2], bits[3], bits[4],
  170525. bits[5], bits[6], bits[7], bits[8]);
  170526. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  170527. bits[9], bits[10], bits[11], bits[12],
  170528. bits[13], bits[14], bits[15], bits[16]);
  170529. /* Here we just do minimal validation of the counts to avoid walking
  170530. * off the end of our table space. jdhuff.c will check more carefully.
  170531. */
  170532. if (count > 256 || ((INT32) count) > length)
  170533. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170534. for (i = 0; i < count; i++)
  170535. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  170536. length -= count;
  170537. if (index & 0x10) { /* AC table definition */
  170538. index -= 0x10;
  170539. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  170540. } else { /* DC table definition */
  170541. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  170542. }
  170543. if (index < 0 || index >= NUM_HUFF_TBLS)
  170544. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  170545. if (*htblptr == NULL)
  170546. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  170547. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  170548. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  170549. }
  170550. if (length != 0)
  170551. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170552. INPUT_SYNC(cinfo);
  170553. return TRUE;
  170554. }
  170555. LOCAL(boolean)
  170556. get_dqt (j_decompress_ptr cinfo)
  170557. /* Process a DQT marker */
  170558. {
  170559. INT32 length;
  170560. int n, i, prec;
  170561. unsigned int tmp;
  170562. JQUANT_TBL *quant_ptr;
  170563. INPUT_VARS(cinfo);
  170564. INPUT_2BYTES(cinfo, length, return FALSE);
  170565. length -= 2;
  170566. while (length > 0) {
  170567. INPUT_BYTE(cinfo, n, return FALSE);
  170568. prec = n >> 4;
  170569. n &= 0x0F;
  170570. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  170571. if (n >= NUM_QUANT_TBLS)
  170572. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  170573. if (cinfo->quant_tbl_ptrs[n] == NULL)
  170574. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  170575. quant_ptr = cinfo->quant_tbl_ptrs[n];
  170576. for (i = 0; i < DCTSIZE2; i++) {
  170577. if (prec)
  170578. INPUT_2BYTES(cinfo, tmp, return FALSE);
  170579. else
  170580. INPUT_BYTE(cinfo, tmp, return FALSE);
  170581. /* We convert the zigzag-order table to natural array order. */
  170582. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  170583. }
  170584. if (cinfo->err->trace_level >= 2) {
  170585. for (i = 0; i < DCTSIZE2; i += 8) {
  170586. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  170587. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  170588. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  170589. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  170590. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  170591. }
  170592. }
  170593. length -= DCTSIZE2+1;
  170594. if (prec) length -= DCTSIZE2;
  170595. }
  170596. if (length != 0)
  170597. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170598. INPUT_SYNC(cinfo);
  170599. return TRUE;
  170600. }
  170601. LOCAL(boolean)
  170602. get_dri (j_decompress_ptr cinfo)
  170603. /* Process a DRI marker */
  170604. {
  170605. INT32 length;
  170606. unsigned int tmp;
  170607. INPUT_VARS(cinfo);
  170608. INPUT_2BYTES(cinfo, length, return FALSE);
  170609. if (length != 4)
  170610. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170611. INPUT_2BYTES(cinfo, tmp, return FALSE);
  170612. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  170613. cinfo->restart_interval = tmp;
  170614. INPUT_SYNC(cinfo);
  170615. return TRUE;
  170616. }
  170617. /*
  170618. * Routines for processing APPn and COM markers.
  170619. * These are either saved in memory or discarded, per application request.
  170620. * APP0 and APP14 are specially checked to see if they are
  170621. * JFIF and Adobe markers, respectively.
  170622. */
  170623. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  170624. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  170625. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  170626. LOCAL(void)
  170627. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  170628. unsigned int datalen, INT32 remaining)
  170629. /* Examine first few bytes from an APP0.
  170630. * Take appropriate action if it is a JFIF marker.
  170631. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  170632. */
  170633. {
  170634. INT32 totallen = (INT32) datalen + remaining;
  170635. if (datalen >= APP0_DATA_LEN &&
  170636. GETJOCTET(data[0]) == 0x4A &&
  170637. GETJOCTET(data[1]) == 0x46 &&
  170638. GETJOCTET(data[2]) == 0x49 &&
  170639. GETJOCTET(data[3]) == 0x46 &&
  170640. GETJOCTET(data[4]) == 0) {
  170641. /* Found JFIF APP0 marker: save info */
  170642. cinfo->saw_JFIF_marker = TRUE;
  170643. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  170644. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  170645. cinfo->density_unit = GETJOCTET(data[7]);
  170646. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  170647. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  170648. /* Check version.
  170649. * Major version must be 1, anything else signals an incompatible change.
  170650. * (We used to treat this as an error, but now it's a nonfatal warning,
  170651. * because some bozo at Hijaak couldn't read the spec.)
  170652. * Minor version should be 0..2, but process anyway if newer.
  170653. */
  170654. if (cinfo->JFIF_major_version != 1)
  170655. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  170656. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  170657. /* Generate trace messages */
  170658. TRACEMS5(cinfo, 1, JTRC_JFIF,
  170659. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  170660. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  170661. /* Validate thumbnail dimensions and issue appropriate messages */
  170662. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  170663. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  170664. GETJOCTET(data[12]), GETJOCTET(data[13]));
  170665. totallen -= APP0_DATA_LEN;
  170666. if (totallen !=
  170667. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  170668. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  170669. } else if (datalen >= 6 &&
  170670. GETJOCTET(data[0]) == 0x4A &&
  170671. GETJOCTET(data[1]) == 0x46 &&
  170672. GETJOCTET(data[2]) == 0x58 &&
  170673. GETJOCTET(data[3]) == 0x58 &&
  170674. GETJOCTET(data[4]) == 0) {
  170675. /* Found JFIF "JFXX" extension APP0 marker */
  170676. /* The library doesn't actually do anything with these,
  170677. * but we try to produce a helpful trace message.
  170678. */
  170679. switch (GETJOCTET(data[5])) {
  170680. case 0x10:
  170681. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  170682. break;
  170683. case 0x11:
  170684. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  170685. break;
  170686. case 0x13:
  170687. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  170688. break;
  170689. default:
  170690. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  170691. GETJOCTET(data[5]), (int) totallen);
  170692. break;
  170693. }
  170694. } else {
  170695. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  170696. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  170697. }
  170698. }
  170699. LOCAL(void)
  170700. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  170701. unsigned int datalen, INT32 remaining)
  170702. /* Examine first few bytes from an APP14.
  170703. * Take appropriate action if it is an Adobe marker.
  170704. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  170705. */
  170706. {
  170707. unsigned int version, flags0, flags1, transform;
  170708. if (datalen >= APP14_DATA_LEN &&
  170709. GETJOCTET(data[0]) == 0x41 &&
  170710. GETJOCTET(data[1]) == 0x64 &&
  170711. GETJOCTET(data[2]) == 0x6F &&
  170712. GETJOCTET(data[3]) == 0x62 &&
  170713. GETJOCTET(data[4]) == 0x65) {
  170714. /* Found Adobe APP14 marker */
  170715. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  170716. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  170717. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  170718. transform = GETJOCTET(data[11]);
  170719. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  170720. cinfo->saw_Adobe_marker = TRUE;
  170721. cinfo->Adobe_transform = (UINT8) transform;
  170722. } else {
  170723. /* Start of APP14 does not match "Adobe", or too short */
  170724. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  170725. }
  170726. }
  170727. METHODDEF(boolean)
  170728. get_interesting_appn (j_decompress_ptr cinfo)
  170729. /* Process an APP0 or APP14 marker without saving it */
  170730. {
  170731. INT32 length;
  170732. JOCTET b[APPN_DATA_LEN];
  170733. unsigned int i, numtoread;
  170734. INPUT_VARS(cinfo);
  170735. INPUT_2BYTES(cinfo, length, return FALSE);
  170736. length -= 2;
  170737. /* get the interesting part of the marker data */
  170738. if (length >= APPN_DATA_LEN)
  170739. numtoread = APPN_DATA_LEN;
  170740. else if (length > 0)
  170741. numtoread = (unsigned int) length;
  170742. else
  170743. numtoread = 0;
  170744. for (i = 0; i < numtoread; i++)
  170745. INPUT_BYTE(cinfo, b[i], return FALSE);
  170746. length -= numtoread;
  170747. /* process it */
  170748. switch (cinfo->unread_marker) {
  170749. case M_APP0:
  170750. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  170751. break;
  170752. case M_APP14:
  170753. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  170754. break;
  170755. default:
  170756. /* can't get here unless jpeg_save_markers chooses wrong processor */
  170757. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  170758. break;
  170759. }
  170760. /* skip any remaining data -- could be lots */
  170761. INPUT_SYNC(cinfo);
  170762. if (length > 0)
  170763. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  170764. return TRUE;
  170765. }
  170766. #ifdef SAVE_MARKERS_SUPPORTED
  170767. METHODDEF(boolean)
  170768. save_marker (j_decompress_ptr cinfo)
  170769. /* Save an APPn or COM marker into the marker list */
  170770. {
  170771. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  170772. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  170773. unsigned int bytes_read, data_length;
  170774. JOCTET FAR * data;
  170775. INT32 length = 0;
  170776. INPUT_VARS(cinfo);
  170777. if (cur_marker == NULL) {
  170778. /* begin reading a marker */
  170779. INPUT_2BYTES(cinfo, length, return FALSE);
  170780. length -= 2;
  170781. if (length >= 0) { /* watch out for bogus length word */
  170782. /* figure out how much we want to save */
  170783. unsigned int limit;
  170784. if (cinfo->unread_marker == (int) M_COM)
  170785. limit = marker->length_limit_COM;
  170786. else
  170787. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  170788. if ((unsigned int) length < limit)
  170789. limit = (unsigned int) length;
  170790. /* allocate and initialize the marker item */
  170791. cur_marker = (jpeg_saved_marker_ptr)
  170792. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170793. SIZEOF(struct jpeg_marker_struct) + limit);
  170794. cur_marker->next = NULL;
  170795. cur_marker->marker = (UINT8) cinfo->unread_marker;
  170796. cur_marker->original_length = (unsigned int) length;
  170797. cur_marker->data_length = limit;
  170798. /* data area is just beyond the jpeg_marker_struct */
  170799. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  170800. marker->cur_marker = cur_marker;
  170801. marker->bytes_read = 0;
  170802. bytes_read = 0;
  170803. data_length = limit;
  170804. } else {
  170805. /* deal with bogus length word */
  170806. bytes_read = data_length = 0;
  170807. data = NULL;
  170808. }
  170809. } else {
  170810. /* resume reading a marker */
  170811. bytes_read = marker->bytes_read;
  170812. data_length = cur_marker->data_length;
  170813. data = cur_marker->data + bytes_read;
  170814. }
  170815. while (bytes_read < data_length) {
  170816. INPUT_SYNC(cinfo); /* move the restart point to here */
  170817. marker->bytes_read = bytes_read;
  170818. /* If there's not at least one byte in buffer, suspend */
  170819. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  170820. /* Copy bytes with reasonable rapidity */
  170821. while (bytes_read < data_length && bytes_in_buffer > 0) {
  170822. *data++ = *next_input_byte++;
  170823. bytes_in_buffer--;
  170824. bytes_read++;
  170825. }
  170826. }
  170827. /* Done reading what we want to read */
  170828. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  170829. /* Add new marker to end of list */
  170830. if (cinfo->marker_list == NULL) {
  170831. cinfo->marker_list = cur_marker;
  170832. } else {
  170833. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  170834. while (prev->next != NULL)
  170835. prev = prev->next;
  170836. prev->next = cur_marker;
  170837. }
  170838. /* Reset pointer & calc remaining data length */
  170839. data = cur_marker->data;
  170840. length = cur_marker->original_length - data_length;
  170841. }
  170842. /* Reset to initial state for next marker */
  170843. marker->cur_marker = NULL;
  170844. /* Process the marker if interesting; else just make a generic trace msg */
  170845. switch (cinfo->unread_marker) {
  170846. case M_APP0:
  170847. examine_app0(cinfo, data, data_length, length);
  170848. break;
  170849. case M_APP14:
  170850. examine_app14(cinfo, data, data_length, length);
  170851. break;
  170852. default:
  170853. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  170854. (int) (data_length + length));
  170855. break;
  170856. }
  170857. /* skip any remaining data -- could be lots */
  170858. INPUT_SYNC(cinfo); /* do before skip_input_data */
  170859. if (length > 0)
  170860. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  170861. return TRUE;
  170862. }
  170863. #endif /* SAVE_MARKERS_SUPPORTED */
  170864. METHODDEF(boolean)
  170865. skip_variable (j_decompress_ptr cinfo)
  170866. /* Skip over an unknown or uninteresting variable-length marker */
  170867. {
  170868. INT32 length;
  170869. INPUT_VARS(cinfo);
  170870. INPUT_2BYTES(cinfo, length, return FALSE);
  170871. length -= 2;
  170872. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  170873. INPUT_SYNC(cinfo); /* do before skip_input_data */
  170874. if (length > 0)
  170875. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  170876. return TRUE;
  170877. }
  170878. /*
  170879. * Find the next JPEG marker, save it in cinfo->unread_marker.
  170880. * Returns FALSE if had to suspend before reaching a marker;
  170881. * in that case cinfo->unread_marker is unchanged.
  170882. *
  170883. * Note that the result might not be a valid marker code,
  170884. * but it will never be 0 or FF.
  170885. */
  170886. LOCAL(boolean)
  170887. next_marker (j_decompress_ptr cinfo)
  170888. {
  170889. int c;
  170890. INPUT_VARS(cinfo);
  170891. for (;;) {
  170892. INPUT_BYTE(cinfo, c, return FALSE);
  170893. /* Skip any non-FF bytes.
  170894. * This may look a bit inefficient, but it will not occur in a valid file.
  170895. * We sync after each discarded byte so that a suspending data source
  170896. * can discard the byte from its buffer.
  170897. */
  170898. while (c != 0xFF) {
  170899. cinfo->marker->discarded_bytes++;
  170900. INPUT_SYNC(cinfo);
  170901. INPUT_BYTE(cinfo, c, return FALSE);
  170902. }
  170903. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  170904. * pad bytes, so don't count them in discarded_bytes. We assume there
  170905. * will not be so many consecutive FF bytes as to overflow a suspending
  170906. * data source's input buffer.
  170907. */
  170908. do {
  170909. INPUT_BYTE(cinfo, c, return FALSE);
  170910. } while (c == 0xFF);
  170911. if (c != 0)
  170912. break; /* found a valid marker, exit loop */
  170913. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  170914. * Discard it and loop back to try again.
  170915. */
  170916. cinfo->marker->discarded_bytes += 2;
  170917. INPUT_SYNC(cinfo);
  170918. }
  170919. if (cinfo->marker->discarded_bytes != 0) {
  170920. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  170921. cinfo->marker->discarded_bytes = 0;
  170922. }
  170923. cinfo->unread_marker = c;
  170924. INPUT_SYNC(cinfo);
  170925. return TRUE;
  170926. }
  170927. LOCAL(boolean)
  170928. first_marker (j_decompress_ptr cinfo)
  170929. /* Like next_marker, but used to obtain the initial SOI marker. */
  170930. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  170931. * we might well scan an entire input file before realizing it ain't JPEG.
  170932. * If an application wants to process non-JFIF files, it must seek to the
  170933. * SOI before calling the JPEG library.
  170934. */
  170935. {
  170936. int c, c2;
  170937. INPUT_VARS(cinfo);
  170938. INPUT_BYTE(cinfo, c, return FALSE);
  170939. INPUT_BYTE(cinfo, c2, return FALSE);
  170940. if (c != 0xFF || c2 != (int) M_SOI)
  170941. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  170942. cinfo->unread_marker = c2;
  170943. INPUT_SYNC(cinfo);
  170944. return TRUE;
  170945. }
  170946. /*
  170947. * Read markers until SOS or EOI.
  170948. *
  170949. * Returns same codes as are defined for jpeg_consume_input:
  170950. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  170951. */
  170952. METHODDEF(int)
  170953. read_markers (j_decompress_ptr cinfo)
  170954. {
  170955. /* Outer loop repeats once for each marker. */
  170956. for (;;) {
  170957. /* Collect the marker proper, unless we already did. */
  170958. /* NB: first_marker() enforces the requirement that SOI appear first. */
  170959. if (cinfo->unread_marker == 0) {
  170960. if (! cinfo->marker->saw_SOI) {
  170961. if (! first_marker(cinfo))
  170962. return JPEG_SUSPENDED;
  170963. } else {
  170964. if (! next_marker(cinfo))
  170965. return JPEG_SUSPENDED;
  170966. }
  170967. }
  170968. /* At this point cinfo->unread_marker contains the marker code and the
  170969. * input point is just past the marker proper, but before any parameters.
  170970. * A suspension will cause us to return with this state still true.
  170971. */
  170972. switch (cinfo->unread_marker) {
  170973. case M_SOI:
  170974. if (! get_soi(cinfo))
  170975. return JPEG_SUSPENDED;
  170976. break;
  170977. case M_SOF0: /* Baseline */
  170978. case M_SOF1: /* Extended sequential, Huffman */
  170979. if (! get_sof(cinfo, FALSE, FALSE))
  170980. return JPEG_SUSPENDED;
  170981. break;
  170982. case M_SOF2: /* Progressive, Huffman */
  170983. if (! get_sof(cinfo, TRUE, FALSE))
  170984. return JPEG_SUSPENDED;
  170985. break;
  170986. case M_SOF9: /* Extended sequential, arithmetic */
  170987. if (! get_sof(cinfo, FALSE, TRUE))
  170988. return JPEG_SUSPENDED;
  170989. break;
  170990. case M_SOF10: /* Progressive, arithmetic */
  170991. if (! get_sof(cinfo, TRUE, TRUE))
  170992. return JPEG_SUSPENDED;
  170993. break;
  170994. /* Currently unsupported SOFn types */
  170995. case M_SOF3: /* Lossless, Huffman */
  170996. case M_SOF5: /* Differential sequential, Huffman */
  170997. case M_SOF6: /* Differential progressive, Huffman */
  170998. case M_SOF7: /* Differential lossless, Huffman */
  170999. case M_JPG: /* Reserved for JPEG extensions */
  171000. case M_SOF11: /* Lossless, arithmetic */
  171001. case M_SOF13: /* Differential sequential, arithmetic */
  171002. case M_SOF14: /* Differential progressive, arithmetic */
  171003. case M_SOF15: /* Differential lossless, arithmetic */
  171004. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  171005. break;
  171006. case M_SOS:
  171007. if (! get_sos(cinfo))
  171008. return JPEG_SUSPENDED;
  171009. cinfo->unread_marker = 0; /* processed the marker */
  171010. return JPEG_REACHED_SOS;
  171011. case M_EOI:
  171012. TRACEMS(cinfo, 1, JTRC_EOI);
  171013. cinfo->unread_marker = 0; /* processed the marker */
  171014. return JPEG_REACHED_EOI;
  171015. case M_DAC:
  171016. if (! get_dac(cinfo))
  171017. return JPEG_SUSPENDED;
  171018. break;
  171019. case M_DHT:
  171020. if (! get_dht(cinfo))
  171021. return JPEG_SUSPENDED;
  171022. break;
  171023. case M_DQT:
  171024. if (! get_dqt(cinfo))
  171025. return JPEG_SUSPENDED;
  171026. break;
  171027. case M_DRI:
  171028. if (! get_dri(cinfo))
  171029. return JPEG_SUSPENDED;
  171030. break;
  171031. case M_APP0:
  171032. case M_APP1:
  171033. case M_APP2:
  171034. case M_APP3:
  171035. case M_APP4:
  171036. case M_APP5:
  171037. case M_APP6:
  171038. case M_APP7:
  171039. case M_APP8:
  171040. case M_APP9:
  171041. case M_APP10:
  171042. case M_APP11:
  171043. case M_APP12:
  171044. case M_APP13:
  171045. case M_APP14:
  171046. case M_APP15:
  171047. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  171048. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  171049. return JPEG_SUSPENDED;
  171050. break;
  171051. case M_COM:
  171052. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  171053. return JPEG_SUSPENDED;
  171054. break;
  171055. case M_RST0: /* these are all parameterless */
  171056. case M_RST1:
  171057. case M_RST2:
  171058. case M_RST3:
  171059. case M_RST4:
  171060. case M_RST5:
  171061. case M_RST6:
  171062. case M_RST7:
  171063. case M_TEM:
  171064. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  171065. break;
  171066. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  171067. if (! skip_variable(cinfo))
  171068. return JPEG_SUSPENDED;
  171069. break;
  171070. default: /* must be DHP, EXP, JPGn, or RESn */
  171071. /* For now, we treat the reserved markers as fatal errors since they are
  171072. * likely to be used to signal incompatible JPEG Part 3 extensions.
  171073. * Once the JPEG 3 version-number marker is well defined, this code
  171074. * ought to change!
  171075. */
  171076. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171077. break;
  171078. }
  171079. /* Successfully processed marker, so reset state variable */
  171080. cinfo->unread_marker = 0;
  171081. } /* end loop */
  171082. }
  171083. /*
  171084. * Read a restart marker, which is expected to appear next in the datastream;
  171085. * if the marker is not there, take appropriate recovery action.
  171086. * Returns FALSE if suspension is required.
  171087. *
  171088. * This is called by the entropy decoder after it has read an appropriate
  171089. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  171090. * has already read a marker from the data source. Under normal conditions
  171091. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  171092. * it holds a marker which the decoder will be unable to read past.
  171093. */
  171094. METHODDEF(boolean)
  171095. read_restart_marker (j_decompress_ptr cinfo)
  171096. {
  171097. /* Obtain a marker unless we already did. */
  171098. /* Note that next_marker will complain if it skips any data. */
  171099. if (cinfo->unread_marker == 0) {
  171100. if (! next_marker(cinfo))
  171101. return FALSE;
  171102. }
  171103. if (cinfo->unread_marker ==
  171104. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  171105. /* Normal case --- swallow the marker and let entropy decoder continue */
  171106. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  171107. cinfo->unread_marker = 0;
  171108. } else {
  171109. /* Uh-oh, the restart markers have been messed up. */
  171110. /* Let the data source manager determine how to resync. */
  171111. if (! (*cinfo->src->resync_to_restart) (cinfo,
  171112. cinfo->marker->next_restart_num))
  171113. return FALSE;
  171114. }
  171115. /* Update next-restart state */
  171116. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  171117. return TRUE;
  171118. }
  171119. /*
  171120. * This is the default resync_to_restart method for data source managers
  171121. * to use if they don't have any better approach. Some data source managers
  171122. * may be able to back up, or may have additional knowledge about the data
  171123. * which permits a more intelligent recovery strategy; such managers would
  171124. * presumably supply their own resync method.
  171125. *
  171126. * read_restart_marker calls resync_to_restart if it finds a marker other than
  171127. * the restart marker it was expecting. (This code is *not* used unless
  171128. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  171129. * the marker code actually found (might be anything, except 0 or FF).
  171130. * The desired restart marker number (0..7) is passed as a parameter.
  171131. * This routine is supposed to apply whatever error recovery strategy seems
  171132. * appropriate in order to position the input stream to the next data segment.
  171133. * Note that cinfo->unread_marker is treated as a marker appearing before
  171134. * the current data-source input point; usually it should be reset to zero
  171135. * before returning.
  171136. * Returns FALSE if suspension is required.
  171137. *
  171138. * This implementation is substantially constrained by wanting to treat the
  171139. * input as a data stream; this means we can't back up. Therefore, we have
  171140. * only the following actions to work with:
  171141. * 1. Simply discard the marker and let the entropy decoder resume at next
  171142. * byte of file.
  171143. * 2. Read forward until we find another marker, discarding intervening
  171144. * data. (In theory we could look ahead within the current bufferload,
  171145. * without having to discard data if we don't find the desired marker.
  171146. * This idea is not implemented here, in part because it makes behavior
  171147. * dependent on buffer size and chance buffer-boundary positions.)
  171148. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  171149. * This will cause the entropy decoder to process an empty data segment,
  171150. * inserting dummy zeroes, and then we will reprocess the marker.
  171151. *
  171152. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  171153. * appropriate if the found marker is a future restart marker (indicating
  171154. * that we have missed the desired restart marker, probably because it got
  171155. * corrupted).
  171156. * We apply #2 or #3 if the found marker is a restart marker no more than
  171157. * two counts behind or ahead of the expected one. We also apply #2 if the
  171158. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  171159. * If the found marker is a restart marker more than 2 counts away, we do #1
  171160. * (too much risk that the marker is erroneous; with luck we will be able to
  171161. * resync at some future point).
  171162. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  171163. * overrunning the end of a scan. An implementation limited to single-scan
  171164. * files might find it better to apply #2 for markers other than EOI, since
  171165. * any other marker would have to be bogus data in that case.
  171166. */
  171167. GLOBAL(boolean)
  171168. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  171169. {
  171170. int marker = cinfo->unread_marker;
  171171. int action = 1;
  171172. /* Always put up a warning. */
  171173. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  171174. /* Outer loop handles repeated decision after scanning forward. */
  171175. for (;;) {
  171176. if (marker < (int) M_SOF0)
  171177. action = 2; /* invalid marker */
  171178. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  171179. action = 3; /* valid non-restart marker */
  171180. else {
  171181. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  171182. marker == ((int) M_RST0 + ((desired+2) & 7)))
  171183. action = 3; /* one of the next two expected restarts */
  171184. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  171185. marker == ((int) M_RST0 + ((desired-2) & 7)))
  171186. action = 2; /* a prior restart, so advance */
  171187. else
  171188. action = 1; /* desired restart or too far away */
  171189. }
  171190. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  171191. switch (action) {
  171192. case 1:
  171193. /* Discard marker and let entropy decoder resume processing. */
  171194. cinfo->unread_marker = 0;
  171195. return TRUE;
  171196. case 2:
  171197. /* Scan to the next marker, and repeat the decision loop. */
  171198. if (! next_marker(cinfo))
  171199. return FALSE;
  171200. marker = cinfo->unread_marker;
  171201. break;
  171202. case 3:
  171203. /* Return without advancing past this marker. */
  171204. /* Entropy decoder will be forced to process an empty segment. */
  171205. return TRUE;
  171206. }
  171207. } /* end loop */
  171208. }
  171209. /*
  171210. * Reset marker processing state to begin a fresh datastream.
  171211. */
  171212. METHODDEF(void)
  171213. reset_marker_reader (j_decompress_ptr cinfo)
  171214. {
  171215. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171216. cinfo->comp_info = NULL; /* until allocated by get_sof */
  171217. cinfo->input_scan_number = 0; /* no SOS seen yet */
  171218. cinfo->unread_marker = 0; /* no pending marker */
  171219. marker->pub.saw_SOI = FALSE; /* set internal state too */
  171220. marker->pub.saw_SOF = FALSE;
  171221. marker->pub.discarded_bytes = 0;
  171222. marker->cur_marker = NULL;
  171223. }
  171224. /*
  171225. * Initialize the marker reader module.
  171226. * This is called only once, when the decompression object is created.
  171227. */
  171228. GLOBAL(void)
  171229. jinit_marker_reader (j_decompress_ptr cinfo)
  171230. {
  171231. my_marker_ptr2 marker;
  171232. int i;
  171233. /* Create subobject in permanent pool */
  171234. marker = (my_marker_ptr2)
  171235. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  171236. SIZEOF(my_marker_reader));
  171237. cinfo->marker = (struct jpeg_marker_reader *) marker;
  171238. /* Initialize public method pointers */
  171239. marker->pub.reset_marker_reader = reset_marker_reader;
  171240. marker->pub.read_markers = read_markers;
  171241. marker->pub.read_restart_marker = read_restart_marker;
  171242. /* Initialize COM/APPn processing.
  171243. * By default, we examine and then discard APP0 and APP14,
  171244. * but simply discard COM and all other APPn.
  171245. */
  171246. marker->process_COM = skip_variable;
  171247. marker->length_limit_COM = 0;
  171248. for (i = 0; i < 16; i++) {
  171249. marker->process_APPn[i] = skip_variable;
  171250. marker->length_limit_APPn[i] = 0;
  171251. }
  171252. marker->process_APPn[0] = get_interesting_appn;
  171253. marker->process_APPn[14] = get_interesting_appn;
  171254. /* Reset marker processing state */
  171255. reset_marker_reader(cinfo);
  171256. }
  171257. /*
  171258. * Control saving of COM and APPn markers into marker_list.
  171259. */
  171260. #ifdef SAVE_MARKERS_SUPPORTED
  171261. GLOBAL(void)
  171262. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  171263. unsigned int length_limit)
  171264. {
  171265. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171266. long maxlength;
  171267. jpeg_marker_parser_method processor;
  171268. /* Length limit mustn't be larger than what we can allocate
  171269. * (should only be a concern in a 16-bit environment).
  171270. */
  171271. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  171272. if (((long) length_limit) > maxlength)
  171273. length_limit = (unsigned int) maxlength;
  171274. /* Choose processor routine to use.
  171275. * APP0/APP14 have special requirements.
  171276. */
  171277. if (length_limit) {
  171278. processor = save_marker;
  171279. /* If saving APP0/APP14, save at least enough for our internal use. */
  171280. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  171281. length_limit = APP0_DATA_LEN;
  171282. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  171283. length_limit = APP14_DATA_LEN;
  171284. } else {
  171285. processor = skip_variable;
  171286. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  171287. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  171288. processor = get_interesting_appn;
  171289. }
  171290. if (marker_code == (int) M_COM) {
  171291. marker->process_COM = processor;
  171292. marker->length_limit_COM = length_limit;
  171293. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  171294. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  171295. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  171296. } else
  171297. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  171298. }
  171299. #endif /* SAVE_MARKERS_SUPPORTED */
  171300. /*
  171301. * Install a special processing method for COM or APPn markers.
  171302. */
  171303. GLOBAL(void)
  171304. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  171305. jpeg_marker_parser_method routine)
  171306. {
  171307. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171308. if (marker_code == (int) M_COM)
  171309. marker->process_COM = routine;
  171310. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  171311. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  171312. else
  171313. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  171314. }
  171315. /*** End of inlined file: jdmarker.c ***/
  171316. /*** Start of inlined file: jdmaster.c ***/
  171317. #define JPEG_INTERNALS
  171318. /* Private state */
  171319. typedef struct {
  171320. struct jpeg_decomp_master pub; /* public fields */
  171321. int pass_number; /* # of passes completed */
  171322. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  171323. /* Saved references to initialized quantizer modules,
  171324. * in case we need to switch modes.
  171325. */
  171326. struct jpeg_color_quantizer * quantizer_1pass;
  171327. struct jpeg_color_quantizer * quantizer_2pass;
  171328. } my_decomp_master;
  171329. typedef my_decomp_master * my_master_ptr6;
  171330. /*
  171331. * Determine whether merged upsample/color conversion should be used.
  171332. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  171333. */
  171334. LOCAL(boolean)
  171335. use_merged_upsample (j_decompress_ptr cinfo)
  171336. {
  171337. #ifdef UPSAMPLE_MERGING_SUPPORTED
  171338. /* Merging is the equivalent of plain box-filter upsampling */
  171339. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  171340. return FALSE;
  171341. /* jdmerge.c only supports YCC=>RGB color conversion */
  171342. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  171343. cinfo->out_color_space != JCS_RGB ||
  171344. cinfo->out_color_components != RGB_PIXELSIZE)
  171345. return FALSE;
  171346. /* and it only handles 2h1v or 2h2v sampling ratios */
  171347. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  171348. cinfo->comp_info[1].h_samp_factor != 1 ||
  171349. cinfo->comp_info[2].h_samp_factor != 1 ||
  171350. cinfo->comp_info[0].v_samp_factor > 2 ||
  171351. cinfo->comp_info[1].v_samp_factor != 1 ||
  171352. cinfo->comp_info[2].v_samp_factor != 1)
  171353. return FALSE;
  171354. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  171355. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  171356. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  171357. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  171358. return FALSE;
  171359. /* ??? also need to test for upsample-time rescaling, when & if supported */
  171360. return TRUE; /* by golly, it'll work... */
  171361. #else
  171362. return FALSE;
  171363. #endif
  171364. }
  171365. /*
  171366. * Compute output image dimensions and related values.
  171367. * NOTE: this is exported for possible use by application.
  171368. * Hence it mustn't do anything that can't be done twice.
  171369. * Also note that it may be called before the master module is initialized!
  171370. */
  171371. GLOBAL(void)
  171372. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  171373. /* Do computations that are needed before master selection phase */
  171374. {
  171375. #ifdef IDCT_SCALING_SUPPORTED
  171376. int ci;
  171377. jpeg_component_info *compptr;
  171378. #endif
  171379. /* Prevent application from calling me at wrong times */
  171380. if (cinfo->global_state != DSTATE_READY)
  171381. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  171382. #ifdef IDCT_SCALING_SUPPORTED
  171383. /* Compute actual output image dimensions and DCT scaling choices. */
  171384. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  171385. /* Provide 1/8 scaling */
  171386. cinfo->output_width = (JDIMENSION)
  171387. jdiv_round_up((long) cinfo->image_width, 8L);
  171388. cinfo->output_height = (JDIMENSION)
  171389. jdiv_round_up((long) cinfo->image_height, 8L);
  171390. cinfo->min_DCT_scaled_size = 1;
  171391. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  171392. /* Provide 1/4 scaling */
  171393. cinfo->output_width = (JDIMENSION)
  171394. jdiv_round_up((long) cinfo->image_width, 4L);
  171395. cinfo->output_height = (JDIMENSION)
  171396. jdiv_round_up((long) cinfo->image_height, 4L);
  171397. cinfo->min_DCT_scaled_size = 2;
  171398. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  171399. /* Provide 1/2 scaling */
  171400. cinfo->output_width = (JDIMENSION)
  171401. jdiv_round_up((long) cinfo->image_width, 2L);
  171402. cinfo->output_height = (JDIMENSION)
  171403. jdiv_round_up((long) cinfo->image_height, 2L);
  171404. cinfo->min_DCT_scaled_size = 4;
  171405. } else {
  171406. /* Provide 1/1 scaling */
  171407. cinfo->output_width = cinfo->image_width;
  171408. cinfo->output_height = cinfo->image_height;
  171409. cinfo->min_DCT_scaled_size = DCTSIZE;
  171410. }
  171411. /* In selecting the actual DCT scaling for each component, we try to
  171412. * scale up the chroma components via IDCT scaling rather than upsampling.
  171413. * This saves time if the upsampler gets to use 1:1 scaling.
  171414. * Note this code assumes that the supported DCT scalings are powers of 2.
  171415. */
  171416. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171417. ci++, compptr++) {
  171418. int ssize = cinfo->min_DCT_scaled_size;
  171419. while (ssize < DCTSIZE &&
  171420. (compptr->h_samp_factor * ssize * 2 <=
  171421. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  171422. (compptr->v_samp_factor * ssize * 2 <=
  171423. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  171424. ssize = ssize * 2;
  171425. }
  171426. compptr->DCT_scaled_size = ssize;
  171427. }
  171428. /* Recompute downsampled dimensions of components;
  171429. * application needs to know these if using raw downsampled data.
  171430. */
  171431. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171432. ci++, compptr++) {
  171433. /* Size in samples, after IDCT scaling */
  171434. compptr->downsampled_width = (JDIMENSION)
  171435. jdiv_round_up((long) cinfo->image_width *
  171436. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  171437. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  171438. compptr->downsampled_height = (JDIMENSION)
  171439. jdiv_round_up((long) cinfo->image_height *
  171440. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  171441. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  171442. }
  171443. #else /* !IDCT_SCALING_SUPPORTED */
  171444. /* Hardwire it to "no scaling" */
  171445. cinfo->output_width = cinfo->image_width;
  171446. cinfo->output_height = cinfo->image_height;
  171447. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  171448. * and has computed unscaled downsampled_width and downsampled_height.
  171449. */
  171450. #endif /* IDCT_SCALING_SUPPORTED */
  171451. /* Report number of components in selected colorspace. */
  171452. /* Probably this should be in the color conversion module... */
  171453. switch (cinfo->out_color_space) {
  171454. case JCS_GRAYSCALE:
  171455. cinfo->out_color_components = 1;
  171456. break;
  171457. case JCS_RGB:
  171458. #if RGB_PIXELSIZE != 3
  171459. cinfo->out_color_components = RGB_PIXELSIZE;
  171460. break;
  171461. #endif /* else share code with YCbCr */
  171462. case JCS_YCbCr:
  171463. cinfo->out_color_components = 3;
  171464. break;
  171465. case JCS_CMYK:
  171466. case JCS_YCCK:
  171467. cinfo->out_color_components = 4;
  171468. break;
  171469. default: /* else must be same colorspace as in file */
  171470. cinfo->out_color_components = cinfo->num_components;
  171471. break;
  171472. }
  171473. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  171474. cinfo->out_color_components);
  171475. /* See if upsampler will want to emit more than one row at a time */
  171476. if (use_merged_upsample(cinfo))
  171477. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  171478. else
  171479. cinfo->rec_outbuf_height = 1;
  171480. }
  171481. /*
  171482. * Several decompression processes need to range-limit values to the range
  171483. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  171484. * due to noise introduced by quantization, roundoff error, etc. These
  171485. * processes are inner loops and need to be as fast as possible. On most
  171486. * machines, particularly CPUs with pipelines or instruction prefetch,
  171487. * a (subscript-check-less) C table lookup
  171488. * x = sample_range_limit[x];
  171489. * is faster than explicit tests
  171490. * if (x < 0) x = 0;
  171491. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  171492. * These processes all use a common table prepared by the routine below.
  171493. *
  171494. * For most steps we can mathematically guarantee that the initial value
  171495. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  171496. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  171497. * limiting step (just after the IDCT), a wildly out-of-range value is
  171498. * possible if the input data is corrupt. To avoid any chance of indexing
  171499. * off the end of memory and getting a bad-pointer trap, we perform the
  171500. * post-IDCT limiting thus:
  171501. * x = range_limit[x & MASK];
  171502. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  171503. * samples. Under normal circumstances this is more than enough range and
  171504. * a correct output will be generated; with bogus input data the mask will
  171505. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  171506. * For the post-IDCT step, we want to convert the data from signed to unsigned
  171507. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  171508. * So the post-IDCT limiting table ends up looking like this:
  171509. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  171510. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  171511. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  171512. * 0,1,...,CENTERJSAMPLE-1
  171513. * Negative inputs select values from the upper half of the table after
  171514. * masking.
  171515. *
  171516. * We can save some space by overlapping the start of the post-IDCT table
  171517. * with the simpler range limiting table. The post-IDCT table begins at
  171518. * sample_range_limit + CENTERJSAMPLE.
  171519. *
  171520. * Note that the table is allocated in near data space on PCs; it's small
  171521. * enough and used often enough to justify this.
  171522. */
  171523. LOCAL(void)
  171524. prepare_range_limit_table (j_decompress_ptr cinfo)
  171525. /* Allocate and fill in the sample_range_limit table */
  171526. {
  171527. JSAMPLE * table;
  171528. int i;
  171529. table = (JSAMPLE *)
  171530. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171531. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  171532. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  171533. cinfo->sample_range_limit = table;
  171534. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  171535. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  171536. /* Main part of "simple" table: limit[x] = x */
  171537. for (i = 0; i <= MAXJSAMPLE; i++)
  171538. table[i] = (JSAMPLE) i;
  171539. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  171540. /* End of simple table, rest of first half of post-IDCT table */
  171541. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  171542. table[i] = MAXJSAMPLE;
  171543. /* Second half of post-IDCT table */
  171544. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  171545. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  171546. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  171547. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  171548. }
  171549. /*
  171550. * Master selection of decompression modules.
  171551. * This is done once at jpeg_start_decompress time. We determine
  171552. * which modules will be used and give them appropriate initialization calls.
  171553. * We also initialize the decompressor input side to begin consuming data.
  171554. *
  171555. * Since jpeg_read_header has finished, we know what is in the SOF
  171556. * and (first) SOS markers. We also have all the application parameter
  171557. * settings.
  171558. */
  171559. LOCAL(void)
  171560. master_selection (j_decompress_ptr cinfo)
  171561. {
  171562. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  171563. boolean use_c_buffer;
  171564. long samplesperrow;
  171565. JDIMENSION jd_samplesperrow;
  171566. /* Initialize dimensions and other stuff */
  171567. jpeg_calc_output_dimensions(cinfo);
  171568. prepare_range_limit_table(cinfo);
  171569. /* Width of an output scanline must be representable as JDIMENSION. */
  171570. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  171571. jd_samplesperrow = (JDIMENSION) samplesperrow;
  171572. if ((long) jd_samplesperrow != samplesperrow)
  171573. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  171574. /* Initialize my private state */
  171575. master->pass_number = 0;
  171576. master->using_merged_upsample = use_merged_upsample(cinfo);
  171577. /* Color quantizer selection */
  171578. master->quantizer_1pass = NULL;
  171579. master->quantizer_2pass = NULL;
  171580. /* No mode changes if not using buffered-image mode. */
  171581. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  171582. cinfo->enable_1pass_quant = FALSE;
  171583. cinfo->enable_external_quant = FALSE;
  171584. cinfo->enable_2pass_quant = FALSE;
  171585. }
  171586. if (cinfo->quantize_colors) {
  171587. if (cinfo->raw_data_out)
  171588. ERREXIT(cinfo, JERR_NOTIMPL);
  171589. /* 2-pass quantizer only works in 3-component color space. */
  171590. if (cinfo->out_color_components != 3) {
  171591. cinfo->enable_1pass_quant = TRUE;
  171592. cinfo->enable_external_quant = FALSE;
  171593. cinfo->enable_2pass_quant = FALSE;
  171594. cinfo->colormap = NULL;
  171595. } else if (cinfo->colormap != NULL) {
  171596. cinfo->enable_external_quant = TRUE;
  171597. } else if (cinfo->two_pass_quantize) {
  171598. cinfo->enable_2pass_quant = TRUE;
  171599. } else {
  171600. cinfo->enable_1pass_quant = TRUE;
  171601. }
  171602. if (cinfo->enable_1pass_quant) {
  171603. #ifdef QUANT_1PASS_SUPPORTED
  171604. jinit_1pass_quantizer(cinfo);
  171605. master->quantizer_1pass = cinfo->cquantize;
  171606. #else
  171607. ERREXIT(cinfo, JERR_NOT_COMPILED);
  171608. #endif
  171609. }
  171610. /* We use the 2-pass code to map to external colormaps. */
  171611. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  171612. #ifdef QUANT_2PASS_SUPPORTED
  171613. jinit_2pass_quantizer(cinfo);
  171614. master->quantizer_2pass = cinfo->cquantize;
  171615. #else
  171616. ERREXIT(cinfo, JERR_NOT_COMPILED);
  171617. #endif
  171618. }
  171619. /* If both quantizers are initialized, the 2-pass one is left active;
  171620. * this is necessary for starting with quantization to an external map.
  171621. */
  171622. }
  171623. /* Post-processing: in particular, color conversion first */
  171624. if (! cinfo->raw_data_out) {
  171625. if (master->using_merged_upsample) {
  171626. #ifdef UPSAMPLE_MERGING_SUPPORTED
  171627. jinit_merged_upsampler(cinfo); /* does color conversion too */
  171628. #else
  171629. ERREXIT(cinfo, JERR_NOT_COMPILED);
  171630. #endif
  171631. } else {
  171632. jinit_color_deconverter(cinfo);
  171633. jinit_upsampler(cinfo);
  171634. }
  171635. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  171636. }
  171637. /* Inverse DCT */
  171638. jinit_inverse_dct(cinfo);
  171639. /* Entropy decoding: either Huffman or arithmetic coding. */
  171640. if (cinfo->arith_code) {
  171641. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  171642. } else {
  171643. if (cinfo->progressive_mode) {
  171644. #ifdef D_PROGRESSIVE_SUPPORTED
  171645. jinit_phuff_decoder(cinfo);
  171646. #else
  171647. ERREXIT(cinfo, JERR_NOT_COMPILED);
  171648. #endif
  171649. } else
  171650. jinit_huff_decoder(cinfo);
  171651. }
  171652. /* Initialize principal buffer controllers. */
  171653. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  171654. jinit_d_coef_controller(cinfo, use_c_buffer);
  171655. if (! cinfo->raw_data_out)
  171656. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  171657. /* We can now tell the memory manager to allocate virtual arrays. */
  171658. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  171659. /* Initialize input side of decompressor to consume first scan. */
  171660. (*cinfo->inputctl->start_input_pass) (cinfo);
  171661. #ifdef D_MULTISCAN_FILES_SUPPORTED
  171662. /* If jpeg_start_decompress will read the whole file, initialize
  171663. * progress monitoring appropriately. The input step is counted
  171664. * as one pass.
  171665. */
  171666. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  171667. cinfo->inputctl->has_multiple_scans) {
  171668. int nscans;
  171669. /* Estimate number of scans to set pass_limit. */
  171670. if (cinfo->progressive_mode) {
  171671. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  171672. nscans = 2 + 3 * cinfo->num_components;
  171673. } else {
  171674. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  171675. nscans = cinfo->num_components;
  171676. }
  171677. cinfo->progress->pass_counter = 0L;
  171678. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  171679. cinfo->progress->completed_passes = 0;
  171680. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  171681. /* Count the input pass as done */
  171682. master->pass_number++;
  171683. }
  171684. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  171685. }
  171686. /*
  171687. * Per-pass setup.
  171688. * This is called at the beginning of each output pass. We determine which
  171689. * modules will be active during this pass and give them appropriate
  171690. * start_pass calls. We also set is_dummy_pass to indicate whether this
  171691. * is a "real" output pass or a dummy pass for color quantization.
  171692. * (In the latter case, jdapistd.c will crank the pass to completion.)
  171693. */
  171694. METHODDEF(void)
  171695. prepare_for_output_pass (j_decompress_ptr cinfo)
  171696. {
  171697. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  171698. if (master->pub.is_dummy_pass) {
  171699. #ifdef QUANT_2PASS_SUPPORTED
  171700. /* Final pass of 2-pass quantization */
  171701. master->pub.is_dummy_pass = FALSE;
  171702. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  171703. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  171704. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  171705. #else
  171706. ERREXIT(cinfo, JERR_NOT_COMPILED);
  171707. #endif /* QUANT_2PASS_SUPPORTED */
  171708. } else {
  171709. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  171710. /* Select new quantization method */
  171711. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  171712. cinfo->cquantize = master->quantizer_2pass;
  171713. master->pub.is_dummy_pass = TRUE;
  171714. } else if (cinfo->enable_1pass_quant) {
  171715. cinfo->cquantize = master->quantizer_1pass;
  171716. } else {
  171717. ERREXIT(cinfo, JERR_MODE_CHANGE);
  171718. }
  171719. }
  171720. (*cinfo->idct->start_pass) (cinfo);
  171721. (*cinfo->coef->start_output_pass) (cinfo);
  171722. if (! cinfo->raw_data_out) {
  171723. if (! master->using_merged_upsample)
  171724. (*cinfo->cconvert->start_pass) (cinfo);
  171725. (*cinfo->upsample->start_pass) (cinfo);
  171726. if (cinfo->quantize_colors)
  171727. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  171728. (*cinfo->post->start_pass) (cinfo,
  171729. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  171730. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  171731. }
  171732. }
  171733. /* Set up progress monitor's pass info if present */
  171734. if (cinfo->progress != NULL) {
  171735. cinfo->progress->completed_passes = master->pass_number;
  171736. cinfo->progress->total_passes = master->pass_number +
  171737. (master->pub.is_dummy_pass ? 2 : 1);
  171738. /* In buffered-image mode, we assume one more output pass if EOI not
  171739. * yet reached, but no more passes if EOI has been reached.
  171740. */
  171741. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  171742. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  171743. }
  171744. }
  171745. }
  171746. /*
  171747. * Finish up at end of an output pass.
  171748. */
  171749. METHODDEF(void)
  171750. finish_output_pass (j_decompress_ptr cinfo)
  171751. {
  171752. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  171753. if (cinfo->quantize_colors)
  171754. (*cinfo->cquantize->finish_pass) (cinfo);
  171755. master->pass_number++;
  171756. }
  171757. #ifdef D_MULTISCAN_FILES_SUPPORTED
  171758. /*
  171759. * Switch to a new external colormap between output passes.
  171760. */
  171761. GLOBAL(void)
  171762. jpeg_new_colormap (j_decompress_ptr cinfo)
  171763. {
  171764. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  171765. /* Prevent application from calling me at wrong times */
  171766. if (cinfo->global_state != DSTATE_BUFIMAGE)
  171767. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  171768. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  171769. cinfo->colormap != NULL) {
  171770. /* Select 2-pass quantizer for external colormap use */
  171771. cinfo->cquantize = master->quantizer_2pass;
  171772. /* Notify quantizer of colormap change */
  171773. (*cinfo->cquantize->new_color_map) (cinfo);
  171774. master->pub.is_dummy_pass = FALSE; /* just in case */
  171775. } else
  171776. ERREXIT(cinfo, JERR_MODE_CHANGE);
  171777. }
  171778. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  171779. /*
  171780. * Initialize master decompression control and select active modules.
  171781. * This is performed at the start of jpeg_start_decompress.
  171782. */
  171783. GLOBAL(void)
  171784. jinit_master_decompress (j_decompress_ptr cinfo)
  171785. {
  171786. my_master_ptr6 master;
  171787. master = (my_master_ptr6)
  171788. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171789. SIZEOF(my_decomp_master));
  171790. cinfo->master = (struct jpeg_decomp_master *) master;
  171791. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  171792. master->pub.finish_output_pass = finish_output_pass;
  171793. master->pub.is_dummy_pass = FALSE;
  171794. master_selection(cinfo);
  171795. }
  171796. /*** End of inlined file: jdmaster.c ***/
  171797. #undef FIX
  171798. /*** Start of inlined file: jdmerge.c ***/
  171799. #define JPEG_INTERNALS
  171800. #ifdef UPSAMPLE_MERGING_SUPPORTED
  171801. /* Private subobject */
  171802. typedef struct {
  171803. struct jpeg_upsampler pub; /* public fields */
  171804. /* Pointer to routine to do actual upsampling/conversion of one row group */
  171805. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  171806. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  171807. JSAMPARRAY output_buf));
  171808. /* Private state for YCC->RGB conversion */
  171809. int * Cr_r_tab; /* => table for Cr to R conversion */
  171810. int * Cb_b_tab; /* => table for Cb to B conversion */
  171811. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  171812. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  171813. /* For 2:1 vertical sampling, we produce two output rows at a time.
  171814. * We need a "spare" row buffer to hold the second output row if the
  171815. * application provides just a one-row buffer; we also use the spare
  171816. * to discard the dummy last row if the image height is odd.
  171817. */
  171818. JSAMPROW spare_row;
  171819. boolean spare_full; /* T if spare buffer is occupied */
  171820. JDIMENSION out_row_width; /* samples per output row */
  171821. JDIMENSION rows_to_go; /* counts rows remaining in image */
  171822. } my_upsampler;
  171823. typedef my_upsampler * my_upsample_ptr;
  171824. #define SCALEBITS 16 /* speediest right-shift on some machines */
  171825. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  171826. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  171827. /*
  171828. * Initialize tables for YCC->RGB colorspace conversion.
  171829. * This is taken directly from jdcolor.c; see that file for more info.
  171830. */
  171831. LOCAL(void)
  171832. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  171833. {
  171834. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  171835. int i;
  171836. INT32 x;
  171837. SHIFT_TEMPS
  171838. upsample->Cr_r_tab = (int *)
  171839. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171840. (MAXJSAMPLE+1) * SIZEOF(int));
  171841. upsample->Cb_b_tab = (int *)
  171842. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171843. (MAXJSAMPLE+1) * SIZEOF(int));
  171844. upsample->Cr_g_tab = (INT32 *)
  171845. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171846. (MAXJSAMPLE+1) * SIZEOF(INT32));
  171847. upsample->Cb_g_tab = (INT32 *)
  171848. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171849. (MAXJSAMPLE+1) * SIZEOF(INT32));
  171850. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  171851. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  171852. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  171853. /* Cr=>R value is nearest int to 1.40200 * x */
  171854. upsample->Cr_r_tab[i] = (int)
  171855. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  171856. /* Cb=>B value is nearest int to 1.77200 * x */
  171857. upsample->Cb_b_tab[i] = (int)
  171858. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  171859. /* Cr=>G value is scaled-up -0.71414 * x */
  171860. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  171861. /* Cb=>G value is scaled-up -0.34414 * x */
  171862. /* We also add in ONE_HALF so that need not do it in inner loop */
  171863. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  171864. }
  171865. }
  171866. /*
  171867. * Initialize for an upsampling pass.
  171868. */
  171869. METHODDEF(void)
  171870. start_pass_merged_upsample (j_decompress_ptr cinfo)
  171871. {
  171872. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  171873. /* Mark the spare buffer empty */
  171874. upsample->spare_full = FALSE;
  171875. /* Initialize total-height counter for detecting bottom of image */
  171876. upsample->rows_to_go = cinfo->output_height;
  171877. }
  171878. /*
  171879. * Control routine to do upsampling (and color conversion).
  171880. *
  171881. * The control routine just handles the row buffering considerations.
  171882. */
  171883. METHODDEF(void)
  171884. merged_2v_upsample (j_decompress_ptr cinfo,
  171885. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  171886. JDIMENSION,
  171887. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171888. JDIMENSION out_rows_avail)
  171889. /* 2:1 vertical sampling case: may need a spare row. */
  171890. {
  171891. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  171892. JSAMPROW work_ptrs[2];
  171893. JDIMENSION num_rows; /* number of rows returned to caller */
  171894. if (upsample->spare_full) {
  171895. /* If we have a spare row saved from a previous cycle, just return it. */
  171896. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  171897. 1, upsample->out_row_width);
  171898. num_rows = 1;
  171899. upsample->spare_full = FALSE;
  171900. } else {
  171901. /* Figure number of rows to return to caller. */
  171902. num_rows = 2;
  171903. /* Not more than the distance to the end of the image. */
  171904. if (num_rows > upsample->rows_to_go)
  171905. num_rows = upsample->rows_to_go;
  171906. /* And not more than what the client can accept: */
  171907. out_rows_avail -= *out_row_ctr;
  171908. if (num_rows > out_rows_avail)
  171909. num_rows = out_rows_avail;
  171910. /* Create output pointer array for upsampler. */
  171911. work_ptrs[0] = output_buf[*out_row_ctr];
  171912. if (num_rows > 1) {
  171913. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  171914. } else {
  171915. work_ptrs[1] = upsample->spare_row;
  171916. upsample->spare_full = TRUE;
  171917. }
  171918. /* Now do the upsampling. */
  171919. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  171920. }
  171921. /* Adjust counts */
  171922. *out_row_ctr += num_rows;
  171923. upsample->rows_to_go -= num_rows;
  171924. /* When the buffer is emptied, declare this input row group consumed */
  171925. if (! upsample->spare_full)
  171926. (*in_row_group_ctr)++;
  171927. }
  171928. METHODDEF(void)
  171929. merged_1v_upsample (j_decompress_ptr cinfo,
  171930. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  171931. JDIMENSION,
  171932. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171933. JDIMENSION)
  171934. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  171935. {
  171936. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  171937. /* Just do the upsampling. */
  171938. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  171939. output_buf + *out_row_ctr);
  171940. /* Adjust counts */
  171941. (*out_row_ctr)++;
  171942. (*in_row_group_ctr)++;
  171943. }
  171944. /*
  171945. * These are the routines invoked by the control routines to do
  171946. * the actual upsampling/conversion. One row group is processed per call.
  171947. *
  171948. * Note: since we may be writing directly into application-supplied buffers,
  171949. * we have to be honest about the output width; we can't assume the buffer
  171950. * has been rounded up to an even width.
  171951. */
  171952. /*
  171953. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  171954. */
  171955. METHODDEF(void)
  171956. h2v1_merged_upsample (j_decompress_ptr cinfo,
  171957. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  171958. JSAMPARRAY output_buf)
  171959. {
  171960. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  171961. register int y, cred, cgreen, cblue;
  171962. int cb, cr;
  171963. register JSAMPROW outptr;
  171964. JSAMPROW inptr0, inptr1, inptr2;
  171965. JDIMENSION col;
  171966. /* copy these pointers into registers if possible */
  171967. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  171968. int * Crrtab = upsample->Cr_r_tab;
  171969. int * Cbbtab = upsample->Cb_b_tab;
  171970. INT32 * Crgtab = upsample->Cr_g_tab;
  171971. INT32 * Cbgtab = upsample->Cb_g_tab;
  171972. SHIFT_TEMPS
  171973. inptr0 = input_buf[0][in_row_group_ctr];
  171974. inptr1 = input_buf[1][in_row_group_ctr];
  171975. inptr2 = input_buf[2][in_row_group_ctr];
  171976. outptr = output_buf[0];
  171977. /* Loop for each pair of output pixels */
  171978. for (col = cinfo->output_width >> 1; col > 0; col--) {
  171979. /* Do the chroma part of the calculation */
  171980. cb = GETJSAMPLE(*inptr1++);
  171981. cr = GETJSAMPLE(*inptr2++);
  171982. cred = Crrtab[cr];
  171983. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  171984. cblue = Cbbtab[cb];
  171985. /* Fetch 2 Y values and emit 2 pixels */
  171986. y = GETJSAMPLE(*inptr0++);
  171987. outptr[RGB_RED] = range_limit[y + cred];
  171988. outptr[RGB_GREEN] = range_limit[y + cgreen];
  171989. outptr[RGB_BLUE] = range_limit[y + cblue];
  171990. outptr += RGB_PIXELSIZE;
  171991. y = GETJSAMPLE(*inptr0++);
  171992. outptr[RGB_RED] = range_limit[y + cred];
  171993. outptr[RGB_GREEN] = range_limit[y + cgreen];
  171994. outptr[RGB_BLUE] = range_limit[y + cblue];
  171995. outptr += RGB_PIXELSIZE;
  171996. }
  171997. /* If image width is odd, do the last output column separately */
  171998. if (cinfo->output_width & 1) {
  171999. cb = GETJSAMPLE(*inptr1);
  172000. cr = GETJSAMPLE(*inptr2);
  172001. cred = Crrtab[cr];
  172002. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172003. cblue = Cbbtab[cb];
  172004. y = GETJSAMPLE(*inptr0);
  172005. outptr[RGB_RED] = range_limit[y + cred];
  172006. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172007. outptr[RGB_BLUE] = range_limit[y + cblue];
  172008. }
  172009. }
  172010. /*
  172011. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  172012. */
  172013. METHODDEF(void)
  172014. h2v2_merged_upsample (j_decompress_ptr cinfo,
  172015. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172016. JSAMPARRAY output_buf)
  172017. {
  172018. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172019. register int y, cred, cgreen, cblue;
  172020. int cb, cr;
  172021. register JSAMPROW outptr0, outptr1;
  172022. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  172023. JDIMENSION col;
  172024. /* copy these pointers into registers if possible */
  172025. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  172026. int * Crrtab = upsample->Cr_r_tab;
  172027. int * Cbbtab = upsample->Cb_b_tab;
  172028. INT32 * Crgtab = upsample->Cr_g_tab;
  172029. INT32 * Cbgtab = upsample->Cb_g_tab;
  172030. SHIFT_TEMPS
  172031. inptr00 = input_buf[0][in_row_group_ctr*2];
  172032. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  172033. inptr1 = input_buf[1][in_row_group_ctr];
  172034. inptr2 = input_buf[2][in_row_group_ctr];
  172035. outptr0 = output_buf[0];
  172036. outptr1 = output_buf[1];
  172037. /* Loop for each group of output pixels */
  172038. for (col = cinfo->output_width >> 1; col > 0; col--) {
  172039. /* Do the chroma part of the calculation */
  172040. cb = GETJSAMPLE(*inptr1++);
  172041. cr = GETJSAMPLE(*inptr2++);
  172042. cred = Crrtab[cr];
  172043. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172044. cblue = Cbbtab[cb];
  172045. /* Fetch 4 Y values and emit 4 pixels */
  172046. y = GETJSAMPLE(*inptr00++);
  172047. outptr0[RGB_RED] = range_limit[y + cred];
  172048. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172049. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172050. outptr0 += RGB_PIXELSIZE;
  172051. y = GETJSAMPLE(*inptr00++);
  172052. outptr0[RGB_RED] = range_limit[y + cred];
  172053. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172054. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172055. outptr0 += RGB_PIXELSIZE;
  172056. y = GETJSAMPLE(*inptr01++);
  172057. outptr1[RGB_RED] = range_limit[y + cred];
  172058. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172059. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172060. outptr1 += RGB_PIXELSIZE;
  172061. y = GETJSAMPLE(*inptr01++);
  172062. outptr1[RGB_RED] = range_limit[y + cred];
  172063. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172064. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172065. outptr1 += RGB_PIXELSIZE;
  172066. }
  172067. /* If image width is odd, do the last output column separately */
  172068. if (cinfo->output_width & 1) {
  172069. cb = GETJSAMPLE(*inptr1);
  172070. cr = GETJSAMPLE(*inptr2);
  172071. cred = Crrtab[cr];
  172072. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172073. cblue = Cbbtab[cb];
  172074. y = GETJSAMPLE(*inptr00);
  172075. outptr0[RGB_RED] = range_limit[y + cred];
  172076. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172077. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172078. y = GETJSAMPLE(*inptr01);
  172079. outptr1[RGB_RED] = range_limit[y + cred];
  172080. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172081. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172082. }
  172083. }
  172084. /*
  172085. * Module initialization routine for merged upsampling/color conversion.
  172086. *
  172087. * NB: this is called under the conditions determined by use_merged_upsample()
  172088. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  172089. * of this module; no safety checks are made here.
  172090. */
  172091. GLOBAL(void)
  172092. jinit_merged_upsampler (j_decompress_ptr cinfo)
  172093. {
  172094. my_upsample_ptr upsample;
  172095. upsample = (my_upsample_ptr)
  172096. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172097. SIZEOF(my_upsampler));
  172098. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  172099. upsample->pub.start_pass = start_pass_merged_upsample;
  172100. upsample->pub.need_context_rows = FALSE;
  172101. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  172102. if (cinfo->max_v_samp_factor == 2) {
  172103. upsample->pub.upsample = merged_2v_upsample;
  172104. upsample->upmethod = h2v2_merged_upsample;
  172105. /* Allocate a spare row buffer */
  172106. upsample->spare_row = (JSAMPROW)
  172107. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172108. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  172109. } else {
  172110. upsample->pub.upsample = merged_1v_upsample;
  172111. upsample->upmethod = h2v1_merged_upsample;
  172112. /* No spare row needed */
  172113. upsample->spare_row = NULL;
  172114. }
  172115. build_ycc_rgb_table2(cinfo);
  172116. }
  172117. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  172118. /*** End of inlined file: jdmerge.c ***/
  172119. #undef ASSIGN_STATE
  172120. /*** Start of inlined file: jdphuff.c ***/
  172121. #define JPEG_INTERNALS
  172122. #ifdef D_PROGRESSIVE_SUPPORTED
  172123. /*
  172124. * Expanded entropy decoder object for progressive Huffman decoding.
  172125. *
  172126. * The savable_state subrecord contains fields that change within an MCU,
  172127. * but must not be updated permanently until we complete the MCU.
  172128. */
  172129. typedef struct {
  172130. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  172131. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  172132. } savable_state3;
  172133. /* This macro is to work around compilers with missing or broken
  172134. * structure assignment. You'll need to fix this code if you have
  172135. * such a compiler and you change MAX_COMPS_IN_SCAN.
  172136. */
  172137. #ifndef NO_STRUCT_ASSIGN
  172138. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  172139. #else
  172140. #if MAX_COMPS_IN_SCAN == 4
  172141. #define ASSIGN_STATE(dest,src) \
  172142. ((dest).EOBRUN = (src).EOBRUN, \
  172143. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  172144. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  172145. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  172146. (dest).last_dc_val[3] = (src).last_dc_val[3])
  172147. #endif
  172148. #endif
  172149. typedef struct {
  172150. struct jpeg_entropy_decoder pub; /* public fields */
  172151. /* These fields are loaded into local variables at start of each MCU.
  172152. * In case of suspension, we exit WITHOUT updating them.
  172153. */
  172154. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  172155. savable_state3 saved; /* Other state at start of MCU */
  172156. /* These fields are NOT loaded into local working state. */
  172157. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  172158. /* Pointers to derived tables (these workspaces have image lifespan) */
  172159. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  172160. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  172161. } phuff_entropy_decoder;
  172162. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  172163. /* Forward declarations */
  172164. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  172165. JBLOCKROW *MCU_data));
  172166. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  172167. JBLOCKROW *MCU_data));
  172168. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  172169. JBLOCKROW *MCU_data));
  172170. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  172171. JBLOCKROW *MCU_data));
  172172. /*
  172173. * Initialize for a Huffman-compressed scan.
  172174. */
  172175. METHODDEF(void)
  172176. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  172177. {
  172178. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172179. boolean is_DC_band, bad;
  172180. int ci, coefi, tbl;
  172181. int *coef_bit_ptr;
  172182. jpeg_component_info * compptr;
  172183. is_DC_band = (cinfo->Ss == 0);
  172184. /* Validate scan parameters */
  172185. bad = FALSE;
  172186. if (is_DC_band) {
  172187. if (cinfo->Se != 0)
  172188. bad = TRUE;
  172189. } else {
  172190. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  172191. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  172192. bad = TRUE;
  172193. /* AC scans may have only one component */
  172194. if (cinfo->comps_in_scan != 1)
  172195. bad = TRUE;
  172196. }
  172197. if (cinfo->Ah != 0) {
  172198. /* Successive approximation refinement scan: must have Al = Ah-1. */
  172199. if (cinfo->Al != cinfo->Ah-1)
  172200. bad = TRUE;
  172201. }
  172202. if (cinfo->Al > 13) /* need not check for < 0 */
  172203. bad = TRUE;
  172204. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  172205. * but the spec doesn't say so, and we try to be liberal about what we
  172206. * accept. Note: large Al values could result in out-of-range DC
  172207. * coefficients during early scans, leading to bizarre displays due to
  172208. * overflows in the IDCT math. But we won't crash.
  172209. */
  172210. if (bad)
  172211. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  172212. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  172213. /* Update progression status, and verify that scan order is legal.
  172214. * Note that inter-scan inconsistencies are treated as warnings
  172215. * not fatal errors ... not clear if this is right way to behave.
  172216. */
  172217. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  172218. int cindex = cinfo->cur_comp_info[ci]->component_index;
  172219. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  172220. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  172221. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  172222. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  172223. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  172224. if (cinfo->Ah != expected)
  172225. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  172226. coef_bit_ptr[coefi] = cinfo->Al;
  172227. }
  172228. }
  172229. /* Select MCU decoding routine */
  172230. if (cinfo->Ah == 0) {
  172231. if (is_DC_band)
  172232. entropy->pub.decode_mcu = decode_mcu_DC_first;
  172233. else
  172234. entropy->pub.decode_mcu = decode_mcu_AC_first;
  172235. } else {
  172236. if (is_DC_band)
  172237. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  172238. else
  172239. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  172240. }
  172241. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  172242. compptr = cinfo->cur_comp_info[ci];
  172243. /* Make sure requested tables are present, and compute derived tables.
  172244. * We may build same derived table more than once, but it's not expensive.
  172245. */
  172246. if (is_DC_band) {
  172247. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  172248. tbl = compptr->dc_tbl_no;
  172249. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  172250. & entropy->derived_tbls[tbl]);
  172251. }
  172252. } else {
  172253. tbl = compptr->ac_tbl_no;
  172254. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  172255. & entropy->derived_tbls[tbl]);
  172256. /* remember the single active table */
  172257. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  172258. }
  172259. /* Initialize DC predictions to 0 */
  172260. entropy->saved.last_dc_val[ci] = 0;
  172261. }
  172262. /* Initialize bitread state variables */
  172263. entropy->bitstate.bits_left = 0;
  172264. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  172265. entropy->pub.insufficient_data = FALSE;
  172266. /* Initialize private state variables */
  172267. entropy->saved.EOBRUN = 0;
  172268. /* Initialize restart counter */
  172269. entropy->restarts_to_go = cinfo->restart_interval;
  172270. }
  172271. /*
  172272. * Check for a restart marker & resynchronize decoder.
  172273. * Returns FALSE if must suspend.
  172274. */
  172275. LOCAL(boolean)
  172276. process_restartp (j_decompress_ptr cinfo)
  172277. {
  172278. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172279. int ci;
  172280. /* Throw away any unused bits remaining in bit buffer; */
  172281. /* include any full bytes in next_marker's count of discarded bytes */
  172282. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  172283. entropy->bitstate.bits_left = 0;
  172284. /* Advance past the RSTn marker */
  172285. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  172286. return FALSE;
  172287. /* Re-initialize DC predictions to 0 */
  172288. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  172289. entropy->saved.last_dc_val[ci] = 0;
  172290. /* Re-init EOB run count, too */
  172291. entropy->saved.EOBRUN = 0;
  172292. /* Reset restart counter */
  172293. entropy->restarts_to_go = cinfo->restart_interval;
  172294. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  172295. * against a marker. In that case we will end up treating the next data
  172296. * segment as empty, and we can avoid producing bogus output pixels by
  172297. * leaving the flag set.
  172298. */
  172299. if (cinfo->unread_marker == 0)
  172300. entropy->pub.insufficient_data = FALSE;
  172301. return TRUE;
  172302. }
  172303. /*
  172304. * Huffman MCU decoding.
  172305. * Each of these routines decodes and returns one MCU's worth of
  172306. * Huffman-compressed coefficients.
  172307. * The coefficients are reordered from zigzag order into natural array order,
  172308. * but are not dequantized.
  172309. *
  172310. * The i'th block of the MCU is stored into the block pointed to by
  172311. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  172312. *
  172313. * We return FALSE if data source requested suspension. In that case no
  172314. * changes have been made to permanent state. (Exception: some output
  172315. * coefficients may already have been assigned. This is harmless for
  172316. * spectral selection, since we'll just re-assign them on the next call.
  172317. * Successive approximation AC refinement has to be more careful, however.)
  172318. */
  172319. /*
  172320. * MCU decoding for DC initial scan (either spectral selection,
  172321. * or first pass of successive approximation).
  172322. */
  172323. METHODDEF(boolean)
  172324. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  172325. {
  172326. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172327. int Al = cinfo->Al;
  172328. register int s, r;
  172329. int blkn, ci;
  172330. JBLOCKROW block;
  172331. BITREAD_STATE_VARS;
  172332. savable_state3 state;
  172333. d_derived_tbl * tbl;
  172334. jpeg_component_info * compptr;
  172335. /* Process restart marker if needed; may have to suspend */
  172336. if (cinfo->restart_interval) {
  172337. if (entropy->restarts_to_go == 0)
  172338. if (! process_restartp(cinfo))
  172339. return FALSE;
  172340. }
  172341. /* If we've run out of data, just leave the MCU set to zeroes.
  172342. * This way, we return uniform gray for the remainder of the segment.
  172343. */
  172344. if (! entropy->pub.insufficient_data) {
  172345. /* Load up working state */
  172346. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  172347. ASSIGN_STATE(state, entropy->saved);
  172348. /* Outer loop handles each block in the MCU */
  172349. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  172350. block = MCU_data[blkn];
  172351. ci = cinfo->MCU_membership[blkn];
  172352. compptr = cinfo->cur_comp_info[ci];
  172353. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  172354. /* Decode a single block's worth of coefficients */
  172355. /* Section F.2.2.1: decode the DC coefficient difference */
  172356. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  172357. if (s) {
  172358. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  172359. r = GET_BITS(s);
  172360. s = HUFF_EXTEND(r, s);
  172361. }
  172362. /* Convert DC difference to actual value, update last_dc_val */
  172363. s += state.last_dc_val[ci];
  172364. state.last_dc_val[ci] = s;
  172365. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  172366. (*block)[0] = (JCOEF) (s << Al);
  172367. }
  172368. /* Completed MCU, so update state */
  172369. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  172370. ASSIGN_STATE(entropy->saved, state);
  172371. }
  172372. /* Account for restart interval (no-op if not using restarts) */
  172373. entropy->restarts_to_go--;
  172374. return TRUE;
  172375. }
  172376. /*
  172377. * MCU decoding for AC initial scan (either spectral selection,
  172378. * or first pass of successive approximation).
  172379. */
  172380. METHODDEF(boolean)
  172381. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  172382. {
  172383. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172384. int Se = cinfo->Se;
  172385. int Al = cinfo->Al;
  172386. register int s, k, r;
  172387. unsigned int EOBRUN;
  172388. JBLOCKROW block;
  172389. BITREAD_STATE_VARS;
  172390. d_derived_tbl * tbl;
  172391. /* Process restart marker if needed; may have to suspend */
  172392. if (cinfo->restart_interval) {
  172393. if (entropy->restarts_to_go == 0)
  172394. if (! process_restartp(cinfo))
  172395. return FALSE;
  172396. }
  172397. /* If we've run out of data, just leave the MCU set to zeroes.
  172398. * This way, we return uniform gray for the remainder of the segment.
  172399. */
  172400. if (! entropy->pub.insufficient_data) {
  172401. /* Load up working state.
  172402. * We can avoid loading/saving bitread state if in an EOB run.
  172403. */
  172404. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  172405. /* There is always only one block per MCU */
  172406. if (EOBRUN > 0) /* if it's a band of zeroes... */
  172407. EOBRUN--; /* ...process it now (we do nothing) */
  172408. else {
  172409. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  172410. block = MCU_data[0];
  172411. tbl = entropy->ac_derived_tbl;
  172412. for (k = cinfo->Ss; k <= Se; k++) {
  172413. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  172414. r = s >> 4;
  172415. s &= 15;
  172416. if (s) {
  172417. k += r;
  172418. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  172419. r = GET_BITS(s);
  172420. s = HUFF_EXTEND(r, s);
  172421. /* Scale and output coefficient in natural (dezigzagged) order */
  172422. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  172423. } else {
  172424. if (r == 15) { /* ZRL */
  172425. k += 15; /* skip 15 zeroes in band */
  172426. } else { /* EOBr, run length is 2^r + appended bits */
  172427. EOBRUN = 1 << r;
  172428. if (r) { /* EOBr, r > 0 */
  172429. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  172430. r = GET_BITS(r);
  172431. EOBRUN += r;
  172432. }
  172433. EOBRUN--; /* this band is processed at this moment */
  172434. break; /* force end-of-band */
  172435. }
  172436. }
  172437. }
  172438. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  172439. }
  172440. /* Completed MCU, so update state */
  172441. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  172442. }
  172443. /* Account for restart interval (no-op if not using restarts) */
  172444. entropy->restarts_to_go--;
  172445. return TRUE;
  172446. }
  172447. /*
  172448. * MCU decoding for DC successive approximation refinement scan.
  172449. * Note: we assume such scans can be multi-component, although the spec
  172450. * is not very clear on the point.
  172451. */
  172452. METHODDEF(boolean)
  172453. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  172454. {
  172455. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172456. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  172457. int blkn;
  172458. JBLOCKROW block;
  172459. BITREAD_STATE_VARS;
  172460. /* Process restart marker if needed; may have to suspend */
  172461. if (cinfo->restart_interval) {
  172462. if (entropy->restarts_to_go == 0)
  172463. if (! process_restartp(cinfo))
  172464. return FALSE;
  172465. }
  172466. /* Not worth the cycles to check insufficient_data here,
  172467. * since we will not change the data anyway if we read zeroes.
  172468. */
  172469. /* Load up working state */
  172470. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  172471. /* Outer loop handles each block in the MCU */
  172472. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  172473. block = MCU_data[blkn];
  172474. /* Encoded data is simply the next bit of the two's-complement DC value */
  172475. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  172476. if (GET_BITS(1))
  172477. (*block)[0] |= p1;
  172478. /* Note: since we use |=, repeating the assignment later is safe */
  172479. }
  172480. /* Completed MCU, so update state */
  172481. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  172482. /* Account for restart interval (no-op if not using restarts) */
  172483. entropy->restarts_to_go--;
  172484. return TRUE;
  172485. }
  172486. /*
  172487. * MCU decoding for AC successive approximation refinement scan.
  172488. */
  172489. METHODDEF(boolean)
  172490. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  172491. {
  172492. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172493. int Se = cinfo->Se;
  172494. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  172495. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  172496. register int s, k, r;
  172497. unsigned int EOBRUN;
  172498. JBLOCKROW block;
  172499. JCOEFPTR thiscoef;
  172500. BITREAD_STATE_VARS;
  172501. d_derived_tbl * tbl;
  172502. int num_newnz;
  172503. int newnz_pos[DCTSIZE2];
  172504. /* Process restart marker if needed; may have to suspend */
  172505. if (cinfo->restart_interval) {
  172506. if (entropy->restarts_to_go == 0)
  172507. if (! process_restartp(cinfo))
  172508. return FALSE;
  172509. }
  172510. /* If we've run out of data, don't modify the MCU.
  172511. */
  172512. if (! entropy->pub.insufficient_data) {
  172513. /* Load up working state */
  172514. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  172515. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  172516. /* There is always only one block per MCU */
  172517. block = MCU_data[0];
  172518. tbl = entropy->ac_derived_tbl;
  172519. /* If we are forced to suspend, we must undo the assignments to any newly
  172520. * nonzero coefficients in the block, because otherwise we'd get confused
  172521. * next time about which coefficients were already nonzero.
  172522. * But we need not undo addition of bits to already-nonzero coefficients;
  172523. * instead, we can test the current bit to see if we already did it.
  172524. */
  172525. num_newnz = 0;
  172526. /* initialize coefficient loop counter to start of band */
  172527. k = cinfo->Ss;
  172528. if (EOBRUN == 0) {
  172529. for (; k <= Se; k++) {
  172530. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  172531. r = s >> 4;
  172532. s &= 15;
  172533. if (s) {
  172534. if (s != 1) /* size of new coef should always be 1 */
  172535. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  172536. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  172537. if (GET_BITS(1))
  172538. s = p1; /* newly nonzero coef is positive */
  172539. else
  172540. s = m1; /* newly nonzero coef is negative */
  172541. } else {
  172542. if (r != 15) {
  172543. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  172544. if (r) {
  172545. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  172546. r = GET_BITS(r);
  172547. EOBRUN += r;
  172548. }
  172549. break; /* rest of block is handled by EOB logic */
  172550. }
  172551. /* note s = 0 for processing ZRL */
  172552. }
  172553. /* Advance over already-nonzero coefs and r still-zero coefs,
  172554. * appending correction bits to the nonzeroes. A correction bit is 1
  172555. * if the absolute value of the coefficient must be increased.
  172556. */
  172557. do {
  172558. thiscoef = *block + jpeg_natural_order[k];
  172559. if (*thiscoef != 0) {
  172560. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  172561. if (GET_BITS(1)) {
  172562. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  172563. if (*thiscoef >= 0)
  172564. *thiscoef += p1;
  172565. else
  172566. *thiscoef += m1;
  172567. }
  172568. }
  172569. } else {
  172570. if (--r < 0)
  172571. break; /* reached target zero coefficient */
  172572. }
  172573. k++;
  172574. } while (k <= Se);
  172575. if (s) {
  172576. int pos = jpeg_natural_order[k];
  172577. /* Output newly nonzero coefficient */
  172578. (*block)[pos] = (JCOEF) s;
  172579. /* Remember its position in case we have to suspend */
  172580. newnz_pos[num_newnz++] = pos;
  172581. }
  172582. }
  172583. }
  172584. if (EOBRUN > 0) {
  172585. /* Scan any remaining coefficient positions after the end-of-band
  172586. * (the last newly nonzero coefficient, if any). Append a correction
  172587. * bit to each already-nonzero coefficient. A correction bit is 1
  172588. * if the absolute value of the coefficient must be increased.
  172589. */
  172590. for (; k <= Se; k++) {
  172591. thiscoef = *block + jpeg_natural_order[k];
  172592. if (*thiscoef != 0) {
  172593. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  172594. if (GET_BITS(1)) {
  172595. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  172596. if (*thiscoef >= 0)
  172597. *thiscoef += p1;
  172598. else
  172599. *thiscoef += m1;
  172600. }
  172601. }
  172602. }
  172603. }
  172604. /* Count one block completed in EOB run */
  172605. EOBRUN--;
  172606. }
  172607. /* Completed MCU, so update state */
  172608. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  172609. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  172610. }
  172611. /* Account for restart interval (no-op if not using restarts) */
  172612. entropy->restarts_to_go--;
  172613. return TRUE;
  172614. undoit:
  172615. /* Re-zero any output coefficients that we made newly nonzero */
  172616. while (num_newnz > 0)
  172617. (*block)[newnz_pos[--num_newnz]] = 0;
  172618. return FALSE;
  172619. }
  172620. /*
  172621. * Module initialization routine for progressive Huffman entropy decoding.
  172622. */
  172623. GLOBAL(void)
  172624. jinit_phuff_decoder (j_decompress_ptr cinfo)
  172625. {
  172626. phuff_entropy_ptr2 entropy;
  172627. int *coef_bit_ptr;
  172628. int ci, i;
  172629. entropy = (phuff_entropy_ptr2)
  172630. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172631. SIZEOF(phuff_entropy_decoder));
  172632. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  172633. entropy->pub.start_pass = start_pass_phuff_decoder;
  172634. /* Mark derived tables unallocated */
  172635. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  172636. entropy->derived_tbls[i] = NULL;
  172637. }
  172638. /* Create progression status table */
  172639. cinfo->coef_bits = (int (*)[DCTSIZE2])
  172640. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172641. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  172642. coef_bit_ptr = & cinfo->coef_bits[0][0];
  172643. for (ci = 0; ci < cinfo->num_components; ci++)
  172644. for (i = 0; i < DCTSIZE2; i++)
  172645. *coef_bit_ptr++ = -1;
  172646. }
  172647. #endif /* D_PROGRESSIVE_SUPPORTED */
  172648. /*** End of inlined file: jdphuff.c ***/
  172649. /*** Start of inlined file: jdpostct.c ***/
  172650. #define JPEG_INTERNALS
  172651. /* Private buffer controller object */
  172652. typedef struct {
  172653. struct jpeg_d_post_controller pub; /* public fields */
  172654. /* Color quantization source buffer: this holds output data from
  172655. * the upsample/color conversion step to be passed to the quantizer.
  172656. * For two-pass color quantization, we need a full-image buffer;
  172657. * for one-pass operation, a strip buffer is sufficient.
  172658. */
  172659. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  172660. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  172661. JDIMENSION strip_height; /* buffer size in rows */
  172662. /* for two-pass mode only: */
  172663. JDIMENSION starting_row; /* row # of first row in current strip */
  172664. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  172665. } my_post_controller;
  172666. typedef my_post_controller * my_post_ptr;
  172667. /* Forward declarations */
  172668. METHODDEF(void) post_process_1pass
  172669. JPP((j_decompress_ptr cinfo,
  172670. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172671. JDIMENSION in_row_groups_avail,
  172672. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172673. JDIMENSION out_rows_avail));
  172674. #ifdef QUANT_2PASS_SUPPORTED
  172675. METHODDEF(void) post_process_prepass
  172676. JPP((j_decompress_ptr cinfo,
  172677. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172678. JDIMENSION in_row_groups_avail,
  172679. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172680. JDIMENSION out_rows_avail));
  172681. METHODDEF(void) post_process_2pass
  172682. JPP((j_decompress_ptr cinfo,
  172683. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172684. JDIMENSION in_row_groups_avail,
  172685. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172686. JDIMENSION out_rows_avail));
  172687. #endif
  172688. /*
  172689. * Initialize for a processing pass.
  172690. */
  172691. METHODDEF(void)
  172692. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  172693. {
  172694. my_post_ptr post = (my_post_ptr) cinfo->post;
  172695. switch (pass_mode) {
  172696. case JBUF_PASS_THRU:
  172697. if (cinfo->quantize_colors) {
  172698. /* Single-pass processing with color quantization. */
  172699. post->pub.post_process_data = post_process_1pass;
  172700. /* We could be doing buffered-image output before starting a 2-pass
  172701. * color quantization; in that case, jinit_d_post_controller did not
  172702. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  172703. */
  172704. if (post->buffer == NULL) {
  172705. post->buffer = (*cinfo->mem->access_virt_sarray)
  172706. ((j_common_ptr) cinfo, post->whole_image,
  172707. (JDIMENSION) 0, post->strip_height, TRUE);
  172708. }
  172709. } else {
  172710. /* For single-pass processing without color quantization,
  172711. * I have no work to do; just call the upsampler directly.
  172712. */
  172713. post->pub.post_process_data = cinfo->upsample->upsample;
  172714. }
  172715. break;
  172716. #ifdef QUANT_2PASS_SUPPORTED
  172717. case JBUF_SAVE_AND_PASS:
  172718. /* First pass of 2-pass quantization */
  172719. if (post->whole_image == NULL)
  172720. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  172721. post->pub.post_process_data = post_process_prepass;
  172722. break;
  172723. case JBUF_CRANK_DEST:
  172724. /* Second pass of 2-pass quantization */
  172725. if (post->whole_image == NULL)
  172726. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  172727. post->pub.post_process_data = post_process_2pass;
  172728. break;
  172729. #endif /* QUANT_2PASS_SUPPORTED */
  172730. default:
  172731. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  172732. break;
  172733. }
  172734. post->starting_row = post->next_row = 0;
  172735. }
  172736. /*
  172737. * Process some data in the one-pass (strip buffer) case.
  172738. * This is used for color precision reduction as well as one-pass quantization.
  172739. */
  172740. METHODDEF(void)
  172741. post_process_1pass (j_decompress_ptr cinfo,
  172742. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172743. JDIMENSION in_row_groups_avail,
  172744. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172745. JDIMENSION out_rows_avail)
  172746. {
  172747. my_post_ptr post = (my_post_ptr) cinfo->post;
  172748. JDIMENSION num_rows, max_rows;
  172749. /* Fill the buffer, but not more than what we can dump out in one go. */
  172750. /* Note we rely on the upsampler to detect bottom of image. */
  172751. max_rows = out_rows_avail - *out_row_ctr;
  172752. if (max_rows > post->strip_height)
  172753. max_rows = post->strip_height;
  172754. num_rows = 0;
  172755. (*cinfo->upsample->upsample) (cinfo,
  172756. input_buf, in_row_group_ctr, in_row_groups_avail,
  172757. post->buffer, &num_rows, max_rows);
  172758. /* Quantize and emit data. */
  172759. (*cinfo->cquantize->color_quantize) (cinfo,
  172760. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  172761. *out_row_ctr += num_rows;
  172762. }
  172763. #ifdef QUANT_2PASS_SUPPORTED
  172764. /*
  172765. * Process some data in the first pass of 2-pass quantization.
  172766. */
  172767. METHODDEF(void)
  172768. post_process_prepass (j_decompress_ptr cinfo,
  172769. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172770. JDIMENSION in_row_groups_avail,
  172771. JSAMPARRAY, JDIMENSION *out_row_ctr,
  172772. JDIMENSION)
  172773. {
  172774. my_post_ptr post = (my_post_ptr) cinfo->post;
  172775. JDIMENSION old_next_row, num_rows;
  172776. /* Reposition virtual buffer if at start of strip. */
  172777. if (post->next_row == 0) {
  172778. post->buffer = (*cinfo->mem->access_virt_sarray)
  172779. ((j_common_ptr) cinfo, post->whole_image,
  172780. post->starting_row, post->strip_height, TRUE);
  172781. }
  172782. /* Upsample some data (up to a strip height's worth). */
  172783. old_next_row = post->next_row;
  172784. (*cinfo->upsample->upsample) (cinfo,
  172785. input_buf, in_row_group_ctr, in_row_groups_avail,
  172786. post->buffer, &post->next_row, post->strip_height);
  172787. /* Allow quantizer to scan new data. No data is emitted, */
  172788. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  172789. if (post->next_row > old_next_row) {
  172790. num_rows = post->next_row - old_next_row;
  172791. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  172792. (JSAMPARRAY) NULL, (int) num_rows);
  172793. *out_row_ctr += num_rows;
  172794. }
  172795. /* Advance if we filled the strip. */
  172796. if (post->next_row >= post->strip_height) {
  172797. post->starting_row += post->strip_height;
  172798. post->next_row = 0;
  172799. }
  172800. }
  172801. /*
  172802. * Process some data in the second pass of 2-pass quantization.
  172803. */
  172804. METHODDEF(void)
  172805. post_process_2pass (j_decompress_ptr cinfo,
  172806. JSAMPIMAGE, JDIMENSION *,
  172807. JDIMENSION,
  172808. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172809. JDIMENSION out_rows_avail)
  172810. {
  172811. my_post_ptr post = (my_post_ptr) cinfo->post;
  172812. JDIMENSION num_rows, max_rows;
  172813. /* Reposition virtual buffer if at start of strip. */
  172814. if (post->next_row == 0) {
  172815. post->buffer = (*cinfo->mem->access_virt_sarray)
  172816. ((j_common_ptr) cinfo, post->whole_image,
  172817. post->starting_row, post->strip_height, FALSE);
  172818. }
  172819. /* Determine number of rows to emit. */
  172820. num_rows = post->strip_height - post->next_row; /* available in strip */
  172821. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  172822. if (num_rows > max_rows)
  172823. num_rows = max_rows;
  172824. /* We have to check bottom of image here, can't depend on upsampler. */
  172825. max_rows = cinfo->output_height - post->starting_row;
  172826. if (num_rows > max_rows)
  172827. num_rows = max_rows;
  172828. /* Quantize and emit data. */
  172829. (*cinfo->cquantize->color_quantize) (cinfo,
  172830. post->buffer + post->next_row, output_buf + *out_row_ctr,
  172831. (int) num_rows);
  172832. *out_row_ctr += num_rows;
  172833. /* Advance if we filled the strip. */
  172834. post->next_row += num_rows;
  172835. if (post->next_row >= post->strip_height) {
  172836. post->starting_row += post->strip_height;
  172837. post->next_row = 0;
  172838. }
  172839. }
  172840. #endif /* QUANT_2PASS_SUPPORTED */
  172841. /*
  172842. * Initialize postprocessing controller.
  172843. */
  172844. GLOBAL(void)
  172845. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  172846. {
  172847. my_post_ptr post;
  172848. post = (my_post_ptr)
  172849. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172850. SIZEOF(my_post_controller));
  172851. cinfo->post = (struct jpeg_d_post_controller *) post;
  172852. post->pub.start_pass = start_pass_dpost;
  172853. post->whole_image = NULL; /* flag for no virtual arrays */
  172854. post->buffer = NULL; /* flag for no strip buffer */
  172855. /* Create the quantization buffer, if needed */
  172856. if (cinfo->quantize_colors) {
  172857. /* The buffer strip height is max_v_samp_factor, which is typically
  172858. * an efficient number of rows for upsampling to return.
  172859. * (In the presence of output rescaling, we might want to be smarter?)
  172860. */
  172861. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  172862. if (need_full_buffer) {
  172863. /* Two-pass color quantization: need full-image storage. */
  172864. /* We round up the number of rows to a multiple of the strip height. */
  172865. #ifdef QUANT_2PASS_SUPPORTED
  172866. post->whole_image = (*cinfo->mem->request_virt_sarray)
  172867. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  172868. cinfo->output_width * cinfo->out_color_components,
  172869. (JDIMENSION) jround_up((long) cinfo->output_height,
  172870. (long) post->strip_height),
  172871. post->strip_height);
  172872. #else
  172873. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  172874. #endif /* QUANT_2PASS_SUPPORTED */
  172875. } else {
  172876. /* One-pass color quantization: just make a strip buffer. */
  172877. post->buffer = (*cinfo->mem->alloc_sarray)
  172878. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172879. cinfo->output_width * cinfo->out_color_components,
  172880. post->strip_height);
  172881. }
  172882. }
  172883. }
  172884. /*** End of inlined file: jdpostct.c ***/
  172885. #undef FIX
  172886. /*** Start of inlined file: jdsample.c ***/
  172887. #define JPEG_INTERNALS
  172888. /* Pointer to routine to upsample a single component */
  172889. typedef JMETHOD(void, upsample1_ptr,
  172890. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  172891. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  172892. /* Private subobject */
  172893. typedef struct {
  172894. struct jpeg_upsampler pub; /* public fields */
  172895. /* Color conversion buffer. When using separate upsampling and color
  172896. * conversion steps, this buffer holds one upsampled row group until it
  172897. * has been color converted and output.
  172898. * Note: we do not allocate any storage for component(s) which are full-size,
  172899. * ie do not need rescaling. The corresponding entry of color_buf[] is
  172900. * simply set to point to the input data array, thereby avoiding copying.
  172901. */
  172902. JSAMPARRAY color_buf[MAX_COMPONENTS];
  172903. /* Per-component upsampling method pointers */
  172904. upsample1_ptr methods[MAX_COMPONENTS];
  172905. int next_row_out; /* counts rows emitted from color_buf */
  172906. JDIMENSION rows_to_go; /* counts rows remaining in image */
  172907. /* Height of an input row group for each component. */
  172908. int rowgroup_height[MAX_COMPONENTS];
  172909. /* These arrays save pixel expansion factors so that int_expand need not
  172910. * recompute them each time. They are unused for other upsampling methods.
  172911. */
  172912. UINT8 h_expand[MAX_COMPONENTS];
  172913. UINT8 v_expand[MAX_COMPONENTS];
  172914. } my_upsampler2;
  172915. typedef my_upsampler2 * my_upsample_ptr2;
  172916. /*
  172917. * Initialize for an upsampling pass.
  172918. */
  172919. METHODDEF(void)
  172920. start_pass_upsample (j_decompress_ptr cinfo)
  172921. {
  172922. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  172923. /* Mark the conversion buffer empty */
  172924. upsample->next_row_out = cinfo->max_v_samp_factor;
  172925. /* Initialize total-height counter for detecting bottom of image */
  172926. upsample->rows_to_go = cinfo->output_height;
  172927. }
  172928. /*
  172929. * Control routine to do upsampling (and color conversion).
  172930. *
  172931. * In this version we upsample each component independently.
  172932. * We upsample one row group into the conversion buffer, then apply
  172933. * color conversion a row at a time.
  172934. */
  172935. METHODDEF(void)
  172936. sep_upsample (j_decompress_ptr cinfo,
  172937. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172938. JDIMENSION,
  172939. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172940. JDIMENSION out_rows_avail)
  172941. {
  172942. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  172943. int ci;
  172944. jpeg_component_info * compptr;
  172945. JDIMENSION num_rows;
  172946. /* Fill the conversion buffer, if it's empty */
  172947. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  172948. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172949. ci++, compptr++) {
  172950. /* Invoke per-component upsample method. Notice we pass a POINTER
  172951. * to color_buf[ci], so that fullsize_upsample can change it.
  172952. */
  172953. (*upsample->methods[ci]) (cinfo, compptr,
  172954. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  172955. upsample->color_buf + ci);
  172956. }
  172957. upsample->next_row_out = 0;
  172958. }
  172959. /* Color-convert and emit rows */
  172960. /* How many we have in the buffer: */
  172961. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  172962. /* Not more than the distance to the end of the image. Need this test
  172963. * in case the image height is not a multiple of max_v_samp_factor:
  172964. */
  172965. if (num_rows > upsample->rows_to_go)
  172966. num_rows = upsample->rows_to_go;
  172967. /* And not more than what the client can accept: */
  172968. out_rows_avail -= *out_row_ctr;
  172969. if (num_rows > out_rows_avail)
  172970. num_rows = out_rows_avail;
  172971. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  172972. (JDIMENSION) upsample->next_row_out,
  172973. output_buf + *out_row_ctr,
  172974. (int) num_rows);
  172975. /* Adjust counts */
  172976. *out_row_ctr += num_rows;
  172977. upsample->rows_to_go -= num_rows;
  172978. upsample->next_row_out += num_rows;
  172979. /* When the buffer is emptied, declare this input row group consumed */
  172980. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  172981. (*in_row_group_ctr)++;
  172982. }
  172983. /*
  172984. * These are the routines invoked by sep_upsample to upsample pixel values
  172985. * of a single component. One row group is processed per call.
  172986. */
  172987. /*
  172988. * For full-size components, we just make color_buf[ci] point at the
  172989. * input buffer, and thus avoid copying any data. Note that this is
  172990. * safe only because sep_upsample doesn't declare the input row group
  172991. * "consumed" until we are done color converting and emitting it.
  172992. */
  172993. METHODDEF(void)
  172994. fullsize_upsample (j_decompress_ptr, jpeg_component_info *,
  172995. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  172996. {
  172997. *output_data_ptr = input_data;
  172998. }
  172999. /*
  173000. * This is a no-op version used for "uninteresting" components.
  173001. * These components will not be referenced by color conversion.
  173002. */
  173003. METHODDEF(void)
  173004. noop_upsample (j_decompress_ptr, jpeg_component_info *,
  173005. JSAMPARRAY, JSAMPARRAY * output_data_ptr)
  173006. {
  173007. *output_data_ptr = NULL; /* safety check */
  173008. }
  173009. /*
  173010. * This version handles any integral sampling ratios.
  173011. * This is not used for typical JPEG files, so it need not be fast.
  173012. * Nor, for that matter, is it particularly accurate: the algorithm is
  173013. * simple replication of the input pixel onto the corresponding output
  173014. * pixels. The hi-falutin sampling literature refers to this as a
  173015. * "box filter". A box filter tends to introduce visible artifacts,
  173016. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  173017. * you would be well advised to improve this code.
  173018. */
  173019. METHODDEF(void)
  173020. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173021. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173022. {
  173023. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173024. JSAMPARRAY output_data = *output_data_ptr;
  173025. register JSAMPROW inptr, outptr;
  173026. register JSAMPLE invalue;
  173027. register int h;
  173028. JSAMPROW outend;
  173029. int h_expand, v_expand;
  173030. int inrow, outrow;
  173031. h_expand = upsample->h_expand[compptr->component_index];
  173032. v_expand = upsample->v_expand[compptr->component_index];
  173033. inrow = outrow = 0;
  173034. while (outrow < cinfo->max_v_samp_factor) {
  173035. /* Generate one output row with proper horizontal expansion */
  173036. inptr = input_data[inrow];
  173037. outptr = output_data[outrow];
  173038. outend = outptr + cinfo->output_width;
  173039. while (outptr < outend) {
  173040. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173041. for (h = h_expand; h > 0; h--) {
  173042. *outptr++ = invalue;
  173043. }
  173044. }
  173045. /* Generate any additional output rows by duplicating the first one */
  173046. if (v_expand > 1) {
  173047. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  173048. v_expand-1, cinfo->output_width);
  173049. }
  173050. inrow++;
  173051. outrow += v_expand;
  173052. }
  173053. }
  173054. /*
  173055. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  173056. * It's still a box filter.
  173057. */
  173058. METHODDEF(void)
  173059. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  173060. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173061. {
  173062. JSAMPARRAY output_data = *output_data_ptr;
  173063. register JSAMPROW inptr, outptr;
  173064. register JSAMPLE invalue;
  173065. JSAMPROW outend;
  173066. int inrow;
  173067. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  173068. inptr = input_data[inrow];
  173069. outptr = output_data[inrow];
  173070. outend = outptr + cinfo->output_width;
  173071. while (outptr < outend) {
  173072. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173073. *outptr++ = invalue;
  173074. *outptr++ = invalue;
  173075. }
  173076. }
  173077. }
  173078. /*
  173079. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  173080. * It's still a box filter.
  173081. */
  173082. METHODDEF(void)
  173083. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  173084. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173085. {
  173086. JSAMPARRAY output_data = *output_data_ptr;
  173087. register JSAMPROW inptr, outptr;
  173088. register JSAMPLE invalue;
  173089. JSAMPROW outend;
  173090. int inrow, outrow;
  173091. inrow = outrow = 0;
  173092. while (outrow < cinfo->max_v_samp_factor) {
  173093. inptr = input_data[inrow];
  173094. outptr = output_data[outrow];
  173095. outend = outptr + cinfo->output_width;
  173096. while (outptr < outend) {
  173097. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173098. *outptr++ = invalue;
  173099. *outptr++ = invalue;
  173100. }
  173101. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  173102. 1, cinfo->output_width);
  173103. inrow++;
  173104. outrow += 2;
  173105. }
  173106. }
  173107. /*
  173108. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  173109. *
  173110. * The upsampling algorithm is linear interpolation between pixel centers,
  173111. * also known as a "triangle filter". This is a good compromise between
  173112. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  173113. * of the way between input pixel centers.
  173114. *
  173115. * A note about the "bias" calculations: when rounding fractional values to
  173116. * integer, we do not want to always round 0.5 up to the next integer.
  173117. * If we did that, we'd introduce a noticeable bias towards larger values.
  173118. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  173119. * alternate pixel locations (a simple ordered dither pattern).
  173120. */
  173121. METHODDEF(void)
  173122. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173123. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173124. {
  173125. JSAMPARRAY output_data = *output_data_ptr;
  173126. register JSAMPROW inptr, outptr;
  173127. register int invalue;
  173128. register JDIMENSION colctr;
  173129. int inrow;
  173130. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  173131. inptr = input_data[inrow];
  173132. outptr = output_data[inrow];
  173133. /* Special case for first column */
  173134. invalue = GETJSAMPLE(*inptr++);
  173135. *outptr++ = (JSAMPLE) invalue;
  173136. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  173137. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  173138. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  173139. invalue = GETJSAMPLE(*inptr++) * 3;
  173140. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  173141. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  173142. }
  173143. /* Special case for last column */
  173144. invalue = GETJSAMPLE(*inptr);
  173145. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  173146. *outptr++ = (JSAMPLE) invalue;
  173147. }
  173148. }
  173149. /*
  173150. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  173151. * Again a triangle filter; see comments for h2v1 case, above.
  173152. *
  173153. * It is OK for us to reference the adjacent input rows because we demanded
  173154. * context from the main buffer controller (see initialization code).
  173155. */
  173156. METHODDEF(void)
  173157. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173158. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173159. {
  173160. JSAMPARRAY output_data = *output_data_ptr;
  173161. register JSAMPROW inptr0, inptr1, outptr;
  173162. #if BITS_IN_JSAMPLE == 8
  173163. register int thiscolsum, lastcolsum, nextcolsum;
  173164. #else
  173165. register INT32 thiscolsum, lastcolsum, nextcolsum;
  173166. #endif
  173167. register JDIMENSION colctr;
  173168. int inrow, outrow, v;
  173169. inrow = outrow = 0;
  173170. while (outrow < cinfo->max_v_samp_factor) {
  173171. for (v = 0; v < 2; v++) {
  173172. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  173173. inptr0 = input_data[inrow];
  173174. if (v == 0) /* next nearest is row above */
  173175. inptr1 = input_data[inrow-1];
  173176. else /* next nearest is row below */
  173177. inptr1 = input_data[inrow+1];
  173178. outptr = output_data[outrow++];
  173179. /* Special case for first column */
  173180. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173181. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173182. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  173183. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  173184. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  173185. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  173186. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  173187. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  173188. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173189. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  173190. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  173191. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  173192. }
  173193. /* Special case for last column */
  173194. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  173195. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  173196. }
  173197. inrow++;
  173198. }
  173199. }
  173200. /*
  173201. * Module initialization routine for upsampling.
  173202. */
  173203. GLOBAL(void)
  173204. jinit_upsampler (j_decompress_ptr cinfo)
  173205. {
  173206. my_upsample_ptr2 upsample;
  173207. int ci;
  173208. jpeg_component_info * compptr;
  173209. boolean need_buffer, do_fancy;
  173210. int h_in_group, v_in_group, h_out_group, v_out_group;
  173211. upsample = (my_upsample_ptr2)
  173212. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173213. SIZEOF(my_upsampler2));
  173214. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  173215. upsample->pub.start_pass = start_pass_upsample;
  173216. upsample->pub.upsample = sep_upsample;
  173217. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  173218. if (cinfo->CCIR601_sampling) /* this isn't supported */
  173219. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  173220. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  173221. * so don't ask for it.
  173222. */
  173223. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  173224. /* Verify we can handle the sampling factors, select per-component methods,
  173225. * and create storage as needed.
  173226. */
  173227. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  173228. ci++, compptr++) {
  173229. /* Compute size of an "input group" after IDCT scaling. This many samples
  173230. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  173231. */
  173232. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  173233. cinfo->min_DCT_scaled_size;
  173234. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  173235. cinfo->min_DCT_scaled_size;
  173236. h_out_group = cinfo->max_h_samp_factor;
  173237. v_out_group = cinfo->max_v_samp_factor;
  173238. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  173239. need_buffer = TRUE;
  173240. if (! compptr->component_needed) {
  173241. /* Don't bother to upsample an uninteresting component. */
  173242. upsample->methods[ci] = noop_upsample;
  173243. need_buffer = FALSE;
  173244. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  173245. /* Fullsize components can be processed without any work. */
  173246. upsample->methods[ci] = fullsize_upsample;
  173247. need_buffer = FALSE;
  173248. } else if (h_in_group * 2 == h_out_group &&
  173249. v_in_group == v_out_group) {
  173250. /* Special cases for 2h1v upsampling */
  173251. if (do_fancy && compptr->downsampled_width > 2)
  173252. upsample->methods[ci] = h2v1_fancy_upsample;
  173253. else
  173254. upsample->methods[ci] = h2v1_upsample;
  173255. } else if (h_in_group * 2 == h_out_group &&
  173256. v_in_group * 2 == v_out_group) {
  173257. /* Special cases for 2h2v upsampling */
  173258. if (do_fancy && compptr->downsampled_width > 2) {
  173259. upsample->methods[ci] = h2v2_fancy_upsample;
  173260. upsample->pub.need_context_rows = TRUE;
  173261. } else
  173262. upsample->methods[ci] = h2v2_upsample;
  173263. } else if ((h_out_group % h_in_group) == 0 &&
  173264. (v_out_group % v_in_group) == 0) {
  173265. /* Generic integral-factors upsampling method */
  173266. upsample->methods[ci] = int_upsample;
  173267. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  173268. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  173269. } else
  173270. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  173271. if (need_buffer) {
  173272. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  173273. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173274. (JDIMENSION) jround_up((long) cinfo->output_width,
  173275. (long) cinfo->max_h_samp_factor),
  173276. (JDIMENSION) cinfo->max_v_samp_factor);
  173277. }
  173278. }
  173279. }
  173280. /*** End of inlined file: jdsample.c ***/
  173281. /*** Start of inlined file: jdtrans.c ***/
  173282. #define JPEG_INTERNALS
  173283. /* Forward declarations */
  173284. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  173285. /*
  173286. * Read the coefficient arrays from a JPEG file.
  173287. * jpeg_read_header must be completed before calling this.
  173288. *
  173289. * The entire image is read into a set of virtual coefficient-block arrays,
  173290. * one per component. The return value is a pointer to the array of
  173291. * virtual-array descriptors. These can be manipulated directly via the
  173292. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  173293. * To release the memory occupied by the virtual arrays, call
  173294. * jpeg_finish_decompress() when done with the data.
  173295. *
  173296. * An alternative usage is to simply obtain access to the coefficient arrays
  173297. * during a buffered-image-mode decompression operation. This is allowed
  173298. * after any jpeg_finish_output() call. The arrays can be accessed until
  173299. * jpeg_finish_decompress() is called. (Note that any call to the library
  173300. * may reposition the arrays, so don't rely on access_virt_barray() results
  173301. * to stay valid across library calls.)
  173302. *
  173303. * Returns NULL if suspended. This case need be checked only if
  173304. * a suspending data source is used.
  173305. */
  173306. GLOBAL(jvirt_barray_ptr *)
  173307. jpeg_read_coefficients (j_decompress_ptr cinfo)
  173308. {
  173309. if (cinfo->global_state == DSTATE_READY) {
  173310. /* First call: initialize active modules */
  173311. transdecode_master_selection(cinfo);
  173312. cinfo->global_state = DSTATE_RDCOEFS;
  173313. }
  173314. if (cinfo->global_state == DSTATE_RDCOEFS) {
  173315. /* Absorb whole file into the coef buffer */
  173316. for (;;) {
  173317. int retcode;
  173318. /* Call progress monitor hook if present */
  173319. if (cinfo->progress != NULL)
  173320. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  173321. /* Absorb some more input */
  173322. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  173323. if (retcode == JPEG_SUSPENDED)
  173324. return NULL;
  173325. if (retcode == JPEG_REACHED_EOI)
  173326. break;
  173327. /* Advance progress counter if appropriate */
  173328. if (cinfo->progress != NULL &&
  173329. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  173330. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  173331. /* startup underestimated number of scans; ratchet up one scan */
  173332. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  173333. }
  173334. }
  173335. }
  173336. /* Set state so that jpeg_finish_decompress does the right thing */
  173337. cinfo->global_state = DSTATE_STOPPING;
  173338. }
  173339. /* At this point we should be in state DSTATE_STOPPING if being used
  173340. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  173341. * to the coefficients during a full buffered-image-mode decompression.
  173342. */
  173343. if ((cinfo->global_state == DSTATE_STOPPING ||
  173344. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  173345. return cinfo->coef->coef_arrays;
  173346. }
  173347. /* Oops, improper usage */
  173348. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  173349. return NULL; /* keep compiler happy */
  173350. }
  173351. /*
  173352. * Master selection of decompression modules for transcoding.
  173353. * This substitutes for jdmaster.c's initialization of the full decompressor.
  173354. */
  173355. LOCAL(void)
  173356. transdecode_master_selection (j_decompress_ptr cinfo)
  173357. {
  173358. /* This is effectively a buffered-image operation. */
  173359. cinfo->buffered_image = TRUE;
  173360. /* Entropy decoding: either Huffman or arithmetic coding. */
  173361. if (cinfo->arith_code) {
  173362. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  173363. } else {
  173364. if (cinfo->progressive_mode) {
  173365. #ifdef D_PROGRESSIVE_SUPPORTED
  173366. jinit_phuff_decoder(cinfo);
  173367. #else
  173368. ERREXIT(cinfo, JERR_NOT_COMPILED);
  173369. #endif
  173370. } else
  173371. jinit_huff_decoder(cinfo);
  173372. }
  173373. /* Always get a full-image coefficient buffer. */
  173374. jinit_d_coef_controller(cinfo, TRUE);
  173375. /* We can now tell the memory manager to allocate virtual arrays. */
  173376. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  173377. /* Initialize input side of decompressor to consume first scan. */
  173378. (*cinfo->inputctl->start_input_pass) (cinfo);
  173379. /* Initialize progress monitoring. */
  173380. if (cinfo->progress != NULL) {
  173381. int nscans;
  173382. /* Estimate number of scans to set pass_limit. */
  173383. if (cinfo->progressive_mode) {
  173384. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  173385. nscans = 2 + 3 * cinfo->num_components;
  173386. } else if (cinfo->inputctl->has_multiple_scans) {
  173387. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  173388. nscans = cinfo->num_components;
  173389. } else {
  173390. nscans = 1;
  173391. }
  173392. cinfo->progress->pass_counter = 0L;
  173393. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  173394. cinfo->progress->completed_passes = 0;
  173395. cinfo->progress->total_passes = 1;
  173396. }
  173397. }
  173398. /*** End of inlined file: jdtrans.c ***/
  173399. /*** Start of inlined file: jfdctflt.c ***/
  173400. #define JPEG_INTERNALS
  173401. #ifdef DCT_FLOAT_SUPPORTED
  173402. /*
  173403. * This module is specialized to the case DCTSIZE = 8.
  173404. */
  173405. #if DCTSIZE != 8
  173406. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  173407. #endif
  173408. /*
  173409. * Perform the forward DCT on one block of samples.
  173410. */
  173411. GLOBAL(void)
  173412. jpeg_fdct_float (FAST_FLOAT * data)
  173413. {
  173414. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  173415. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  173416. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  173417. FAST_FLOAT *dataptr;
  173418. int ctr;
  173419. /* Pass 1: process rows. */
  173420. dataptr = data;
  173421. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  173422. tmp0 = dataptr[0] + dataptr[7];
  173423. tmp7 = dataptr[0] - dataptr[7];
  173424. tmp1 = dataptr[1] + dataptr[6];
  173425. tmp6 = dataptr[1] - dataptr[6];
  173426. tmp2 = dataptr[2] + dataptr[5];
  173427. tmp5 = dataptr[2] - dataptr[5];
  173428. tmp3 = dataptr[3] + dataptr[4];
  173429. tmp4 = dataptr[3] - dataptr[4];
  173430. /* Even part */
  173431. tmp10 = tmp0 + tmp3; /* phase 2 */
  173432. tmp13 = tmp0 - tmp3;
  173433. tmp11 = tmp1 + tmp2;
  173434. tmp12 = tmp1 - tmp2;
  173435. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  173436. dataptr[4] = tmp10 - tmp11;
  173437. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  173438. dataptr[2] = tmp13 + z1; /* phase 5 */
  173439. dataptr[6] = tmp13 - z1;
  173440. /* Odd part */
  173441. tmp10 = tmp4 + tmp5; /* phase 2 */
  173442. tmp11 = tmp5 + tmp6;
  173443. tmp12 = tmp6 + tmp7;
  173444. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  173445. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  173446. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  173447. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  173448. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  173449. z11 = tmp7 + z3; /* phase 5 */
  173450. z13 = tmp7 - z3;
  173451. dataptr[5] = z13 + z2; /* phase 6 */
  173452. dataptr[3] = z13 - z2;
  173453. dataptr[1] = z11 + z4;
  173454. dataptr[7] = z11 - z4;
  173455. dataptr += DCTSIZE; /* advance pointer to next row */
  173456. }
  173457. /* Pass 2: process columns. */
  173458. dataptr = data;
  173459. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  173460. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  173461. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  173462. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  173463. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  173464. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  173465. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  173466. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  173467. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  173468. /* Even part */
  173469. tmp10 = tmp0 + tmp3; /* phase 2 */
  173470. tmp13 = tmp0 - tmp3;
  173471. tmp11 = tmp1 + tmp2;
  173472. tmp12 = tmp1 - tmp2;
  173473. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  173474. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  173475. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  173476. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  173477. dataptr[DCTSIZE*6] = tmp13 - z1;
  173478. /* Odd part */
  173479. tmp10 = tmp4 + tmp5; /* phase 2 */
  173480. tmp11 = tmp5 + tmp6;
  173481. tmp12 = tmp6 + tmp7;
  173482. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  173483. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  173484. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  173485. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  173486. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  173487. z11 = tmp7 + z3; /* phase 5 */
  173488. z13 = tmp7 - z3;
  173489. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  173490. dataptr[DCTSIZE*3] = z13 - z2;
  173491. dataptr[DCTSIZE*1] = z11 + z4;
  173492. dataptr[DCTSIZE*7] = z11 - z4;
  173493. dataptr++; /* advance pointer to next column */
  173494. }
  173495. }
  173496. #endif /* DCT_FLOAT_SUPPORTED */
  173497. /*** End of inlined file: jfdctflt.c ***/
  173498. /*** Start of inlined file: jfdctint.c ***/
  173499. #define JPEG_INTERNALS
  173500. #ifdef DCT_ISLOW_SUPPORTED
  173501. /*
  173502. * This module is specialized to the case DCTSIZE = 8.
  173503. */
  173504. #if DCTSIZE != 8
  173505. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  173506. #endif
  173507. /*
  173508. * The poop on this scaling stuff is as follows:
  173509. *
  173510. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  173511. * larger than the true DCT outputs. The final outputs are therefore
  173512. * a factor of N larger than desired; since N=8 this can be cured by
  173513. * a simple right shift at the end of the algorithm. The advantage of
  173514. * this arrangement is that we save two multiplications per 1-D DCT,
  173515. * because the y0 and y4 outputs need not be divided by sqrt(N).
  173516. * In the IJG code, this factor of 8 is removed by the quantization step
  173517. * (in jcdctmgr.c), NOT in this module.
  173518. *
  173519. * We have to do addition and subtraction of the integer inputs, which
  173520. * is no problem, and multiplication by fractional constants, which is
  173521. * a problem to do in integer arithmetic. We multiply all the constants
  173522. * by CONST_SCALE and convert them to integer constants (thus retaining
  173523. * CONST_BITS bits of precision in the constants). After doing a
  173524. * multiplication we have to divide the product by CONST_SCALE, with proper
  173525. * rounding, to produce the correct output. This division can be done
  173526. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  173527. * as long as possible so that partial sums can be added together with
  173528. * full fractional precision.
  173529. *
  173530. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  173531. * they are represented to better-than-integral precision. These outputs
  173532. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  173533. * with the recommended scaling. (For 12-bit sample data, the intermediate
  173534. * array is INT32 anyway.)
  173535. *
  173536. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  173537. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  173538. * shows that the values given below are the most effective.
  173539. */
  173540. #if BITS_IN_JSAMPLE == 8
  173541. #define CONST_BITS 13
  173542. #define PASS1_BITS 2
  173543. #else
  173544. #define CONST_BITS 13
  173545. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  173546. #endif
  173547. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  173548. * causing a lot of useless floating-point operations at run time.
  173549. * To get around this we use the following pre-calculated constants.
  173550. * If you change CONST_BITS you may want to add appropriate values.
  173551. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  173552. */
  173553. #if CONST_BITS == 13
  173554. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  173555. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  173556. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  173557. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  173558. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  173559. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  173560. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  173561. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  173562. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  173563. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  173564. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  173565. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  173566. #else
  173567. #define FIX_0_298631336 FIX(0.298631336)
  173568. #define FIX_0_390180644 FIX(0.390180644)
  173569. #define FIX_0_541196100 FIX(0.541196100)
  173570. #define FIX_0_765366865 FIX(0.765366865)
  173571. #define FIX_0_899976223 FIX(0.899976223)
  173572. #define FIX_1_175875602 FIX(1.175875602)
  173573. #define FIX_1_501321110 FIX(1.501321110)
  173574. #define FIX_1_847759065 FIX(1.847759065)
  173575. #define FIX_1_961570560 FIX(1.961570560)
  173576. #define FIX_2_053119869 FIX(2.053119869)
  173577. #define FIX_2_562915447 FIX(2.562915447)
  173578. #define FIX_3_072711026 FIX(3.072711026)
  173579. #endif
  173580. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  173581. * For 8-bit samples with the recommended scaling, all the variable
  173582. * and constant values involved are no more than 16 bits wide, so a
  173583. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  173584. * For 12-bit samples, a full 32-bit multiplication will be needed.
  173585. */
  173586. #if BITS_IN_JSAMPLE == 8
  173587. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  173588. #else
  173589. #define MULTIPLY(var,const) ((var) * (const))
  173590. #endif
  173591. /*
  173592. * Perform the forward DCT on one block of samples.
  173593. */
  173594. GLOBAL(void)
  173595. jpeg_fdct_islow (DCTELEM * data)
  173596. {
  173597. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  173598. INT32 tmp10, tmp11, tmp12, tmp13;
  173599. INT32 z1, z2, z3, z4, z5;
  173600. DCTELEM *dataptr;
  173601. int ctr;
  173602. SHIFT_TEMPS
  173603. /* Pass 1: process rows. */
  173604. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  173605. /* furthermore, we scale the results by 2**PASS1_BITS. */
  173606. dataptr = data;
  173607. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  173608. tmp0 = dataptr[0] + dataptr[7];
  173609. tmp7 = dataptr[0] - dataptr[7];
  173610. tmp1 = dataptr[1] + dataptr[6];
  173611. tmp6 = dataptr[1] - dataptr[6];
  173612. tmp2 = dataptr[2] + dataptr[5];
  173613. tmp5 = dataptr[2] - dataptr[5];
  173614. tmp3 = dataptr[3] + dataptr[4];
  173615. tmp4 = dataptr[3] - dataptr[4];
  173616. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  173617. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  173618. */
  173619. tmp10 = tmp0 + tmp3;
  173620. tmp13 = tmp0 - tmp3;
  173621. tmp11 = tmp1 + tmp2;
  173622. tmp12 = tmp1 - tmp2;
  173623. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  173624. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  173625. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  173626. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  173627. CONST_BITS-PASS1_BITS);
  173628. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  173629. CONST_BITS-PASS1_BITS);
  173630. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  173631. * cK represents cos(K*pi/16).
  173632. * i0..i3 in the paper are tmp4..tmp7 here.
  173633. */
  173634. z1 = tmp4 + tmp7;
  173635. z2 = tmp5 + tmp6;
  173636. z3 = tmp4 + tmp6;
  173637. z4 = tmp5 + tmp7;
  173638. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  173639. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  173640. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  173641. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  173642. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  173643. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  173644. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  173645. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  173646. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  173647. z3 += z5;
  173648. z4 += z5;
  173649. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  173650. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  173651. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  173652. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  173653. dataptr += DCTSIZE; /* advance pointer to next row */
  173654. }
  173655. /* Pass 2: process columns.
  173656. * We remove the PASS1_BITS scaling, but leave the results scaled up
  173657. * by an overall factor of 8.
  173658. */
  173659. dataptr = data;
  173660. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  173661. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  173662. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  173663. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  173664. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  173665. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  173666. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  173667. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  173668. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  173669. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  173670. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  173671. */
  173672. tmp10 = tmp0 + tmp3;
  173673. tmp13 = tmp0 - tmp3;
  173674. tmp11 = tmp1 + tmp2;
  173675. tmp12 = tmp1 - tmp2;
  173676. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  173677. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  173678. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  173679. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  173680. CONST_BITS+PASS1_BITS);
  173681. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  173682. CONST_BITS+PASS1_BITS);
  173683. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  173684. * cK represents cos(K*pi/16).
  173685. * i0..i3 in the paper are tmp4..tmp7 here.
  173686. */
  173687. z1 = tmp4 + tmp7;
  173688. z2 = tmp5 + tmp6;
  173689. z3 = tmp4 + tmp6;
  173690. z4 = tmp5 + tmp7;
  173691. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  173692. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  173693. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  173694. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  173695. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  173696. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  173697. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  173698. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  173699. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  173700. z3 += z5;
  173701. z4 += z5;
  173702. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  173703. CONST_BITS+PASS1_BITS);
  173704. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  173705. CONST_BITS+PASS1_BITS);
  173706. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  173707. CONST_BITS+PASS1_BITS);
  173708. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  173709. CONST_BITS+PASS1_BITS);
  173710. dataptr++; /* advance pointer to next column */
  173711. }
  173712. }
  173713. #endif /* DCT_ISLOW_SUPPORTED */
  173714. /*** End of inlined file: jfdctint.c ***/
  173715. #undef CONST_BITS
  173716. #undef MULTIPLY
  173717. #undef FIX_0_541196100
  173718. /*** Start of inlined file: jfdctfst.c ***/
  173719. #define JPEG_INTERNALS
  173720. #ifdef DCT_IFAST_SUPPORTED
  173721. /*
  173722. * This module is specialized to the case DCTSIZE = 8.
  173723. */
  173724. #if DCTSIZE != 8
  173725. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  173726. #endif
  173727. /* Scaling decisions are generally the same as in the LL&M algorithm;
  173728. * see jfdctint.c for more details. However, we choose to descale
  173729. * (right shift) multiplication products as soon as they are formed,
  173730. * rather than carrying additional fractional bits into subsequent additions.
  173731. * This compromises accuracy slightly, but it lets us save a few shifts.
  173732. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  173733. * everywhere except in the multiplications proper; this saves a good deal
  173734. * of work on 16-bit-int machines.
  173735. *
  173736. * Again to save a few shifts, the intermediate results between pass 1 and
  173737. * pass 2 are not upscaled, but are represented only to integral precision.
  173738. *
  173739. * A final compromise is to represent the multiplicative constants to only
  173740. * 8 fractional bits, rather than 13. This saves some shifting work on some
  173741. * machines, and may also reduce the cost of multiplication (since there
  173742. * are fewer one-bits in the constants).
  173743. */
  173744. #define CONST_BITS 8
  173745. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  173746. * causing a lot of useless floating-point operations at run time.
  173747. * To get around this we use the following pre-calculated constants.
  173748. * If you change CONST_BITS you may want to add appropriate values.
  173749. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  173750. */
  173751. #if CONST_BITS == 8
  173752. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  173753. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  173754. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  173755. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  173756. #else
  173757. #define FIX_0_382683433 FIX(0.382683433)
  173758. #define FIX_0_541196100 FIX(0.541196100)
  173759. #define FIX_0_707106781 FIX(0.707106781)
  173760. #define FIX_1_306562965 FIX(1.306562965)
  173761. #endif
  173762. /* We can gain a little more speed, with a further compromise in accuracy,
  173763. * by omitting the addition in a descaling shift. This yields an incorrectly
  173764. * rounded result half the time...
  173765. */
  173766. #ifndef USE_ACCURATE_ROUNDING
  173767. #undef DESCALE
  173768. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  173769. #endif
  173770. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  173771. * descale to yield a DCTELEM result.
  173772. */
  173773. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  173774. /*
  173775. * Perform the forward DCT on one block of samples.
  173776. */
  173777. GLOBAL(void)
  173778. jpeg_fdct_ifast (DCTELEM * data)
  173779. {
  173780. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  173781. DCTELEM tmp10, tmp11, tmp12, tmp13;
  173782. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  173783. DCTELEM *dataptr;
  173784. int ctr;
  173785. SHIFT_TEMPS
  173786. /* Pass 1: process rows. */
  173787. dataptr = data;
  173788. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  173789. tmp0 = dataptr[0] + dataptr[7];
  173790. tmp7 = dataptr[0] - dataptr[7];
  173791. tmp1 = dataptr[1] + dataptr[6];
  173792. tmp6 = dataptr[1] - dataptr[6];
  173793. tmp2 = dataptr[2] + dataptr[5];
  173794. tmp5 = dataptr[2] - dataptr[5];
  173795. tmp3 = dataptr[3] + dataptr[4];
  173796. tmp4 = dataptr[3] - dataptr[4];
  173797. /* Even part */
  173798. tmp10 = tmp0 + tmp3; /* phase 2 */
  173799. tmp13 = tmp0 - tmp3;
  173800. tmp11 = tmp1 + tmp2;
  173801. tmp12 = tmp1 - tmp2;
  173802. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  173803. dataptr[4] = tmp10 - tmp11;
  173804. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  173805. dataptr[2] = tmp13 + z1; /* phase 5 */
  173806. dataptr[6] = tmp13 - z1;
  173807. /* Odd part */
  173808. tmp10 = tmp4 + tmp5; /* phase 2 */
  173809. tmp11 = tmp5 + tmp6;
  173810. tmp12 = tmp6 + tmp7;
  173811. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  173812. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  173813. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  173814. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  173815. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  173816. z11 = tmp7 + z3; /* phase 5 */
  173817. z13 = tmp7 - z3;
  173818. dataptr[5] = z13 + z2; /* phase 6 */
  173819. dataptr[3] = z13 - z2;
  173820. dataptr[1] = z11 + z4;
  173821. dataptr[7] = z11 - z4;
  173822. dataptr += DCTSIZE; /* advance pointer to next row */
  173823. }
  173824. /* Pass 2: process columns. */
  173825. dataptr = data;
  173826. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  173827. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  173828. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  173829. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  173830. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  173831. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  173832. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  173833. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  173834. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  173835. /* Even part */
  173836. tmp10 = tmp0 + tmp3; /* phase 2 */
  173837. tmp13 = tmp0 - tmp3;
  173838. tmp11 = tmp1 + tmp2;
  173839. tmp12 = tmp1 - tmp2;
  173840. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  173841. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  173842. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  173843. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  173844. dataptr[DCTSIZE*6] = tmp13 - z1;
  173845. /* Odd part */
  173846. tmp10 = tmp4 + tmp5; /* phase 2 */
  173847. tmp11 = tmp5 + tmp6;
  173848. tmp12 = tmp6 + tmp7;
  173849. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  173850. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  173851. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  173852. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  173853. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  173854. z11 = tmp7 + z3; /* phase 5 */
  173855. z13 = tmp7 - z3;
  173856. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  173857. dataptr[DCTSIZE*3] = z13 - z2;
  173858. dataptr[DCTSIZE*1] = z11 + z4;
  173859. dataptr[DCTSIZE*7] = z11 - z4;
  173860. dataptr++; /* advance pointer to next column */
  173861. }
  173862. }
  173863. #endif /* DCT_IFAST_SUPPORTED */
  173864. /*** End of inlined file: jfdctfst.c ***/
  173865. #undef FIX_0_541196100
  173866. /*** Start of inlined file: jidctflt.c ***/
  173867. #define JPEG_INTERNALS
  173868. #ifdef DCT_FLOAT_SUPPORTED
  173869. /*
  173870. * This module is specialized to the case DCTSIZE = 8.
  173871. */
  173872. #if DCTSIZE != 8
  173873. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  173874. #endif
  173875. /* Dequantize a coefficient by multiplying it by the multiplier-table
  173876. * entry; produce a float result.
  173877. */
  173878. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  173879. /*
  173880. * Perform dequantization and inverse DCT on one block of coefficients.
  173881. */
  173882. GLOBAL(void)
  173883. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173884. JCOEFPTR coef_block,
  173885. JSAMPARRAY output_buf, JDIMENSION output_col)
  173886. {
  173887. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  173888. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  173889. FAST_FLOAT z5, z10, z11, z12, z13;
  173890. JCOEFPTR inptr;
  173891. FLOAT_MULT_TYPE * quantptr;
  173892. FAST_FLOAT * wsptr;
  173893. JSAMPROW outptr;
  173894. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  173895. int ctr;
  173896. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  173897. SHIFT_TEMPS
  173898. /* Pass 1: process columns from input, store into work array. */
  173899. inptr = coef_block;
  173900. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  173901. wsptr = workspace;
  173902. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  173903. /* Due to quantization, we will usually find that many of the input
  173904. * coefficients are zero, especially the AC terms. We can exploit this
  173905. * by short-circuiting the IDCT calculation for any column in which all
  173906. * the AC terms are zero. In that case each output is equal to the
  173907. * DC coefficient (with scale factor as needed).
  173908. * With typical images and quantization tables, half or more of the
  173909. * column DCT calculations can be simplified this way.
  173910. */
  173911. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  173912. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  173913. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  173914. inptr[DCTSIZE*7] == 0) {
  173915. /* AC terms all zero */
  173916. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  173917. wsptr[DCTSIZE*0] = dcval;
  173918. wsptr[DCTSIZE*1] = dcval;
  173919. wsptr[DCTSIZE*2] = dcval;
  173920. wsptr[DCTSIZE*3] = dcval;
  173921. wsptr[DCTSIZE*4] = dcval;
  173922. wsptr[DCTSIZE*5] = dcval;
  173923. wsptr[DCTSIZE*6] = dcval;
  173924. wsptr[DCTSIZE*7] = dcval;
  173925. inptr++; /* advance pointers to next column */
  173926. quantptr++;
  173927. wsptr++;
  173928. continue;
  173929. }
  173930. /* Even part */
  173931. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  173932. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  173933. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  173934. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  173935. tmp10 = tmp0 + tmp2; /* phase 3 */
  173936. tmp11 = tmp0 - tmp2;
  173937. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  173938. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  173939. tmp0 = tmp10 + tmp13; /* phase 2 */
  173940. tmp3 = tmp10 - tmp13;
  173941. tmp1 = tmp11 + tmp12;
  173942. tmp2 = tmp11 - tmp12;
  173943. /* Odd part */
  173944. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  173945. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  173946. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  173947. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  173948. z13 = tmp6 + tmp5; /* phase 6 */
  173949. z10 = tmp6 - tmp5;
  173950. z11 = tmp4 + tmp7;
  173951. z12 = tmp4 - tmp7;
  173952. tmp7 = z11 + z13; /* phase 5 */
  173953. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  173954. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  173955. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  173956. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  173957. tmp6 = tmp12 - tmp7; /* phase 2 */
  173958. tmp5 = tmp11 - tmp6;
  173959. tmp4 = tmp10 + tmp5;
  173960. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  173961. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  173962. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  173963. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  173964. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  173965. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  173966. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  173967. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  173968. inptr++; /* advance pointers to next column */
  173969. quantptr++;
  173970. wsptr++;
  173971. }
  173972. /* Pass 2: process rows from work array, store into output array. */
  173973. /* Note that we must descale the results by a factor of 8 == 2**3. */
  173974. wsptr = workspace;
  173975. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  173976. outptr = output_buf[ctr] + output_col;
  173977. /* Rows of zeroes can be exploited in the same way as we did with columns.
  173978. * However, the column calculation has created many nonzero AC terms, so
  173979. * the simplification applies less often (typically 5% to 10% of the time).
  173980. * And testing floats for zero is relatively expensive, so we don't bother.
  173981. */
  173982. /* Even part */
  173983. tmp10 = wsptr[0] + wsptr[4];
  173984. tmp11 = wsptr[0] - wsptr[4];
  173985. tmp13 = wsptr[2] + wsptr[6];
  173986. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  173987. tmp0 = tmp10 + tmp13;
  173988. tmp3 = tmp10 - tmp13;
  173989. tmp1 = tmp11 + tmp12;
  173990. tmp2 = tmp11 - tmp12;
  173991. /* Odd part */
  173992. z13 = wsptr[5] + wsptr[3];
  173993. z10 = wsptr[5] - wsptr[3];
  173994. z11 = wsptr[1] + wsptr[7];
  173995. z12 = wsptr[1] - wsptr[7];
  173996. tmp7 = z11 + z13;
  173997. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  173998. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  173999. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  174000. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  174001. tmp6 = tmp12 - tmp7;
  174002. tmp5 = tmp11 - tmp6;
  174003. tmp4 = tmp10 + tmp5;
  174004. /* Final output stage: scale down by a factor of 8 and range-limit */
  174005. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  174006. & RANGE_MASK];
  174007. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  174008. & RANGE_MASK];
  174009. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  174010. & RANGE_MASK];
  174011. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  174012. & RANGE_MASK];
  174013. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  174014. & RANGE_MASK];
  174015. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  174016. & RANGE_MASK];
  174017. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  174018. & RANGE_MASK];
  174019. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  174020. & RANGE_MASK];
  174021. wsptr += DCTSIZE; /* advance pointer to next row */
  174022. }
  174023. }
  174024. #endif /* DCT_FLOAT_SUPPORTED */
  174025. /*** End of inlined file: jidctflt.c ***/
  174026. #undef CONST_BITS
  174027. #undef FIX_1_847759065
  174028. #undef MULTIPLY
  174029. #undef DEQUANTIZE
  174030. #undef DESCALE
  174031. /*** Start of inlined file: jidctfst.c ***/
  174032. #define JPEG_INTERNALS
  174033. #ifdef DCT_IFAST_SUPPORTED
  174034. /*
  174035. * This module is specialized to the case DCTSIZE = 8.
  174036. */
  174037. #if DCTSIZE != 8
  174038. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174039. #endif
  174040. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174041. * see jidctint.c for more details. However, we choose to descale
  174042. * (right shift) multiplication products as soon as they are formed,
  174043. * rather than carrying additional fractional bits into subsequent additions.
  174044. * This compromises accuracy slightly, but it lets us save a few shifts.
  174045. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174046. * everywhere except in the multiplications proper; this saves a good deal
  174047. * of work on 16-bit-int machines.
  174048. *
  174049. * The dequantized coefficients are not integers because the AA&N scaling
  174050. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  174051. * so that the first and second IDCT rounds have the same input scaling.
  174052. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  174053. * avoid a descaling shift; this compromises accuracy rather drastically
  174054. * for small quantization table entries, but it saves a lot of shifts.
  174055. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  174056. * so we use a much larger scaling factor to preserve accuracy.
  174057. *
  174058. * A final compromise is to represent the multiplicative constants to only
  174059. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174060. * machines, and may also reduce the cost of multiplication (since there
  174061. * are fewer one-bits in the constants).
  174062. */
  174063. #if BITS_IN_JSAMPLE == 8
  174064. #define CONST_BITS 8
  174065. #define PASS1_BITS 2
  174066. #else
  174067. #define CONST_BITS 8
  174068. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174069. #endif
  174070. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174071. * causing a lot of useless floating-point operations at run time.
  174072. * To get around this we use the following pre-calculated constants.
  174073. * If you change CONST_BITS you may want to add appropriate values.
  174074. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174075. */
  174076. #if CONST_BITS == 8
  174077. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  174078. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  174079. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  174080. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  174081. #else
  174082. #define FIX_1_082392200 FIX(1.082392200)
  174083. #define FIX_1_414213562 FIX(1.414213562)
  174084. #define FIX_1_847759065 FIX(1.847759065)
  174085. #define FIX_2_613125930 FIX(2.613125930)
  174086. #endif
  174087. /* We can gain a little more speed, with a further compromise in accuracy,
  174088. * by omitting the addition in a descaling shift. This yields an incorrectly
  174089. * rounded result half the time...
  174090. */
  174091. #ifndef USE_ACCURATE_ROUNDING
  174092. #undef DESCALE
  174093. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  174094. #endif
  174095. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  174096. * descale to yield a DCTELEM result.
  174097. */
  174098. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  174099. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174100. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  174101. * multiplication will do. For 12-bit data, the multiplier table is
  174102. * declared INT32, so a 32-bit multiply will be used.
  174103. */
  174104. #if BITS_IN_JSAMPLE == 8
  174105. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  174106. #else
  174107. #define DEQUANTIZE(coef,quantval) \
  174108. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  174109. #endif
  174110. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  174111. * We assume that int right shift is unsigned if INT32 right shift is.
  174112. */
  174113. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  174114. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  174115. #if BITS_IN_JSAMPLE == 8
  174116. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  174117. #else
  174118. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  174119. #endif
  174120. #define IRIGHT_SHIFT(x,shft) \
  174121. ((ishift_temp = (x)) < 0 ? \
  174122. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  174123. (ishift_temp >> (shft)))
  174124. #else
  174125. #define ISHIFT_TEMPS
  174126. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  174127. #endif
  174128. #ifdef USE_ACCURATE_ROUNDING
  174129. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  174130. #else
  174131. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  174132. #endif
  174133. /*
  174134. * Perform dequantization and inverse DCT on one block of coefficients.
  174135. */
  174136. GLOBAL(void)
  174137. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174138. JCOEFPTR coef_block,
  174139. JSAMPARRAY output_buf, JDIMENSION output_col)
  174140. {
  174141. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174142. DCTELEM tmp10, tmp11, tmp12, tmp13;
  174143. DCTELEM z5, z10, z11, z12, z13;
  174144. JCOEFPTR inptr;
  174145. IFAST_MULT_TYPE * quantptr;
  174146. int * wsptr;
  174147. JSAMPROW outptr;
  174148. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174149. int ctr;
  174150. int workspace[DCTSIZE2]; /* buffers data between passes */
  174151. SHIFT_TEMPS /* for DESCALE */
  174152. ISHIFT_TEMPS /* for IDESCALE */
  174153. /* Pass 1: process columns from input, store into work array. */
  174154. inptr = coef_block;
  174155. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  174156. wsptr = workspace;
  174157. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174158. /* Due to quantization, we will usually find that many of the input
  174159. * coefficients are zero, especially the AC terms. We can exploit this
  174160. * by short-circuiting the IDCT calculation for any column in which all
  174161. * the AC terms are zero. In that case each output is equal to the
  174162. * DC coefficient (with scale factor as needed).
  174163. * With typical images and quantization tables, half or more of the
  174164. * column DCT calculations can be simplified this way.
  174165. */
  174166. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174167. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174168. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174169. inptr[DCTSIZE*7] == 0) {
  174170. /* AC terms all zero */
  174171. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174172. wsptr[DCTSIZE*0] = dcval;
  174173. wsptr[DCTSIZE*1] = dcval;
  174174. wsptr[DCTSIZE*2] = dcval;
  174175. wsptr[DCTSIZE*3] = dcval;
  174176. wsptr[DCTSIZE*4] = dcval;
  174177. wsptr[DCTSIZE*5] = dcval;
  174178. wsptr[DCTSIZE*6] = dcval;
  174179. wsptr[DCTSIZE*7] = dcval;
  174180. inptr++; /* advance pointers to next column */
  174181. quantptr++;
  174182. wsptr++;
  174183. continue;
  174184. }
  174185. /* Even part */
  174186. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174187. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174188. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  174189. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174190. tmp10 = tmp0 + tmp2; /* phase 3 */
  174191. tmp11 = tmp0 - tmp2;
  174192. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  174193. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  174194. tmp0 = tmp10 + tmp13; /* phase 2 */
  174195. tmp3 = tmp10 - tmp13;
  174196. tmp1 = tmp11 + tmp12;
  174197. tmp2 = tmp11 - tmp12;
  174198. /* Odd part */
  174199. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174200. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174201. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174202. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174203. z13 = tmp6 + tmp5; /* phase 6 */
  174204. z10 = tmp6 - tmp5;
  174205. z11 = tmp4 + tmp7;
  174206. z12 = tmp4 - tmp7;
  174207. tmp7 = z11 + z13; /* phase 5 */
  174208. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  174209. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  174210. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  174211. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  174212. tmp6 = tmp12 - tmp7; /* phase 2 */
  174213. tmp5 = tmp11 - tmp6;
  174214. tmp4 = tmp10 + tmp5;
  174215. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  174216. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  174217. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  174218. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  174219. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  174220. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  174221. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  174222. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  174223. inptr++; /* advance pointers to next column */
  174224. quantptr++;
  174225. wsptr++;
  174226. }
  174227. /* Pass 2: process rows from work array, store into output array. */
  174228. /* Note that we must descale the results by a factor of 8 == 2**3, */
  174229. /* and also undo the PASS1_BITS scaling. */
  174230. wsptr = workspace;
  174231. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  174232. outptr = output_buf[ctr] + output_col;
  174233. /* Rows of zeroes can be exploited in the same way as we did with columns.
  174234. * However, the column calculation has created many nonzero AC terms, so
  174235. * the simplification applies less often (typically 5% to 10% of the time).
  174236. * On machines with very fast multiplication, it's possible that the
  174237. * test takes more time than it's worth. In that case this section
  174238. * may be commented out.
  174239. */
  174240. #ifndef NO_ZERO_ROW_TEST
  174241. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  174242. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  174243. /* AC terms all zero */
  174244. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  174245. & RANGE_MASK];
  174246. outptr[0] = dcval;
  174247. outptr[1] = dcval;
  174248. outptr[2] = dcval;
  174249. outptr[3] = dcval;
  174250. outptr[4] = dcval;
  174251. outptr[5] = dcval;
  174252. outptr[6] = dcval;
  174253. outptr[7] = dcval;
  174254. wsptr += DCTSIZE; /* advance pointer to next row */
  174255. continue;
  174256. }
  174257. #endif
  174258. /* Even part */
  174259. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  174260. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  174261. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  174262. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  174263. - tmp13;
  174264. tmp0 = tmp10 + tmp13;
  174265. tmp3 = tmp10 - tmp13;
  174266. tmp1 = tmp11 + tmp12;
  174267. tmp2 = tmp11 - tmp12;
  174268. /* Odd part */
  174269. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  174270. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  174271. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  174272. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  174273. tmp7 = z11 + z13; /* phase 5 */
  174274. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  174275. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  174276. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  174277. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  174278. tmp6 = tmp12 - tmp7; /* phase 2 */
  174279. tmp5 = tmp11 - tmp6;
  174280. tmp4 = tmp10 + tmp5;
  174281. /* Final output stage: scale down by a factor of 8 and range-limit */
  174282. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  174283. & RANGE_MASK];
  174284. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  174285. & RANGE_MASK];
  174286. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  174287. & RANGE_MASK];
  174288. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  174289. & RANGE_MASK];
  174290. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  174291. & RANGE_MASK];
  174292. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  174293. & RANGE_MASK];
  174294. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  174295. & RANGE_MASK];
  174296. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  174297. & RANGE_MASK];
  174298. wsptr += DCTSIZE; /* advance pointer to next row */
  174299. }
  174300. }
  174301. #endif /* DCT_IFAST_SUPPORTED */
  174302. /*** End of inlined file: jidctfst.c ***/
  174303. #undef CONST_BITS
  174304. #undef FIX_1_847759065
  174305. #undef MULTIPLY
  174306. #undef DEQUANTIZE
  174307. /*** Start of inlined file: jidctint.c ***/
  174308. #define JPEG_INTERNALS
  174309. #ifdef DCT_ISLOW_SUPPORTED
  174310. /*
  174311. * This module is specialized to the case DCTSIZE = 8.
  174312. */
  174313. #if DCTSIZE != 8
  174314. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174315. #endif
  174316. /*
  174317. * The poop on this scaling stuff is as follows:
  174318. *
  174319. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  174320. * larger than the true IDCT outputs. The final outputs are therefore
  174321. * a factor of N larger than desired; since N=8 this can be cured by
  174322. * a simple right shift at the end of the algorithm. The advantage of
  174323. * this arrangement is that we save two multiplications per 1-D IDCT,
  174324. * because the y0 and y4 inputs need not be divided by sqrt(N).
  174325. *
  174326. * We have to do addition and subtraction of the integer inputs, which
  174327. * is no problem, and multiplication by fractional constants, which is
  174328. * a problem to do in integer arithmetic. We multiply all the constants
  174329. * by CONST_SCALE and convert them to integer constants (thus retaining
  174330. * CONST_BITS bits of precision in the constants). After doing a
  174331. * multiplication we have to divide the product by CONST_SCALE, with proper
  174332. * rounding, to produce the correct output. This division can be done
  174333. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  174334. * as long as possible so that partial sums can be added together with
  174335. * full fractional precision.
  174336. *
  174337. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  174338. * they are represented to better-than-integral precision. These outputs
  174339. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  174340. * with the recommended scaling. (To scale up 12-bit sample data further, an
  174341. * intermediate INT32 array would be needed.)
  174342. *
  174343. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  174344. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  174345. * shows that the values given below are the most effective.
  174346. */
  174347. #if BITS_IN_JSAMPLE == 8
  174348. #define CONST_BITS 13
  174349. #define PASS1_BITS 2
  174350. #else
  174351. #define CONST_BITS 13
  174352. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174353. #endif
  174354. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174355. * causing a lot of useless floating-point operations at run time.
  174356. * To get around this we use the following pre-calculated constants.
  174357. * If you change CONST_BITS you may want to add appropriate values.
  174358. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174359. */
  174360. #if CONST_BITS == 13
  174361. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  174362. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  174363. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  174364. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  174365. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  174366. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  174367. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  174368. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  174369. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  174370. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  174371. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  174372. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  174373. #else
  174374. #define FIX_0_298631336 FIX(0.298631336)
  174375. #define FIX_0_390180644 FIX(0.390180644)
  174376. #define FIX_0_541196100 FIX(0.541196100)
  174377. #define FIX_0_765366865 FIX(0.765366865)
  174378. #define FIX_0_899976223 FIX(0.899976223)
  174379. #define FIX_1_175875602 FIX(1.175875602)
  174380. #define FIX_1_501321110 FIX(1.501321110)
  174381. #define FIX_1_847759065 FIX(1.847759065)
  174382. #define FIX_1_961570560 FIX(1.961570560)
  174383. #define FIX_2_053119869 FIX(2.053119869)
  174384. #define FIX_2_562915447 FIX(2.562915447)
  174385. #define FIX_3_072711026 FIX(3.072711026)
  174386. #endif
  174387. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  174388. * For 8-bit samples with the recommended scaling, all the variable
  174389. * and constant values involved are no more than 16 bits wide, so a
  174390. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  174391. * For 12-bit samples, a full 32-bit multiplication will be needed.
  174392. */
  174393. #if BITS_IN_JSAMPLE == 8
  174394. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  174395. #else
  174396. #define MULTIPLY(var,const) ((var) * (const))
  174397. #endif
  174398. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174399. * entry; produce an int result. In this module, both inputs and result
  174400. * are 16 bits or less, so either int or short multiply will work.
  174401. */
  174402. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  174403. /*
  174404. * Perform dequantization and inverse DCT on one block of coefficients.
  174405. */
  174406. GLOBAL(void)
  174407. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174408. JCOEFPTR coef_block,
  174409. JSAMPARRAY output_buf, JDIMENSION output_col)
  174410. {
  174411. INT32 tmp0, tmp1, tmp2, tmp3;
  174412. INT32 tmp10, tmp11, tmp12, tmp13;
  174413. INT32 z1, z2, z3, z4, z5;
  174414. JCOEFPTR inptr;
  174415. ISLOW_MULT_TYPE * quantptr;
  174416. int * wsptr;
  174417. JSAMPROW outptr;
  174418. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174419. int ctr;
  174420. int workspace[DCTSIZE2]; /* buffers data between passes */
  174421. SHIFT_TEMPS
  174422. /* Pass 1: process columns from input, store into work array. */
  174423. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  174424. /* furthermore, we scale the results by 2**PASS1_BITS. */
  174425. inptr = coef_block;
  174426. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  174427. wsptr = workspace;
  174428. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174429. /* Due to quantization, we will usually find that many of the input
  174430. * coefficients are zero, especially the AC terms. We can exploit this
  174431. * by short-circuiting the IDCT calculation for any column in which all
  174432. * the AC terms are zero. In that case each output is equal to the
  174433. * DC coefficient (with scale factor as needed).
  174434. * With typical images and quantization tables, half or more of the
  174435. * column DCT calculations can be simplified this way.
  174436. */
  174437. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174438. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174439. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174440. inptr[DCTSIZE*7] == 0) {
  174441. /* AC terms all zero */
  174442. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  174443. wsptr[DCTSIZE*0] = dcval;
  174444. wsptr[DCTSIZE*1] = dcval;
  174445. wsptr[DCTSIZE*2] = dcval;
  174446. wsptr[DCTSIZE*3] = dcval;
  174447. wsptr[DCTSIZE*4] = dcval;
  174448. wsptr[DCTSIZE*5] = dcval;
  174449. wsptr[DCTSIZE*6] = dcval;
  174450. wsptr[DCTSIZE*7] = dcval;
  174451. inptr++; /* advance pointers to next column */
  174452. quantptr++;
  174453. wsptr++;
  174454. continue;
  174455. }
  174456. /* Even part: reverse the even part of the forward DCT. */
  174457. /* The rotator is sqrt(2)*c(-6). */
  174458. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174459. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174460. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  174461. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  174462. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  174463. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174464. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  174465. tmp0 = (z2 + z3) << CONST_BITS;
  174466. tmp1 = (z2 - z3) << CONST_BITS;
  174467. tmp10 = tmp0 + tmp3;
  174468. tmp13 = tmp0 - tmp3;
  174469. tmp11 = tmp1 + tmp2;
  174470. tmp12 = tmp1 - tmp2;
  174471. /* Odd part per figure 8; the matrix is unitary and hence its
  174472. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  174473. */
  174474. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174475. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174476. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174477. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174478. z1 = tmp0 + tmp3;
  174479. z2 = tmp1 + tmp2;
  174480. z3 = tmp0 + tmp2;
  174481. z4 = tmp1 + tmp3;
  174482. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174483. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174484. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174485. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174486. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174487. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174488. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174489. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174490. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174491. z3 += z5;
  174492. z4 += z5;
  174493. tmp0 += z1 + z3;
  174494. tmp1 += z2 + z4;
  174495. tmp2 += z2 + z3;
  174496. tmp3 += z1 + z4;
  174497. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  174498. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  174499. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  174500. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  174501. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  174502. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  174503. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  174504. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  174505. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  174506. inptr++; /* advance pointers to next column */
  174507. quantptr++;
  174508. wsptr++;
  174509. }
  174510. /* Pass 2: process rows from work array, store into output array. */
  174511. /* Note that we must descale the results by a factor of 8 == 2**3, */
  174512. /* and also undo the PASS1_BITS scaling. */
  174513. wsptr = workspace;
  174514. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  174515. outptr = output_buf[ctr] + output_col;
  174516. /* Rows of zeroes can be exploited in the same way as we did with columns.
  174517. * However, the column calculation has created many nonzero AC terms, so
  174518. * the simplification applies less often (typically 5% to 10% of the time).
  174519. * On machines with very fast multiplication, it's possible that the
  174520. * test takes more time than it's worth. In that case this section
  174521. * may be commented out.
  174522. */
  174523. #ifndef NO_ZERO_ROW_TEST
  174524. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  174525. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  174526. /* AC terms all zero */
  174527. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  174528. & RANGE_MASK];
  174529. outptr[0] = dcval;
  174530. outptr[1] = dcval;
  174531. outptr[2] = dcval;
  174532. outptr[3] = dcval;
  174533. outptr[4] = dcval;
  174534. outptr[5] = dcval;
  174535. outptr[6] = dcval;
  174536. outptr[7] = dcval;
  174537. wsptr += DCTSIZE; /* advance pointer to next row */
  174538. continue;
  174539. }
  174540. #endif
  174541. /* Even part: reverse the even part of the forward DCT. */
  174542. /* The rotator is sqrt(2)*c(-6). */
  174543. z2 = (INT32) wsptr[2];
  174544. z3 = (INT32) wsptr[6];
  174545. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  174546. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  174547. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  174548. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  174549. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  174550. tmp10 = tmp0 + tmp3;
  174551. tmp13 = tmp0 - tmp3;
  174552. tmp11 = tmp1 + tmp2;
  174553. tmp12 = tmp1 - tmp2;
  174554. /* Odd part per figure 8; the matrix is unitary and hence its
  174555. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  174556. */
  174557. tmp0 = (INT32) wsptr[7];
  174558. tmp1 = (INT32) wsptr[5];
  174559. tmp2 = (INT32) wsptr[3];
  174560. tmp3 = (INT32) wsptr[1];
  174561. z1 = tmp0 + tmp3;
  174562. z2 = tmp1 + tmp2;
  174563. z3 = tmp0 + tmp2;
  174564. z4 = tmp1 + tmp3;
  174565. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174566. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174567. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174568. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174569. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174570. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174571. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174572. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174573. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174574. z3 += z5;
  174575. z4 += z5;
  174576. tmp0 += z1 + z3;
  174577. tmp1 += z2 + z4;
  174578. tmp2 += z2 + z3;
  174579. tmp3 += z1 + z4;
  174580. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  174581. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  174582. CONST_BITS+PASS1_BITS+3)
  174583. & RANGE_MASK];
  174584. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  174585. CONST_BITS+PASS1_BITS+3)
  174586. & RANGE_MASK];
  174587. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  174588. CONST_BITS+PASS1_BITS+3)
  174589. & RANGE_MASK];
  174590. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  174591. CONST_BITS+PASS1_BITS+3)
  174592. & RANGE_MASK];
  174593. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  174594. CONST_BITS+PASS1_BITS+3)
  174595. & RANGE_MASK];
  174596. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  174597. CONST_BITS+PASS1_BITS+3)
  174598. & RANGE_MASK];
  174599. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  174600. CONST_BITS+PASS1_BITS+3)
  174601. & RANGE_MASK];
  174602. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  174603. CONST_BITS+PASS1_BITS+3)
  174604. & RANGE_MASK];
  174605. wsptr += DCTSIZE; /* advance pointer to next row */
  174606. }
  174607. }
  174608. #endif /* DCT_ISLOW_SUPPORTED */
  174609. /*** End of inlined file: jidctint.c ***/
  174610. /*** Start of inlined file: jidctred.c ***/
  174611. #define JPEG_INTERNALS
  174612. #ifdef IDCT_SCALING_SUPPORTED
  174613. /*
  174614. * This module is specialized to the case DCTSIZE = 8.
  174615. */
  174616. #if DCTSIZE != 8
  174617. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174618. #endif
  174619. /* Scaling is the same as in jidctint.c. */
  174620. #if BITS_IN_JSAMPLE == 8
  174621. #define CONST_BITS 13
  174622. #define PASS1_BITS 2
  174623. #else
  174624. #define CONST_BITS 13
  174625. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174626. #endif
  174627. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174628. * causing a lot of useless floating-point operations at run time.
  174629. * To get around this we use the following pre-calculated constants.
  174630. * If you change CONST_BITS you may want to add appropriate values.
  174631. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174632. */
  174633. #if CONST_BITS == 13
  174634. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  174635. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  174636. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  174637. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  174638. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  174639. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  174640. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  174641. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  174642. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  174643. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  174644. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  174645. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  174646. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  174647. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  174648. #else
  174649. #define FIX_0_211164243 FIX(0.211164243)
  174650. #define FIX_0_509795579 FIX(0.509795579)
  174651. #define FIX_0_601344887 FIX(0.601344887)
  174652. #define FIX_0_720959822 FIX(0.720959822)
  174653. #define FIX_0_765366865 FIX(0.765366865)
  174654. #define FIX_0_850430095 FIX(0.850430095)
  174655. #define FIX_0_899976223 FIX(0.899976223)
  174656. #define FIX_1_061594337 FIX(1.061594337)
  174657. #define FIX_1_272758580 FIX(1.272758580)
  174658. #define FIX_1_451774981 FIX(1.451774981)
  174659. #define FIX_1_847759065 FIX(1.847759065)
  174660. #define FIX_2_172734803 FIX(2.172734803)
  174661. #define FIX_2_562915447 FIX(2.562915447)
  174662. #define FIX_3_624509785 FIX(3.624509785)
  174663. #endif
  174664. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  174665. * For 8-bit samples with the recommended scaling, all the variable
  174666. * and constant values involved are no more than 16 bits wide, so a
  174667. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  174668. * For 12-bit samples, a full 32-bit multiplication will be needed.
  174669. */
  174670. #if BITS_IN_JSAMPLE == 8
  174671. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  174672. #else
  174673. #define MULTIPLY(var,const) ((var) * (const))
  174674. #endif
  174675. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174676. * entry; produce an int result. In this module, both inputs and result
  174677. * are 16 bits or less, so either int or short multiply will work.
  174678. */
  174679. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  174680. /*
  174681. * Perform dequantization and inverse DCT on one block of coefficients,
  174682. * producing a reduced-size 4x4 output block.
  174683. */
  174684. GLOBAL(void)
  174685. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174686. JCOEFPTR coef_block,
  174687. JSAMPARRAY output_buf, JDIMENSION output_col)
  174688. {
  174689. INT32 tmp0, tmp2, tmp10, tmp12;
  174690. INT32 z1, z2, z3, z4;
  174691. JCOEFPTR inptr;
  174692. ISLOW_MULT_TYPE * quantptr;
  174693. int * wsptr;
  174694. JSAMPROW outptr;
  174695. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174696. int ctr;
  174697. int workspace[DCTSIZE*4]; /* buffers data between passes */
  174698. SHIFT_TEMPS
  174699. /* Pass 1: process columns from input, store into work array. */
  174700. inptr = coef_block;
  174701. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  174702. wsptr = workspace;
  174703. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  174704. /* Don't bother to process column 4, because second pass won't use it */
  174705. if (ctr == DCTSIZE-4)
  174706. continue;
  174707. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174708. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  174709. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  174710. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  174711. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  174712. wsptr[DCTSIZE*0] = dcval;
  174713. wsptr[DCTSIZE*1] = dcval;
  174714. wsptr[DCTSIZE*2] = dcval;
  174715. wsptr[DCTSIZE*3] = dcval;
  174716. continue;
  174717. }
  174718. /* Even part */
  174719. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174720. tmp0 <<= (CONST_BITS+1);
  174721. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174722. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174723. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  174724. tmp10 = tmp0 + tmp2;
  174725. tmp12 = tmp0 - tmp2;
  174726. /* Odd part */
  174727. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174728. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174729. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174730. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174731. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  174732. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  174733. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  174734. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  174735. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  174736. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  174737. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  174738. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  174739. /* Final output stage */
  174740. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  174741. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  174742. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  174743. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  174744. }
  174745. /* Pass 2: process 4 rows from work array, store into output array. */
  174746. wsptr = workspace;
  174747. for (ctr = 0; ctr < 4; ctr++) {
  174748. outptr = output_buf[ctr] + output_col;
  174749. /* It's not clear whether a zero row test is worthwhile here ... */
  174750. #ifndef NO_ZERO_ROW_TEST
  174751. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  174752. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  174753. /* AC terms all zero */
  174754. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  174755. & RANGE_MASK];
  174756. outptr[0] = dcval;
  174757. outptr[1] = dcval;
  174758. outptr[2] = dcval;
  174759. outptr[3] = dcval;
  174760. wsptr += DCTSIZE; /* advance pointer to next row */
  174761. continue;
  174762. }
  174763. #endif
  174764. /* Even part */
  174765. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  174766. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  174767. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  174768. tmp10 = tmp0 + tmp2;
  174769. tmp12 = tmp0 - tmp2;
  174770. /* Odd part */
  174771. z1 = (INT32) wsptr[7];
  174772. z2 = (INT32) wsptr[5];
  174773. z3 = (INT32) wsptr[3];
  174774. z4 = (INT32) wsptr[1];
  174775. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  174776. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  174777. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  174778. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  174779. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  174780. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  174781. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  174782. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  174783. /* Final output stage */
  174784. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  174785. CONST_BITS+PASS1_BITS+3+1)
  174786. & RANGE_MASK];
  174787. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  174788. CONST_BITS+PASS1_BITS+3+1)
  174789. & RANGE_MASK];
  174790. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  174791. CONST_BITS+PASS1_BITS+3+1)
  174792. & RANGE_MASK];
  174793. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  174794. CONST_BITS+PASS1_BITS+3+1)
  174795. & RANGE_MASK];
  174796. wsptr += DCTSIZE; /* advance pointer to next row */
  174797. }
  174798. }
  174799. /*
  174800. * Perform dequantization and inverse DCT on one block of coefficients,
  174801. * producing a reduced-size 2x2 output block.
  174802. */
  174803. GLOBAL(void)
  174804. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174805. JCOEFPTR coef_block,
  174806. JSAMPARRAY output_buf, JDIMENSION output_col)
  174807. {
  174808. INT32 tmp0, tmp10, z1;
  174809. JCOEFPTR inptr;
  174810. ISLOW_MULT_TYPE * quantptr;
  174811. int * wsptr;
  174812. JSAMPROW outptr;
  174813. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174814. int ctr;
  174815. int workspace[DCTSIZE*2]; /* buffers data between passes */
  174816. SHIFT_TEMPS
  174817. /* Pass 1: process columns from input, store into work array. */
  174818. inptr = coef_block;
  174819. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  174820. wsptr = workspace;
  174821. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  174822. /* Don't bother to process columns 2,4,6 */
  174823. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  174824. continue;
  174825. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  174826. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  174827. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  174828. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  174829. wsptr[DCTSIZE*0] = dcval;
  174830. wsptr[DCTSIZE*1] = dcval;
  174831. continue;
  174832. }
  174833. /* Even part */
  174834. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174835. tmp10 = z1 << (CONST_BITS+2);
  174836. /* Odd part */
  174837. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174838. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  174839. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174840. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  174841. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174842. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  174843. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174844. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  174845. /* Final output stage */
  174846. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  174847. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  174848. }
  174849. /* Pass 2: process 2 rows from work array, store into output array. */
  174850. wsptr = workspace;
  174851. for (ctr = 0; ctr < 2; ctr++) {
  174852. outptr = output_buf[ctr] + output_col;
  174853. /* It's not clear whether a zero row test is worthwhile here ... */
  174854. #ifndef NO_ZERO_ROW_TEST
  174855. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  174856. /* AC terms all zero */
  174857. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  174858. & RANGE_MASK];
  174859. outptr[0] = dcval;
  174860. outptr[1] = dcval;
  174861. wsptr += DCTSIZE; /* advance pointer to next row */
  174862. continue;
  174863. }
  174864. #endif
  174865. /* Even part */
  174866. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  174867. /* Odd part */
  174868. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  174869. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  174870. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  174871. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  174872. /* Final output stage */
  174873. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  174874. CONST_BITS+PASS1_BITS+3+2)
  174875. & RANGE_MASK];
  174876. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  174877. CONST_BITS+PASS1_BITS+3+2)
  174878. & RANGE_MASK];
  174879. wsptr += DCTSIZE; /* advance pointer to next row */
  174880. }
  174881. }
  174882. /*
  174883. * Perform dequantization and inverse DCT on one block of coefficients,
  174884. * producing a reduced-size 1x1 output block.
  174885. */
  174886. GLOBAL(void)
  174887. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174888. JCOEFPTR coef_block,
  174889. JSAMPARRAY output_buf, JDIMENSION output_col)
  174890. {
  174891. int dcval;
  174892. ISLOW_MULT_TYPE * quantptr;
  174893. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174894. SHIFT_TEMPS
  174895. /* We hardly need an inverse DCT routine for this: just take the
  174896. * average pixel value, which is one-eighth of the DC coefficient.
  174897. */
  174898. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  174899. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  174900. dcval = (int) DESCALE((INT32) dcval, 3);
  174901. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  174902. }
  174903. #endif /* IDCT_SCALING_SUPPORTED */
  174904. /*** End of inlined file: jidctred.c ***/
  174905. /*** Start of inlined file: jmemmgr.c ***/
  174906. #define JPEG_INTERNALS
  174907. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  174908. /*** Start of inlined file: jmemsys.h ***/
  174909. #ifndef __jmemsys_h__
  174910. #define __jmemsys_h__
  174911. /* Short forms of external names for systems with brain-damaged linkers. */
  174912. #ifdef NEED_SHORT_EXTERNAL_NAMES
  174913. #define jpeg_get_small jGetSmall
  174914. #define jpeg_free_small jFreeSmall
  174915. #define jpeg_get_large jGetLarge
  174916. #define jpeg_free_large jFreeLarge
  174917. #define jpeg_mem_available jMemAvail
  174918. #define jpeg_open_backing_store jOpenBackStore
  174919. #define jpeg_mem_init jMemInit
  174920. #define jpeg_mem_term jMemTerm
  174921. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  174922. /*
  174923. * These two functions are used to allocate and release small chunks of
  174924. * memory. (Typically the total amount requested through jpeg_get_small is
  174925. * no more than 20K or so; this will be requested in chunks of a few K each.)
  174926. * Behavior should be the same as for the standard library functions malloc
  174927. * and free; in particular, jpeg_get_small must return NULL on failure.
  174928. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  174929. * size of the object being freed, just in case it's needed.
  174930. * On an 80x86 machine using small-data memory model, these manage near heap.
  174931. */
  174932. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  174933. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  174934. size_t sizeofobject));
  174935. /*
  174936. * These two functions are used to allocate and release large chunks of
  174937. * memory (up to the total free space designated by jpeg_mem_available).
  174938. * The interface is the same as above, except that on an 80x86 machine,
  174939. * far pointers are used. On most other machines these are identical to
  174940. * the jpeg_get/free_small routines; but we keep them separate anyway,
  174941. * in case a different allocation strategy is desirable for large chunks.
  174942. */
  174943. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  174944. size_t sizeofobject));
  174945. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  174946. size_t sizeofobject));
  174947. /*
  174948. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  174949. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  174950. * matter, but that case should never come into play). This macro is needed
  174951. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  174952. * On those machines, we expect that jconfig.h will provide a proper value.
  174953. * On machines with 32-bit flat address spaces, any large constant may be used.
  174954. *
  174955. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  174956. * size_t and will be a multiple of sizeof(align_type).
  174957. */
  174958. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  174959. #define MAX_ALLOC_CHUNK 1000000000L
  174960. #endif
  174961. /*
  174962. * This routine computes the total space still available for allocation by
  174963. * jpeg_get_large. If more space than this is needed, backing store will be
  174964. * used. NOTE: any memory already allocated must not be counted.
  174965. *
  174966. * There is a minimum space requirement, corresponding to the minimum
  174967. * feasible buffer sizes; jmemmgr.c will request that much space even if
  174968. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  174969. * all working storage in memory, is also passed in case it is useful.
  174970. * Finally, the total space already allocated is passed. If no better
  174971. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  174972. * is often a suitable calculation.
  174973. *
  174974. * It is OK for jpeg_mem_available to underestimate the space available
  174975. * (that'll just lead to more backing-store access than is really necessary).
  174976. * However, an overestimate will lead to failure. Hence it's wise to subtract
  174977. * a slop factor from the true available space. 5% should be enough.
  174978. *
  174979. * On machines with lots of virtual memory, any large constant may be returned.
  174980. * Conversely, zero may be returned to always use the minimum amount of memory.
  174981. */
  174982. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  174983. long min_bytes_needed,
  174984. long max_bytes_needed,
  174985. long already_allocated));
  174986. /*
  174987. * This structure holds whatever state is needed to access a single
  174988. * backing-store object. The read/write/close method pointers are called
  174989. * by jmemmgr.c to manipulate the backing-store object; all other fields
  174990. * are private to the system-dependent backing store routines.
  174991. */
  174992. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  174993. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  174994. typedef unsigned short XMSH; /* type of extended-memory handles */
  174995. typedef unsigned short EMSH; /* type of expanded-memory handles */
  174996. typedef union {
  174997. short file_handle; /* DOS file handle if it's a temp file */
  174998. XMSH xms_handle; /* handle if it's a chunk of XMS */
  174999. EMSH ems_handle; /* handle if it's a chunk of EMS */
  175000. } handle_union;
  175001. #endif /* USE_MSDOS_MEMMGR */
  175002. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  175003. #include <Files.h>
  175004. #endif /* USE_MAC_MEMMGR */
  175005. //typedef struct backing_store_struct * backing_store_ptr;
  175006. typedef struct backing_store_struct {
  175007. /* Methods for reading/writing/closing this backing-store object */
  175008. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  175009. struct backing_store_struct *info,
  175010. void FAR * buffer_address,
  175011. long file_offset, long byte_count));
  175012. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  175013. struct backing_store_struct *info,
  175014. void FAR * buffer_address,
  175015. long file_offset, long byte_count));
  175016. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  175017. struct backing_store_struct *info));
  175018. /* Private fields for system-dependent backing-store management */
  175019. #ifdef USE_MSDOS_MEMMGR
  175020. /* For the MS-DOS manager (jmemdos.c), we need: */
  175021. handle_union handle; /* reference to backing-store storage object */
  175022. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  175023. #else
  175024. #ifdef USE_MAC_MEMMGR
  175025. /* For the Mac manager (jmemmac.c), we need: */
  175026. short temp_file; /* file reference number to temp file */
  175027. FSSpec tempSpec; /* the FSSpec for the temp file */
  175028. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  175029. #else
  175030. /* For a typical implementation with temp files, we need: */
  175031. FILE * temp_file; /* stdio reference to temp file */
  175032. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  175033. #endif
  175034. #endif
  175035. } backing_store_info;
  175036. /*
  175037. * Initial opening of a backing-store object. This must fill in the
  175038. * read/write/close pointers in the object. The read/write routines
  175039. * may take an error exit if the specified maximum file size is exceeded.
  175040. * (If jpeg_mem_available always returns a large value, this routine can
  175041. * just take an error exit.)
  175042. */
  175043. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  175044. struct backing_store_struct *info,
  175045. long total_bytes_needed));
  175046. /*
  175047. * These routines take care of any system-dependent initialization and
  175048. * cleanup required. jpeg_mem_init will be called before anything is
  175049. * allocated (and, therefore, nothing in cinfo is of use except the error
  175050. * manager pointer). It should return a suitable default value for
  175051. * max_memory_to_use; this may subsequently be overridden by the surrounding
  175052. * application. (Note that max_memory_to_use is only important if
  175053. * jpeg_mem_available chooses to consult it ... no one else will.)
  175054. * jpeg_mem_term may assume that all requested memory has been freed and that
  175055. * all opened backing-store objects have been closed.
  175056. */
  175057. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  175058. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  175059. #endif
  175060. /*** End of inlined file: jmemsys.h ***/
  175061. /* import the system-dependent declarations */
  175062. #ifndef NO_GETENV
  175063. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  175064. extern char * getenv JPP((const char * name));
  175065. #endif
  175066. #endif
  175067. /*
  175068. * Some important notes:
  175069. * The allocation routines provided here must never return NULL.
  175070. * They should exit to error_exit if unsuccessful.
  175071. *
  175072. * It's not a good idea to try to merge the sarray and barray routines,
  175073. * even though they are textually almost the same, because samples are
  175074. * usually stored as bytes while coefficients are shorts or ints. Thus,
  175075. * in machines where byte pointers have a different representation from
  175076. * word pointers, the resulting machine code could not be the same.
  175077. */
  175078. /*
  175079. * Many machines require storage alignment: longs must start on 4-byte
  175080. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  175081. * always returns pointers that are multiples of the worst-case alignment
  175082. * requirement, and we had better do so too.
  175083. * There isn't any really portable way to determine the worst-case alignment
  175084. * requirement. This module assumes that the alignment requirement is
  175085. * multiples of sizeof(ALIGN_TYPE).
  175086. * By default, we define ALIGN_TYPE as double. This is necessary on some
  175087. * workstations (where doubles really do need 8-byte alignment) and will work
  175088. * fine on nearly everything. If your machine has lesser alignment needs,
  175089. * you can save a few bytes by making ALIGN_TYPE smaller.
  175090. * The only place I know of where this will NOT work is certain Macintosh
  175091. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  175092. * Doing 10-byte alignment is counterproductive because longwords won't be
  175093. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  175094. * such a compiler.
  175095. */
  175096. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  175097. #define ALIGN_TYPE double
  175098. #endif
  175099. /*
  175100. * We allocate objects from "pools", where each pool is gotten with a single
  175101. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  175102. * overhead within a pool, except for alignment padding. Each pool has a
  175103. * header with a link to the next pool of the same class.
  175104. * Small and large pool headers are identical except that the latter's
  175105. * link pointer must be FAR on 80x86 machines.
  175106. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  175107. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  175108. * of the alignment requirement of ALIGN_TYPE.
  175109. */
  175110. typedef union small_pool_struct * small_pool_ptr;
  175111. typedef union small_pool_struct {
  175112. struct {
  175113. small_pool_ptr next; /* next in list of pools */
  175114. size_t bytes_used; /* how many bytes already used within pool */
  175115. size_t bytes_left; /* bytes still available in this pool */
  175116. } hdr;
  175117. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  175118. } small_pool_hdr;
  175119. typedef union large_pool_struct FAR * large_pool_ptr;
  175120. typedef union large_pool_struct {
  175121. struct {
  175122. large_pool_ptr next; /* next in list of pools */
  175123. size_t bytes_used; /* how many bytes already used within pool */
  175124. size_t bytes_left; /* bytes still available in this pool */
  175125. } hdr;
  175126. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  175127. } large_pool_hdr;
  175128. /*
  175129. * Here is the full definition of a memory manager object.
  175130. */
  175131. typedef struct {
  175132. struct jpeg_memory_mgr pub; /* public fields */
  175133. /* Each pool identifier (lifetime class) names a linked list of pools. */
  175134. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  175135. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  175136. /* Since we only have one lifetime class of virtual arrays, only one
  175137. * linked list is necessary (for each datatype). Note that the virtual
  175138. * array control blocks being linked together are actually stored somewhere
  175139. * in the small-pool list.
  175140. */
  175141. jvirt_sarray_ptr virt_sarray_list;
  175142. jvirt_barray_ptr virt_barray_list;
  175143. /* This counts total space obtained from jpeg_get_small/large */
  175144. long total_space_allocated;
  175145. /* alloc_sarray and alloc_barray set this value for use by virtual
  175146. * array routines.
  175147. */
  175148. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  175149. } my_memory_mgr;
  175150. typedef my_memory_mgr * my_mem_ptr;
  175151. /*
  175152. * The control blocks for virtual arrays.
  175153. * Note that these blocks are allocated in the "small" pool area.
  175154. * System-dependent info for the associated backing store (if any) is hidden
  175155. * inside the backing_store_info struct.
  175156. */
  175157. struct jvirt_sarray_control {
  175158. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  175159. JDIMENSION rows_in_array; /* total virtual array height */
  175160. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  175161. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  175162. JDIMENSION rows_in_mem; /* height of memory buffer */
  175163. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  175164. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  175165. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  175166. boolean pre_zero; /* pre-zero mode requested? */
  175167. boolean dirty; /* do current buffer contents need written? */
  175168. boolean b_s_open; /* is backing-store data valid? */
  175169. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  175170. backing_store_info b_s_info; /* System-dependent control info */
  175171. };
  175172. struct jvirt_barray_control {
  175173. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  175174. JDIMENSION rows_in_array; /* total virtual array height */
  175175. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  175176. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  175177. JDIMENSION rows_in_mem; /* height of memory buffer */
  175178. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  175179. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  175180. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  175181. boolean pre_zero; /* pre-zero mode requested? */
  175182. boolean dirty; /* do current buffer contents need written? */
  175183. boolean b_s_open; /* is backing-store data valid? */
  175184. jvirt_barray_ptr next; /* link to next virtual barray control block */
  175185. backing_store_info b_s_info; /* System-dependent control info */
  175186. };
  175187. #ifdef MEM_STATS /* optional extra stuff for statistics */
  175188. LOCAL(void)
  175189. print_mem_stats (j_common_ptr cinfo, int pool_id)
  175190. {
  175191. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175192. small_pool_ptr shdr_ptr;
  175193. large_pool_ptr lhdr_ptr;
  175194. /* Since this is only a debugging stub, we can cheat a little by using
  175195. * fprintf directly rather than going through the trace message code.
  175196. * This is helpful because message parm array can't handle longs.
  175197. */
  175198. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  175199. pool_id, mem->total_space_allocated);
  175200. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  175201. lhdr_ptr = lhdr_ptr->hdr.next) {
  175202. fprintf(stderr, " Large chunk used %ld\n",
  175203. (long) lhdr_ptr->hdr.bytes_used);
  175204. }
  175205. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  175206. shdr_ptr = shdr_ptr->hdr.next) {
  175207. fprintf(stderr, " Small chunk used %ld free %ld\n",
  175208. (long) shdr_ptr->hdr.bytes_used,
  175209. (long) shdr_ptr->hdr.bytes_left);
  175210. }
  175211. }
  175212. #endif /* MEM_STATS */
  175213. LOCAL(void)
  175214. out_of_memory (j_common_ptr cinfo, int which)
  175215. /* Report an out-of-memory error and stop execution */
  175216. /* If we compiled MEM_STATS support, report alloc requests before dying */
  175217. {
  175218. #ifdef MEM_STATS
  175219. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  175220. #endif
  175221. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  175222. }
  175223. /*
  175224. * Allocation of "small" objects.
  175225. *
  175226. * For these, we use pooled storage. When a new pool must be created,
  175227. * we try to get enough space for the current request plus a "slop" factor,
  175228. * where the slop will be the amount of leftover space in the new pool.
  175229. * The speed vs. space tradeoff is largely determined by the slop values.
  175230. * A different slop value is provided for each pool class (lifetime),
  175231. * and we also distinguish the first pool of a class from later ones.
  175232. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  175233. * machines, but may be too small if longs are 64 bits or more.
  175234. */
  175235. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  175236. {
  175237. 1600, /* first PERMANENT pool */
  175238. 16000 /* first IMAGE pool */
  175239. };
  175240. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  175241. {
  175242. 0, /* additional PERMANENT pools */
  175243. 5000 /* additional IMAGE pools */
  175244. };
  175245. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  175246. METHODDEF(void *)
  175247. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  175248. /* Allocate a "small" object */
  175249. {
  175250. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175251. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  175252. char * data_ptr;
  175253. size_t odd_bytes, min_request, slop;
  175254. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  175255. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  175256. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  175257. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  175258. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  175259. if (odd_bytes > 0)
  175260. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  175261. /* See if space is available in any existing pool */
  175262. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  175263. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  175264. prev_hdr_ptr = NULL;
  175265. hdr_ptr = mem->small_list[pool_id];
  175266. while (hdr_ptr != NULL) {
  175267. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  175268. break; /* found pool with enough space */
  175269. prev_hdr_ptr = hdr_ptr;
  175270. hdr_ptr = hdr_ptr->hdr.next;
  175271. }
  175272. /* Time to make a new pool? */
  175273. if (hdr_ptr == NULL) {
  175274. /* min_request is what we need now, slop is what will be leftover */
  175275. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  175276. if (prev_hdr_ptr == NULL) /* first pool in class? */
  175277. slop = first_pool_slop[pool_id];
  175278. else
  175279. slop = extra_pool_slop[pool_id];
  175280. /* Don't ask for more than MAX_ALLOC_CHUNK */
  175281. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  175282. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  175283. /* Try to get space, if fail reduce slop and try again */
  175284. for (;;) {
  175285. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  175286. if (hdr_ptr != NULL)
  175287. break;
  175288. slop /= 2;
  175289. if (slop < MIN_SLOP) /* give up when it gets real small */
  175290. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  175291. }
  175292. mem->total_space_allocated += min_request + slop;
  175293. /* Success, initialize the new pool header and add to end of list */
  175294. hdr_ptr->hdr.next = NULL;
  175295. hdr_ptr->hdr.bytes_used = 0;
  175296. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  175297. if (prev_hdr_ptr == NULL) /* first pool in class? */
  175298. mem->small_list[pool_id] = hdr_ptr;
  175299. else
  175300. prev_hdr_ptr->hdr.next = hdr_ptr;
  175301. }
  175302. /* OK, allocate the object from the current pool */
  175303. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  175304. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  175305. hdr_ptr->hdr.bytes_used += sizeofobject;
  175306. hdr_ptr->hdr.bytes_left -= sizeofobject;
  175307. return (void *) data_ptr;
  175308. }
  175309. /*
  175310. * Allocation of "large" objects.
  175311. *
  175312. * The external semantics of these are the same as "small" objects,
  175313. * except that FAR pointers are used on 80x86. However the pool
  175314. * management heuristics are quite different. We assume that each
  175315. * request is large enough that it may as well be passed directly to
  175316. * jpeg_get_large; the pool management just links everything together
  175317. * so that we can free it all on demand.
  175318. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  175319. * structures. The routines that create these structures (see below)
  175320. * deliberately bunch rows together to ensure a large request size.
  175321. */
  175322. METHODDEF(void FAR *)
  175323. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  175324. /* Allocate a "large" object */
  175325. {
  175326. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175327. large_pool_ptr hdr_ptr;
  175328. size_t odd_bytes;
  175329. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  175330. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  175331. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  175332. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  175333. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  175334. if (odd_bytes > 0)
  175335. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  175336. /* Always make a new pool */
  175337. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  175338. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  175339. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  175340. SIZEOF(large_pool_hdr));
  175341. if (hdr_ptr == NULL)
  175342. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  175343. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  175344. /* Success, initialize the new pool header and add to list */
  175345. hdr_ptr->hdr.next = mem->large_list[pool_id];
  175346. /* We maintain space counts in each pool header for statistical purposes,
  175347. * even though they are not needed for allocation.
  175348. */
  175349. hdr_ptr->hdr.bytes_used = sizeofobject;
  175350. hdr_ptr->hdr.bytes_left = 0;
  175351. mem->large_list[pool_id] = hdr_ptr;
  175352. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  175353. }
  175354. /*
  175355. * Creation of 2-D sample arrays.
  175356. * The pointers are in near heap, the samples themselves in FAR heap.
  175357. *
  175358. * To minimize allocation overhead and to allow I/O of large contiguous
  175359. * blocks, we allocate the sample rows in groups of as many rows as possible
  175360. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  175361. * NB: the virtual array control routines, later in this file, know about
  175362. * this chunking of rows. The rowsperchunk value is left in the mem manager
  175363. * object so that it can be saved away if this sarray is the workspace for
  175364. * a virtual array.
  175365. */
  175366. METHODDEF(JSAMPARRAY)
  175367. alloc_sarray (j_common_ptr cinfo, int pool_id,
  175368. JDIMENSION samplesperrow, JDIMENSION numrows)
  175369. /* Allocate a 2-D sample array */
  175370. {
  175371. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175372. JSAMPARRAY result;
  175373. JSAMPROW workspace;
  175374. JDIMENSION rowsperchunk, currow, i;
  175375. long ltemp;
  175376. /* Calculate max # of rows allowed in one allocation chunk */
  175377. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  175378. ((long) samplesperrow * SIZEOF(JSAMPLE));
  175379. if (ltemp <= 0)
  175380. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  175381. if (ltemp < (long) numrows)
  175382. rowsperchunk = (JDIMENSION) ltemp;
  175383. else
  175384. rowsperchunk = numrows;
  175385. mem->last_rowsperchunk = rowsperchunk;
  175386. /* Get space for row pointers (small object) */
  175387. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  175388. (size_t) (numrows * SIZEOF(JSAMPROW)));
  175389. /* Get the rows themselves (large objects) */
  175390. currow = 0;
  175391. while (currow < numrows) {
  175392. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  175393. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  175394. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  175395. * SIZEOF(JSAMPLE)));
  175396. for (i = rowsperchunk; i > 0; i--) {
  175397. result[currow++] = workspace;
  175398. workspace += samplesperrow;
  175399. }
  175400. }
  175401. return result;
  175402. }
  175403. /*
  175404. * Creation of 2-D coefficient-block arrays.
  175405. * This is essentially the same as the code for sample arrays, above.
  175406. */
  175407. METHODDEF(JBLOCKARRAY)
  175408. alloc_barray (j_common_ptr cinfo, int pool_id,
  175409. JDIMENSION blocksperrow, JDIMENSION numrows)
  175410. /* Allocate a 2-D coefficient-block array */
  175411. {
  175412. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175413. JBLOCKARRAY result;
  175414. JBLOCKROW workspace;
  175415. JDIMENSION rowsperchunk, currow, i;
  175416. long ltemp;
  175417. /* Calculate max # of rows allowed in one allocation chunk */
  175418. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  175419. ((long) blocksperrow * SIZEOF(JBLOCK));
  175420. if (ltemp <= 0)
  175421. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  175422. if (ltemp < (long) numrows)
  175423. rowsperchunk = (JDIMENSION) ltemp;
  175424. else
  175425. rowsperchunk = numrows;
  175426. mem->last_rowsperchunk = rowsperchunk;
  175427. /* Get space for row pointers (small object) */
  175428. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  175429. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  175430. /* Get the rows themselves (large objects) */
  175431. currow = 0;
  175432. while (currow < numrows) {
  175433. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  175434. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  175435. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  175436. * SIZEOF(JBLOCK)));
  175437. for (i = rowsperchunk; i > 0; i--) {
  175438. result[currow++] = workspace;
  175439. workspace += blocksperrow;
  175440. }
  175441. }
  175442. return result;
  175443. }
  175444. /*
  175445. * About virtual array management:
  175446. *
  175447. * The above "normal" array routines are only used to allocate strip buffers
  175448. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  175449. * are handled as "virtual" arrays. The array is still accessed a strip at a
  175450. * time, but the memory manager must save the whole array for repeated
  175451. * accesses. The intended implementation is that there is a strip buffer in
  175452. * memory (as high as is possible given the desired memory limit), plus a
  175453. * backing file that holds the rest of the array.
  175454. *
  175455. * The request_virt_array routines are told the total size of the image and
  175456. * the maximum number of rows that will be accessed at once. The in-memory
  175457. * buffer must be at least as large as the maxaccess value.
  175458. *
  175459. * The request routines create control blocks but not the in-memory buffers.
  175460. * That is postponed until realize_virt_arrays is called. At that time the
  175461. * total amount of space needed is known (approximately, anyway), so free
  175462. * memory can be divided up fairly.
  175463. *
  175464. * The access_virt_array routines are responsible for making a specific strip
  175465. * area accessible (after reading or writing the backing file, if necessary).
  175466. * Note that the access routines are told whether the caller intends to modify
  175467. * the accessed strip; during a read-only pass this saves having to rewrite
  175468. * data to disk. The access routines are also responsible for pre-zeroing
  175469. * any newly accessed rows, if pre-zeroing was requested.
  175470. *
  175471. * In current usage, the access requests are usually for nonoverlapping
  175472. * strips; that is, successive access start_row numbers differ by exactly
  175473. * num_rows = maxaccess. This means we can get good performance with simple
  175474. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  175475. * of the access height; then there will never be accesses across bufferload
  175476. * boundaries. The code will still work with overlapping access requests,
  175477. * but it doesn't handle bufferload overlaps very efficiently.
  175478. */
  175479. METHODDEF(jvirt_sarray_ptr)
  175480. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  175481. JDIMENSION samplesperrow, JDIMENSION numrows,
  175482. JDIMENSION maxaccess)
  175483. /* Request a virtual 2-D sample array */
  175484. {
  175485. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175486. jvirt_sarray_ptr result;
  175487. /* Only IMAGE-lifetime virtual arrays are currently supported */
  175488. if (pool_id != JPOOL_IMAGE)
  175489. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  175490. /* get control block */
  175491. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  175492. SIZEOF(struct jvirt_sarray_control));
  175493. result->mem_buffer = NULL; /* marks array not yet realized */
  175494. result->rows_in_array = numrows;
  175495. result->samplesperrow = samplesperrow;
  175496. result->maxaccess = maxaccess;
  175497. result->pre_zero = pre_zero;
  175498. result->b_s_open = FALSE; /* no associated backing-store object */
  175499. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  175500. mem->virt_sarray_list = result;
  175501. return result;
  175502. }
  175503. METHODDEF(jvirt_barray_ptr)
  175504. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  175505. JDIMENSION blocksperrow, JDIMENSION numrows,
  175506. JDIMENSION maxaccess)
  175507. /* Request a virtual 2-D coefficient-block array */
  175508. {
  175509. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175510. jvirt_barray_ptr result;
  175511. /* Only IMAGE-lifetime virtual arrays are currently supported */
  175512. if (pool_id != JPOOL_IMAGE)
  175513. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  175514. /* get control block */
  175515. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  175516. SIZEOF(struct jvirt_barray_control));
  175517. result->mem_buffer = NULL; /* marks array not yet realized */
  175518. result->rows_in_array = numrows;
  175519. result->blocksperrow = blocksperrow;
  175520. result->maxaccess = maxaccess;
  175521. result->pre_zero = pre_zero;
  175522. result->b_s_open = FALSE; /* no associated backing-store object */
  175523. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  175524. mem->virt_barray_list = result;
  175525. return result;
  175526. }
  175527. METHODDEF(void)
  175528. realize_virt_arrays (j_common_ptr cinfo)
  175529. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  175530. {
  175531. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175532. long space_per_minheight, maximum_space, avail_mem;
  175533. long minheights, max_minheights;
  175534. jvirt_sarray_ptr sptr;
  175535. jvirt_barray_ptr bptr;
  175536. /* Compute the minimum space needed (maxaccess rows in each buffer)
  175537. * and the maximum space needed (full image height in each buffer).
  175538. * These may be of use to the system-dependent jpeg_mem_available routine.
  175539. */
  175540. space_per_minheight = 0;
  175541. maximum_space = 0;
  175542. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  175543. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  175544. space_per_minheight += (long) sptr->maxaccess *
  175545. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  175546. maximum_space += (long) sptr->rows_in_array *
  175547. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  175548. }
  175549. }
  175550. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  175551. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  175552. space_per_minheight += (long) bptr->maxaccess *
  175553. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  175554. maximum_space += (long) bptr->rows_in_array *
  175555. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  175556. }
  175557. }
  175558. if (space_per_minheight <= 0)
  175559. return; /* no unrealized arrays, no work */
  175560. /* Determine amount of memory to actually use; this is system-dependent. */
  175561. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  175562. mem->total_space_allocated);
  175563. /* If the maximum space needed is available, make all the buffers full
  175564. * height; otherwise parcel it out with the same number of minheights
  175565. * in each buffer.
  175566. */
  175567. if (avail_mem >= maximum_space)
  175568. max_minheights = 1000000000L;
  175569. else {
  175570. max_minheights = avail_mem / space_per_minheight;
  175571. /* If there doesn't seem to be enough space, try to get the minimum
  175572. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  175573. */
  175574. if (max_minheights <= 0)
  175575. max_minheights = 1;
  175576. }
  175577. /* Allocate the in-memory buffers and initialize backing store as needed. */
  175578. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  175579. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  175580. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  175581. if (minheights <= max_minheights) {
  175582. /* This buffer fits in memory */
  175583. sptr->rows_in_mem = sptr->rows_in_array;
  175584. } else {
  175585. /* It doesn't fit in memory, create backing store. */
  175586. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  175587. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  175588. (long) sptr->rows_in_array *
  175589. (long) sptr->samplesperrow *
  175590. (long) SIZEOF(JSAMPLE));
  175591. sptr->b_s_open = TRUE;
  175592. }
  175593. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  175594. sptr->samplesperrow, sptr->rows_in_mem);
  175595. sptr->rowsperchunk = mem->last_rowsperchunk;
  175596. sptr->cur_start_row = 0;
  175597. sptr->first_undef_row = 0;
  175598. sptr->dirty = FALSE;
  175599. }
  175600. }
  175601. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  175602. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  175603. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  175604. if (minheights <= max_minheights) {
  175605. /* This buffer fits in memory */
  175606. bptr->rows_in_mem = bptr->rows_in_array;
  175607. } else {
  175608. /* It doesn't fit in memory, create backing store. */
  175609. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  175610. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  175611. (long) bptr->rows_in_array *
  175612. (long) bptr->blocksperrow *
  175613. (long) SIZEOF(JBLOCK));
  175614. bptr->b_s_open = TRUE;
  175615. }
  175616. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  175617. bptr->blocksperrow, bptr->rows_in_mem);
  175618. bptr->rowsperchunk = mem->last_rowsperchunk;
  175619. bptr->cur_start_row = 0;
  175620. bptr->first_undef_row = 0;
  175621. bptr->dirty = FALSE;
  175622. }
  175623. }
  175624. }
  175625. LOCAL(void)
  175626. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  175627. /* Do backing store read or write of a virtual sample array */
  175628. {
  175629. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  175630. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  175631. file_offset = ptr->cur_start_row * bytesperrow;
  175632. /* Loop to read or write each allocation chunk in mem_buffer */
  175633. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  175634. /* One chunk, but check for short chunk at end of buffer */
  175635. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  175636. /* Transfer no more than is currently defined */
  175637. thisrow = (long) ptr->cur_start_row + i;
  175638. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  175639. /* Transfer no more than fits in file */
  175640. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  175641. if (rows <= 0) /* this chunk might be past end of file! */
  175642. break;
  175643. byte_count = rows * bytesperrow;
  175644. if (writing)
  175645. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  175646. (void FAR *) ptr->mem_buffer[i],
  175647. file_offset, byte_count);
  175648. else
  175649. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  175650. (void FAR *) ptr->mem_buffer[i],
  175651. file_offset, byte_count);
  175652. file_offset += byte_count;
  175653. }
  175654. }
  175655. LOCAL(void)
  175656. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  175657. /* Do backing store read or write of a virtual coefficient-block array */
  175658. {
  175659. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  175660. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  175661. file_offset = ptr->cur_start_row * bytesperrow;
  175662. /* Loop to read or write each allocation chunk in mem_buffer */
  175663. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  175664. /* One chunk, but check for short chunk at end of buffer */
  175665. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  175666. /* Transfer no more than is currently defined */
  175667. thisrow = (long) ptr->cur_start_row + i;
  175668. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  175669. /* Transfer no more than fits in file */
  175670. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  175671. if (rows <= 0) /* this chunk might be past end of file! */
  175672. break;
  175673. byte_count = rows * bytesperrow;
  175674. if (writing)
  175675. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  175676. (void FAR *) ptr->mem_buffer[i],
  175677. file_offset, byte_count);
  175678. else
  175679. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  175680. (void FAR *) ptr->mem_buffer[i],
  175681. file_offset, byte_count);
  175682. file_offset += byte_count;
  175683. }
  175684. }
  175685. METHODDEF(JSAMPARRAY)
  175686. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  175687. JDIMENSION start_row, JDIMENSION num_rows,
  175688. boolean writable)
  175689. /* Access the part of a virtual sample array starting at start_row */
  175690. /* and extending for num_rows rows. writable is true if */
  175691. /* caller intends to modify the accessed area. */
  175692. {
  175693. JDIMENSION end_row = start_row + num_rows;
  175694. JDIMENSION undef_row;
  175695. /* debugging check */
  175696. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  175697. ptr->mem_buffer == NULL)
  175698. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  175699. /* Make the desired part of the virtual array accessible */
  175700. if (start_row < ptr->cur_start_row ||
  175701. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  175702. if (! ptr->b_s_open)
  175703. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  175704. /* Flush old buffer contents if necessary */
  175705. if (ptr->dirty) {
  175706. do_sarray_io(cinfo, ptr, TRUE);
  175707. ptr->dirty = FALSE;
  175708. }
  175709. /* Decide what part of virtual array to access.
  175710. * Algorithm: if target address > current window, assume forward scan,
  175711. * load starting at target address. If target address < current window,
  175712. * assume backward scan, load so that target area is top of window.
  175713. * Note that when switching from forward write to forward read, will have
  175714. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  175715. */
  175716. if (start_row > ptr->cur_start_row) {
  175717. ptr->cur_start_row = start_row;
  175718. } else {
  175719. /* use long arithmetic here to avoid overflow & unsigned problems */
  175720. long ltemp;
  175721. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  175722. if (ltemp < 0)
  175723. ltemp = 0; /* don't fall off front end of file */
  175724. ptr->cur_start_row = (JDIMENSION) ltemp;
  175725. }
  175726. /* Read in the selected part of the array.
  175727. * During the initial write pass, we will do no actual read
  175728. * because the selected part is all undefined.
  175729. */
  175730. do_sarray_io(cinfo, ptr, FALSE);
  175731. }
  175732. /* Ensure the accessed part of the array is defined; prezero if needed.
  175733. * To improve locality of access, we only prezero the part of the array
  175734. * that the caller is about to access, not the entire in-memory array.
  175735. */
  175736. if (ptr->first_undef_row < end_row) {
  175737. if (ptr->first_undef_row < start_row) {
  175738. if (writable) /* writer skipped over a section of array */
  175739. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  175740. undef_row = start_row; /* but reader is allowed to read ahead */
  175741. } else {
  175742. undef_row = ptr->first_undef_row;
  175743. }
  175744. if (writable)
  175745. ptr->first_undef_row = end_row;
  175746. if (ptr->pre_zero) {
  175747. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  175748. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  175749. end_row -= ptr->cur_start_row;
  175750. while (undef_row < end_row) {
  175751. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  175752. undef_row++;
  175753. }
  175754. } else {
  175755. if (! writable) /* reader looking at undefined data */
  175756. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  175757. }
  175758. }
  175759. /* Flag the buffer dirty if caller will write in it */
  175760. if (writable)
  175761. ptr->dirty = TRUE;
  175762. /* Return address of proper part of the buffer */
  175763. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  175764. }
  175765. METHODDEF(JBLOCKARRAY)
  175766. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  175767. JDIMENSION start_row, JDIMENSION num_rows,
  175768. boolean writable)
  175769. /* Access the part of a virtual block array starting at start_row */
  175770. /* and extending for num_rows rows. writable is true if */
  175771. /* caller intends to modify the accessed area. */
  175772. {
  175773. JDIMENSION end_row = start_row + num_rows;
  175774. JDIMENSION undef_row;
  175775. /* debugging check */
  175776. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  175777. ptr->mem_buffer == NULL)
  175778. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  175779. /* Make the desired part of the virtual array accessible */
  175780. if (start_row < ptr->cur_start_row ||
  175781. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  175782. if (! ptr->b_s_open)
  175783. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  175784. /* Flush old buffer contents if necessary */
  175785. if (ptr->dirty) {
  175786. do_barray_io(cinfo, ptr, TRUE);
  175787. ptr->dirty = FALSE;
  175788. }
  175789. /* Decide what part of virtual array to access.
  175790. * Algorithm: if target address > current window, assume forward scan,
  175791. * load starting at target address. If target address < current window,
  175792. * assume backward scan, load so that target area is top of window.
  175793. * Note that when switching from forward write to forward read, will have
  175794. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  175795. */
  175796. if (start_row > ptr->cur_start_row) {
  175797. ptr->cur_start_row = start_row;
  175798. } else {
  175799. /* use long arithmetic here to avoid overflow & unsigned problems */
  175800. long ltemp;
  175801. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  175802. if (ltemp < 0)
  175803. ltemp = 0; /* don't fall off front end of file */
  175804. ptr->cur_start_row = (JDIMENSION) ltemp;
  175805. }
  175806. /* Read in the selected part of the array.
  175807. * During the initial write pass, we will do no actual read
  175808. * because the selected part is all undefined.
  175809. */
  175810. do_barray_io(cinfo, ptr, FALSE);
  175811. }
  175812. /* Ensure the accessed part of the array is defined; prezero if needed.
  175813. * To improve locality of access, we only prezero the part of the array
  175814. * that the caller is about to access, not the entire in-memory array.
  175815. */
  175816. if (ptr->first_undef_row < end_row) {
  175817. if (ptr->first_undef_row < start_row) {
  175818. if (writable) /* writer skipped over a section of array */
  175819. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  175820. undef_row = start_row; /* but reader is allowed to read ahead */
  175821. } else {
  175822. undef_row = ptr->first_undef_row;
  175823. }
  175824. if (writable)
  175825. ptr->first_undef_row = end_row;
  175826. if (ptr->pre_zero) {
  175827. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  175828. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  175829. end_row -= ptr->cur_start_row;
  175830. while (undef_row < end_row) {
  175831. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  175832. undef_row++;
  175833. }
  175834. } else {
  175835. if (! writable) /* reader looking at undefined data */
  175836. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  175837. }
  175838. }
  175839. /* Flag the buffer dirty if caller will write in it */
  175840. if (writable)
  175841. ptr->dirty = TRUE;
  175842. /* Return address of proper part of the buffer */
  175843. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  175844. }
  175845. /*
  175846. * Release all objects belonging to a specified pool.
  175847. */
  175848. METHODDEF(void)
  175849. free_pool (j_common_ptr cinfo, int pool_id)
  175850. {
  175851. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175852. small_pool_ptr shdr_ptr;
  175853. large_pool_ptr lhdr_ptr;
  175854. size_t space_freed;
  175855. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  175856. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  175857. #ifdef MEM_STATS
  175858. if (cinfo->err->trace_level > 1)
  175859. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  175860. #endif
  175861. /* If freeing IMAGE pool, close any virtual arrays first */
  175862. if (pool_id == JPOOL_IMAGE) {
  175863. jvirt_sarray_ptr sptr;
  175864. jvirt_barray_ptr bptr;
  175865. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  175866. if (sptr->b_s_open) { /* there may be no backing store */
  175867. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  175868. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  175869. }
  175870. }
  175871. mem->virt_sarray_list = NULL;
  175872. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  175873. if (bptr->b_s_open) { /* there may be no backing store */
  175874. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  175875. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  175876. }
  175877. }
  175878. mem->virt_barray_list = NULL;
  175879. }
  175880. /* Release large objects */
  175881. lhdr_ptr = mem->large_list[pool_id];
  175882. mem->large_list[pool_id] = NULL;
  175883. while (lhdr_ptr != NULL) {
  175884. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  175885. space_freed = lhdr_ptr->hdr.bytes_used +
  175886. lhdr_ptr->hdr.bytes_left +
  175887. SIZEOF(large_pool_hdr);
  175888. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  175889. mem->total_space_allocated -= space_freed;
  175890. lhdr_ptr = next_lhdr_ptr;
  175891. }
  175892. /* Release small objects */
  175893. shdr_ptr = mem->small_list[pool_id];
  175894. mem->small_list[pool_id] = NULL;
  175895. while (shdr_ptr != NULL) {
  175896. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  175897. space_freed = shdr_ptr->hdr.bytes_used +
  175898. shdr_ptr->hdr.bytes_left +
  175899. SIZEOF(small_pool_hdr);
  175900. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  175901. mem->total_space_allocated -= space_freed;
  175902. shdr_ptr = next_shdr_ptr;
  175903. }
  175904. }
  175905. /*
  175906. * Close up shop entirely.
  175907. * Note that this cannot be called unless cinfo->mem is non-NULL.
  175908. */
  175909. METHODDEF(void)
  175910. self_destruct (j_common_ptr cinfo)
  175911. {
  175912. int pool;
  175913. /* Close all backing store, release all memory.
  175914. * Releasing pools in reverse order might help avoid fragmentation
  175915. * with some (brain-damaged) malloc libraries.
  175916. */
  175917. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  175918. free_pool(cinfo, pool);
  175919. }
  175920. /* Release the memory manager control block too. */
  175921. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  175922. cinfo->mem = NULL; /* ensures I will be called only once */
  175923. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  175924. }
  175925. /*
  175926. * Memory manager initialization.
  175927. * When this is called, only the error manager pointer is valid in cinfo!
  175928. */
  175929. GLOBAL(void)
  175930. jinit_memory_mgr (j_common_ptr cinfo)
  175931. {
  175932. my_mem_ptr mem;
  175933. long max_to_use;
  175934. int pool;
  175935. size_t test_mac;
  175936. cinfo->mem = NULL; /* for safety if init fails */
  175937. /* Check for configuration errors.
  175938. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  175939. * doesn't reflect any real hardware alignment requirement.
  175940. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  175941. * in common if and only if X is a power of 2, ie has only one one-bit.
  175942. * Some compilers may give an "unreachable code" warning here; ignore it.
  175943. */
  175944. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  175945. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  175946. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  175947. * a multiple of SIZEOF(ALIGN_TYPE).
  175948. * Again, an "unreachable code" warning may be ignored here.
  175949. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  175950. */
  175951. test_mac = (size_t) MAX_ALLOC_CHUNK;
  175952. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  175953. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  175954. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  175955. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  175956. /* Attempt to allocate memory manager's control block */
  175957. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  175958. if (mem == NULL) {
  175959. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  175960. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  175961. }
  175962. /* OK, fill in the method pointers */
  175963. mem->pub.alloc_small = alloc_small;
  175964. mem->pub.alloc_large = alloc_large;
  175965. mem->pub.alloc_sarray = alloc_sarray;
  175966. mem->pub.alloc_barray = alloc_barray;
  175967. mem->pub.request_virt_sarray = request_virt_sarray;
  175968. mem->pub.request_virt_barray = request_virt_barray;
  175969. mem->pub.realize_virt_arrays = realize_virt_arrays;
  175970. mem->pub.access_virt_sarray = access_virt_sarray;
  175971. mem->pub.access_virt_barray = access_virt_barray;
  175972. mem->pub.free_pool = free_pool;
  175973. mem->pub.self_destruct = self_destruct;
  175974. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  175975. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  175976. /* Initialize working state */
  175977. mem->pub.max_memory_to_use = max_to_use;
  175978. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  175979. mem->small_list[pool] = NULL;
  175980. mem->large_list[pool] = NULL;
  175981. }
  175982. mem->virt_sarray_list = NULL;
  175983. mem->virt_barray_list = NULL;
  175984. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  175985. /* Declare ourselves open for business */
  175986. cinfo->mem = & mem->pub;
  175987. /* Check for an environment variable JPEGMEM; if found, override the
  175988. * default max_memory setting from jpeg_mem_init. Note that the
  175989. * surrounding application may again override this value.
  175990. * If your system doesn't support getenv(), define NO_GETENV to disable
  175991. * this feature.
  175992. */
  175993. #ifndef NO_GETENV
  175994. { char * memenv;
  175995. if ((memenv = getenv("JPEGMEM")) != NULL) {
  175996. char ch = 'x';
  175997. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  175998. if (ch == 'm' || ch == 'M')
  175999. max_to_use *= 1000L;
  176000. mem->pub.max_memory_to_use = max_to_use * 1000L;
  176001. }
  176002. }
  176003. }
  176004. #endif
  176005. }
  176006. /*** End of inlined file: jmemmgr.c ***/
  176007. /*** Start of inlined file: jmemnobs.c ***/
  176008. #define JPEG_INTERNALS
  176009. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  176010. extern void * malloc JPP((size_t size));
  176011. extern void free JPP((void *ptr));
  176012. #endif
  176013. /*
  176014. * Memory allocation and freeing are controlled by the regular library
  176015. * routines malloc() and free().
  176016. */
  176017. GLOBAL(void *)
  176018. jpeg_get_small (j_common_ptr , size_t sizeofobject)
  176019. {
  176020. return (void *) malloc(sizeofobject);
  176021. }
  176022. GLOBAL(void)
  176023. jpeg_free_small (j_common_ptr , void * object, size_t)
  176024. {
  176025. free(object);
  176026. }
  176027. /*
  176028. * "Large" objects are treated the same as "small" ones.
  176029. * NB: although we include FAR keywords in the routine declarations,
  176030. * this file won't actually work in 80x86 small/medium model; at least,
  176031. * you probably won't be able to process useful-size images in only 64KB.
  176032. */
  176033. GLOBAL(void FAR *)
  176034. jpeg_get_large (j_common_ptr, size_t sizeofobject)
  176035. {
  176036. return (void FAR *) malloc(sizeofobject);
  176037. }
  176038. GLOBAL(void)
  176039. jpeg_free_large (j_common_ptr, void FAR * object, size_t)
  176040. {
  176041. free(object);
  176042. }
  176043. /*
  176044. * This routine computes the total memory space available for allocation.
  176045. * Here we always say, "we got all you want bud!"
  176046. */
  176047. GLOBAL(long)
  176048. jpeg_mem_available (j_common_ptr, long,
  176049. long max_bytes_needed, long)
  176050. {
  176051. return max_bytes_needed;
  176052. }
  176053. /*
  176054. * Backing store (temporary file) management.
  176055. * Since jpeg_mem_available always promised the moon,
  176056. * this should never be called and we can just error out.
  176057. */
  176058. GLOBAL(void)
  176059. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *,
  176060. long )
  176061. {
  176062. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  176063. }
  176064. /*
  176065. * These routines take care of any system-dependent initialization and
  176066. * cleanup required. Here, there isn't any.
  176067. */
  176068. GLOBAL(long)
  176069. jpeg_mem_init (j_common_ptr)
  176070. {
  176071. return 0; /* just set max_memory_to_use to 0 */
  176072. }
  176073. GLOBAL(void)
  176074. jpeg_mem_term (j_common_ptr)
  176075. {
  176076. /* no work */
  176077. }
  176078. /*** End of inlined file: jmemnobs.c ***/
  176079. /*** Start of inlined file: jquant1.c ***/
  176080. #define JPEG_INTERNALS
  176081. #ifdef QUANT_1PASS_SUPPORTED
  176082. /*
  176083. * The main purpose of 1-pass quantization is to provide a fast, if not very
  176084. * high quality, colormapped output capability. A 2-pass quantizer usually
  176085. * gives better visual quality; however, for quantized grayscale output this
  176086. * quantizer is perfectly adequate. Dithering is highly recommended with this
  176087. * quantizer, though you can turn it off if you really want to.
  176088. *
  176089. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  176090. * image. We use a map consisting of all combinations of Ncolors[i] color
  176091. * values for the i'th component. The Ncolors[] values are chosen so that
  176092. * their product, the total number of colors, is no more than that requested.
  176093. * (In most cases, the product will be somewhat less.)
  176094. *
  176095. * Since the colormap is orthogonal, the representative value for each color
  176096. * component can be determined without considering the other components;
  176097. * then these indexes can be combined into a colormap index by a standard
  176098. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  176099. * can be precalculated and stored in the lookup table colorindex[].
  176100. * colorindex[i][j] maps pixel value j in component i to the nearest
  176101. * representative value (grid plane) for that component; this index is
  176102. * multiplied by the array stride for component i, so that the
  176103. * index of the colormap entry closest to a given pixel value is just
  176104. * sum( colorindex[component-number][pixel-component-value] )
  176105. * Aside from being fast, this scheme allows for variable spacing between
  176106. * representative values with no additional lookup cost.
  176107. *
  176108. * If gamma correction has been applied in color conversion, it might be wise
  176109. * to adjust the color grid spacing so that the representative colors are
  176110. * equidistant in linear space. At this writing, gamma correction is not
  176111. * implemented by jdcolor, so nothing is done here.
  176112. */
  176113. /* Declarations for ordered dithering.
  176114. *
  176115. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  176116. * dithering is described in many references, for instance Dale Schumacher's
  176117. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  176118. * In place of Schumacher's comparisons against a "threshold" value, we add a
  176119. * "dither" value to the input pixel and then round the result to the nearest
  176120. * output value. The dither value is equivalent to (0.5 - threshold) times
  176121. * the distance between output values. For ordered dithering, we assume that
  176122. * the output colors are equally spaced; if not, results will probably be
  176123. * worse, since the dither may be too much or too little at a given point.
  176124. *
  176125. * The normal calculation would be to form pixel value + dither, range-limit
  176126. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  176127. * We can skip the separate range-limiting step by extending the colorindex
  176128. * table in both directions.
  176129. */
  176130. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  176131. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  176132. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  176133. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  176134. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  176135. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  176136. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  176137. /* Bayer's order-4 dither array. Generated by the code given in
  176138. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  176139. * The values in this array must range from 0 to ODITHER_CELLS-1.
  176140. */
  176141. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  176142. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  176143. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  176144. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  176145. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  176146. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  176147. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  176148. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  176149. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  176150. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  176151. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  176152. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  176153. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  176154. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  176155. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  176156. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  176157. };
  176158. /* Declarations for Floyd-Steinberg dithering.
  176159. *
  176160. * Errors are accumulated into the array fserrors[], at a resolution of
  176161. * 1/16th of a pixel count. The error at a given pixel is propagated
  176162. * to its not-yet-processed neighbors using the standard F-S fractions,
  176163. * ... (here) 7/16
  176164. * 3/16 5/16 1/16
  176165. * We work left-to-right on even rows, right-to-left on odd rows.
  176166. *
  176167. * We can get away with a single array (holding one row's worth of errors)
  176168. * by using it to store the current row's errors at pixel columns not yet
  176169. * processed, but the next row's errors at columns already processed. We
  176170. * need only a few extra variables to hold the errors immediately around the
  176171. * current column. (If we are lucky, those variables are in registers, but
  176172. * even if not, they're probably cheaper to access than array elements are.)
  176173. *
  176174. * The fserrors[] array is indexed [component#][position].
  176175. * We provide (#columns + 2) entries per component; the extra entry at each
  176176. * end saves us from special-casing the first and last pixels.
  176177. *
  176178. * Note: on a wide image, we might not have enough room in a PC's near data
  176179. * segment to hold the error array; so it is allocated with alloc_large.
  176180. */
  176181. #if BITS_IN_JSAMPLE == 8
  176182. typedef INT16 FSERROR; /* 16 bits should be enough */
  176183. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  176184. #else
  176185. typedef INT32 FSERROR; /* may need more than 16 bits */
  176186. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  176187. #endif
  176188. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  176189. /* Private subobject */
  176190. #define MAX_Q_COMPS 4 /* max components I can handle */
  176191. typedef struct {
  176192. struct jpeg_color_quantizer pub; /* public fields */
  176193. /* Initially allocated colormap is saved here */
  176194. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  176195. int sv_actual; /* number of entries in use */
  176196. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  176197. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  176198. * premultiplied as described above. Since colormap indexes must fit into
  176199. * JSAMPLEs, the entries of this array will too.
  176200. */
  176201. boolean is_padded; /* is the colorindex padded for odither? */
  176202. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  176203. /* Variables for ordered dithering */
  176204. int row_index; /* cur row's vertical index in dither matrix */
  176205. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  176206. /* Variables for Floyd-Steinberg dithering */
  176207. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  176208. boolean on_odd_row; /* flag to remember which row we are on */
  176209. } my_cquantizer;
  176210. typedef my_cquantizer * my_cquantize_ptr;
  176211. /*
  176212. * Policy-making subroutines for create_colormap and create_colorindex.
  176213. * These routines determine the colormap to be used. The rest of the module
  176214. * only assumes that the colormap is orthogonal.
  176215. *
  176216. * * select_ncolors decides how to divvy up the available colors
  176217. * among the components.
  176218. * * output_value defines the set of representative values for a component.
  176219. * * largest_input_value defines the mapping from input values to
  176220. * representative values for a component.
  176221. * Note that the latter two routines may impose different policies for
  176222. * different components, though this is not currently done.
  176223. */
  176224. LOCAL(int)
  176225. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  176226. /* Determine allocation of desired colors to components, */
  176227. /* and fill in Ncolors[] array to indicate choice. */
  176228. /* Return value is total number of colors (product of Ncolors[] values). */
  176229. {
  176230. int nc = cinfo->out_color_components; /* number of color components */
  176231. int max_colors = cinfo->desired_number_of_colors;
  176232. int total_colors, iroot, i, j;
  176233. boolean changed;
  176234. long temp;
  176235. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  176236. /* We can allocate at least the nc'th root of max_colors per component. */
  176237. /* Compute floor(nc'th root of max_colors). */
  176238. iroot = 1;
  176239. do {
  176240. iroot++;
  176241. temp = iroot; /* set temp = iroot ** nc */
  176242. for (i = 1; i < nc; i++)
  176243. temp *= iroot;
  176244. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  176245. iroot--; /* now iroot = floor(root) */
  176246. /* Must have at least 2 color values per component */
  176247. if (iroot < 2)
  176248. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  176249. /* Initialize to iroot color values for each component */
  176250. total_colors = 1;
  176251. for (i = 0; i < nc; i++) {
  176252. Ncolors[i] = iroot;
  176253. total_colors *= iroot;
  176254. }
  176255. /* We may be able to increment the count for one or more components without
  176256. * exceeding max_colors, though we know not all can be incremented.
  176257. * Sometimes, the first component can be incremented more than once!
  176258. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  176259. * In RGB colorspace, try to increment G first, then R, then B.
  176260. */
  176261. do {
  176262. changed = FALSE;
  176263. for (i = 0; i < nc; i++) {
  176264. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  176265. /* calculate new total_colors if Ncolors[j] is incremented */
  176266. temp = total_colors / Ncolors[j];
  176267. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  176268. if (temp > (long) max_colors)
  176269. break; /* won't fit, done with this pass */
  176270. Ncolors[j]++; /* OK, apply the increment */
  176271. total_colors = (int) temp;
  176272. changed = TRUE;
  176273. }
  176274. } while (changed);
  176275. return total_colors;
  176276. }
  176277. LOCAL(int)
  176278. output_value (j_decompress_ptr, int, int j, int maxj)
  176279. /* Return j'th output value, where j will range from 0 to maxj */
  176280. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  176281. {
  176282. /* We always provide values 0 and MAXJSAMPLE for each component;
  176283. * any additional values are equally spaced between these limits.
  176284. * (Forcing the upper and lower values to the limits ensures that
  176285. * dithering can't produce a color outside the selected gamut.)
  176286. */
  176287. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  176288. }
  176289. LOCAL(int)
  176290. largest_input_value (j_decompress_ptr, int, int j, int maxj)
  176291. /* Return largest input value that should map to j'th output value */
  176292. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  176293. {
  176294. /* Breakpoints are halfway between values returned by output_value */
  176295. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  176296. }
  176297. /*
  176298. * Create the colormap.
  176299. */
  176300. LOCAL(void)
  176301. create_colormap (j_decompress_ptr cinfo)
  176302. {
  176303. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176304. JSAMPARRAY colormap; /* Created colormap */
  176305. int total_colors; /* Number of distinct output colors */
  176306. int i,j,k, nci, blksize, blkdist, ptr, val;
  176307. /* Select number of colors for each component */
  176308. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  176309. /* Report selected color counts */
  176310. if (cinfo->out_color_components == 3)
  176311. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  176312. total_colors, cquantize->Ncolors[0],
  176313. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  176314. else
  176315. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  176316. /* Allocate and fill in the colormap. */
  176317. /* The colors are ordered in the map in standard row-major order, */
  176318. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  176319. colormap = (*cinfo->mem->alloc_sarray)
  176320. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  176321. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  176322. /* blksize is number of adjacent repeated entries for a component */
  176323. /* blkdist is distance between groups of identical entries for a component */
  176324. blkdist = total_colors;
  176325. for (i = 0; i < cinfo->out_color_components; i++) {
  176326. /* fill in colormap entries for i'th color component */
  176327. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  176328. blksize = blkdist / nci;
  176329. for (j = 0; j < nci; j++) {
  176330. /* Compute j'th output value (out of nci) for component */
  176331. val = output_value(cinfo, i, j, nci-1);
  176332. /* Fill in all colormap entries that have this value of this component */
  176333. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  176334. /* fill in blksize entries beginning at ptr */
  176335. for (k = 0; k < blksize; k++)
  176336. colormap[i][ptr+k] = (JSAMPLE) val;
  176337. }
  176338. }
  176339. blkdist = blksize; /* blksize of this color is blkdist of next */
  176340. }
  176341. /* Save the colormap in private storage,
  176342. * where it will survive color quantization mode changes.
  176343. */
  176344. cquantize->sv_colormap = colormap;
  176345. cquantize->sv_actual = total_colors;
  176346. }
  176347. /*
  176348. * Create the color index table.
  176349. */
  176350. LOCAL(void)
  176351. create_colorindex (j_decompress_ptr cinfo)
  176352. {
  176353. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176354. JSAMPROW indexptr;
  176355. int i,j,k, nci, blksize, val, pad;
  176356. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  176357. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  176358. * This is not necessary in the other dithering modes. However, we
  176359. * flag whether it was done in case user changes dithering mode.
  176360. */
  176361. if (cinfo->dither_mode == JDITHER_ORDERED) {
  176362. pad = MAXJSAMPLE*2;
  176363. cquantize->is_padded = TRUE;
  176364. } else {
  176365. pad = 0;
  176366. cquantize->is_padded = FALSE;
  176367. }
  176368. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  176369. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  176370. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  176371. (JDIMENSION) cinfo->out_color_components);
  176372. /* blksize is number of adjacent repeated entries for a component */
  176373. blksize = cquantize->sv_actual;
  176374. for (i = 0; i < cinfo->out_color_components; i++) {
  176375. /* fill in colorindex entries for i'th color component */
  176376. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  176377. blksize = blksize / nci;
  176378. /* adjust colorindex pointers to provide padding at negative indexes. */
  176379. if (pad)
  176380. cquantize->colorindex[i] += MAXJSAMPLE;
  176381. /* in loop, val = index of current output value, */
  176382. /* and k = largest j that maps to current val */
  176383. indexptr = cquantize->colorindex[i];
  176384. val = 0;
  176385. k = largest_input_value(cinfo, i, 0, nci-1);
  176386. for (j = 0; j <= MAXJSAMPLE; j++) {
  176387. while (j > k) /* advance val if past boundary */
  176388. k = largest_input_value(cinfo, i, ++val, nci-1);
  176389. /* premultiply so that no multiplication needed in main processing */
  176390. indexptr[j] = (JSAMPLE) (val * blksize);
  176391. }
  176392. /* Pad at both ends if necessary */
  176393. if (pad)
  176394. for (j = 1; j <= MAXJSAMPLE; j++) {
  176395. indexptr[-j] = indexptr[0];
  176396. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  176397. }
  176398. }
  176399. }
  176400. /*
  176401. * Create an ordered-dither array for a component having ncolors
  176402. * distinct output values.
  176403. */
  176404. LOCAL(ODITHER_MATRIX_PTR)
  176405. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  176406. {
  176407. ODITHER_MATRIX_PTR odither;
  176408. int j,k;
  176409. INT32 num,den;
  176410. odither = (ODITHER_MATRIX_PTR)
  176411. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  176412. SIZEOF(ODITHER_MATRIX));
  176413. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  176414. * Hence the dither value for the matrix cell with fill order f
  176415. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  176416. * On 16-bit-int machine, be careful to avoid overflow.
  176417. */
  176418. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  176419. for (j = 0; j < ODITHER_SIZE; j++) {
  176420. for (k = 0; k < ODITHER_SIZE; k++) {
  176421. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  176422. * MAXJSAMPLE;
  176423. /* Ensure round towards zero despite C's lack of consistency
  176424. * about rounding negative values in integer division...
  176425. */
  176426. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  176427. }
  176428. }
  176429. return odither;
  176430. }
  176431. /*
  176432. * Create the ordered-dither tables.
  176433. * Components having the same number of representative colors may
  176434. * share a dither table.
  176435. */
  176436. LOCAL(void)
  176437. create_odither_tables (j_decompress_ptr cinfo)
  176438. {
  176439. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176440. ODITHER_MATRIX_PTR odither;
  176441. int i, j, nci;
  176442. for (i = 0; i < cinfo->out_color_components; i++) {
  176443. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  176444. odither = NULL; /* search for matching prior component */
  176445. for (j = 0; j < i; j++) {
  176446. if (nci == cquantize->Ncolors[j]) {
  176447. odither = cquantize->odither[j];
  176448. break;
  176449. }
  176450. }
  176451. if (odither == NULL) /* need a new table? */
  176452. odither = make_odither_array(cinfo, nci);
  176453. cquantize->odither[i] = odither;
  176454. }
  176455. }
  176456. /*
  176457. * Map some rows of pixels to the output colormapped representation.
  176458. */
  176459. METHODDEF(void)
  176460. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176461. JSAMPARRAY output_buf, int num_rows)
  176462. /* General case, no dithering */
  176463. {
  176464. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176465. JSAMPARRAY colorindex = cquantize->colorindex;
  176466. register int pixcode, ci;
  176467. register JSAMPROW ptrin, ptrout;
  176468. int row;
  176469. JDIMENSION col;
  176470. JDIMENSION width = cinfo->output_width;
  176471. register int nc = cinfo->out_color_components;
  176472. for (row = 0; row < num_rows; row++) {
  176473. ptrin = input_buf[row];
  176474. ptrout = output_buf[row];
  176475. for (col = width; col > 0; col--) {
  176476. pixcode = 0;
  176477. for (ci = 0; ci < nc; ci++) {
  176478. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  176479. }
  176480. *ptrout++ = (JSAMPLE) pixcode;
  176481. }
  176482. }
  176483. }
  176484. METHODDEF(void)
  176485. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176486. JSAMPARRAY output_buf, int num_rows)
  176487. /* Fast path for out_color_components==3, no dithering */
  176488. {
  176489. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176490. register int pixcode;
  176491. register JSAMPROW ptrin, ptrout;
  176492. JSAMPROW colorindex0 = cquantize->colorindex[0];
  176493. JSAMPROW colorindex1 = cquantize->colorindex[1];
  176494. JSAMPROW colorindex2 = cquantize->colorindex[2];
  176495. int row;
  176496. JDIMENSION col;
  176497. JDIMENSION width = cinfo->output_width;
  176498. for (row = 0; row < num_rows; row++) {
  176499. ptrin = input_buf[row];
  176500. ptrout = output_buf[row];
  176501. for (col = width; col > 0; col--) {
  176502. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  176503. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  176504. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  176505. *ptrout++ = (JSAMPLE) pixcode;
  176506. }
  176507. }
  176508. }
  176509. METHODDEF(void)
  176510. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176511. JSAMPARRAY output_buf, int num_rows)
  176512. /* General case, with ordered dithering */
  176513. {
  176514. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176515. register JSAMPROW input_ptr;
  176516. register JSAMPROW output_ptr;
  176517. JSAMPROW colorindex_ci;
  176518. int * dither; /* points to active row of dither matrix */
  176519. int row_index, col_index; /* current indexes into dither matrix */
  176520. int nc = cinfo->out_color_components;
  176521. int ci;
  176522. int row;
  176523. JDIMENSION col;
  176524. JDIMENSION width = cinfo->output_width;
  176525. for (row = 0; row < num_rows; row++) {
  176526. /* Initialize output values to 0 so can process components separately */
  176527. jzero_far((void FAR *) output_buf[row],
  176528. (size_t) (width * SIZEOF(JSAMPLE)));
  176529. row_index = cquantize->row_index;
  176530. for (ci = 0; ci < nc; ci++) {
  176531. input_ptr = input_buf[row] + ci;
  176532. output_ptr = output_buf[row];
  176533. colorindex_ci = cquantize->colorindex[ci];
  176534. dither = cquantize->odither[ci][row_index];
  176535. col_index = 0;
  176536. for (col = width; col > 0; col--) {
  176537. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  176538. * select output value, accumulate into output code for this pixel.
  176539. * Range-limiting need not be done explicitly, as we have extended
  176540. * the colorindex table to produce the right answers for out-of-range
  176541. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  176542. * required amount of padding.
  176543. */
  176544. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  176545. input_ptr += nc;
  176546. output_ptr++;
  176547. col_index = (col_index + 1) & ODITHER_MASK;
  176548. }
  176549. }
  176550. /* Advance row index for next row */
  176551. row_index = (row_index + 1) & ODITHER_MASK;
  176552. cquantize->row_index = row_index;
  176553. }
  176554. }
  176555. METHODDEF(void)
  176556. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176557. JSAMPARRAY output_buf, int num_rows)
  176558. /* Fast path for out_color_components==3, with ordered dithering */
  176559. {
  176560. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176561. register int pixcode;
  176562. register JSAMPROW input_ptr;
  176563. register JSAMPROW output_ptr;
  176564. JSAMPROW colorindex0 = cquantize->colorindex[0];
  176565. JSAMPROW colorindex1 = cquantize->colorindex[1];
  176566. JSAMPROW colorindex2 = cquantize->colorindex[2];
  176567. int * dither0; /* points to active row of dither matrix */
  176568. int * dither1;
  176569. int * dither2;
  176570. int row_index, col_index; /* current indexes into dither matrix */
  176571. int row;
  176572. JDIMENSION col;
  176573. JDIMENSION width = cinfo->output_width;
  176574. for (row = 0; row < num_rows; row++) {
  176575. row_index = cquantize->row_index;
  176576. input_ptr = input_buf[row];
  176577. output_ptr = output_buf[row];
  176578. dither0 = cquantize->odither[0][row_index];
  176579. dither1 = cquantize->odither[1][row_index];
  176580. dither2 = cquantize->odither[2][row_index];
  176581. col_index = 0;
  176582. for (col = width; col > 0; col--) {
  176583. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  176584. dither0[col_index]]);
  176585. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  176586. dither1[col_index]]);
  176587. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  176588. dither2[col_index]]);
  176589. *output_ptr++ = (JSAMPLE) pixcode;
  176590. col_index = (col_index + 1) & ODITHER_MASK;
  176591. }
  176592. row_index = (row_index + 1) & ODITHER_MASK;
  176593. cquantize->row_index = row_index;
  176594. }
  176595. }
  176596. METHODDEF(void)
  176597. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176598. JSAMPARRAY output_buf, int num_rows)
  176599. /* General case, with Floyd-Steinberg dithering */
  176600. {
  176601. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176602. register LOCFSERROR cur; /* current error or pixel value */
  176603. LOCFSERROR belowerr; /* error for pixel below cur */
  176604. LOCFSERROR bpreverr; /* error for below/prev col */
  176605. LOCFSERROR bnexterr; /* error for below/next col */
  176606. LOCFSERROR delta;
  176607. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  176608. register JSAMPROW input_ptr;
  176609. register JSAMPROW output_ptr;
  176610. JSAMPROW colorindex_ci;
  176611. JSAMPROW colormap_ci;
  176612. int pixcode;
  176613. int nc = cinfo->out_color_components;
  176614. int dir; /* 1 for left-to-right, -1 for right-to-left */
  176615. int dirnc; /* dir * nc */
  176616. int ci;
  176617. int row;
  176618. JDIMENSION col;
  176619. JDIMENSION width = cinfo->output_width;
  176620. JSAMPLE *range_limit = cinfo->sample_range_limit;
  176621. SHIFT_TEMPS
  176622. for (row = 0; row < num_rows; row++) {
  176623. /* Initialize output values to 0 so can process components separately */
  176624. jzero_far((void FAR *) output_buf[row],
  176625. (size_t) (width * SIZEOF(JSAMPLE)));
  176626. for (ci = 0; ci < nc; ci++) {
  176627. input_ptr = input_buf[row] + ci;
  176628. output_ptr = output_buf[row];
  176629. if (cquantize->on_odd_row) {
  176630. /* work right to left in this row */
  176631. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  176632. output_ptr += width-1;
  176633. dir = -1;
  176634. dirnc = -nc;
  176635. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  176636. } else {
  176637. /* work left to right in this row */
  176638. dir = 1;
  176639. dirnc = nc;
  176640. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  176641. }
  176642. colorindex_ci = cquantize->colorindex[ci];
  176643. colormap_ci = cquantize->sv_colormap[ci];
  176644. /* Preset error values: no error propagated to first pixel from left */
  176645. cur = 0;
  176646. /* and no error propagated to row below yet */
  176647. belowerr = bpreverr = 0;
  176648. for (col = width; col > 0; col--) {
  176649. /* cur holds the error propagated from the previous pixel on the
  176650. * current line. Add the error propagated from the previous line
  176651. * to form the complete error correction term for this pixel, and
  176652. * round the error term (which is expressed * 16) to an integer.
  176653. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  176654. * for either sign of the error value.
  176655. * Note: errorptr points to *previous* column's array entry.
  176656. */
  176657. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  176658. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  176659. * The maximum error is +- MAXJSAMPLE; this sets the required size
  176660. * of the range_limit array.
  176661. */
  176662. cur += GETJSAMPLE(*input_ptr);
  176663. cur = GETJSAMPLE(range_limit[cur]);
  176664. /* Select output value, accumulate into output code for this pixel */
  176665. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  176666. *output_ptr += (JSAMPLE) pixcode;
  176667. /* Compute actual representation error at this pixel */
  176668. /* Note: we can do this even though we don't have the final */
  176669. /* pixel code, because the colormap is orthogonal. */
  176670. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  176671. /* Compute error fractions to be propagated to adjacent pixels.
  176672. * Add these into the running sums, and simultaneously shift the
  176673. * next-line error sums left by 1 column.
  176674. */
  176675. bnexterr = cur;
  176676. delta = cur * 2;
  176677. cur += delta; /* form error * 3 */
  176678. errorptr[0] = (FSERROR) (bpreverr + cur);
  176679. cur += delta; /* form error * 5 */
  176680. bpreverr = belowerr + cur;
  176681. belowerr = bnexterr;
  176682. cur += delta; /* form error * 7 */
  176683. /* At this point cur contains the 7/16 error value to be propagated
  176684. * to the next pixel on the current line, and all the errors for the
  176685. * next line have been shifted over. We are therefore ready to move on.
  176686. */
  176687. input_ptr += dirnc; /* advance input ptr to next column */
  176688. output_ptr += dir; /* advance output ptr to next column */
  176689. errorptr += dir; /* advance errorptr to current column */
  176690. }
  176691. /* Post-loop cleanup: we must unload the final error value into the
  176692. * final fserrors[] entry. Note we need not unload belowerr because
  176693. * it is for the dummy column before or after the actual array.
  176694. */
  176695. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  176696. }
  176697. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  176698. }
  176699. }
  176700. /*
  176701. * Allocate workspace for Floyd-Steinberg errors.
  176702. */
  176703. LOCAL(void)
  176704. alloc_fs_workspace (j_decompress_ptr cinfo)
  176705. {
  176706. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176707. size_t arraysize;
  176708. int i;
  176709. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  176710. for (i = 0; i < cinfo->out_color_components; i++) {
  176711. cquantize->fserrors[i] = (FSERRPTR)
  176712. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  176713. }
  176714. }
  176715. /*
  176716. * Initialize for one-pass color quantization.
  176717. */
  176718. METHODDEF(void)
  176719. start_pass_1_quant (j_decompress_ptr cinfo, boolean)
  176720. {
  176721. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176722. size_t arraysize;
  176723. int i;
  176724. /* Install my colormap. */
  176725. cinfo->colormap = cquantize->sv_colormap;
  176726. cinfo->actual_number_of_colors = cquantize->sv_actual;
  176727. /* Initialize for desired dithering mode. */
  176728. switch (cinfo->dither_mode) {
  176729. case JDITHER_NONE:
  176730. if (cinfo->out_color_components == 3)
  176731. cquantize->pub.color_quantize = color_quantize3;
  176732. else
  176733. cquantize->pub.color_quantize = color_quantize;
  176734. break;
  176735. case JDITHER_ORDERED:
  176736. if (cinfo->out_color_components == 3)
  176737. cquantize->pub.color_quantize = quantize3_ord_dither;
  176738. else
  176739. cquantize->pub.color_quantize = quantize_ord_dither;
  176740. cquantize->row_index = 0; /* initialize state for ordered dither */
  176741. /* If user changed to ordered dither from another mode,
  176742. * we must recreate the color index table with padding.
  176743. * This will cost extra space, but probably isn't very likely.
  176744. */
  176745. if (! cquantize->is_padded)
  176746. create_colorindex(cinfo);
  176747. /* Create ordered-dither tables if we didn't already. */
  176748. if (cquantize->odither[0] == NULL)
  176749. create_odither_tables(cinfo);
  176750. break;
  176751. case JDITHER_FS:
  176752. cquantize->pub.color_quantize = quantize_fs_dither;
  176753. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  176754. /* Allocate Floyd-Steinberg workspace if didn't already. */
  176755. if (cquantize->fserrors[0] == NULL)
  176756. alloc_fs_workspace(cinfo);
  176757. /* Initialize the propagated errors to zero. */
  176758. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  176759. for (i = 0; i < cinfo->out_color_components; i++)
  176760. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  176761. break;
  176762. default:
  176763. ERREXIT(cinfo, JERR_NOT_COMPILED);
  176764. break;
  176765. }
  176766. }
  176767. /*
  176768. * Finish up at the end of the pass.
  176769. */
  176770. METHODDEF(void)
  176771. finish_pass_1_quant (j_decompress_ptr)
  176772. {
  176773. /* no work in 1-pass case */
  176774. }
  176775. /*
  176776. * Switch to a new external colormap between output passes.
  176777. * Shouldn't get to this module!
  176778. */
  176779. METHODDEF(void)
  176780. new_color_map_1_quant (j_decompress_ptr cinfo)
  176781. {
  176782. ERREXIT(cinfo, JERR_MODE_CHANGE);
  176783. }
  176784. /*
  176785. * Module initialization routine for 1-pass color quantization.
  176786. */
  176787. GLOBAL(void)
  176788. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  176789. {
  176790. my_cquantize_ptr cquantize;
  176791. cquantize = (my_cquantize_ptr)
  176792. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  176793. SIZEOF(my_cquantizer));
  176794. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  176795. cquantize->pub.start_pass = start_pass_1_quant;
  176796. cquantize->pub.finish_pass = finish_pass_1_quant;
  176797. cquantize->pub.new_color_map = new_color_map_1_quant;
  176798. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  176799. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  176800. /* Make sure my internal arrays won't overflow */
  176801. if (cinfo->out_color_components > MAX_Q_COMPS)
  176802. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  176803. /* Make sure colormap indexes can be represented by JSAMPLEs */
  176804. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  176805. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  176806. /* Create the colormap and color index table. */
  176807. create_colormap(cinfo);
  176808. create_colorindex(cinfo);
  176809. /* Allocate Floyd-Steinberg workspace now if requested.
  176810. * We do this now since it is FAR storage and may affect the memory
  176811. * manager's space calculations. If the user changes to FS dither
  176812. * mode in a later pass, we will allocate the space then, and will
  176813. * possibly overrun the max_memory_to_use setting.
  176814. */
  176815. if (cinfo->dither_mode == JDITHER_FS)
  176816. alloc_fs_workspace(cinfo);
  176817. }
  176818. #endif /* QUANT_1PASS_SUPPORTED */
  176819. /*** End of inlined file: jquant1.c ***/
  176820. /*** Start of inlined file: jquant2.c ***/
  176821. #define JPEG_INTERNALS
  176822. #ifdef QUANT_2PASS_SUPPORTED
  176823. /*
  176824. * This module implements the well-known Heckbert paradigm for color
  176825. * quantization. Most of the ideas used here can be traced back to
  176826. * Heckbert's seminal paper
  176827. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  176828. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  176829. *
  176830. * In the first pass over the image, we accumulate a histogram showing the
  176831. * usage count of each possible color. To keep the histogram to a reasonable
  176832. * size, we reduce the precision of the input; typical practice is to retain
  176833. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  176834. * in the same histogram cell.
  176835. *
  176836. * Next, the color-selection step begins with a box representing the whole
  176837. * color space, and repeatedly splits the "largest" remaining box until we
  176838. * have as many boxes as desired colors. Then the mean color in each
  176839. * remaining box becomes one of the possible output colors.
  176840. *
  176841. * The second pass over the image maps each input pixel to the closest output
  176842. * color (optionally after applying a Floyd-Steinberg dithering correction).
  176843. * This mapping is logically trivial, but making it go fast enough requires
  176844. * considerable care.
  176845. *
  176846. * Heckbert-style quantizers vary a good deal in their policies for choosing
  176847. * the "largest" box and deciding where to cut it. The particular policies
  176848. * used here have proved out well in experimental comparisons, but better ones
  176849. * may yet be found.
  176850. *
  176851. * In earlier versions of the IJG code, this module quantized in YCbCr color
  176852. * space, processing the raw upsampled data without a color conversion step.
  176853. * This allowed the color conversion math to be done only once per colormap
  176854. * entry, not once per pixel. However, that optimization precluded other
  176855. * useful optimizations (such as merging color conversion with upsampling)
  176856. * and it also interfered with desired capabilities such as quantizing to an
  176857. * externally-supplied colormap. We have therefore abandoned that approach.
  176858. * The present code works in the post-conversion color space, typically RGB.
  176859. *
  176860. * To improve the visual quality of the results, we actually work in scaled
  176861. * RGB space, giving G distances more weight than R, and R in turn more than
  176862. * B. To do everything in integer math, we must use integer scale factors.
  176863. * The 2/3/1 scale factors used here correspond loosely to the relative
  176864. * weights of the colors in the NTSC grayscale equation.
  176865. * If you want to use this code to quantize a non-RGB color space, you'll
  176866. * probably need to change these scale factors.
  176867. */
  176868. #define R_SCALE 2 /* scale R distances by this much */
  176869. #define G_SCALE 3 /* scale G distances by this much */
  176870. #define B_SCALE 1 /* and B by this much */
  176871. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  176872. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  176873. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  176874. * you'll get compile errors until you extend this logic. In that case
  176875. * you'll probably want to tweak the histogram sizes too.
  176876. */
  176877. #if RGB_RED == 0
  176878. #define C0_SCALE R_SCALE
  176879. #endif
  176880. #if RGB_BLUE == 0
  176881. #define C0_SCALE B_SCALE
  176882. #endif
  176883. #if RGB_GREEN == 1
  176884. #define C1_SCALE G_SCALE
  176885. #endif
  176886. #if RGB_RED == 2
  176887. #define C2_SCALE R_SCALE
  176888. #endif
  176889. #if RGB_BLUE == 2
  176890. #define C2_SCALE B_SCALE
  176891. #endif
  176892. /*
  176893. * First we have the histogram data structure and routines for creating it.
  176894. *
  176895. * The number of bits of precision can be adjusted by changing these symbols.
  176896. * We recommend keeping 6 bits for G and 5 each for R and B.
  176897. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  176898. * better results; if you are short of memory, 5 bits all around will save
  176899. * some space but degrade the results.
  176900. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  176901. * (preferably unsigned long) for each cell. In practice this is overkill;
  176902. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  176903. * and clamping those that do overflow to the maximum value will give close-
  176904. * enough results. This reduces the recommended histogram size from 256Kb
  176905. * to 128Kb, which is a useful savings on PC-class machines.
  176906. * (In the second pass the histogram space is re-used for pixel mapping data;
  176907. * in that capacity, each cell must be able to store zero to the number of
  176908. * desired colors. 16 bits/cell is plenty for that too.)
  176909. * Since the JPEG code is intended to run in small memory model on 80x86
  176910. * machines, we can't just allocate the histogram in one chunk. Instead
  176911. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  176912. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  176913. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  176914. * on 80x86 machines, the pointer row is in near memory but the actual
  176915. * arrays are in far memory (same arrangement as we use for image arrays).
  176916. */
  176917. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  176918. /* These will do the right thing for either R,G,B or B,G,R color order,
  176919. * but you may not like the results for other color orders.
  176920. */
  176921. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  176922. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  176923. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  176924. /* Number of elements along histogram axes. */
  176925. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  176926. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  176927. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  176928. /* These are the amounts to shift an input value to get a histogram index. */
  176929. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  176930. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  176931. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  176932. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  176933. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  176934. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  176935. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  176936. typedef hist2d * hist3d; /* type for top-level pointer */
  176937. /* Declarations for Floyd-Steinberg dithering.
  176938. *
  176939. * Errors are accumulated into the array fserrors[], at a resolution of
  176940. * 1/16th of a pixel count. The error at a given pixel is propagated
  176941. * to its not-yet-processed neighbors using the standard F-S fractions,
  176942. * ... (here) 7/16
  176943. * 3/16 5/16 1/16
  176944. * We work left-to-right on even rows, right-to-left on odd rows.
  176945. *
  176946. * We can get away with a single array (holding one row's worth of errors)
  176947. * by using it to store the current row's errors at pixel columns not yet
  176948. * processed, but the next row's errors at columns already processed. We
  176949. * need only a few extra variables to hold the errors immediately around the
  176950. * current column. (If we are lucky, those variables are in registers, but
  176951. * even if not, they're probably cheaper to access than array elements are.)
  176952. *
  176953. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  176954. * each end saves us from special-casing the first and last pixels.
  176955. * Each entry is three values long, one value for each color component.
  176956. *
  176957. * Note: on a wide image, we might not have enough room in a PC's near data
  176958. * segment to hold the error array; so it is allocated with alloc_large.
  176959. */
  176960. #if BITS_IN_JSAMPLE == 8
  176961. typedef INT16 FSERROR; /* 16 bits should be enough */
  176962. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  176963. #else
  176964. typedef INT32 FSERROR; /* may need more than 16 bits */
  176965. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  176966. #endif
  176967. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  176968. /* Private subobject */
  176969. typedef struct {
  176970. struct jpeg_color_quantizer pub; /* public fields */
  176971. /* Space for the eventually created colormap is stashed here */
  176972. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  176973. int desired; /* desired # of colors = size of colormap */
  176974. /* Variables for accumulating image statistics */
  176975. hist3d histogram; /* pointer to the histogram */
  176976. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  176977. /* Variables for Floyd-Steinberg dithering */
  176978. FSERRPTR fserrors; /* accumulated errors */
  176979. boolean on_odd_row; /* flag to remember which row we are on */
  176980. int * error_limiter; /* table for clamping the applied error */
  176981. } my_cquantizer2;
  176982. typedef my_cquantizer2 * my_cquantize_ptr2;
  176983. /*
  176984. * Prescan some rows of pixels.
  176985. * In this module the prescan simply updates the histogram, which has been
  176986. * initialized to zeroes by start_pass.
  176987. * An output_buf parameter is required by the method signature, but no data
  176988. * is actually output (in fact the buffer controller is probably passing a
  176989. * NULL pointer).
  176990. */
  176991. METHODDEF(void)
  176992. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  176993. JSAMPARRAY, int num_rows)
  176994. {
  176995. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  176996. register JSAMPROW ptr;
  176997. register histptr histp;
  176998. register hist3d histogram = cquantize->histogram;
  176999. int row;
  177000. JDIMENSION col;
  177001. JDIMENSION width = cinfo->output_width;
  177002. for (row = 0; row < num_rows; row++) {
  177003. ptr = input_buf[row];
  177004. for (col = width; col > 0; col--) {
  177005. /* get pixel value and index into the histogram */
  177006. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  177007. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  177008. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  177009. /* increment, check for overflow and undo increment if so. */
  177010. if (++(*histp) <= 0)
  177011. (*histp)--;
  177012. ptr += 3;
  177013. }
  177014. }
  177015. }
  177016. /*
  177017. * Next we have the really interesting routines: selection of a colormap
  177018. * given the completed histogram.
  177019. * These routines work with a list of "boxes", each representing a rectangular
  177020. * subset of the input color space (to histogram precision).
  177021. */
  177022. typedef struct {
  177023. /* The bounds of the box (inclusive); expressed as histogram indexes */
  177024. int c0min, c0max;
  177025. int c1min, c1max;
  177026. int c2min, c2max;
  177027. /* The volume (actually 2-norm) of the box */
  177028. INT32 volume;
  177029. /* The number of nonzero histogram cells within this box */
  177030. long colorcount;
  177031. } box;
  177032. typedef box * boxptr;
  177033. LOCAL(boxptr)
  177034. find_biggest_color_pop (boxptr boxlist, int numboxes)
  177035. /* Find the splittable box with the largest color population */
  177036. /* Returns NULL if no splittable boxes remain */
  177037. {
  177038. register boxptr boxp;
  177039. register int i;
  177040. register long maxc = 0;
  177041. boxptr which = NULL;
  177042. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  177043. if (boxp->colorcount > maxc && boxp->volume > 0) {
  177044. which = boxp;
  177045. maxc = boxp->colorcount;
  177046. }
  177047. }
  177048. return which;
  177049. }
  177050. LOCAL(boxptr)
  177051. find_biggest_volume (boxptr boxlist, int numboxes)
  177052. /* Find the splittable box with the largest (scaled) volume */
  177053. /* Returns NULL if no splittable boxes remain */
  177054. {
  177055. register boxptr boxp;
  177056. register int i;
  177057. register INT32 maxv = 0;
  177058. boxptr which = NULL;
  177059. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  177060. if (boxp->volume > maxv) {
  177061. which = boxp;
  177062. maxv = boxp->volume;
  177063. }
  177064. }
  177065. return which;
  177066. }
  177067. LOCAL(void)
  177068. update_box (j_decompress_ptr cinfo, boxptr boxp)
  177069. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  177070. /* and recompute its volume and population */
  177071. {
  177072. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177073. hist3d histogram = cquantize->histogram;
  177074. histptr histp;
  177075. int c0,c1,c2;
  177076. int c0min,c0max,c1min,c1max,c2min,c2max;
  177077. INT32 dist0,dist1,dist2;
  177078. long ccount;
  177079. c0min = boxp->c0min; c0max = boxp->c0max;
  177080. c1min = boxp->c1min; c1max = boxp->c1max;
  177081. c2min = boxp->c2min; c2max = boxp->c2max;
  177082. if (c0max > c0min)
  177083. for (c0 = c0min; c0 <= c0max; c0++)
  177084. for (c1 = c1min; c1 <= c1max; c1++) {
  177085. histp = & histogram[c0][c1][c2min];
  177086. for (c2 = c2min; c2 <= c2max; c2++)
  177087. if (*histp++ != 0) {
  177088. boxp->c0min = c0min = c0;
  177089. goto have_c0min;
  177090. }
  177091. }
  177092. have_c0min:
  177093. if (c0max > c0min)
  177094. for (c0 = c0max; c0 >= c0min; c0--)
  177095. for (c1 = c1min; c1 <= c1max; c1++) {
  177096. histp = & histogram[c0][c1][c2min];
  177097. for (c2 = c2min; c2 <= c2max; c2++)
  177098. if (*histp++ != 0) {
  177099. boxp->c0max = c0max = c0;
  177100. goto have_c0max;
  177101. }
  177102. }
  177103. have_c0max:
  177104. if (c1max > c1min)
  177105. for (c1 = c1min; c1 <= c1max; c1++)
  177106. for (c0 = c0min; c0 <= c0max; c0++) {
  177107. histp = & histogram[c0][c1][c2min];
  177108. for (c2 = c2min; c2 <= c2max; c2++)
  177109. if (*histp++ != 0) {
  177110. boxp->c1min = c1min = c1;
  177111. goto have_c1min;
  177112. }
  177113. }
  177114. have_c1min:
  177115. if (c1max > c1min)
  177116. for (c1 = c1max; c1 >= c1min; c1--)
  177117. for (c0 = c0min; c0 <= c0max; c0++) {
  177118. histp = & histogram[c0][c1][c2min];
  177119. for (c2 = c2min; c2 <= c2max; c2++)
  177120. if (*histp++ != 0) {
  177121. boxp->c1max = c1max = c1;
  177122. goto have_c1max;
  177123. }
  177124. }
  177125. have_c1max:
  177126. if (c2max > c2min)
  177127. for (c2 = c2min; c2 <= c2max; c2++)
  177128. for (c0 = c0min; c0 <= c0max; c0++) {
  177129. histp = & histogram[c0][c1min][c2];
  177130. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  177131. if (*histp != 0) {
  177132. boxp->c2min = c2min = c2;
  177133. goto have_c2min;
  177134. }
  177135. }
  177136. have_c2min:
  177137. if (c2max > c2min)
  177138. for (c2 = c2max; c2 >= c2min; c2--)
  177139. for (c0 = c0min; c0 <= c0max; c0++) {
  177140. histp = & histogram[c0][c1min][c2];
  177141. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  177142. if (*histp != 0) {
  177143. boxp->c2max = c2max = c2;
  177144. goto have_c2max;
  177145. }
  177146. }
  177147. have_c2max:
  177148. /* Update box volume.
  177149. * We use 2-norm rather than real volume here; this biases the method
  177150. * against making long narrow boxes, and it has the side benefit that
  177151. * a box is splittable iff norm > 0.
  177152. * Since the differences are expressed in histogram-cell units,
  177153. * we have to shift back to JSAMPLE units to get consistent distances;
  177154. * after which, we scale according to the selected distance scale factors.
  177155. */
  177156. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  177157. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  177158. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  177159. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  177160. /* Now scan remaining volume of box and compute population */
  177161. ccount = 0;
  177162. for (c0 = c0min; c0 <= c0max; c0++)
  177163. for (c1 = c1min; c1 <= c1max; c1++) {
  177164. histp = & histogram[c0][c1][c2min];
  177165. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  177166. if (*histp != 0) {
  177167. ccount++;
  177168. }
  177169. }
  177170. boxp->colorcount = ccount;
  177171. }
  177172. LOCAL(int)
  177173. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  177174. int desired_colors)
  177175. /* Repeatedly select and split the largest box until we have enough boxes */
  177176. {
  177177. int n,lb;
  177178. int c0,c1,c2,cmax;
  177179. register boxptr b1,b2;
  177180. while (numboxes < desired_colors) {
  177181. /* Select box to split.
  177182. * Current algorithm: by population for first half, then by volume.
  177183. */
  177184. if (numboxes*2 <= desired_colors) {
  177185. b1 = find_biggest_color_pop(boxlist, numboxes);
  177186. } else {
  177187. b1 = find_biggest_volume(boxlist, numboxes);
  177188. }
  177189. if (b1 == NULL) /* no splittable boxes left! */
  177190. break;
  177191. b2 = &boxlist[numboxes]; /* where new box will go */
  177192. /* Copy the color bounds to the new box. */
  177193. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  177194. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  177195. /* Choose which axis to split the box on.
  177196. * Current algorithm: longest scaled axis.
  177197. * See notes in update_box about scaling distances.
  177198. */
  177199. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  177200. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  177201. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  177202. /* We want to break any ties in favor of green, then red, blue last.
  177203. * This code does the right thing for R,G,B or B,G,R color orders only.
  177204. */
  177205. #if RGB_RED == 0
  177206. cmax = c1; n = 1;
  177207. if (c0 > cmax) { cmax = c0; n = 0; }
  177208. if (c2 > cmax) { n = 2; }
  177209. #else
  177210. cmax = c1; n = 1;
  177211. if (c2 > cmax) { cmax = c2; n = 2; }
  177212. if (c0 > cmax) { n = 0; }
  177213. #endif
  177214. /* Choose split point along selected axis, and update box bounds.
  177215. * Current algorithm: split at halfway point.
  177216. * (Since the box has been shrunk to minimum volume,
  177217. * any split will produce two nonempty subboxes.)
  177218. * Note that lb value is max for lower box, so must be < old max.
  177219. */
  177220. switch (n) {
  177221. case 0:
  177222. lb = (b1->c0max + b1->c0min) / 2;
  177223. b1->c0max = lb;
  177224. b2->c0min = lb+1;
  177225. break;
  177226. case 1:
  177227. lb = (b1->c1max + b1->c1min) / 2;
  177228. b1->c1max = lb;
  177229. b2->c1min = lb+1;
  177230. break;
  177231. case 2:
  177232. lb = (b1->c2max + b1->c2min) / 2;
  177233. b1->c2max = lb;
  177234. b2->c2min = lb+1;
  177235. break;
  177236. }
  177237. /* Update stats for boxes */
  177238. update_box(cinfo, b1);
  177239. update_box(cinfo, b2);
  177240. numboxes++;
  177241. }
  177242. return numboxes;
  177243. }
  177244. LOCAL(void)
  177245. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  177246. /* Compute representative color for a box, put it in colormap[icolor] */
  177247. {
  177248. /* Current algorithm: mean weighted by pixels (not colors) */
  177249. /* Note it is important to get the rounding correct! */
  177250. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177251. hist3d histogram = cquantize->histogram;
  177252. histptr histp;
  177253. int c0,c1,c2;
  177254. int c0min,c0max,c1min,c1max,c2min,c2max;
  177255. long count;
  177256. long total = 0;
  177257. long c0total = 0;
  177258. long c1total = 0;
  177259. long c2total = 0;
  177260. c0min = boxp->c0min; c0max = boxp->c0max;
  177261. c1min = boxp->c1min; c1max = boxp->c1max;
  177262. c2min = boxp->c2min; c2max = boxp->c2max;
  177263. for (c0 = c0min; c0 <= c0max; c0++)
  177264. for (c1 = c1min; c1 <= c1max; c1++) {
  177265. histp = & histogram[c0][c1][c2min];
  177266. for (c2 = c2min; c2 <= c2max; c2++) {
  177267. if ((count = *histp++) != 0) {
  177268. total += count;
  177269. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  177270. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  177271. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  177272. }
  177273. }
  177274. }
  177275. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  177276. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  177277. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  177278. }
  177279. LOCAL(void)
  177280. select_colors (j_decompress_ptr cinfo, int desired_colors)
  177281. /* Master routine for color selection */
  177282. {
  177283. boxptr boxlist;
  177284. int numboxes;
  177285. int i;
  177286. /* Allocate workspace for box list */
  177287. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  177288. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  177289. /* Initialize one box containing whole space */
  177290. numboxes = 1;
  177291. boxlist[0].c0min = 0;
  177292. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  177293. boxlist[0].c1min = 0;
  177294. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  177295. boxlist[0].c2min = 0;
  177296. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  177297. /* Shrink it to actually-used volume and set its statistics */
  177298. update_box(cinfo, & boxlist[0]);
  177299. /* Perform median-cut to produce final box list */
  177300. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  177301. /* Compute the representative color for each box, fill colormap */
  177302. for (i = 0; i < numboxes; i++)
  177303. compute_color(cinfo, & boxlist[i], i);
  177304. cinfo->actual_number_of_colors = numboxes;
  177305. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  177306. }
  177307. /*
  177308. * These routines are concerned with the time-critical task of mapping input
  177309. * colors to the nearest color in the selected colormap.
  177310. *
  177311. * We re-use the histogram space as an "inverse color map", essentially a
  177312. * cache for the results of nearest-color searches. All colors within a
  177313. * histogram cell will be mapped to the same colormap entry, namely the one
  177314. * closest to the cell's center. This may not be quite the closest entry to
  177315. * the actual input color, but it's almost as good. A zero in the cache
  177316. * indicates we haven't found the nearest color for that cell yet; the array
  177317. * is cleared to zeroes before starting the mapping pass. When we find the
  177318. * nearest color for a cell, its colormap index plus one is recorded in the
  177319. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  177320. * when they need to use an unfilled entry in the cache.
  177321. *
  177322. * Our method of efficiently finding nearest colors is based on the "locally
  177323. * sorted search" idea described by Heckbert and on the incremental distance
  177324. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  177325. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  177326. * the distances from a given colormap entry to each cell of the histogram can
  177327. * be computed quickly using an incremental method: the differences between
  177328. * distances to adjacent cells themselves differ by a constant. This allows a
  177329. * fairly fast implementation of the "brute force" approach of computing the
  177330. * distance from every colormap entry to every histogram cell. Unfortunately,
  177331. * it needs a work array to hold the best-distance-so-far for each histogram
  177332. * cell (because the inner loop has to be over cells, not colormap entries).
  177333. * The work array elements have to be INT32s, so the work array would need
  177334. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  177335. *
  177336. * To get around these problems, we apply Thomas' method to compute the
  177337. * nearest colors for only the cells within a small subbox of the histogram.
  177338. * The work array need be only as big as the subbox, so the memory usage
  177339. * problem is solved. Furthermore, we need not fill subboxes that are never
  177340. * referenced in pass2; many images use only part of the color gamut, so a
  177341. * fair amount of work is saved. An additional advantage of this
  177342. * approach is that we can apply Heckbert's locality criterion to quickly
  177343. * eliminate colormap entries that are far away from the subbox; typically
  177344. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  177345. * and we need not compute their distances to individual cells in the subbox.
  177346. * The speed of this approach is heavily influenced by the subbox size: too
  177347. * small means too much overhead, too big loses because Heckbert's criterion
  177348. * can't eliminate as many colormap entries. Empirically the best subbox
  177349. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  177350. *
  177351. * Thomas' article also describes a refined method which is asymptotically
  177352. * faster than the brute-force method, but it is also far more complex and
  177353. * cannot efficiently be applied to small subboxes. It is therefore not
  177354. * useful for programs intended to be portable to DOS machines. On machines
  177355. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  177356. * refined method might be faster than the present code --- but then again,
  177357. * it might not be any faster, and it's certainly more complicated.
  177358. */
  177359. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  177360. #define BOX_C0_LOG (HIST_C0_BITS-3)
  177361. #define BOX_C1_LOG (HIST_C1_BITS-3)
  177362. #define BOX_C2_LOG (HIST_C2_BITS-3)
  177363. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  177364. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  177365. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  177366. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  177367. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  177368. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  177369. /*
  177370. * The next three routines implement inverse colormap filling. They could
  177371. * all be folded into one big routine, but splitting them up this way saves
  177372. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  177373. * and may allow some compilers to produce better code by registerizing more
  177374. * inner-loop variables.
  177375. */
  177376. LOCAL(int)
  177377. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  177378. JSAMPLE colorlist[])
  177379. /* Locate the colormap entries close enough to an update box to be candidates
  177380. * for the nearest entry to some cell(s) in the update box. The update box
  177381. * is specified by the center coordinates of its first cell. The number of
  177382. * candidate colormap entries is returned, and their colormap indexes are
  177383. * placed in colorlist[].
  177384. * This routine uses Heckbert's "locally sorted search" criterion to select
  177385. * the colors that need further consideration.
  177386. */
  177387. {
  177388. int numcolors = cinfo->actual_number_of_colors;
  177389. int maxc0, maxc1, maxc2;
  177390. int centerc0, centerc1, centerc2;
  177391. int i, x, ncolors;
  177392. INT32 minmaxdist, min_dist, max_dist, tdist;
  177393. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  177394. /* Compute true coordinates of update box's upper corner and center.
  177395. * Actually we compute the coordinates of the center of the upper-corner
  177396. * histogram cell, which are the upper bounds of the volume we care about.
  177397. * Note that since ">>" rounds down, the "center" values may be closer to
  177398. * min than to max; hence comparisons to them must be "<=", not "<".
  177399. */
  177400. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  177401. centerc0 = (minc0 + maxc0) >> 1;
  177402. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  177403. centerc1 = (minc1 + maxc1) >> 1;
  177404. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  177405. centerc2 = (minc2 + maxc2) >> 1;
  177406. /* For each color in colormap, find:
  177407. * 1. its minimum squared-distance to any point in the update box
  177408. * (zero if color is within update box);
  177409. * 2. its maximum squared-distance to any point in the update box.
  177410. * Both of these can be found by considering only the corners of the box.
  177411. * We save the minimum distance for each color in mindist[];
  177412. * only the smallest maximum distance is of interest.
  177413. */
  177414. minmaxdist = 0x7FFFFFFFL;
  177415. for (i = 0; i < numcolors; i++) {
  177416. /* We compute the squared-c0-distance term, then add in the other two. */
  177417. x = GETJSAMPLE(cinfo->colormap[0][i]);
  177418. if (x < minc0) {
  177419. tdist = (x - minc0) * C0_SCALE;
  177420. min_dist = tdist*tdist;
  177421. tdist = (x - maxc0) * C0_SCALE;
  177422. max_dist = tdist*tdist;
  177423. } else if (x > maxc0) {
  177424. tdist = (x - maxc0) * C0_SCALE;
  177425. min_dist = tdist*tdist;
  177426. tdist = (x - minc0) * C0_SCALE;
  177427. max_dist = tdist*tdist;
  177428. } else {
  177429. /* within cell range so no contribution to min_dist */
  177430. min_dist = 0;
  177431. if (x <= centerc0) {
  177432. tdist = (x - maxc0) * C0_SCALE;
  177433. max_dist = tdist*tdist;
  177434. } else {
  177435. tdist = (x - minc0) * C0_SCALE;
  177436. max_dist = tdist*tdist;
  177437. }
  177438. }
  177439. x = GETJSAMPLE(cinfo->colormap[1][i]);
  177440. if (x < minc1) {
  177441. tdist = (x - minc1) * C1_SCALE;
  177442. min_dist += tdist*tdist;
  177443. tdist = (x - maxc1) * C1_SCALE;
  177444. max_dist += tdist*tdist;
  177445. } else if (x > maxc1) {
  177446. tdist = (x - maxc1) * C1_SCALE;
  177447. min_dist += tdist*tdist;
  177448. tdist = (x - minc1) * C1_SCALE;
  177449. max_dist += tdist*tdist;
  177450. } else {
  177451. /* within cell range so no contribution to min_dist */
  177452. if (x <= centerc1) {
  177453. tdist = (x - maxc1) * C1_SCALE;
  177454. max_dist += tdist*tdist;
  177455. } else {
  177456. tdist = (x - minc1) * C1_SCALE;
  177457. max_dist += tdist*tdist;
  177458. }
  177459. }
  177460. x = GETJSAMPLE(cinfo->colormap[2][i]);
  177461. if (x < minc2) {
  177462. tdist = (x - minc2) * C2_SCALE;
  177463. min_dist += tdist*tdist;
  177464. tdist = (x - maxc2) * C2_SCALE;
  177465. max_dist += tdist*tdist;
  177466. } else if (x > maxc2) {
  177467. tdist = (x - maxc2) * C2_SCALE;
  177468. min_dist += tdist*tdist;
  177469. tdist = (x - minc2) * C2_SCALE;
  177470. max_dist += tdist*tdist;
  177471. } else {
  177472. /* within cell range so no contribution to min_dist */
  177473. if (x <= centerc2) {
  177474. tdist = (x - maxc2) * C2_SCALE;
  177475. max_dist += tdist*tdist;
  177476. } else {
  177477. tdist = (x - minc2) * C2_SCALE;
  177478. max_dist += tdist*tdist;
  177479. }
  177480. }
  177481. mindist[i] = min_dist; /* save away the results */
  177482. if (max_dist < minmaxdist)
  177483. minmaxdist = max_dist;
  177484. }
  177485. /* Now we know that no cell in the update box is more than minmaxdist
  177486. * away from some colormap entry. Therefore, only colors that are
  177487. * within minmaxdist of some part of the box need be considered.
  177488. */
  177489. ncolors = 0;
  177490. for (i = 0; i < numcolors; i++) {
  177491. if (mindist[i] <= minmaxdist)
  177492. colorlist[ncolors++] = (JSAMPLE) i;
  177493. }
  177494. return ncolors;
  177495. }
  177496. LOCAL(void)
  177497. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  177498. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  177499. /* Find the closest colormap entry for each cell in the update box,
  177500. * given the list of candidate colors prepared by find_nearby_colors.
  177501. * Return the indexes of the closest entries in the bestcolor[] array.
  177502. * This routine uses Thomas' incremental distance calculation method to
  177503. * find the distance from a colormap entry to successive cells in the box.
  177504. */
  177505. {
  177506. int ic0, ic1, ic2;
  177507. int i, icolor;
  177508. register INT32 * bptr; /* pointer into bestdist[] array */
  177509. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  177510. INT32 dist0, dist1; /* initial distance values */
  177511. register INT32 dist2; /* current distance in inner loop */
  177512. INT32 xx0, xx1; /* distance increments */
  177513. register INT32 xx2;
  177514. INT32 inc0, inc1, inc2; /* initial values for increments */
  177515. /* This array holds the distance to the nearest-so-far color for each cell */
  177516. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  177517. /* Initialize best-distance for each cell of the update box */
  177518. bptr = bestdist;
  177519. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  177520. *bptr++ = 0x7FFFFFFFL;
  177521. /* For each color selected by find_nearby_colors,
  177522. * compute its distance to the center of each cell in the box.
  177523. * If that's less than best-so-far, update best distance and color number.
  177524. */
  177525. /* Nominal steps between cell centers ("x" in Thomas article) */
  177526. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  177527. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  177528. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  177529. for (i = 0; i < numcolors; i++) {
  177530. icolor = GETJSAMPLE(colorlist[i]);
  177531. /* Compute (square of) distance from minc0/c1/c2 to this color */
  177532. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  177533. dist0 = inc0*inc0;
  177534. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  177535. dist0 += inc1*inc1;
  177536. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  177537. dist0 += inc2*inc2;
  177538. /* Form the initial difference increments */
  177539. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  177540. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  177541. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  177542. /* Now loop over all cells in box, updating distance per Thomas method */
  177543. bptr = bestdist;
  177544. cptr = bestcolor;
  177545. xx0 = inc0;
  177546. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  177547. dist1 = dist0;
  177548. xx1 = inc1;
  177549. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  177550. dist2 = dist1;
  177551. xx2 = inc2;
  177552. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  177553. if (dist2 < *bptr) {
  177554. *bptr = dist2;
  177555. *cptr = (JSAMPLE) icolor;
  177556. }
  177557. dist2 += xx2;
  177558. xx2 += 2 * STEP_C2 * STEP_C2;
  177559. bptr++;
  177560. cptr++;
  177561. }
  177562. dist1 += xx1;
  177563. xx1 += 2 * STEP_C1 * STEP_C1;
  177564. }
  177565. dist0 += xx0;
  177566. xx0 += 2 * STEP_C0 * STEP_C0;
  177567. }
  177568. }
  177569. }
  177570. LOCAL(void)
  177571. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  177572. /* Fill the inverse-colormap entries in the update box that contains */
  177573. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  177574. /* we can fill as many others as we wish.) */
  177575. {
  177576. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177577. hist3d histogram = cquantize->histogram;
  177578. int minc0, minc1, minc2; /* lower left corner of update box */
  177579. int ic0, ic1, ic2;
  177580. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  177581. register histptr cachep; /* pointer into main cache array */
  177582. /* This array lists the candidate colormap indexes. */
  177583. JSAMPLE colorlist[MAXNUMCOLORS];
  177584. int numcolors; /* number of candidate colors */
  177585. /* This array holds the actually closest colormap index for each cell. */
  177586. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  177587. /* Convert cell coordinates to update box ID */
  177588. c0 >>= BOX_C0_LOG;
  177589. c1 >>= BOX_C1_LOG;
  177590. c2 >>= BOX_C2_LOG;
  177591. /* Compute true coordinates of update box's origin corner.
  177592. * Actually we compute the coordinates of the center of the corner
  177593. * histogram cell, which are the lower bounds of the volume we care about.
  177594. */
  177595. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  177596. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  177597. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  177598. /* Determine which colormap entries are close enough to be candidates
  177599. * for the nearest entry to some cell in the update box.
  177600. */
  177601. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  177602. /* Determine the actually nearest colors. */
  177603. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  177604. bestcolor);
  177605. /* Save the best color numbers (plus 1) in the main cache array */
  177606. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  177607. c1 <<= BOX_C1_LOG;
  177608. c2 <<= BOX_C2_LOG;
  177609. cptr = bestcolor;
  177610. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  177611. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  177612. cachep = & histogram[c0+ic0][c1+ic1][c2];
  177613. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  177614. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  177615. }
  177616. }
  177617. }
  177618. }
  177619. /*
  177620. * Map some rows of pixels to the output colormapped representation.
  177621. */
  177622. METHODDEF(void)
  177623. pass2_no_dither (j_decompress_ptr cinfo,
  177624. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  177625. /* This version performs no dithering */
  177626. {
  177627. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177628. hist3d histogram = cquantize->histogram;
  177629. register JSAMPROW inptr, outptr;
  177630. register histptr cachep;
  177631. register int c0, c1, c2;
  177632. int row;
  177633. JDIMENSION col;
  177634. JDIMENSION width = cinfo->output_width;
  177635. for (row = 0; row < num_rows; row++) {
  177636. inptr = input_buf[row];
  177637. outptr = output_buf[row];
  177638. for (col = width; col > 0; col--) {
  177639. /* get pixel value and index into the cache */
  177640. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  177641. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  177642. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  177643. cachep = & histogram[c0][c1][c2];
  177644. /* If we have not seen this color before, find nearest colormap entry */
  177645. /* and update the cache */
  177646. if (*cachep == 0)
  177647. fill_inverse_cmap(cinfo, c0,c1,c2);
  177648. /* Now emit the colormap index for this cell */
  177649. *outptr++ = (JSAMPLE) (*cachep - 1);
  177650. }
  177651. }
  177652. }
  177653. METHODDEF(void)
  177654. pass2_fs_dither (j_decompress_ptr cinfo,
  177655. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  177656. /* This version performs Floyd-Steinberg dithering */
  177657. {
  177658. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177659. hist3d histogram = cquantize->histogram;
  177660. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  177661. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  177662. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  177663. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  177664. JSAMPROW inptr; /* => current input pixel */
  177665. JSAMPROW outptr; /* => current output pixel */
  177666. histptr cachep;
  177667. int dir; /* +1 or -1 depending on direction */
  177668. int dir3; /* 3*dir, for advancing inptr & errorptr */
  177669. int row;
  177670. JDIMENSION col;
  177671. JDIMENSION width = cinfo->output_width;
  177672. JSAMPLE *range_limit = cinfo->sample_range_limit;
  177673. int *error_limit = cquantize->error_limiter;
  177674. JSAMPROW colormap0 = cinfo->colormap[0];
  177675. JSAMPROW colormap1 = cinfo->colormap[1];
  177676. JSAMPROW colormap2 = cinfo->colormap[2];
  177677. SHIFT_TEMPS
  177678. for (row = 0; row < num_rows; row++) {
  177679. inptr = input_buf[row];
  177680. outptr = output_buf[row];
  177681. if (cquantize->on_odd_row) {
  177682. /* work right to left in this row */
  177683. inptr += (width-1) * 3; /* so point to rightmost pixel */
  177684. outptr += width-1;
  177685. dir = -1;
  177686. dir3 = -3;
  177687. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  177688. cquantize->on_odd_row = FALSE; /* flip for next time */
  177689. } else {
  177690. /* work left to right in this row */
  177691. dir = 1;
  177692. dir3 = 3;
  177693. errorptr = cquantize->fserrors; /* => entry before first real column */
  177694. cquantize->on_odd_row = TRUE; /* flip for next time */
  177695. }
  177696. /* Preset error values: no error propagated to first pixel from left */
  177697. cur0 = cur1 = cur2 = 0;
  177698. /* and no error propagated to row below yet */
  177699. belowerr0 = belowerr1 = belowerr2 = 0;
  177700. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  177701. for (col = width; col > 0; col--) {
  177702. /* curN holds the error propagated from the previous pixel on the
  177703. * current line. Add the error propagated from the previous line
  177704. * to form the complete error correction term for this pixel, and
  177705. * round the error term (which is expressed * 16) to an integer.
  177706. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  177707. * for either sign of the error value.
  177708. * Note: errorptr points to *previous* column's array entry.
  177709. */
  177710. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  177711. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  177712. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  177713. /* Limit the error using transfer function set by init_error_limit.
  177714. * See comments with init_error_limit for rationale.
  177715. */
  177716. cur0 = error_limit[cur0];
  177717. cur1 = error_limit[cur1];
  177718. cur2 = error_limit[cur2];
  177719. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  177720. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  177721. * this sets the required size of the range_limit array.
  177722. */
  177723. cur0 += GETJSAMPLE(inptr[0]);
  177724. cur1 += GETJSAMPLE(inptr[1]);
  177725. cur2 += GETJSAMPLE(inptr[2]);
  177726. cur0 = GETJSAMPLE(range_limit[cur0]);
  177727. cur1 = GETJSAMPLE(range_limit[cur1]);
  177728. cur2 = GETJSAMPLE(range_limit[cur2]);
  177729. /* Index into the cache with adjusted pixel value */
  177730. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  177731. /* If we have not seen this color before, find nearest colormap */
  177732. /* entry and update the cache */
  177733. if (*cachep == 0)
  177734. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  177735. /* Now emit the colormap index for this cell */
  177736. { register int pixcode = *cachep - 1;
  177737. *outptr = (JSAMPLE) pixcode;
  177738. /* Compute representation error for this pixel */
  177739. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  177740. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  177741. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  177742. }
  177743. /* Compute error fractions to be propagated to adjacent pixels.
  177744. * Add these into the running sums, and simultaneously shift the
  177745. * next-line error sums left by 1 column.
  177746. */
  177747. { register LOCFSERROR bnexterr, delta;
  177748. bnexterr = cur0; /* Process component 0 */
  177749. delta = cur0 * 2;
  177750. cur0 += delta; /* form error * 3 */
  177751. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  177752. cur0 += delta; /* form error * 5 */
  177753. bpreverr0 = belowerr0 + cur0;
  177754. belowerr0 = bnexterr;
  177755. cur0 += delta; /* form error * 7 */
  177756. bnexterr = cur1; /* Process component 1 */
  177757. delta = cur1 * 2;
  177758. cur1 += delta; /* form error * 3 */
  177759. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  177760. cur1 += delta; /* form error * 5 */
  177761. bpreverr1 = belowerr1 + cur1;
  177762. belowerr1 = bnexterr;
  177763. cur1 += delta; /* form error * 7 */
  177764. bnexterr = cur2; /* Process component 2 */
  177765. delta = cur2 * 2;
  177766. cur2 += delta; /* form error * 3 */
  177767. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  177768. cur2 += delta; /* form error * 5 */
  177769. bpreverr2 = belowerr2 + cur2;
  177770. belowerr2 = bnexterr;
  177771. cur2 += delta; /* form error * 7 */
  177772. }
  177773. /* At this point curN contains the 7/16 error value to be propagated
  177774. * to the next pixel on the current line, and all the errors for the
  177775. * next line have been shifted over. We are therefore ready to move on.
  177776. */
  177777. inptr += dir3; /* Advance pixel pointers to next column */
  177778. outptr += dir;
  177779. errorptr += dir3; /* advance errorptr to current column */
  177780. }
  177781. /* Post-loop cleanup: we must unload the final error values into the
  177782. * final fserrors[] entry. Note we need not unload belowerrN because
  177783. * it is for the dummy column before or after the actual array.
  177784. */
  177785. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  177786. errorptr[1] = (FSERROR) bpreverr1;
  177787. errorptr[2] = (FSERROR) bpreverr2;
  177788. }
  177789. }
  177790. /*
  177791. * Initialize the error-limiting transfer function (lookup table).
  177792. * The raw F-S error computation can potentially compute error values of up to
  177793. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  177794. * much less, otherwise obviously wrong pixels will be created. (Typical
  177795. * effects include weird fringes at color-area boundaries, isolated bright
  177796. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  177797. * is to ensure that the "corners" of the color cube are allocated as output
  177798. * colors; then repeated errors in the same direction cannot cause cascading
  177799. * error buildup. However, that only prevents the error from getting
  177800. * completely out of hand; Aaron Giles reports that error limiting improves
  177801. * the results even with corner colors allocated.
  177802. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  177803. * well, but the smoother transfer function used below is even better. Thanks
  177804. * to Aaron Giles for this idea.
  177805. */
  177806. LOCAL(void)
  177807. init_error_limit (j_decompress_ptr cinfo)
  177808. /* Allocate and fill in the error_limiter table */
  177809. {
  177810. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177811. int * table;
  177812. int in, out;
  177813. table = (int *) (*cinfo->mem->alloc_small)
  177814. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  177815. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  177816. cquantize->error_limiter = table;
  177817. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  177818. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  177819. out = 0;
  177820. for (in = 0; in < STEPSIZE; in++, out++) {
  177821. table[in] = out; table[-in] = -out;
  177822. }
  177823. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  177824. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  177825. table[in] = out; table[-in] = -out;
  177826. }
  177827. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  177828. for (; in <= MAXJSAMPLE; in++) {
  177829. table[in] = out; table[-in] = -out;
  177830. }
  177831. #undef STEPSIZE
  177832. }
  177833. /*
  177834. * Finish up at the end of each pass.
  177835. */
  177836. METHODDEF(void)
  177837. finish_pass1 (j_decompress_ptr cinfo)
  177838. {
  177839. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177840. /* Select the representative colors and fill in cinfo->colormap */
  177841. cinfo->colormap = cquantize->sv_colormap;
  177842. select_colors(cinfo, cquantize->desired);
  177843. /* Force next pass to zero the color index table */
  177844. cquantize->needs_zeroed = TRUE;
  177845. }
  177846. METHODDEF(void)
  177847. finish_pass2 (j_decompress_ptr)
  177848. {
  177849. /* no work */
  177850. }
  177851. /*
  177852. * Initialize for each processing pass.
  177853. */
  177854. METHODDEF(void)
  177855. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  177856. {
  177857. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177858. hist3d histogram = cquantize->histogram;
  177859. int i;
  177860. /* Only F-S dithering or no dithering is supported. */
  177861. /* If user asks for ordered dither, give him F-S. */
  177862. if (cinfo->dither_mode != JDITHER_NONE)
  177863. cinfo->dither_mode = JDITHER_FS;
  177864. if (is_pre_scan) {
  177865. /* Set up method pointers */
  177866. cquantize->pub.color_quantize = prescan_quantize;
  177867. cquantize->pub.finish_pass = finish_pass1;
  177868. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  177869. } else {
  177870. /* Set up method pointers */
  177871. if (cinfo->dither_mode == JDITHER_FS)
  177872. cquantize->pub.color_quantize = pass2_fs_dither;
  177873. else
  177874. cquantize->pub.color_quantize = pass2_no_dither;
  177875. cquantize->pub.finish_pass = finish_pass2;
  177876. /* Make sure color count is acceptable */
  177877. i = cinfo->actual_number_of_colors;
  177878. if (i < 1)
  177879. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  177880. if (i > MAXNUMCOLORS)
  177881. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  177882. if (cinfo->dither_mode == JDITHER_FS) {
  177883. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  177884. (3 * SIZEOF(FSERROR)));
  177885. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  177886. if (cquantize->fserrors == NULL)
  177887. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  177888. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  177889. /* Initialize the propagated errors to zero. */
  177890. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  177891. /* Make the error-limit table if we didn't already. */
  177892. if (cquantize->error_limiter == NULL)
  177893. init_error_limit(cinfo);
  177894. cquantize->on_odd_row = FALSE;
  177895. }
  177896. }
  177897. /* Zero the histogram or inverse color map, if necessary */
  177898. if (cquantize->needs_zeroed) {
  177899. for (i = 0; i < HIST_C0_ELEMS; i++) {
  177900. jzero_far((void FAR *) histogram[i],
  177901. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  177902. }
  177903. cquantize->needs_zeroed = FALSE;
  177904. }
  177905. }
  177906. /*
  177907. * Switch to a new external colormap between output passes.
  177908. */
  177909. METHODDEF(void)
  177910. new_color_map_2_quant (j_decompress_ptr cinfo)
  177911. {
  177912. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177913. /* Reset the inverse color map */
  177914. cquantize->needs_zeroed = TRUE;
  177915. }
  177916. /*
  177917. * Module initialization routine for 2-pass color quantization.
  177918. */
  177919. GLOBAL(void)
  177920. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  177921. {
  177922. my_cquantize_ptr2 cquantize;
  177923. int i;
  177924. cquantize = (my_cquantize_ptr2)
  177925. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177926. SIZEOF(my_cquantizer2));
  177927. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  177928. cquantize->pub.start_pass = start_pass_2_quant;
  177929. cquantize->pub.new_color_map = new_color_map_2_quant;
  177930. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  177931. cquantize->error_limiter = NULL;
  177932. /* Make sure jdmaster didn't give me a case I can't handle */
  177933. if (cinfo->out_color_components != 3)
  177934. ERREXIT(cinfo, JERR_NOTIMPL);
  177935. /* Allocate the histogram/inverse colormap storage */
  177936. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  177937. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  177938. for (i = 0; i < HIST_C0_ELEMS; i++) {
  177939. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  177940. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177941. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  177942. }
  177943. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  177944. /* Allocate storage for the completed colormap, if required.
  177945. * We do this now since it is FAR storage and may affect
  177946. * the memory manager's space calculations.
  177947. */
  177948. if (cinfo->enable_2pass_quant) {
  177949. /* Make sure color count is acceptable */
  177950. int desired = cinfo->desired_number_of_colors;
  177951. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  177952. if (desired < 8)
  177953. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  177954. /* Make sure colormap indexes can be represented by JSAMPLEs */
  177955. if (desired > MAXNUMCOLORS)
  177956. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  177957. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  177958. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  177959. cquantize->desired = desired;
  177960. } else
  177961. cquantize->sv_colormap = NULL;
  177962. /* Only F-S dithering or no dithering is supported. */
  177963. /* If user asks for ordered dither, give him F-S. */
  177964. if (cinfo->dither_mode != JDITHER_NONE)
  177965. cinfo->dither_mode = JDITHER_FS;
  177966. /* Allocate Floyd-Steinberg workspace if necessary.
  177967. * This isn't really needed until pass 2, but again it is FAR storage.
  177968. * Although we will cope with a later change in dither_mode,
  177969. * we do not promise to honor max_memory_to_use if dither_mode changes.
  177970. */
  177971. if (cinfo->dither_mode == JDITHER_FS) {
  177972. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  177973. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177974. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  177975. /* Might as well create the error-limiting table too. */
  177976. init_error_limit(cinfo);
  177977. }
  177978. }
  177979. #endif /* QUANT_2PASS_SUPPORTED */
  177980. /*** End of inlined file: jquant2.c ***/
  177981. /*** Start of inlined file: jutils.c ***/
  177982. #define JPEG_INTERNALS
  177983. /*
  177984. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  177985. * of a DCT block read in natural order (left to right, top to bottom).
  177986. */
  177987. #if 0 /* This table is not actually needed in v6a */
  177988. const int jpeg_zigzag_order[DCTSIZE2] = {
  177989. 0, 1, 5, 6, 14, 15, 27, 28,
  177990. 2, 4, 7, 13, 16, 26, 29, 42,
  177991. 3, 8, 12, 17, 25, 30, 41, 43,
  177992. 9, 11, 18, 24, 31, 40, 44, 53,
  177993. 10, 19, 23, 32, 39, 45, 52, 54,
  177994. 20, 22, 33, 38, 46, 51, 55, 60,
  177995. 21, 34, 37, 47, 50, 56, 59, 61,
  177996. 35, 36, 48, 49, 57, 58, 62, 63
  177997. };
  177998. #endif
  177999. /*
  178000. * jpeg_natural_order[i] is the natural-order position of the i'th element
  178001. * of zigzag order.
  178002. *
  178003. * When reading corrupted data, the Huffman decoders could attempt
  178004. * to reference an entry beyond the end of this array (if the decoded
  178005. * zero run length reaches past the end of the block). To prevent
  178006. * wild stores without adding an inner-loop test, we put some extra
  178007. * "63"s after the real entries. This will cause the extra coefficient
  178008. * to be stored in location 63 of the block, not somewhere random.
  178009. * The worst case would be a run-length of 15, which means we need 16
  178010. * fake entries.
  178011. */
  178012. const int jpeg_natural_order[DCTSIZE2+16] = {
  178013. 0, 1, 8, 16, 9, 2, 3, 10,
  178014. 17, 24, 32, 25, 18, 11, 4, 5,
  178015. 12, 19, 26, 33, 40, 48, 41, 34,
  178016. 27, 20, 13, 6, 7, 14, 21, 28,
  178017. 35, 42, 49, 56, 57, 50, 43, 36,
  178018. 29, 22, 15, 23, 30, 37, 44, 51,
  178019. 58, 59, 52, 45, 38, 31, 39, 46,
  178020. 53, 60, 61, 54, 47, 55, 62, 63,
  178021. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  178022. 63, 63, 63, 63, 63, 63, 63, 63
  178023. };
  178024. /*
  178025. * Arithmetic utilities
  178026. */
  178027. GLOBAL(long)
  178028. jdiv_round_up (long a, long b)
  178029. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  178030. /* Assumes a >= 0, b > 0 */
  178031. {
  178032. return (a + b - 1L) / b;
  178033. }
  178034. GLOBAL(long)
  178035. jround_up (long a, long b)
  178036. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  178037. /* Assumes a >= 0, b > 0 */
  178038. {
  178039. a += b - 1L;
  178040. return a - (a % b);
  178041. }
  178042. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  178043. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  178044. * are FAR and we're assuming a small-pointer memory model. However, some
  178045. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  178046. * in the small-model libraries. These will be used if USE_FMEM is defined.
  178047. * Otherwise, the routines below do it the hard way. (The performance cost
  178048. * is not all that great, because these routines aren't very heavily used.)
  178049. */
  178050. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  178051. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  178052. #define FMEMZERO(target,size) MEMZERO(target,size)
  178053. #else /* 80x86 case, define if we can */
  178054. #ifdef USE_FMEM
  178055. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  178056. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  178057. #endif
  178058. #endif
  178059. GLOBAL(void)
  178060. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  178061. JSAMPARRAY output_array, int dest_row,
  178062. int num_rows, JDIMENSION num_cols)
  178063. /* Copy some rows of samples from one place to another.
  178064. * num_rows rows are copied from input_array[source_row++]
  178065. * to output_array[dest_row++]; these areas may overlap for duplication.
  178066. * The source and destination arrays must be at least as wide as num_cols.
  178067. */
  178068. {
  178069. register JSAMPROW inptr, outptr;
  178070. #ifdef FMEMCOPY
  178071. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  178072. #else
  178073. register JDIMENSION count;
  178074. #endif
  178075. register int row;
  178076. input_array += source_row;
  178077. output_array += dest_row;
  178078. for (row = num_rows; row > 0; row--) {
  178079. inptr = *input_array++;
  178080. outptr = *output_array++;
  178081. #ifdef FMEMCOPY
  178082. FMEMCOPY(outptr, inptr, count);
  178083. #else
  178084. for (count = num_cols; count > 0; count--)
  178085. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  178086. #endif
  178087. }
  178088. }
  178089. GLOBAL(void)
  178090. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  178091. JDIMENSION num_blocks)
  178092. /* Copy a row of coefficient blocks from one place to another. */
  178093. {
  178094. #ifdef FMEMCOPY
  178095. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  178096. #else
  178097. register JCOEFPTR inptr, outptr;
  178098. register long count;
  178099. inptr = (JCOEFPTR) input_row;
  178100. outptr = (JCOEFPTR) output_row;
  178101. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  178102. *outptr++ = *inptr++;
  178103. }
  178104. #endif
  178105. }
  178106. GLOBAL(void)
  178107. jzero_far (void FAR * target, size_t bytestozero)
  178108. /* Zero out a chunk of FAR memory. */
  178109. /* This might be sample-array data, block-array data, or alloc_large data. */
  178110. {
  178111. #ifdef FMEMZERO
  178112. FMEMZERO(target, bytestozero);
  178113. #else
  178114. register char FAR * ptr = (char FAR *) target;
  178115. register size_t count;
  178116. for (count = bytestozero; count > 0; count--) {
  178117. *ptr++ = 0;
  178118. }
  178119. #endif
  178120. }
  178121. /*** End of inlined file: jutils.c ***/
  178122. /*** Start of inlined file: transupp.c ***/
  178123. /* Although this file really shouldn't have access to the library internals,
  178124. * it's helpful to let it call jround_up() and jcopy_block_row().
  178125. */
  178126. #define JPEG_INTERNALS
  178127. /*** Start of inlined file: transupp.h ***/
  178128. /* If you happen not to want the image transform support, disable it here */
  178129. #ifndef TRANSFORMS_SUPPORTED
  178130. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  178131. #endif
  178132. /* Short forms of external names for systems with brain-damaged linkers. */
  178133. #ifdef NEED_SHORT_EXTERNAL_NAMES
  178134. #define jtransform_request_workspace jTrRequest
  178135. #define jtransform_adjust_parameters jTrAdjust
  178136. #define jtransform_execute_transformation jTrExec
  178137. #define jcopy_markers_setup jCMrkSetup
  178138. #define jcopy_markers_execute jCMrkExec
  178139. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  178140. /*
  178141. * Codes for supported types of image transformations.
  178142. */
  178143. typedef enum {
  178144. JXFORM_NONE, /* no transformation */
  178145. JXFORM_FLIP_H, /* horizontal flip */
  178146. JXFORM_FLIP_V, /* vertical flip */
  178147. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  178148. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  178149. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  178150. JXFORM_ROT_180, /* 180-degree rotation */
  178151. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  178152. } JXFORM_CODE;
  178153. /*
  178154. * Although rotating and flipping data expressed as DCT coefficients is not
  178155. * hard, there is an asymmetry in the JPEG format specification for images
  178156. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  178157. * image edges are padded out to the next iMCU boundary with junk data; but
  178158. * no padding is possible at the top and left edges. If we were to flip
  178159. * the whole image including the pad data, then pad garbage would become
  178160. * visible at the top and/or left, and real pixels would disappear into the
  178161. * pad margins --- perhaps permanently, since encoders & decoders may not
  178162. * bother to preserve DCT blocks that appear to be completely outside the
  178163. * nominal image area. So, we have to exclude any partial iMCUs from the
  178164. * basic transformation.
  178165. *
  178166. * Transpose is the only transformation that can handle partial iMCUs at the
  178167. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  178168. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  178169. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  178170. * The other transforms are defined as combinations of these basic transforms
  178171. * and process edge blocks in a way that preserves the equivalence.
  178172. *
  178173. * The "trim" option causes untransformable partial iMCUs to be dropped;
  178174. * this is not strictly lossless, but it usually gives the best-looking
  178175. * result for odd-size images. Note that when this option is active,
  178176. * the expected mathematical equivalences between the transforms may not hold.
  178177. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  178178. * followed by -rot 180 -trim trims both edges.)
  178179. *
  178180. * We also offer a "force to grayscale" option, which simply discards the
  178181. * chrominance channels of a YCbCr image. This is lossless in the sense that
  178182. * the luminance channel is preserved exactly. It's not the same kind of
  178183. * thing as the rotate/flip transformations, but it's convenient to handle it
  178184. * as part of this package, mainly because the transformation routines have to
  178185. * be aware of the option to know how many components to work on.
  178186. */
  178187. typedef struct {
  178188. /* Options: set by caller */
  178189. JXFORM_CODE transform; /* image transform operator */
  178190. boolean trim; /* if TRUE, trim partial MCUs as needed */
  178191. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  178192. /* Internal workspace: caller should not touch these */
  178193. int num_components; /* # of components in workspace */
  178194. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  178195. } jpeg_transform_info;
  178196. #if TRANSFORMS_SUPPORTED
  178197. /* Request any required workspace */
  178198. EXTERN(void) jtransform_request_workspace
  178199. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  178200. /* Adjust output image parameters */
  178201. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  178202. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178203. jvirt_barray_ptr *src_coef_arrays,
  178204. jpeg_transform_info *info));
  178205. /* Execute the actual transformation, if any */
  178206. EXTERN(void) jtransform_execute_transformation
  178207. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178208. jvirt_barray_ptr *src_coef_arrays,
  178209. jpeg_transform_info *info));
  178210. #endif /* TRANSFORMS_SUPPORTED */
  178211. /*
  178212. * Support for copying optional markers from source to destination file.
  178213. */
  178214. typedef enum {
  178215. JCOPYOPT_NONE, /* copy no optional markers */
  178216. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  178217. JCOPYOPT_ALL /* copy all optional markers */
  178218. } JCOPY_OPTION;
  178219. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  178220. /* Setup decompression object to save desired markers in memory */
  178221. EXTERN(void) jcopy_markers_setup
  178222. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  178223. /* Copy markers saved in the given source object to the destination object */
  178224. EXTERN(void) jcopy_markers_execute
  178225. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178226. JCOPY_OPTION option));
  178227. /*** End of inlined file: transupp.h ***/
  178228. /* My own external interface */
  178229. #if TRANSFORMS_SUPPORTED
  178230. /*
  178231. * Lossless image transformation routines. These routines work on DCT
  178232. * coefficient arrays and thus do not require any lossy decompression
  178233. * or recompression of the image.
  178234. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  178235. *
  178236. * Horizontal flipping is done in-place, using a single top-to-bottom
  178237. * pass through the virtual source array. It will thus be much the
  178238. * fastest option for images larger than main memory.
  178239. *
  178240. * The other routines require a set of destination virtual arrays, so they
  178241. * need twice as much memory as jpegtran normally does. The destination
  178242. * arrays are always written in normal scan order (top to bottom) because
  178243. * the virtual array manager expects this. The source arrays will be scanned
  178244. * in the corresponding order, which means multiple passes through the source
  178245. * arrays for most of the transforms. That could result in much thrashing
  178246. * if the image is larger than main memory.
  178247. *
  178248. * Some notes about the operating environment of the individual transform
  178249. * routines:
  178250. * 1. Both the source and destination virtual arrays are allocated from the
  178251. * source JPEG object, and therefore should be manipulated by calling the
  178252. * source's memory manager.
  178253. * 2. The destination's component count should be used. It may be smaller
  178254. * than the source's when forcing to grayscale.
  178255. * 3. Likewise the destination's sampling factors should be used. When
  178256. * forcing to grayscale the destination's sampling factors will be all 1,
  178257. * and we may as well take that as the effective iMCU size.
  178258. * 4. When "trim" is in effect, the destination's dimensions will be the
  178259. * trimmed values but the source's will be untrimmed.
  178260. * 5. All the routines assume that the source and destination buffers are
  178261. * padded out to a full iMCU boundary. This is true, although for the
  178262. * source buffer it is an undocumented property of jdcoefct.c.
  178263. * Notes 2,3,4 boil down to this: generally we should use the destination's
  178264. * dimensions and ignore the source's.
  178265. */
  178266. LOCAL(void)
  178267. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178268. jvirt_barray_ptr *src_coef_arrays)
  178269. /* Horizontal flip; done in-place, so no separate dest array is required */
  178270. {
  178271. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  178272. int ci, k, offset_y;
  178273. JBLOCKARRAY buffer;
  178274. JCOEFPTR ptr1, ptr2;
  178275. JCOEF temp1, temp2;
  178276. jpeg_component_info *compptr;
  178277. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  178278. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  178279. * mirroring by changing the signs of odd-numbered columns.
  178280. * Partial iMCUs at the right edge are left untouched.
  178281. */
  178282. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  178283. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178284. compptr = dstinfo->comp_info + ci;
  178285. comp_width = MCU_cols * compptr->h_samp_factor;
  178286. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  178287. blk_y += compptr->v_samp_factor) {
  178288. buffer = (*srcinfo->mem->access_virt_barray)
  178289. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  178290. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178291. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178292. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  178293. ptr1 = buffer[offset_y][blk_x];
  178294. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  178295. /* this unrolled loop doesn't need to know which row it's on... */
  178296. for (k = 0; k < DCTSIZE2; k += 2) {
  178297. temp1 = *ptr1; /* swap even column */
  178298. temp2 = *ptr2;
  178299. *ptr1++ = temp2;
  178300. *ptr2++ = temp1;
  178301. temp1 = *ptr1; /* swap odd column with sign change */
  178302. temp2 = *ptr2;
  178303. *ptr1++ = -temp2;
  178304. *ptr2++ = -temp1;
  178305. }
  178306. }
  178307. }
  178308. }
  178309. }
  178310. }
  178311. LOCAL(void)
  178312. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178313. jvirt_barray_ptr *src_coef_arrays,
  178314. jvirt_barray_ptr *dst_coef_arrays)
  178315. /* Vertical flip */
  178316. {
  178317. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  178318. int ci, i, j, offset_y;
  178319. JBLOCKARRAY src_buffer, dst_buffer;
  178320. JBLOCKROW src_row_ptr, dst_row_ptr;
  178321. JCOEFPTR src_ptr, dst_ptr;
  178322. jpeg_component_info *compptr;
  178323. /* We output into a separate array because we can't touch different
  178324. * rows of the source virtual array simultaneously. Otherwise, this
  178325. * is a pretty straightforward analog of horizontal flip.
  178326. * Within a DCT block, vertical mirroring is done by changing the signs
  178327. * of odd-numbered rows.
  178328. * Partial iMCUs at the bottom edge are copied verbatim.
  178329. */
  178330. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  178331. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178332. compptr = dstinfo->comp_info + ci;
  178333. comp_height = MCU_rows * compptr->v_samp_factor;
  178334. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178335. dst_blk_y += compptr->v_samp_factor) {
  178336. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178337. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178338. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178339. if (dst_blk_y < comp_height) {
  178340. /* Row is within the mirrorable area. */
  178341. src_buffer = (*srcinfo->mem->access_virt_barray)
  178342. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  178343. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  178344. (JDIMENSION) compptr->v_samp_factor, FALSE);
  178345. } else {
  178346. /* Bottom-edge blocks will be copied verbatim. */
  178347. src_buffer = (*srcinfo->mem->access_virt_barray)
  178348. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  178349. (JDIMENSION) compptr->v_samp_factor, FALSE);
  178350. }
  178351. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178352. if (dst_blk_y < comp_height) {
  178353. /* Row is within the mirrorable area. */
  178354. dst_row_ptr = dst_buffer[offset_y];
  178355. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  178356. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178357. dst_blk_x++) {
  178358. dst_ptr = dst_row_ptr[dst_blk_x];
  178359. src_ptr = src_row_ptr[dst_blk_x];
  178360. for (i = 0; i < DCTSIZE; i += 2) {
  178361. /* copy even row */
  178362. for (j = 0; j < DCTSIZE; j++)
  178363. *dst_ptr++ = *src_ptr++;
  178364. /* copy odd row with sign change */
  178365. for (j = 0; j < DCTSIZE; j++)
  178366. *dst_ptr++ = - *src_ptr++;
  178367. }
  178368. }
  178369. } else {
  178370. /* Just copy row verbatim. */
  178371. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  178372. compptr->width_in_blocks);
  178373. }
  178374. }
  178375. }
  178376. }
  178377. }
  178378. LOCAL(void)
  178379. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178380. jvirt_barray_ptr *src_coef_arrays,
  178381. jvirt_barray_ptr *dst_coef_arrays)
  178382. /* Transpose source into destination */
  178383. {
  178384. JDIMENSION dst_blk_x, dst_blk_y;
  178385. int ci, i, j, offset_x, offset_y;
  178386. JBLOCKARRAY src_buffer, dst_buffer;
  178387. JCOEFPTR src_ptr, dst_ptr;
  178388. jpeg_component_info *compptr;
  178389. /* Transposing pixels within a block just requires transposing the
  178390. * DCT coefficients.
  178391. * Partial iMCUs at the edges require no special treatment; we simply
  178392. * process all the available DCT blocks for every component.
  178393. */
  178394. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178395. compptr = dstinfo->comp_info + ci;
  178396. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178397. dst_blk_y += compptr->v_samp_factor) {
  178398. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178399. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178400. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178401. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178402. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178403. dst_blk_x += compptr->h_samp_factor) {
  178404. src_buffer = (*srcinfo->mem->access_virt_barray)
  178405. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  178406. (JDIMENSION) compptr->h_samp_factor, FALSE);
  178407. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  178408. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  178409. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  178410. for (i = 0; i < DCTSIZE; i++)
  178411. for (j = 0; j < DCTSIZE; j++)
  178412. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178413. }
  178414. }
  178415. }
  178416. }
  178417. }
  178418. }
  178419. LOCAL(void)
  178420. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178421. jvirt_barray_ptr *src_coef_arrays,
  178422. jvirt_barray_ptr *dst_coef_arrays)
  178423. /* 90 degree rotation is equivalent to
  178424. * 1. Transposing the image;
  178425. * 2. Horizontal mirroring.
  178426. * These two steps are merged into a single processing routine.
  178427. */
  178428. {
  178429. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  178430. int ci, i, j, offset_x, offset_y;
  178431. JBLOCKARRAY src_buffer, dst_buffer;
  178432. JCOEFPTR src_ptr, dst_ptr;
  178433. jpeg_component_info *compptr;
  178434. /* Because of the horizontal mirror step, we can't process partial iMCUs
  178435. * at the (output) right edge properly. They just get transposed and
  178436. * not mirrored.
  178437. */
  178438. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  178439. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178440. compptr = dstinfo->comp_info + ci;
  178441. comp_width = MCU_cols * compptr->h_samp_factor;
  178442. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178443. dst_blk_y += compptr->v_samp_factor) {
  178444. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178445. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178446. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178447. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178448. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178449. dst_blk_x += compptr->h_samp_factor) {
  178450. src_buffer = (*srcinfo->mem->access_virt_barray)
  178451. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  178452. (JDIMENSION) compptr->h_samp_factor, FALSE);
  178453. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  178454. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  178455. if (dst_blk_x < comp_width) {
  178456. /* Block is within the mirrorable area. */
  178457. dst_ptr = dst_buffer[offset_y]
  178458. [comp_width - dst_blk_x - offset_x - 1];
  178459. for (i = 0; i < DCTSIZE; i++) {
  178460. for (j = 0; j < DCTSIZE; j++)
  178461. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178462. i++;
  178463. for (j = 0; j < DCTSIZE; j++)
  178464. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  178465. }
  178466. } else {
  178467. /* Edge blocks are transposed but not mirrored. */
  178468. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  178469. for (i = 0; i < DCTSIZE; i++)
  178470. for (j = 0; j < DCTSIZE; j++)
  178471. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178472. }
  178473. }
  178474. }
  178475. }
  178476. }
  178477. }
  178478. }
  178479. LOCAL(void)
  178480. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178481. jvirt_barray_ptr *src_coef_arrays,
  178482. jvirt_barray_ptr *dst_coef_arrays)
  178483. /* 270 degree rotation is equivalent to
  178484. * 1. Horizontal mirroring;
  178485. * 2. Transposing the image.
  178486. * These two steps are merged into a single processing routine.
  178487. */
  178488. {
  178489. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  178490. int ci, i, j, offset_x, offset_y;
  178491. JBLOCKARRAY src_buffer, dst_buffer;
  178492. JCOEFPTR src_ptr, dst_ptr;
  178493. jpeg_component_info *compptr;
  178494. /* Because of the horizontal mirror step, we can't process partial iMCUs
  178495. * at the (output) bottom edge properly. They just get transposed and
  178496. * not mirrored.
  178497. */
  178498. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  178499. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178500. compptr = dstinfo->comp_info + ci;
  178501. comp_height = MCU_rows * compptr->v_samp_factor;
  178502. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178503. dst_blk_y += compptr->v_samp_factor) {
  178504. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178505. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178506. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178507. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178508. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178509. dst_blk_x += compptr->h_samp_factor) {
  178510. src_buffer = (*srcinfo->mem->access_virt_barray)
  178511. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  178512. (JDIMENSION) compptr->h_samp_factor, FALSE);
  178513. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  178514. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  178515. if (dst_blk_y < comp_height) {
  178516. /* Block is within the mirrorable area. */
  178517. src_ptr = src_buffer[offset_x]
  178518. [comp_height - dst_blk_y - offset_y - 1];
  178519. for (i = 0; i < DCTSIZE; i++) {
  178520. for (j = 0; j < DCTSIZE; j++) {
  178521. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178522. j++;
  178523. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  178524. }
  178525. }
  178526. } else {
  178527. /* Edge blocks are transposed but not mirrored. */
  178528. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  178529. for (i = 0; i < DCTSIZE; i++)
  178530. for (j = 0; j < DCTSIZE; j++)
  178531. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178532. }
  178533. }
  178534. }
  178535. }
  178536. }
  178537. }
  178538. }
  178539. LOCAL(void)
  178540. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178541. jvirt_barray_ptr *src_coef_arrays,
  178542. jvirt_barray_ptr *dst_coef_arrays)
  178543. /* 180 degree rotation is equivalent to
  178544. * 1. Vertical mirroring;
  178545. * 2. Horizontal mirroring.
  178546. * These two steps are merged into a single processing routine.
  178547. */
  178548. {
  178549. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  178550. int ci, i, j, offset_y;
  178551. JBLOCKARRAY src_buffer, dst_buffer;
  178552. JBLOCKROW src_row_ptr, dst_row_ptr;
  178553. JCOEFPTR src_ptr, dst_ptr;
  178554. jpeg_component_info *compptr;
  178555. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  178556. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  178557. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178558. compptr = dstinfo->comp_info + ci;
  178559. comp_width = MCU_cols * compptr->h_samp_factor;
  178560. comp_height = MCU_rows * compptr->v_samp_factor;
  178561. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178562. dst_blk_y += compptr->v_samp_factor) {
  178563. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178564. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178565. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178566. if (dst_blk_y < comp_height) {
  178567. /* Row is within the vertically mirrorable area. */
  178568. src_buffer = (*srcinfo->mem->access_virt_barray)
  178569. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  178570. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  178571. (JDIMENSION) compptr->v_samp_factor, FALSE);
  178572. } else {
  178573. /* Bottom-edge rows are only mirrored horizontally. */
  178574. src_buffer = (*srcinfo->mem->access_virt_barray)
  178575. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  178576. (JDIMENSION) compptr->v_samp_factor, FALSE);
  178577. }
  178578. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178579. if (dst_blk_y < comp_height) {
  178580. /* Row is within the mirrorable area. */
  178581. dst_row_ptr = dst_buffer[offset_y];
  178582. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  178583. /* Process the blocks that can be mirrored both ways. */
  178584. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  178585. dst_ptr = dst_row_ptr[dst_blk_x];
  178586. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  178587. for (i = 0; i < DCTSIZE; i += 2) {
  178588. /* For even row, negate every odd column. */
  178589. for (j = 0; j < DCTSIZE; j += 2) {
  178590. *dst_ptr++ = *src_ptr++;
  178591. *dst_ptr++ = - *src_ptr++;
  178592. }
  178593. /* For odd row, negate every even column. */
  178594. for (j = 0; j < DCTSIZE; j += 2) {
  178595. *dst_ptr++ = - *src_ptr++;
  178596. *dst_ptr++ = *src_ptr++;
  178597. }
  178598. }
  178599. }
  178600. /* Any remaining right-edge blocks are only mirrored vertically. */
  178601. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  178602. dst_ptr = dst_row_ptr[dst_blk_x];
  178603. src_ptr = src_row_ptr[dst_blk_x];
  178604. for (i = 0; i < DCTSIZE; i += 2) {
  178605. for (j = 0; j < DCTSIZE; j++)
  178606. *dst_ptr++ = *src_ptr++;
  178607. for (j = 0; j < DCTSIZE; j++)
  178608. *dst_ptr++ = - *src_ptr++;
  178609. }
  178610. }
  178611. } else {
  178612. /* Remaining rows are just mirrored horizontally. */
  178613. dst_row_ptr = dst_buffer[offset_y];
  178614. src_row_ptr = src_buffer[offset_y];
  178615. /* Process the blocks that can be mirrored. */
  178616. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  178617. dst_ptr = dst_row_ptr[dst_blk_x];
  178618. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  178619. for (i = 0; i < DCTSIZE2; i += 2) {
  178620. *dst_ptr++ = *src_ptr++;
  178621. *dst_ptr++ = - *src_ptr++;
  178622. }
  178623. }
  178624. /* Any remaining right-edge blocks are only copied. */
  178625. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  178626. dst_ptr = dst_row_ptr[dst_blk_x];
  178627. src_ptr = src_row_ptr[dst_blk_x];
  178628. for (i = 0; i < DCTSIZE2; i++)
  178629. *dst_ptr++ = *src_ptr++;
  178630. }
  178631. }
  178632. }
  178633. }
  178634. }
  178635. }
  178636. LOCAL(void)
  178637. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178638. jvirt_barray_ptr *src_coef_arrays,
  178639. jvirt_barray_ptr *dst_coef_arrays)
  178640. /* Transverse transpose is equivalent to
  178641. * 1. 180 degree rotation;
  178642. * 2. Transposition;
  178643. * or
  178644. * 1. Horizontal mirroring;
  178645. * 2. Transposition;
  178646. * 3. Horizontal mirroring.
  178647. * These steps are merged into a single processing routine.
  178648. */
  178649. {
  178650. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  178651. int ci, i, j, offset_x, offset_y;
  178652. JBLOCKARRAY src_buffer, dst_buffer;
  178653. JCOEFPTR src_ptr, dst_ptr;
  178654. jpeg_component_info *compptr;
  178655. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  178656. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  178657. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178658. compptr = dstinfo->comp_info + ci;
  178659. comp_width = MCU_cols * compptr->h_samp_factor;
  178660. comp_height = MCU_rows * compptr->v_samp_factor;
  178661. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178662. dst_blk_y += compptr->v_samp_factor) {
  178663. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178664. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178665. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178666. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178667. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178668. dst_blk_x += compptr->h_samp_factor) {
  178669. src_buffer = (*srcinfo->mem->access_virt_barray)
  178670. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  178671. (JDIMENSION) compptr->h_samp_factor, FALSE);
  178672. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  178673. if (dst_blk_y < comp_height) {
  178674. src_ptr = src_buffer[offset_x]
  178675. [comp_height - dst_blk_y - offset_y - 1];
  178676. if (dst_blk_x < comp_width) {
  178677. /* Block is within the mirrorable area. */
  178678. dst_ptr = dst_buffer[offset_y]
  178679. [comp_width - dst_blk_x - offset_x - 1];
  178680. for (i = 0; i < DCTSIZE; i++) {
  178681. for (j = 0; j < DCTSIZE; j++) {
  178682. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178683. j++;
  178684. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  178685. }
  178686. i++;
  178687. for (j = 0; j < DCTSIZE; j++) {
  178688. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  178689. j++;
  178690. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178691. }
  178692. }
  178693. } else {
  178694. /* Right-edge blocks are mirrored in y only */
  178695. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  178696. for (i = 0; i < DCTSIZE; i++) {
  178697. for (j = 0; j < DCTSIZE; j++) {
  178698. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178699. j++;
  178700. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  178701. }
  178702. }
  178703. }
  178704. } else {
  178705. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  178706. if (dst_blk_x < comp_width) {
  178707. /* Bottom-edge blocks are mirrored in x only */
  178708. dst_ptr = dst_buffer[offset_y]
  178709. [comp_width - dst_blk_x - offset_x - 1];
  178710. for (i = 0; i < DCTSIZE; i++) {
  178711. for (j = 0; j < DCTSIZE; j++)
  178712. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178713. i++;
  178714. for (j = 0; j < DCTSIZE; j++)
  178715. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  178716. }
  178717. } else {
  178718. /* At lower right corner, just transpose, no mirroring */
  178719. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  178720. for (i = 0; i < DCTSIZE; i++)
  178721. for (j = 0; j < DCTSIZE; j++)
  178722. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178723. }
  178724. }
  178725. }
  178726. }
  178727. }
  178728. }
  178729. }
  178730. }
  178731. /* Request any required workspace.
  178732. *
  178733. * We allocate the workspace virtual arrays from the source decompression
  178734. * object, so that all the arrays (both the original data and the workspace)
  178735. * will be taken into account while making memory management decisions.
  178736. * Hence, this routine must be called after jpeg_read_header (which reads
  178737. * the image dimensions) and before jpeg_read_coefficients (which realizes
  178738. * the source's virtual arrays).
  178739. */
  178740. GLOBAL(void)
  178741. jtransform_request_workspace (j_decompress_ptr srcinfo,
  178742. jpeg_transform_info *info)
  178743. {
  178744. jvirt_barray_ptr *coef_arrays = NULL;
  178745. jpeg_component_info *compptr;
  178746. int ci;
  178747. if (info->force_grayscale &&
  178748. srcinfo->jpeg_color_space == JCS_YCbCr &&
  178749. srcinfo->num_components == 3) {
  178750. /* We'll only process the first component */
  178751. info->num_components = 1;
  178752. } else {
  178753. /* Process all the components */
  178754. info->num_components = srcinfo->num_components;
  178755. }
  178756. switch (info->transform) {
  178757. case JXFORM_NONE:
  178758. case JXFORM_FLIP_H:
  178759. /* Don't need a workspace array */
  178760. break;
  178761. case JXFORM_FLIP_V:
  178762. case JXFORM_ROT_180:
  178763. /* Need workspace arrays having same dimensions as source image.
  178764. * Note that we allocate arrays padded out to the next iMCU boundary,
  178765. * so that transform routines need not worry about missing edge blocks.
  178766. */
  178767. coef_arrays = (jvirt_barray_ptr *)
  178768. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  178769. SIZEOF(jvirt_barray_ptr) * info->num_components);
  178770. for (ci = 0; ci < info->num_components; ci++) {
  178771. compptr = srcinfo->comp_info + ci;
  178772. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  178773. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  178774. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  178775. (long) compptr->h_samp_factor),
  178776. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  178777. (long) compptr->v_samp_factor),
  178778. (JDIMENSION) compptr->v_samp_factor);
  178779. }
  178780. break;
  178781. case JXFORM_TRANSPOSE:
  178782. case JXFORM_TRANSVERSE:
  178783. case JXFORM_ROT_90:
  178784. case JXFORM_ROT_270:
  178785. /* Need workspace arrays having transposed dimensions.
  178786. * Note that we allocate arrays padded out to the next iMCU boundary,
  178787. * so that transform routines need not worry about missing edge blocks.
  178788. */
  178789. coef_arrays = (jvirt_barray_ptr *)
  178790. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  178791. SIZEOF(jvirt_barray_ptr) * info->num_components);
  178792. for (ci = 0; ci < info->num_components; ci++) {
  178793. compptr = srcinfo->comp_info + ci;
  178794. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  178795. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  178796. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  178797. (long) compptr->v_samp_factor),
  178798. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  178799. (long) compptr->h_samp_factor),
  178800. (JDIMENSION) compptr->h_samp_factor);
  178801. }
  178802. break;
  178803. }
  178804. info->workspace_coef_arrays = coef_arrays;
  178805. }
  178806. /* Transpose destination image parameters */
  178807. LOCAL(void)
  178808. transpose_critical_parameters (j_compress_ptr dstinfo)
  178809. {
  178810. int tblno, i, j, ci, itemp;
  178811. jpeg_component_info *compptr;
  178812. JQUANT_TBL *qtblptr;
  178813. JDIMENSION dtemp;
  178814. UINT16 qtemp;
  178815. /* Transpose basic image dimensions */
  178816. dtemp = dstinfo->image_width;
  178817. dstinfo->image_width = dstinfo->image_height;
  178818. dstinfo->image_height = dtemp;
  178819. /* Transpose sampling factors */
  178820. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178821. compptr = dstinfo->comp_info + ci;
  178822. itemp = compptr->h_samp_factor;
  178823. compptr->h_samp_factor = compptr->v_samp_factor;
  178824. compptr->v_samp_factor = itemp;
  178825. }
  178826. /* Transpose quantization tables */
  178827. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  178828. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  178829. if (qtblptr != NULL) {
  178830. for (i = 0; i < DCTSIZE; i++) {
  178831. for (j = 0; j < i; j++) {
  178832. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  178833. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  178834. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  178835. }
  178836. }
  178837. }
  178838. }
  178839. }
  178840. /* Trim off any partial iMCUs on the indicated destination edge */
  178841. LOCAL(void)
  178842. trim_right_edge (j_compress_ptr dstinfo)
  178843. {
  178844. int ci, max_h_samp_factor;
  178845. JDIMENSION MCU_cols;
  178846. /* We have to compute max_h_samp_factor ourselves,
  178847. * because it hasn't been set yet in the destination
  178848. * (and we don't want to use the source's value).
  178849. */
  178850. max_h_samp_factor = 1;
  178851. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178852. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  178853. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  178854. }
  178855. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  178856. if (MCU_cols > 0) /* can't trim to 0 pixels */
  178857. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  178858. }
  178859. LOCAL(void)
  178860. trim_bottom_edge (j_compress_ptr dstinfo)
  178861. {
  178862. int ci, max_v_samp_factor;
  178863. JDIMENSION MCU_rows;
  178864. /* We have to compute max_v_samp_factor ourselves,
  178865. * because it hasn't been set yet in the destination
  178866. * (and we don't want to use the source's value).
  178867. */
  178868. max_v_samp_factor = 1;
  178869. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178870. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  178871. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  178872. }
  178873. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  178874. if (MCU_rows > 0) /* can't trim to 0 pixels */
  178875. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  178876. }
  178877. /* Adjust output image parameters as needed.
  178878. *
  178879. * This must be called after jpeg_copy_critical_parameters()
  178880. * and before jpeg_write_coefficients().
  178881. *
  178882. * The return value is the set of virtual coefficient arrays to be written
  178883. * (either the ones allocated by jtransform_request_workspace, or the
  178884. * original source data arrays). The caller will need to pass this value
  178885. * to jpeg_write_coefficients().
  178886. */
  178887. GLOBAL(jvirt_barray_ptr *)
  178888. jtransform_adjust_parameters (j_decompress_ptr,
  178889. j_compress_ptr dstinfo,
  178890. jvirt_barray_ptr *src_coef_arrays,
  178891. jpeg_transform_info *info)
  178892. {
  178893. /* If force-to-grayscale is requested, adjust destination parameters */
  178894. if (info->force_grayscale) {
  178895. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  178896. * properly. Among other things, the target h_samp_factor & v_samp_factor
  178897. * will get set to 1, which typically won't match the source.
  178898. * In fact we do this even if the source is already grayscale; that
  178899. * provides an easy way of coercing a grayscale JPEG with funny sampling
  178900. * factors to the customary 1,1. (Some decoders fail on other factors.)
  178901. */
  178902. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  178903. dstinfo->num_components == 3) ||
  178904. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  178905. dstinfo->num_components == 1)) {
  178906. /* We have to preserve the source's quantization table number. */
  178907. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  178908. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  178909. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  178910. } else {
  178911. /* Sorry, can't do it */
  178912. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  178913. }
  178914. }
  178915. /* Correct the destination's image dimensions etc if necessary */
  178916. switch (info->transform) {
  178917. case JXFORM_NONE:
  178918. /* Nothing to do */
  178919. break;
  178920. case JXFORM_FLIP_H:
  178921. if (info->trim)
  178922. trim_right_edge(dstinfo);
  178923. break;
  178924. case JXFORM_FLIP_V:
  178925. if (info->trim)
  178926. trim_bottom_edge(dstinfo);
  178927. break;
  178928. case JXFORM_TRANSPOSE:
  178929. transpose_critical_parameters(dstinfo);
  178930. /* transpose does NOT have to trim anything */
  178931. break;
  178932. case JXFORM_TRANSVERSE:
  178933. transpose_critical_parameters(dstinfo);
  178934. if (info->trim) {
  178935. trim_right_edge(dstinfo);
  178936. trim_bottom_edge(dstinfo);
  178937. }
  178938. break;
  178939. case JXFORM_ROT_90:
  178940. transpose_critical_parameters(dstinfo);
  178941. if (info->trim)
  178942. trim_right_edge(dstinfo);
  178943. break;
  178944. case JXFORM_ROT_180:
  178945. if (info->trim) {
  178946. trim_right_edge(dstinfo);
  178947. trim_bottom_edge(dstinfo);
  178948. }
  178949. break;
  178950. case JXFORM_ROT_270:
  178951. transpose_critical_parameters(dstinfo);
  178952. if (info->trim)
  178953. trim_bottom_edge(dstinfo);
  178954. break;
  178955. }
  178956. /* Return the appropriate output data set */
  178957. if (info->workspace_coef_arrays != NULL)
  178958. return info->workspace_coef_arrays;
  178959. return src_coef_arrays;
  178960. }
  178961. /* Execute the actual transformation, if any.
  178962. *
  178963. * This must be called *after* jpeg_write_coefficients, because it depends
  178964. * on jpeg_write_coefficients to have computed subsidiary values such as
  178965. * the per-component width and height fields in the destination object.
  178966. *
  178967. * Note that some transformations will modify the source data arrays!
  178968. */
  178969. GLOBAL(void)
  178970. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  178971. j_compress_ptr dstinfo,
  178972. jvirt_barray_ptr *src_coef_arrays,
  178973. jpeg_transform_info *info)
  178974. {
  178975. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  178976. switch (info->transform) {
  178977. case JXFORM_NONE:
  178978. break;
  178979. case JXFORM_FLIP_H:
  178980. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  178981. break;
  178982. case JXFORM_FLIP_V:
  178983. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  178984. break;
  178985. case JXFORM_TRANSPOSE:
  178986. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  178987. break;
  178988. case JXFORM_TRANSVERSE:
  178989. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  178990. break;
  178991. case JXFORM_ROT_90:
  178992. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  178993. break;
  178994. case JXFORM_ROT_180:
  178995. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  178996. break;
  178997. case JXFORM_ROT_270:
  178998. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  178999. break;
  179000. }
  179001. }
  179002. #endif /* TRANSFORMS_SUPPORTED */
  179003. /* Setup decompression object to save desired markers in memory.
  179004. * This must be called before jpeg_read_header() to have the desired effect.
  179005. */
  179006. GLOBAL(void)
  179007. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  179008. {
  179009. #ifdef SAVE_MARKERS_SUPPORTED
  179010. int m;
  179011. /* Save comments except under NONE option */
  179012. if (option != JCOPYOPT_NONE) {
  179013. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  179014. }
  179015. /* Save all types of APPn markers iff ALL option */
  179016. if (option == JCOPYOPT_ALL) {
  179017. for (m = 0; m < 16; m++)
  179018. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  179019. }
  179020. #endif /* SAVE_MARKERS_SUPPORTED */
  179021. }
  179022. /* Copy markers saved in the given source object to the destination object.
  179023. * This should be called just after jpeg_start_compress() or
  179024. * jpeg_write_coefficients().
  179025. * Note that those routines will have written the SOI, and also the
  179026. * JFIF APP0 or Adobe APP14 markers if selected.
  179027. */
  179028. GLOBAL(void)
  179029. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179030. JCOPY_OPTION)
  179031. {
  179032. jpeg_saved_marker_ptr marker;
  179033. /* In the current implementation, we don't actually need to examine the
  179034. * option flag here; we just copy everything that got saved.
  179035. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  179036. * if the encoder library already wrote one.
  179037. */
  179038. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  179039. if (dstinfo->write_JFIF_header &&
  179040. marker->marker == JPEG_APP0 &&
  179041. marker->data_length >= 5 &&
  179042. GETJOCTET(marker->data[0]) == 0x4A &&
  179043. GETJOCTET(marker->data[1]) == 0x46 &&
  179044. GETJOCTET(marker->data[2]) == 0x49 &&
  179045. GETJOCTET(marker->data[3]) == 0x46 &&
  179046. GETJOCTET(marker->data[4]) == 0)
  179047. continue; /* reject duplicate JFIF */
  179048. if (dstinfo->write_Adobe_marker &&
  179049. marker->marker == JPEG_APP0+14 &&
  179050. marker->data_length >= 5 &&
  179051. GETJOCTET(marker->data[0]) == 0x41 &&
  179052. GETJOCTET(marker->data[1]) == 0x64 &&
  179053. GETJOCTET(marker->data[2]) == 0x6F &&
  179054. GETJOCTET(marker->data[3]) == 0x62 &&
  179055. GETJOCTET(marker->data[4]) == 0x65)
  179056. continue; /* reject duplicate Adobe */
  179057. #ifdef NEED_FAR_POINTERS
  179058. /* We could use jpeg_write_marker if the data weren't FAR... */
  179059. {
  179060. unsigned int i;
  179061. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  179062. for (i = 0; i < marker->data_length; i++)
  179063. jpeg_write_m_byte(dstinfo, marker->data[i]);
  179064. }
  179065. #else
  179066. jpeg_write_marker(dstinfo, marker->marker,
  179067. marker->data, marker->data_length);
  179068. #endif
  179069. }
  179070. }
  179071. /*** End of inlined file: transupp.c ***/
  179072. }
  179073. #else
  179074. #define JPEG_INTERNALS
  179075. #undef FAR
  179076. #include <jpeglib.h>
  179077. #endif
  179078. }
  179079. #undef max
  179080. #undef min
  179081. #if JUCE_MSVC
  179082. #pragma warning (pop)
  179083. #endif
  179084. BEGIN_JUCE_NAMESPACE
  179085. namespace JPEGHelpers
  179086. {
  179087. using namespace jpeglibNamespace;
  179088. #if ! JUCE_MSVC
  179089. using jpeglibNamespace::boolean;
  179090. #endif
  179091. struct JPEGDecodingFailure {};
  179092. static void fatalErrorHandler (j_common_ptr)
  179093. {
  179094. throw JPEGDecodingFailure();
  179095. }
  179096. static void silentErrorCallback1 (j_common_ptr) {}
  179097. static void silentErrorCallback2 (j_common_ptr, int) {}
  179098. static void silentErrorCallback3 (j_common_ptr, char*) {}
  179099. static void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  179100. {
  179101. zerostruct (err);
  179102. err.error_exit = fatalErrorHandler;
  179103. err.emit_message = silentErrorCallback2;
  179104. err.output_message = silentErrorCallback1;
  179105. err.format_message = silentErrorCallback3;
  179106. err.reset_error_mgr = silentErrorCallback1;
  179107. }
  179108. static void dummyCallback1 (j_decompress_ptr)
  179109. {
  179110. }
  179111. static void jpegSkip (j_decompress_ptr decompStruct, long num)
  179112. {
  179113. decompStruct->src->next_input_byte += num;
  179114. num = jmin (num, (long) decompStruct->src->bytes_in_buffer);
  179115. decompStruct->src->bytes_in_buffer -= num;
  179116. }
  179117. static boolean jpegFill (j_decompress_ptr)
  179118. {
  179119. return 0;
  179120. }
  179121. static const int jpegBufferSize = 512;
  179122. struct JuceJpegDest : public jpeg_destination_mgr
  179123. {
  179124. OutputStream* output;
  179125. char* buffer;
  179126. };
  179127. static void jpegWriteInit (j_compress_ptr)
  179128. {
  179129. }
  179130. static void jpegWriteTerminate (j_compress_ptr cinfo)
  179131. {
  179132. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  179133. const size_t numToWrite = jpegBufferSize - dest->free_in_buffer;
  179134. dest->output->write (dest->buffer, (int) numToWrite);
  179135. }
  179136. static boolean jpegWriteFlush (j_compress_ptr cinfo)
  179137. {
  179138. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  179139. const int numToWrite = jpegBufferSize;
  179140. dest->next_output_byte = reinterpret_cast <JOCTET*> (dest->buffer);
  179141. dest->free_in_buffer = jpegBufferSize;
  179142. return dest->output->write (dest->buffer, numToWrite);
  179143. }
  179144. }
  179145. JPEGImageFormat::JPEGImageFormat()
  179146. : quality (-1.0f)
  179147. {
  179148. }
  179149. JPEGImageFormat::~JPEGImageFormat() {}
  179150. void JPEGImageFormat::setQuality (const float newQuality)
  179151. {
  179152. quality = newQuality;
  179153. }
  179154. const String JPEGImageFormat::getFormatName()
  179155. {
  179156. return "JPEG";
  179157. }
  179158. bool JPEGImageFormat::canUnderstand (InputStream& in)
  179159. {
  179160. const int bytesNeeded = 10;
  179161. uint8 header [bytesNeeded];
  179162. if (in.read (header, bytesNeeded) == bytesNeeded)
  179163. {
  179164. return header[0] == 0xff
  179165. && header[1] == 0xd8
  179166. && header[2] == 0xff
  179167. && (header[3] == 0xe0 || header[3] == 0xe1);
  179168. }
  179169. return false;
  179170. }
  179171. const Image JPEGImageFormat::decodeImage (InputStream& in)
  179172. {
  179173. using namespace jpeglibNamespace;
  179174. using namespace JPEGHelpers;
  179175. MemoryBlock mb;
  179176. in.readIntoMemoryBlock (mb);
  179177. Image image;
  179178. if (mb.getSize() > 16)
  179179. {
  179180. struct jpeg_decompress_struct jpegDecompStruct;
  179181. struct jpeg_error_mgr jerr;
  179182. setupSilentErrorHandler (jerr);
  179183. jpegDecompStruct.err = &jerr;
  179184. jpeg_create_decompress (&jpegDecompStruct);
  179185. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  179186. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  179187. jpegDecompStruct.src->init_source = dummyCallback1;
  179188. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  179189. jpegDecompStruct.src->skip_input_data = jpegSkip;
  179190. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  179191. jpegDecompStruct.src->term_source = dummyCallback1;
  179192. jpegDecompStruct.src->next_input_byte = static_cast <const unsigned char*> (mb.getData());
  179193. jpegDecompStruct.src->bytes_in_buffer = mb.getSize();
  179194. try
  179195. {
  179196. jpeg_read_header (&jpegDecompStruct, TRUE);
  179197. jpeg_calc_output_dimensions (&jpegDecompStruct);
  179198. const int width = jpegDecompStruct.output_width;
  179199. const int height = jpegDecompStruct.output_height;
  179200. jpegDecompStruct.out_color_space = JCS_RGB;
  179201. JSAMPARRAY buffer
  179202. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  179203. JPOOL_IMAGE,
  179204. width * 3, 1);
  179205. if (jpeg_start_decompress (&jpegDecompStruct))
  179206. {
  179207. image = Image (Image::RGB, width, height, false);
  179208. const bool hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  179209. const Image::BitmapData destData (image, 0, 0, width, height, true);
  179210. for (int y = 0; y < height; ++y)
  179211. {
  179212. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  179213. const uint8* src = *buffer;
  179214. uint8* dest = destData.getLinePointer (y);
  179215. if (hasAlphaChan)
  179216. {
  179217. for (int i = width; --i >= 0;)
  179218. {
  179219. ((PixelARGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  179220. ((PixelARGB*) dest)->premultiply();
  179221. dest += destData.pixelStride;
  179222. src += 3;
  179223. }
  179224. }
  179225. else
  179226. {
  179227. for (int i = width; --i >= 0;)
  179228. {
  179229. ((PixelRGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  179230. dest += destData.pixelStride;
  179231. src += 3;
  179232. }
  179233. }
  179234. }
  179235. jpeg_finish_decompress (&jpegDecompStruct);
  179236. in.setPosition (((char*) jpegDecompStruct.src->next_input_byte) - (char*) mb.getData());
  179237. }
  179238. jpeg_destroy_decompress (&jpegDecompStruct);
  179239. }
  179240. catch (...)
  179241. {}
  179242. }
  179243. return image;
  179244. }
  179245. bool JPEGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  179246. {
  179247. using namespace jpeglibNamespace;
  179248. using namespace JPEGHelpers;
  179249. if (image.hasAlphaChannel())
  179250. {
  179251. // this method could fill the background in white and still save the image..
  179252. jassertfalse;
  179253. return true;
  179254. }
  179255. struct jpeg_compress_struct jpegCompStruct;
  179256. struct jpeg_error_mgr jerr;
  179257. setupSilentErrorHandler (jerr);
  179258. jpegCompStruct.err = &jerr;
  179259. jpeg_create_compress (&jpegCompStruct);
  179260. JuceJpegDest dest;
  179261. jpegCompStruct.dest = &dest;
  179262. dest.output = &out;
  179263. HeapBlock <char> tempBuffer (jpegBufferSize);
  179264. dest.buffer = tempBuffer;
  179265. dest.next_output_byte = (JOCTET*) dest.buffer;
  179266. dest.free_in_buffer = jpegBufferSize;
  179267. dest.init_destination = jpegWriteInit;
  179268. dest.empty_output_buffer = jpegWriteFlush;
  179269. dest.term_destination = jpegWriteTerminate;
  179270. jpegCompStruct.image_width = image.getWidth();
  179271. jpegCompStruct.image_height = image.getHeight();
  179272. jpegCompStruct.input_components = 3;
  179273. jpegCompStruct.in_color_space = JCS_RGB;
  179274. jpegCompStruct.write_JFIF_header = 1;
  179275. jpegCompStruct.X_density = 72;
  179276. jpegCompStruct.Y_density = 72;
  179277. jpeg_set_defaults (&jpegCompStruct);
  179278. jpegCompStruct.dct_method = JDCT_FLOAT;
  179279. jpegCompStruct.optimize_coding = 1;
  179280. //jpegCompStruct.smoothing_factor = 10;
  179281. if (quality < 0.0f)
  179282. quality = 0.85f;
  179283. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundToInt (quality * 100.0f)), TRUE);
  179284. jpeg_start_compress (&jpegCompStruct, TRUE);
  179285. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  179286. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  179287. JPOOL_IMAGE, strideBytes, 1);
  179288. const Image::BitmapData srcData (image, 0, 0, jpegCompStruct.image_width, jpegCompStruct.image_height);
  179289. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  179290. {
  179291. const uint8* src = srcData.getLinePointer (jpegCompStruct.next_scanline);
  179292. uint8* dst = *buffer;
  179293. for (int i = jpegCompStruct.image_width; --i >= 0;)
  179294. {
  179295. *dst++ = ((const PixelRGB*) src)->getRed();
  179296. *dst++ = ((const PixelRGB*) src)->getGreen();
  179297. *dst++ = ((const PixelRGB*) src)->getBlue();
  179298. src += srcData.pixelStride;
  179299. }
  179300. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  179301. }
  179302. jpeg_finish_compress (&jpegCompStruct);
  179303. jpeg_destroy_compress (&jpegCompStruct);
  179304. out.flush();
  179305. return true;
  179306. }
  179307. END_JUCE_NAMESPACE
  179308. /*** End of inlined file: juce_JPEGLoader.cpp ***/
  179309. /*** Start of inlined file: juce_PNGLoader.cpp ***/
  179310. #if JUCE_MSVC
  179311. #pragma warning (push)
  179312. #pragma warning (disable: 4390 4611)
  179313. #endif
  179314. namespace zlibNamespace
  179315. {
  179316. #if JUCE_INCLUDE_ZLIB_CODE
  179317. #undef OS_CODE
  179318. #undef fdopen
  179319. #undef OS_CODE
  179320. #else
  179321. #include <zlib.h>
  179322. #endif
  179323. }
  179324. namespace pnglibNamespace
  179325. {
  179326. using namespace zlibNamespace;
  179327. #if JUCE_INCLUDE_PNGLIB_CODE
  179328. #if _MSC_VER != 1310
  179329. using ::calloc; // (causes conflict in VS.NET 2003)
  179330. using ::malloc;
  179331. using ::free;
  179332. #endif
  179333. extern "C"
  179334. {
  179335. using ::abs;
  179336. #define PNG_INTERNAL
  179337. #define NO_DUMMY_DECL
  179338. #define PNG_SETJMP_NOT_SUPPORTED
  179339. /*** Start of inlined file: png.h ***/
  179340. /* png.h - header file for PNG reference library
  179341. *
  179342. * libpng version 1.2.21 - October 4, 2007
  179343. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  179344. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  179345. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  179346. *
  179347. * Authors and maintainers:
  179348. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  179349. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  179350. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  179351. * See also "Contributing Authors", below.
  179352. *
  179353. * Note about libpng version numbers:
  179354. *
  179355. * Due to various miscommunications, unforeseen code incompatibilities
  179356. * and occasional factors outside the authors' control, version numbering
  179357. * on the library has not always been consistent and straightforward.
  179358. * The following table summarizes matters since version 0.89c, which was
  179359. * the first widely used release:
  179360. *
  179361. * source png.h png.h shared-lib
  179362. * version string int version
  179363. * ------- ------ ----- ----------
  179364. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  179365. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  179366. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  179367. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  179368. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  179369. * 0.97c 0.97 97 2.0.97
  179370. * 0.98 0.98 98 2.0.98
  179371. * 0.99 0.99 98 2.0.99
  179372. * 0.99a-m 0.99 99 2.0.99
  179373. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  179374. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  179375. * 1.0.1 png.h string is 10001 2.1.0
  179376. * 1.0.1a-e identical to the 10002 from here on, the shared library
  179377. * 1.0.2 source version) 10002 is 2.V where V is the source code
  179378. * 1.0.2a-b 10003 version, except as noted.
  179379. * 1.0.3 10003
  179380. * 1.0.3a-d 10004
  179381. * 1.0.4 10004
  179382. * 1.0.4a-f 10005
  179383. * 1.0.5 (+ 2 patches) 10005
  179384. * 1.0.5a-d 10006
  179385. * 1.0.5e-r 10100 (not source compatible)
  179386. * 1.0.5s-v 10006 (not binary compatible)
  179387. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  179388. * 1.0.6d-f 10007 (still binary incompatible)
  179389. * 1.0.6g 10007
  179390. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  179391. * 1.0.6i 10007 10.6i
  179392. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  179393. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  179394. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  179395. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  179396. * 1.0.7 1 10007 (still compatible)
  179397. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  179398. * 1.0.8rc1 1 10008 2.1.0.8rc1
  179399. * 1.0.8 1 10008 2.1.0.8
  179400. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  179401. * 1.0.9rc1 1 10009 2.1.0.9rc1
  179402. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  179403. * 1.0.9rc2 1 10009 2.1.0.9rc2
  179404. * 1.0.9 1 10009 2.1.0.9
  179405. * 1.0.10beta1 1 10010 2.1.0.10beta1
  179406. * 1.0.10rc1 1 10010 2.1.0.10rc1
  179407. * 1.0.10 1 10010 2.1.0.10
  179408. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  179409. * 1.0.11rc1 1 10011 2.1.0.11rc1
  179410. * 1.0.11 1 10011 2.1.0.11
  179411. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  179412. * 1.0.12rc1 2 10012 2.1.0.12rc1
  179413. * 1.0.12 2 10012 2.1.0.12
  179414. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  179415. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  179416. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  179417. * 1.2.0rc1 3 10200 3.1.2.0rc1
  179418. * 1.2.0 3 10200 3.1.2.0
  179419. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  179420. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  179421. * 1.2.1 3 10201 3.1.2.1
  179422. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  179423. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  179424. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  179425. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  179426. * 1.0.13 10 10013 10.so.0.1.0.13
  179427. * 1.2.2 12 10202 12.so.0.1.2.2
  179428. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  179429. * 1.2.3 12 10203 12.so.0.1.2.3
  179430. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  179431. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  179432. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  179433. * 1.0.14 10 10014 10.so.0.1.0.14
  179434. * 1.2.4 13 10204 12.so.0.1.2.4
  179435. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  179436. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  179437. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  179438. * 1.0.15 10 10015 10.so.0.1.0.15
  179439. * 1.2.5 13 10205 12.so.0.1.2.5
  179440. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  179441. * 1.0.16 10 10016 10.so.0.1.0.16
  179442. * 1.2.6 13 10206 12.so.0.1.2.6
  179443. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  179444. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  179445. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  179446. * 1.0.17 10 10017 10.so.0.1.0.17
  179447. * 1.2.7 13 10207 12.so.0.1.2.7
  179448. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  179449. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  179450. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  179451. * 1.0.18 10 10018 10.so.0.1.0.18
  179452. * 1.2.8 13 10208 12.so.0.1.2.8
  179453. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  179454. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  179455. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  179456. * 1.2.9 13 10209 12.so.0.9[.0]
  179457. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  179458. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  179459. * 1.2.10 13 10210 12.so.0.10[.0]
  179460. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  179461. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  179462. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  179463. * 1.0.19 10 10019 10.so.0.19[.0]
  179464. * 1.2.11 13 10211 12.so.0.11[.0]
  179465. * 1.0.20 10 10020 10.so.0.20[.0]
  179466. * 1.2.12 13 10212 12.so.0.12[.0]
  179467. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  179468. * 1.0.21 10 10021 10.so.0.21[.0]
  179469. * 1.2.13 13 10213 12.so.0.13[.0]
  179470. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  179471. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  179472. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  179473. * 1.0.22 10 10022 10.so.0.22[.0]
  179474. * 1.2.14 13 10214 12.so.0.14[.0]
  179475. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  179476. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  179477. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  179478. * 1.0.23 10 10023 10.so.0.23[.0]
  179479. * 1.2.15 13 10215 12.so.0.15[.0]
  179480. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  179481. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  179482. * 1.0.24 10 10024 10.so.0.24[.0]
  179483. * 1.2.16 13 10216 12.so.0.16[.0]
  179484. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  179485. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  179486. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  179487. * 1.0.25 10 10025 10.so.0.25[.0]
  179488. * 1.2.17 13 10217 12.so.0.17[.0]
  179489. * 1.0.26 10 10026 10.so.0.26[.0]
  179490. * 1.2.18 13 10218 12.so.0.18[.0]
  179491. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  179492. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  179493. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  179494. * 1.0.27 10 10027 10.so.0.27[.0]
  179495. * 1.2.19 13 10219 12.so.0.19[.0]
  179496. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  179497. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  179498. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  179499. * 1.0.28 10 10028 10.so.0.28[.0]
  179500. * 1.2.20 13 10220 12.so.0.20[.0]
  179501. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  179502. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  179503. * 1.0.29 10 10029 10.so.0.29[.0]
  179504. * 1.2.21 13 10221 12.so.0.21[.0]
  179505. *
  179506. * Henceforth the source version will match the shared-library major
  179507. * and minor numbers; the shared-library major version number will be
  179508. * used for changes in backward compatibility, as it is intended. The
  179509. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  179510. * for applications, is an unsigned integer of the form xyyzz corresponding
  179511. * to the source version x.y.z (leading zeros in y and z). Beta versions
  179512. * were given the previous public release number plus a letter, until
  179513. * version 1.0.6j; from then on they were given the upcoming public
  179514. * release number plus "betaNN" or "rcN".
  179515. *
  179516. * Binary incompatibility exists only when applications make direct access
  179517. * to the info_ptr or png_ptr members through png.h, and the compiled
  179518. * application is loaded with a different version of the library.
  179519. *
  179520. * DLLNUM will change each time there are forward or backward changes
  179521. * in binary compatibility (e.g., when a new feature is added).
  179522. *
  179523. * See libpng.txt or libpng.3 for more information. The PNG specification
  179524. * is available as a W3C Recommendation and as an ISO Specification,
  179525. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  179526. */
  179527. /*
  179528. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  179529. *
  179530. * If you modify libpng you may insert additional notices immediately following
  179531. * this sentence.
  179532. *
  179533. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  179534. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  179535. * distributed according to the same disclaimer and license as libpng-1.2.5
  179536. * with the following individual added to the list of Contributing Authors:
  179537. *
  179538. * Cosmin Truta
  179539. *
  179540. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  179541. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  179542. * distributed according to the same disclaimer and license as libpng-1.0.6
  179543. * with the following individuals added to the list of Contributing Authors:
  179544. *
  179545. * Simon-Pierre Cadieux
  179546. * Eric S. Raymond
  179547. * Gilles Vollant
  179548. *
  179549. * and with the following additions to the disclaimer:
  179550. *
  179551. * There is no warranty against interference with your enjoyment of the
  179552. * library or against infringement. There is no warranty that our
  179553. * efforts or the library will fulfill any of your particular purposes
  179554. * or needs. This library is provided with all faults, and the entire
  179555. * risk of satisfactory quality, performance, accuracy, and effort is with
  179556. * the user.
  179557. *
  179558. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  179559. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  179560. * distributed according to the same disclaimer and license as libpng-0.96,
  179561. * with the following individuals added to the list of Contributing Authors:
  179562. *
  179563. * Tom Lane
  179564. * Glenn Randers-Pehrson
  179565. * Willem van Schaik
  179566. *
  179567. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  179568. * Copyright (c) 1996, 1997 Andreas Dilger
  179569. * Distributed according to the same disclaimer and license as libpng-0.88,
  179570. * with the following individuals added to the list of Contributing Authors:
  179571. *
  179572. * John Bowler
  179573. * Kevin Bracey
  179574. * Sam Bushell
  179575. * Magnus Holmgren
  179576. * Greg Roelofs
  179577. * Tom Tanner
  179578. *
  179579. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  179580. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  179581. *
  179582. * For the purposes of this copyright and license, "Contributing Authors"
  179583. * is defined as the following set of individuals:
  179584. *
  179585. * Andreas Dilger
  179586. * Dave Martindale
  179587. * Guy Eric Schalnat
  179588. * Paul Schmidt
  179589. * Tim Wegner
  179590. *
  179591. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  179592. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  179593. * including, without limitation, the warranties of merchantability and of
  179594. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  179595. * assume no liability for direct, indirect, incidental, special, exemplary,
  179596. * or consequential damages, which may result from the use of the PNG
  179597. * Reference Library, even if advised of the possibility of such damage.
  179598. *
  179599. * Permission is hereby granted to use, copy, modify, and distribute this
  179600. * source code, or portions hereof, for any purpose, without fee, subject
  179601. * to the following restrictions:
  179602. *
  179603. * 1. The origin of this source code must not be misrepresented.
  179604. *
  179605. * 2. Altered versions must be plainly marked as such and
  179606. * must not be misrepresented as being the original source.
  179607. *
  179608. * 3. This Copyright notice may not be removed or altered from
  179609. * any source or altered source distribution.
  179610. *
  179611. * The Contributing Authors and Group 42, Inc. specifically permit, without
  179612. * fee, and encourage the use of this source code as a component to
  179613. * supporting the PNG file format in commercial products. If you use this
  179614. * source code in a product, acknowledgment is not required but would be
  179615. * appreciated.
  179616. */
  179617. /*
  179618. * A "png_get_copyright" function is available, for convenient use in "about"
  179619. * boxes and the like:
  179620. *
  179621. * printf("%s",png_get_copyright(NULL));
  179622. *
  179623. * Also, the PNG logo (in PNG format, of course) is supplied in the
  179624. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  179625. */
  179626. /*
  179627. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  179628. * certification mark of the Open Source Initiative.
  179629. */
  179630. /*
  179631. * The contributing authors would like to thank all those who helped
  179632. * with testing, bug fixes, and patience. This wouldn't have been
  179633. * possible without all of you.
  179634. *
  179635. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  179636. */
  179637. /*
  179638. * Y2K compliance in libpng:
  179639. * =========================
  179640. *
  179641. * October 4, 2007
  179642. *
  179643. * Since the PNG Development group is an ad-hoc body, we can't make
  179644. * an official declaration.
  179645. *
  179646. * This is your unofficial assurance that libpng from version 0.71 and
  179647. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  179648. * versions were also Y2K compliant.
  179649. *
  179650. * Libpng only has three year fields. One is a 2-byte unsigned integer
  179651. * that will hold years up to 65535. The other two hold the date in text
  179652. * format, and will hold years up to 9999.
  179653. *
  179654. * The integer is
  179655. * "png_uint_16 year" in png_time_struct.
  179656. *
  179657. * The strings are
  179658. * "png_charp time_buffer" in png_struct and
  179659. * "near_time_buffer", which is a local character string in png.c.
  179660. *
  179661. * There are seven time-related functions:
  179662. * png.c: png_convert_to_rfc_1123() in png.c
  179663. * (formerly png_convert_to_rfc_1152() in error)
  179664. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  179665. * png_convert_from_time_t() in pngwrite.c
  179666. * png_get_tIME() in pngget.c
  179667. * png_handle_tIME() in pngrutil.c, called in pngread.c
  179668. * png_set_tIME() in pngset.c
  179669. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  179670. *
  179671. * All handle dates properly in a Y2K environment. The
  179672. * png_convert_from_time_t() function calls gmtime() to convert from system
  179673. * clock time, which returns (year - 1900), which we properly convert to
  179674. * the full 4-digit year. There is a possibility that applications using
  179675. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  179676. * function, or that they are incorrectly passing only a 2-digit year
  179677. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  179678. * but this is not under our control. The libpng documentation has always
  179679. * stated that it works with 4-digit years, and the APIs have been
  179680. * documented as such.
  179681. *
  179682. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  179683. * integer to hold the year, and can hold years as large as 65535.
  179684. *
  179685. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  179686. * no date-related code.
  179687. *
  179688. * Glenn Randers-Pehrson
  179689. * libpng maintainer
  179690. * PNG Development Group
  179691. */
  179692. #ifndef PNG_H
  179693. #define PNG_H
  179694. /* This is not the place to learn how to use libpng. The file libpng.txt
  179695. * describes how to use libpng, and the file example.c summarizes it
  179696. * with some code on which to build. This file is useful for looking
  179697. * at the actual function definitions and structure components.
  179698. */
  179699. /* Version information for png.h - this should match the version in png.c */
  179700. #define PNG_LIBPNG_VER_STRING "1.2.21"
  179701. #define PNG_HEADER_VERSION_STRING \
  179702. " libpng version 1.2.21 - October 4, 2007\n"
  179703. #define PNG_LIBPNG_VER_SONUM 0
  179704. #define PNG_LIBPNG_VER_DLLNUM 13
  179705. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  179706. #define PNG_LIBPNG_VER_MAJOR 1
  179707. #define PNG_LIBPNG_VER_MINOR 2
  179708. #define PNG_LIBPNG_VER_RELEASE 21
  179709. /* This should match the numeric part of the final component of
  179710. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  179711. #define PNG_LIBPNG_VER_BUILD 0
  179712. /* Release Status */
  179713. #define PNG_LIBPNG_BUILD_ALPHA 1
  179714. #define PNG_LIBPNG_BUILD_BETA 2
  179715. #define PNG_LIBPNG_BUILD_RC 3
  179716. #define PNG_LIBPNG_BUILD_STABLE 4
  179717. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  179718. /* Release-Specific Flags */
  179719. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  179720. PNG_LIBPNG_BUILD_STABLE only */
  179721. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  179722. PNG_LIBPNG_BUILD_SPECIAL */
  179723. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  179724. PNG_LIBPNG_BUILD_PRIVATE */
  179725. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  179726. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  179727. * We must not include leading zeros.
  179728. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  179729. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  179730. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  179731. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  179732. #ifndef PNG_VERSION_INFO_ONLY
  179733. /* include the compression library's header */
  179734. #endif
  179735. /* include all user configurable info, including optional assembler routines */
  179736. /*** Start of inlined file: pngconf.h ***/
  179737. /* pngconf.h - machine configurable file for libpng
  179738. *
  179739. * libpng version 1.2.21 - October 4, 2007
  179740. * For conditions of distribution and use, see copyright notice in png.h
  179741. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  179742. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  179743. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  179744. */
  179745. /* Any machine specific code is near the front of this file, so if you
  179746. * are configuring libpng for a machine, you may want to read the section
  179747. * starting here down to where it starts to typedef png_color, png_text,
  179748. * and png_info.
  179749. */
  179750. #ifndef PNGCONF_H
  179751. #define PNGCONF_H
  179752. #define PNG_1_2_X
  179753. // These are some Juce config settings that should remove any unnecessary code bloat..
  179754. #define PNG_NO_STDIO 1
  179755. #define PNG_DEBUG 0
  179756. #define PNG_NO_WARNINGS 1
  179757. #define PNG_NO_ERROR_TEXT 1
  179758. #define PNG_NO_ERROR_NUMBERS 1
  179759. #define PNG_NO_USER_MEM 1
  179760. #define PNG_NO_READ_iCCP 1
  179761. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  179762. #define PNG_NO_READ_USER_CHUNKS 1
  179763. #define PNG_NO_READ_iTXt 1
  179764. #define PNG_NO_READ_sCAL 1
  179765. #define PNG_NO_READ_sPLT 1
  179766. #define png_error(a, b) png_err(a)
  179767. #define png_warning(a, b)
  179768. #define png_chunk_error(a, b) png_err(a)
  179769. #define png_chunk_warning(a, b)
  179770. /*
  179771. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  179772. * includes the resource compiler for Windows DLL configurations.
  179773. */
  179774. #ifdef PNG_USER_CONFIG
  179775. # ifndef PNG_USER_PRIVATEBUILD
  179776. # define PNG_USER_PRIVATEBUILD
  179777. # endif
  179778. #include "pngusr.h"
  179779. #endif
  179780. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  179781. #ifdef PNG_CONFIGURE_LIBPNG
  179782. #ifdef HAVE_CONFIG_H
  179783. #include "config.h"
  179784. #endif
  179785. #endif
  179786. /*
  179787. * Added at libpng-1.2.8
  179788. *
  179789. * If you create a private DLL you need to define in "pngusr.h" the followings:
  179790. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  179791. * the DLL was built>
  179792. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  179793. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  179794. * distinguish your DLL from those of the official release. These
  179795. * correspond to the trailing letters that come after the version
  179796. * number and must match your private DLL name>
  179797. * e.g. // private DLL "libpng13gx.dll"
  179798. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  179799. *
  179800. * The following macros are also at your disposal if you want to complete the
  179801. * DLL VERSIONINFO structure.
  179802. * - PNG_USER_VERSIONINFO_COMMENTS
  179803. * - PNG_USER_VERSIONINFO_COMPANYNAME
  179804. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  179805. */
  179806. #ifdef __STDC__
  179807. #ifdef SPECIALBUILD
  179808. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  179809. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  179810. #endif
  179811. #ifdef PRIVATEBUILD
  179812. # pragma message("PRIVATEBUILD is deprecated.\
  179813. Use PNG_USER_PRIVATEBUILD instead.")
  179814. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  179815. #endif
  179816. #endif /* __STDC__ */
  179817. #ifndef PNG_VERSION_INFO_ONLY
  179818. /* End of material added to libpng-1.2.8 */
  179819. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  179820. Restored at libpng-1.2.21 */
  179821. # define PNG_WARN_UNINITIALIZED_ROW 1
  179822. /* End of material added at libpng-1.2.19/1.2.21 */
  179823. /* This is the size of the compression buffer, and thus the size of
  179824. * an IDAT chunk. Make this whatever size you feel is best for your
  179825. * machine. One of these will be allocated per png_struct. When this
  179826. * is full, it writes the data to the disk, and does some other
  179827. * calculations. Making this an extremely small size will slow
  179828. * the library down, but you may want to experiment to determine
  179829. * where it becomes significant, if you are concerned with memory
  179830. * usage. Note that zlib allocates at least 32Kb also. For readers,
  179831. * this describes the size of the buffer available to read the data in.
  179832. * Unless this gets smaller than the size of a row (compressed),
  179833. * it should not make much difference how big this is.
  179834. */
  179835. #ifndef PNG_ZBUF_SIZE
  179836. # define PNG_ZBUF_SIZE 8192
  179837. #endif
  179838. /* Enable if you want a write-only libpng */
  179839. #ifndef PNG_NO_READ_SUPPORTED
  179840. # define PNG_READ_SUPPORTED
  179841. #endif
  179842. /* Enable if you want a read-only libpng */
  179843. #ifndef PNG_NO_WRITE_SUPPORTED
  179844. # define PNG_WRITE_SUPPORTED
  179845. #endif
  179846. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  179847. support PNGs that are embedded in MNG datastreams */
  179848. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  179849. # ifndef PNG_MNG_FEATURES_SUPPORTED
  179850. # define PNG_MNG_FEATURES_SUPPORTED
  179851. # endif
  179852. #endif
  179853. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  179854. # ifndef PNG_FLOATING_POINT_SUPPORTED
  179855. # define PNG_FLOATING_POINT_SUPPORTED
  179856. # endif
  179857. #endif
  179858. /* If you are running on a machine where you cannot allocate more
  179859. * than 64K of memory at once, uncomment this. While libpng will not
  179860. * normally need that much memory in a chunk (unless you load up a very
  179861. * large file), zlib needs to know how big of a chunk it can use, and
  179862. * libpng thus makes sure to check any memory allocation to verify it
  179863. * will fit into memory.
  179864. #define PNG_MAX_MALLOC_64K
  179865. */
  179866. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  179867. # define PNG_MAX_MALLOC_64K
  179868. #endif
  179869. /* Special munging to support doing things the 'cygwin' way:
  179870. * 'Normal' png-on-win32 defines/defaults:
  179871. * PNG_BUILD_DLL -- building dll
  179872. * PNG_USE_DLL -- building an application, linking to dll
  179873. * (no define) -- building static library, or building an
  179874. * application and linking to the static lib
  179875. * 'Cygwin' defines/defaults:
  179876. * PNG_BUILD_DLL -- (ignored) building the dll
  179877. * (no define) -- (ignored) building an application, linking to the dll
  179878. * PNG_STATIC -- (ignored) building the static lib, or building an
  179879. * application that links to the static lib.
  179880. * ALL_STATIC -- (ignored) building various static libs, or building an
  179881. * application that links to the static libs.
  179882. * Thus,
  179883. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  179884. * this bit of #ifdefs will define the 'correct' config variables based on
  179885. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  179886. * unnecessary.
  179887. *
  179888. * Also, the precedence order is:
  179889. * ALL_STATIC (since we can't #undef something outside our namespace)
  179890. * PNG_BUILD_DLL
  179891. * PNG_STATIC
  179892. * (nothing) == PNG_USE_DLL
  179893. *
  179894. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  179895. * of auto-import in binutils, we no longer need to worry about
  179896. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  179897. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  179898. * to __declspec() stuff. However, we DO need to worry about
  179899. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  179900. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  179901. */
  179902. #if defined(__CYGWIN__)
  179903. # if defined(ALL_STATIC)
  179904. # if defined(PNG_BUILD_DLL)
  179905. # undef PNG_BUILD_DLL
  179906. # endif
  179907. # if defined(PNG_USE_DLL)
  179908. # undef PNG_USE_DLL
  179909. # endif
  179910. # if defined(PNG_DLL)
  179911. # undef PNG_DLL
  179912. # endif
  179913. # if !defined(PNG_STATIC)
  179914. # define PNG_STATIC
  179915. # endif
  179916. # else
  179917. # if defined (PNG_BUILD_DLL)
  179918. # if defined(PNG_STATIC)
  179919. # undef PNG_STATIC
  179920. # endif
  179921. # if defined(PNG_USE_DLL)
  179922. # undef PNG_USE_DLL
  179923. # endif
  179924. # if !defined(PNG_DLL)
  179925. # define PNG_DLL
  179926. # endif
  179927. # else
  179928. # if defined(PNG_STATIC)
  179929. # if defined(PNG_USE_DLL)
  179930. # undef PNG_USE_DLL
  179931. # endif
  179932. # if defined(PNG_DLL)
  179933. # undef PNG_DLL
  179934. # endif
  179935. # else
  179936. # if !defined(PNG_USE_DLL)
  179937. # define PNG_USE_DLL
  179938. # endif
  179939. # if !defined(PNG_DLL)
  179940. # define PNG_DLL
  179941. # endif
  179942. # endif
  179943. # endif
  179944. # endif
  179945. #endif
  179946. /* This protects us against compilers that run on a windowing system
  179947. * and thus don't have or would rather us not use the stdio types:
  179948. * stdin, stdout, and stderr. The only one currently used is stderr
  179949. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  179950. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  179951. * will also prevent these, plus will prevent the entire set of stdio
  179952. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  179953. * unless (PNG_DEBUG > 0) has been #defined.
  179954. *
  179955. * #define PNG_NO_CONSOLE_IO
  179956. * #define PNG_NO_STDIO
  179957. */
  179958. #if defined(_WIN32_WCE)
  179959. # include <windows.h>
  179960. /* Console I/O functions are not supported on WindowsCE */
  179961. # define PNG_NO_CONSOLE_IO
  179962. # ifdef PNG_DEBUG
  179963. # undef PNG_DEBUG
  179964. # endif
  179965. #endif
  179966. #ifdef PNG_BUILD_DLL
  179967. # ifndef PNG_CONSOLE_IO_SUPPORTED
  179968. # ifndef PNG_NO_CONSOLE_IO
  179969. # define PNG_NO_CONSOLE_IO
  179970. # endif
  179971. # endif
  179972. #endif
  179973. # ifdef PNG_NO_STDIO
  179974. # ifndef PNG_NO_CONSOLE_IO
  179975. # define PNG_NO_CONSOLE_IO
  179976. # endif
  179977. # ifdef PNG_DEBUG
  179978. # if (PNG_DEBUG > 0)
  179979. # include <stdio.h>
  179980. # endif
  179981. # endif
  179982. # else
  179983. # if !defined(_WIN32_WCE)
  179984. /* "stdio.h" functions are not supported on WindowsCE */
  179985. # include <stdio.h>
  179986. # endif
  179987. # endif
  179988. /* This macro protects us against machines that don't have function
  179989. * prototypes (ie K&R style headers). If your compiler does not handle
  179990. * function prototypes, define this macro and use the included ansi2knr.
  179991. * I've always been able to use _NO_PROTO as the indicator, but you may
  179992. * need to drag the empty declaration out in front of here, or change the
  179993. * ifdef to suit your own needs.
  179994. */
  179995. #ifndef PNGARG
  179996. #ifdef OF /* zlib prototype munger */
  179997. # define PNGARG(arglist) OF(arglist)
  179998. #else
  179999. #ifdef _NO_PROTO
  180000. # define PNGARG(arglist) ()
  180001. # ifndef PNG_TYPECAST_NULL
  180002. # define PNG_TYPECAST_NULL
  180003. # endif
  180004. #else
  180005. # define PNGARG(arglist) arglist
  180006. #endif /* _NO_PROTO */
  180007. #endif /* OF */
  180008. #endif /* PNGARG */
  180009. /* Try to determine if we are compiling on a Mac. Note that testing for
  180010. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  180011. * on non-Mac platforms.
  180012. */
  180013. #ifndef MACOS
  180014. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  180015. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  180016. # define MACOS
  180017. # endif
  180018. #endif
  180019. /* enough people need this for various reasons to include it here */
  180020. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  180021. # include <sys/types.h>
  180022. #endif
  180023. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  180024. # define PNG_SETJMP_SUPPORTED
  180025. #endif
  180026. #ifdef PNG_SETJMP_SUPPORTED
  180027. /* This is an attempt to force a single setjmp behaviour on Linux. If
  180028. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  180029. */
  180030. # ifdef __linux__
  180031. # ifdef _BSD_SOURCE
  180032. # define PNG_SAVE_BSD_SOURCE
  180033. # undef _BSD_SOURCE
  180034. # endif
  180035. # ifdef _SETJMP_H
  180036. /* If you encounter a compiler error here, see the explanation
  180037. * near the end of INSTALL.
  180038. */
  180039. __png.h__ already includes setjmp.h;
  180040. __dont__ include it again.;
  180041. # endif
  180042. # endif /* __linux__ */
  180043. /* include setjmp.h for error handling */
  180044. # include <setjmp.h>
  180045. # ifdef __linux__
  180046. # ifdef PNG_SAVE_BSD_SOURCE
  180047. # define _BSD_SOURCE
  180048. # undef PNG_SAVE_BSD_SOURCE
  180049. # endif
  180050. # endif /* __linux__ */
  180051. #endif /* PNG_SETJMP_SUPPORTED */
  180052. #ifdef BSD
  180053. #if ! JUCE_MAC
  180054. # include <strings.h>
  180055. #endif
  180056. #else
  180057. # include <string.h>
  180058. #endif
  180059. /* Other defines for things like memory and the like can go here. */
  180060. #ifdef PNG_INTERNAL
  180061. #include <stdlib.h>
  180062. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  180063. * aren't usually used outside the library (as far as I know), so it is
  180064. * debatable if they should be exported at all. In the future, when it is
  180065. * possible to have run-time registry of chunk-handling functions, some of
  180066. * these will be made available again.
  180067. #define PNG_EXTERN extern
  180068. */
  180069. #define PNG_EXTERN
  180070. /* Other defines specific to compilers can go here. Try to keep
  180071. * them inside an appropriate ifdef/endif pair for portability.
  180072. */
  180073. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  180074. # if defined(MACOS)
  180075. /* We need to check that <math.h> hasn't already been included earlier
  180076. * as it seems it doesn't agree with <fp.h>, yet we should really use
  180077. * <fp.h> if possible.
  180078. */
  180079. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  180080. # include <fp.h>
  180081. # endif
  180082. # else
  180083. # include <math.h>
  180084. # endif
  180085. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  180086. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  180087. * MATH=68881
  180088. */
  180089. # include <m68881.h>
  180090. # endif
  180091. #endif
  180092. /* Codewarrior on NT has linking problems without this. */
  180093. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  180094. # define PNG_ALWAYS_EXTERN
  180095. #endif
  180096. /* This provides the non-ANSI (far) memory allocation routines. */
  180097. #if defined(__TURBOC__) && defined(__MSDOS__)
  180098. # include <mem.h>
  180099. # include <alloc.h>
  180100. #endif
  180101. /* I have no idea why is this necessary... */
  180102. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  180103. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  180104. # include <malloc.h>
  180105. #endif
  180106. /* This controls how fine the dithering gets. As this allocates
  180107. * a largish chunk of memory (32K), those who are not as concerned
  180108. * with dithering quality can decrease some or all of these.
  180109. */
  180110. #ifndef PNG_DITHER_RED_BITS
  180111. # define PNG_DITHER_RED_BITS 5
  180112. #endif
  180113. #ifndef PNG_DITHER_GREEN_BITS
  180114. # define PNG_DITHER_GREEN_BITS 5
  180115. #endif
  180116. #ifndef PNG_DITHER_BLUE_BITS
  180117. # define PNG_DITHER_BLUE_BITS 5
  180118. #endif
  180119. /* This controls how fine the gamma correction becomes when you
  180120. * are only interested in 8 bits anyway. Increasing this value
  180121. * results in more memory being used, and more pow() functions
  180122. * being called to fill in the gamma tables. Don't set this value
  180123. * less then 8, and even that may not work (I haven't tested it).
  180124. */
  180125. #ifndef PNG_MAX_GAMMA_8
  180126. # define PNG_MAX_GAMMA_8 11
  180127. #endif
  180128. /* This controls how much a difference in gamma we can tolerate before
  180129. * we actually start doing gamma conversion.
  180130. */
  180131. #ifndef PNG_GAMMA_THRESHOLD
  180132. # define PNG_GAMMA_THRESHOLD 0.05
  180133. #endif
  180134. #endif /* PNG_INTERNAL */
  180135. /* The following uses const char * instead of char * for error
  180136. * and warning message functions, so some compilers won't complain.
  180137. * If you do not want to use const, define PNG_NO_CONST here.
  180138. */
  180139. #ifndef PNG_NO_CONST
  180140. # define PNG_CONST const
  180141. #else
  180142. # define PNG_CONST
  180143. #endif
  180144. /* The following defines give you the ability to remove code from the
  180145. * library that you will not be using. I wish I could figure out how to
  180146. * automate this, but I can't do that without making it seriously hard
  180147. * on the users. So if you are not using an ability, change the #define
  180148. * to and #undef, and that part of the library will not be compiled. If
  180149. * your linker can't find a function, you may want to make sure the
  180150. * ability is defined here. Some of these depend upon some others being
  180151. * defined. I haven't figured out all the interactions here, so you may
  180152. * have to experiment awhile to get everything to compile. If you are
  180153. * creating or using a shared library, you probably shouldn't touch this,
  180154. * as it will affect the size of the structures, and this will cause bad
  180155. * things to happen if the library and/or application ever change.
  180156. */
  180157. /* Any features you will not be using can be undef'ed here */
  180158. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  180159. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  180160. * on the compile line, then pick and choose which ones to define without
  180161. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  180162. * if you only want to have a png-compliant reader/writer but don't need
  180163. * any of the extra transformations. This saves about 80 kbytes in a
  180164. * typical installation of the library. (PNG_NO_* form added in version
  180165. * 1.0.1c, for consistency)
  180166. */
  180167. /* The size of the png_text structure changed in libpng-1.0.6 when
  180168. * iTXt support was added. iTXt support was turned off by default through
  180169. * libpng-1.2.x, to support old apps that malloc the png_text structure
  180170. * instead of calling png_set_text() and letting libpng malloc it. It
  180171. * was turned on by default in libpng-1.3.0.
  180172. */
  180173. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180174. # ifndef PNG_NO_iTXt_SUPPORTED
  180175. # define PNG_NO_iTXt_SUPPORTED
  180176. # endif
  180177. # ifndef PNG_NO_READ_iTXt
  180178. # define PNG_NO_READ_iTXt
  180179. # endif
  180180. # ifndef PNG_NO_WRITE_iTXt
  180181. # define PNG_NO_WRITE_iTXt
  180182. # endif
  180183. #endif
  180184. #if !defined(PNG_NO_iTXt_SUPPORTED)
  180185. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  180186. # define PNG_READ_iTXt
  180187. # endif
  180188. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  180189. # define PNG_WRITE_iTXt
  180190. # endif
  180191. #endif
  180192. /* The following support, added after version 1.0.0, can be turned off here en
  180193. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  180194. * with old applications that require the length of png_struct and png_info
  180195. * to remain unchanged.
  180196. */
  180197. #ifdef PNG_LEGACY_SUPPORTED
  180198. # define PNG_NO_FREE_ME
  180199. # define PNG_NO_READ_UNKNOWN_CHUNKS
  180200. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  180201. # define PNG_NO_READ_USER_CHUNKS
  180202. # define PNG_NO_READ_iCCP
  180203. # define PNG_NO_WRITE_iCCP
  180204. # define PNG_NO_READ_iTXt
  180205. # define PNG_NO_WRITE_iTXt
  180206. # define PNG_NO_READ_sCAL
  180207. # define PNG_NO_WRITE_sCAL
  180208. # define PNG_NO_READ_sPLT
  180209. # define PNG_NO_WRITE_sPLT
  180210. # define PNG_NO_INFO_IMAGE
  180211. # define PNG_NO_READ_RGB_TO_GRAY
  180212. # define PNG_NO_READ_USER_TRANSFORM
  180213. # define PNG_NO_WRITE_USER_TRANSFORM
  180214. # define PNG_NO_USER_MEM
  180215. # define PNG_NO_READ_EMPTY_PLTE
  180216. # define PNG_NO_MNG_FEATURES
  180217. # define PNG_NO_FIXED_POINT_SUPPORTED
  180218. #endif
  180219. /* Ignore attempt to turn off both floating and fixed point support */
  180220. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  180221. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  180222. # define PNG_FIXED_POINT_SUPPORTED
  180223. #endif
  180224. #ifndef PNG_NO_FREE_ME
  180225. # define PNG_FREE_ME_SUPPORTED
  180226. #endif
  180227. #if defined(PNG_READ_SUPPORTED)
  180228. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  180229. !defined(PNG_NO_READ_TRANSFORMS)
  180230. # define PNG_READ_TRANSFORMS_SUPPORTED
  180231. #endif
  180232. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  180233. # ifndef PNG_NO_READ_EXPAND
  180234. # define PNG_READ_EXPAND_SUPPORTED
  180235. # endif
  180236. # ifndef PNG_NO_READ_SHIFT
  180237. # define PNG_READ_SHIFT_SUPPORTED
  180238. # endif
  180239. # ifndef PNG_NO_READ_PACK
  180240. # define PNG_READ_PACK_SUPPORTED
  180241. # endif
  180242. # ifndef PNG_NO_READ_BGR
  180243. # define PNG_READ_BGR_SUPPORTED
  180244. # endif
  180245. # ifndef PNG_NO_READ_SWAP
  180246. # define PNG_READ_SWAP_SUPPORTED
  180247. # endif
  180248. # ifndef PNG_NO_READ_PACKSWAP
  180249. # define PNG_READ_PACKSWAP_SUPPORTED
  180250. # endif
  180251. # ifndef PNG_NO_READ_INVERT
  180252. # define PNG_READ_INVERT_SUPPORTED
  180253. # endif
  180254. # ifndef PNG_NO_READ_DITHER
  180255. # define PNG_READ_DITHER_SUPPORTED
  180256. # endif
  180257. # ifndef PNG_NO_READ_BACKGROUND
  180258. # define PNG_READ_BACKGROUND_SUPPORTED
  180259. # endif
  180260. # ifndef PNG_NO_READ_16_TO_8
  180261. # define PNG_READ_16_TO_8_SUPPORTED
  180262. # endif
  180263. # ifndef PNG_NO_READ_FILLER
  180264. # define PNG_READ_FILLER_SUPPORTED
  180265. # endif
  180266. # ifndef PNG_NO_READ_GAMMA
  180267. # define PNG_READ_GAMMA_SUPPORTED
  180268. # endif
  180269. # ifndef PNG_NO_READ_GRAY_TO_RGB
  180270. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  180271. # endif
  180272. # ifndef PNG_NO_READ_SWAP_ALPHA
  180273. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  180274. # endif
  180275. # ifndef PNG_NO_READ_INVERT_ALPHA
  180276. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  180277. # endif
  180278. # ifndef PNG_NO_READ_STRIP_ALPHA
  180279. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  180280. # endif
  180281. # ifndef PNG_NO_READ_USER_TRANSFORM
  180282. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  180283. # endif
  180284. # ifndef PNG_NO_READ_RGB_TO_GRAY
  180285. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  180286. # endif
  180287. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  180288. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  180289. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  180290. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  180291. #endif /* about interlacing capability! You'll */
  180292. /* still have interlacing unless you change the following line: */
  180293. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  180294. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  180295. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  180296. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  180297. # endif
  180298. #endif
  180299. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180300. /* Deprecated, will be removed from version 2.0.0.
  180301. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  180302. #ifndef PNG_NO_READ_EMPTY_PLTE
  180303. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  180304. #endif
  180305. #endif
  180306. #endif /* PNG_READ_SUPPORTED */
  180307. #if defined(PNG_WRITE_SUPPORTED)
  180308. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  180309. !defined(PNG_NO_WRITE_TRANSFORMS)
  180310. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  180311. #endif
  180312. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  180313. # ifndef PNG_NO_WRITE_SHIFT
  180314. # define PNG_WRITE_SHIFT_SUPPORTED
  180315. # endif
  180316. # ifndef PNG_NO_WRITE_PACK
  180317. # define PNG_WRITE_PACK_SUPPORTED
  180318. # endif
  180319. # ifndef PNG_NO_WRITE_BGR
  180320. # define PNG_WRITE_BGR_SUPPORTED
  180321. # endif
  180322. # ifndef PNG_NO_WRITE_SWAP
  180323. # define PNG_WRITE_SWAP_SUPPORTED
  180324. # endif
  180325. # ifndef PNG_NO_WRITE_PACKSWAP
  180326. # define PNG_WRITE_PACKSWAP_SUPPORTED
  180327. # endif
  180328. # ifndef PNG_NO_WRITE_INVERT
  180329. # define PNG_WRITE_INVERT_SUPPORTED
  180330. # endif
  180331. # ifndef PNG_NO_WRITE_FILLER
  180332. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  180333. # endif
  180334. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  180335. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  180336. # endif
  180337. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  180338. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  180339. # endif
  180340. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  180341. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  180342. # endif
  180343. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  180344. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  180345. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  180346. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  180347. encoders, but can cause trouble
  180348. if left undefined */
  180349. #endif
  180350. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  180351. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  180352. defined(PNG_FLOATING_POINT_SUPPORTED)
  180353. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  180354. #endif
  180355. #ifndef PNG_NO_WRITE_FLUSH
  180356. # define PNG_WRITE_FLUSH_SUPPORTED
  180357. #endif
  180358. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180359. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  180360. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  180361. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  180362. #endif
  180363. #endif
  180364. #endif /* PNG_WRITE_SUPPORTED */
  180365. #ifndef PNG_1_0_X
  180366. # ifndef PNG_NO_ERROR_NUMBERS
  180367. # define PNG_ERROR_NUMBERS_SUPPORTED
  180368. # endif
  180369. #endif /* PNG_1_0_X */
  180370. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  180371. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  180372. # ifndef PNG_NO_USER_TRANSFORM_PTR
  180373. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  180374. # endif
  180375. #endif
  180376. #ifndef PNG_NO_STDIO
  180377. # define PNG_TIME_RFC1123_SUPPORTED
  180378. #endif
  180379. /* This adds extra functions in pngget.c for accessing data from the
  180380. * info pointer (added in version 0.99)
  180381. * png_get_image_width()
  180382. * png_get_image_height()
  180383. * png_get_bit_depth()
  180384. * png_get_color_type()
  180385. * png_get_compression_type()
  180386. * png_get_filter_type()
  180387. * png_get_interlace_type()
  180388. * png_get_pixel_aspect_ratio()
  180389. * png_get_pixels_per_meter()
  180390. * png_get_x_offset_pixels()
  180391. * png_get_y_offset_pixels()
  180392. * png_get_x_offset_microns()
  180393. * png_get_y_offset_microns()
  180394. */
  180395. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  180396. # define PNG_EASY_ACCESS_SUPPORTED
  180397. #endif
  180398. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  180399. * and removed from version 1.2.20. The following will be removed
  180400. * from libpng-1.4.0
  180401. */
  180402. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  180403. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  180404. # define PNG_OPTIMIZED_CODE_SUPPORTED
  180405. # endif
  180406. #endif
  180407. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  180408. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  180409. # define PNG_ASSEMBLER_CODE_SUPPORTED
  180410. # endif
  180411. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  180412. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  180413. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180414. # define PNG_NO_MMX_CODE
  180415. # endif
  180416. # endif
  180417. # if defined(__APPLE__)
  180418. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180419. # define PNG_NO_MMX_CODE
  180420. # endif
  180421. # endif
  180422. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  180423. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180424. # define PNG_NO_MMX_CODE
  180425. # endif
  180426. # endif
  180427. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180428. # define PNG_MMX_CODE_SUPPORTED
  180429. # endif
  180430. #endif
  180431. /* end of obsolete code to be removed from libpng-1.4.0 */
  180432. #if !defined(PNG_1_0_X)
  180433. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  180434. # define PNG_USER_MEM_SUPPORTED
  180435. #endif
  180436. #endif /* PNG_1_0_X */
  180437. /* Added at libpng-1.2.6 */
  180438. #if !defined(PNG_1_0_X)
  180439. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  180440. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  180441. # define PNG_SET_USER_LIMITS_SUPPORTED
  180442. #endif
  180443. #endif
  180444. #endif /* PNG_1_0_X */
  180445. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  180446. * how large, set these limits to 0x7fffffffL
  180447. */
  180448. #ifndef PNG_USER_WIDTH_MAX
  180449. # define PNG_USER_WIDTH_MAX 1000000L
  180450. #endif
  180451. #ifndef PNG_USER_HEIGHT_MAX
  180452. # define PNG_USER_HEIGHT_MAX 1000000L
  180453. #endif
  180454. /* These are currently experimental features, define them if you want */
  180455. /* very little testing */
  180456. /*
  180457. #ifdef PNG_READ_SUPPORTED
  180458. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  180459. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  180460. # endif
  180461. #endif
  180462. */
  180463. /* This is only for PowerPC big-endian and 680x0 systems */
  180464. /* some testing */
  180465. /*
  180466. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  180467. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  180468. #endif
  180469. */
  180470. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  180471. /*
  180472. #define PNG_NO_POINTER_INDEXING
  180473. */
  180474. /* These functions are turned off by default, as they will be phased out. */
  180475. /*
  180476. #define PNG_USELESS_TESTS_SUPPORTED
  180477. #define PNG_CORRECT_PALETTE_SUPPORTED
  180478. */
  180479. /* Any chunks you are not interested in, you can undef here. The
  180480. * ones that allocate memory may be expecially important (hIST,
  180481. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  180482. * a bit smaller.
  180483. */
  180484. #if defined(PNG_READ_SUPPORTED) && \
  180485. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  180486. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  180487. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  180488. #endif
  180489. #if defined(PNG_WRITE_SUPPORTED) && \
  180490. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  180491. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  180492. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  180493. #endif
  180494. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  180495. #ifdef PNG_NO_READ_TEXT
  180496. # define PNG_NO_READ_iTXt
  180497. # define PNG_NO_READ_tEXt
  180498. # define PNG_NO_READ_zTXt
  180499. #endif
  180500. #ifndef PNG_NO_READ_bKGD
  180501. # define PNG_READ_bKGD_SUPPORTED
  180502. # define PNG_bKGD_SUPPORTED
  180503. #endif
  180504. #ifndef PNG_NO_READ_cHRM
  180505. # define PNG_READ_cHRM_SUPPORTED
  180506. # define PNG_cHRM_SUPPORTED
  180507. #endif
  180508. #ifndef PNG_NO_READ_gAMA
  180509. # define PNG_READ_gAMA_SUPPORTED
  180510. # define PNG_gAMA_SUPPORTED
  180511. #endif
  180512. #ifndef PNG_NO_READ_hIST
  180513. # define PNG_READ_hIST_SUPPORTED
  180514. # define PNG_hIST_SUPPORTED
  180515. #endif
  180516. #ifndef PNG_NO_READ_iCCP
  180517. # define PNG_READ_iCCP_SUPPORTED
  180518. # define PNG_iCCP_SUPPORTED
  180519. #endif
  180520. #ifndef PNG_NO_READ_iTXt
  180521. # ifndef PNG_READ_iTXt_SUPPORTED
  180522. # define PNG_READ_iTXt_SUPPORTED
  180523. # endif
  180524. # ifndef PNG_iTXt_SUPPORTED
  180525. # define PNG_iTXt_SUPPORTED
  180526. # endif
  180527. #endif
  180528. #ifndef PNG_NO_READ_oFFs
  180529. # define PNG_READ_oFFs_SUPPORTED
  180530. # define PNG_oFFs_SUPPORTED
  180531. #endif
  180532. #ifndef PNG_NO_READ_pCAL
  180533. # define PNG_READ_pCAL_SUPPORTED
  180534. # define PNG_pCAL_SUPPORTED
  180535. #endif
  180536. #ifndef PNG_NO_READ_sCAL
  180537. # define PNG_READ_sCAL_SUPPORTED
  180538. # define PNG_sCAL_SUPPORTED
  180539. #endif
  180540. #ifndef PNG_NO_READ_pHYs
  180541. # define PNG_READ_pHYs_SUPPORTED
  180542. # define PNG_pHYs_SUPPORTED
  180543. #endif
  180544. #ifndef PNG_NO_READ_sBIT
  180545. # define PNG_READ_sBIT_SUPPORTED
  180546. # define PNG_sBIT_SUPPORTED
  180547. #endif
  180548. #ifndef PNG_NO_READ_sPLT
  180549. # define PNG_READ_sPLT_SUPPORTED
  180550. # define PNG_sPLT_SUPPORTED
  180551. #endif
  180552. #ifndef PNG_NO_READ_sRGB
  180553. # define PNG_READ_sRGB_SUPPORTED
  180554. # define PNG_sRGB_SUPPORTED
  180555. #endif
  180556. #ifndef PNG_NO_READ_tEXt
  180557. # define PNG_READ_tEXt_SUPPORTED
  180558. # define PNG_tEXt_SUPPORTED
  180559. #endif
  180560. #ifndef PNG_NO_READ_tIME
  180561. # define PNG_READ_tIME_SUPPORTED
  180562. # define PNG_tIME_SUPPORTED
  180563. #endif
  180564. #ifndef PNG_NO_READ_tRNS
  180565. # define PNG_READ_tRNS_SUPPORTED
  180566. # define PNG_tRNS_SUPPORTED
  180567. #endif
  180568. #ifndef PNG_NO_READ_zTXt
  180569. # define PNG_READ_zTXt_SUPPORTED
  180570. # define PNG_zTXt_SUPPORTED
  180571. #endif
  180572. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  180573. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  180574. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  180575. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  180576. # endif
  180577. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  180578. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  180579. # endif
  180580. #endif
  180581. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  180582. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  180583. # define PNG_READ_USER_CHUNKS_SUPPORTED
  180584. # define PNG_USER_CHUNKS_SUPPORTED
  180585. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  180586. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  180587. # endif
  180588. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  180589. # undef PNG_NO_HANDLE_AS_UNKNOWN
  180590. # endif
  180591. #endif
  180592. #ifndef PNG_NO_READ_OPT_PLTE
  180593. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  180594. #endif /* optional PLTE chunk in RGB and RGBA images */
  180595. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  180596. defined(PNG_READ_zTXt_SUPPORTED)
  180597. # define PNG_READ_TEXT_SUPPORTED
  180598. # define PNG_TEXT_SUPPORTED
  180599. #endif
  180600. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  180601. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  180602. #ifdef PNG_NO_WRITE_TEXT
  180603. # define PNG_NO_WRITE_iTXt
  180604. # define PNG_NO_WRITE_tEXt
  180605. # define PNG_NO_WRITE_zTXt
  180606. #endif
  180607. #ifndef PNG_NO_WRITE_bKGD
  180608. # define PNG_WRITE_bKGD_SUPPORTED
  180609. # ifndef PNG_bKGD_SUPPORTED
  180610. # define PNG_bKGD_SUPPORTED
  180611. # endif
  180612. #endif
  180613. #ifndef PNG_NO_WRITE_cHRM
  180614. # define PNG_WRITE_cHRM_SUPPORTED
  180615. # ifndef PNG_cHRM_SUPPORTED
  180616. # define PNG_cHRM_SUPPORTED
  180617. # endif
  180618. #endif
  180619. #ifndef PNG_NO_WRITE_gAMA
  180620. # define PNG_WRITE_gAMA_SUPPORTED
  180621. # ifndef PNG_gAMA_SUPPORTED
  180622. # define PNG_gAMA_SUPPORTED
  180623. # endif
  180624. #endif
  180625. #ifndef PNG_NO_WRITE_hIST
  180626. # define PNG_WRITE_hIST_SUPPORTED
  180627. # ifndef PNG_hIST_SUPPORTED
  180628. # define PNG_hIST_SUPPORTED
  180629. # endif
  180630. #endif
  180631. #ifndef PNG_NO_WRITE_iCCP
  180632. # define PNG_WRITE_iCCP_SUPPORTED
  180633. # ifndef PNG_iCCP_SUPPORTED
  180634. # define PNG_iCCP_SUPPORTED
  180635. # endif
  180636. #endif
  180637. #ifndef PNG_NO_WRITE_iTXt
  180638. # ifndef PNG_WRITE_iTXt_SUPPORTED
  180639. # define PNG_WRITE_iTXt_SUPPORTED
  180640. # endif
  180641. # ifndef PNG_iTXt_SUPPORTED
  180642. # define PNG_iTXt_SUPPORTED
  180643. # endif
  180644. #endif
  180645. #ifndef PNG_NO_WRITE_oFFs
  180646. # define PNG_WRITE_oFFs_SUPPORTED
  180647. # ifndef PNG_oFFs_SUPPORTED
  180648. # define PNG_oFFs_SUPPORTED
  180649. # endif
  180650. #endif
  180651. #ifndef PNG_NO_WRITE_pCAL
  180652. # define PNG_WRITE_pCAL_SUPPORTED
  180653. # ifndef PNG_pCAL_SUPPORTED
  180654. # define PNG_pCAL_SUPPORTED
  180655. # endif
  180656. #endif
  180657. #ifndef PNG_NO_WRITE_sCAL
  180658. # define PNG_WRITE_sCAL_SUPPORTED
  180659. # ifndef PNG_sCAL_SUPPORTED
  180660. # define PNG_sCAL_SUPPORTED
  180661. # endif
  180662. #endif
  180663. #ifndef PNG_NO_WRITE_pHYs
  180664. # define PNG_WRITE_pHYs_SUPPORTED
  180665. # ifndef PNG_pHYs_SUPPORTED
  180666. # define PNG_pHYs_SUPPORTED
  180667. # endif
  180668. #endif
  180669. #ifndef PNG_NO_WRITE_sBIT
  180670. # define PNG_WRITE_sBIT_SUPPORTED
  180671. # ifndef PNG_sBIT_SUPPORTED
  180672. # define PNG_sBIT_SUPPORTED
  180673. # endif
  180674. #endif
  180675. #ifndef PNG_NO_WRITE_sPLT
  180676. # define PNG_WRITE_sPLT_SUPPORTED
  180677. # ifndef PNG_sPLT_SUPPORTED
  180678. # define PNG_sPLT_SUPPORTED
  180679. # endif
  180680. #endif
  180681. #ifndef PNG_NO_WRITE_sRGB
  180682. # define PNG_WRITE_sRGB_SUPPORTED
  180683. # ifndef PNG_sRGB_SUPPORTED
  180684. # define PNG_sRGB_SUPPORTED
  180685. # endif
  180686. #endif
  180687. #ifndef PNG_NO_WRITE_tEXt
  180688. # define PNG_WRITE_tEXt_SUPPORTED
  180689. # ifndef PNG_tEXt_SUPPORTED
  180690. # define PNG_tEXt_SUPPORTED
  180691. # endif
  180692. #endif
  180693. #ifndef PNG_NO_WRITE_tIME
  180694. # define PNG_WRITE_tIME_SUPPORTED
  180695. # ifndef PNG_tIME_SUPPORTED
  180696. # define PNG_tIME_SUPPORTED
  180697. # endif
  180698. #endif
  180699. #ifndef PNG_NO_WRITE_tRNS
  180700. # define PNG_WRITE_tRNS_SUPPORTED
  180701. # ifndef PNG_tRNS_SUPPORTED
  180702. # define PNG_tRNS_SUPPORTED
  180703. # endif
  180704. #endif
  180705. #ifndef PNG_NO_WRITE_zTXt
  180706. # define PNG_WRITE_zTXt_SUPPORTED
  180707. # ifndef PNG_zTXt_SUPPORTED
  180708. # define PNG_zTXt_SUPPORTED
  180709. # endif
  180710. #endif
  180711. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  180712. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  180713. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  180714. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  180715. # endif
  180716. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  180717. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  180718. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  180719. # endif
  180720. # endif
  180721. #endif
  180722. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  180723. defined(PNG_WRITE_zTXt_SUPPORTED)
  180724. # define PNG_WRITE_TEXT_SUPPORTED
  180725. # ifndef PNG_TEXT_SUPPORTED
  180726. # define PNG_TEXT_SUPPORTED
  180727. # endif
  180728. #endif
  180729. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  180730. /* Turn this off to disable png_read_png() and
  180731. * png_write_png() and leave the row_pointers member
  180732. * out of the info structure.
  180733. */
  180734. #ifndef PNG_NO_INFO_IMAGE
  180735. # define PNG_INFO_IMAGE_SUPPORTED
  180736. #endif
  180737. /* need the time information for reading tIME chunks */
  180738. #if defined(PNG_tIME_SUPPORTED)
  180739. # if !defined(_WIN32_WCE)
  180740. /* "time.h" functions are not supported on WindowsCE */
  180741. # include <time.h>
  180742. # endif
  180743. #endif
  180744. /* Some typedefs to get us started. These should be safe on most of the
  180745. * common platforms. The typedefs should be at least as large as the
  180746. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  180747. * don't have to be exactly that size. Some compilers dislike passing
  180748. * unsigned shorts as function parameters, so you may be better off using
  180749. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  180750. * want to have unsigned int for png_uint_32 instead of unsigned long.
  180751. */
  180752. typedef unsigned long png_uint_32;
  180753. typedef long png_int_32;
  180754. typedef unsigned short png_uint_16;
  180755. typedef short png_int_16;
  180756. typedef unsigned char png_byte;
  180757. /* This is usually size_t. It is typedef'ed just in case you need it to
  180758. change (I'm not sure if you will or not, so I thought I'd be safe) */
  180759. #ifdef PNG_SIZE_T
  180760. typedef PNG_SIZE_T png_size_t;
  180761. # define png_sizeof(x) png_convert_size(sizeof (x))
  180762. #else
  180763. typedef size_t png_size_t;
  180764. # define png_sizeof(x) sizeof (x)
  180765. #endif
  180766. /* The following is needed for medium model support. It cannot be in the
  180767. * PNG_INTERNAL section. Needs modification for other compilers besides
  180768. * MSC. Model independent support declares all arrays and pointers to be
  180769. * large using the far keyword. The zlib version used must also support
  180770. * model independent data. As of version zlib 1.0.4, the necessary changes
  180771. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  180772. * changes that are needed. (Tim Wegner)
  180773. */
  180774. /* Separate compiler dependencies (problem here is that zlib.h always
  180775. defines FAR. (SJT) */
  180776. #ifdef __BORLANDC__
  180777. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  180778. # define LDATA 1
  180779. # else
  180780. # define LDATA 0
  180781. # endif
  180782. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  180783. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  180784. # define PNG_MAX_MALLOC_64K
  180785. # if (LDATA != 1)
  180786. # ifndef FAR
  180787. # define FAR __far
  180788. # endif
  180789. # define USE_FAR_KEYWORD
  180790. # endif /* LDATA != 1 */
  180791. /* Possibly useful for moving data out of default segment.
  180792. * Uncomment it if you want. Could also define FARDATA as
  180793. * const if your compiler supports it. (SJT)
  180794. # define FARDATA FAR
  180795. */
  180796. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  180797. #endif /* __BORLANDC__ */
  180798. /* Suggest testing for specific compiler first before testing for
  180799. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  180800. * making reliance oncertain keywords suspect. (SJT)
  180801. */
  180802. /* MSC Medium model */
  180803. #if defined(FAR)
  180804. # if defined(M_I86MM)
  180805. # define USE_FAR_KEYWORD
  180806. # define FARDATA FAR
  180807. # include <dos.h>
  180808. # endif
  180809. #endif
  180810. /* SJT: default case */
  180811. #ifndef FAR
  180812. # define FAR
  180813. #endif
  180814. /* At this point FAR is always defined */
  180815. #ifndef FARDATA
  180816. # define FARDATA
  180817. #endif
  180818. /* Typedef for floating-point numbers that are converted
  180819. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  180820. typedef png_int_32 png_fixed_point;
  180821. /* Add typedefs for pointers */
  180822. typedef void FAR * png_voidp;
  180823. typedef png_byte FAR * png_bytep;
  180824. typedef png_uint_32 FAR * png_uint_32p;
  180825. typedef png_int_32 FAR * png_int_32p;
  180826. typedef png_uint_16 FAR * png_uint_16p;
  180827. typedef png_int_16 FAR * png_int_16p;
  180828. typedef PNG_CONST char FAR * png_const_charp;
  180829. typedef char FAR * png_charp;
  180830. typedef png_fixed_point FAR * png_fixed_point_p;
  180831. #ifndef PNG_NO_STDIO
  180832. #if defined(_WIN32_WCE)
  180833. typedef HANDLE png_FILE_p;
  180834. #else
  180835. typedef FILE * png_FILE_p;
  180836. #endif
  180837. #endif
  180838. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180839. typedef double FAR * png_doublep;
  180840. #endif
  180841. /* Pointers to pointers; i.e. arrays */
  180842. typedef png_byte FAR * FAR * png_bytepp;
  180843. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  180844. typedef png_int_32 FAR * FAR * png_int_32pp;
  180845. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  180846. typedef png_int_16 FAR * FAR * png_int_16pp;
  180847. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  180848. typedef char FAR * FAR * png_charpp;
  180849. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  180850. #ifdef PNG_FLOATING_POINT_SUPPORTED
  180851. typedef double FAR * FAR * png_doublepp;
  180852. #endif
  180853. /* Pointers to pointers to pointers; i.e., pointer to array */
  180854. typedef char FAR * FAR * FAR * png_charppp;
  180855. #if 0
  180856. /* SPC - Is this stuff deprecated? */
  180857. /* It'll be removed as of libpng-1.3.0 - GR-P */
  180858. /* libpng typedefs for types in zlib. If zlib changes
  180859. * or another compression library is used, then change these.
  180860. * Eliminates need to change all the source files.
  180861. */
  180862. typedef charf * png_zcharp;
  180863. typedef charf * FAR * png_zcharpp;
  180864. typedef z_stream FAR * png_zstreamp;
  180865. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  180866. /*
  180867. * Define PNG_BUILD_DLL if the module being built is a Windows
  180868. * LIBPNG DLL.
  180869. *
  180870. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  180871. * It is equivalent to Microsoft predefined macro _DLL that is
  180872. * automatically defined when you compile using the share
  180873. * version of the CRT (C Run-Time library)
  180874. *
  180875. * The cygwin mods make this behavior a little different:
  180876. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  180877. * Define PNG_STATIC if you are building a static library for use with cygwin,
  180878. * -or- if you are building an application that you want to link to the
  180879. * static library.
  180880. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  180881. * the other flags is defined.
  180882. */
  180883. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  180884. # define PNG_DLL
  180885. #endif
  180886. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  180887. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  180888. * command-line override
  180889. */
  180890. #if defined(__CYGWIN__)
  180891. # if !defined(PNG_STATIC)
  180892. # if defined(PNG_USE_GLOBAL_ARRAYS)
  180893. # undef PNG_USE_GLOBAL_ARRAYS
  180894. # endif
  180895. # if !defined(PNG_USE_LOCAL_ARRAYS)
  180896. # define PNG_USE_LOCAL_ARRAYS
  180897. # endif
  180898. # else
  180899. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  180900. # if defined(PNG_USE_GLOBAL_ARRAYS)
  180901. # undef PNG_USE_GLOBAL_ARRAYS
  180902. # endif
  180903. # endif
  180904. # endif
  180905. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  180906. # define PNG_USE_LOCAL_ARRAYS
  180907. # endif
  180908. #endif
  180909. /* Do not use global arrays (helps with building DLL's)
  180910. * They are no longer used in libpng itself, since version 1.0.5c,
  180911. * but might be required for some pre-1.0.5c applications.
  180912. */
  180913. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  180914. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  180915. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  180916. # define PNG_USE_LOCAL_ARRAYS
  180917. # else
  180918. # define PNG_USE_GLOBAL_ARRAYS
  180919. # endif
  180920. #endif
  180921. #if defined(__CYGWIN__)
  180922. # undef PNGAPI
  180923. # define PNGAPI __cdecl
  180924. # undef PNG_IMPEXP
  180925. # define PNG_IMPEXP
  180926. #endif
  180927. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  180928. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  180929. * Don't ignore those warnings; you must also reset the default calling
  180930. * convention in your compiler to match your PNGAPI, and you must build
  180931. * zlib and your applications the same way you build libpng.
  180932. */
  180933. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  180934. # ifndef PNG_NO_MODULEDEF
  180935. # define PNG_NO_MODULEDEF
  180936. # endif
  180937. #endif
  180938. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  180939. # define PNG_IMPEXP
  180940. #endif
  180941. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  180942. (( defined(_Windows) || defined(_WINDOWS) || \
  180943. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  180944. # ifndef PNGAPI
  180945. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  180946. # define PNGAPI __cdecl
  180947. # else
  180948. # define PNGAPI _cdecl
  180949. # endif
  180950. # endif
  180951. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  180952. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  180953. # define PNG_IMPEXP
  180954. # endif
  180955. # if !defined(PNG_IMPEXP)
  180956. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  180957. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  180958. /* Borland/Microsoft */
  180959. # if defined(_MSC_VER) || defined(__BORLANDC__)
  180960. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  180961. # define PNG_EXPORT PNG_EXPORT_TYPE1
  180962. # else
  180963. # define PNG_EXPORT PNG_EXPORT_TYPE2
  180964. # if defined(PNG_BUILD_DLL)
  180965. # define PNG_IMPEXP __export
  180966. # else
  180967. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  180968. VC++ */
  180969. # endif /* Exists in Borland C++ for
  180970. C++ classes (== huge) */
  180971. # endif
  180972. # endif
  180973. # if !defined(PNG_IMPEXP)
  180974. # if defined(PNG_BUILD_DLL)
  180975. # define PNG_IMPEXP __declspec(dllexport)
  180976. # else
  180977. # define PNG_IMPEXP __declspec(dllimport)
  180978. # endif
  180979. # endif
  180980. # endif /* PNG_IMPEXP */
  180981. #else /* !(DLL || non-cygwin WINDOWS) */
  180982. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  180983. # ifndef PNGAPI
  180984. # define PNGAPI _System
  180985. # endif
  180986. # else
  180987. # if 0 /* ... other platforms, with other meanings */
  180988. # endif
  180989. # endif
  180990. #endif
  180991. #ifndef PNGAPI
  180992. # define PNGAPI
  180993. #endif
  180994. #ifndef PNG_IMPEXP
  180995. # define PNG_IMPEXP
  180996. #endif
  180997. #ifdef PNG_BUILDSYMS
  180998. # ifndef PNG_EXPORT
  180999. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  181000. # endif
  181001. # ifdef PNG_USE_GLOBAL_ARRAYS
  181002. # ifndef PNG_EXPORT_VAR
  181003. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  181004. # endif
  181005. # endif
  181006. #endif
  181007. #ifndef PNG_EXPORT
  181008. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  181009. #endif
  181010. #ifdef PNG_USE_GLOBAL_ARRAYS
  181011. # ifndef PNG_EXPORT_VAR
  181012. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  181013. # endif
  181014. #endif
  181015. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  181016. * functions that are passed far data must be model independent.
  181017. */
  181018. #ifndef PNG_ABORT
  181019. # define PNG_ABORT() abort()
  181020. #endif
  181021. #ifdef PNG_SETJMP_SUPPORTED
  181022. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  181023. #else
  181024. # define png_jmpbuf(png_ptr) \
  181025. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  181026. #endif
  181027. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  181028. /* use this to make far-to-near assignments */
  181029. # define CHECK 1
  181030. # define NOCHECK 0
  181031. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  181032. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  181033. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  181034. # define png_strcpy _fstrcpy
  181035. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  181036. # define png_strlen _fstrlen
  181037. # define png_memcmp _fmemcmp /* SJT: added */
  181038. # define png_memcpy _fmemcpy
  181039. # define png_memset _fmemset
  181040. #else /* use the usual functions */
  181041. # define CVT_PTR(ptr) (ptr)
  181042. # define CVT_PTR_NOCHECK(ptr) (ptr)
  181043. # ifndef PNG_NO_SNPRINTF
  181044. # ifdef _MSC_VER
  181045. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  181046. # define png_snprintf2 _snprintf
  181047. # define png_snprintf6 _snprintf
  181048. # else
  181049. # define png_snprintf snprintf /* Added to v 1.2.19 */
  181050. # define png_snprintf2 snprintf
  181051. # define png_snprintf6 snprintf
  181052. # endif
  181053. # else
  181054. /* You don't have or don't want to use snprintf(). Caution: Using
  181055. * sprintf instead of snprintf exposes your application to accidental
  181056. * or malevolent buffer overflows. If you don't have snprintf()
  181057. * as a general rule you should provide one (you can get one from
  181058. * Portable OpenSSH). */
  181059. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  181060. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  181061. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  181062. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  181063. # endif
  181064. # define png_strcpy strcpy
  181065. # define png_strncpy strncpy /* Added to v 1.2.6 */
  181066. # define png_strlen strlen
  181067. # define png_memcmp memcmp /* SJT: added */
  181068. # define png_memcpy memcpy
  181069. # define png_memset memset
  181070. #endif
  181071. /* End of memory model independent support */
  181072. /* Just a little check that someone hasn't tried to define something
  181073. * contradictory.
  181074. */
  181075. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  181076. # undef PNG_ZBUF_SIZE
  181077. # define PNG_ZBUF_SIZE 65536L
  181078. #endif
  181079. /* Added at libpng-1.2.8 */
  181080. #endif /* PNG_VERSION_INFO_ONLY */
  181081. #endif /* PNGCONF_H */
  181082. /*** End of inlined file: pngconf.h ***/
  181083. #ifdef _MSC_VER
  181084. #pragma warning (disable: 4996 4100)
  181085. #endif
  181086. /*
  181087. * Added at libpng-1.2.8 */
  181088. /* Ref MSDN: Private as priority over Special
  181089. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  181090. * procedures. If this value is given, the StringFileInfo block must
  181091. * contain a PrivateBuild string.
  181092. *
  181093. * VS_FF_SPECIALBUILD File *was* built by the original company using
  181094. * standard release procedures but is a variation of the standard
  181095. * file of the same version number. If this value is given, the
  181096. * StringFileInfo block must contain a SpecialBuild string.
  181097. */
  181098. #if defined(PNG_USER_PRIVATEBUILD)
  181099. # define PNG_LIBPNG_BUILD_TYPE \
  181100. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  181101. #else
  181102. # if defined(PNG_LIBPNG_SPECIALBUILD)
  181103. # define PNG_LIBPNG_BUILD_TYPE \
  181104. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  181105. # else
  181106. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  181107. # endif
  181108. #endif
  181109. #ifndef PNG_VERSION_INFO_ONLY
  181110. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  181111. #ifdef __cplusplus
  181112. extern "C" {
  181113. #endif /* __cplusplus */
  181114. /* This file is arranged in several sections. The first section contains
  181115. * structure and type definitions. The second section contains the external
  181116. * library functions, while the third has the internal library functions,
  181117. * which applications aren't expected to use directly.
  181118. */
  181119. #ifndef PNG_NO_TYPECAST_NULL
  181120. #define int_p_NULL (int *)NULL
  181121. #define png_bytep_NULL (png_bytep)NULL
  181122. #define png_bytepp_NULL (png_bytepp)NULL
  181123. #define png_doublep_NULL (png_doublep)NULL
  181124. #define png_error_ptr_NULL (png_error_ptr)NULL
  181125. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  181126. #define png_free_ptr_NULL (png_free_ptr)NULL
  181127. #define png_infopp_NULL (png_infopp)NULL
  181128. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  181129. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  181130. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  181131. #define png_structp_NULL (png_structp)NULL
  181132. #define png_uint_16p_NULL (png_uint_16p)NULL
  181133. #define png_voidp_NULL (png_voidp)NULL
  181134. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  181135. #else
  181136. #define int_p_NULL NULL
  181137. #define png_bytep_NULL NULL
  181138. #define png_bytepp_NULL NULL
  181139. #define png_doublep_NULL NULL
  181140. #define png_error_ptr_NULL NULL
  181141. #define png_flush_ptr_NULL NULL
  181142. #define png_free_ptr_NULL NULL
  181143. #define png_infopp_NULL NULL
  181144. #define png_malloc_ptr_NULL NULL
  181145. #define png_read_status_ptr_NULL NULL
  181146. #define png_rw_ptr_NULL NULL
  181147. #define png_structp_NULL NULL
  181148. #define png_uint_16p_NULL NULL
  181149. #define png_voidp_NULL NULL
  181150. #define png_write_status_ptr_NULL NULL
  181151. #endif
  181152. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  181153. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  181154. /* Version information for C files, stored in png.c. This had better match
  181155. * the version above.
  181156. */
  181157. #ifdef PNG_USE_GLOBAL_ARRAYS
  181158. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  181159. /* need room for 99.99.99beta99z */
  181160. #else
  181161. #define png_libpng_ver png_get_header_ver(NULL)
  181162. #endif
  181163. #ifdef PNG_USE_GLOBAL_ARRAYS
  181164. /* This was removed in version 1.0.5c */
  181165. /* Structures to facilitate easy interlacing. See png.c for more details */
  181166. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  181167. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  181168. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  181169. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  181170. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  181171. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  181172. /* This isn't currently used. If you need it, see png.c for more details.
  181173. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  181174. */
  181175. #endif
  181176. #endif /* PNG_NO_EXTERN */
  181177. /* Three color definitions. The order of the red, green, and blue, (and the
  181178. * exact size) is not important, although the size of the fields need to
  181179. * be png_byte or png_uint_16 (as defined below).
  181180. */
  181181. typedef struct png_color_struct
  181182. {
  181183. png_byte red;
  181184. png_byte green;
  181185. png_byte blue;
  181186. } png_color;
  181187. typedef png_color FAR * png_colorp;
  181188. typedef png_color FAR * FAR * png_colorpp;
  181189. typedef struct png_color_16_struct
  181190. {
  181191. png_byte index; /* used for palette files */
  181192. png_uint_16 red; /* for use in red green blue files */
  181193. png_uint_16 green;
  181194. png_uint_16 blue;
  181195. png_uint_16 gray; /* for use in grayscale files */
  181196. } png_color_16;
  181197. typedef png_color_16 FAR * png_color_16p;
  181198. typedef png_color_16 FAR * FAR * png_color_16pp;
  181199. typedef struct png_color_8_struct
  181200. {
  181201. png_byte red; /* for use in red green blue files */
  181202. png_byte green;
  181203. png_byte blue;
  181204. png_byte gray; /* for use in grayscale files */
  181205. png_byte alpha; /* for alpha channel files */
  181206. } png_color_8;
  181207. typedef png_color_8 FAR * png_color_8p;
  181208. typedef png_color_8 FAR * FAR * png_color_8pp;
  181209. /*
  181210. * The following two structures are used for the in-core representation
  181211. * of sPLT chunks.
  181212. */
  181213. typedef struct png_sPLT_entry_struct
  181214. {
  181215. png_uint_16 red;
  181216. png_uint_16 green;
  181217. png_uint_16 blue;
  181218. png_uint_16 alpha;
  181219. png_uint_16 frequency;
  181220. } png_sPLT_entry;
  181221. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  181222. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  181223. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  181224. * occupy the LSB of their respective members, and the MSB of each member
  181225. * is zero-filled. The frequency member always occupies the full 16 bits.
  181226. */
  181227. typedef struct png_sPLT_struct
  181228. {
  181229. png_charp name; /* palette name */
  181230. png_byte depth; /* depth of palette samples */
  181231. png_sPLT_entryp entries; /* palette entries */
  181232. png_int_32 nentries; /* number of palette entries */
  181233. } png_sPLT_t;
  181234. typedef png_sPLT_t FAR * png_sPLT_tp;
  181235. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  181236. #ifdef PNG_TEXT_SUPPORTED
  181237. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  181238. * and whether that contents is compressed or not. The "key" field
  181239. * points to a regular zero-terminated C string. The "text", "lang", and
  181240. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  181241. * However, the * structure returned by png_get_text() will always contain
  181242. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  181243. * so they can be safely used in printf() and other string-handling functions.
  181244. */
  181245. typedef struct png_text_struct
  181246. {
  181247. int compression; /* compression value:
  181248. -1: tEXt, none
  181249. 0: zTXt, deflate
  181250. 1: iTXt, none
  181251. 2: iTXt, deflate */
  181252. png_charp key; /* keyword, 1-79 character description of "text" */
  181253. png_charp text; /* comment, may be an empty string (ie "")
  181254. or a NULL pointer */
  181255. png_size_t text_length; /* length of the text string */
  181256. #ifdef PNG_iTXt_SUPPORTED
  181257. png_size_t itxt_length; /* length of the itxt string */
  181258. png_charp lang; /* language code, 0-79 characters
  181259. or a NULL pointer */
  181260. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  181261. chars or a NULL pointer */
  181262. #endif
  181263. } png_text;
  181264. typedef png_text FAR * png_textp;
  181265. typedef png_text FAR * FAR * png_textpp;
  181266. #endif
  181267. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  181268. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  181269. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  181270. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  181271. #define PNG_TEXT_COMPRESSION_NONE -1
  181272. #define PNG_TEXT_COMPRESSION_zTXt 0
  181273. #define PNG_ITXT_COMPRESSION_NONE 1
  181274. #define PNG_ITXT_COMPRESSION_zTXt 2
  181275. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  181276. /* png_time is a way to hold the time in an machine independent way.
  181277. * Two conversions are provided, both from time_t and struct tm. There
  181278. * is no portable way to convert to either of these structures, as far
  181279. * as I know. If you know of a portable way, send it to me. As a side
  181280. * note - PNG has always been Year 2000 compliant!
  181281. */
  181282. typedef struct png_time_struct
  181283. {
  181284. png_uint_16 year; /* full year, as in, 1995 */
  181285. png_byte month; /* month of year, 1 - 12 */
  181286. png_byte day; /* day of month, 1 - 31 */
  181287. png_byte hour; /* hour of day, 0 - 23 */
  181288. png_byte minute; /* minute of hour, 0 - 59 */
  181289. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  181290. } png_time;
  181291. typedef png_time FAR * png_timep;
  181292. typedef png_time FAR * FAR * png_timepp;
  181293. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  181294. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  181295. * no specific support. The idea is that we can use this to queue
  181296. * up private chunks for output even though the library doesn't actually
  181297. * know about their semantics.
  181298. */
  181299. typedef struct png_unknown_chunk_t
  181300. {
  181301. png_byte name[5];
  181302. png_byte *data;
  181303. png_size_t size;
  181304. /* libpng-using applications should NOT directly modify this byte. */
  181305. png_byte location; /* mode of operation at read time */
  181306. }
  181307. png_unknown_chunk;
  181308. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  181309. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  181310. #endif
  181311. /* png_info is a structure that holds the information in a PNG file so
  181312. * that the application can find out the characteristics of the image.
  181313. * If you are reading the file, this structure will tell you what is
  181314. * in the PNG file. If you are writing the file, fill in the information
  181315. * you want to put into the PNG file, then call png_write_info().
  181316. * The names chosen should be very close to the PNG specification, so
  181317. * consult that document for information about the meaning of each field.
  181318. *
  181319. * With libpng < 0.95, it was only possible to directly set and read the
  181320. * the values in the png_info_struct, which meant that the contents and
  181321. * order of the values had to remain fixed. With libpng 0.95 and later,
  181322. * however, there are now functions that abstract the contents of
  181323. * png_info_struct from the application, so this makes it easier to use
  181324. * libpng with dynamic libraries, and even makes it possible to use
  181325. * libraries that don't have all of the libpng ancillary chunk-handing
  181326. * functionality.
  181327. *
  181328. * In any case, the order of the parameters in png_info_struct should NOT
  181329. * be changed for as long as possible to keep compatibility with applications
  181330. * that use the old direct-access method with png_info_struct.
  181331. *
  181332. * The following members may have allocated storage attached that should be
  181333. * cleaned up before the structure is discarded: palette, trans, text,
  181334. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  181335. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  181336. * are automatically freed when the info structure is deallocated, if they were
  181337. * allocated internally by libpng. This behavior can be changed by means
  181338. * of the png_data_freer() function.
  181339. *
  181340. * More allocation details: all the chunk-reading functions that
  181341. * change these members go through the corresponding png_set_*
  181342. * functions. A function to clear these members is available: see
  181343. * png_free_data(). The png_set_* functions do not depend on being
  181344. * able to point info structure members to any of the storage they are
  181345. * passed (they make their own copies), EXCEPT that the png_set_text
  181346. * functions use the same storage passed to them in the text_ptr or
  181347. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  181348. * functions do not make their own copies.
  181349. */
  181350. typedef struct png_info_struct
  181351. {
  181352. /* the following are necessary for every PNG file */
  181353. png_uint_32 width; /* width of image in pixels (from IHDR) */
  181354. png_uint_32 height; /* height of image in pixels (from IHDR) */
  181355. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  181356. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  181357. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  181358. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  181359. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  181360. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  181361. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  181362. /* The following three should have been named *_method not *_type */
  181363. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  181364. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  181365. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  181366. /* The following is informational only on read, and not used on writes. */
  181367. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  181368. png_byte pixel_depth; /* number of bits per pixel */
  181369. png_byte spare_byte; /* to align the data, and for future use */
  181370. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  181371. /* The rest of the data is optional. If you are reading, check the
  181372. * valid field to see if the information in these are valid. If you
  181373. * are writing, set the valid field to those chunks you want written,
  181374. * and initialize the appropriate fields below.
  181375. */
  181376. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  181377. /* The gAMA chunk describes the gamma characteristics of the system
  181378. * on which the image was created, normally in the range [1.0, 2.5].
  181379. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  181380. */
  181381. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  181382. #endif
  181383. #if defined(PNG_sRGB_SUPPORTED)
  181384. /* GR-P, 0.96a */
  181385. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  181386. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  181387. #endif
  181388. #if defined(PNG_TEXT_SUPPORTED)
  181389. /* The tEXt, and zTXt chunks contain human-readable textual data in
  181390. * uncompressed, compressed, and optionally compressed forms, respectively.
  181391. * The data in "text" is an array of pointers to uncompressed,
  181392. * null-terminated C strings. Each chunk has a keyword that describes the
  181393. * textual data contained in that chunk. Keywords are not required to be
  181394. * unique, and the text string may be empty. Any number of text chunks may
  181395. * be in an image.
  181396. */
  181397. int num_text; /* number of comments read/to write */
  181398. int max_text; /* current size of text array */
  181399. png_textp text; /* array of comments read/to write */
  181400. #endif /* PNG_TEXT_SUPPORTED */
  181401. #if defined(PNG_tIME_SUPPORTED)
  181402. /* The tIME chunk holds the last time the displayed image data was
  181403. * modified. See the png_time struct for the contents of this struct.
  181404. */
  181405. png_time mod_time;
  181406. #endif
  181407. #if defined(PNG_sBIT_SUPPORTED)
  181408. /* The sBIT chunk specifies the number of significant high-order bits
  181409. * in the pixel data. Values are in the range [1, bit_depth], and are
  181410. * only specified for the channels in the pixel data. The contents of
  181411. * the low-order bits is not specified. Data is valid if
  181412. * (valid & PNG_INFO_sBIT) is non-zero.
  181413. */
  181414. png_color_8 sig_bit; /* significant bits in color channels */
  181415. #endif
  181416. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  181417. defined(PNG_READ_BACKGROUND_SUPPORTED)
  181418. /* The tRNS chunk supplies transparency data for paletted images and
  181419. * other image types that don't need a full alpha channel. There are
  181420. * "num_trans" transparency values for a paletted image, stored in the
  181421. * same order as the palette colors, starting from index 0. Values
  181422. * for the data are in the range [0, 255], ranging from fully transparent
  181423. * to fully opaque, respectively. For non-paletted images, there is a
  181424. * single color specified that should be treated as fully transparent.
  181425. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  181426. */
  181427. png_bytep trans; /* transparent values for paletted image */
  181428. png_color_16 trans_values; /* transparent color for non-palette image */
  181429. #endif
  181430. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  181431. /* The bKGD chunk gives the suggested image background color if the
  181432. * display program does not have its own background color and the image
  181433. * is needs to composited onto a background before display. The colors
  181434. * in "background" are normally in the same color space/depth as the
  181435. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  181436. */
  181437. png_color_16 background;
  181438. #endif
  181439. #if defined(PNG_oFFs_SUPPORTED)
  181440. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  181441. * and downwards from the top-left corner of the display, page, or other
  181442. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  181443. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  181444. */
  181445. png_int_32 x_offset; /* x offset on page */
  181446. png_int_32 y_offset; /* y offset on page */
  181447. png_byte offset_unit_type; /* offset units type */
  181448. #endif
  181449. #if defined(PNG_pHYs_SUPPORTED)
  181450. /* The pHYs chunk gives the physical pixel density of the image for
  181451. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  181452. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  181453. */
  181454. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  181455. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  181456. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  181457. #endif
  181458. #if defined(PNG_hIST_SUPPORTED)
  181459. /* The hIST chunk contains the relative frequency or importance of the
  181460. * various palette entries, so that a viewer can intelligently select a
  181461. * reduced-color palette, if required. Data is an array of "num_palette"
  181462. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  181463. * is non-zero.
  181464. */
  181465. png_uint_16p hist;
  181466. #endif
  181467. #ifdef PNG_cHRM_SUPPORTED
  181468. /* The cHRM chunk describes the CIE color characteristics of the monitor
  181469. * on which the PNG was created. This data allows the viewer to do gamut
  181470. * mapping of the input image to ensure that the viewer sees the same
  181471. * colors in the image as the creator. Values are in the range
  181472. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  181473. */
  181474. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181475. float x_white;
  181476. float y_white;
  181477. float x_red;
  181478. float y_red;
  181479. float x_green;
  181480. float y_green;
  181481. float x_blue;
  181482. float y_blue;
  181483. #endif
  181484. #endif
  181485. #if defined(PNG_pCAL_SUPPORTED)
  181486. /* The pCAL chunk describes a transformation between the stored pixel
  181487. * values and original physical data values used to create the image.
  181488. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  181489. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  181490. * (possibly non-linear) transformation function given by "pcal_type"
  181491. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  181492. * defines below, and the PNG-Group's PNG extensions document for a
  181493. * complete description of the transformations and how they should be
  181494. * implemented, and for a description of the ASCII parameter strings.
  181495. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  181496. */
  181497. png_charp pcal_purpose; /* pCAL chunk description string */
  181498. png_int_32 pcal_X0; /* minimum value */
  181499. png_int_32 pcal_X1; /* maximum value */
  181500. png_charp pcal_units; /* Latin-1 string giving physical units */
  181501. png_charpp pcal_params; /* ASCII strings containing parameter values */
  181502. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  181503. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  181504. #endif
  181505. /* New members added in libpng-1.0.6 */
  181506. #ifdef PNG_FREE_ME_SUPPORTED
  181507. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  181508. #endif
  181509. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  181510. /* storage for unknown chunks that the library doesn't recognize. */
  181511. png_unknown_chunkp unknown_chunks;
  181512. png_size_t unknown_chunks_num;
  181513. #endif
  181514. #if defined(PNG_iCCP_SUPPORTED)
  181515. /* iCCP chunk data. */
  181516. png_charp iccp_name; /* profile name */
  181517. png_charp iccp_profile; /* International Color Consortium profile data */
  181518. /* Note to maintainer: should be png_bytep */
  181519. png_uint_32 iccp_proflen; /* ICC profile data length */
  181520. png_byte iccp_compression; /* Always zero */
  181521. #endif
  181522. #if defined(PNG_sPLT_SUPPORTED)
  181523. /* data on sPLT chunks (there may be more than one). */
  181524. png_sPLT_tp splt_palettes;
  181525. png_uint_32 splt_palettes_num;
  181526. #endif
  181527. #if defined(PNG_sCAL_SUPPORTED)
  181528. /* The sCAL chunk describes the actual physical dimensions of the
  181529. * subject matter of the graphic. The chunk contains a unit specification
  181530. * a byte value, and two ASCII strings representing floating-point
  181531. * values. The values are width and height corresponsing to one pixel
  181532. * in the image. This external representation is converted to double
  181533. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  181534. */
  181535. png_byte scal_unit; /* unit of physical scale */
  181536. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181537. double scal_pixel_width; /* width of one pixel */
  181538. double scal_pixel_height; /* height of one pixel */
  181539. #endif
  181540. #ifdef PNG_FIXED_POINT_SUPPORTED
  181541. png_charp scal_s_width; /* string containing height */
  181542. png_charp scal_s_height; /* string containing width */
  181543. #endif
  181544. #endif
  181545. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  181546. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  181547. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  181548. png_bytepp row_pointers; /* the image bits */
  181549. #endif
  181550. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  181551. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  181552. #endif
  181553. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  181554. png_fixed_point int_x_white;
  181555. png_fixed_point int_y_white;
  181556. png_fixed_point int_x_red;
  181557. png_fixed_point int_y_red;
  181558. png_fixed_point int_x_green;
  181559. png_fixed_point int_y_green;
  181560. png_fixed_point int_x_blue;
  181561. png_fixed_point int_y_blue;
  181562. #endif
  181563. } png_info;
  181564. typedef png_info FAR * png_infop;
  181565. typedef png_info FAR * FAR * png_infopp;
  181566. /* Maximum positive integer used in PNG is (2^31)-1 */
  181567. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  181568. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  181569. #define PNG_SIZE_MAX ((png_size_t)(-1))
  181570. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181571. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  181572. #define PNG_MAX_UINT PNG_UINT_31_MAX
  181573. #endif
  181574. /* These describe the color_type field in png_info. */
  181575. /* color type masks */
  181576. #define PNG_COLOR_MASK_PALETTE 1
  181577. #define PNG_COLOR_MASK_COLOR 2
  181578. #define PNG_COLOR_MASK_ALPHA 4
  181579. /* color types. Note that not all combinations are legal */
  181580. #define PNG_COLOR_TYPE_GRAY 0
  181581. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  181582. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  181583. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  181584. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  181585. /* aliases */
  181586. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  181587. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  181588. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  181589. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  181590. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  181591. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  181592. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  181593. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  181594. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  181595. /* These are for the interlacing type. These values should NOT be changed. */
  181596. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  181597. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  181598. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  181599. /* These are for the oFFs chunk. These values should NOT be changed. */
  181600. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  181601. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  181602. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  181603. /* These are for the pCAL chunk. These values should NOT be changed. */
  181604. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  181605. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  181606. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  181607. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  181608. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  181609. /* These are for the sCAL chunk. These values should NOT be changed. */
  181610. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  181611. #define PNG_SCALE_METER 1 /* meters per pixel */
  181612. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  181613. #define PNG_SCALE_LAST 3 /* Not a valid value */
  181614. /* These are for the pHYs chunk. These values should NOT be changed. */
  181615. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  181616. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  181617. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  181618. /* These are for the sRGB chunk. These values should NOT be changed. */
  181619. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  181620. #define PNG_sRGB_INTENT_RELATIVE 1
  181621. #define PNG_sRGB_INTENT_SATURATION 2
  181622. #define PNG_sRGB_INTENT_ABSOLUTE 3
  181623. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  181624. /* This is for text chunks */
  181625. #define PNG_KEYWORD_MAX_LENGTH 79
  181626. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  181627. #define PNG_MAX_PALETTE_LENGTH 256
  181628. /* These determine if an ancillary chunk's data has been successfully read
  181629. * from the PNG header, or if the application has filled in the corresponding
  181630. * data in the info_struct to be written into the output file. The values
  181631. * of the PNG_INFO_<chunk> defines should NOT be changed.
  181632. */
  181633. #define PNG_INFO_gAMA 0x0001
  181634. #define PNG_INFO_sBIT 0x0002
  181635. #define PNG_INFO_cHRM 0x0004
  181636. #define PNG_INFO_PLTE 0x0008
  181637. #define PNG_INFO_tRNS 0x0010
  181638. #define PNG_INFO_bKGD 0x0020
  181639. #define PNG_INFO_hIST 0x0040
  181640. #define PNG_INFO_pHYs 0x0080
  181641. #define PNG_INFO_oFFs 0x0100
  181642. #define PNG_INFO_tIME 0x0200
  181643. #define PNG_INFO_pCAL 0x0400
  181644. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  181645. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  181646. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  181647. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  181648. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  181649. /* This is used for the transformation routines, as some of them
  181650. * change these values for the row. It also should enable using
  181651. * the routines for other purposes.
  181652. */
  181653. typedef struct png_row_info_struct
  181654. {
  181655. png_uint_32 width; /* width of row */
  181656. png_uint_32 rowbytes; /* number of bytes in row */
  181657. png_byte color_type; /* color type of row */
  181658. png_byte bit_depth; /* bit depth of row */
  181659. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  181660. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  181661. } png_row_info;
  181662. typedef png_row_info FAR * png_row_infop;
  181663. typedef png_row_info FAR * FAR * png_row_infopp;
  181664. /* These are the function types for the I/O functions and for the functions
  181665. * that allow the user to override the default I/O functions with his or her
  181666. * own. The png_error_ptr type should match that of user-supplied warning
  181667. * and error functions, while the png_rw_ptr type should match that of the
  181668. * user read/write data functions.
  181669. */
  181670. typedef struct png_struct_def png_struct;
  181671. typedef png_struct FAR * png_structp;
  181672. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  181673. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  181674. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  181675. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  181676. int));
  181677. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  181678. int));
  181679. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  181680. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  181681. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  181682. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  181683. png_uint_32, int));
  181684. #endif
  181685. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  181686. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  181687. defined(PNG_LEGACY_SUPPORTED)
  181688. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  181689. png_row_infop, png_bytep));
  181690. #endif
  181691. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  181692. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  181693. #endif
  181694. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  181695. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  181696. #endif
  181697. /* Transform masks for the high-level interface */
  181698. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  181699. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  181700. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  181701. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  181702. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  181703. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  181704. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  181705. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  181706. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  181707. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  181708. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  181709. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  181710. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  181711. /* Flags for MNG supported features */
  181712. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  181713. #define PNG_FLAG_MNG_FILTER_64 0x04
  181714. #define PNG_ALL_MNG_FEATURES 0x05
  181715. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  181716. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  181717. /* The structure that holds the information to read and write PNG files.
  181718. * The only people who need to care about what is inside of this are the
  181719. * people who will be modifying the library for their own special needs.
  181720. * It should NOT be accessed directly by an application, except to store
  181721. * the jmp_buf.
  181722. */
  181723. struct png_struct_def
  181724. {
  181725. #ifdef PNG_SETJMP_SUPPORTED
  181726. jmp_buf jmpbuf; /* used in png_error */
  181727. #endif
  181728. png_error_ptr error_fn; /* function for printing errors and aborting */
  181729. png_error_ptr warning_fn; /* function for printing warnings */
  181730. png_voidp error_ptr; /* user supplied struct for error functions */
  181731. png_rw_ptr write_data_fn; /* function for writing output data */
  181732. png_rw_ptr read_data_fn; /* function for reading input data */
  181733. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  181734. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  181735. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  181736. #endif
  181737. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  181738. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  181739. #endif
  181740. /* These were added in libpng-1.0.2 */
  181741. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  181742. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  181743. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  181744. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  181745. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  181746. png_byte user_transform_channels; /* channels in user transformed pixels */
  181747. #endif
  181748. #endif
  181749. png_uint_32 mode; /* tells us where we are in the PNG file */
  181750. png_uint_32 flags; /* flags indicating various things to libpng */
  181751. png_uint_32 transformations; /* which transformations to perform */
  181752. z_stream zstream; /* pointer to decompression structure (below) */
  181753. png_bytep zbuf; /* buffer for zlib */
  181754. png_size_t zbuf_size; /* size of zbuf */
  181755. int zlib_level; /* holds zlib compression level */
  181756. int zlib_method; /* holds zlib compression method */
  181757. int zlib_window_bits; /* holds zlib compression window bits */
  181758. int zlib_mem_level; /* holds zlib compression memory level */
  181759. int zlib_strategy; /* holds zlib compression strategy */
  181760. png_uint_32 width; /* width of image in pixels */
  181761. png_uint_32 height; /* height of image in pixels */
  181762. png_uint_32 num_rows; /* number of rows in current pass */
  181763. png_uint_32 usr_width; /* width of row at start of write */
  181764. png_uint_32 rowbytes; /* size of row in bytes */
  181765. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  181766. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  181767. png_uint_32 row_number; /* current row in interlace pass */
  181768. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  181769. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  181770. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  181771. png_bytep up_row; /* buffer to save "up" row when filtering */
  181772. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  181773. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  181774. png_row_info row_info; /* used for transformation routines */
  181775. png_uint_32 idat_size; /* current IDAT size for read */
  181776. png_uint_32 crc; /* current chunk CRC value */
  181777. png_colorp palette; /* palette from the input file */
  181778. png_uint_16 num_palette; /* number of color entries in palette */
  181779. png_uint_16 num_trans; /* number of transparency values */
  181780. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  181781. png_byte compression; /* file compression type (always 0) */
  181782. png_byte filter; /* file filter type (always 0) */
  181783. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  181784. png_byte pass; /* current interlace pass (0 - 6) */
  181785. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  181786. png_byte color_type; /* color type of file */
  181787. png_byte bit_depth; /* bit depth of file */
  181788. png_byte usr_bit_depth; /* bit depth of users row */
  181789. png_byte pixel_depth; /* number of bits per pixel */
  181790. png_byte channels; /* number of channels in file */
  181791. png_byte usr_channels; /* channels at start of write */
  181792. png_byte sig_bytes; /* magic bytes read/written from start of file */
  181793. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  181794. #ifdef PNG_LEGACY_SUPPORTED
  181795. png_byte filler; /* filler byte for pixel expansion */
  181796. #else
  181797. png_uint_16 filler; /* filler bytes for pixel expansion */
  181798. #endif
  181799. #endif
  181800. #if defined(PNG_bKGD_SUPPORTED)
  181801. png_byte background_gamma_type;
  181802. # ifdef PNG_FLOATING_POINT_SUPPORTED
  181803. float background_gamma;
  181804. # endif
  181805. png_color_16 background; /* background color in screen gamma space */
  181806. #if defined(PNG_READ_GAMMA_SUPPORTED)
  181807. png_color_16 background_1; /* background normalized to gamma 1.0 */
  181808. #endif
  181809. #endif /* PNG_bKGD_SUPPORTED */
  181810. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  181811. png_flush_ptr output_flush_fn;/* Function for flushing output */
  181812. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  181813. png_uint_32 flush_rows; /* number of rows written since last flush */
  181814. #endif
  181815. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  181816. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  181817. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181818. float gamma; /* file gamma value */
  181819. float screen_gamma; /* screen gamma value (display_exponent) */
  181820. #endif
  181821. #endif
  181822. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  181823. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  181824. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  181825. png_bytep gamma_to_1; /* converts from file to 1.0 */
  181826. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  181827. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  181828. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  181829. #endif
  181830. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  181831. png_color_8 sig_bit; /* significant bits in each available channel */
  181832. #endif
  181833. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  181834. png_color_8 shift; /* shift for significant bit tranformation */
  181835. #endif
  181836. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  181837. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  181838. png_bytep trans; /* transparency values for paletted files */
  181839. png_color_16 trans_values; /* transparency values for non-paletted files */
  181840. #endif
  181841. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  181842. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  181843. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  181844. png_progressive_info_ptr info_fn; /* called after header data fully read */
  181845. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  181846. png_progressive_end_ptr end_fn; /* called after image is complete */
  181847. png_bytep save_buffer_ptr; /* current location in save_buffer */
  181848. png_bytep save_buffer; /* buffer for previously read data */
  181849. png_bytep current_buffer_ptr; /* current location in current_buffer */
  181850. png_bytep current_buffer; /* buffer for recently used data */
  181851. png_uint_32 push_length; /* size of current input chunk */
  181852. png_uint_32 skip_length; /* bytes to skip in input data */
  181853. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  181854. png_size_t save_buffer_max; /* total size of save_buffer */
  181855. png_size_t buffer_size; /* total amount of available input data */
  181856. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  181857. int process_mode; /* what push library is currently doing */
  181858. int cur_palette; /* current push library palette index */
  181859. # if defined(PNG_TEXT_SUPPORTED)
  181860. png_size_t current_text_size; /* current size of text input data */
  181861. png_size_t current_text_left; /* how much text left to read in input */
  181862. png_charp current_text; /* current text chunk buffer */
  181863. png_charp current_text_ptr; /* current location in current_text */
  181864. # endif /* PNG_TEXT_SUPPORTED */
  181865. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  181866. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  181867. /* for the Borland special 64K segment handler */
  181868. png_bytepp offset_table_ptr;
  181869. png_bytep offset_table;
  181870. png_uint_16 offset_table_number;
  181871. png_uint_16 offset_table_count;
  181872. png_uint_16 offset_table_count_free;
  181873. #endif
  181874. #if defined(PNG_READ_DITHER_SUPPORTED)
  181875. png_bytep palette_lookup; /* lookup table for dithering */
  181876. png_bytep dither_index; /* index translation for palette files */
  181877. #endif
  181878. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  181879. png_uint_16p hist; /* histogram */
  181880. #endif
  181881. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  181882. png_byte heuristic_method; /* heuristic for row filter selection */
  181883. png_byte num_prev_filters; /* number of weights for previous rows */
  181884. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  181885. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  181886. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  181887. png_uint_16p filter_costs; /* relative filter calculation cost */
  181888. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  181889. #endif
  181890. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  181891. png_charp time_buffer; /* String to hold RFC 1123 time text */
  181892. #endif
  181893. /* New members added in libpng-1.0.6 */
  181894. #ifdef PNG_FREE_ME_SUPPORTED
  181895. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  181896. #endif
  181897. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  181898. png_voidp user_chunk_ptr;
  181899. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  181900. #endif
  181901. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  181902. int num_chunk_list;
  181903. png_bytep chunk_list;
  181904. #endif
  181905. /* New members added in libpng-1.0.3 */
  181906. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  181907. png_byte rgb_to_gray_status;
  181908. /* These were changed from png_byte in libpng-1.0.6 */
  181909. png_uint_16 rgb_to_gray_red_coeff;
  181910. png_uint_16 rgb_to_gray_green_coeff;
  181911. png_uint_16 rgb_to_gray_blue_coeff;
  181912. #endif
  181913. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  181914. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  181915. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  181916. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  181917. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  181918. #ifdef PNG_1_0_X
  181919. png_byte mng_features_permitted;
  181920. #else
  181921. png_uint_32 mng_features_permitted;
  181922. #endif /* PNG_1_0_X */
  181923. #endif
  181924. /* New member added in libpng-1.0.7 */
  181925. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  181926. png_fixed_point int_gamma;
  181927. #endif
  181928. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  181929. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  181930. png_byte filter_type;
  181931. #endif
  181932. #if defined(PNG_1_0_X)
  181933. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  181934. png_uint_32 row_buf_size;
  181935. #endif
  181936. /* New members added in libpng-1.2.0 */
  181937. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  181938. # if !defined(PNG_1_0_X)
  181939. # if defined(PNG_MMX_CODE_SUPPORTED)
  181940. png_byte mmx_bitdepth_threshold;
  181941. png_uint_32 mmx_rowbytes_threshold;
  181942. # endif
  181943. png_uint_32 asm_flags;
  181944. # endif
  181945. #endif
  181946. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  181947. #ifdef PNG_USER_MEM_SUPPORTED
  181948. png_voidp mem_ptr; /* user supplied struct for mem functions */
  181949. png_malloc_ptr malloc_fn; /* function for allocating memory */
  181950. png_free_ptr free_fn; /* function for freeing memory */
  181951. #endif
  181952. /* New member added in libpng-1.0.13 and 1.2.0 */
  181953. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  181954. #if defined(PNG_READ_DITHER_SUPPORTED)
  181955. /* The following three members were added at version 1.0.14 and 1.2.4 */
  181956. png_bytep dither_sort; /* working sort array */
  181957. png_bytep index_to_palette; /* where the original index currently is */
  181958. /* in the palette */
  181959. png_bytep palette_to_index; /* which original index points to this */
  181960. /* palette color */
  181961. #endif
  181962. /* New members added in libpng-1.0.16 and 1.2.6 */
  181963. png_byte compression_type;
  181964. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  181965. png_uint_32 user_width_max;
  181966. png_uint_32 user_height_max;
  181967. #endif
  181968. /* New member added in libpng-1.0.25 and 1.2.17 */
  181969. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  181970. /* storage for unknown chunk that the library doesn't recognize. */
  181971. png_unknown_chunk unknown_chunk;
  181972. #endif
  181973. };
  181974. /* This triggers a compiler error in png.c, if png.c and png.h
  181975. * do not agree upon the version number.
  181976. */
  181977. typedef png_structp version_1_2_21;
  181978. typedef png_struct FAR * FAR * png_structpp;
  181979. /* Here are the function definitions most commonly used. This is not
  181980. * the place to find out how to use libpng. See libpng.txt for the
  181981. * full explanation, see example.c for the summary. This just provides
  181982. * a simple one line description of the use of each function.
  181983. */
  181984. /* Returns the version number of the library */
  181985. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  181986. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  181987. * Handling more than 8 bytes from the beginning of the file is an error.
  181988. */
  181989. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  181990. int num_bytes));
  181991. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  181992. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  181993. * signature, and non-zero otherwise. Having num_to_check == 0 or
  181994. * start > 7 will always fail (ie return non-zero).
  181995. */
  181996. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  181997. png_size_t num_to_check));
  181998. /* Simple signature checking function. This is the same as calling
  181999. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  182000. */
  182001. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  182002. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  182003. extern PNG_EXPORT(png_structp,png_create_read_struct)
  182004. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182005. png_error_ptr error_fn, png_error_ptr warn_fn));
  182006. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  182007. extern PNG_EXPORT(png_structp,png_create_write_struct)
  182008. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182009. png_error_ptr error_fn, png_error_ptr warn_fn));
  182010. #ifdef PNG_WRITE_SUPPORTED
  182011. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  182012. PNGARG((png_structp png_ptr));
  182013. #endif
  182014. #ifdef PNG_WRITE_SUPPORTED
  182015. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  182016. PNGARG((png_structp png_ptr, png_uint_32 size));
  182017. #endif
  182018. /* Reset the compression stream */
  182019. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  182020. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  182021. #ifdef PNG_USER_MEM_SUPPORTED
  182022. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  182023. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182024. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182025. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182026. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  182027. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182028. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182029. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182030. #endif
  182031. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  182032. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  182033. png_bytep chunk_name, png_bytep data, png_size_t length));
  182034. /* Write the start of a PNG chunk - length and chunk name. */
  182035. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  182036. png_bytep chunk_name, png_uint_32 length));
  182037. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  182038. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  182039. png_bytep data, png_size_t length));
  182040. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  182041. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  182042. /* Allocate and initialize the info structure */
  182043. extern PNG_EXPORT(png_infop,png_create_info_struct)
  182044. PNGARG((png_structp png_ptr));
  182045. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182046. /* Initialize the info structure (old interface - DEPRECATED) */
  182047. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  182048. #undef png_info_init
  182049. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  182050. png_sizeof(png_info));
  182051. #endif
  182052. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  182053. png_size_t png_info_struct_size));
  182054. /* Writes all the PNG information before the image. */
  182055. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  182056. png_infop info_ptr));
  182057. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  182058. png_infop info_ptr));
  182059. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182060. /* read the information before the actual image data. */
  182061. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  182062. png_infop info_ptr));
  182063. #endif
  182064. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182065. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  182066. PNGARG((png_structp png_ptr, png_timep ptime));
  182067. #endif
  182068. #if !defined(_WIN32_WCE)
  182069. /* "time.h" functions are not supported on WindowsCE */
  182070. #if defined(PNG_WRITE_tIME_SUPPORTED)
  182071. /* convert from a struct tm to png_time */
  182072. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  182073. struct tm FAR * ttime));
  182074. /* convert from time_t to png_time. Uses gmtime() */
  182075. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  182076. time_t ttime));
  182077. #endif /* PNG_WRITE_tIME_SUPPORTED */
  182078. #endif /* _WIN32_WCE */
  182079. #if defined(PNG_READ_EXPAND_SUPPORTED)
  182080. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  182081. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  182082. #if !defined(PNG_1_0_X)
  182083. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  182084. png_ptr));
  182085. #endif
  182086. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  182087. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  182088. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182089. /* Deprecated */
  182090. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  182091. #endif
  182092. #endif
  182093. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  182094. /* Use blue, green, red order for pixels. */
  182095. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  182096. #endif
  182097. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  182098. /* Expand the grayscale to 24-bit RGB if necessary. */
  182099. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  182100. #endif
  182101. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182102. /* Reduce RGB to grayscale. */
  182103. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182104. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  182105. int error_action, double red, double green ));
  182106. #endif
  182107. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  182108. int error_action, png_fixed_point red, png_fixed_point green ));
  182109. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  182110. png_ptr));
  182111. #endif
  182112. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  182113. png_colorp palette));
  182114. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  182115. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  182116. #endif
  182117. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  182118. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  182119. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  182120. #endif
  182121. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  182122. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  182123. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  182124. #endif
  182125. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  182126. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  182127. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  182128. png_uint_32 filler, int flags));
  182129. /* The values of the PNG_FILLER_ defines should NOT be changed */
  182130. #define PNG_FILLER_BEFORE 0
  182131. #define PNG_FILLER_AFTER 1
  182132. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  182133. #if !defined(PNG_1_0_X)
  182134. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  182135. png_uint_32 filler, int flags));
  182136. #endif
  182137. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  182138. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  182139. /* Swap bytes in 16-bit depth files. */
  182140. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  182141. #endif
  182142. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  182143. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  182144. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  182145. #endif
  182146. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  182147. /* Swap packing order of pixels in bytes. */
  182148. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  182149. #endif
  182150. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  182151. /* Converts files to legal bit depths. */
  182152. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  182153. png_color_8p true_bits));
  182154. #endif
  182155. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  182156. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  182157. /* Have the code handle the interlacing. Returns the number of passes. */
  182158. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  182159. #endif
  182160. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  182161. /* Invert monochrome files */
  182162. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  182163. #endif
  182164. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  182165. /* Handle alpha and tRNS by replacing with a background color. */
  182166. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182167. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  182168. png_color_16p background_color, int background_gamma_code,
  182169. int need_expand, double background_gamma));
  182170. #endif
  182171. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  182172. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  182173. #define PNG_BACKGROUND_GAMMA_FILE 2
  182174. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  182175. #endif
  182176. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  182177. /* strip the second byte of information from a 16-bit depth file. */
  182178. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  182179. #endif
  182180. #if defined(PNG_READ_DITHER_SUPPORTED)
  182181. /* Turn on dithering, and reduce the palette to the number of colors available. */
  182182. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  182183. png_colorp palette, int num_palette, int maximum_colors,
  182184. png_uint_16p histogram, int full_dither));
  182185. #endif
  182186. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182187. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  182188. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182189. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  182190. double screen_gamma, double default_file_gamma));
  182191. #endif
  182192. #endif
  182193. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182194. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  182195. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  182196. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  182197. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  182198. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  182199. int empty_plte_permitted));
  182200. #endif
  182201. #endif
  182202. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  182203. /* Set how many lines between output flushes - 0 for no flushing */
  182204. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  182205. /* Flush the current PNG output buffer */
  182206. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  182207. #endif
  182208. /* optional update palette with requested transformations */
  182209. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  182210. /* optional call to update the users info structure */
  182211. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  182212. png_infop info_ptr));
  182213. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182214. /* read one or more rows of image data. */
  182215. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  182216. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  182217. #endif
  182218. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182219. /* read a row of data. */
  182220. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  182221. png_bytep row,
  182222. png_bytep display_row));
  182223. #endif
  182224. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182225. /* read the whole image into memory at once. */
  182226. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  182227. png_bytepp image));
  182228. #endif
  182229. /* write a row of image data */
  182230. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  182231. png_bytep row));
  182232. /* write a few rows of image data */
  182233. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  182234. png_bytepp row, png_uint_32 num_rows));
  182235. /* write the image data */
  182236. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  182237. png_bytepp image));
  182238. /* writes the end of the PNG file. */
  182239. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  182240. png_infop info_ptr));
  182241. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182242. /* read the end of the PNG file. */
  182243. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  182244. png_infop info_ptr));
  182245. #endif
  182246. /* free any memory associated with the png_info_struct */
  182247. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  182248. png_infopp info_ptr_ptr));
  182249. /* free any memory associated with the png_struct and the png_info_structs */
  182250. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  182251. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  182252. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  182253. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  182254. png_infop end_info_ptr));
  182255. /* free any memory associated with the png_struct and the png_info_structs */
  182256. extern PNG_EXPORT(void,png_destroy_write_struct)
  182257. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  182258. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  182259. extern void png_write_destroy PNGARG((png_structp png_ptr));
  182260. /* set the libpng method of handling chunk CRC errors */
  182261. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  182262. int crit_action, int ancil_action));
  182263. /* Values for png_set_crc_action() to say how to handle CRC errors in
  182264. * ancillary and critical chunks, and whether to use the data contained
  182265. * therein. Note that it is impossible to "discard" data in a critical
  182266. * chunk. For versions prior to 0.90, the action was always error/quit,
  182267. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  182268. * chunks is warn/discard. These values should NOT be changed.
  182269. *
  182270. * value action:critical action:ancillary
  182271. */
  182272. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  182273. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  182274. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  182275. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  182276. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  182277. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  182278. /* These functions give the user control over the scan-line filtering in
  182279. * libpng and the compression methods used by zlib. These functions are
  182280. * mainly useful for testing, as the defaults should work with most users.
  182281. * Those users who are tight on memory or want faster performance at the
  182282. * expense of compression can modify them. See the compression library
  182283. * header file (zlib.h) for an explination of the compression functions.
  182284. */
  182285. /* set the filtering method(s) used by libpng. Currently, the only valid
  182286. * value for "method" is 0.
  182287. */
  182288. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  182289. int filters));
  182290. /* Flags for png_set_filter() to say which filters to use. The flags
  182291. * are chosen so that they don't conflict with real filter types
  182292. * below, in case they are supplied instead of the #defined constants.
  182293. * These values should NOT be changed.
  182294. */
  182295. #define PNG_NO_FILTERS 0x00
  182296. #define PNG_FILTER_NONE 0x08
  182297. #define PNG_FILTER_SUB 0x10
  182298. #define PNG_FILTER_UP 0x20
  182299. #define PNG_FILTER_AVG 0x40
  182300. #define PNG_FILTER_PAETH 0x80
  182301. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  182302. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  182303. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  182304. * These defines should NOT be changed.
  182305. */
  182306. #define PNG_FILTER_VALUE_NONE 0
  182307. #define PNG_FILTER_VALUE_SUB 1
  182308. #define PNG_FILTER_VALUE_UP 2
  182309. #define PNG_FILTER_VALUE_AVG 3
  182310. #define PNG_FILTER_VALUE_PAETH 4
  182311. #define PNG_FILTER_VALUE_LAST 5
  182312. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  182313. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  182314. * defines, either the default (minimum-sum-of-absolute-differences), or
  182315. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  182316. *
  182317. * Weights are factors >= 1.0, indicating how important it is to keep the
  182318. * filter type consistent between rows. Larger numbers mean the current
  182319. * filter is that many times as likely to be the same as the "num_weights"
  182320. * previous filters. This is cumulative for each previous row with a weight.
  182321. * There needs to be "num_weights" values in "filter_weights", or it can be
  182322. * NULL if the weights aren't being specified. Weights have no influence on
  182323. * the selection of the first row filter. Well chosen weights can (in theory)
  182324. * improve the compression for a given image.
  182325. *
  182326. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  182327. * filter type. Higher costs indicate more decoding expense, and are
  182328. * therefore less likely to be selected over a filter with lower computational
  182329. * costs. There needs to be a value in "filter_costs" for each valid filter
  182330. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  182331. * setting the costs. Costs try to improve the speed of decompression without
  182332. * unduly increasing the compressed image size.
  182333. *
  182334. * A negative weight or cost indicates the default value is to be used, and
  182335. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  182336. * The default values for both weights and costs are currently 1.0, but may
  182337. * change if good general weighting/cost heuristics can be found. If both
  182338. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  182339. * to the UNWEIGHTED method, but with added encoding time/computation.
  182340. */
  182341. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182342. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  182343. int heuristic_method, int num_weights, png_doublep filter_weights,
  182344. png_doublep filter_costs));
  182345. #endif
  182346. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  182347. /* Heuristic used for row filter selection. These defines should NOT be
  182348. * changed.
  182349. */
  182350. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  182351. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  182352. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  182353. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  182354. /* Set the library compression level. Currently, valid values range from
  182355. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  182356. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  182357. * shown that zlib compression levels 3-6 usually perform as well as level 9
  182358. * for PNG images, and do considerably fewer caclulations. In the future,
  182359. * these values may not correspond directly to the zlib compression levels.
  182360. */
  182361. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  182362. int level));
  182363. extern PNG_EXPORT(void,png_set_compression_mem_level)
  182364. PNGARG((png_structp png_ptr, int mem_level));
  182365. extern PNG_EXPORT(void,png_set_compression_strategy)
  182366. PNGARG((png_structp png_ptr, int strategy));
  182367. extern PNG_EXPORT(void,png_set_compression_window_bits)
  182368. PNGARG((png_structp png_ptr, int window_bits));
  182369. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  182370. int method));
  182371. /* These next functions are called for input/output, memory, and error
  182372. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  182373. * and call standard C I/O routines such as fread(), fwrite(), and
  182374. * fprintf(). These functions can be made to use other I/O routines
  182375. * at run time for those applications that need to handle I/O in a
  182376. * different manner by calling png_set_???_fn(). See libpng.txt for
  182377. * more information.
  182378. */
  182379. #if !defined(PNG_NO_STDIO)
  182380. /* Initialize the input/output for the PNG file to the default functions. */
  182381. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  182382. #endif
  182383. /* Replace the (error and abort), and warning functions with user
  182384. * supplied functions. If no messages are to be printed you must still
  182385. * write and use replacement functions. The replacement error_fn should
  182386. * still do a longjmp to the last setjmp location if you are using this
  182387. * method of error handling. If error_fn or warning_fn is NULL, the
  182388. * default function will be used.
  182389. */
  182390. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  182391. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  182392. /* Return the user pointer associated with the error functions */
  182393. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  182394. /* Replace the default data output functions with a user supplied one(s).
  182395. * If buffered output is not used, then output_flush_fn can be set to NULL.
  182396. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  182397. * output_flush_fn will be ignored (and thus can be NULL).
  182398. */
  182399. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  182400. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  182401. /* Replace the default data input function with a user supplied one. */
  182402. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  182403. png_voidp io_ptr, png_rw_ptr read_data_fn));
  182404. /* Return the user pointer associated with the I/O functions */
  182405. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  182406. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  182407. png_read_status_ptr read_row_fn));
  182408. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  182409. png_write_status_ptr write_row_fn));
  182410. #ifdef PNG_USER_MEM_SUPPORTED
  182411. /* Replace the default memory allocation functions with user supplied one(s). */
  182412. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  182413. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182414. /* Return the user pointer associated with the memory functions */
  182415. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  182416. #endif
  182417. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182418. defined(PNG_LEGACY_SUPPORTED)
  182419. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  182420. png_ptr, png_user_transform_ptr read_user_transform_fn));
  182421. #endif
  182422. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182423. defined(PNG_LEGACY_SUPPORTED)
  182424. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  182425. png_ptr, png_user_transform_ptr write_user_transform_fn));
  182426. #endif
  182427. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182428. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182429. defined(PNG_LEGACY_SUPPORTED)
  182430. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  182431. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  182432. int user_transform_channels));
  182433. /* Return the user pointer associated with the user transform functions */
  182434. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  182435. PNGARG((png_structp png_ptr));
  182436. #endif
  182437. #ifdef PNG_USER_CHUNKS_SUPPORTED
  182438. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  182439. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  182440. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  182441. png_ptr));
  182442. #endif
  182443. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182444. /* Sets the function callbacks for the push reader, and a pointer to a
  182445. * user-defined structure available to the callback functions.
  182446. */
  182447. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  182448. png_voidp progressive_ptr,
  182449. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  182450. png_progressive_end_ptr end_fn));
  182451. /* returns the user pointer associated with the push read functions */
  182452. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  182453. PNGARG((png_structp png_ptr));
  182454. /* function to be called when data becomes available */
  182455. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  182456. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  182457. /* function that combines rows. Not very much different than the
  182458. * png_combine_row() call. Is this even used?????
  182459. */
  182460. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  182461. png_bytep old_row, png_bytep new_row));
  182462. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  182463. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  182464. png_uint_32 size));
  182465. #if defined(PNG_1_0_X)
  182466. # define png_malloc_warn png_malloc
  182467. #else
  182468. /* Added at libpng version 1.2.4 */
  182469. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  182470. png_uint_32 size));
  182471. #endif
  182472. /* frees a pointer allocated by png_malloc() */
  182473. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  182474. #if defined(PNG_1_0_X)
  182475. /* Function to allocate memory for zlib. */
  182476. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  182477. uInt size));
  182478. /* Function to free memory for zlib */
  182479. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  182480. #endif
  182481. /* Free data that was allocated internally */
  182482. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  182483. png_infop info_ptr, png_uint_32 free_me, int num));
  182484. #ifdef PNG_FREE_ME_SUPPORTED
  182485. /* Reassign responsibility for freeing existing data, whether allocated
  182486. * by libpng or by the application */
  182487. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  182488. png_infop info_ptr, int freer, png_uint_32 mask));
  182489. #endif
  182490. /* assignments for png_data_freer */
  182491. #define PNG_DESTROY_WILL_FREE_DATA 1
  182492. #define PNG_SET_WILL_FREE_DATA 1
  182493. #define PNG_USER_WILL_FREE_DATA 2
  182494. /* Flags for png_ptr->free_me and info_ptr->free_me */
  182495. #define PNG_FREE_HIST 0x0008
  182496. #define PNG_FREE_ICCP 0x0010
  182497. #define PNG_FREE_SPLT 0x0020
  182498. #define PNG_FREE_ROWS 0x0040
  182499. #define PNG_FREE_PCAL 0x0080
  182500. #define PNG_FREE_SCAL 0x0100
  182501. #define PNG_FREE_UNKN 0x0200
  182502. #define PNG_FREE_LIST 0x0400
  182503. #define PNG_FREE_PLTE 0x1000
  182504. #define PNG_FREE_TRNS 0x2000
  182505. #define PNG_FREE_TEXT 0x4000
  182506. #define PNG_FREE_ALL 0x7fff
  182507. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  182508. #ifdef PNG_USER_MEM_SUPPORTED
  182509. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  182510. png_uint_32 size));
  182511. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  182512. png_voidp ptr));
  182513. #endif
  182514. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  182515. png_voidp s1, png_voidp s2, png_uint_32 size));
  182516. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  182517. png_voidp s1, int value, png_uint_32 size));
  182518. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  182519. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  182520. int check));
  182521. #endif /* USE_FAR_KEYWORD */
  182522. #ifndef PNG_NO_ERROR_TEXT
  182523. /* Fatal error in PNG image of libpng - can't continue */
  182524. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  182525. png_const_charp error_message));
  182526. /* The same, but the chunk name is prepended to the error string. */
  182527. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  182528. png_const_charp error_message));
  182529. #else
  182530. /* Fatal error in PNG image of libpng - can't continue */
  182531. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  182532. #endif
  182533. #ifndef PNG_NO_WARNINGS
  182534. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  182535. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  182536. png_const_charp warning_message));
  182537. #ifdef PNG_READ_SUPPORTED
  182538. /* Non-fatal error in libpng, chunk name is prepended to message. */
  182539. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  182540. png_const_charp warning_message));
  182541. #endif /* PNG_READ_SUPPORTED */
  182542. #endif /* PNG_NO_WARNINGS */
  182543. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  182544. * Similarly, the png_get_<chunk> calls are used to read values from the
  182545. * png_info_struct, either storing the parameters in the passed variables, or
  182546. * setting pointers into the png_info_struct where the data is stored. The
  182547. * png_get_<chunk> functions return a non-zero value if the data was available
  182548. * in info_ptr, or return zero and do not change any of the parameters if the
  182549. * data was not available.
  182550. *
  182551. * These functions should be used instead of directly accessing png_info
  182552. * to avoid problems with future changes in the size and internal layout of
  182553. * png_info_struct.
  182554. */
  182555. /* Returns "flag" if chunk data is valid in info_ptr. */
  182556. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  182557. png_infop info_ptr, png_uint_32 flag));
  182558. /* Returns number of bytes needed to hold a transformed row. */
  182559. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  182560. png_infop info_ptr));
  182561. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  182562. /* Returns row_pointers, which is an array of pointers to scanlines that was
  182563. returned from png_read_png(). */
  182564. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  182565. png_infop info_ptr));
  182566. /* Set row_pointers, which is an array of pointers to scanlines for use
  182567. by png_write_png(). */
  182568. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  182569. png_infop info_ptr, png_bytepp row_pointers));
  182570. #endif
  182571. /* Returns number of color channels in image. */
  182572. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  182573. png_infop info_ptr));
  182574. #ifdef PNG_EASY_ACCESS_SUPPORTED
  182575. /* Returns image width in pixels. */
  182576. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  182577. png_ptr, png_infop info_ptr));
  182578. /* Returns image height in pixels. */
  182579. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  182580. png_ptr, png_infop info_ptr));
  182581. /* Returns image bit_depth. */
  182582. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  182583. png_ptr, png_infop info_ptr));
  182584. /* Returns image color_type. */
  182585. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  182586. png_ptr, png_infop info_ptr));
  182587. /* Returns image filter_type. */
  182588. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  182589. png_ptr, png_infop info_ptr));
  182590. /* Returns image interlace_type. */
  182591. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  182592. png_ptr, png_infop info_ptr));
  182593. /* Returns image compression_type. */
  182594. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  182595. png_ptr, png_infop info_ptr));
  182596. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  182597. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  182598. png_ptr, png_infop info_ptr));
  182599. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  182600. png_ptr, png_infop info_ptr));
  182601. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  182602. png_ptr, png_infop info_ptr));
  182603. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  182604. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182605. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  182606. png_ptr, png_infop info_ptr));
  182607. #endif
  182608. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  182609. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  182610. png_ptr, png_infop info_ptr));
  182611. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  182612. png_ptr, png_infop info_ptr));
  182613. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  182614. png_ptr, png_infop info_ptr));
  182615. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  182616. png_ptr, png_infop info_ptr));
  182617. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  182618. /* Returns pointer to signature string read from PNG header */
  182619. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  182620. png_infop info_ptr));
  182621. #if defined(PNG_bKGD_SUPPORTED)
  182622. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  182623. png_infop info_ptr, png_color_16p *background));
  182624. #endif
  182625. #if defined(PNG_bKGD_SUPPORTED)
  182626. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  182627. png_infop info_ptr, png_color_16p background));
  182628. #endif
  182629. #if defined(PNG_cHRM_SUPPORTED)
  182630. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182631. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  182632. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  182633. double *red_y, double *green_x, double *green_y, double *blue_x,
  182634. double *blue_y));
  182635. #endif
  182636. #ifdef PNG_FIXED_POINT_SUPPORTED
  182637. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  182638. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  182639. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  182640. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  182641. *int_blue_x, png_fixed_point *int_blue_y));
  182642. #endif
  182643. #endif
  182644. #if defined(PNG_cHRM_SUPPORTED)
  182645. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182646. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  182647. png_infop info_ptr, double white_x, double white_y, double red_x,
  182648. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  182649. #endif
  182650. #ifdef PNG_FIXED_POINT_SUPPORTED
  182651. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  182652. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  182653. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  182654. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  182655. png_fixed_point int_blue_y));
  182656. #endif
  182657. #endif
  182658. #if defined(PNG_gAMA_SUPPORTED)
  182659. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182660. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  182661. png_infop info_ptr, double *file_gamma));
  182662. #endif
  182663. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  182664. png_infop info_ptr, png_fixed_point *int_file_gamma));
  182665. #endif
  182666. #if defined(PNG_gAMA_SUPPORTED)
  182667. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182668. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  182669. png_infop info_ptr, double file_gamma));
  182670. #endif
  182671. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  182672. png_infop info_ptr, png_fixed_point int_file_gamma));
  182673. #endif
  182674. #if defined(PNG_hIST_SUPPORTED)
  182675. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  182676. png_infop info_ptr, png_uint_16p *hist));
  182677. #endif
  182678. #if defined(PNG_hIST_SUPPORTED)
  182679. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  182680. png_infop info_ptr, png_uint_16p hist));
  182681. #endif
  182682. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  182683. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  182684. int *bit_depth, int *color_type, int *interlace_method,
  182685. int *compression_method, int *filter_method));
  182686. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  182687. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  182688. int color_type, int interlace_method, int compression_method,
  182689. int filter_method));
  182690. #if defined(PNG_oFFs_SUPPORTED)
  182691. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  182692. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  182693. int *unit_type));
  182694. #endif
  182695. #if defined(PNG_oFFs_SUPPORTED)
  182696. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  182697. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  182698. int unit_type));
  182699. #endif
  182700. #if defined(PNG_pCAL_SUPPORTED)
  182701. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  182702. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  182703. int *type, int *nparams, png_charp *units, png_charpp *params));
  182704. #endif
  182705. #if defined(PNG_pCAL_SUPPORTED)
  182706. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  182707. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  182708. int type, int nparams, png_charp units, png_charpp params));
  182709. #endif
  182710. #if defined(PNG_pHYs_SUPPORTED)
  182711. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  182712. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  182713. #endif
  182714. #if defined(PNG_pHYs_SUPPORTED)
  182715. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  182716. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  182717. #endif
  182718. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  182719. png_infop info_ptr, png_colorp *palette, int *num_palette));
  182720. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  182721. png_infop info_ptr, png_colorp palette, int num_palette));
  182722. #if defined(PNG_sBIT_SUPPORTED)
  182723. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  182724. png_infop info_ptr, png_color_8p *sig_bit));
  182725. #endif
  182726. #if defined(PNG_sBIT_SUPPORTED)
  182727. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  182728. png_infop info_ptr, png_color_8p sig_bit));
  182729. #endif
  182730. #if defined(PNG_sRGB_SUPPORTED)
  182731. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  182732. png_infop info_ptr, int *intent));
  182733. #endif
  182734. #if defined(PNG_sRGB_SUPPORTED)
  182735. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  182736. png_infop info_ptr, int intent));
  182737. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  182738. png_infop info_ptr, int intent));
  182739. #endif
  182740. #if defined(PNG_iCCP_SUPPORTED)
  182741. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  182742. png_infop info_ptr, png_charpp name, int *compression_type,
  182743. png_charpp profile, png_uint_32 *proflen));
  182744. /* Note to maintainer: profile should be png_bytepp */
  182745. #endif
  182746. #if defined(PNG_iCCP_SUPPORTED)
  182747. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  182748. png_infop info_ptr, png_charp name, int compression_type,
  182749. png_charp profile, png_uint_32 proflen));
  182750. /* Note to maintainer: profile should be png_bytep */
  182751. #endif
  182752. #if defined(PNG_sPLT_SUPPORTED)
  182753. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  182754. png_infop info_ptr, png_sPLT_tpp entries));
  182755. #endif
  182756. #if defined(PNG_sPLT_SUPPORTED)
  182757. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  182758. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  182759. #endif
  182760. #if defined(PNG_TEXT_SUPPORTED)
  182761. /* png_get_text also returns the number of text chunks in *num_text */
  182762. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  182763. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  182764. #endif
  182765. /*
  182766. * Note while png_set_text() will accept a structure whose text,
  182767. * language, and translated keywords are NULL pointers, the structure
  182768. * returned by png_get_text will always contain regular
  182769. * zero-terminated C strings. They might be empty strings but
  182770. * they will never be NULL pointers.
  182771. */
  182772. #if defined(PNG_TEXT_SUPPORTED)
  182773. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  182774. png_infop info_ptr, png_textp text_ptr, int num_text));
  182775. #endif
  182776. #if defined(PNG_tIME_SUPPORTED)
  182777. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  182778. png_infop info_ptr, png_timep *mod_time));
  182779. #endif
  182780. #if defined(PNG_tIME_SUPPORTED)
  182781. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  182782. png_infop info_ptr, png_timep mod_time));
  182783. #endif
  182784. #if defined(PNG_tRNS_SUPPORTED)
  182785. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  182786. png_infop info_ptr, png_bytep *trans, int *num_trans,
  182787. png_color_16p *trans_values));
  182788. #endif
  182789. #if defined(PNG_tRNS_SUPPORTED)
  182790. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  182791. png_infop info_ptr, png_bytep trans, int num_trans,
  182792. png_color_16p trans_values));
  182793. #endif
  182794. #if defined(PNG_tRNS_SUPPORTED)
  182795. #endif
  182796. #if defined(PNG_sCAL_SUPPORTED)
  182797. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182798. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  182799. png_infop info_ptr, int *unit, double *width, double *height));
  182800. #else
  182801. #ifdef PNG_FIXED_POINT_SUPPORTED
  182802. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  182803. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  182804. #endif
  182805. #endif
  182806. #endif /* PNG_sCAL_SUPPORTED */
  182807. #if defined(PNG_sCAL_SUPPORTED)
  182808. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182809. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  182810. png_infop info_ptr, int unit, double width, double height));
  182811. #else
  182812. #ifdef PNG_FIXED_POINT_SUPPORTED
  182813. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  182814. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  182815. #endif
  182816. #endif
  182817. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  182818. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182819. /* provide a list of chunks and how they are to be handled, if the built-in
  182820. handling or default unknown chunk handling is not desired. Any chunks not
  182821. listed will be handled in the default manner. The IHDR and IEND chunks
  182822. must not be listed.
  182823. keep = 0: follow default behaviour
  182824. = 1: do not keep
  182825. = 2: keep only if safe-to-copy
  182826. = 3: keep even if unsafe-to-copy
  182827. */
  182828. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  182829. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  182830. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  182831. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  182832. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  182833. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  182834. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  182835. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  182836. #endif
  182837. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  182838. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  182839. chunk_name));
  182840. #endif
  182841. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  182842. If you need to turn it off for a chunk that your application has freed,
  182843. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  182844. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  182845. png_infop info_ptr, int mask));
  182846. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  182847. /* The "params" pointer is currently not used and is for future expansion. */
  182848. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  182849. png_infop info_ptr,
  182850. int transforms,
  182851. png_voidp params));
  182852. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  182853. png_infop info_ptr,
  182854. int transforms,
  182855. png_voidp params));
  182856. #endif
  182857. /* Define PNG_DEBUG at compile time for debugging information. Higher
  182858. * numbers for PNG_DEBUG mean more debugging information. This has
  182859. * only been added since version 0.95 so it is not implemented throughout
  182860. * libpng yet, but more support will be added as needed.
  182861. */
  182862. #ifdef PNG_DEBUG
  182863. #if (PNG_DEBUG > 0)
  182864. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  182865. #include <crtdbg.h>
  182866. #if (PNG_DEBUG > 1)
  182867. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  182868. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  182869. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  182870. #endif
  182871. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  182872. #ifndef PNG_DEBUG_FILE
  182873. #define PNG_DEBUG_FILE stderr
  182874. #endif /* PNG_DEBUG_FILE */
  182875. #if (PNG_DEBUG > 1)
  182876. #define png_debug(l,m) \
  182877. { \
  182878. int num_tabs=l; \
  182879. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  182880. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  182881. }
  182882. #define png_debug1(l,m,p1) \
  182883. { \
  182884. int num_tabs=l; \
  182885. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  182886. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  182887. }
  182888. #define png_debug2(l,m,p1,p2) \
  182889. { \
  182890. int num_tabs=l; \
  182891. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  182892. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  182893. }
  182894. #endif /* (PNG_DEBUG > 1) */
  182895. #endif /* _MSC_VER */
  182896. #endif /* (PNG_DEBUG > 0) */
  182897. #endif /* PNG_DEBUG */
  182898. #ifndef png_debug
  182899. #define png_debug(l, m)
  182900. #endif
  182901. #ifndef png_debug1
  182902. #define png_debug1(l, m, p1)
  182903. #endif
  182904. #ifndef png_debug2
  182905. #define png_debug2(l, m, p1, p2)
  182906. #endif
  182907. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  182908. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  182909. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  182910. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  182911. #ifdef PNG_MNG_FEATURES_SUPPORTED
  182912. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  182913. png_ptr, png_uint_32 mng_features_permitted));
  182914. #endif
  182915. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  182916. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  182917. #define PNG_HANDLE_CHUNK_NEVER 1
  182918. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  182919. #define PNG_HANDLE_CHUNK_ALWAYS 3
  182920. /* Added to version 1.2.0 */
  182921. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  182922. #if defined(PNG_MMX_CODE_SUPPORTED)
  182923. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  182924. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  182925. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  182926. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  182927. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  182928. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  182929. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  182930. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  182931. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  182932. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  182933. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  182934. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  182935. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  182936. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  182937. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  182938. #define PNG_MMX_WRITE_FLAGS ( 0 )
  182939. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  182940. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  182941. | PNG_MMX_READ_FLAGS \
  182942. | PNG_MMX_WRITE_FLAGS )
  182943. #define PNG_SELECT_READ 1
  182944. #define PNG_SELECT_WRITE 2
  182945. #endif /* PNG_MMX_CODE_SUPPORTED */
  182946. #if !defined(PNG_1_0_X)
  182947. /* pngget.c */
  182948. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  182949. PNGARG((int flag_select, int *compilerID));
  182950. /* pngget.c */
  182951. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  182952. PNGARG((int flag_select));
  182953. /* pngget.c */
  182954. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  182955. PNGARG((png_structp png_ptr));
  182956. /* pngget.c */
  182957. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  182958. PNGARG((png_structp png_ptr));
  182959. /* pngget.c */
  182960. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  182961. PNGARG((png_structp png_ptr));
  182962. /* pngset.c */
  182963. extern PNG_EXPORT(void,png_set_asm_flags)
  182964. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  182965. /* pngset.c */
  182966. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  182967. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  182968. png_uint_32 mmx_rowbytes_threshold));
  182969. #endif /* PNG_1_0_X */
  182970. #if !defined(PNG_1_0_X)
  182971. /* png.c, pnggccrd.c, or pngvcrd.c */
  182972. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  182973. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  182974. /* Strip the prepended error numbers ("#nnn ") from error and warning
  182975. * messages before passing them to the error or warning handler. */
  182976. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  182977. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  182978. png_ptr, png_uint_32 strip_mode));
  182979. #endif
  182980. #endif /* PNG_1_0_X */
  182981. /* Added at libpng-1.2.6 */
  182982. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  182983. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  182984. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  182985. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  182986. png_ptr));
  182987. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  182988. png_ptr));
  182989. #endif
  182990. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  182991. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  182992. /* With these routines we avoid an integer divide, which will be slower on
  182993. * most machines. However, it does take more operations than the corresponding
  182994. * divide method, so it may be slower on a few RISC systems. There are two
  182995. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  182996. *
  182997. * Note that the rounding factors are NOT supposed to be the same! 128 and
  182998. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  182999. * standard method.
  183000. *
  183001. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  183002. */
  183003. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  183004. # define png_composite(composite, fg, alpha, bg) \
  183005. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  183006. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  183007. (png_uint_16)(alpha)) + (png_uint_16)128); \
  183008. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  183009. # define png_composite_16(composite, fg, alpha, bg) \
  183010. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  183011. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  183012. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  183013. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  183014. #else /* standard method using integer division */
  183015. # define png_composite(composite, fg, alpha, bg) \
  183016. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  183017. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  183018. (png_uint_16)127) / 255)
  183019. # define png_composite_16(composite, fg, alpha, bg) \
  183020. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  183021. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  183022. (png_uint_32)32767) / (png_uint_32)65535L)
  183023. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  183024. /* Inline macros to do direct reads of bytes from the input buffer. These
  183025. * require that you are using an architecture that uses PNG byte ordering
  183026. * (MSB first) and supports unaligned data storage. I think that PowerPC
  183027. * in big-endian mode and 680x0 are the only ones that will support this.
  183028. * The x86 line of processors definitely do not. The png_get_int_32()
  183029. * routine also assumes we are using two's complement format for negative
  183030. * values, which is almost certainly true.
  183031. */
  183032. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  183033. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  183034. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  183035. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  183036. #else
  183037. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  183038. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  183039. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  183040. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  183041. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  183042. PNGARG((png_structp png_ptr, png_bytep buf));
  183043. /* No png_get_int_16 -- may be added if there's a real need for it. */
  183044. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  183045. */
  183046. extern PNG_EXPORT(void,png_save_uint_32)
  183047. PNGARG((png_bytep buf, png_uint_32 i));
  183048. extern PNG_EXPORT(void,png_save_int_32)
  183049. PNGARG((png_bytep buf, png_int_32 i));
  183050. /* Place a 16-bit number into a buffer in PNG byte order.
  183051. * The parameter is declared unsigned int, not png_uint_16,
  183052. * just to avoid potential problems on pre-ANSI C compilers.
  183053. */
  183054. extern PNG_EXPORT(void,png_save_uint_16)
  183055. PNGARG((png_bytep buf, unsigned int i));
  183056. /* No png_save_int_16 -- may be added if there's a real need for it. */
  183057. /* ************************************************************************* */
  183058. /* These next functions are used internally in the code. They generally
  183059. * shouldn't be used unless you are writing code to add or replace some
  183060. * functionality in libpng. More information about most functions can
  183061. * be found in the files where the functions are located.
  183062. */
  183063. /* Various modes of operation, that are visible to applications because
  183064. * they are used for unknown chunk location.
  183065. */
  183066. #define PNG_HAVE_IHDR 0x01
  183067. #define PNG_HAVE_PLTE 0x02
  183068. #define PNG_HAVE_IDAT 0x04
  183069. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  183070. #define PNG_HAVE_IEND 0x10
  183071. #if defined(PNG_INTERNAL)
  183072. /* More modes of operation. Note that after an init, mode is set to
  183073. * zero automatically when the structure is created.
  183074. */
  183075. #define PNG_HAVE_gAMA 0x20
  183076. #define PNG_HAVE_cHRM 0x40
  183077. #define PNG_HAVE_sRGB 0x80
  183078. #define PNG_HAVE_CHUNK_HEADER 0x100
  183079. #define PNG_WROTE_tIME 0x200
  183080. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  183081. #define PNG_BACKGROUND_IS_GRAY 0x800
  183082. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  183083. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  183084. /* flags for the transformations the PNG library does on the image data */
  183085. #define PNG_BGR 0x0001
  183086. #define PNG_INTERLACE 0x0002
  183087. #define PNG_PACK 0x0004
  183088. #define PNG_SHIFT 0x0008
  183089. #define PNG_SWAP_BYTES 0x0010
  183090. #define PNG_INVERT_MONO 0x0020
  183091. #define PNG_DITHER 0x0040
  183092. #define PNG_BACKGROUND 0x0080
  183093. #define PNG_BACKGROUND_EXPAND 0x0100
  183094. /* 0x0200 unused */
  183095. #define PNG_16_TO_8 0x0400
  183096. #define PNG_RGBA 0x0800
  183097. #define PNG_EXPAND 0x1000
  183098. #define PNG_GAMMA 0x2000
  183099. #define PNG_GRAY_TO_RGB 0x4000
  183100. #define PNG_FILLER 0x8000L
  183101. #define PNG_PACKSWAP 0x10000L
  183102. #define PNG_SWAP_ALPHA 0x20000L
  183103. #define PNG_STRIP_ALPHA 0x40000L
  183104. #define PNG_INVERT_ALPHA 0x80000L
  183105. #define PNG_USER_TRANSFORM 0x100000L
  183106. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  183107. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  183108. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  183109. /* 0x800000L Unused */
  183110. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  183111. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  183112. /* 0x4000000L unused */
  183113. /* 0x8000000L unused */
  183114. /* 0x10000000L unused */
  183115. /* 0x20000000L unused */
  183116. /* 0x40000000L unused */
  183117. /* flags for png_create_struct */
  183118. #define PNG_STRUCT_PNG 0x0001
  183119. #define PNG_STRUCT_INFO 0x0002
  183120. /* Scaling factor for filter heuristic weighting calculations */
  183121. #define PNG_WEIGHT_SHIFT 8
  183122. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  183123. #define PNG_COST_SHIFT 3
  183124. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  183125. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  183126. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  183127. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  183128. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  183129. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  183130. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  183131. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  183132. #define PNG_FLAG_ROW_INIT 0x0040
  183133. #define PNG_FLAG_FILLER_AFTER 0x0080
  183134. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  183135. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  183136. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  183137. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  183138. #define PNG_FLAG_FREE_PLTE 0x1000
  183139. #define PNG_FLAG_FREE_TRNS 0x2000
  183140. #define PNG_FLAG_FREE_HIST 0x4000
  183141. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  183142. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  183143. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  183144. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  183145. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  183146. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  183147. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  183148. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  183149. /* 0x800000L unused */
  183150. /* 0x1000000L unused */
  183151. /* 0x2000000L unused */
  183152. /* 0x4000000L unused */
  183153. /* 0x8000000L unused */
  183154. /* 0x10000000L unused */
  183155. /* 0x20000000L unused */
  183156. /* 0x40000000L unused */
  183157. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  183158. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  183159. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  183160. PNG_FLAG_CRC_CRITICAL_IGNORE)
  183161. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  183162. PNG_FLAG_CRC_CRITICAL_MASK)
  183163. /* save typing and make code easier to understand */
  183164. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  183165. abs((int)((c1).green) - (int)((c2).green)) + \
  183166. abs((int)((c1).blue) - (int)((c2).blue)))
  183167. /* Added to libpng-1.2.6 JB */
  183168. #define PNG_ROWBYTES(pixel_bits, width) \
  183169. ((pixel_bits) >= 8 ? \
  183170. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  183171. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  183172. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  183173. ideal-delta..ideal+delta. Each argument is evaluated twice.
  183174. "ideal" and "delta" should be constants, normally simple
  183175. integers, "value" a variable. Added to libpng-1.2.6 JB */
  183176. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  183177. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  183178. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  183179. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  183180. /* place to hold the signature string for a PNG file. */
  183181. #ifdef PNG_USE_GLOBAL_ARRAYS
  183182. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  183183. #else
  183184. #endif
  183185. #endif /* PNG_NO_EXTERN */
  183186. /* Constant strings for known chunk types. If you need to add a chunk,
  183187. * define the name here, and add an invocation of the macro in png.c and
  183188. * wherever it's needed.
  183189. */
  183190. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  183191. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  183192. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  183193. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  183194. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  183195. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  183196. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  183197. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  183198. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  183199. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  183200. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  183201. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  183202. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  183203. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  183204. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  183205. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  183206. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  183207. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  183208. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  183209. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  183210. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  183211. #ifdef PNG_USE_GLOBAL_ARRAYS
  183212. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  183213. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  183214. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  183215. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  183216. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  183217. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  183218. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  183219. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  183220. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  183221. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  183222. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  183223. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  183224. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  183225. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  183226. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  183227. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  183228. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  183229. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  183230. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  183231. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  183232. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  183233. #endif /* PNG_USE_GLOBAL_ARRAYS */
  183234. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183235. /* Initialize png_ptr struct for reading, and allocate any other memory.
  183236. * (old interface - DEPRECATED - use png_create_read_struct instead).
  183237. */
  183238. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  183239. #undef png_read_init
  183240. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  183241. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  183242. #endif
  183243. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  183244. png_const_charp user_png_ver, png_size_t png_struct_size));
  183245. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183246. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  183247. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  183248. png_info_size));
  183249. #endif
  183250. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183251. /* Initialize png_ptr struct for writing, and allocate any other memory.
  183252. * (old interface - DEPRECATED - use png_create_write_struct instead).
  183253. */
  183254. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  183255. #undef png_write_init
  183256. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  183257. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  183258. #endif
  183259. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  183260. png_const_charp user_png_ver, png_size_t png_struct_size));
  183261. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  183262. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  183263. png_info_size));
  183264. /* Allocate memory for an internal libpng struct */
  183265. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  183266. /* Free memory from internal libpng struct */
  183267. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  183268. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  183269. malloc_fn, png_voidp mem_ptr));
  183270. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  183271. png_free_ptr free_fn, png_voidp mem_ptr));
  183272. /* Free any memory that info_ptr points to and reset struct. */
  183273. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  183274. png_infop info_ptr));
  183275. #ifndef PNG_1_0_X
  183276. /* Function to allocate memory for zlib. */
  183277. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  183278. /* Function to free memory for zlib */
  183279. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  183280. #ifdef PNG_SIZE_T
  183281. /* Function to convert a sizeof an item to png_sizeof item */
  183282. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  183283. #endif
  183284. /* Next four functions are used internally as callbacks. PNGAPI is required
  183285. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  183286. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  183287. png_bytep data, png_size_t length));
  183288. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183289. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  183290. png_bytep buffer, png_size_t length));
  183291. #endif
  183292. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  183293. png_bytep data, png_size_t length));
  183294. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  183295. #if !defined(PNG_NO_STDIO)
  183296. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  183297. #endif
  183298. #endif
  183299. #else /* PNG_1_0_X */
  183300. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183301. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  183302. png_bytep buffer, png_size_t length));
  183303. #endif
  183304. #endif /* PNG_1_0_X */
  183305. /* Reset the CRC variable */
  183306. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  183307. /* Write the "data" buffer to whatever output you are using. */
  183308. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  183309. png_size_t length));
  183310. /* Read data from whatever input you are using into the "data" buffer */
  183311. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  183312. png_size_t length));
  183313. /* Read bytes into buf, and update png_ptr->crc */
  183314. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  183315. png_size_t length));
  183316. /* Decompress data in a chunk that uses compression */
  183317. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  183318. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  183319. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  183320. int comp_type, png_charp chunkdata, png_size_t chunklength,
  183321. png_size_t prefix_length, png_size_t *data_length));
  183322. #endif
  183323. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  183324. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  183325. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  183326. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  183327. /* Calculate the CRC over a section of data. Note that we are only
  183328. * passing a maximum of 64K on systems that have this as a memory limit,
  183329. * since this is the maximum buffer size we can specify.
  183330. */
  183331. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  183332. png_size_t length));
  183333. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  183334. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  183335. #endif
  183336. /* simple function to write the signature */
  183337. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  183338. /* write various chunks */
  183339. /* Write the IHDR chunk, and update the png_struct with the necessary
  183340. * information.
  183341. */
  183342. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  183343. png_uint_32 height,
  183344. int bit_depth, int color_type, int compression_method, int filter_method,
  183345. int interlace_method));
  183346. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  183347. png_uint_32 num_pal));
  183348. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  183349. png_size_t length));
  183350. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  183351. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  183352. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183353. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  183354. #endif
  183355. #ifdef PNG_FIXED_POINT_SUPPORTED
  183356. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  183357. file_gamma));
  183358. #endif
  183359. #endif
  183360. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  183361. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  183362. int color_type));
  183363. #endif
  183364. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  183365. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183366. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  183367. double white_x, double white_y,
  183368. double red_x, double red_y, double green_x, double green_y,
  183369. double blue_x, double blue_y));
  183370. #endif
  183371. #ifdef PNG_FIXED_POINT_SUPPORTED
  183372. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  183373. png_fixed_point int_white_x, png_fixed_point int_white_y,
  183374. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  183375. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  183376. png_fixed_point int_blue_y));
  183377. #endif
  183378. #endif
  183379. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  183380. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  183381. int intent));
  183382. #endif
  183383. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  183384. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  183385. png_charp name, int compression_type,
  183386. png_charp profile, int proflen));
  183387. /* Note to maintainer: profile should be png_bytep */
  183388. #endif
  183389. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  183390. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  183391. png_sPLT_tp palette));
  183392. #endif
  183393. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  183394. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  183395. png_color_16p values, int number, int color_type));
  183396. #endif
  183397. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  183398. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  183399. png_color_16p values, int color_type));
  183400. #endif
  183401. #if defined(PNG_WRITE_hIST_SUPPORTED)
  183402. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  183403. int num_hist));
  183404. #endif
  183405. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  183406. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  183407. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  183408. png_charp key, png_charpp new_key));
  183409. #endif
  183410. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  183411. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  183412. png_charp text, png_size_t text_len));
  183413. #endif
  183414. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  183415. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  183416. png_charp text, png_size_t text_len, int compression));
  183417. #endif
  183418. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  183419. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  183420. int compression, png_charp key, png_charp lang, png_charp lang_key,
  183421. png_charp text));
  183422. #endif
  183423. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  183424. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  183425. png_infop info_ptr, png_textp text_ptr, int num_text));
  183426. #endif
  183427. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  183428. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  183429. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  183430. #endif
  183431. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  183432. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  183433. png_int_32 X0, png_int_32 X1, int type, int nparams,
  183434. png_charp units, png_charpp params));
  183435. #endif
  183436. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  183437. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  183438. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  183439. int unit_type));
  183440. #endif
  183441. #if defined(PNG_WRITE_tIME_SUPPORTED)
  183442. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  183443. png_timep mod_time));
  183444. #endif
  183445. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  183446. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  183447. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  183448. int unit, double width, double height));
  183449. #else
  183450. #ifdef PNG_FIXED_POINT_SUPPORTED
  183451. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  183452. int unit, png_charp width, png_charp height));
  183453. #endif
  183454. #endif
  183455. #endif
  183456. /* Called when finished processing a row of data */
  183457. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  183458. /* Internal use only. Called before first row of data */
  183459. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  183460. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183461. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  183462. #endif
  183463. /* combine a row of data, dealing with alpha, etc. if requested */
  183464. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  183465. int mask));
  183466. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  183467. /* expand an interlaced row */
  183468. /* OLD pre-1.0.9 interface:
  183469. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  183470. png_bytep row, int pass, png_uint_32 transformations));
  183471. */
  183472. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  183473. #endif
  183474. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  183475. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  183476. /* grab pixels out of a row for an interlaced pass */
  183477. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  183478. png_bytep row, int pass));
  183479. #endif
  183480. /* unfilter a row */
  183481. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  183482. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  183483. /* Choose the best filter to use and filter the row data */
  183484. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  183485. png_row_infop row_info));
  183486. /* Write out the filtered row. */
  183487. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  183488. png_bytep filtered_row));
  183489. /* finish a row while reading, dealing with interlacing passes, etc. */
  183490. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  183491. /* initialize the row buffers, etc. */
  183492. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  183493. /* optional call to update the users info structure */
  183494. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  183495. png_infop info_ptr));
  183496. /* these are the functions that do the transformations */
  183497. #if defined(PNG_READ_FILLER_SUPPORTED)
  183498. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  183499. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  183500. #endif
  183501. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  183502. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  183503. png_bytep row));
  183504. #endif
  183505. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  183506. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  183507. png_bytep row));
  183508. #endif
  183509. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  183510. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  183511. png_bytep row));
  183512. #endif
  183513. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  183514. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  183515. png_bytep row));
  183516. #endif
  183517. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  183518. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  183519. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  183520. png_bytep row, png_uint_32 flags));
  183521. #endif
  183522. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  183523. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  183524. #endif
  183525. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  183526. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  183527. #endif
  183528. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  183529. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  183530. row_info, png_bytep row));
  183531. #endif
  183532. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  183533. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  183534. png_bytep row));
  183535. #endif
  183536. #if defined(PNG_READ_PACK_SUPPORTED)
  183537. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  183538. #endif
  183539. #if defined(PNG_READ_SHIFT_SUPPORTED)
  183540. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  183541. png_color_8p sig_bits));
  183542. #endif
  183543. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  183544. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  183545. #endif
  183546. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  183547. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  183548. #endif
  183549. #if defined(PNG_READ_DITHER_SUPPORTED)
  183550. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  183551. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  183552. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  183553. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  183554. png_colorp palette, int num_palette));
  183555. # endif
  183556. #endif
  183557. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  183558. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  183559. #endif
  183560. #if defined(PNG_WRITE_PACK_SUPPORTED)
  183561. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  183562. png_bytep row, png_uint_32 bit_depth));
  183563. #endif
  183564. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  183565. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  183566. png_color_8p bit_depth));
  183567. #endif
  183568. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  183569. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183570. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  183571. png_color_16p trans_values, png_color_16p background,
  183572. png_color_16p background_1,
  183573. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  183574. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  183575. png_uint_16pp gamma_16_to_1, int gamma_shift));
  183576. #else
  183577. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  183578. png_color_16p trans_values, png_color_16p background));
  183579. #endif
  183580. #endif
  183581. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183582. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  183583. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  183584. int gamma_shift));
  183585. #endif
  183586. #if defined(PNG_READ_EXPAND_SUPPORTED)
  183587. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  183588. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  183589. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  183590. png_bytep row, png_color_16p trans_value));
  183591. #endif
  183592. /* The following decodes the appropriate chunks, and does error correction,
  183593. * then calls the appropriate callback for the chunk if it is valid.
  183594. */
  183595. /* decode the IHDR chunk */
  183596. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  183597. png_uint_32 length));
  183598. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  183599. png_uint_32 length));
  183600. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  183601. png_uint_32 length));
  183602. #if defined(PNG_READ_bKGD_SUPPORTED)
  183603. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  183604. png_uint_32 length));
  183605. #endif
  183606. #if defined(PNG_READ_cHRM_SUPPORTED)
  183607. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  183608. png_uint_32 length));
  183609. #endif
  183610. #if defined(PNG_READ_gAMA_SUPPORTED)
  183611. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  183612. png_uint_32 length));
  183613. #endif
  183614. #if defined(PNG_READ_hIST_SUPPORTED)
  183615. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  183616. png_uint_32 length));
  183617. #endif
  183618. #if defined(PNG_READ_iCCP_SUPPORTED)
  183619. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  183620. png_uint_32 length));
  183621. #endif /* PNG_READ_iCCP_SUPPORTED */
  183622. #if defined(PNG_READ_iTXt_SUPPORTED)
  183623. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  183624. png_uint_32 length));
  183625. #endif
  183626. #if defined(PNG_READ_oFFs_SUPPORTED)
  183627. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  183628. png_uint_32 length));
  183629. #endif
  183630. #if defined(PNG_READ_pCAL_SUPPORTED)
  183631. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  183632. png_uint_32 length));
  183633. #endif
  183634. #if defined(PNG_READ_pHYs_SUPPORTED)
  183635. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  183636. png_uint_32 length));
  183637. #endif
  183638. #if defined(PNG_READ_sBIT_SUPPORTED)
  183639. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  183640. png_uint_32 length));
  183641. #endif
  183642. #if defined(PNG_READ_sCAL_SUPPORTED)
  183643. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  183644. png_uint_32 length));
  183645. #endif
  183646. #if defined(PNG_READ_sPLT_SUPPORTED)
  183647. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  183648. png_uint_32 length));
  183649. #endif /* PNG_READ_sPLT_SUPPORTED */
  183650. #if defined(PNG_READ_sRGB_SUPPORTED)
  183651. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  183652. png_uint_32 length));
  183653. #endif
  183654. #if defined(PNG_READ_tEXt_SUPPORTED)
  183655. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  183656. png_uint_32 length));
  183657. #endif
  183658. #if defined(PNG_READ_tIME_SUPPORTED)
  183659. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  183660. png_uint_32 length));
  183661. #endif
  183662. #if defined(PNG_READ_tRNS_SUPPORTED)
  183663. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  183664. png_uint_32 length));
  183665. #endif
  183666. #if defined(PNG_READ_zTXt_SUPPORTED)
  183667. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  183668. png_uint_32 length));
  183669. #endif
  183670. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  183671. png_infop info_ptr, png_uint_32 length));
  183672. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  183673. png_bytep chunk_name));
  183674. /* handle the transformations for reading and writing */
  183675. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  183676. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  183677. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  183678. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183679. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  183680. png_infop info_ptr));
  183681. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  183682. png_infop info_ptr));
  183683. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  183684. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  183685. png_uint_32 length));
  183686. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  183687. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  183688. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  183689. png_bytep buffer, png_size_t buffer_length));
  183690. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  183691. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  183692. png_bytep buffer, png_size_t buffer_length));
  183693. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  183694. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  183695. png_infop info_ptr, png_uint_32 length));
  183696. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  183697. png_infop info_ptr));
  183698. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  183699. png_infop info_ptr));
  183700. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  183701. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  183702. png_infop info_ptr));
  183703. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  183704. png_infop info_ptr));
  183705. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  183706. #if defined(PNG_READ_tEXt_SUPPORTED)
  183707. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  183708. png_infop info_ptr, png_uint_32 length));
  183709. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  183710. png_infop info_ptr));
  183711. #endif
  183712. #if defined(PNG_READ_zTXt_SUPPORTED)
  183713. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  183714. png_infop info_ptr, png_uint_32 length));
  183715. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  183716. png_infop info_ptr));
  183717. #endif
  183718. #if defined(PNG_READ_iTXt_SUPPORTED)
  183719. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  183720. png_infop info_ptr, png_uint_32 length));
  183721. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  183722. png_infop info_ptr));
  183723. #endif
  183724. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  183725. #ifdef PNG_MNG_FEATURES_SUPPORTED
  183726. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  183727. png_bytep row));
  183728. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  183729. png_bytep row));
  183730. #endif
  183731. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  183732. #if defined(PNG_MMX_CODE_SUPPORTED)
  183733. /* png.c */ /* PRIVATE */
  183734. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  183735. #endif
  183736. #endif
  183737. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  183738. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  183739. png_infop info_ptr));
  183740. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  183741. png_infop info_ptr));
  183742. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  183743. png_infop info_ptr));
  183744. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  183745. png_infop info_ptr));
  183746. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  183747. png_infop info_ptr));
  183748. #if defined(PNG_pHYs_SUPPORTED)
  183749. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  183750. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  183751. #endif /* PNG_pHYs_SUPPORTED */
  183752. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  183753. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  183754. #endif /* PNG_INTERNAL */
  183755. #ifdef __cplusplus
  183756. }
  183757. #endif
  183758. #endif /* PNG_VERSION_INFO_ONLY */
  183759. /* do not put anything past this line */
  183760. #endif /* PNG_H */
  183761. /*** End of inlined file: png.h ***/
  183762. #define PNG_NO_EXTERN
  183763. /*** Start of inlined file: png.c ***/
  183764. /* png.c - location for general purpose libpng functions
  183765. *
  183766. * Last changed in libpng 1.2.21 [October 4, 2007]
  183767. * For conditions of distribution and use, see copyright notice in png.h
  183768. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  183769. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  183770. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  183771. */
  183772. #define PNG_INTERNAL
  183773. #define PNG_NO_EXTERN
  183774. /* Generate a compiler error if there is an old png.h in the search path. */
  183775. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  183776. /* Version information for C files. This had better match the version
  183777. * string defined in png.h. */
  183778. #ifdef PNG_USE_GLOBAL_ARRAYS
  183779. /* png_libpng_ver was changed to a function in version 1.0.5c */
  183780. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  183781. #ifdef PNG_READ_SUPPORTED
  183782. /* png_sig was changed to a function in version 1.0.5c */
  183783. /* Place to hold the signature string for a PNG file. */
  183784. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  183785. #endif /* PNG_READ_SUPPORTED */
  183786. /* Invoke global declarations for constant strings for known chunk types */
  183787. PNG_IHDR;
  183788. PNG_IDAT;
  183789. PNG_IEND;
  183790. PNG_PLTE;
  183791. PNG_bKGD;
  183792. PNG_cHRM;
  183793. PNG_gAMA;
  183794. PNG_hIST;
  183795. PNG_iCCP;
  183796. PNG_iTXt;
  183797. PNG_oFFs;
  183798. PNG_pCAL;
  183799. PNG_sCAL;
  183800. PNG_pHYs;
  183801. PNG_sBIT;
  183802. PNG_sPLT;
  183803. PNG_sRGB;
  183804. PNG_tEXt;
  183805. PNG_tIME;
  183806. PNG_tRNS;
  183807. PNG_zTXt;
  183808. #ifdef PNG_READ_SUPPORTED
  183809. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  183810. /* start of interlace block */
  183811. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  183812. /* offset to next interlace block */
  183813. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  183814. /* start of interlace block in the y direction */
  183815. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  183816. /* offset to next interlace block in the y direction */
  183817. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  183818. /* Height of interlace block. This is not currently used - if you need
  183819. * it, uncomment it here and in png.h
  183820. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  183821. */
  183822. /* Mask to determine which pixels are valid in a pass */
  183823. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  183824. /* Mask to determine which pixels to overwrite while displaying */
  183825. PNG_CONST int FARDATA png_pass_dsp_mask[]
  183826. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  183827. #endif /* PNG_READ_SUPPORTED */
  183828. #endif /* PNG_USE_GLOBAL_ARRAYS */
  183829. /* Tells libpng that we have already handled the first "num_bytes" bytes
  183830. * of the PNG file signature. If the PNG data is embedded into another
  183831. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  183832. * or write any of the magic bytes before it starts on the IHDR.
  183833. */
  183834. #ifdef PNG_READ_SUPPORTED
  183835. void PNGAPI
  183836. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  183837. {
  183838. if(png_ptr == NULL) return;
  183839. png_debug(1, "in png_set_sig_bytes\n");
  183840. if (num_bytes > 8)
  183841. png_error(png_ptr, "Too many bytes for PNG signature.");
  183842. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  183843. }
  183844. /* Checks whether the supplied bytes match the PNG signature. We allow
  183845. * checking less than the full 8-byte signature so that those apps that
  183846. * already read the first few bytes of a file to determine the file type
  183847. * can simply check the remaining bytes for extra assurance. Returns
  183848. * an integer less than, equal to, or greater than zero if sig is found,
  183849. * respectively, to be less than, to match, or be greater than the correct
  183850. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  183851. */
  183852. int PNGAPI
  183853. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  183854. {
  183855. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  183856. if (num_to_check > 8)
  183857. num_to_check = 8;
  183858. else if (num_to_check < 1)
  183859. return (-1);
  183860. if (start > 7)
  183861. return (-1);
  183862. if (start + num_to_check > 8)
  183863. num_to_check = 8 - start;
  183864. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  183865. }
  183866. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  183867. /* (Obsolete) function to check signature bytes. It does not allow one
  183868. * to check a partial signature. This function might be removed in the
  183869. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  183870. */
  183871. int PNGAPI
  183872. png_check_sig(png_bytep sig, int num)
  183873. {
  183874. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  183875. }
  183876. #endif
  183877. #endif /* PNG_READ_SUPPORTED */
  183878. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  183879. /* Function to allocate memory for zlib and clear it to 0. */
  183880. #ifdef PNG_1_0_X
  183881. voidpf PNGAPI
  183882. #else
  183883. voidpf /* private */
  183884. #endif
  183885. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  183886. {
  183887. png_voidp ptr;
  183888. png_structp p=(png_structp)png_ptr;
  183889. png_uint_32 save_flags=p->flags;
  183890. png_uint_32 num_bytes;
  183891. if(png_ptr == NULL) return (NULL);
  183892. if (items > PNG_UINT_32_MAX/size)
  183893. {
  183894. png_warning (p, "Potential overflow in png_zalloc()");
  183895. return (NULL);
  183896. }
  183897. num_bytes = (png_uint_32)items * size;
  183898. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  183899. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  183900. p->flags=save_flags;
  183901. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  183902. if (ptr == NULL)
  183903. return ((voidpf)ptr);
  183904. if (num_bytes > (png_uint_32)0x8000L)
  183905. {
  183906. png_memset(ptr, 0, (png_size_t)0x8000L);
  183907. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  183908. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  183909. }
  183910. else
  183911. {
  183912. png_memset(ptr, 0, (png_size_t)num_bytes);
  183913. }
  183914. #endif
  183915. return ((voidpf)ptr);
  183916. }
  183917. /* function to free memory for zlib */
  183918. #ifdef PNG_1_0_X
  183919. void PNGAPI
  183920. #else
  183921. void /* private */
  183922. #endif
  183923. png_zfree(voidpf png_ptr, voidpf ptr)
  183924. {
  183925. png_free((png_structp)png_ptr, (png_voidp)ptr);
  183926. }
  183927. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  183928. * in case CRC is > 32 bits to leave the top bits 0.
  183929. */
  183930. void /* PRIVATE */
  183931. png_reset_crc(png_structp png_ptr)
  183932. {
  183933. png_ptr->crc = crc32(0, Z_NULL, 0);
  183934. }
  183935. /* Calculate the CRC over a section of data. We can only pass as
  183936. * much data to this routine as the largest single buffer size. We
  183937. * also check that this data will actually be used before going to the
  183938. * trouble of calculating it.
  183939. */
  183940. void /* PRIVATE */
  183941. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  183942. {
  183943. int need_crc = 1;
  183944. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  183945. {
  183946. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  183947. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  183948. need_crc = 0;
  183949. }
  183950. else /* critical */
  183951. {
  183952. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  183953. need_crc = 0;
  183954. }
  183955. if (need_crc)
  183956. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  183957. }
  183958. /* Allocate the memory for an info_struct for the application. We don't
  183959. * really need the png_ptr, but it could potentially be useful in the
  183960. * future. This should be used in favour of malloc(png_sizeof(png_info))
  183961. * and png_info_init() so that applications that want to use a shared
  183962. * libpng don't have to be recompiled if png_info changes size.
  183963. */
  183964. png_infop PNGAPI
  183965. png_create_info_struct(png_structp png_ptr)
  183966. {
  183967. png_infop info_ptr;
  183968. png_debug(1, "in png_create_info_struct\n");
  183969. if(png_ptr == NULL) return (NULL);
  183970. #ifdef PNG_USER_MEM_SUPPORTED
  183971. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  183972. png_ptr->malloc_fn, png_ptr->mem_ptr);
  183973. #else
  183974. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  183975. #endif
  183976. if (info_ptr != NULL)
  183977. png_info_init_3(&info_ptr, png_sizeof(png_info));
  183978. return (info_ptr);
  183979. }
  183980. /* This function frees the memory associated with a single info struct.
  183981. * Normally, one would use either png_destroy_read_struct() or
  183982. * png_destroy_write_struct() to free an info struct, but this may be
  183983. * useful for some applications.
  183984. */
  183985. void PNGAPI
  183986. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  183987. {
  183988. png_infop info_ptr = NULL;
  183989. if(png_ptr == NULL) return;
  183990. png_debug(1, "in png_destroy_info_struct\n");
  183991. if (info_ptr_ptr != NULL)
  183992. info_ptr = *info_ptr_ptr;
  183993. if (info_ptr != NULL)
  183994. {
  183995. png_info_destroy(png_ptr, info_ptr);
  183996. #ifdef PNG_USER_MEM_SUPPORTED
  183997. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  183998. png_ptr->mem_ptr);
  183999. #else
  184000. png_destroy_struct((png_voidp)info_ptr);
  184001. #endif
  184002. *info_ptr_ptr = NULL;
  184003. }
  184004. }
  184005. /* Initialize the info structure. This is now an internal function (0.89)
  184006. * and applications using it are urged to use png_create_info_struct()
  184007. * instead.
  184008. */
  184009. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184010. #undef png_info_init
  184011. void PNGAPI
  184012. png_info_init(png_infop info_ptr)
  184013. {
  184014. /* We only come here via pre-1.0.12-compiled applications */
  184015. png_info_init_3(&info_ptr, 0);
  184016. }
  184017. #endif
  184018. void PNGAPI
  184019. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  184020. {
  184021. png_infop info_ptr = *ptr_ptr;
  184022. if(info_ptr == NULL) return;
  184023. png_debug(1, "in png_info_init_3\n");
  184024. if(png_sizeof(png_info) > png_info_struct_size)
  184025. {
  184026. png_destroy_struct(info_ptr);
  184027. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  184028. *ptr_ptr = info_ptr;
  184029. }
  184030. /* set everything to 0 */
  184031. png_memset(info_ptr, 0, png_sizeof (png_info));
  184032. }
  184033. #ifdef PNG_FREE_ME_SUPPORTED
  184034. void PNGAPI
  184035. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  184036. int freer, png_uint_32 mask)
  184037. {
  184038. png_debug(1, "in png_data_freer\n");
  184039. if (png_ptr == NULL || info_ptr == NULL)
  184040. return;
  184041. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  184042. info_ptr->free_me |= mask;
  184043. else if(freer == PNG_USER_WILL_FREE_DATA)
  184044. info_ptr->free_me &= ~mask;
  184045. else
  184046. png_warning(png_ptr,
  184047. "Unknown freer parameter in png_data_freer.");
  184048. }
  184049. #endif
  184050. void PNGAPI
  184051. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  184052. int num)
  184053. {
  184054. png_debug(1, "in png_free_data\n");
  184055. if (png_ptr == NULL || info_ptr == NULL)
  184056. return;
  184057. #if defined(PNG_TEXT_SUPPORTED)
  184058. /* free text item num or (if num == -1) all text items */
  184059. #ifdef PNG_FREE_ME_SUPPORTED
  184060. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  184061. #else
  184062. if (mask & PNG_FREE_TEXT)
  184063. #endif
  184064. {
  184065. if (num != -1)
  184066. {
  184067. if (info_ptr->text && info_ptr->text[num].key)
  184068. {
  184069. png_free(png_ptr, info_ptr->text[num].key);
  184070. info_ptr->text[num].key = NULL;
  184071. }
  184072. }
  184073. else
  184074. {
  184075. int i;
  184076. for (i = 0; i < info_ptr->num_text; i++)
  184077. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  184078. png_free(png_ptr, info_ptr->text);
  184079. info_ptr->text = NULL;
  184080. info_ptr->num_text=0;
  184081. }
  184082. }
  184083. #endif
  184084. #if defined(PNG_tRNS_SUPPORTED)
  184085. /* free any tRNS entry */
  184086. #ifdef PNG_FREE_ME_SUPPORTED
  184087. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  184088. #else
  184089. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  184090. #endif
  184091. {
  184092. png_free(png_ptr, info_ptr->trans);
  184093. info_ptr->valid &= ~PNG_INFO_tRNS;
  184094. #ifndef PNG_FREE_ME_SUPPORTED
  184095. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  184096. #endif
  184097. info_ptr->trans = NULL;
  184098. }
  184099. #endif
  184100. #if defined(PNG_sCAL_SUPPORTED)
  184101. /* free any sCAL entry */
  184102. #ifdef PNG_FREE_ME_SUPPORTED
  184103. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  184104. #else
  184105. if (mask & PNG_FREE_SCAL)
  184106. #endif
  184107. {
  184108. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  184109. png_free(png_ptr, info_ptr->scal_s_width);
  184110. png_free(png_ptr, info_ptr->scal_s_height);
  184111. info_ptr->scal_s_width = NULL;
  184112. info_ptr->scal_s_height = NULL;
  184113. #endif
  184114. info_ptr->valid &= ~PNG_INFO_sCAL;
  184115. }
  184116. #endif
  184117. #if defined(PNG_pCAL_SUPPORTED)
  184118. /* free any pCAL entry */
  184119. #ifdef PNG_FREE_ME_SUPPORTED
  184120. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  184121. #else
  184122. if (mask & PNG_FREE_PCAL)
  184123. #endif
  184124. {
  184125. png_free(png_ptr, info_ptr->pcal_purpose);
  184126. png_free(png_ptr, info_ptr->pcal_units);
  184127. info_ptr->pcal_purpose = NULL;
  184128. info_ptr->pcal_units = NULL;
  184129. if (info_ptr->pcal_params != NULL)
  184130. {
  184131. int i;
  184132. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  184133. {
  184134. png_free(png_ptr, info_ptr->pcal_params[i]);
  184135. info_ptr->pcal_params[i]=NULL;
  184136. }
  184137. png_free(png_ptr, info_ptr->pcal_params);
  184138. info_ptr->pcal_params = NULL;
  184139. }
  184140. info_ptr->valid &= ~PNG_INFO_pCAL;
  184141. }
  184142. #endif
  184143. #if defined(PNG_iCCP_SUPPORTED)
  184144. /* free any iCCP entry */
  184145. #ifdef PNG_FREE_ME_SUPPORTED
  184146. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  184147. #else
  184148. if (mask & PNG_FREE_ICCP)
  184149. #endif
  184150. {
  184151. png_free(png_ptr, info_ptr->iccp_name);
  184152. png_free(png_ptr, info_ptr->iccp_profile);
  184153. info_ptr->iccp_name = NULL;
  184154. info_ptr->iccp_profile = NULL;
  184155. info_ptr->valid &= ~PNG_INFO_iCCP;
  184156. }
  184157. #endif
  184158. #if defined(PNG_sPLT_SUPPORTED)
  184159. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  184160. #ifdef PNG_FREE_ME_SUPPORTED
  184161. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  184162. #else
  184163. if (mask & PNG_FREE_SPLT)
  184164. #endif
  184165. {
  184166. if (num != -1)
  184167. {
  184168. if(info_ptr->splt_palettes)
  184169. {
  184170. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  184171. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  184172. info_ptr->splt_palettes[num].name = NULL;
  184173. info_ptr->splt_palettes[num].entries = NULL;
  184174. }
  184175. }
  184176. else
  184177. {
  184178. if(info_ptr->splt_palettes_num)
  184179. {
  184180. int i;
  184181. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  184182. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  184183. png_free(png_ptr, info_ptr->splt_palettes);
  184184. info_ptr->splt_palettes = NULL;
  184185. info_ptr->splt_palettes_num = 0;
  184186. }
  184187. info_ptr->valid &= ~PNG_INFO_sPLT;
  184188. }
  184189. }
  184190. #endif
  184191. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  184192. if(png_ptr->unknown_chunk.data)
  184193. {
  184194. png_free(png_ptr, png_ptr->unknown_chunk.data);
  184195. png_ptr->unknown_chunk.data = NULL;
  184196. }
  184197. #ifdef PNG_FREE_ME_SUPPORTED
  184198. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  184199. #else
  184200. if (mask & PNG_FREE_UNKN)
  184201. #endif
  184202. {
  184203. if (num != -1)
  184204. {
  184205. if(info_ptr->unknown_chunks)
  184206. {
  184207. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  184208. info_ptr->unknown_chunks[num].data = NULL;
  184209. }
  184210. }
  184211. else
  184212. {
  184213. int i;
  184214. if(info_ptr->unknown_chunks_num)
  184215. {
  184216. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  184217. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  184218. png_free(png_ptr, info_ptr->unknown_chunks);
  184219. info_ptr->unknown_chunks = NULL;
  184220. info_ptr->unknown_chunks_num = 0;
  184221. }
  184222. }
  184223. }
  184224. #endif
  184225. #if defined(PNG_hIST_SUPPORTED)
  184226. /* free any hIST entry */
  184227. #ifdef PNG_FREE_ME_SUPPORTED
  184228. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  184229. #else
  184230. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  184231. #endif
  184232. {
  184233. png_free(png_ptr, info_ptr->hist);
  184234. info_ptr->hist = NULL;
  184235. info_ptr->valid &= ~PNG_INFO_hIST;
  184236. #ifndef PNG_FREE_ME_SUPPORTED
  184237. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  184238. #endif
  184239. }
  184240. #endif
  184241. /* free any PLTE entry that was internally allocated */
  184242. #ifdef PNG_FREE_ME_SUPPORTED
  184243. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  184244. #else
  184245. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  184246. #endif
  184247. {
  184248. png_zfree(png_ptr, info_ptr->palette);
  184249. info_ptr->palette = NULL;
  184250. info_ptr->valid &= ~PNG_INFO_PLTE;
  184251. #ifndef PNG_FREE_ME_SUPPORTED
  184252. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  184253. #endif
  184254. info_ptr->num_palette = 0;
  184255. }
  184256. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  184257. /* free any image bits attached to the info structure */
  184258. #ifdef PNG_FREE_ME_SUPPORTED
  184259. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  184260. #else
  184261. if (mask & PNG_FREE_ROWS)
  184262. #endif
  184263. {
  184264. if(info_ptr->row_pointers)
  184265. {
  184266. int row;
  184267. for (row = 0; row < (int)info_ptr->height; row++)
  184268. {
  184269. png_free(png_ptr, info_ptr->row_pointers[row]);
  184270. info_ptr->row_pointers[row]=NULL;
  184271. }
  184272. png_free(png_ptr, info_ptr->row_pointers);
  184273. info_ptr->row_pointers=NULL;
  184274. }
  184275. info_ptr->valid &= ~PNG_INFO_IDAT;
  184276. }
  184277. #endif
  184278. #ifdef PNG_FREE_ME_SUPPORTED
  184279. if(num == -1)
  184280. info_ptr->free_me &= ~mask;
  184281. else
  184282. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  184283. #endif
  184284. }
  184285. /* This is an internal routine to free any memory that the info struct is
  184286. * pointing to before re-using it or freeing the struct itself. Recall
  184287. * that png_free() checks for NULL pointers for us.
  184288. */
  184289. void /* PRIVATE */
  184290. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  184291. {
  184292. png_debug(1, "in png_info_destroy\n");
  184293. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  184294. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  184295. if (png_ptr->num_chunk_list)
  184296. {
  184297. png_free(png_ptr, png_ptr->chunk_list);
  184298. png_ptr->chunk_list=NULL;
  184299. png_ptr->num_chunk_list=0;
  184300. }
  184301. #endif
  184302. png_info_init_3(&info_ptr, png_sizeof(png_info));
  184303. }
  184304. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  184305. /* This function returns a pointer to the io_ptr associated with the user
  184306. * functions. The application should free any memory associated with this
  184307. * pointer before png_write_destroy() or png_read_destroy() are called.
  184308. */
  184309. png_voidp PNGAPI
  184310. png_get_io_ptr(png_structp png_ptr)
  184311. {
  184312. if(png_ptr == NULL) return (NULL);
  184313. return (png_ptr->io_ptr);
  184314. }
  184315. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184316. #if !defined(PNG_NO_STDIO)
  184317. /* Initialize the default input/output functions for the PNG file. If you
  184318. * use your own read or write routines, you can call either png_set_read_fn()
  184319. * or png_set_write_fn() instead of png_init_io(). If you have defined
  184320. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  184321. * necessarily available.
  184322. */
  184323. void PNGAPI
  184324. png_init_io(png_structp png_ptr, png_FILE_p fp)
  184325. {
  184326. png_debug(1, "in png_init_io\n");
  184327. if(png_ptr == NULL) return;
  184328. png_ptr->io_ptr = (png_voidp)fp;
  184329. }
  184330. #endif
  184331. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  184332. /* Convert the supplied time into an RFC 1123 string suitable for use in
  184333. * a "Creation Time" or other text-based time string.
  184334. */
  184335. png_charp PNGAPI
  184336. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  184337. {
  184338. static PNG_CONST char short_months[12][4] =
  184339. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  184340. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  184341. if(png_ptr == NULL) return (NULL);
  184342. if (png_ptr->time_buffer == NULL)
  184343. {
  184344. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  184345. png_sizeof(char)));
  184346. }
  184347. #if defined(_WIN32_WCE)
  184348. {
  184349. wchar_t time_buf[29];
  184350. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  184351. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  184352. ptime->year, ptime->hour % 24, ptime->minute % 60,
  184353. ptime->second % 61);
  184354. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  184355. NULL, NULL);
  184356. }
  184357. #else
  184358. #ifdef USE_FAR_KEYWORD
  184359. {
  184360. char near_time_buf[29];
  184361. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  184362. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  184363. ptime->year, ptime->hour % 24, ptime->minute % 60,
  184364. ptime->second % 61);
  184365. png_memcpy(png_ptr->time_buffer, near_time_buf,
  184366. 29*png_sizeof(char));
  184367. }
  184368. #else
  184369. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  184370. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  184371. ptime->year, ptime->hour % 24, ptime->minute % 60,
  184372. ptime->second % 61);
  184373. #endif
  184374. #endif /* _WIN32_WCE */
  184375. return ((png_charp)png_ptr->time_buffer);
  184376. }
  184377. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  184378. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  184379. png_charp PNGAPI
  184380. png_get_copyright(png_structp png_ptr)
  184381. {
  184382. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184383. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  184384. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  184385. Copyright (c) 1996-1997 Andreas Dilger\n\
  184386. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  184387. }
  184388. /* The following return the library version as a short string in the
  184389. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  184390. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  184391. * is defined in png.h.
  184392. * Note: now there is no difference between png_get_libpng_ver() and
  184393. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  184394. * it is guaranteed that png.c uses the correct version of png.h.
  184395. */
  184396. png_charp PNGAPI
  184397. png_get_libpng_ver(png_structp png_ptr)
  184398. {
  184399. /* Version of *.c files used when building libpng */
  184400. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184401. return ((png_charp) PNG_LIBPNG_VER_STRING);
  184402. }
  184403. png_charp PNGAPI
  184404. png_get_header_ver(png_structp png_ptr)
  184405. {
  184406. /* Version of *.h files used when building libpng */
  184407. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184408. return ((png_charp) PNG_LIBPNG_VER_STRING);
  184409. }
  184410. png_charp PNGAPI
  184411. png_get_header_version(png_structp png_ptr)
  184412. {
  184413. /* Returns longer string containing both version and date */
  184414. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184415. return ((png_charp) PNG_HEADER_VERSION_STRING
  184416. #ifndef PNG_READ_SUPPORTED
  184417. " (NO READ SUPPORT)"
  184418. #endif
  184419. "\n");
  184420. }
  184421. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184422. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  184423. int PNGAPI
  184424. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  184425. {
  184426. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  184427. int i;
  184428. png_bytep p;
  184429. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  184430. return 0;
  184431. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  184432. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  184433. if (!png_memcmp(chunk_name, p, 4))
  184434. return ((int)*(p+4));
  184435. return 0;
  184436. }
  184437. #endif
  184438. /* This function, added to libpng-1.0.6g, is untested. */
  184439. int PNGAPI
  184440. png_reset_zstream(png_structp png_ptr)
  184441. {
  184442. if (png_ptr == NULL) return Z_STREAM_ERROR;
  184443. return (inflateReset(&png_ptr->zstream));
  184444. }
  184445. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  184446. /* This function was added to libpng-1.0.7 */
  184447. png_uint_32 PNGAPI
  184448. png_access_version_number(void)
  184449. {
  184450. /* Version of *.c files used when building libpng */
  184451. return((png_uint_32) PNG_LIBPNG_VER);
  184452. }
  184453. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  184454. #if !defined(PNG_1_0_X)
  184455. /* this function was added to libpng 1.2.0 */
  184456. int PNGAPI
  184457. png_mmx_support(void)
  184458. {
  184459. /* obsolete, to be removed from libpng-1.4.0 */
  184460. return -1;
  184461. }
  184462. #endif /* PNG_1_0_X */
  184463. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  184464. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184465. #ifdef PNG_SIZE_T
  184466. /* Added at libpng version 1.2.6 */
  184467. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  184468. png_size_t PNGAPI
  184469. png_convert_size(size_t size)
  184470. {
  184471. if (size > (png_size_t)-1)
  184472. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  184473. return ((png_size_t)size);
  184474. }
  184475. #endif /* PNG_SIZE_T */
  184476. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  184477. /*** End of inlined file: png.c ***/
  184478. /*** Start of inlined file: pngerror.c ***/
  184479. /* pngerror.c - stub functions for i/o and memory allocation
  184480. *
  184481. * Last changed in libpng 1.2.20 October 4, 2007
  184482. * For conditions of distribution and use, see copyright notice in png.h
  184483. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184484. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184485. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184486. *
  184487. * This file provides a location for all error handling. Users who
  184488. * need special error handling are expected to write replacement functions
  184489. * and use png_set_error_fn() to use those functions. See the instructions
  184490. * at each function.
  184491. */
  184492. #define PNG_INTERNAL
  184493. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184494. static void /* PRIVATE */
  184495. png_default_error PNGARG((png_structp png_ptr,
  184496. png_const_charp error_message));
  184497. #ifndef PNG_NO_WARNINGS
  184498. static void /* PRIVATE */
  184499. png_default_warning PNGARG((png_structp png_ptr,
  184500. png_const_charp warning_message));
  184501. #endif /* PNG_NO_WARNINGS */
  184502. /* This function is called whenever there is a fatal error. This function
  184503. * should not be changed. If there is a need to handle errors differently,
  184504. * you should supply a replacement error function and use png_set_error_fn()
  184505. * to replace the error function at run-time.
  184506. */
  184507. #ifndef PNG_NO_ERROR_TEXT
  184508. void PNGAPI
  184509. png_error(png_structp png_ptr, png_const_charp error_message)
  184510. {
  184511. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184512. char msg[16];
  184513. if (png_ptr != NULL)
  184514. {
  184515. if (png_ptr->flags&
  184516. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  184517. {
  184518. if (*error_message == '#')
  184519. {
  184520. int offset;
  184521. for (offset=1; offset<15; offset++)
  184522. if (*(error_message+offset) == ' ')
  184523. break;
  184524. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  184525. {
  184526. int i;
  184527. for (i=0; i<offset-1; i++)
  184528. msg[i]=error_message[i+1];
  184529. msg[i]='\0';
  184530. error_message=msg;
  184531. }
  184532. else
  184533. error_message+=offset;
  184534. }
  184535. else
  184536. {
  184537. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  184538. {
  184539. msg[0]='0';
  184540. msg[1]='\0';
  184541. error_message=msg;
  184542. }
  184543. }
  184544. }
  184545. }
  184546. #endif
  184547. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  184548. (*(png_ptr->error_fn))(png_ptr, error_message);
  184549. /* If the custom handler doesn't exist, or if it returns,
  184550. use the default handler, which will not return. */
  184551. png_default_error(png_ptr, error_message);
  184552. }
  184553. #else
  184554. void PNGAPI
  184555. png_err(png_structp png_ptr)
  184556. {
  184557. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  184558. (*(png_ptr->error_fn))(png_ptr, '\0');
  184559. /* If the custom handler doesn't exist, or if it returns,
  184560. use the default handler, which will not return. */
  184561. png_default_error(png_ptr, '\0');
  184562. }
  184563. #endif /* PNG_NO_ERROR_TEXT */
  184564. #ifndef PNG_NO_WARNINGS
  184565. /* This function is called whenever there is a non-fatal error. This function
  184566. * should not be changed. If there is a need to handle warnings differently,
  184567. * you should supply a replacement warning function and use
  184568. * png_set_error_fn() to replace the warning function at run-time.
  184569. */
  184570. void PNGAPI
  184571. png_warning(png_structp png_ptr, png_const_charp warning_message)
  184572. {
  184573. int offset = 0;
  184574. if (png_ptr != NULL)
  184575. {
  184576. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184577. if (png_ptr->flags&
  184578. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  184579. #endif
  184580. {
  184581. if (*warning_message == '#')
  184582. {
  184583. for (offset=1; offset<15; offset++)
  184584. if (*(warning_message+offset) == ' ')
  184585. break;
  184586. }
  184587. }
  184588. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  184589. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  184590. }
  184591. else
  184592. png_default_warning(png_ptr, warning_message+offset);
  184593. }
  184594. #endif /* PNG_NO_WARNINGS */
  184595. /* These utilities are used internally to build an error message that relates
  184596. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  184597. * this is used to prefix the message. The message is limited in length
  184598. * to 63 bytes, the name characters are output as hex digits wrapped in []
  184599. * if the character is invalid.
  184600. */
  184601. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  184602. /*static PNG_CONST char png_digit[16] = {
  184603. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  184604. 'A', 'B', 'C', 'D', 'E', 'F'
  184605. };*/
  184606. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  184607. static void /* PRIVATE */
  184608. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  184609. error_message)
  184610. {
  184611. int iout = 0, iin = 0;
  184612. while (iin < 4)
  184613. {
  184614. int c = png_ptr->chunk_name[iin++];
  184615. if (isnonalpha(c))
  184616. {
  184617. buffer[iout++] = '[';
  184618. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  184619. buffer[iout++] = png_digit[c & 0x0f];
  184620. buffer[iout++] = ']';
  184621. }
  184622. else
  184623. {
  184624. buffer[iout++] = (png_byte)c;
  184625. }
  184626. }
  184627. if (error_message == NULL)
  184628. buffer[iout] = 0;
  184629. else
  184630. {
  184631. buffer[iout++] = ':';
  184632. buffer[iout++] = ' ';
  184633. png_strncpy(buffer+iout, error_message, 63);
  184634. buffer[iout+63] = 0;
  184635. }
  184636. }
  184637. #ifdef PNG_READ_SUPPORTED
  184638. void PNGAPI
  184639. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  184640. {
  184641. char msg[18+64];
  184642. if (png_ptr == NULL)
  184643. png_error(png_ptr, error_message);
  184644. else
  184645. {
  184646. png_format_buffer(png_ptr, msg, error_message);
  184647. png_error(png_ptr, msg);
  184648. }
  184649. }
  184650. #endif /* PNG_READ_SUPPORTED */
  184651. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  184652. #ifndef PNG_NO_WARNINGS
  184653. void PNGAPI
  184654. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  184655. {
  184656. char msg[18+64];
  184657. if (png_ptr == NULL)
  184658. png_warning(png_ptr, warning_message);
  184659. else
  184660. {
  184661. png_format_buffer(png_ptr, msg, warning_message);
  184662. png_warning(png_ptr, msg);
  184663. }
  184664. }
  184665. #endif /* PNG_NO_WARNINGS */
  184666. /* This is the default error handling function. Note that replacements for
  184667. * this function MUST NOT RETURN, or the program will likely crash. This
  184668. * function is used by default, or if the program supplies NULL for the
  184669. * error function pointer in png_set_error_fn().
  184670. */
  184671. static void /* PRIVATE */
  184672. png_default_error(png_structp, png_const_charp error_message)
  184673. {
  184674. #ifndef PNG_NO_CONSOLE_IO
  184675. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184676. if (*error_message == '#')
  184677. {
  184678. int offset;
  184679. char error_number[16];
  184680. for (offset=0; offset<15; offset++)
  184681. {
  184682. error_number[offset] = *(error_message+offset+1);
  184683. if (*(error_message+offset) == ' ')
  184684. break;
  184685. }
  184686. if((offset > 1) && (offset < 15))
  184687. {
  184688. error_number[offset-1]='\0';
  184689. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  184690. error_message+offset);
  184691. }
  184692. else
  184693. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  184694. }
  184695. else
  184696. #endif
  184697. fprintf(stderr, "libpng error: %s\n", error_message);
  184698. #endif
  184699. #ifdef PNG_SETJMP_SUPPORTED
  184700. if (png_ptr)
  184701. {
  184702. # ifdef USE_FAR_KEYWORD
  184703. {
  184704. jmp_buf jmpbuf;
  184705. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  184706. longjmp(jmpbuf, 1);
  184707. }
  184708. # else
  184709. longjmp(png_ptr->jmpbuf, 1);
  184710. # endif
  184711. }
  184712. #else
  184713. PNG_ABORT();
  184714. #endif
  184715. #ifdef PNG_NO_CONSOLE_IO
  184716. error_message = error_message; /* make compiler happy */
  184717. #endif
  184718. }
  184719. #ifndef PNG_NO_WARNINGS
  184720. /* This function is called when there is a warning, but the library thinks
  184721. * it can continue anyway. Replacement functions don't have to do anything
  184722. * here if you don't want them to. In the default configuration, png_ptr is
  184723. * not used, but it is passed in case it may be useful.
  184724. */
  184725. static void /* PRIVATE */
  184726. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  184727. {
  184728. #ifndef PNG_NO_CONSOLE_IO
  184729. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184730. if (*warning_message == '#')
  184731. {
  184732. int offset;
  184733. char warning_number[16];
  184734. for (offset=0; offset<15; offset++)
  184735. {
  184736. warning_number[offset]=*(warning_message+offset+1);
  184737. if (*(warning_message+offset) == ' ')
  184738. break;
  184739. }
  184740. if((offset > 1) && (offset < 15))
  184741. {
  184742. warning_number[offset-1]='\0';
  184743. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  184744. warning_message+offset);
  184745. }
  184746. else
  184747. fprintf(stderr, "libpng warning: %s\n", warning_message);
  184748. }
  184749. else
  184750. # endif
  184751. fprintf(stderr, "libpng warning: %s\n", warning_message);
  184752. #else
  184753. warning_message = warning_message; /* make compiler happy */
  184754. #endif
  184755. png_ptr = png_ptr; /* make compiler happy */
  184756. }
  184757. #endif /* PNG_NO_WARNINGS */
  184758. /* This function is called when the application wants to use another method
  184759. * of handling errors and warnings. Note that the error function MUST NOT
  184760. * return to the calling routine or serious problems will occur. The return
  184761. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  184762. */
  184763. void PNGAPI
  184764. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  184765. png_error_ptr error_fn, png_error_ptr warning_fn)
  184766. {
  184767. if (png_ptr == NULL)
  184768. return;
  184769. png_ptr->error_ptr = error_ptr;
  184770. png_ptr->error_fn = error_fn;
  184771. png_ptr->warning_fn = warning_fn;
  184772. }
  184773. /* This function returns a pointer to the error_ptr associated with the user
  184774. * functions. The application should free any memory associated with this
  184775. * pointer before png_write_destroy and png_read_destroy are called.
  184776. */
  184777. png_voidp PNGAPI
  184778. png_get_error_ptr(png_structp png_ptr)
  184779. {
  184780. if (png_ptr == NULL)
  184781. return NULL;
  184782. return ((png_voidp)png_ptr->error_ptr);
  184783. }
  184784. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184785. void PNGAPI
  184786. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  184787. {
  184788. if(png_ptr != NULL)
  184789. {
  184790. png_ptr->flags &=
  184791. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  184792. }
  184793. }
  184794. #endif
  184795. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  184796. /*** End of inlined file: pngerror.c ***/
  184797. /*** Start of inlined file: pngget.c ***/
  184798. /* pngget.c - retrieval of values from info struct
  184799. *
  184800. * Last changed in libpng 1.2.15 January 5, 2007
  184801. * For conditions of distribution and use, see copyright notice in png.h
  184802. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184803. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184804. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184805. */
  184806. #define PNG_INTERNAL
  184807. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184808. png_uint_32 PNGAPI
  184809. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  184810. {
  184811. if (png_ptr != NULL && info_ptr != NULL)
  184812. return(info_ptr->valid & flag);
  184813. else
  184814. return(0);
  184815. }
  184816. png_uint_32 PNGAPI
  184817. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  184818. {
  184819. if (png_ptr != NULL && info_ptr != NULL)
  184820. return(info_ptr->rowbytes);
  184821. else
  184822. return(0);
  184823. }
  184824. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  184825. png_bytepp PNGAPI
  184826. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  184827. {
  184828. if (png_ptr != NULL && info_ptr != NULL)
  184829. return(info_ptr->row_pointers);
  184830. else
  184831. return(0);
  184832. }
  184833. #endif
  184834. #ifdef PNG_EASY_ACCESS_SUPPORTED
  184835. /* easy access to info, added in libpng-0.99 */
  184836. png_uint_32 PNGAPI
  184837. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  184838. {
  184839. if (png_ptr != NULL && info_ptr != NULL)
  184840. {
  184841. return info_ptr->width;
  184842. }
  184843. return (0);
  184844. }
  184845. png_uint_32 PNGAPI
  184846. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  184847. {
  184848. if (png_ptr != NULL && info_ptr != NULL)
  184849. {
  184850. return info_ptr->height;
  184851. }
  184852. return (0);
  184853. }
  184854. png_byte PNGAPI
  184855. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  184856. {
  184857. if (png_ptr != NULL && info_ptr != NULL)
  184858. {
  184859. return info_ptr->bit_depth;
  184860. }
  184861. return (0);
  184862. }
  184863. png_byte PNGAPI
  184864. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  184865. {
  184866. if (png_ptr != NULL && info_ptr != NULL)
  184867. {
  184868. return info_ptr->color_type;
  184869. }
  184870. return (0);
  184871. }
  184872. png_byte PNGAPI
  184873. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  184874. {
  184875. if (png_ptr != NULL && info_ptr != NULL)
  184876. {
  184877. return info_ptr->filter_type;
  184878. }
  184879. return (0);
  184880. }
  184881. png_byte PNGAPI
  184882. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  184883. {
  184884. if (png_ptr != NULL && info_ptr != NULL)
  184885. {
  184886. return info_ptr->interlace_type;
  184887. }
  184888. return (0);
  184889. }
  184890. png_byte PNGAPI
  184891. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  184892. {
  184893. if (png_ptr != NULL && info_ptr != NULL)
  184894. {
  184895. return info_ptr->compression_type;
  184896. }
  184897. return (0);
  184898. }
  184899. png_uint_32 PNGAPI
  184900. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  184901. {
  184902. if (png_ptr != NULL && info_ptr != NULL)
  184903. #if defined(PNG_pHYs_SUPPORTED)
  184904. if (info_ptr->valid & PNG_INFO_pHYs)
  184905. {
  184906. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  184907. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  184908. return (0);
  184909. else return (info_ptr->x_pixels_per_unit);
  184910. }
  184911. #else
  184912. return (0);
  184913. #endif
  184914. return (0);
  184915. }
  184916. png_uint_32 PNGAPI
  184917. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  184918. {
  184919. if (png_ptr != NULL && info_ptr != NULL)
  184920. #if defined(PNG_pHYs_SUPPORTED)
  184921. if (info_ptr->valid & PNG_INFO_pHYs)
  184922. {
  184923. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  184924. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  184925. return (0);
  184926. else return (info_ptr->y_pixels_per_unit);
  184927. }
  184928. #else
  184929. return (0);
  184930. #endif
  184931. return (0);
  184932. }
  184933. png_uint_32 PNGAPI
  184934. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  184935. {
  184936. if (png_ptr != NULL && info_ptr != NULL)
  184937. #if defined(PNG_pHYs_SUPPORTED)
  184938. if (info_ptr->valid & PNG_INFO_pHYs)
  184939. {
  184940. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  184941. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  184942. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  184943. return (0);
  184944. else return (info_ptr->x_pixels_per_unit);
  184945. }
  184946. #else
  184947. return (0);
  184948. #endif
  184949. return (0);
  184950. }
  184951. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184952. float PNGAPI
  184953. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  184954. {
  184955. if (png_ptr != NULL && info_ptr != NULL)
  184956. #if defined(PNG_pHYs_SUPPORTED)
  184957. if (info_ptr->valid & PNG_INFO_pHYs)
  184958. {
  184959. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  184960. if (info_ptr->x_pixels_per_unit == 0)
  184961. return ((float)0.0);
  184962. else
  184963. return ((float)((float)info_ptr->y_pixels_per_unit
  184964. /(float)info_ptr->x_pixels_per_unit));
  184965. }
  184966. #else
  184967. return (0.0);
  184968. #endif
  184969. return ((float)0.0);
  184970. }
  184971. #endif
  184972. png_int_32 PNGAPI
  184973. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  184974. {
  184975. if (png_ptr != NULL && info_ptr != NULL)
  184976. #if defined(PNG_oFFs_SUPPORTED)
  184977. if (info_ptr->valid & PNG_INFO_oFFs)
  184978. {
  184979. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  184980. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  184981. return (0);
  184982. else return (info_ptr->x_offset);
  184983. }
  184984. #else
  184985. return (0);
  184986. #endif
  184987. return (0);
  184988. }
  184989. png_int_32 PNGAPI
  184990. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  184991. {
  184992. if (png_ptr != NULL && info_ptr != NULL)
  184993. #if defined(PNG_oFFs_SUPPORTED)
  184994. if (info_ptr->valid & PNG_INFO_oFFs)
  184995. {
  184996. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  184997. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  184998. return (0);
  184999. else return (info_ptr->y_offset);
  185000. }
  185001. #else
  185002. return (0);
  185003. #endif
  185004. return (0);
  185005. }
  185006. png_int_32 PNGAPI
  185007. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  185008. {
  185009. if (png_ptr != NULL && info_ptr != NULL)
  185010. #if defined(PNG_oFFs_SUPPORTED)
  185011. if (info_ptr->valid & PNG_INFO_oFFs)
  185012. {
  185013. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  185014. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  185015. return (0);
  185016. else return (info_ptr->x_offset);
  185017. }
  185018. #else
  185019. return (0);
  185020. #endif
  185021. return (0);
  185022. }
  185023. png_int_32 PNGAPI
  185024. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  185025. {
  185026. if (png_ptr != NULL && info_ptr != NULL)
  185027. #if defined(PNG_oFFs_SUPPORTED)
  185028. if (info_ptr->valid & PNG_INFO_oFFs)
  185029. {
  185030. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  185031. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  185032. return (0);
  185033. else return (info_ptr->y_offset);
  185034. }
  185035. #else
  185036. return (0);
  185037. #endif
  185038. return (0);
  185039. }
  185040. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  185041. png_uint_32 PNGAPI
  185042. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185043. {
  185044. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  185045. *.0254 +.5));
  185046. }
  185047. png_uint_32 PNGAPI
  185048. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185049. {
  185050. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  185051. *.0254 +.5));
  185052. }
  185053. png_uint_32 PNGAPI
  185054. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185055. {
  185056. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  185057. *.0254 +.5));
  185058. }
  185059. float PNGAPI
  185060. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  185061. {
  185062. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  185063. *.00003937);
  185064. }
  185065. float PNGAPI
  185066. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  185067. {
  185068. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  185069. *.00003937);
  185070. }
  185071. #if defined(PNG_pHYs_SUPPORTED)
  185072. png_uint_32 PNGAPI
  185073. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  185074. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  185075. {
  185076. png_uint_32 retval = 0;
  185077. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  185078. {
  185079. png_debug1(1, "in %s retrieval function\n", "pHYs");
  185080. if (res_x != NULL)
  185081. {
  185082. *res_x = info_ptr->x_pixels_per_unit;
  185083. retval |= PNG_INFO_pHYs;
  185084. }
  185085. if (res_y != NULL)
  185086. {
  185087. *res_y = info_ptr->y_pixels_per_unit;
  185088. retval |= PNG_INFO_pHYs;
  185089. }
  185090. if (unit_type != NULL)
  185091. {
  185092. *unit_type = (int)info_ptr->phys_unit_type;
  185093. retval |= PNG_INFO_pHYs;
  185094. if(*unit_type == 1)
  185095. {
  185096. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  185097. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  185098. }
  185099. }
  185100. }
  185101. return (retval);
  185102. }
  185103. #endif /* PNG_pHYs_SUPPORTED */
  185104. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  185105. /* png_get_channels really belongs in here, too, but it's been around longer */
  185106. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  185107. png_byte PNGAPI
  185108. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  185109. {
  185110. if (png_ptr != NULL && info_ptr != NULL)
  185111. return(info_ptr->channels);
  185112. else
  185113. return (0);
  185114. }
  185115. png_bytep PNGAPI
  185116. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  185117. {
  185118. if (png_ptr != NULL && info_ptr != NULL)
  185119. return(info_ptr->signature);
  185120. else
  185121. return (NULL);
  185122. }
  185123. #if defined(PNG_bKGD_SUPPORTED)
  185124. png_uint_32 PNGAPI
  185125. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  185126. png_color_16p *background)
  185127. {
  185128. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  185129. && background != NULL)
  185130. {
  185131. png_debug1(1, "in %s retrieval function\n", "bKGD");
  185132. *background = &(info_ptr->background);
  185133. return (PNG_INFO_bKGD);
  185134. }
  185135. return (0);
  185136. }
  185137. #endif
  185138. #if defined(PNG_cHRM_SUPPORTED)
  185139. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185140. png_uint_32 PNGAPI
  185141. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  185142. double *white_x, double *white_y, double *red_x, double *red_y,
  185143. double *green_x, double *green_y, double *blue_x, double *blue_y)
  185144. {
  185145. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  185146. {
  185147. png_debug1(1, "in %s retrieval function\n", "cHRM");
  185148. if (white_x != NULL)
  185149. *white_x = (double)info_ptr->x_white;
  185150. if (white_y != NULL)
  185151. *white_y = (double)info_ptr->y_white;
  185152. if (red_x != NULL)
  185153. *red_x = (double)info_ptr->x_red;
  185154. if (red_y != NULL)
  185155. *red_y = (double)info_ptr->y_red;
  185156. if (green_x != NULL)
  185157. *green_x = (double)info_ptr->x_green;
  185158. if (green_y != NULL)
  185159. *green_y = (double)info_ptr->y_green;
  185160. if (blue_x != NULL)
  185161. *blue_x = (double)info_ptr->x_blue;
  185162. if (blue_y != NULL)
  185163. *blue_y = (double)info_ptr->y_blue;
  185164. return (PNG_INFO_cHRM);
  185165. }
  185166. return (0);
  185167. }
  185168. #endif
  185169. #ifdef PNG_FIXED_POINT_SUPPORTED
  185170. png_uint_32 PNGAPI
  185171. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  185172. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  185173. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  185174. png_fixed_point *blue_x, png_fixed_point *blue_y)
  185175. {
  185176. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  185177. {
  185178. png_debug1(1, "in %s retrieval function\n", "cHRM");
  185179. if (white_x != NULL)
  185180. *white_x = info_ptr->int_x_white;
  185181. if (white_y != NULL)
  185182. *white_y = info_ptr->int_y_white;
  185183. if (red_x != NULL)
  185184. *red_x = info_ptr->int_x_red;
  185185. if (red_y != NULL)
  185186. *red_y = info_ptr->int_y_red;
  185187. if (green_x != NULL)
  185188. *green_x = info_ptr->int_x_green;
  185189. if (green_y != NULL)
  185190. *green_y = info_ptr->int_y_green;
  185191. if (blue_x != NULL)
  185192. *blue_x = info_ptr->int_x_blue;
  185193. if (blue_y != NULL)
  185194. *blue_y = info_ptr->int_y_blue;
  185195. return (PNG_INFO_cHRM);
  185196. }
  185197. return (0);
  185198. }
  185199. #endif
  185200. #endif
  185201. #if defined(PNG_gAMA_SUPPORTED)
  185202. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185203. png_uint_32 PNGAPI
  185204. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  185205. {
  185206. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  185207. && file_gamma != NULL)
  185208. {
  185209. png_debug1(1, "in %s retrieval function\n", "gAMA");
  185210. *file_gamma = (double)info_ptr->gamma;
  185211. return (PNG_INFO_gAMA);
  185212. }
  185213. return (0);
  185214. }
  185215. #endif
  185216. #ifdef PNG_FIXED_POINT_SUPPORTED
  185217. png_uint_32 PNGAPI
  185218. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  185219. png_fixed_point *int_file_gamma)
  185220. {
  185221. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  185222. && int_file_gamma != NULL)
  185223. {
  185224. png_debug1(1, "in %s retrieval function\n", "gAMA");
  185225. *int_file_gamma = info_ptr->int_gamma;
  185226. return (PNG_INFO_gAMA);
  185227. }
  185228. return (0);
  185229. }
  185230. #endif
  185231. #endif
  185232. #if defined(PNG_sRGB_SUPPORTED)
  185233. png_uint_32 PNGAPI
  185234. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  185235. {
  185236. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  185237. && file_srgb_intent != NULL)
  185238. {
  185239. png_debug1(1, "in %s retrieval function\n", "sRGB");
  185240. *file_srgb_intent = (int)info_ptr->srgb_intent;
  185241. return (PNG_INFO_sRGB);
  185242. }
  185243. return (0);
  185244. }
  185245. #endif
  185246. #if defined(PNG_iCCP_SUPPORTED)
  185247. png_uint_32 PNGAPI
  185248. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  185249. png_charpp name, int *compression_type,
  185250. png_charpp profile, png_uint_32 *proflen)
  185251. {
  185252. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  185253. && name != NULL && profile != NULL && proflen != NULL)
  185254. {
  185255. png_debug1(1, "in %s retrieval function\n", "iCCP");
  185256. *name = info_ptr->iccp_name;
  185257. *profile = info_ptr->iccp_profile;
  185258. /* compression_type is a dummy so the API won't have to change
  185259. if we introduce multiple compression types later. */
  185260. *proflen = (int)info_ptr->iccp_proflen;
  185261. *compression_type = (int)info_ptr->iccp_compression;
  185262. return (PNG_INFO_iCCP);
  185263. }
  185264. return (0);
  185265. }
  185266. #endif
  185267. #if defined(PNG_sPLT_SUPPORTED)
  185268. png_uint_32 PNGAPI
  185269. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  185270. png_sPLT_tpp spalettes)
  185271. {
  185272. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  185273. {
  185274. *spalettes = info_ptr->splt_palettes;
  185275. return ((png_uint_32)info_ptr->splt_palettes_num);
  185276. }
  185277. return (0);
  185278. }
  185279. #endif
  185280. #if defined(PNG_hIST_SUPPORTED)
  185281. png_uint_32 PNGAPI
  185282. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  185283. {
  185284. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  185285. && hist != NULL)
  185286. {
  185287. png_debug1(1, "in %s retrieval function\n", "hIST");
  185288. *hist = info_ptr->hist;
  185289. return (PNG_INFO_hIST);
  185290. }
  185291. return (0);
  185292. }
  185293. #endif
  185294. png_uint_32 PNGAPI
  185295. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  185296. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  185297. int *color_type, int *interlace_type, int *compression_type,
  185298. int *filter_type)
  185299. {
  185300. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  185301. bit_depth != NULL && color_type != NULL)
  185302. {
  185303. png_debug1(1, "in %s retrieval function\n", "IHDR");
  185304. *width = info_ptr->width;
  185305. *height = info_ptr->height;
  185306. *bit_depth = info_ptr->bit_depth;
  185307. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  185308. png_error(png_ptr, "Invalid bit depth");
  185309. *color_type = info_ptr->color_type;
  185310. if (info_ptr->color_type > 6)
  185311. png_error(png_ptr, "Invalid color type");
  185312. if (compression_type != NULL)
  185313. *compression_type = info_ptr->compression_type;
  185314. if (filter_type != NULL)
  185315. *filter_type = info_ptr->filter_type;
  185316. if (interlace_type != NULL)
  185317. *interlace_type = info_ptr->interlace_type;
  185318. /* check for potential overflow of rowbytes */
  185319. if (*width == 0 || *width > PNG_UINT_31_MAX)
  185320. png_error(png_ptr, "Invalid image width");
  185321. if (*height == 0 || *height > PNG_UINT_31_MAX)
  185322. png_error(png_ptr, "Invalid image height");
  185323. if (info_ptr->width > (PNG_UINT_32_MAX
  185324. >> 3) /* 8-byte RGBA pixels */
  185325. - 64 /* bigrowbuf hack */
  185326. - 1 /* filter byte */
  185327. - 7*8 /* rounding of width to multiple of 8 pixels */
  185328. - 8) /* extra max_pixel_depth pad */
  185329. {
  185330. png_warning(png_ptr,
  185331. "Width too large for libpng to process image data.");
  185332. }
  185333. return (1);
  185334. }
  185335. return (0);
  185336. }
  185337. #if defined(PNG_oFFs_SUPPORTED)
  185338. png_uint_32 PNGAPI
  185339. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  185340. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  185341. {
  185342. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  185343. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  185344. {
  185345. png_debug1(1, "in %s retrieval function\n", "oFFs");
  185346. *offset_x = info_ptr->x_offset;
  185347. *offset_y = info_ptr->y_offset;
  185348. *unit_type = (int)info_ptr->offset_unit_type;
  185349. return (PNG_INFO_oFFs);
  185350. }
  185351. return (0);
  185352. }
  185353. #endif
  185354. #if defined(PNG_pCAL_SUPPORTED)
  185355. png_uint_32 PNGAPI
  185356. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  185357. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  185358. png_charp *units, png_charpp *params)
  185359. {
  185360. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  185361. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  185362. nparams != NULL && units != NULL && params != NULL)
  185363. {
  185364. png_debug1(1, "in %s retrieval function\n", "pCAL");
  185365. *purpose = info_ptr->pcal_purpose;
  185366. *X0 = info_ptr->pcal_X0;
  185367. *X1 = info_ptr->pcal_X1;
  185368. *type = (int)info_ptr->pcal_type;
  185369. *nparams = (int)info_ptr->pcal_nparams;
  185370. *units = info_ptr->pcal_units;
  185371. *params = info_ptr->pcal_params;
  185372. return (PNG_INFO_pCAL);
  185373. }
  185374. return (0);
  185375. }
  185376. #endif
  185377. #if defined(PNG_sCAL_SUPPORTED)
  185378. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185379. png_uint_32 PNGAPI
  185380. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  185381. int *unit, double *width, double *height)
  185382. {
  185383. if (png_ptr != NULL && info_ptr != NULL &&
  185384. (info_ptr->valid & PNG_INFO_sCAL))
  185385. {
  185386. *unit = info_ptr->scal_unit;
  185387. *width = info_ptr->scal_pixel_width;
  185388. *height = info_ptr->scal_pixel_height;
  185389. return (PNG_INFO_sCAL);
  185390. }
  185391. return(0);
  185392. }
  185393. #else
  185394. #ifdef PNG_FIXED_POINT_SUPPORTED
  185395. png_uint_32 PNGAPI
  185396. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  185397. int *unit, png_charpp width, png_charpp height)
  185398. {
  185399. if (png_ptr != NULL && info_ptr != NULL &&
  185400. (info_ptr->valid & PNG_INFO_sCAL))
  185401. {
  185402. *unit = info_ptr->scal_unit;
  185403. *width = info_ptr->scal_s_width;
  185404. *height = info_ptr->scal_s_height;
  185405. return (PNG_INFO_sCAL);
  185406. }
  185407. return(0);
  185408. }
  185409. #endif
  185410. #endif
  185411. #endif
  185412. #if defined(PNG_pHYs_SUPPORTED)
  185413. png_uint_32 PNGAPI
  185414. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  185415. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  185416. {
  185417. png_uint_32 retval = 0;
  185418. if (png_ptr != NULL && info_ptr != NULL &&
  185419. (info_ptr->valid & PNG_INFO_pHYs))
  185420. {
  185421. png_debug1(1, "in %s retrieval function\n", "pHYs");
  185422. if (res_x != NULL)
  185423. {
  185424. *res_x = info_ptr->x_pixels_per_unit;
  185425. retval |= PNG_INFO_pHYs;
  185426. }
  185427. if (res_y != NULL)
  185428. {
  185429. *res_y = info_ptr->y_pixels_per_unit;
  185430. retval |= PNG_INFO_pHYs;
  185431. }
  185432. if (unit_type != NULL)
  185433. {
  185434. *unit_type = (int)info_ptr->phys_unit_type;
  185435. retval |= PNG_INFO_pHYs;
  185436. }
  185437. }
  185438. return (retval);
  185439. }
  185440. #endif
  185441. png_uint_32 PNGAPI
  185442. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  185443. int *num_palette)
  185444. {
  185445. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  185446. && palette != NULL)
  185447. {
  185448. png_debug1(1, "in %s retrieval function\n", "PLTE");
  185449. *palette = info_ptr->palette;
  185450. *num_palette = info_ptr->num_palette;
  185451. png_debug1(3, "num_palette = %d\n", *num_palette);
  185452. return (PNG_INFO_PLTE);
  185453. }
  185454. return (0);
  185455. }
  185456. #if defined(PNG_sBIT_SUPPORTED)
  185457. png_uint_32 PNGAPI
  185458. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  185459. {
  185460. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  185461. && sig_bit != NULL)
  185462. {
  185463. png_debug1(1, "in %s retrieval function\n", "sBIT");
  185464. *sig_bit = &(info_ptr->sig_bit);
  185465. return (PNG_INFO_sBIT);
  185466. }
  185467. return (0);
  185468. }
  185469. #endif
  185470. #if defined(PNG_TEXT_SUPPORTED)
  185471. png_uint_32 PNGAPI
  185472. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  185473. int *num_text)
  185474. {
  185475. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  185476. {
  185477. png_debug1(1, "in %s retrieval function\n",
  185478. (png_ptr->chunk_name[0] == '\0' ? "text"
  185479. : (png_const_charp)png_ptr->chunk_name));
  185480. if (text_ptr != NULL)
  185481. *text_ptr = info_ptr->text;
  185482. if (num_text != NULL)
  185483. *num_text = info_ptr->num_text;
  185484. return ((png_uint_32)info_ptr->num_text);
  185485. }
  185486. if (num_text != NULL)
  185487. *num_text = 0;
  185488. return(0);
  185489. }
  185490. #endif
  185491. #if defined(PNG_tIME_SUPPORTED)
  185492. png_uint_32 PNGAPI
  185493. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  185494. {
  185495. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  185496. && mod_time != NULL)
  185497. {
  185498. png_debug1(1, "in %s retrieval function\n", "tIME");
  185499. *mod_time = &(info_ptr->mod_time);
  185500. return (PNG_INFO_tIME);
  185501. }
  185502. return (0);
  185503. }
  185504. #endif
  185505. #if defined(PNG_tRNS_SUPPORTED)
  185506. png_uint_32 PNGAPI
  185507. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  185508. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  185509. {
  185510. png_uint_32 retval = 0;
  185511. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  185512. {
  185513. png_debug1(1, "in %s retrieval function\n", "tRNS");
  185514. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  185515. {
  185516. if (trans != NULL)
  185517. {
  185518. *trans = info_ptr->trans;
  185519. retval |= PNG_INFO_tRNS;
  185520. }
  185521. if (trans_values != NULL)
  185522. *trans_values = &(info_ptr->trans_values);
  185523. }
  185524. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  185525. {
  185526. if (trans_values != NULL)
  185527. {
  185528. *trans_values = &(info_ptr->trans_values);
  185529. retval |= PNG_INFO_tRNS;
  185530. }
  185531. if(trans != NULL)
  185532. *trans = NULL;
  185533. }
  185534. if(num_trans != NULL)
  185535. {
  185536. *num_trans = info_ptr->num_trans;
  185537. retval |= PNG_INFO_tRNS;
  185538. }
  185539. }
  185540. return (retval);
  185541. }
  185542. #endif
  185543. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  185544. png_uint_32 PNGAPI
  185545. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  185546. png_unknown_chunkpp unknowns)
  185547. {
  185548. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  185549. {
  185550. *unknowns = info_ptr->unknown_chunks;
  185551. return ((png_uint_32)info_ptr->unknown_chunks_num);
  185552. }
  185553. return (0);
  185554. }
  185555. #endif
  185556. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  185557. png_byte PNGAPI
  185558. png_get_rgb_to_gray_status (png_structp png_ptr)
  185559. {
  185560. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  185561. }
  185562. #endif
  185563. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  185564. png_voidp PNGAPI
  185565. png_get_user_chunk_ptr(png_structp png_ptr)
  185566. {
  185567. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  185568. }
  185569. #endif
  185570. #ifdef PNG_WRITE_SUPPORTED
  185571. png_uint_32 PNGAPI
  185572. png_get_compression_buffer_size(png_structp png_ptr)
  185573. {
  185574. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  185575. }
  185576. #endif
  185577. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  185578. #ifndef PNG_1_0_X
  185579. /* this function was added to libpng 1.2.0 and should exist by default */
  185580. png_uint_32 PNGAPI
  185581. png_get_asm_flags (png_structp png_ptr)
  185582. {
  185583. /* obsolete, to be removed from libpng-1.4.0 */
  185584. return (png_ptr? 0L: 0L);
  185585. }
  185586. /* this function was added to libpng 1.2.0 and should exist by default */
  185587. png_uint_32 PNGAPI
  185588. png_get_asm_flagmask (int flag_select)
  185589. {
  185590. /* obsolete, to be removed from libpng-1.4.0 */
  185591. flag_select=flag_select;
  185592. return 0L;
  185593. }
  185594. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  185595. /* this function was added to libpng 1.2.0 */
  185596. png_uint_32 PNGAPI
  185597. png_get_mmx_flagmask (int flag_select, int *compilerID)
  185598. {
  185599. /* obsolete, to be removed from libpng-1.4.0 */
  185600. flag_select=flag_select;
  185601. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  185602. return 0L;
  185603. }
  185604. /* this function was added to libpng 1.2.0 */
  185605. png_byte PNGAPI
  185606. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  185607. {
  185608. /* obsolete, to be removed from libpng-1.4.0 */
  185609. return (png_ptr? 0: 0);
  185610. }
  185611. /* this function was added to libpng 1.2.0 */
  185612. png_uint_32 PNGAPI
  185613. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  185614. {
  185615. /* obsolete, to be removed from libpng-1.4.0 */
  185616. return (png_ptr? 0L: 0L);
  185617. }
  185618. #endif /* ?PNG_1_0_X */
  185619. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  185620. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  185621. /* these functions were added to libpng 1.2.6 */
  185622. png_uint_32 PNGAPI
  185623. png_get_user_width_max (png_structp png_ptr)
  185624. {
  185625. return (png_ptr? png_ptr->user_width_max : 0);
  185626. }
  185627. png_uint_32 PNGAPI
  185628. png_get_user_height_max (png_structp png_ptr)
  185629. {
  185630. return (png_ptr? png_ptr->user_height_max : 0);
  185631. }
  185632. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  185633. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  185634. /*** End of inlined file: pngget.c ***/
  185635. /*** Start of inlined file: pngmem.c ***/
  185636. /* pngmem.c - stub functions for memory allocation
  185637. *
  185638. * Last changed in libpng 1.2.13 November 13, 2006
  185639. * For conditions of distribution and use, see copyright notice in png.h
  185640. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  185641. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185642. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185643. *
  185644. * This file provides a location for all memory allocation. Users who
  185645. * need special memory handling are expected to supply replacement
  185646. * functions for png_malloc() and png_free(), and to use
  185647. * png_create_read_struct_2() and png_create_write_struct_2() to
  185648. * identify the replacement functions.
  185649. */
  185650. #define PNG_INTERNAL
  185651. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185652. /* Borland DOS special memory handler */
  185653. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  185654. /* if you change this, be sure to change the one in png.h also */
  185655. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  185656. by a single call to calloc() if this is thought to improve performance. */
  185657. png_voidp /* PRIVATE */
  185658. png_create_struct(int type)
  185659. {
  185660. #ifdef PNG_USER_MEM_SUPPORTED
  185661. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  185662. }
  185663. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  185664. png_voidp /* PRIVATE */
  185665. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  185666. {
  185667. #endif /* PNG_USER_MEM_SUPPORTED */
  185668. png_size_t size;
  185669. png_voidp struct_ptr;
  185670. if (type == PNG_STRUCT_INFO)
  185671. size = png_sizeof(png_info);
  185672. else if (type == PNG_STRUCT_PNG)
  185673. size = png_sizeof(png_struct);
  185674. else
  185675. return (png_get_copyright(NULL));
  185676. #ifdef PNG_USER_MEM_SUPPORTED
  185677. if(malloc_fn != NULL)
  185678. {
  185679. png_struct dummy_struct;
  185680. png_structp png_ptr = &dummy_struct;
  185681. png_ptr->mem_ptr=mem_ptr;
  185682. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  185683. }
  185684. else
  185685. #endif /* PNG_USER_MEM_SUPPORTED */
  185686. struct_ptr = (png_voidp)farmalloc(size);
  185687. if (struct_ptr != NULL)
  185688. png_memset(struct_ptr, 0, size);
  185689. return (struct_ptr);
  185690. }
  185691. /* Free memory allocated by a png_create_struct() call */
  185692. void /* PRIVATE */
  185693. png_destroy_struct(png_voidp struct_ptr)
  185694. {
  185695. #ifdef PNG_USER_MEM_SUPPORTED
  185696. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  185697. }
  185698. /* Free memory allocated by a png_create_struct() call */
  185699. void /* PRIVATE */
  185700. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  185701. png_voidp mem_ptr)
  185702. {
  185703. #endif
  185704. if (struct_ptr != NULL)
  185705. {
  185706. #ifdef PNG_USER_MEM_SUPPORTED
  185707. if(free_fn != NULL)
  185708. {
  185709. png_struct dummy_struct;
  185710. png_structp png_ptr = &dummy_struct;
  185711. png_ptr->mem_ptr=mem_ptr;
  185712. (*(free_fn))(png_ptr, struct_ptr);
  185713. return;
  185714. }
  185715. #endif /* PNG_USER_MEM_SUPPORTED */
  185716. farfree (struct_ptr);
  185717. }
  185718. }
  185719. /* Allocate memory. For reasonable files, size should never exceed
  185720. * 64K. However, zlib may allocate more then 64K if you don't tell
  185721. * it not to. See zconf.h and png.h for more information. zlib does
  185722. * need to allocate exactly 64K, so whatever you call here must
  185723. * have the ability to do that.
  185724. *
  185725. * Borland seems to have a problem in DOS mode for exactly 64K.
  185726. * It gives you a segment with an offset of 8 (perhaps to store its
  185727. * memory stuff). zlib doesn't like this at all, so we have to
  185728. * detect and deal with it. This code should not be needed in
  185729. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  185730. * been updated by Alexander Lehmann for version 0.89 to waste less
  185731. * memory.
  185732. *
  185733. * Note that we can't use png_size_t for the "size" declaration,
  185734. * since on some systems a png_size_t is a 16-bit quantity, and as a
  185735. * result, we would be truncating potentially larger memory requests
  185736. * (which should cause a fatal error) and introducing major problems.
  185737. */
  185738. png_voidp PNGAPI
  185739. png_malloc(png_structp png_ptr, png_uint_32 size)
  185740. {
  185741. png_voidp ret;
  185742. if (png_ptr == NULL || size == 0)
  185743. return (NULL);
  185744. #ifdef PNG_USER_MEM_SUPPORTED
  185745. if(png_ptr->malloc_fn != NULL)
  185746. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  185747. else
  185748. ret = (png_malloc_default(png_ptr, size));
  185749. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  185750. png_error(png_ptr, "Out of memory!");
  185751. return (ret);
  185752. }
  185753. png_voidp PNGAPI
  185754. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  185755. {
  185756. png_voidp ret;
  185757. #endif /* PNG_USER_MEM_SUPPORTED */
  185758. if (png_ptr == NULL || size == 0)
  185759. return (NULL);
  185760. #ifdef PNG_MAX_MALLOC_64K
  185761. if (size > (png_uint_32)65536L)
  185762. {
  185763. png_warning(png_ptr, "Cannot Allocate > 64K");
  185764. ret = NULL;
  185765. }
  185766. else
  185767. #endif
  185768. if (size != (size_t)size)
  185769. ret = NULL;
  185770. else if (size == (png_uint_32)65536L)
  185771. {
  185772. if (png_ptr->offset_table == NULL)
  185773. {
  185774. /* try to see if we need to do any of this fancy stuff */
  185775. ret = farmalloc(size);
  185776. if (ret == NULL || ((png_size_t)ret & 0xffff))
  185777. {
  185778. int num_blocks;
  185779. png_uint_32 total_size;
  185780. png_bytep table;
  185781. int i;
  185782. png_byte huge * hptr;
  185783. if (ret != NULL)
  185784. {
  185785. farfree(ret);
  185786. ret = NULL;
  185787. }
  185788. if(png_ptr->zlib_window_bits > 14)
  185789. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  185790. else
  185791. num_blocks = 1;
  185792. if (png_ptr->zlib_mem_level >= 7)
  185793. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  185794. else
  185795. num_blocks++;
  185796. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  185797. table = farmalloc(total_size);
  185798. if (table == NULL)
  185799. {
  185800. #ifndef PNG_USER_MEM_SUPPORTED
  185801. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  185802. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  185803. else
  185804. png_warning(png_ptr, "Out Of Memory.");
  185805. #endif
  185806. return (NULL);
  185807. }
  185808. if ((png_size_t)table & 0xfff0)
  185809. {
  185810. #ifndef PNG_USER_MEM_SUPPORTED
  185811. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  185812. png_error(png_ptr,
  185813. "Farmalloc didn't return normalized pointer");
  185814. else
  185815. png_warning(png_ptr,
  185816. "Farmalloc didn't return normalized pointer");
  185817. #endif
  185818. return (NULL);
  185819. }
  185820. png_ptr->offset_table = table;
  185821. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  185822. png_sizeof (png_bytep));
  185823. if (png_ptr->offset_table_ptr == NULL)
  185824. {
  185825. #ifndef PNG_USER_MEM_SUPPORTED
  185826. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  185827. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  185828. else
  185829. png_warning(png_ptr, "Out Of memory.");
  185830. #endif
  185831. return (NULL);
  185832. }
  185833. hptr = (png_byte huge *)table;
  185834. if ((png_size_t)hptr & 0xf)
  185835. {
  185836. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  185837. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  185838. }
  185839. for (i = 0; i < num_blocks; i++)
  185840. {
  185841. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  185842. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  185843. }
  185844. png_ptr->offset_table_number = num_blocks;
  185845. png_ptr->offset_table_count = 0;
  185846. png_ptr->offset_table_count_free = 0;
  185847. }
  185848. }
  185849. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  185850. {
  185851. #ifndef PNG_USER_MEM_SUPPORTED
  185852. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  185853. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  185854. else
  185855. png_warning(png_ptr, "Out of Memory.");
  185856. #endif
  185857. return (NULL);
  185858. }
  185859. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  185860. }
  185861. else
  185862. ret = farmalloc(size);
  185863. #ifndef PNG_USER_MEM_SUPPORTED
  185864. if (ret == NULL)
  185865. {
  185866. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  185867. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  185868. else
  185869. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  185870. }
  185871. #endif
  185872. return (ret);
  185873. }
  185874. /* free a pointer allocated by png_malloc(). In the default
  185875. configuration, png_ptr is not used, but is passed in case it
  185876. is needed. If ptr is NULL, return without taking any action. */
  185877. void PNGAPI
  185878. png_free(png_structp png_ptr, png_voidp ptr)
  185879. {
  185880. if (png_ptr == NULL || ptr == NULL)
  185881. return;
  185882. #ifdef PNG_USER_MEM_SUPPORTED
  185883. if (png_ptr->free_fn != NULL)
  185884. {
  185885. (*(png_ptr->free_fn))(png_ptr, ptr);
  185886. return;
  185887. }
  185888. else png_free_default(png_ptr, ptr);
  185889. }
  185890. void PNGAPI
  185891. png_free_default(png_structp png_ptr, png_voidp ptr)
  185892. {
  185893. #endif /* PNG_USER_MEM_SUPPORTED */
  185894. if(png_ptr == NULL) return;
  185895. if (png_ptr->offset_table != NULL)
  185896. {
  185897. int i;
  185898. for (i = 0; i < png_ptr->offset_table_count; i++)
  185899. {
  185900. if (ptr == png_ptr->offset_table_ptr[i])
  185901. {
  185902. ptr = NULL;
  185903. png_ptr->offset_table_count_free++;
  185904. break;
  185905. }
  185906. }
  185907. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  185908. {
  185909. farfree(png_ptr->offset_table);
  185910. farfree(png_ptr->offset_table_ptr);
  185911. png_ptr->offset_table = NULL;
  185912. png_ptr->offset_table_ptr = NULL;
  185913. }
  185914. }
  185915. if (ptr != NULL)
  185916. {
  185917. farfree(ptr);
  185918. }
  185919. }
  185920. #else /* Not the Borland DOS special memory handler */
  185921. /* Allocate memory for a png_struct or a png_info. The malloc and
  185922. memset can be replaced by a single call to calloc() if this is thought
  185923. to improve performance noticably. */
  185924. png_voidp /* PRIVATE */
  185925. png_create_struct(int type)
  185926. {
  185927. #ifdef PNG_USER_MEM_SUPPORTED
  185928. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  185929. }
  185930. /* Allocate memory for a png_struct or a png_info. The malloc and
  185931. memset can be replaced by a single call to calloc() if this is thought
  185932. to improve performance noticably. */
  185933. png_voidp /* PRIVATE */
  185934. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  185935. {
  185936. #endif /* PNG_USER_MEM_SUPPORTED */
  185937. png_size_t size;
  185938. png_voidp struct_ptr;
  185939. if (type == PNG_STRUCT_INFO)
  185940. size = png_sizeof(png_info);
  185941. else if (type == PNG_STRUCT_PNG)
  185942. size = png_sizeof(png_struct);
  185943. else
  185944. return (NULL);
  185945. #ifdef PNG_USER_MEM_SUPPORTED
  185946. if(malloc_fn != NULL)
  185947. {
  185948. png_struct dummy_struct;
  185949. png_structp png_ptr = &dummy_struct;
  185950. png_ptr->mem_ptr=mem_ptr;
  185951. struct_ptr = (*(malloc_fn))(png_ptr, size);
  185952. if (struct_ptr != NULL)
  185953. png_memset(struct_ptr, 0, size);
  185954. return (struct_ptr);
  185955. }
  185956. #endif /* PNG_USER_MEM_SUPPORTED */
  185957. #if defined(__TURBOC__) && !defined(__FLAT__)
  185958. struct_ptr = (png_voidp)farmalloc(size);
  185959. #else
  185960. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  185961. struct_ptr = (png_voidp)halloc(size,1);
  185962. # else
  185963. struct_ptr = (png_voidp)malloc(size);
  185964. # endif
  185965. #endif
  185966. if (struct_ptr != NULL)
  185967. png_memset(struct_ptr, 0, size);
  185968. return (struct_ptr);
  185969. }
  185970. /* Free memory allocated by a png_create_struct() call */
  185971. void /* PRIVATE */
  185972. png_destroy_struct(png_voidp struct_ptr)
  185973. {
  185974. #ifdef PNG_USER_MEM_SUPPORTED
  185975. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  185976. }
  185977. /* Free memory allocated by a png_create_struct() call */
  185978. void /* PRIVATE */
  185979. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  185980. png_voidp mem_ptr)
  185981. {
  185982. #endif /* PNG_USER_MEM_SUPPORTED */
  185983. if (struct_ptr != NULL)
  185984. {
  185985. #ifdef PNG_USER_MEM_SUPPORTED
  185986. if(free_fn != NULL)
  185987. {
  185988. png_struct dummy_struct;
  185989. png_structp png_ptr = &dummy_struct;
  185990. png_ptr->mem_ptr=mem_ptr;
  185991. (*(free_fn))(png_ptr, struct_ptr);
  185992. return;
  185993. }
  185994. #endif /* PNG_USER_MEM_SUPPORTED */
  185995. #if defined(__TURBOC__) && !defined(__FLAT__)
  185996. farfree(struct_ptr);
  185997. #else
  185998. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  185999. hfree(struct_ptr);
  186000. # else
  186001. free(struct_ptr);
  186002. # endif
  186003. #endif
  186004. }
  186005. }
  186006. /* Allocate memory. For reasonable files, size should never exceed
  186007. 64K. However, zlib may allocate more then 64K if you don't tell
  186008. it not to. See zconf.h and png.h for more information. zlib does
  186009. need to allocate exactly 64K, so whatever you call here must
  186010. have the ability to do that. */
  186011. png_voidp PNGAPI
  186012. png_malloc(png_structp png_ptr, png_uint_32 size)
  186013. {
  186014. png_voidp ret;
  186015. #ifdef PNG_USER_MEM_SUPPORTED
  186016. if (png_ptr == NULL || size == 0)
  186017. return (NULL);
  186018. if(png_ptr->malloc_fn != NULL)
  186019. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186020. else
  186021. ret = (png_malloc_default(png_ptr, size));
  186022. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186023. png_error(png_ptr, "Out of Memory!");
  186024. return (ret);
  186025. }
  186026. png_voidp PNGAPI
  186027. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186028. {
  186029. png_voidp ret;
  186030. #endif /* PNG_USER_MEM_SUPPORTED */
  186031. if (png_ptr == NULL || size == 0)
  186032. return (NULL);
  186033. #ifdef PNG_MAX_MALLOC_64K
  186034. if (size > (png_uint_32)65536L)
  186035. {
  186036. #ifndef PNG_USER_MEM_SUPPORTED
  186037. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186038. png_error(png_ptr, "Cannot Allocate > 64K");
  186039. else
  186040. #endif
  186041. return NULL;
  186042. }
  186043. #endif
  186044. /* Check for overflow */
  186045. #if defined(__TURBOC__) && !defined(__FLAT__)
  186046. if (size != (unsigned long)size)
  186047. ret = NULL;
  186048. else
  186049. ret = farmalloc(size);
  186050. #else
  186051. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186052. if (size != (unsigned long)size)
  186053. ret = NULL;
  186054. else
  186055. ret = halloc(size, 1);
  186056. # else
  186057. if (size != (size_t)size)
  186058. ret = NULL;
  186059. else
  186060. ret = malloc((size_t)size);
  186061. # endif
  186062. #endif
  186063. #ifndef PNG_USER_MEM_SUPPORTED
  186064. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186065. png_error(png_ptr, "Out of Memory");
  186066. #endif
  186067. return (ret);
  186068. }
  186069. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  186070. without taking any action. */
  186071. void PNGAPI
  186072. png_free(png_structp png_ptr, png_voidp ptr)
  186073. {
  186074. if (png_ptr == NULL || ptr == NULL)
  186075. return;
  186076. #ifdef PNG_USER_MEM_SUPPORTED
  186077. if (png_ptr->free_fn != NULL)
  186078. {
  186079. (*(png_ptr->free_fn))(png_ptr, ptr);
  186080. return;
  186081. }
  186082. else png_free_default(png_ptr, ptr);
  186083. }
  186084. void PNGAPI
  186085. png_free_default(png_structp png_ptr, png_voidp ptr)
  186086. {
  186087. if (png_ptr == NULL || ptr == NULL)
  186088. return;
  186089. #endif /* PNG_USER_MEM_SUPPORTED */
  186090. #if defined(__TURBOC__) && !defined(__FLAT__)
  186091. farfree(ptr);
  186092. #else
  186093. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186094. hfree(ptr);
  186095. # else
  186096. free(ptr);
  186097. # endif
  186098. #endif
  186099. }
  186100. #endif /* Not Borland DOS special memory handler */
  186101. #if defined(PNG_1_0_X)
  186102. # define png_malloc_warn png_malloc
  186103. #else
  186104. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  186105. * function will set up png_malloc() to issue a png_warning and return NULL
  186106. * instead of issuing a png_error, if it fails to allocate the requested
  186107. * memory.
  186108. */
  186109. png_voidp PNGAPI
  186110. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  186111. {
  186112. png_voidp ptr;
  186113. png_uint_32 save_flags;
  186114. if(png_ptr == NULL) return (NULL);
  186115. save_flags=png_ptr->flags;
  186116. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  186117. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  186118. png_ptr->flags=save_flags;
  186119. return(ptr);
  186120. }
  186121. #endif
  186122. png_voidp PNGAPI
  186123. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  186124. png_uint_32 length)
  186125. {
  186126. png_size_t size;
  186127. size = (png_size_t)length;
  186128. if ((png_uint_32)size != length)
  186129. png_error(png_ptr,"Overflow in png_memcpy_check.");
  186130. return(png_memcpy (s1, s2, size));
  186131. }
  186132. png_voidp PNGAPI
  186133. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  186134. png_uint_32 length)
  186135. {
  186136. png_size_t size;
  186137. size = (png_size_t)length;
  186138. if ((png_uint_32)size != length)
  186139. png_error(png_ptr,"Overflow in png_memset_check.");
  186140. return (png_memset (s1, value, size));
  186141. }
  186142. #ifdef PNG_USER_MEM_SUPPORTED
  186143. /* This function is called when the application wants to use another method
  186144. * of allocating and freeing memory.
  186145. */
  186146. void PNGAPI
  186147. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  186148. malloc_fn, png_free_ptr free_fn)
  186149. {
  186150. if(png_ptr != NULL) {
  186151. png_ptr->mem_ptr = mem_ptr;
  186152. png_ptr->malloc_fn = malloc_fn;
  186153. png_ptr->free_fn = free_fn;
  186154. }
  186155. }
  186156. /* This function returns a pointer to the mem_ptr associated with the user
  186157. * functions. The application should free any memory associated with this
  186158. * pointer before png_write_destroy and png_read_destroy are called.
  186159. */
  186160. png_voidp PNGAPI
  186161. png_get_mem_ptr(png_structp png_ptr)
  186162. {
  186163. if(png_ptr == NULL) return (NULL);
  186164. return ((png_voidp)png_ptr->mem_ptr);
  186165. }
  186166. #endif /* PNG_USER_MEM_SUPPORTED */
  186167. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  186168. /*** End of inlined file: pngmem.c ***/
  186169. /*** Start of inlined file: pngread.c ***/
  186170. /* pngread.c - read a PNG file
  186171. *
  186172. * Last changed in libpng 1.2.20 September 7, 2007
  186173. * For conditions of distribution and use, see copyright notice in png.h
  186174. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  186175. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186176. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186177. *
  186178. * This file contains routines that an application calls directly to
  186179. * read a PNG file or stream.
  186180. */
  186181. #define PNG_INTERNAL
  186182. #if defined(PNG_READ_SUPPORTED)
  186183. /* Create a PNG structure for reading, and allocate any memory needed. */
  186184. png_structp PNGAPI
  186185. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  186186. png_error_ptr error_fn, png_error_ptr warn_fn)
  186187. {
  186188. #ifdef PNG_USER_MEM_SUPPORTED
  186189. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  186190. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  186191. }
  186192. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  186193. png_structp PNGAPI
  186194. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  186195. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  186196. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  186197. {
  186198. #endif /* PNG_USER_MEM_SUPPORTED */
  186199. png_structp png_ptr;
  186200. #ifdef PNG_SETJMP_SUPPORTED
  186201. #ifdef USE_FAR_KEYWORD
  186202. jmp_buf jmpbuf;
  186203. #endif
  186204. #endif
  186205. int i;
  186206. png_debug(1, "in png_create_read_struct\n");
  186207. #ifdef PNG_USER_MEM_SUPPORTED
  186208. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  186209. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  186210. #else
  186211. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  186212. #endif
  186213. if (png_ptr == NULL)
  186214. return (NULL);
  186215. /* added at libpng-1.2.6 */
  186216. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186217. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  186218. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  186219. #endif
  186220. #ifdef PNG_SETJMP_SUPPORTED
  186221. #ifdef USE_FAR_KEYWORD
  186222. if (setjmp(jmpbuf))
  186223. #else
  186224. if (setjmp(png_ptr->jmpbuf))
  186225. #endif
  186226. {
  186227. png_free(png_ptr, png_ptr->zbuf);
  186228. png_ptr->zbuf=NULL;
  186229. #ifdef PNG_USER_MEM_SUPPORTED
  186230. png_destroy_struct_2((png_voidp)png_ptr,
  186231. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  186232. #else
  186233. png_destroy_struct((png_voidp)png_ptr);
  186234. #endif
  186235. return (NULL);
  186236. }
  186237. #ifdef USE_FAR_KEYWORD
  186238. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  186239. #endif
  186240. #endif
  186241. #ifdef PNG_USER_MEM_SUPPORTED
  186242. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  186243. #endif
  186244. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  186245. i=0;
  186246. do
  186247. {
  186248. if(user_png_ver[i] != png_libpng_ver[i])
  186249. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  186250. } while (png_libpng_ver[i++]);
  186251. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  186252. {
  186253. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  186254. * we must recompile any applications that use any older library version.
  186255. * For versions after libpng 1.0, we will be compatible, so we need
  186256. * only check the first digit.
  186257. */
  186258. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  186259. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  186260. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  186261. {
  186262. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  186263. char msg[80];
  186264. if (user_png_ver)
  186265. {
  186266. png_snprintf(msg, 80,
  186267. "Application was compiled with png.h from libpng-%.20s",
  186268. user_png_ver);
  186269. png_warning(png_ptr, msg);
  186270. }
  186271. png_snprintf(msg, 80,
  186272. "Application is running with png.c from libpng-%.20s",
  186273. png_libpng_ver);
  186274. png_warning(png_ptr, msg);
  186275. #endif
  186276. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  186277. png_ptr->flags=0;
  186278. #endif
  186279. png_error(png_ptr,
  186280. "Incompatible libpng version in application and library");
  186281. }
  186282. }
  186283. /* initialize zbuf - compression buffer */
  186284. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  186285. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  186286. (png_uint_32)png_ptr->zbuf_size);
  186287. png_ptr->zstream.zalloc = png_zalloc;
  186288. png_ptr->zstream.zfree = png_zfree;
  186289. png_ptr->zstream.opaque = (voidpf)png_ptr;
  186290. switch (inflateInit(&png_ptr->zstream))
  186291. {
  186292. case Z_OK: /* Do nothing */ break;
  186293. case Z_MEM_ERROR:
  186294. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  186295. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  186296. default: png_error(png_ptr, "Unknown zlib error");
  186297. }
  186298. png_ptr->zstream.next_out = png_ptr->zbuf;
  186299. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  186300. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  186301. #ifdef PNG_SETJMP_SUPPORTED
  186302. /* Applications that neglect to set up their own setjmp() and then encounter
  186303. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  186304. abort instead of returning. */
  186305. #ifdef USE_FAR_KEYWORD
  186306. if (setjmp(jmpbuf))
  186307. PNG_ABORT();
  186308. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  186309. #else
  186310. if (setjmp(png_ptr->jmpbuf))
  186311. PNG_ABORT();
  186312. #endif
  186313. #endif
  186314. return (png_ptr);
  186315. }
  186316. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  186317. /* Initialize PNG structure for reading, and allocate any memory needed.
  186318. This interface is deprecated in favour of the png_create_read_struct(),
  186319. and it will disappear as of libpng-1.3.0. */
  186320. #undef png_read_init
  186321. void PNGAPI
  186322. png_read_init(png_structp png_ptr)
  186323. {
  186324. /* We only come here via pre-1.0.7-compiled applications */
  186325. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  186326. }
  186327. void PNGAPI
  186328. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  186329. png_size_t png_struct_size, png_size_t png_info_size)
  186330. {
  186331. /* We only come here via pre-1.0.12-compiled applications */
  186332. if(png_ptr == NULL) return;
  186333. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  186334. if(png_sizeof(png_struct) > png_struct_size ||
  186335. png_sizeof(png_info) > png_info_size)
  186336. {
  186337. char msg[80];
  186338. png_ptr->warning_fn=NULL;
  186339. if (user_png_ver)
  186340. {
  186341. png_snprintf(msg, 80,
  186342. "Application was compiled with png.h from libpng-%.20s",
  186343. user_png_ver);
  186344. png_warning(png_ptr, msg);
  186345. }
  186346. png_snprintf(msg, 80,
  186347. "Application is running with png.c from libpng-%.20s",
  186348. png_libpng_ver);
  186349. png_warning(png_ptr, msg);
  186350. }
  186351. #endif
  186352. if(png_sizeof(png_struct) > png_struct_size)
  186353. {
  186354. png_ptr->error_fn=NULL;
  186355. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  186356. png_ptr->flags=0;
  186357. #endif
  186358. png_error(png_ptr,
  186359. "The png struct allocated by the application for reading is too small.");
  186360. }
  186361. if(png_sizeof(png_info) > png_info_size)
  186362. {
  186363. png_ptr->error_fn=NULL;
  186364. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  186365. png_ptr->flags=0;
  186366. #endif
  186367. png_error(png_ptr,
  186368. "The info struct allocated by application for reading is too small.");
  186369. }
  186370. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  186371. }
  186372. #endif /* PNG_1_0_X || PNG_1_2_X */
  186373. void PNGAPI
  186374. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  186375. png_size_t png_struct_size)
  186376. {
  186377. #ifdef PNG_SETJMP_SUPPORTED
  186378. jmp_buf tmp_jmp; /* to save current jump buffer */
  186379. #endif
  186380. int i=0;
  186381. png_structp png_ptr=*ptr_ptr;
  186382. if(png_ptr == NULL) return;
  186383. do
  186384. {
  186385. if(user_png_ver[i] != png_libpng_ver[i])
  186386. {
  186387. #ifdef PNG_LEGACY_SUPPORTED
  186388. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  186389. #else
  186390. png_ptr->warning_fn=NULL;
  186391. png_warning(png_ptr,
  186392. "Application uses deprecated png_read_init() and should be recompiled.");
  186393. break;
  186394. #endif
  186395. }
  186396. } while (png_libpng_ver[i++]);
  186397. png_debug(1, "in png_read_init_3\n");
  186398. #ifdef PNG_SETJMP_SUPPORTED
  186399. /* save jump buffer and error functions */
  186400. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  186401. #endif
  186402. if(png_sizeof(png_struct) > png_struct_size)
  186403. {
  186404. png_destroy_struct(png_ptr);
  186405. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  186406. png_ptr = *ptr_ptr;
  186407. }
  186408. /* reset all variables to 0 */
  186409. png_memset(png_ptr, 0, png_sizeof (png_struct));
  186410. #ifdef PNG_SETJMP_SUPPORTED
  186411. /* restore jump buffer */
  186412. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  186413. #endif
  186414. /* added at libpng-1.2.6 */
  186415. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186416. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  186417. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  186418. #endif
  186419. /* initialize zbuf - compression buffer */
  186420. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  186421. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  186422. (png_uint_32)png_ptr->zbuf_size);
  186423. png_ptr->zstream.zalloc = png_zalloc;
  186424. png_ptr->zstream.zfree = png_zfree;
  186425. png_ptr->zstream.opaque = (voidpf)png_ptr;
  186426. switch (inflateInit(&png_ptr->zstream))
  186427. {
  186428. case Z_OK: /* Do nothing */ break;
  186429. case Z_MEM_ERROR:
  186430. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  186431. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  186432. default: png_error(png_ptr, "Unknown zlib error");
  186433. }
  186434. png_ptr->zstream.next_out = png_ptr->zbuf;
  186435. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  186436. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  186437. }
  186438. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  186439. /* Read the information before the actual image data. This has been
  186440. * changed in v0.90 to allow reading a file that already has the magic
  186441. * bytes read from the stream. You can tell libpng how many bytes have
  186442. * been read from the beginning of the stream (up to the maximum of 8)
  186443. * via png_set_sig_bytes(), and we will only check the remaining bytes
  186444. * here. The application can then have access to the signature bytes we
  186445. * read if it is determined that this isn't a valid PNG file.
  186446. */
  186447. void PNGAPI
  186448. png_read_info(png_structp png_ptr, png_infop info_ptr)
  186449. {
  186450. if(png_ptr == NULL) return;
  186451. png_debug(1, "in png_read_info\n");
  186452. /* If we haven't checked all of the PNG signature bytes, do so now. */
  186453. if (png_ptr->sig_bytes < 8)
  186454. {
  186455. png_size_t num_checked = png_ptr->sig_bytes,
  186456. num_to_check = 8 - num_checked;
  186457. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  186458. png_ptr->sig_bytes = 8;
  186459. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  186460. {
  186461. if (num_checked < 4 &&
  186462. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  186463. png_error(png_ptr, "Not a PNG file");
  186464. else
  186465. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  186466. }
  186467. if (num_checked < 3)
  186468. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  186469. }
  186470. for(;;)
  186471. {
  186472. #ifdef PNG_USE_LOCAL_ARRAYS
  186473. PNG_CONST PNG_IHDR;
  186474. PNG_CONST PNG_IDAT;
  186475. PNG_CONST PNG_IEND;
  186476. PNG_CONST PNG_PLTE;
  186477. #if defined(PNG_READ_bKGD_SUPPORTED)
  186478. PNG_CONST PNG_bKGD;
  186479. #endif
  186480. #if defined(PNG_READ_cHRM_SUPPORTED)
  186481. PNG_CONST PNG_cHRM;
  186482. #endif
  186483. #if defined(PNG_READ_gAMA_SUPPORTED)
  186484. PNG_CONST PNG_gAMA;
  186485. #endif
  186486. #if defined(PNG_READ_hIST_SUPPORTED)
  186487. PNG_CONST PNG_hIST;
  186488. #endif
  186489. #if defined(PNG_READ_iCCP_SUPPORTED)
  186490. PNG_CONST PNG_iCCP;
  186491. #endif
  186492. #if defined(PNG_READ_iTXt_SUPPORTED)
  186493. PNG_CONST PNG_iTXt;
  186494. #endif
  186495. #if defined(PNG_READ_oFFs_SUPPORTED)
  186496. PNG_CONST PNG_oFFs;
  186497. #endif
  186498. #if defined(PNG_READ_pCAL_SUPPORTED)
  186499. PNG_CONST PNG_pCAL;
  186500. #endif
  186501. #if defined(PNG_READ_pHYs_SUPPORTED)
  186502. PNG_CONST PNG_pHYs;
  186503. #endif
  186504. #if defined(PNG_READ_sBIT_SUPPORTED)
  186505. PNG_CONST PNG_sBIT;
  186506. #endif
  186507. #if defined(PNG_READ_sCAL_SUPPORTED)
  186508. PNG_CONST PNG_sCAL;
  186509. #endif
  186510. #if defined(PNG_READ_sPLT_SUPPORTED)
  186511. PNG_CONST PNG_sPLT;
  186512. #endif
  186513. #if defined(PNG_READ_sRGB_SUPPORTED)
  186514. PNG_CONST PNG_sRGB;
  186515. #endif
  186516. #if defined(PNG_READ_tEXt_SUPPORTED)
  186517. PNG_CONST PNG_tEXt;
  186518. #endif
  186519. #if defined(PNG_READ_tIME_SUPPORTED)
  186520. PNG_CONST PNG_tIME;
  186521. #endif
  186522. #if defined(PNG_READ_tRNS_SUPPORTED)
  186523. PNG_CONST PNG_tRNS;
  186524. #endif
  186525. #if defined(PNG_READ_zTXt_SUPPORTED)
  186526. PNG_CONST PNG_zTXt;
  186527. #endif
  186528. #endif /* PNG_USE_LOCAL_ARRAYS */
  186529. png_byte chunk_length[4];
  186530. png_uint_32 length;
  186531. png_read_data(png_ptr, chunk_length, 4);
  186532. length = png_get_uint_31(png_ptr,chunk_length);
  186533. png_reset_crc(png_ptr);
  186534. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  186535. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  186536. length);
  186537. /* This should be a binary subdivision search or a hash for
  186538. * matching the chunk name rather than a linear search.
  186539. */
  186540. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  186541. if(png_ptr->mode & PNG_AFTER_IDAT)
  186542. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  186543. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  186544. png_handle_IHDR(png_ptr, info_ptr, length);
  186545. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  186546. png_handle_IEND(png_ptr, info_ptr, length);
  186547. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  186548. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  186549. {
  186550. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  186551. png_ptr->mode |= PNG_HAVE_IDAT;
  186552. png_handle_unknown(png_ptr, info_ptr, length);
  186553. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  186554. png_ptr->mode |= PNG_HAVE_PLTE;
  186555. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  186556. {
  186557. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  186558. png_error(png_ptr, "Missing IHDR before IDAT");
  186559. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  186560. !(png_ptr->mode & PNG_HAVE_PLTE))
  186561. png_error(png_ptr, "Missing PLTE before IDAT");
  186562. break;
  186563. }
  186564. }
  186565. #endif
  186566. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  186567. png_handle_PLTE(png_ptr, info_ptr, length);
  186568. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  186569. {
  186570. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  186571. png_error(png_ptr, "Missing IHDR before IDAT");
  186572. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  186573. !(png_ptr->mode & PNG_HAVE_PLTE))
  186574. png_error(png_ptr, "Missing PLTE before IDAT");
  186575. png_ptr->idat_size = length;
  186576. png_ptr->mode |= PNG_HAVE_IDAT;
  186577. break;
  186578. }
  186579. #if defined(PNG_READ_bKGD_SUPPORTED)
  186580. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  186581. png_handle_bKGD(png_ptr, info_ptr, length);
  186582. #endif
  186583. #if defined(PNG_READ_cHRM_SUPPORTED)
  186584. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  186585. png_handle_cHRM(png_ptr, info_ptr, length);
  186586. #endif
  186587. #if defined(PNG_READ_gAMA_SUPPORTED)
  186588. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  186589. png_handle_gAMA(png_ptr, info_ptr, length);
  186590. #endif
  186591. #if defined(PNG_READ_hIST_SUPPORTED)
  186592. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  186593. png_handle_hIST(png_ptr, info_ptr, length);
  186594. #endif
  186595. #if defined(PNG_READ_oFFs_SUPPORTED)
  186596. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  186597. png_handle_oFFs(png_ptr, info_ptr, length);
  186598. #endif
  186599. #if defined(PNG_READ_pCAL_SUPPORTED)
  186600. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  186601. png_handle_pCAL(png_ptr, info_ptr, length);
  186602. #endif
  186603. #if defined(PNG_READ_sCAL_SUPPORTED)
  186604. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  186605. png_handle_sCAL(png_ptr, info_ptr, length);
  186606. #endif
  186607. #if defined(PNG_READ_pHYs_SUPPORTED)
  186608. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  186609. png_handle_pHYs(png_ptr, info_ptr, length);
  186610. #endif
  186611. #if defined(PNG_READ_sBIT_SUPPORTED)
  186612. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  186613. png_handle_sBIT(png_ptr, info_ptr, length);
  186614. #endif
  186615. #if defined(PNG_READ_sRGB_SUPPORTED)
  186616. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  186617. png_handle_sRGB(png_ptr, info_ptr, length);
  186618. #endif
  186619. #if defined(PNG_READ_iCCP_SUPPORTED)
  186620. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  186621. png_handle_iCCP(png_ptr, info_ptr, length);
  186622. #endif
  186623. #if defined(PNG_READ_sPLT_SUPPORTED)
  186624. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  186625. png_handle_sPLT(png_ptr, info_ptr, length);
  186626. #endif
  186627. #if defined(PNG_READ_tEXt_SUPPORTED)
  186628. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  186629. png_handle_tEXt(png_ptr, info_ptr, length);
  186630. #endif
  186631. #if defined(PNG_READ_tIME_SUPPORTED)
  186632. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  186633. png_handle_tIME(png_ptr, info_ptr, length);
  186634. #endif
  186635. #if defined(PNG_READ_tRNS_SUPPORTED)
  186636. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  186637. png_handle_tRNS(png_ptr, info_ptr, length);
  186638. #endif
  186639. #if defined(PNG_READ_zTXt_SUPPORTED)
  186640. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  186641. png_handle_zTXt(png_ptr, info_ptr, length);
  186642. #endif
  186643. #if defined(PNG_READ_iTXt_SUPPORTED)
  186644. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  186645. png_handle_iTXt(png_ptr, info_ptr, length);
  186646. #endif
  186647. else
  186648. png_handle_unknown(png_ptr, info_ptr, length);
  186649. }
  186650. }
  186651. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  186652. /* optional call to update the users info_ptr structure */
  186653. void PNGAPI
  186654. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  186655. {
  186656. png_debug(1, "in png_read_update_info\n");
  186657. if(png_ptr == NULL) return;
  186658. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  186659. png_read_start_row(png_ptr);
  186660. else
  186661. png_warning(png_ptr,
  186662. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  186663. png_read_transform_info(png_ptr, info_ptr);
  186664. }
  186665. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  186666. /* Initialize palette, background, etc, after transformations
  186667. * are set, but before any reading takes place. This allows
  186668. * the user to obtain a gamma-corrected palette, for example.
  186669. * If the user doesn't call this, we will do it ourselves.
  186670. */
  186671. void PNGAPI
  186672. png_start_read_image(png_structp png_ptr)
  186673. {
  186674. png_debug(1, "in png_start_read_image\n");
  186675. if(png_ptr == NULL) return;
  186676. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  186677. png_read_start_row(png_ptr);
  186678. }
  186679. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  186680. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  186681. void PNGAPI
  186682. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  186683. {
  186684. #ifdef PNG_USE_LOCAL_ARRAYS
  186685. PNG_CONST PNG_IDAT;
  186686. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  186687. 0xff};
  186688. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  186689. #endif
  186690. int ret;
  186691. if(png_ptr == NULL) return;
  186692. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  186693. png_ptr->row_number, png_ptr->pass);
  186694. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  186695. png_read_start_row(png_ptr);
  186696. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  186697. {
  186698. /* check for transforms that have been set but were defined out */
  186699. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  186700. if (png_ptr->transformations & PNG_INVERT_MONO)
  186701. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  186702. #endif
  186703. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  186704. if (png_ptr->transformations & PNG_FILLER)
  186705. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  186706. #endif
  186707. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  186708. if (png_ptr->transformations & PNG_PACKSWAP)
  186709. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  186710. #endif
  186711. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  186712. if (png_ptr->transformations & PNG_PACK)
  186713. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  186714. #endif
  186715. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  186716. if (png_ptr->transformations & PNG_SHIFT)
  186717. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  186718. #endif
  186719. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  186720. if (png_ptr->transformations & PNG_BGR)
  186721. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  186722. #endif
  186723. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  186724. if (png_ptr->transformations & PNG_SWAP_BYTES)
  186725. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  186726. #endif
  186727. }
  186728. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  186729. /* if interlaced and we do not need a new row, combine row and return */
  186730. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  186731. {
  186732. switch (png_ptr->pass)
  186733. {
  186734. case 0:
  186735. if (png_ptr->row_number & 0x07)
  186736. {
  186737. if (dsp_row != NULL)
  186738. png_combine_row(png_ptr, dsp_row,
  186739. png_pass_dsp_mask[png_ptr->pass]);
  186740. png_read_finish_row(png_ptr);
  186741. return;
  186742. }
  186743. break;
  186744. case 1:
  186745. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  186746. {
  186747. if (dsp_row != NULL)
  186748. png_combine_row(png_ptr, dsp_row,
  186749. png_pass_dsp_mask[png_ptr->pass]);
  186750. png_read_finish_row(png_ptr);
  186751. return;
  186752. }
  186753. break;
  186754. case 2:
  186755. if ((png_ptr->row_number & 0x07) != 4)
  186756. {
  186757. if (dsp_row != NULL && (png_ptr->row_number & 4))
  186758. png_combine_row(png_ptr, dsp_row,
  186759. png_pass_dsp_mask[png_ptr->pass]);
  186760. png_read_finish_row(png_ptr);
  186761. return;
  186762. }
  186763. break;
  186764. case 3:
  186765. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  186766. {
  186767. if (dsp_row != NULL)
  186768. png_combine_row(png_ptr, dsp_row,
  186769. png_pass_dsp_mask[png_ptr->pass]);
  186770. png_read_finish_row(png_ptr);
  186771. return;
  186772. }
  186773. break;
  186774. case 4:
  186775. if ((png_ptr->row_number & 3) != 2)
  186776. {
  186777. if (dsp_row != NULL && (png_ptr->row_number & 2))
  186778. png_combine_row(png_ptr, dsp_row,
  186779. png_pass_dsp_mask[png_ptr->pass]);
  186780. png_read_finish_row(png_ptr);
  186781. return;
  186782. }
  186783. break;
  186784. case 5:
  186785. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  186786. {
  186787. if (dsp_row != NULL)
  186788. png_combine_row(png_ptr, dsp_row,
  186789. png_pass_dsp_mask[png_ptr->pass]);
  186790. png_read_finish_row(png_ptr);
  186791. return;
  186792. }
  186793. break;
  186794. case 6:
  186795. if (!(png_ptr->row_number & 1))
  186796. {
  186797. png_read_finish_row(png_ptr);
  186798. return;
  186799. }
  186800. break;
  186801. }
  186802. }
  186803. #endif
  186804. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  186805. png_error(png_ptr, "Invalid attempt to read row data");
  186806. png_ptr->zstream.next_out = png_ptr->row_buf;
  186807. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  186808. do
  186809. {
  186810. if (!(png_ptr->zstream.avail_in))
  186811. {
  186812. while (!png_ptr->idat_size)
  186813. {
  186814. png_byte chunk_length[4];
  186815. png_crc_finish(png_ptr, 0);
  186816. png_read_data(png_ptr, chunk_length, 4);
  186817. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  186818. png_reset_crc(png_ptr);
  186819. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  186820. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  186821. png_error(png_ptr, "Not enough image data");
  186822. }
  186823. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  186824. png_ptr->zstream.next_in = png_ptr->zbuf;
  186825. if (png_ptr->zbuf_size > png_ptr->idat_size)
  186826. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  186827. png_crc_read(png_ptr, png_ptr->zbuf,
  186828. (png_size_t)png_ptr->zstream.avail_in);
  186829. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  186830. }
  186831. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  186832. if (ret == Z_STREAM_END)
  186833. {
  186834. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  186835. png_ptr->idat_size)
  186836. png_error(png_ptr, "Extra compressed data");
  186837. png_ptr->mode |= PNG_AFTER_IDAT;
  186838. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  186839. break;
  186840. }
  186841. if (ret != Z_OK)
  186842. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  186843. "Decompression error");
  186844. } while (png_ptr->zstream.avail_out);
  186845. png_ptr->row_info.color_type = png_ptr->color_type;
  186846. png_ptr->row_info.width = png_ptr->iwidth;
  186847. png_ptr->row_info.channels = png_ptr->channels;
  186848. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  186849. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  186850. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  186851. png_ptr->row_info.width);
  186852. if(png_ptr->row_buf[0])
  186853. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  186854. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  186855. (int)(png_ptr->row_buf[0]));
  186856. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  186857. png_ptr->rowbytes + 1);
  186858. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  186859. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  186860. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  186861. {
  186862. /* Intrapixel differencing */
  186863. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186864. }
  186865. #endif
  186866. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  186867. png_do_read_transformations(png_ptr);
  186868. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  186869. /* blow up interlaced rows to full size */
  186870. if (png_ptr->interlaced &&
  186871. (png_ptr->transformations & PNG_INTERLACE))
  186872. {
  186873. if (png_ptr->pass < 6)
  186874. /* old interface (pre-1.0.9):
  186875. png_do_read_interlace(&(png_ptr->row_info),
  186876. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  186877. */
  186878. png_do_read_interlace(png_ptr);
  186879. if (dsp_row != NULL)
  186880. png_combine_row(png_ptr, dsp_row,
  186881. png_pass_dsp_mask[png_ptr->pass]);
  186882. if (row != NULL)
  186883. png_combine_row(png_ptr, row,
  186884. png_pass_mask[png_ptr->pass]);
  186885. }
  186886. else
  186887. #endif
  186888. {
  186889. if (row != NULL)
  186890. png_combine_row(png_ptr, row, 0xff);
  186891. if (dsp_row != NULL)
  186892. png_combine_row(png_ptr, dsp_row, 0xff);
  186893. }
  186894. png_read_finish_row(png_ptr);
  186895. if (png_ptr->read_row_fn != NULL)
  186896. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  186897. }
  186898. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  186899. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  186900. /* Read one or more rows of image data. If the image is interlaced,
  186901. * and png_set_interlace_handling() has been called, the rows need to
  186902. * contain the contents of the rows from the previous pass. If the
  186903. * image has alpha or transparency, and png_handle_alpha()[*] has been
  186904. * called, the rows contents must be initialized to the contents of the
  186905. * screen.
  186906. *
  186907. * "row" holds the actual image, and pixels are placed in it
  186908. * as they arrive. If the image is displayed after each pass, it will
  186909. * appear to "sparkle" in. "display_row" can be used to display a
  186910. * "chunky" progressive image, with finer detail added as it becomes
  186911. * available. If you do not want this "chunky" display, you may pass
  186912. * NULL for display_row. If you do not want the sparkle display, and
  186913. * you have not called png_handle_alpha(), you may pass NULL for rows.
  186914. * If you have called png_handle_alpha(), and the image has either an
  186915. * alpha channel or a transparency chunk, you must provide a buffer for
  186916. * rows. In this case, you do not have to provide a display_row buffer
  186917. * also, but you may. If the image is not interlaced, or if you have
  186918. * not called png_set_interlace_handling(), the display_row buffer will
  186919. * be ignored, so pass NULL to it.
  186920. *
  186921. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  186922. */
  186923. void PNGAPI
  186924. png_read_rows(png_structp png_ptr, png_bytepp row,
  186925. png_bytepp display_row, png_uint_32 num_rows)
  186926. {
  186927. png_uint_32 i;
  186928. png_bytepp rp;
  186929. png_bytepp dp;
  186930. png_debug(1, "in png_read_rows\n");
  186931. if(png_ptr == NULL) return;
  186932. rp = row;
  186933. dp = display_row;
  186934. if (rp != NULL && dp != NULL)
  186935. for (i = 0; i < num_rows; i++)
  186936. {
  186937. png_bytep rptr = *rp++;
  186938. png_bytep dptr = *dp++;
  186939. png_read_row(png_ptr, rptr, dptr);
  186940. }
  186941. else if(rp != NULL)
  186942. for (i = 0; i < num_rows; i++)
  186943. {
  186944. png_bytep rptr = *rp;
  186945. png_read_row(png_ptr, rptr, png_bytep_NULL);
  186946. rp++;
  186947. }
  186948. else if(dp != NULL)
  186949. for (i = 0; i < num_rows; i++)
  186950. {
  186951. png_bytep dptr = *dp;
  186952. png_read_row(png_ptr, png_bytep_NULL, dptr);
  186953. dp++;
  186954. }
  186955. }
  186956. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  186957. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  186958. /* Read the entire image. If the image has an alpha channel or a tRNS
  186959. * chunk, and you have called png_handle_alpha()[*], you will need to
  186960. * initialize the image to the current image that PNG will be overlaying.
  186961. * We set the num_rows again here, in case it was incorrectly set in
  186962. * png_read_start_row() by a call to png_read_update_info() or
  186963. * png_start_read_image() if png_set_interlace_handling() wasn't called
  186964. * prior to either of these functions like it should have been. You can
  186965. * only call this function once. If you desire to have an image for
  186966. * each pass of a interlaced image, use png_read_rows() instead.
  186967. *
  186968. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  186969. */
  186970. void PNGAPI
  186971. png_read_image(png_structp png_ptr, png_bytepp image)
  186972. {
  186973. png_uint_32 i,image_height;
  186974. int pass, j;
  186975. png_bytepp rp;
  186976. png_debug(1, "in png_read_image\n");
  186977. if(png_ptr == NULL) return;
  186978. #ifdef PNG_READ_INTERLACING_SUPPORTED
  186979. pass = png_set_interlace_handling(png_ptr);
  186980. #else
  186981. if (png_ptr->interlaced)
  186982. png_error(png_ptr,
  186983. "Cannot read interlaced image -- interlace handler disabled.");
  186984. pass = 1;
  186985. #endif
  186986. image_height=png_ptr->height;
  186987. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  186988. for (j = 0; j < pass; j++)
  186989. {
  186990. rp = image;
  186991. for (i = 0; i < image_height; i++)
  186992. {
  186993. png_read_row(png_ptr, *rp, png_bytep_NULL);
  186994. rp++;
  186995. }
  186996. }
  186997. }
  186998. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  186999. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187000. /* Read the end of the PNG file. Will not read past the end of the
  187001. * file, will verify the end is accurate, and will read any comments
  187002. * or time information at the end of the file, if info is not NULL.
  187003. */
  187004. void PNGAPI
  187005. png_read_end(png_structp png_ptr, png_infop info_ptr)
  187006. {
  187007. png_byte chunk_length[4];
  187008. png_uint_32 length;
  187009. png_debug(1, "in png_read_end\n");
  187010. if(png_ptr == NULL) return;
  187011. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  187012. do
  187013. {
  187014. #ifdef PNG_USE_LOCAL_ARRAYS
  187015. PNG_CONST PNG_IHDR;
  187016. PNG_CONST PNG_IDAT;
  187017. PNG_CONST PNG_IEND;
  187018. PNG_CONST PNG_PLTE;
  187019. #if defined(PNG_READ_bKGD_SUPPORTED)
  187020. PNG_CONST PNG_bKGD;
  187021. #endif
  187022. #if defined(PNG_READ_cHRM_SUPPORTED)
  187023. PNG_CONST PNG_cHRM;
  187024. #endif
  187025. #if defined(PNG_READ_gAMA_SUPPORTED)
  187026. PNG_CONST PNG_gAMA;
  187027. #endif
  187028. #if defined(PNG_READ_hIST_SUPPORTED)
  187029. PNG_CONST PNG_hIST;
  187030. #endif
  187031. #if defined(PNG_READ_iCCP_SUPPORTED)
  187032. PNG_CONST PNG_iCCP;
  187033. #endif
  187034. #if defined(PNG_READ_iTXt_SUPPORTED)
  187035. PNG_CONST PNG_iTXt;
  187036. #endif
  187037. #if defined(PNG_READ_oFFs_SUPPORTED)
  187038. PNG_CONST PNG_oFFs;
  187039. #endif
  187040. #if defined(PNG_READ_pCAL_SUPPORTED)
  187041. PNG_CONST PNG_pCAL;
  187042. #endif
  187043. #if defined(PNG_READ_pHYs_SUPPORTED)
  187044. PNG_CONST PNG_pHYs;
  187045. #endif
  187046. #if defined(PNG_READ_sBIT_SUPPORTED)
  187047. PNG_CONST PNG_sBIT;
  187048. #endif
  187049. #if defined(PNG_READ_sCAL_SUPPORTED)
  187050. PNG_CONST PNG_sCAL;
  187051. #endif
  187052. #if defined(PNG_READ_sPLT_SUPPORTED)
  187053. PNG_CONST PNG_sPLT;
  187054. #endif
  187055. #if defined(PNG_READ_sRGB_SUPPORTED)
  187056. PNG_CONST PNG_sRGB;
  187057. #endif
  187058. #if defined(PNG_READ_tEXt_SUPPORTED)
  187059. PNG_CONST PNG_tEXt;
  187060. #endif
  187061. #if defined(PNG_READ_tIME_SUPPORTED)
  187062. PNG_CONST PNG_tIME;
  187063. #endif
  187064. #if defined(PNG_READ_tRNS_SUPPORTED)
  187065. PNG_CONST PNG_tRNS;
  187066. #endif
  187067. #if defined(PNG_READ_zTXt_SUPPORTED)
  187068. PNG_CONST PNG_zTXt;
  187069. #endif
  187070. #endif /* PNG_USE_LOCAL_ARRAYS */
  187071. png_read_data(png_ptr, chunk_length, 4);
  187072. length = png_get_uint_31(png_ptr,chunk_length);
  187073. png_reset_crc(png_ptr);
  187074. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187075. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  187076. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187077. png_handle_IHDR(png_ptr, info_ptr, length);
  187078. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187079. png_handle_IEND(png_ptr, info_ptr, length);
  187080. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187081. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187082. {
  187083. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187084. {
  187085. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  187086. png_error(png_ptr, "Too many IDAT's found");
  187087. }
  187088. png_handle_unknown(png_ptr, info_ptr, length);
  187089. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187090. png_ptr->mode |= PNG_HAVE_PLTE;
  187091. }
  187092. #endif
  187093. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187094. {
  187095. /* Zero length IDATs are legal after the last IDAT has been
  187096. * read, but not after other chunks have been read.
  187097. */
  187098. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  187099. png_error(png_ptr, "Too many IDAT's found");
  187100. png_crc_finish(png_ptr, length);
  187101. }
  187102. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187103. png_handle_PLTE(png_ptr, info_ptr, length);
  187104. #if defined(PNG_READ_bKGD_SUPPORTED)
  187105. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187106. png_handle_bKGD(png_ptr, info_ptr, length);
  187107. #endif
  187108. #if defined(PNG_READ_cHRM_SUPPORTED)
  187109. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187110. png_handle_cHRM(png_ptr, info_ptr, length);
  187111. #endif
  187112. #if defined(PNG_READ_gAMA_SUPPORTED)
  187113. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187114. png_handle_gAMA(png_ptr, info_ptr, length);
  187115. #endif
  187116. #if defined(PNG_READ_hIST_SUPPORTED)
  187117. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  187118. png_handle_hIST(png_ptr, info_ptr, length);
  187119. #endif
  187120. #if defined(PNG_READ_oFFs_SUPPORTED)
  187121. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  187122. png_handle_oFFs(png_ptr, info_ptr, length);
  187123. #endif
  187124. #if defined(PNG_READ_pCAL_SUPPORTED)
  187125. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  187126. png_handle_pCAL(png_ptr, info_ptr, length);
  187127. #endif
  187128. #if defined(PNG_READ_sCAL_SUPPORTED)
  187129. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  187130. png_handle_sCAL(png_ptr, info_ptr, length);
  187131. #endif
  187132. #if defined(PNG_READ_pHYs_SUPPORTED)
  187133. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  187134. png_handle_pHYs(png_ptr, info_ptr, length);
  187135. #endif
  187136. #if defined(PNG_READ_sBIT_SUPPORTED)
  187137. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  187138. png_handle_sBIT(png_ptr, info_ptr, length);
  187139. #endif
  187140. #if defined(PNG_READ_sRGB_SUPPORTED)
  187141. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  187142. png_handle_sRGB(png_ptr, info_ptr, length);
  187143. #endif
  187144. #if defined(PNG_READ_iCCP_SUPPORTED)
  187145. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  187146. png_handle_iCCP(png_ptr, info_ptr, length);
  187147. #endif
  187148. #if defined(PNG_READ_sPLT_SUPPORTED)
  187149. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  187150. png_handle_sPLT(png_ptr, info_ptr, length);
  187151. #endif
  187152. #if defined(PNG_READ_tEXt_SUPPORTED)
  187153. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  187154. png_handle_tEXt(png_ptr, info_ptr, length);
  187155. #endif
  187156. #if defined(PNG_READ_tIME_SUPPORTED)
  187157. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  187158. png_handle_tIME(png_ptr, info_ptr, length);
  187159. #endif
  187160. #if defined(PNG_READ_tRNS_SUPPORTED)
  187161. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  187162. png_handle_tRNS(png_ptr, info_ptr, length);
  187163. #endif
  187164. #if defined(PNG_READ_zTXt_SUPPORTED)
  187165. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  187166. png_handle_zTXt(png_ptr, info_ptr, length);
  187167. #endif
  187168. #if defined(PNG_READ_iTXt_SUPPORTED)
  187169. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  187170. png_handle_iTXt(png_ptr, info_ptr, length);
  187171. #endif
  187172. else
  187173. png_handle_unknown(png_ptr, info_ptr, length);
  187174. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  187175. }
  187176. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187177. /* free all memory used by the read */
  187178. void PNGAPI
  187179. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  187180. png_infopp end_info_ptr_ptr)
  187181. {
  187182. png_structp png_ptr = NULL;
  187183. png_infop info_ptr = NULL, end_info_ptr = NULL;
  187184. #ifdef PNG_USER_MEM_SUPPORTED
  187185. png_free_ptr free_fn;
  187186. png_voidp mem_ptr;
  187187. #endif
  187188. png_debug(1, "in png_destroy_read_struct\n");
  187189. if (png_ptr_ptr != NULL)
  187190. png_ptr = *png_ptr_ptr;
  187191. if (info_ptr_ptr != NULL)
  187192. info_ptr = *info_ptr_ptr;
  187193. if (end_info_ptr_ptr != NULL)
  187194. end_info_ptr = *end_info_ptr_ptr;
  187195. #ifdef PNG_USER_MEM_SUPPORTED
  187196. free_fn = png_ptr->free_fn;
  187197. mem_ptr = png_ptr->mem_ptr;
  187198. #endif
  187199. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  187200. if (info_ptr != NULL)
  187201. {
  187202. #if defined(PNG_TEXT_SUPPORTED)
  187203. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  187204. #endif
  187205. #ifdef PNG_USER_MEM_SUPPORTED
  187206. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  187207. (png_voidp)mem_ptr);
  187208. #else
  187209. png_destroy_struct((png_voidp)info_ptr);
  187210. #endif
  187211. *info_ptr_ptr = NULL;
  187212. }
  187213. if (end_info_ptr != NULL)
  187214. {
  187215. #if defined(PNG_READ_TEXT_SUPPORTED)
  187216. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  187217. #endif
  187218. #ifdef PNG_USER_MEM_SUPPORTED
  187219. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  187220. (png_voidp)mem_ptr);
  187221. #else
  187222. png_destroy_struct((png_voidp)end_info_ptr);
  187223. #endif
  187224. *end_info_ptr_ptr = NULL;
  187225. }
  187226. if (png_ptr != NULL)
  187227. {
  187228. #ifdef PNG_USER_MEM_SUPPORTED
  187229. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  187230. (png_voidp)mem_ptr);
  187231. #else
  187232. png_destroy_struct((png_voidp)png_ptr);
  187233. #endif
  187234. *png_ptr_ptr = NULL;
  187235. }
  187236. }
  187237. /* free all memory used by the read (old method) */
  187238. void /* PRIVATE */
  187239. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  187240. {
  187241. #ifdef PNG_SETJMP_SUPPORTED
  187242. jmp_buf tmp_jmp;
  187243. #endif
  187244. png_error_ptr error_fn;
  187245. png_error_ptr warning_fn;
  187246. png_voidp error_ptr;
  187247. #ifdef PNG_USER_MEM_SUPPORTED
  187248. png_free_ptr free_fn;
  187249. #endif
  187250. png_debug(1, "in png_read_destroy\n");
  187251. if (info_ptr != NULL)
  187252. png_info_destroy(png_ptr, info_ptr);
  187253. if (end_info_ptr != NULL)
  187254. png_info_destroy(png_ptr, end_info_ptr);
  187255. png_free(png_ptr, png_ptr->zbuf);
  187256. png_free(png_ptr, png_ptr->big_row_buf);
  187257. png_free(png_ptr, png_ptr->prev_row);
  187258. #if defined(PNG_READ_DITHER_SUPPORTED)
  187259. png_free(png_ptr, png_ptr->palette_lookup);
  187260. png_free(png_ptr, png_ptr->dither_index);
  187261. #endif
  187262. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187263. png_free(png_ptr, png_ptr->gamma_table);
  187264. #endif
  187265. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187266. png_free(png_ptr, png_ptr->gamma_from_1);
  187267. png_free(png_ptr, png_ptr->gamma_to_1);
  187268. #endif
  187269. #ifdef PNG_FREE_ME_SUPPORTED
  187270. if (png_ptr->free_me & PNG_FREE_PLTE)
  187271. png_zfree(png_ptr, png_ptr->palette);
  187272. png_ptr->free_me &= ~PNG_FREE_PLTE;
  187273. #else
  187274. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  187275. png_zfree(png_ptr, png_ptr->palette);
  187276. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  187277. #endif
  187278. #if defined(PNG_tRNS_SUPPORTED) || \
  187279. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  187280. #ifdef PNG_FREE_ME_SUPPORTED
  187281. if (png_ptr->free_me & PNG_FREE_TRNS)
  187282. png_free(png_ptr, png_ptr->trans);
  187283. png_ptr->free_me &= ~PNG_FREE_TRNS;
  187284. #else
  187285. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  187286. png_free(png_ptr, png_ptr->trans);
  187287. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  187288. #endif
  187289. #endif
  187290. #if defined(PNG_READ_hIST_SUPPORTED)
  187291. #ifdef PNG_FREE_ME_SUPPORTED
  187292. if (png_ptr->free_me & PNG_FREE_HIST)
  187293. png_free(png_ptr, png_ptr->hist);
  187294. png_ptr->free_me &= ~PNG_FREE_HIST;
  187295. #else
  187296. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  187297. png_free(png_ptr, png_ptr->hist);
  187298. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  187299. #endif
  187300. #endif
  187301. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187302. if (png_ptr->gamma_16_table != NULL)
  187303. {
  187304. int i;
  187305. int istop = (1 << (8 - png_ptr->gamma_shift));
  187306. for (i = 0; i < istop; i++)
  187307. {
  187308. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  187309. }
  187310. png_free(png_ptr, png_ptr->gamma_16_table);
  187311. }
  187312. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187313. if (png_ptr->gamma_16_from_1 != NULL)
  187314. {
  187315. int i;
  187316. int istop = (1 << (8 - png_ptr->gamma_shift));
  187317. for (i = 0; i < istop; i++)
  187318. {
  187319. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  187320. }
  187321. png_free(png_ptr, png_ptr->gamma_16_from_1);
  187322. }
  187323. if (png_ptr->gamma_16_to_1 != NULL)
  187324. {
  187325. int i;
  187326. int istop = (1 << (8 - png_ptr->gamma_shift));
  187327. for (i = 0; i < istop; i++)
  187328. {
  187329. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  187330. }
  187331. png_free(png_ptr, png_ptr->gamma_16_to_1);
  187332. }
  187333. #endif
  187334. #endif
  187335. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  187336. png_free(png_ptr, png_ptr->time_buffer);
  187337. #endif
  187338. inflateEnd(&png_ptr->zstream);
  187339. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  187340. png_free(png_ptr, png_ptr->save_buffer);
  187341. #endif
  187342. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  187343. #ifdef PNG_TEXT_SUPPORTED
  187344. png_free(png_ptr, png_ptr->current_text);
  187345. #endif /* PNG_TEXT_SUPPORTED */
  187346. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  187347. /* Save the important info out of the png_struct, in case it is
  187348. * being used again.
  187349. */
  187350. #ifdef PNG_SETJMP_SUPPORTED
  187351. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  187352. #endif
  187353. error_fn = png_ptr->error_fn;
  187354. warning_fn = png_ptr->warning_fn;
  187355. error_ptr = png_ptr->error_ptr;
  187356. #ifdef PNG_USER_MEM_SUPPORTED
  187357. free_fn = png_ptr->free_fn;
  187358. #endif
  187359. png_memset(png_ptr, 0, png_sizeof (png_struct));
  187360. png_ptr->error_fn = error_fn;
  187361. png_ptr->warning_fn = warning_fn;
  187362. png_ptr->error_ptr = error_ptr;
  187363. #ifdef PNG_USER_MEM_SUPPORTED
  187364. png_ptr->free_fn = free_fn;
  187365. #endif
  187366. #ifdef PNG_SETJMP_SUPPORTED
  187367. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  187368. #endif
  187369. }
  187370. void PNGAPI
  187371. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  187372. {
  187373. if(png_ptr == NULL) return;
  187374. png_ptr->read_row_fn = read_row_fn;
  187375. }
  187376. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187377. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  187378. void PNGAPI
  187379. png_read_png(png_structp png_ptr, png_infop info_ptr,
  187380. int transforms,
  187381. voidp params)
  187382. {
  187383. int row;
  187384. if(png_ptr == NULL) return;
  187385. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  187386. /* invert the alpha channel from opacity to transparency
  187387. */
  187388. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  187389. png_set_invert_alpha(png_ptr);
  187390. #endif
  187391. /* png_read_info() gives us all of the information from the
  187392. * PNG file before the first IDAT (image data chunk).
  187393. */
  187394. png_read_info(png_ptr, info_ptr);
  187395. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  187396. png_error(png_ptr,"Image is too high to process with png_read_png()");
  187397. /* -------------- image transformations start here ------------------- */
  187398. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  187399. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  187400. */
  187401. if (transforms & PNG_TRANSFORM_STRIP_16)
  187402. png_set_strip_16(png_ptr);
  187403. #endif
  187404. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  187405. /* Strip alpha bytes from the input data without combining with
  187406. * the background (not recommended).
  187407. */
  187408. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  187409. png_set_strip_alpha(png_ptr);
  187410. #endif
  187411. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  187412. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  187413. * byte into separate bytes (useful for paletted and grayscale images).
  187414. */
  187415. if (transforms & PNG_TRANSFORM_PACKING)
  187416. png_set_packing(png_ptr);
  187417. #endif
  187418. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  187419. /* Change the order of packed pixels to least significant bit first
  187420. * (not useful if you are using png_set_packing).
  187421. */
  187422. if (transforms & PNG_TRANSFORM_PACKSWAP)
  187423. png_set_packswap(png_ptr);
  187424. #endif
  187425. #if defined(PNG_READ_EXPAND_SUPPORTED)
  187426. /* Expand paletted colors into true RGB triplets
  187427. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  187428. * Expand paletted or RGB images with transparency to full alpha
  187429. * channels so the data will be available as RGBA quartets.
  187430. */
  187431. if (transforms & PNG_TRANSFORM_EXPAND)
  187432. if ((png_ptr->bit_depth < 8) ||
  187433. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  187434. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  187435. png_set_expand(png_ptr);
  187436. #endif
  187437. /* We don't handle background color or gamma transformation or dithering.
  187438. */
  187439. #if defined(PNG_READ_INVERT_SUPPORTED)
  187440. /* invert monochrome files to have 0 as white and 1 as black
  187441. */
  187442. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  187443. png_set_invert_mono(png_ptr);
  187444. #endif
  187445. #if defined(PNG_READ_SHIFT_SUPPORTED)
  187446. /* If you want to shift the pixel values from the range [0,255] or
  187447. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  187448. * colors were originally in:
  187449. */
  187450. if ((transforms & PNG_TRANSFORM_SHIFT)
  187451. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  187452. {
  187453. png_color_8p sig_bit;
  187454. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  187455. png_set_shift(png_ptr, sig_bit);
  187456. }
  187457. #endif
  187458. #if defined(PNG_READ_BGR_SUPPORTED)
  187459. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  187460. */
  187461. if (transforms & PNG_TRANSFORM_BGR)
  187462. png_set_bgr(png_ptr);
  187463. #endif
  187464. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  187465. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  187466. */
  187467. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  187468. png_set_swap_alpha(png_ptr);
  187469. #endif
  187470. #if defined(PNG_READ_SWAP_SUPPORTED)
  187471. /* swap bytes of 16 bit files to least significant byte first
  187472. */
  187473. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  187474. png_set_swap(png_ptr);
  187475. #endif
  187476. /* We don't handle adding filler bytes */
  187477. /* Optional call to gamma correct and add the background to the palette
  187478. * and update info structure. REQUIRED if you are expecting libpng to
  187479. * update the palette for you (i.e., you selected such a transform above).
  187480. */
  187481. png_read_update_info(png_ptr, info_ptr);
  187482. /* -------------- image transformations end here ------------------- */
  187483. #ifdef PNG_FREE_ME_SUPPORTED
  187484. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  187485. #endif
  187486. if(info_ptr->row_pointers == NULL)
  187487. {
  187488. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  187489. info_ptr->height * png_sizeof(png_bytep));
  187490. #ifdef PNG_FREE_ME_SUPPORTED
  187491. info_ptr->free_me |= PNG_FREE_ROWS;
  187492. #endif
  187493. for (row = 0; row < (int)info_ptr->height; row++)
  187494. {
  187495. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  187496. png_get_rowbytes(png_ptr, info_ptr));
  187497. }
  187498. }
  187499. png_read_image(png_ptr, info_ptr->row_pointers);
  187500. info_ptr->valid |= PNG_INFO_IDAT;
  187501. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  187502. png_read_end(png_ptr, info_ptr);
  187503. transforms = transforms; /* quiet compiler warnings */
  187504. params = params;
  187505. }
  187506. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  187507. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187508. #endif /* PNG_READ_SUPPORTED */
  187509. /*** End of inlined file: pngread.c ***/
  187510. /*** Start of inlined file: pngpread.c ***/
  187511. /* pngpread.c - read a png file in push mode
  187512. *
  187513. * Last changed in libpng 1.2.21 October 4, 2007
  187514. * For conditions of distribution and use, see copyright notice in png.h
  187515. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  187516. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  187517. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  187518. */
  187519. #define PNG_INTERNAL
  187520. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  187521. /* push model modes */
  187522. #define PNG_READ_SIG_MODE 0
  187523. #define PNG_READ_CHUNK_MODE 1
  187524. #define PNG_READ_IDAT_MODE 2
  187525. #define PNG_SKIP_MODE 3
  187526. #define PNG_READ_tEXt_MODE 4
  187527. #define PNG_READ_zTXt_MODE 5
  187528. #define PNG_READ_DONE_MODE 6
  187529. #define PNG_READ_iTXt_MODE 7
  187530. #define PNG_ERROR_MODE 8
  187531. void PNGAPI
  187532. png_process_data(png_structp png_ptr, png_infop info_ptr,
  187533. png_bytep buffer, png_size_t buffer_size)
  187534. {
  187535. if(png_ptr == NULL) return;
  187536. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  187537. while (png_ptr->buffer_size)
  187538. {
  187539. png_process_some_data(png_ptr, info_ptr);
  187540. }
  187541. }
  187542. /* What we do with the incoming data depends on what we were previously
  187543. * doing before we ran out of data...
  187544. */
  187545. void /* PRIVATE */
  187546. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  187547. {
  187548. if(png_ptr == NULL) return;
  187549. switch (png_ptr->process_mode)
  187550. {
  187551. case PNG_READ_SIG_MODE:
  187552. {
  187553. png_push_read_sig(png_ptr, info_ptr);
  187554. break;
  187555. }
  187556. case PNG_READ_CHUNK_MODE:
  187557. {
  187558. png_push_read_chunk(png_ptr, info_ptr);
  187559. break;
  187560. }
  187561. case PNG_READ_IDAT_MODE:
  187562. {
  187563. png_push_read_IDAT(png_ptr);
  187564. break;
  187565. }
  187566. #if defined(PNG_READ_tEXt_SUPPORTED)
  187567. case PNG_READ_tEXt_MODE:
  187568. {
  187569. png_push_read_tEXt(png_ptr, info_ptr);
  187570. break;
  187571. }
  187572. #endif
  187573. #if defined(PNG_READ_zTXt_SUPPORTED)
  187574. case PNG_READ_zTXt_MODE:
  187575. {
  187576. png_push_read_zTXt(png_ptr, info_ptr);
  187577. break;
  187578. }
  187579. #endif
  187580. #if defined(PNG_READ_iTXt_SUPPORTED)
  187581. case PNG_READ_iTXt_MODE:
  187582. {
  187583. png_push_read_iTXt(png_ptr, info_ptr);
  187584. break;
  187585. }
  187586. #endif
  187587. case PNG_SKIP_MODE:
  187588. {
  187589. png_push_crc_finish(png_ptr);
  187590. break;
  187591. }
  187592. default:
  187593. {
  187594. png_ptr->buffer_size = 0;
  187595. break;
  187596. }
  187597. }
  187598. }
  187599. /* Read any remaining signature bytes from the stream and compare them with
  187600. * the correct PNG signature. It is possible that this routine is called
  187601. * with bytes already read from the signature, either because they have been
  187602. * checked by the calling application, or because of multiple calls to this
  187603. * routine.
  187604. */
  187605. void /* PRIVATE */
  187606. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  187607. {
  187608. png_size_t num_checked = png_ptr->sig_bytes,
  187609. num_to_check = 8 - num_checked;
  187610. if (png_ptr->buffer_size < num_to_check)
  187611. {
  187612. num_to_check = png_ptr->buffer_size;
  187613. }
  187614. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  187615. num_to_check);
  187616. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  187617. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  187618. {
  187619. if (num_checked < 4 &&
  187620. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  187621. png_error(png_ptr, "Not a PNG file");
  187622. else
  187623. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  187624. }
  187625. else
  187626. {
  187627. if (png_ptr->sig_bytes >= 8)
  187628. {
  187629. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  187630. }
  187631. }
  187632. }
  187633. void /* PRIVATE */
  187634. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  187635. {
  187636. #ifdef PNG_USE_LOCAL_ARRAYS
  187637. PNG_CONST PNG_IHDR;
  187638. PNG_CONST PNG_IDAT;
  187639. PNG_CONST PNG_IEND;
  187640. PNG_CONST PNG_PLTE;
  187641. #if defined(PNG_READ_bKGD_SUPPORTED)
  187642. PNG_CONST PNG_bKGD;
  187643. #endif
  187644. #if defined(PNG_READ_cHRM_SUPPORTED)
  187645. PNG_CONST PNG_cHRM;
  187646. #endif
  187647. #if defined(PNG_READ_gAMA_SUPPORTED)
  187648. PNG_CONST PNG_gAMA;
  187649. #endif
  187650. #if defined(PNG_READ_hIST_SUPPORTED)
  187651. PNG_CONST PNG_hIST;
  187652. #endif
  187653. #if defined(PNG_READ_iCCP_SUPPORTED)
  187654. PNG_CONST PNG_iCCP;
  187655. #endif
  187656. #if defined(PNG_READ_iTXt_SUPPORTED)
  187657. PNG_CONST PNG_iTXt;
  187658. #endif
  187659. #if defined(PNG_READ_oFFs_SUPPORTED)
  187660. PNG_CONST PNG_oFFs;
  187661. #endif
  187662. #if defined(PNG_READ_pCAL_SUPPORTED)
  187663. PNG_CONST PNG_pCAL;
  187664. #endif
  187665. #if defined(PNG_READ_pHYs_SUPPORTED)
  187666. PNG_CONST PNG_pHYs;
  187667. #endif
  187668. #if defined(PNG_READ_sBIT_SUPPORTED)
  187669. PNG_CONST PNG_sBIT;
  187670. #endif
  187671. #if defined(PNG_READ_sCAL_SUPPORTED)
  187672. PNG_CONST PNG_sCAL;
  187673. #endif
  187674. #if defined(PNG_READ_sRGB_SUPPORTED)
  187675. PNG_CONST PNG_sRGB;
  187676. #endif
  187677. #if defined(PNG_READ_sPLT_SUPPORTED)
  187678. PNG_CONST PNG_sPLT;
  187679. #endif
  187680. #if defined(PNG_READ_tEXt_SUPPORTED)
  187681. PNG_CONST PNG_tEXt;
  187682. #endif
  187683. #if defined(PNG_READ_tIME_SUPPORTED)
  187684. PNG_CONST PNG_tIME;
  187685. #endif
  187686. #if defined(PNG_READ_tRNS_SUPPORTED)
  187687. PNG_CONST PNG_tRNS;
  187688. #endif
  187689. #if defined(PNG_READ_zTXt_SUPPORTED)
  187690. PNG_CONST PNG_zTXt;
  187691. #endif
  187692. #endif /* PNG_USE_LOCAL_ARRAYS */
  187693. /* First we make sure we have enough data for the 4 byte chunk name
  187694. * and the 4 byte chunk length before proceeding with decoding the
  187695. * chunk data. To fully decode each of these chunks, we also make
  187696. * sure we have enough data in the buffer for the 4 byte CRC at the
  187697. * end of every chunk (except IDAT, which is handled separately).
  187698. */
  187699. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  187700. {
  187701. png_byte chunk_length[4];
  187702. if (png_ptr->buffer_size < 8)
  187703. {
  187704. png_push_save_buffer(png_ptr);
  187705. return;
  187706. }
  187707. png_push_fill_buffer(png_ptr, chunk_length, 4);
  187708. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  187709. png_reset_crc(png_ptr);
  187710. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187711. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  187712. }
  187713. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187714. if(png_ptr->mode & PNG_AFTER_IDAT)
  187715. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  187716. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187717. {
  187718. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187719. {
  187720. png_push_save_buffer(png_ptr);
  187721. return;
  187722. }
  187723. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  187724. }
  187725. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187726. {
  187727. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187728. {
  187729. png_push_save_buffer(png_ptr);
  187730. return;
  187731. }
  187732. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  187733. png_ptr->process_mode = PNG_READ_DONE_MODE;
  187734. png_push_have_end(png_ptr, info_ptr);
  187735. }
  187736. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187737. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187738. {
  187739. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187740. {
  187741. png_push_save_buffer(png_ptr);
  187742. return;
  187743. }
  187744. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187745. png_ptr->mode |= PNG_HAVE_IDAT;
  187746. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  187747. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187748. png_ptr->mode |= PNG_HAVE_PLTE;
  187749. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187750. {
  187751. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187752. png_error(png_ptr, "Missing IHDR before IDAT");
  187753. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187754. !(png_ptr->mode & PNG_HAVE_PLTE))
  187755. png_error(png_ptr, "Missing PLTE before IDAT");
  187756. }
  187757. }
  187758. #endif
  187759. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187760. {
  187761. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187762. {
  187763. png_push_save_buffer(png_ptr);
  187764. return;
  187765. }
  187766. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  187767. }
  187768. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187769. {
  187770. /* If we reach an IDAT chunk, this means we have read all of the
  187771. * header chunks, and we can start reading the image (or if this
  187772. * is called after the image has been read - we have an error).
  187773. */
  187774. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187775. png_error(png_ptr, "Missing IHDR before IDAT");
  187776. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187777. !(png_ptr->mode & PNG_HAVE_PLTE))
  187778. png_error(png_ptr, "Missing PLTE before IDAT");
  187779. if (png_ptr->mode & PNG_HAVE_IDAT)
  187780. {
  187781. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  187782. if (png_ptr->push_length == 0)
  187783. return;
  187784. if (png_ptr->mode & PNG_AFTER_IDAT)
  187785. png_error(png_ptr, "Too many IDAT's found");
  187786. }
  187787. png_ptr->idat_size = png_ptr->push_length;
  187788. png_ptr->mode |= PNG_HAVE_IDAT;
  187789. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  187790. png_push_have_info(png_ptr, info_ptr);
  187791. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  187792. png_ptr->zstream.next_out = png_ptr->row_buf;
  187793. return;
  187794. }
  187795. #if defined(PNG_READ_gAMA_SUPPORTED)
  187796. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187797. {
  187798. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187799. {
  187800. png_push_save_buffer(png_ptr);
  187801. return;
  187802. }
  187803. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  187804. }
  187805. #endif
  187806. #if defined(PNG_READ_sBIT_SUPPORTED)
  187807. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  187808. {
  187809. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187810. {
  187811. png_push_save_buffer(png_ptr);
  187812. return;
  187813. }
  187814. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  187815. }
  187816. #endif
  187817. #if defined(PNG_READ_cHRM_SUPPORTED)
  187818. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187819. {
  187820. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187821. {
  187822. png_push_save_buffer(png_ptr);
  187823. return;
  187824. }
  187825. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  187826. }
  187827. #endif
  187828. #if defined(PNG_READ_sRGB_SUPPORTED)
  187829. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  187830. {
  187831. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187832. {
  187833. png_push_save_buffer(png_ptr);
  187834. return;
  187835. }
  187836. png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  187837. }
  187838. #endif
  187839. #if defined(PNG_READ_iCCP_SUPPORTED)
  187840. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  187841. {
  187842. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187843. {
  187844. png_push_save_buffer(png_ptr);
  187845. return;
  187846. }
  187847. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  187848. }
  187849. #endif
  187850. #if defined(PNG_READ_sPLT_SUPPORTED)
  187851. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  187852. {
  187853. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187854. {
  187855. png_push_save_buffer(png_ptr);
  187856. return;
  187857. }
  187858. png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  187859. }
  187860. #endif
  187861. #if defined(PNG_READ_tRNS_SUPPORTED)
  187862. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  187863. {
  187864. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187865. {
  187866. png_push_save_buffer(png_ptr);
  187867. return;
  187868. }
  187869. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  187870. }
  187871. #endif
  187872. #if defined(PNG_READ_bKGD_SUPPORTED)
  187873. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187874. {
  187875. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187876. {
  187877. png_push_save_buffer(png_ptr);
  187878. return;
  187879. }
  187880. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  187881. }
  187882. #endif
  187883. #if defined(PNG_READ_hIST_SUPPORTED)
  187884. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  187885. {
  187886. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187887. {
  187888. png_push_save_buffer(png_ptr);
  187889. return;
  187890. }
  187891. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  187892. }
  187893. #endif
  187894. #if defined(PNG_READ_pHYs_SUPPORTED)
  187895. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  187896. {
  187897. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187898. {
  187899. png_push_save_buffer(png_ptr);
  187900. return;
  187901. }
  187902. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  187903. }
  187904. #endif
  187905. #if defined(PNG_READ_oFFs_SUPPORTED)
  187906. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  187907. {
  187908. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187909. {
  187910. png_push_save_buffer(png_ptr);
  187911. return;
  187912. }
  187913. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  187914. }
  187915. #endif
  187916. #if defined(PNG_READ_pCAL_SUPPORTED)
  187917. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  187918. {
  187919. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187920. {
  187921. png_push_save_buffer(png_ptr);
  187922. return;
  187923. }
  187924. png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  187925. }
  187926. #endif
  187927. #if defined(PNG_READ_sCAL_SUPPORTED)
  187928. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  187929. {
  187930. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187931. {
  187932. png_push_save_buffer(png_ptr);
  187933. return;
  187934. }
  187935. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  187936. }
  187937. #endif
  187938. #if defined(PNG_READ_tIME_SUPPORTED)
  187939. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  187940. {
  187941. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187942. {
  187943. png_push_save_buffer(png_ptr);
  187944. return;
  187945. }
  187946. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  187947. }
  187948. #endif
  187949. #if defined(PNG_READ_tEXt_SUPPORTED)
  187950. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  187951. {
  187952. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187953. {
  187954. png_push_save_buffer(png_ptr);
  187955. return;
  187956. }
  187957. png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  187958. }
  187959. #endif
  187960. #if defined(PNG_READ_zTXt_SUPPORTED)
  187961. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  187962. {
  187963. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187964. {
  187965. png_push_save_buffer(png_ptr);
  187966. return;
  187967. }
  187968. png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  187969. }
  187970. #endif
  187971. #if defined(PNG_READ_iTXt_SUPPORTED)
  187972. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  187973. {
  187974. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187975. {
  187976. png_push_save_buffer(png_ptr);
  187977. return;
  187978. }
  187979. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  187980. }
  187981. #endif
  187982. else
  187983. {
  187984. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  187985. {
  187986. png_push_save_buffer(png_ptr);
  187987. return;
  187988. }
  187989. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  187990. }
  187991. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  187992. }
  187993. void /* PRIVATE */
  187994. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  187995. {
  187996. png_ptr->process_mode = PNG_SKIP_MODE;
  187997. png_ptr->skip_length = skip;
  187998. }
  187999. void /* PRIVATE */
  188000. png_push_crc_finish(png_structp png_ptr)
  188001. {
  188002. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  188003. {
  188004. png_size_t save_size;
  188005. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  188006. save_size = (png_size_t)png_ptr->skip_length;
  188007. else
  188008. save_size = png_ptr->save_buffer_size;
  188009. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188010. png_ptr->skip_length -= save_size;
  188011. png_ptr->buffer_size -= save_size;
  188012. png_ptr->save_buffer_size -= save_size;
  188013. png_ptr->save_buffer_ptr += save_size;
  188014. }
  188015. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  188016. {
  188017. png_size_t save_size;
  188018. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  188019. save_size = (png_size_t)png_ptr->skip_length;
  188020. else
  188021. save_size = png_ptr->current_buffer_size;
  188022. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188023. png_ptr->skip_length -= save_size;
  188024. png_ptr->buffer_size -= save_size;
  188025. png_ptr->current_buffer_size -= save_size;
  188026. png_ptr->current_buffer_ptr += save_size;
  188027. }
  188028. if (!png_ptr->skip_length)
  188029. {
  188030. if (png_ptr->buffer_size < 4)
  188031. {
  188032. png_push_save_buffer(png_ptr);
  188033. return;
  188034. }
  188035. png_crc_finish(png_ptr, 0);
  188036. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188037. }
  188038. }
  188039. void PNGAPI
  188040. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  188041. {
  188042. png_bytep ptr;
  188043. if(png_ptr == NULL) return;
  188044. ptr = buffer;
  188045. if (png_ptr->save_buffer_size)
  188046. {
  188047. png_size_t save_size;
  188048. if (length < png_ptr->save_buffer_size)
  188049. save_size = length;
  188050. else
  188051. save_size = png_ptr->save_buffer_size;
  188052. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  188053. length -= save_size;
  188054. ptr += save_size;
  188055. png_ptr->buffer_size -= save_size;
  188056. png_ptr->save_buffer_size -= save_size;
  188057. png_ptr->save_buffer_ptr += save_size;
  188058. }
  188059. if (length && png_ptr->current_buffer_size)
  188060. {
  188061. png_size_t save_size;
  188062. if (length < png_ptr->current_buffer_size)
  188063. save_size = length;
  188064. else
  188065. save_size = png_ptr->current_buffer_size;
  188066. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  188067. png_ptr->buffer_size -= save_size;
  188068. png_ptr->current_buffer_size -= save_size;
  188069. png_ptr->current_buffer_ptr += save_size;
  188070. }
  188071. }
  188072. void /* PRIVATE */
  188073. png_push_save_buffer(png_structp png_ptr)
  188074. {
  188075. if (png_ptr->save_buffer_size)
  188076. {
  188077. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  188078. {
  188079. png_size_t i,istop;
  188080. png_bytep sp;
  188081. png_bytep dp;
  188082. istop = png_ptr->save_buffer_size;
  188083. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  188084. i < istop; i++, sp++, dp++)
  188085. {
  188086. *dp = *sp;
  188087. }
  188088. }
  188089. }
  188090. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  188091. png_ptr->save_buffer_max)
  188092. {
  188093. png_size_t new_max;
  188094. png_bytep old_buffer;
  188095. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  188096. (png_ptr->current_buffer_size + 256))
  188097. {
  188098. png_error(png_ptr, "Potential overflow of save_buffer");
  188099. }
  188100. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  188101. old_buffer = png_ptr->save_buffer;
  188102. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  188103. (png_uint_32)new_max);
  188104. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  188105. png_free(png_ptr, old_buffer);
  188106. png_ptr->save_buffer_max = new_max;
  188107. }
  188108. if (png_ptr->current_buffer_size)
  188109. {
  188110. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  188111. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  188112. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  188113. png_ptr->current_buffer_size = 0;
  188114. }
  188115. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  188116. png_ptr->buffer_size = 0;
  188117. }
  188118. void /* PRIVATE */
  188119. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  188120. png_size_t buffer_length)
  188121. {
  188122. png_ptr->current_buffer = buffer;
  188123. png_ptr->current_buffer_size = buffer_length;
  188124. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  188125. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  188126. }
  188127. void /* PRIVATE */
  188128. png_push_read_IDAT(png_structp png_ptr)
  188129. {
  188130. #ifdef PNG_USE_LOCAL_ARRAYS
  188131. PNG_CONST PNG_IDAT;
  188132. #endif
  188133. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  188134. {
  188135. png_byte chunk_length[4];
  188136. if (png_ptr->buffer_size < 8)
  188137. {
  188138. png_push_save_buffer(png_ptr);
  188139. return;
  188140. }
  188141. png_push_fill_buffer(png_ptr, chunk_length, 4);
  188142. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  188143. png_reset_crc(png_ptr);
  188144. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188145. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  188146. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188147. {
  188148. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188149. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188150. png_error(png_ptr, "Not enough compressed data");
  188151. return;
  188152. }
  188153. png_ptr->idat_size = png_ptr->push_length;
  188154. }
  188155. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  188156. {
  188157. png_size_t save_size;
  188158. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  188159. {
  188160. save_size = (png_size_t)png_ptr->idat_size;
  188161. /* check for overflow */
  188162. if((png_uint_32)save_size != png_ptr->idat_size)
  188163. png_error(png_ptr, "save_size overflowed in pngpread");
  188164. }
  188165. else
  188166. save_size = png_ptr->save_buffer_size;
  188167. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188168. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188169. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188170. png_ptr->idat_size -= save_size;
  188171. png_ptr->buffer_size -= save_size;
  188172. png_ptr->save_buffer_size -= save_size;
  188173. png_ptr->save_buffer_ptr += save_size;
  188174. }
  188175. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  188176. {
  188177. png_size_t save_size;
  188178. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  188179. {
  188180. save_size = (png_size_t)png_ptr->idat_size;
  188181. /* check for overflow */
  188182. if((png_uint_32)save_size != png_ptr->idat_size)
  188183. png_error(png_ptr, "save_size overflowed in pngpread");
  188184. }
  188185. else
  188186. save_size = png_ptr->current_buffer_size;
  188187. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188188. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188189. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188190. png_ptr->idat_size -= save_size;
  188191. png_ptr->buffer_size -= save_size;
  188192. png_ptr->current_buffer_size -= save_size;
  188193. png_ptr->current_buffer_ptr += save_size;
  188194. }
  188195. if (!png_ptr->idat_size)
  188196. {
  188197. if (png_ptr->buffer_size < 4)
  188198. {
  188199. png_push_save_buffer(png_ptr);
  188200. return;
  188201. }
  188202. png_crc_finish(png_ptr, 0);
  188203. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  188204. png_ptr->mode |= PNG_AFTER_IDAT;
  188205. }
  188206. }
  188207. void /* PRIVATE */
  188208. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  188209. png_size_t buffer_length)
  188210. {
  188211. int ret;
  188212. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  188213. png_error(png_ptr, "Extra compression data");
  188214. png_ptr->zstream.next_in = buffer;
  188215. png_ptr->zstream.avail_in = (uInt)buffer_length;
  188216. for(;;)
  188217. {
  188218. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  188219. if (ret != Z_OK)
  188220. {
  188221. if (ret == Z_STREAM_END)
  188222. {
  188223. if (png_ptr->zstream.avail_in)
  188224. png_error(png_ptr, "Extra compressed data");
  188225. if (!(png_ptr->zstream.avail_out))
  188226. {
  188227. png_push_process_row(png_ptr);
  188228. }
  188229. png_ptr->mode |= PNG_AFTER_IDAT;
  188230. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  188231. break;
  188232. }
  188233. else if (ret == Z_BUF_ERROR)
  188234. break;
  188235. else
  188236. png_error(png_ptr, "Decompression Error");
  188237. }
  188238. if (!(png_ptr->zstream.avail_out))
  188239. {
  188240. if ((
  188241. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  188242. png_ptr->interlaced && png_ptr->pass > 6) ||
  188243. (!png_ptr->interlaced &&
  188244. #endif
  188245. png_ptr->row_number == png_ptr->num_rows))
  188246. {
  188247. if (png_ptr->zstream.avail_in)
  188248. {
  188249. png_warning(png_ptr, "Too much data in IDAT chunks");
  188250. }
  188251. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  188252. break;
  188253. }
  188254. png_push_process_row(png_ptr);
  188255. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  188256. png_ptr->zstream.next_out = png_ptr->row_buf;
  188257. }
  188258. else
  188259. break;
  188260. }
  188261. }
  188262. void /* PRIVATE */
  188263. png_push_process_row(png_structp png_ptr)
  188264. {
  188265. png_ptr->row_info.color_type = png_ptr->color_type;
  188266. png_ptr->row_info.width = png_ptr->iwidth;
  188267. png_ptr->row_info.channels = png_ptr->channels;
  188268. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  188269. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  188270. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  188271. png_ptr->row_info.width);
  188272. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  188273. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  188274. (int)(png_ptr->row_buf[0]));
  188275. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  188276. png_ptr->rowbytes + 1);
  188277. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  188278. png_do_read_transformations(png_ptr);
  188279. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  188280. /* blow up interlaced rows to full size */
  188281. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  188282. {
  188283. if (png_ptr->pass < 6)
  188284. /* old interface (pre-1.0.9):
  188285. png_do_read_interlace(&(png_ptr->row_info),
  188286. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  188287. */
  188288. png_do_read_interlace(png_ptr);
  188289. switch (png_ptr->pass)
  188290. {
  188291. case 0:
  188292. {
  188293. int i;
  188294. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  188295. {
  188296. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188297. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  188298. }
  188299. if (png_ptr->pass == 2) /* pass 1 might be empty */
  188300. {
  188301. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188302. {
  188303. png_push_have_row(png_ptr, png_bytep_NULL);
  188304. png_read_push_finish_row(png_ptr);
  188305. }
  188306. }
  188307. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  188308. {
  188309. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188310. {
  188311. png_push_have_row(png_ptr, png_bytep_NULL);
  188312. png_read_push_finish_row(png_ptr);
  188313. }
  188314. }
  188315. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  188316. {
  188317. png_push_have_row(png_ptr, png_bytep_NULL);
  188318. png_read_push_finish_row(png_ptr);
  188319. }
  188320. break;
  188321. }
  188322. case 1:
  188323. {
  188324. int i;
  188325. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  188326. {
  188327. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188328. png_read_push_finish_row(png_ptr);
  188329. }
  188330. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  188331. {
  188332. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188333. {
  188334. png_push_have_row(png_ptr, png_bytep_NULL);
  188335. png_read_push_finish_row(png_ptr);
  188336. }
  188337. }
  188338. break;
  188339. }
  188340. case 2:
  188341. {
  188342. int i;
  188343. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188344. {
  188345. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188346. png_read_push_finish_row(png_ptr);
  188347. }
  188348. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188349. {
  188350. png_push_have_row(png_ptr, png_bytep_NULL);
  188351. png_read_push_finish_row(png_ptr);
  188352. }
  188353. if (png_ptr->pass == 4) /* pass 3 might be empty */
  188354. {
  188355. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188356. {
  188357. png_push_have_row(png_ptr, png_bytep_NULL);
  188358. png_read_push_finish_row(png_ptr);
  188359. }
  188360. }
  188361. break;
  188362. }
  188363. case 3:
  188364. {
  188365. int i;
  188366. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  188367. {
  188368. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188369. png_read_push_finish_row(png_ptr);
  188370. }
  188371. if (png_ptr->pass == 4) /* skip top two generated rows */
  188372. {
  188373. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188374. {
  188375. png_push_have_row(png_ptr, png_bytep_NULL);
  188376. png_read_push_finish_row(png_ptr);
  188377. }
  188378. }
  188379. break;
  188380. }
  188381. case 4:
  188382. {
  188383. int i;
  188384. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188385. {
  188386. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188387. png_read_push_finish_row(png_ptr);
  188388. }
  188389. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188390. {
  188391. png_push_have_row(png_ptr, png_bytep_NULL);
  188392. png_read_push_finish_row(png_ptr);
  188393. }
  188394. if (png_ptr->pass == 6) /* pass 5 might be empty */
  188395. {
  188396. png_push_have_row(png_ptr, png_bytep_NULL);
  188397. png_read_push_finish_row(png_ptr);
  188398. }
  188399. break;
  188400. }
  188401. case 5:
  188402. {
  188403. int i;
  188404. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  188405. {
  188406. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188407. png_read_push_finish_row(png_ptr);
  188408. }
  188409. if (png_ptr->pass == 6) /* skip top generated row */
  188410. {
  188411. png_push_have_row(png_ptr, png_bytep_NULL);
  188412. png_read_push_finish_row(png_ptr);
  188413. }
  188414. break;
  188415. }
  188416. case 6:
  188417. {
  188418. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188419. png_read_push_finish_row(png_ptr);
  188420. if (png_ptr->pass != 6)
  188421. break;
  188422. png_push_have_row(png_ptr, png_bytep_NULL);
  188423. png_read_push_finish_row(png_ptr);
  188424. }
  188425. }
  188426. }
  188427. else
  188428. #endif
  188429. {
  188430. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188431. png_read_push_finish_row(png_ptr);
  188432. }
  188433. }
  188434. void /* PRIVATE */
  188435. png_read_push_finish_row(png_structp png_ptr)
  188436. {
  188437. #ifdef PNG_USE_LOCAL_ARRAYS
  188438. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  188439. /* start of interlace block */
  188440. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  188441. /* offset to next interlace block */
  188442. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  188443. /* start of interlace block in the y direction */
  188444. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  188445. /* offset to next interlace block in the y direction */
  188446. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  188447. /* Height of interlace block. This is not currently used - if you need
  188448. * it, uncomment it here and in png.h
  188449. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  188450. */
  188451. #endif
  188452. png_ptr->row_number++;
  188453. if (png_ptr->row_number < png_ptr->num_rows)
  188454. return;
  188455. if (png_ptr->interlaced)
  188456. {
  188457. png_ptr->row_number = 0;
  188458. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  188459. png_ptr->rowbytes + 1);
  188460. do
  188461. {
  188462. png_ptr->pass++;
  188463. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  188464. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  188465. (png_ptr->pass == 5 && png_ptr->width < 2))
  188466. png_ptr->pass++;
  188467. if (png_ptr->pass > 7)
  188468. png_ptr->pass--;
  188469. if (png_ptr->pass >= 7)
  188470. break;
  188471. png_ptr->iwidth = (png_ptr->width +
  188472. png_pass_inc[png_ptr->pass] - 1 -
  188473. png_pass_start[png_ptr->pass]) /
  188474. png_pass_inc[png_ptr->pass];
  188475. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  188476. png_ptr->iwidth) + 1;
  188477. if (png_ptr->transformations & PNG_INTERLACE)
  188478. break;
  188479. png_ptr->num_rows = (png_ptr->height +
  188480. png_pass_yinc[png_ptr->pass] - 1 -
  188481. png_pass_ystart[png_ptr->pass]) /
  188482. png_pass_yinc[png_ptr->pass];
  188483. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  188484. }
  188485. }
  188486. #if defined(PNG_READ_tEXt_SUPPORTED)
  188487. void /* PRIVATE */
  188488. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  188489. length)
  188490. {
  188491. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  188492. {
  188493. png_error(png_ptr, "Out of place tEXt");
  188494. info_ptr = info_ptr; /* to quiet some compiler warnings */
  188495. }
  188496. #ifdef PNG_MAX_MALLOC_64K
  188497. png_ptr->skip_length = 0; /* This may not be necessary */
  188498. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  188499. {
  188500. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  188501. png_ptr->skip_length = length - (png_uint_32)65535L;
  188502. length = (png_uint_32)65535L;
  188503. }
  188504. #endif
  188505. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  188506. (png_uint_32)(length+1));
  188507. png_ptr->current_text[length] = '\0';
  188508. png_ptr->current_text_ptr = png_ptr->current_text;
  188509. png_ptr->current_text_size = (png_size_t)length;
  188510. png_ptr->current_text_left = (png_size_t)length;
  188511. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  188512. }
  188513. void /* PRIVATE */
  188514. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  188515. {
  188516. if (png_ptr->buffer_size && png_ptr->current_text_left)
  188517. {
  188518. png_size_t text_size;
  188519. if (png_ptr->buffer_size < png_ptr->current_text_left)
  188520. text_size = png_ptr->buffer_size;
  188521. else
  188522. text_size = png_ptr->current_text_left;
  188523. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  188524. png_ptr->current_text_left -= text_size;
  188525. png_ptr->current_text_ptr += text_size;
  188526. }
  188527. if (!(png_ptr->current_text_left))
  188528. {
  188529. png_textp text_ptr;
  188530. png_charp text;
  188531. png_charp key;
  188532. int ret;
  188533. if (png_ptr->buffer_size < 4)
  188534. {
  188535. png_push_save_buffer(png_ptr);
  188536. return;
  188537. }
  188538. png_push_crc_finish(png_ptr);
  188539. #if defined(PNG_MAX_MALLOC_64K)
  188540. if (png_ptr->skip_length)
  188541. return;
  188542. #endif
  188543. key = png_ptr->current_text;
  188544. for (text = key; *text; text++)
  188545. /* empty loop */ ;
  188546. if (text < key + png_ptr->current_text_size)
  188547. text++;
  188548. text_ptr = (png_textp)png_malloc(png_ptr,
  188549. (png_uint_32)png_sizeof(png_text));
  188550. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  188551. text_ptr->key = key;
  188552. #ifdef PNG_iTXt_SUPPORTED
  188553. text_ptr->lang = NULL;
  188554. text_ptr->lang_key = NULL;
  188555. #endif
  188556. text_ptr->text = text;
  188557. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  188558. png_free(png_ptr, key);
  188559. png_free(png_ptr, text_ptr);
  188560. png_ptr->current_text = NULL;
  188561. if (ret)
  188562. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  188563. }
  188564. }
  188565. #endif
  188566. #if defined(PNG_READ_zTXt_SUPPORTED)
  188567. void /* PRIVATE */
  188568. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  188569. length)
  188570. {
  188571. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  188572. {
  188573. png_error(png_ptr, "Out of place zTXt");
  188574. info_ptr = info_ptr; /* to quiet some compiler warnings */
  188575. }
  188576. #ifdef PNG_MAX_MALLOC_64K
  188577. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  188578. * to be able to store the uncompressed data. Actually, the threshold
  188579. * is probably around 32K, but it isn't as definite as 64K is.
  188580. */
  188581. if (length > (png_uint_32)65535L)
  188582. {
  188583. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  188584. png_push_crc_skip(png_ptr, length);
  188585. return;
  188586. }
  188587. #endif
  188588. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  188589. (png_uint_32)(length+1));
  188590. png_ptr->current_text[length] = '\0';
  188591. png_ptr->current_text_ptr = png_ptr->current_text;
  188592. png_ptr->current_text_size = (png_size_t)length;
  188593. png_ptr->current_text_left = (png_size_t)length;
  188594. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  188595. }
  188596. void /* PRIVATE */
  188597. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  188598. {
  188599. if (png_ptr->buffer_size && png_ptr->current_text_left)
  188600. {
  188601. png_size_t text_size;
  188602. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  188603. text_size = png_ptr->buffer_size;
  188604. else
  188605. text_size = png_ptr->current_text_left;
  188606. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  188607. png_ptr->current_text_left -= text_size;
  188608. png_ptr->current_text_ptr += text_size;
  188609. }
  188610. if (!(png_ptr->current_text_left))
  188611. {
  188612. png_textp text_ptr;
  188613. png_charp text;
  188614. png_charp key;
  188615. int ret;
  188616. png_size_t text_size, key_size;
  188617. if (png_ptr->buffer_size < 4)
  188618. {
  188619. png_push_save_buffer(png_ptr);
  188620. return;
  188621. }
  188622. png_push_crc_finish(png_ptr);
  188623. key = png_ptr->current_text;
  188624. for (text = key; *text; text++)
  188625. /* empty loop */ ;
  188626. /* zTXt can't have zero text */
  188627. if (text >= key + png_ptr->current_text_size)
  188628. {
  188629. png_ptr->current_text = NULL;
  188630. png_free(png_ptr, key);
  188631. return;
  188632. }
  188633. text++;
  188634. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  188635. {
  188636. png_ptr->current_text = NULL;
  188637. png_free(png_ptr, key);
  188638. return;
  188639. }
  188640. text++;
  188641. png_ptr->zstream.next_in = (png_bytep )text;
  188642. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  188643. (text - key));
  188644. png_ptr->zstream.next_out = png_ptr->zbuf;
  188645. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  188646. key_size = text - key;
  188647. text_size = 0;
  188648. text = NULL;
  188649. ret = Z_STREAM_END;
  188650. while (png_ptr->zstream.avail_in)
  188651. {
  188652. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  188653. if (ret != Z_OK && ret != Z_STREAM_END)
  188654. {
  188655. inflateReset(&png_ptr->zstream);
  188656. png_ptr->zstream.avail_in = 0;
  188657. png_ptr->current_text = NULL;
  188658. png_free(png_ptr, key);
  188659. png_free(png_ptr, text);
  188660. return;
  188661. }
  188662. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  188663. {
  188664. if (text == NULL)
  188665. {
  188666. text = (png_charp)png_malloc(png_ptr,
  188667. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  188668. + key_size + 1));
  188669. png_memcpy(text + key_size, png_ptr->zbuf,
  188670. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  188671. png_memcpy(text, key, key_size);
  188672. text_size = key_size + png_ptr->zbuf_size -
  188673. png_ptr->zstream.avail_out;
  188674. *(text + text_size) = '\0';
  188675. }
  188676. else
  188677. {
  188678. png_charp tmp;
  188679. tmp = text;
  188680. text = (png_charp)png_malloc(png_ptr, text_size +
  188681. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  188682. + 1));
  188683. png_memcpy(text, tmp, text_size);
  188684. png_free(png_ptr, tmp);
  188685. png_memcpy(text + text_size, png_ptr->zbuf,
  188686. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  188687. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  188688. *(text + text_size) = '\0';
  188689. }
  188690. if (ret != Z_STREAM_END)
  188691. {
  188692. png_ptr->zstream.next_out = png_ptr->zbuf;
  188693. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  188694. }
  188695. }
  188696. else
  188697. {
  188698. break;
  188699. }
  188700. if (ret == Z_STREAM_END)
  188701. break;
  188702. }
  188703. inflateReset(&png_ptr->zstream);
  188704. png_ptr->zstream.avail_in = 0;
  188705. if (ret != Z_STREAM_END)
  188706. {
  188707. png_ptr->current_text = NULL;
  188708. png_free(png_ptr, key);
  188709. png_free(png_ptr, text);
  188710. return;
  188711. }
  188712. png_ptr->current_text = NULL;
  188713. png_free(png_ptr, key);
  188714. key = text;
  188715. text += key_size;
  188716. text_ptr = (png_textp)png_malloc(png_ptr,
  188717. (png_uint_32)png_sizeof(png_text));
  188718. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  188719. text_ptr->key = key;
  188720. #ifdef PNG_iTXt_SUPPORTED
  188721. text_ptr->lang = NULL;
  188722. text_ptr->lang_key = NULL;
  188723. #endif
  188724. text_ptr->text = text;
  188725. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  188726. png_free(png_ptr, key);
  188727. png_free(png_ptr, text_ptr);
  188728. if (ret)
  188729. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  188730. }
  188731. }
  188732. #endif
  188733. #if defined(PNG_READ_iTXt_SUPPORTED)
  188734. void /* PRIVATE */
  188735. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  188736. length)
  188737. {
  188738. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  188739. {
  188740. png_error(png_ptr, "Out of place iTXt");
  188741. info_ptr = info_ptr; /* to quiet some compiler warnings */
  188742. }
  188743. #ifdef PNG_MAX_MALLOC_64K
  188744. png_ptr->skip_length = 0; /* This may not be necessary */
  188745. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  188746. {
  188747. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  188748. png_ptr->skip_length = length - (png_uint_32)65535L;
  188749. length = (png_uint_32)65535L;
  188750. }
  188751. #endif
  188752. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  188753. (png_uint_32)(length+1));
  188754. png_ptr->current_text[length] = '\0';
  188755. png_ptr->current_text_ptr = png_ptr->current_text;
  188756. png_ptr->current_text_size = (png_size_t)length;
  188757. png_ptr->current_text_left = (png_size_t)length;
  188758. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  188759. }
  188760. void /* PRIVATE */
  188761. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  188762. {
  188763. if (png_ptr->buffer_size && png_ptr->current_text_left)
  188764. {
  188765. png_size_t text_size;
  188766. if (png_ptr->buffer_size < png_ptr->current_text_left)
  188767. text_size = png_ptr->buffer_size;
  188768. else
  188769. text_size = png_ptr->current_text_left;
  188770. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  188771. png_ptr->current_text_left -= text_size;
  188772. png_ptr->current_text_ptr += text_size;
  188773. }
  188774. if (!(png_ptr->current_text_left))
  188775. {
  188776. png_textp text_ptr;
  188777. png_charp key;
  188778. int comp_flag;
  188779. png_charp lang;
  188780. png_charp lang_key;
  188781. png_charp text;
  188782. int ret;
  188783. if (png_ptr->buffer_size < 4)
  188784. {
  188785. png_push_save_buffer(png_ptr);
  188786. return;
  188787. }
  188788. png_push_crc_finish(png_ptr);
  188789. #if defined(PNG_MAX_MALLOC_64K)
  188790. if (png_ptr->skip_length)
  188791. return;
  188792. #endif
  188793. key = png_ptr->current_text;
  188794. for (lang = key; *lang; lang++)
  188795. /* empty loop */ ;
  188796. if (lang < key + png_ptr->current_text_size - 3)
  188797. lang++;
  188798. comp_flag = *lang++;
  188799. lang++; /* skip comp_type, always zero */
  188800. for (lang_key = lang; *lang_key; lang_key++)
  188801. /* empty loop */ ;
  188802. lang_key++; /* skip NUL separator */
  188803. text=lang_key;
  188804. if (lang_key < key + png_ptr->current_text_size - 1)
  188805. {
  188806. for (; *text; text++)
  188807. /* empty loop */ ;
  188808. }
  188809. if (text < key + png_ptr->current_text_size)
  188810. text++;
  188811. text_ptr = (png_textp)png_malloc(png_ptr,
  188812. (png_uint_32)png_sizeof(png_text));
  188813. text_ptr->compression = comp_flag + 2;
  188814. text_ptr->key = key;
  188815. text_ptr->lang = lang;
  188816. text_ptr->lang_key = lang_key;
  188817. text_ptr->text = text;
  188818. text_ptr->text_length = 0;
  188819. text_ptr->itxt_length = png_strlen(text);
  188820. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  188821. png_ptr->current_text = NULL;
  188822. png_free(png_ptr, text_ptr);
  188823. if (ret)
  188824. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  188825. }
  188826. }
  188827. #endif
  188828. /* This function is called when we haven't found a handler for this
  188829. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  188830. * name or a critical chunk), the chunk is (currently) silently ignored.
  188831. */
  188832. void /* PRIVATE */
  188833. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  188834. length)
  188835. {
  188836. png_uint_32 skip=0;
  188837. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  188838. if (!(png_ptr->chunk_name[0] & 0x20))
  188839. {
  188840. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  188841. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  188842. PNG_HANDLE_CHUNK_ALWAYS
  188843. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  188844. && png_ptr->read_user_chunk_fn == NULL
  188845. #endif
  188846. )
  188847. #endif
  188848. png_chunk_error(png_ptr, "unknown critical chunk");
  188849. info_ptr = info_ptr; /* to quiet some compiler warnings */
  188850. }
  188851. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  188852. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  188853. {
  188854. #ifdef PNG_MAX_MALLOC_64K
  188855. if (length > (png_uint_32)65535L)
  188856. {
  188857. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  188858. skip = length - (png_uint_32)65535L;
  188859. length = (png_uint_32)65535L;
  188860. }
  188861. #endif
  188862. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  188863. (png_charp)png_ptr->chunk_name, 5);
  188864. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  188865. png_ptr->unknown_chunk.size = (png_size_t)length;
  188866. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  188867. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  188868. if(png_ptr->read_user_chunk_fn != NULL)
  188869. {
  188870. /* callback to user unknown chunk handler */
  188871. int ret;
  188872. ret = (*(png_ptr->read_user_chunk_fn))
  188873. (png_ptr, &png_ptr->unknown_chunk);
  188874. if (ret < 0)
  188875. png_chunk_error(png_ptr, "error in user chunk");
  188876. if (ret == 0)
  188877. {
  188878. if (!(png_ptr->chunk_name[0] & 0x20))
  188879. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  188880. PNG_HANDLE_CHUNK_ALWAYS)
  188881. png_chunk_error(png_ptr, "unknown critical chunk");
  188882. png_set_unknown_chunks(png_ptr, info_ptr,
  188883. &png_ptr->unknown_chunk, 1);
  188884. }
  188885. }
  188886. #else
  188887. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  188888. #endif
  188889. png_free(png_ptr, png_ptr->unknown_chunk.data);
  188890. png_ptr->unknown_chunk.data = NULL;
  188891. }
  188892. else
  188893. #endif
  188894. skip=length;
  188895. png_push_crc_skip(png_ptr, skip);
  188896. }
  188897. void /* PRIVATE */
  188898. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  188899. {
  188900. if (png_ptr->info_fn != NULL)
  188901. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  188902. }
  188903. void /* PRIVATE */
  188904. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  188905. {
  188906. if (png_ptr->end_fn != NULL)
  188907. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  188908. }
  188909. void /* PRIVATE */
  188910. png_push_have_row(png_structp png_ptr, png_bytep row)
  188911. {
  188912. if (png_ptr->row_fn != NULL)
  188913. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  188914. (int)png_ptr->pass);
  188915. }
  188916. void PNGAPI
  188917. png_progressive_combine_row (png_structp png_ptr,
  188918. png_bytep old_row, png_bytep new_row)
  188919. {
  188920. #ifdef PNG_USE_LOCAL_ARRAYS
  188921. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  188922. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  188923. #endif
  188924. if(png_ptr == NULL) return;
  188925. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  188926. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  188927. }
  188928. void PNGAPI
  188929. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  188930. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  188931. png_progressive_end_ptr end_fn)
  188932. {
  188933. if(png_ptr == NULL) return;
  188934. png_ptr->info_fn = info_fn;
  188935. png_ptr->row_fn = row_fn;
  188936. png_ptr->end_fn = end_fn;
  188937. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  188938. }
  188939. png_voidp PNGAPI
  188940. png_get_progressive_ptr(png_structp png_ptr)
  188941. {
  188942. if(png_ptr == NULL) return (NULL);
  188943. return png_ptr->io_ptr;
  188944. }
  188945. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  188946. /*** End of inlined file: pngpread.c ***/
  188947. /*** Start of inlined file: pngrio.c ***/
  188948. /* pngrio.c - functions for data input
  188949. *
  188950. * Last changed in libpng 1.2.13 November 13, 2006
  188951. * For conditions of distribution and use, see copyright notice in png.h
  188952. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  188953. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  188954. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  188955. *
  188956. * This file provides a location for all input. Users who need
  188957. * special handling are expected to write a function that has the same
  188958. * arguments as this and performs a similar function, but that possibly
  188959. * has a different input method. Note that you shouldn't change this
  188960. * function, but rather write a replacement function and then make
  188961. * libpng use it at run time with png_set_read_fn(...).
  188962. */
  188963. #define PNG_INTERNAL
  188964. #if defined(PNG_READ_SUPPORTED)
  188965. /* Read the data from whatever input you are using. The default routine
  188966. reads from a file pointer. Note that this routine sometimes gets called
  188967. with very small lengths, so you should implement some kind of simple
  188968. buffering if you are using unbuffered reads. This should never be asked
  188969. to read more then 64K on a 16 bit machine. */
  188970. void /* PRIVATE */
  188971. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  188972. {
  188973. png_debug1(4,"reading %d bytes\n", (int)length);
  188974. if (png_ptr->read_data_fn != NULL)
  188975. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  188976. else
  188977. png_error(png_ptr, "Call to NULL read function");
  188978. }
  188979. #if !defined(PNG_NO_STDIO)
  188980. /* This is the function that does the actual reading of data. If you are
  188981. not reading from a standard C stream, you should create a replacement
  188982. read_data function and use it at run time with png_set_read_fn(), rather
  188983. than changing the library. */
  188984. #ifndef USE_FAR_KEYWORD
  188985. void PNGAPI
  188986. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  188987. {
  188988. png_size_t check;
  188989. if(png_ptr == NULL) return;
  188990. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  188991. * instead of an int, which is what fread() actually returns.
  188992. */
  188993. #if defined(_WIN32_WCE)
  188994. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  188995. check = 0;
  188996. #else
  188997. check = (png_size_t)fread(data, (png_size_t)1, length,
  188998. (png_FILE_p)png_ptr->io_ptr);
  188999. #endif
  189000. if (check != length)
  189001. png_error(png_ptr, "Read Error");
  189002. }
  189003. #else
  189004. /* this is the model-independent version. Since the standard I/O library
  189005. can't handle far buffers in the medium and small models, we have to copy
  189006. the data.
  189007. */
  189008. #define NEAR_BUF_SIZE 1024
  189009. #define MIN(a,b) (a <= b ? a : b)
  189010. static void PNGAPI
  189011. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189012. {
  189013. int check;
  189014. png_byte *n_data;
  189015. png_FILE_p io_ptr;
  189016. if(png_ptr == NULL) return;
  189017. /* Check if data really is near. If so, use usual code. */
  189018. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  189019. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  189020. if ((png_bytep)n_data == data)
  189021. {
  189022. #if defined(_WIN32_WCE)
  189023. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  189024. check = 0;
  189025. #else
  189026. check = fread(n_data, 1, length, io_ptr);
  189027. #endif
  189028. }
  189029. else
  189030. {
  189031. png_byte buf[NEAR_BUF_SIZE];
  189032. png_size_t read, remaining, err;
  189033. check = 0;
  189034. remaining = length;
  189035. do
  189036. {
  189037. read = MIN(NEAR_BUF_SIZE, remaining);
  189038. #if defined(_WIN32_WCE)
  189039. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  189040. err = 0;
  189041. #else
  189042. err = fread(buf, (png_size_t)1, read, io_ptr);
  189043. #endif
  189044. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  189045. if(err != read)
  189046. break;
  189047. else
  189048. check += err;
  189049. data += read;
  189050. remaining -= read;
  189051. }
  189052. while (remaining != 0);
  189053. }
  189054. if ((png_uint_32)check != (png_uint_32)length)
  189055. png_error(png_ptr, "read Error");
  189056. }
  189057. #endif
  189058. #endif
  189059. /* This function allows the application to supply a new input function
  189060. for libpng if standard C streams aren't being used.
  189061. This function takes as its arguments:
  189062. png_ptr - pointer to a png input data structure
  189063. io_ptr - pointer to user supplied structure containing info about
  189064. the input functions. May be NULL.
  189065. read_data_fn - pointer to a new input function that takes as its
  189066. arguments a pointer to a png_struct, a pointer to
  189067. a location where input data can be stored, and a 32-bit
  189068. unsigned int that is the number of bytes to be read.
  189069. To exit and output any fatal error messages the new write
  189070. function should call png_error(png_ptr, "Error msg"). */
  189071. void PNGAPI
  189072. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  189073. png_rw_ptr read_data_fn)
  189074. {
  189075. if(png_ptr == NULL) return;
  189076. png_ptr->io_ptr = io_ptr;
  189077. #if !defined(PNG_NO_STDIO)
  189078. if (read_data_fn != NULL)
  189079. png_ptr->read_data_fn = read_data_fn;
  189080. else
  189081. png_ptr->read_data_fn = png_default_read_data;
  189082. #else
  189083. png_ptr->read_data_fn = read_data_fn;
  189084. #endif
  189085. /* It is an error to write to a read device */
  189086. if (png_ptr->write_data_fn != NULL)
  189087. {
  189088. png_ptr->write_data_fn = NULL;
  189089. png_warning(png_ptr,
  189090. "It's an error to set both read_data_fn and write_data_fn in the ");
  189091. png_warning(png_ptr,
  189092. "same structure. Resetting write_data_fn to NULL.");
  189093. }
  189094. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  189095. png_ptr->output_flush_fn = NULL;
  189096. #endif
  189097. }
  189098. #endif /* PNG_READ_SUPPORTED */
  189099. /*** End of inlined file: pngrio.c ***/
  189100. /*** Start of inlined file: pngrtran.c ***/
  189101. /* pngrtran.c - transforms the data in a row for PNG readers
  189102. *
  189103. * Last changed in libpng 1.2.21 [October 4, 2007]
  189104. * For conditions of distribution and use, see copyright notice in png.h
  189105. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  189106. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  189107. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  189108. *
  189109. * This file contains functions optionally called by an application
  189110. * in order to tell libpng how to handle data when reading a PNG.
  189111. * Transformations that are used in both reading and writing are
  189112. * in pngtrans.c.
  189113. */
  189114. #define PNG_INTERNAL
  189115. #if defined(PNG_READ_SUPPORTED)
  189116. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  189117. void PNGAPI
  189118. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  189119. {
  189120. png_debug(1, "in png_set_crc_action\n");
  189121. /* Tell libpng how we react to CRC errors in critical chunks */
  189122. if(png_ptr == NULL) return;
  189123. switch (crit_action)
  189124. {
  189125. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  189126. break;
  189127. case PNG_CRC_WARN_USE: /* warn/use data */
  189128. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189129. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  189130. break;
  189131. case PNG_CRC_QUIET_USE: /* quiet/use data */
  189132. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189133. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  189134. PNG_FLAG_CRC_CRITICAL_IGNORE;
  189135. break;
  189136. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  189137. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  189138. case PNG_CRC_ERROR_QUIT: /* error/quit */
  189139. case PNG_CRC_DEFAULT:
  189140. default:
  189141. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189142. break;
  189143. }
  189144. switch (ancil_action)
  189145. {
  189146. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  189147. break;
  189148. case PNG_CRC_WARN_USE: /* warn/use data */
  189149. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189150. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  189151. break;
  189152. case PNG_CRC_QUIET_USE: /* quiet/use data */
  189153. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189154. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  189155. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  189156. break;
  189157. case PNG_CRC_ERROR_QUIT: /* error/quit */
  189158. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189159. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  189160. break;
  189161. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  189162. case PNG_CRC_DEFAULT:
  189163. default:
  189164. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189165. break;
  189166. }
  189167. }
  189168. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  189169. defined(PNG_FLOATING_POINT_SUPPORTED)
  189170. /* handle alpha and tRNS via a background color */
  189171. void PNGAPI
  189172. png_set_background(png_structp png_ptr,
  189173. png_color_16p background_color, int background_gamma_code,
  189174. int need_expand, double background_gamma)
  189175. {
  189176. png_debug(1, "in png_set_background\n");
  189177. if(png_ptr == NULL) return;
  189178. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  189179. {
  189180. png_warning(png_ptr, "Application must supply a known background gamma");
  189181. return;
  189182. }
  189183. png_ptr->transformations |= PNG_BACKGROUND;
  189184. png_memcpy(&(png_ptr->background), background_color,
  189185. png_sizeof(png_color_16));
  189186. png_ptr->background_gamma = (float)background_gamma;
  189187. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  189188. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  189189. }
  189190. #endif
  189191. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  189192. /* strip 16 bit depth files to 8 bit depth */
  189193. void PNGAPI
  189194. png_set_strip_16(png_structp png_ptr)
  189195. {
  189196. png_debug(1, "in png_set_strip_16\n");
  189197. if(png_ptr == NULL) return;
  189198. png_ptr->transformations |= PNG_16_TO_8;
  189199. }
  189200. #endif
  189201. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  189202. void PNGAPI
  189203. png_set_strip_alpha(png_structp png_ptr)
  189204. {
  189205. png_debug(1, "in png_set_strip_alpha\n");
  189206. if(png_ptr == NULL) return;
  189207. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  189208. }
  189209. #endif
  189210. #if defined(PNG_READ_DITHER_SUPPORTED)
  189211. /* Dither file to 8 bit. Supply a palette, the current number
  189212. * of elements in the palette, the maximum number of elements
  189213. * allowed, and a histogram if possible. If the current number
  189214. * of colors is greater then the maximum number, the palette will be
  189215. * modified to fit in the maximum number. "full_dither" indicates
  189216. * whether we need a dithering cube set up for RGB images, or if we
  189217. * simply are reducing the number of colors in a paletted image.
  189218. */
  189219. typedef struct png_dsort_struct
  189220. {
  189221. struct png_dsort_struct FAR * next;
  189222. png_byte left;
  189223. png_byte right;
  189224. } png_dsort;
  189225. typedef png_dsort FAR * png_dsortp;
  189226. typedef png_dsort FAR * FAR * png_dsortpp;
  189227. void PNGAPI
  189228. png_set_dither(png_structp png_ptr, png_colorp palette,
  189229. int num_palette, int maximum_colors, png_uint_16p histogram,
  189230. int full_dither)
  189231. {
  189232. png_debug(1, "in png_set_dither\n");
  189233. if(png_ptr == NULL) return;
  189234. png_ptr->transformations |= PNG_DITHER;
  189235. if (!full_dither)
  189236. {
  189237. int i;
  189238. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  189239. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189240. for (i = 0; i < num_palette; i++)
  189241. png_ptr->dither_index[i] = (png_byte)i;
  189242. }
  189243. if (num_palette > maximum_colors)
  189244. {
  189245. if (histogram != NULL)
  189246. {
  189247. /* This is easy enough, just throw out the least used colors.
  189248. Perhaps not the best solution, but good enough. */
  189249. int i;
  189250. /* initialize an array to sort colors */
  189251. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  189252. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189253. /* initialize the dither_sort array */
  189254. for (i = 0; i < num_palette; i++)
  189255. png_ptr->dither_sort[i] = (png_byte)i;
  189256. /* Find the least used palette entries by starting a
  189257. bubble sort, and running it until we have sorted
  189258. out enough colors. Note that we don't care about
  189259. sorting all the colors, just finding which are
  189260. least used. */
  189261. for (i = num_palette - 1; i >= maximum_colors; i--)
  189262. {
  189263. int done; /* to stop early if the list is pre-sorted */
  189264. int j;
  189265. done = 1;
  189266. for (j = 0; j < i; j++)
  189267. {
  189268. if (histogram[png_ptr->dither_sort[j]]
  189269. < histogram[png_ptr->dither_sort[j + 1]])
  189270. {
  189271. png_byte t;
  189272. t = png_ptr->dither_sort[j];
  189273. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  189274. png_ptr->dither_sort[j + 1] = t;
  189275. done = 0;
  189276. }
  189277. }
  189278. if (done)
  189279. break;
  189280. }
  189281. /* swap the palette around, and set up a table, if necessary */
  189282. if (full_dither)
  189283. {
  189284. int j = num_palette;
  189285. /* put all the useful colors within the max, but don't
  189286. move the others */
  189287. for (i = 0; i < maximum_colors; i++)
  189288. {
  189289. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  189290. {
  189291. do
  189292. j--;
  189293. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  189294. palette[i] = palette[j];
  189295. }
  189296. }
  189297. }
  189298. else
  189299. {
  189300. int j = num_palette;
  189301. /* move all the used colors inside the max limit, and
  189302. develop a translation table */
  189303. for (i = 0; i < maximum_colors; i++)
  189304. {
  189305. /* only move the colors we need to */
  189306. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  189307. {
  189308. png_color tmp_color;
  189309. do
  189310. j--;
  189311. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  189312. tmp_color = palette[j];
  189313. palette[j] = palette[i];
  189314. palette[i] = tmp_color;
  189315. /* indicate where the color went */
  189316. png_ptr->dither_index[j] = (png_byte)i;
  189317. png_ptr->dither_index[i] = (png_byte)j;
  189318. }
  189319. }
  189320. /* find closest color for those colors we are not using */
  189321. for (i = 0; i < num_palette; i++)
  189322. {
  189323. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  189324. {
  189325. int min_d, k, min_k, d_index;
  189326. /* find the closest color to one we threw out */
  189327. d_index = png_ptr->dither_index[i];
  189328. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  189329. for (k = 1, min_k = 0; k < maximum_colors; k++)
  189330. {
  189331. int d;
  189332. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  189333. if (d < min_d)
  189334. {
  189335. min_d = d;
  189336. min_k = k;
  189337. }
  189338. }
  189339. /* point to closest color */
  189340. png_ptr->dither_index[i] = (png_byte)min_k;
  189341. }
  189342. }
  189343. }
  189344. png_free(png_ptr, png_ptr->dither_sort);
  189345. png_ptr->dither_sort=NULL;
  189346. }
  189347. else
  189348. {
  189349. /* This is much harder to do simply (and quickly). Perhaps
  189350. we need to go through a median cut routine, but those
  189351. don't always behave themselves with only a few colors
  189352. as input. So we will just find the closest two colors,
  189353. and throw out one of them (chosen somewhat randomly).
  189354. [We don't understand this at all, so if someone wants to
  189355. work on improving it, be our guest - AED, GRP]
  189356. */
  189357. int i;
  189358. int max_d;
  189359. int num_new_palette;
  189360. png_dsortp t;
  189361. png_dsortpp hash;
  189362. t=NULL;
  189363. /* initialize palette index arrays */
  189364. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  189365. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189366. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  189367. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189368. /* initialize the sort array */
  189369. for (i = 0; i < num_palette; i++)
  189370. {
  189371. png_ptr->index_to_palette[i] = (png_byte)i;
  189372. png_ptr->palette_to_index[i] = (png_byte)i;
  189373. }
  189374. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  189375. png_sizeof (png_dsortp)));
  189376. for (i = 0; i < 769; i++)
  189377. hash[i] = NULL;
  189378. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  189379. num_new_palette = num_palette;
  189380. /* initial wild guess at how far apart the farthest pixel
  189381. pair we will be eliminating will be. Larger
  189382. numbers mean more areas will be allocated, Smaller
  189383. numbers run the risk of not saving enough data, and
  189384. having to do this all over again.
  189385. I have not done extensive checking on this number.
  189386. */
  189387. max_d = 96;
  189388. while (num_new_palette > maximum_colors)
  189389. {
  189390. for (i = 0; i < num_new_palette - 1; i++)
  189391. {
  189392. int j;
  189393. for (j = i + 1; j < num_new_palette; j++)
  189394. {
  189395. int d;
  189396. d = PNG_COLOR_DIST(palette[i], palette[j]);
  189397. if (d <= max_d)
  189398. {
  189399. t = (png_dsortp)png_malloc_warn(png_ptr,
  189400. (png_uint_32)(png_sizeof(png_dsort)));
  189401. if (t == NULL)
  189402. break;
  189403. t->next = hash[d];
  189404. t->left = (png_byte)i;
  189405. t->right = (png_byte)j;
  189406. hash[d] = t;
  189407. }
  189408. }
  189409. if (t == NULL)
  189410. break;
  189411. }
  189412. if (t != NULL)
  189413. for (i = 0; i <= max_d; i++)
  189414. {
  189415. if (hash[i] != NULL)
  189416. {
  189417. png_dsortp p;
  189418. for (p = hash[i]; p; p = p->next)
  189419. {
  189420. if ((int)png_ptr->index_to_palette[p->left]
  189421. < num_new_palette &&
  189422. (int)png_ptr->index_to_palette[p->right]
  189423. < num_new_palette)
  189424. {
  189425. int j, next_j;
  189426. if (num_new_palette & 0x01)
  189427. {
  189428. j = p->left;
  189429. next_j = p->right;
  189430. }
  189431. else
  189432. {
  189433. j = p->right;
  189434. next_j = p->left;
  189435. }
  189436. num_new_palette--;
  189437. palette[png_ptr->index_to_palette[j]]
  189438. = palette[num_new_palette];
  189439. if (!full_dither)
  189440. {
  189441. int k;
  189442. for (k = 0; k < num_palette; k++)
  189443. {
  189444. if (png_ptr->dither_index[k] ==
  189445. png_ptr->index_to_palette[j])
  189446. png_ptr->dither_index[k] =
  189447. png_ptr->index_to_palette[next_j];
  189448. if ((int)png_ptr->dither_index[k] ==
  189449. num_new_palette)
  189450. png_ptr->dither_index[k] =
  189451. png_ptr->index_to_palette[j];
  189452. }
  189453. }
  189454. png_ptr->index_to_palette[png_ptr->palette_to_index
  189455. [num_new_palette]] = png_ptr->index_to_palette[j];
  189456. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  189457. = png_ptr->palette_to_index[num_new_palette];
  189458. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  189459. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  189460. }
  189461. if (num_new_palette <= maximum_colors)
  189462. break;
  189463. }
  189464. if (num_new_palette <= maximum_colors)
  189465. break;
  189466. }
  189467. }
  189468. for (i = 0; i < 769; i++)
  189469. {
  189470. if (hash[i] != NULL)
  189471. {
  189472. png_dsortp p = hash[i];
  189473. while (p)
  189474. {
  189475. t = p->next;
  189476. png_free(png_ptr, p);
  189477. p = t;
  189478. }
  189479. }
  189480. hash[i] = 0;
  189481. }
  189482. max_d += 96;
  189483. }
  189484. png_free(png_ptr, hash);
  189485. png_free(png_ptr, png_ptr->palette_to_index);
  189486. png_free(png_ptr, png_ptr->index_to_palette);
  189487. png_ptr->palette_to_index=NULL;
  189488. png_ptr->index_to_palette=NULL;
  189489. }
  189490. num_palette = maximum_colors;
  189491. }
  189492. if (png_ptr->palette == NULL)
  189493. {
  189494. png_ptr->palette = palette;
  189495. }
  189496. png_ptr->num_palette = (png_uint_16)num_palette;
  189497. if (full_dither)
  189498. {
  189499. int i;
  189500. png_bytep distance;
  189501. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  189502. PNG_DITHER_BLUE_BITS;
  189503. int num_red = (1 << PNG_DITHER_RED_BITS);
  189504. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  189505. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  189506. png_size_t num_entries = ((png_size_t)1 << total_bits);
  189507. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  189508. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  189509. png_memset(png_ptr->palette_lookup, 0, num_entries *
  189510. png_sizeof (png_byte));
  189511. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  189512. png_sizeof(png_byte)));
  189513. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  189514. for (i = 0; i < num_palette; i++)
  189515. {
  189516. int ir, ig, ib;
  189517. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  189518. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  189519. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  189520. for (ir = 0; ir < num_red; ir++)
  189521. {
  189522. /* int dr = abs(ir - r); */
  189523. int dr = ((ir > r) ? ir - r : r - ir);
  189524. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  189525. for (ig = 0; ig < num_green; ig++)
  189526. {
  189527. /* int dg = abs(ig - g); */
  189528. int dg = ((ig > g) ? ig - g : g - ig);
  189529. int dt = dr + dg;
  189530. int dm = ((dr > dg) ? dr : dg);
  189531. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  189532. for (ib = 0; ib < num_blue; ib++)
  189533. {
  189534. int d_index = index_g | ib;
  189535. /* int db = abs(ib - b); */
  189536. int db = ((ib > b) ? ib - b : b - ib);
  189537. int dmax = ((dm > db) ? dm : db);
  189538. int d = dmax + dt + db;
  189539. if (d < (int)distance[d_index])
  189540. {
  189541. distance[d_index] = (png_byte)d;
  189542. png_ptr->palette_lookup[d_index] = (png_byte)i;
  189543. }
  189544. }
  189545. }
  189546. }
  189547. }
  189548. png_free(png_ptr, distance);
  189549. }
  189550. }
  189551. #endif
  189552. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  189553. /* Transform the image from the file_gamma to the screen_gamma. We
  189554. * only do transformations on images where the file_gamma and screen_gamma
  189555. * are not close reciprocals, otherwise it slows things down slightly, and
  189556. * also needlessly introduces small errors.
  189557. *
  189558. * We will turn off gamma transformation later if no semitransparent entries
  189559. * are present in the tRNS array for palette images. We can't do it here
  189560. * because we don't necessarily have the tRNS chunk yet.
  189561. */
  189562. void PNGAPI
  189563. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  189564. {
  189565. png_debug(1, "in png_set_gamma\n");
  189566. if(png_ptr == NULL) return;
  189567. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  189568. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  189569. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  189570. png_ptr->transformations |= PNG_GAMMA;
  189571. png_ptr->gamma = (float)file_gamma;
  189572. png_ptr->screen_gamma = (float)scrn_gamma;
  189573. }
  189574. #endif
  189575. #if defined(PNG_READ_EXPAND_SUPPORTED)
  189576. /* Expand paletted images to RGB, expand grayscale images of
  189577. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  189578. * to alpha channels.
  189579. */
  189580. void PNGAPI
  189581. png_set_expand(png_structp png_ptr)
  189582. {
  189583. png_debug(1, "in png_set_expand\n");
  189584. if(png_ptr == NULL) return;
  189585. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  189586. #ifdef PNG_WARN_UNINITIALIZED_ROW
  189587. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  189588. #endif
  189589. }
  189590. /* GRR 19990627: the following three functions currently are identical
  189591. * to png_set_expand(). However, it is entirely reasonable that someone
  189592. * might wish to expand an indexed image to RGB but *not* expand a single,
  189593. * fully transparent palette entry to a full alpha channel--perhaps instead
  189594. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  189595. * the transparent color with a particular RGB value, or drop tRNS entirely.
  189596. * IOW, a future version of the library may make the transformations flag
  189597. * a bit more fine-grained, with separate bits for each of these three
  189598. * functions.
  189599. *
  189600. * More to the point, these functions make it obvious what libpng will be
  189601. * doing, whereas "expand" can (and does) mean any number of things.
  189602. *
  189603. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  189604. * to expand only the sample depth but not to expand the tRNS to alpha.
  189605. */
  189606. /* Expand paletted images to RGB. */
  189607. void PNGAPI
  189608. png_set_palette_to_rgb(png_structp png_ptr)
  189609. {
  189610. png_debug(1, "in png_set_palette_to_rgb\n");
  189611. if(png_ptr == NULL) return;
  189612. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  189613. #ifdef PNG_WARN_UNINITIALIZED_ROW
  189614. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  189615. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  189616. #endif
  189617. }
  189618. #if !defined(PNG_1_0_X)
  189619. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  189620. void PNGAPI
  189621. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  189622. {
  189623. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  189624. if(png_ptr == NULL) return;
  189625. png_ptr->transformations |= PNG_EXPAND;
  189626. #ifdef PNG_WARN_UNINITIALIZED_ROW
  189627. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  189628. #endif
  189629. }
  189630. #endif
  189631. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  189632. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  189633. /* Deprecated as of libpng-1.2.9 */
  189634. void PNGAPI
  189635. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  189636. {
  189637. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  189638. if(png_ptr == NULL) return;
  189639. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  189640. }
  189641. #endif
  189642. /* Expand tRNS chunks to alpha channels. */
  189643. void PNGAPI
  189644. png_set_tRNS_to_alpha(png_structp png_ptr)
  189645. {
  189646. png_debug(1, "in png_set_tRNS_to_alpha\n");
  189647. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  189648. #ifdef PNG_WARN_UNINITIALIZED_ROW
  189649. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  189650. #endif
  189651. }
  189652. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  189653. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  189654. void PNGAPI
  189655. png_set_gray_to_rgb(png_structp png_ptr)
  189656. {
  189657. png_debug(1, "in png_set_gray_to_rgb\n");
  189658. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  189659. #ifdef PNG_WARN_UNINITIALIZED_ROW
  189660. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  189661. #endif
  189662. }
  189663. #endif
  189664. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  189665. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  189666. /* Convert a RGB image to a grayscale of the same width. This allows us,
  189667. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  189668. */
  189669. void PNGAPI
  189670. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  189671. double green)
  189672. {
  189673. int red_fixed = (int)((float)red*100000.0 + 0.5);
  189674. int green_fixed = (int)((float)green*100000.0 + 0.5);
  189675. if(png_ptr == NULL) return;
  189676. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  189677. }
  189678. #endif
  189679. void PNGAPI
  189680. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  189681. png_fixed_point red, png_fixed_point green)
  189682. {
  189683. png_debug(1, "in png_set_rgb_to_gray\n");
  189684. if(png_ptr == NULL) return;
  189685. switch(error_action)
  189686. {
  189687. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  189688. break;
  189689. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  189690. break;
  189691. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  189692. }
  189693. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  189694. #if defined(PNG_READ_EXPAND_SUPPORTED)
  189695. png_ptr->transformations |= PNG_EXPAND;
  189696. #else
  189697. {
  189698. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  189699. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  189700. }
  189701. #endif
  189702. {
  189703. png_uint_16 red_int, green_int;
  189704. if(red < 0 || green < 0)
  189705. {
  189706. red_int = 6968; /* .212671 * 32768 + .5 */
  189707. green_int = 23434; /* .715160 * 32768 + .5 */
  189708. }
  189709. else if(red + green < 100000L)
  189710. {
  189711. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  189712. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  189713. }
  189714. else
  189715. {
  189716. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  189717. red_int = 6968;
  189718. green_int = 23434;
  189719. }
  189720. png_ptr->rgb_to_gray_red_coeff = red_int;
  189721. png_ptr->rgb_to_gray_green_coeff = green_int;
  189722. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  189723. }
  189724. }
  189725. #endif
  189726. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  189727. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  189728. defined(PNG_LEGACY_SUPPORTED)
  189729. void PNGAPI
  189730. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  189731. read_user_transform_fn)
  189732. {
  189733. png_debug(1, "in png_set_read_user_transform_fn\n");
  189734. if(png_ptr == NULL) return;
  189735. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  189736. png_ptr->transformations |= PNG_USER_TRANSFORM;
  189737. png_ptr->read_user_transform_fn = read_user_transform_fn;
  189738. #endif
  189739. #ifdef PNG_LEGACY_SUPPORTED
  189740. if(read_user_transform_fn)
  189741. png_warning(png_ptr,
  189742. "This version of libpng does not support user transforms");
  189743. #endif
  189744. }
  189745. #endif
  189746. /* Initialize everything needed for the read. This includes modifying
  189747. * the palette.
  189748. */
  189749. void /* PRIVATE */
  189750. png_init_read_transformations(png_structp png_ptr)
  189751. {
  189752. png_debug(1, "in png_init_read_transformations\n");
  189753. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  189754. if(png_ptr != NULL)
  189755. #endif
  189756. {
  189757. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  189758. || defined(PNG_READ_GAMMA_SUPPORTED)
  189759. int color_type = png_ptr->color_type;
  189760. #endif
  189761. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  189762. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  189763. /* Detect gray background and attempt to enable optimization
  189764. * for gray --> RGB case */
  189765. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  189766. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  189767. * background color might actually be gray yet not be flagged as such.
  189768. * This is not a problem for the current code, which uses
  189769. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  189770. * png_do_gray_to_rgb() transformation.
  189771. */
  189772. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  189773. !(color_type & PNG_COLOR_MASK_COLOR))
  189774. {
  189775. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  189776. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  189777. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  189778. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  189779. png_ptr->background.red == png_ptr->background.green &&
  189780. png_ptr->background.red == png_ptr->background.blue)
  189781. {
  189782. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  189783. png_ptr->background.gray = png_ptr->background.red;
  189784. }
  189785. #endif
  189786. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  189787. (png_ptr->transformations & PNG_EXPAND))
  189788. {
  189789. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  189790. {
  189791. /* expand background and tRNS chunks */
  189792. switch (png_ptr->bit_depth)
  189793. {
  189794. case 1:
  189795. png_ptr->background.gray *= (png_uint_16)0xff;
  189796. png_ptr->background.red = png_ptr->background.green
  189797. = png_ptr->background.blue = png_ptr->background.gray;
  189798. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  189799. {
  189800. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  189801. png_ptr->trans_values.red = png_ptr->trans_values.green
  189802. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  189803. }
  189804. break;
  189805. case 2:
  189806. png_ptr->background.gray *= (png_uint_16)0x55;
  189807. png_ptr->background.red = png_ptr->background.green
  189808. = png_ptr->background.blue = png_ptr->background.gray;
  189809. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  189810. {
  189811. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  189812. png_ptr->trans_values.red = png_ptr->trans_values.green
  189813. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  189814. }
  189815. break;
  189816. case 4:
  189817. png_ptr->background.gray *= (png_uint_16)0x11;
  189818. png_ptr->background.red = png_ptr->background.green
  189819. = png_ptr->background.blue = png_ptr->background.gray;
  189820. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  189821. {
  189822. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  189823. png_ptr->trans_values.red = png_ptr->trans_values.green
  189824. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  189825. }
  189826. break;
  189827. case 8:
  189828. case 16:
  189829. png_ptr->background.red = png_ptr->background.green
  189830. = png_ptr->background.blue = png_ptr->background.gray;
  189831. break;
  189832. }
  189833. }
  189834. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  189835. {
  189836. png_ptr->background.red =
  189837. png_ptr->palette[png_ptr->background.index].red;
  189838. png_ptr->background.green =
  189839. png_ptr->palette[png_ptr->background.index].green;
  189840. png_ptr->background.blue =
  189841. png_ptr->palette[png_ptr->background.index].blue;
  189842. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  189843. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  189844. {
  189845. #if defined(PNG_READ_EXPAND_SUPPORTED)
  189846. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  189847. #endif
  189848. {
  189849. /* invert the alpha channel (in tRNS) unless the pixels are
  189850. going to be expanded, in which case leave it for later */
  189851. int i,istop;
  189852. istop=(int)png_ptr->num_trans;
  189853. for (i=0; i<istop; i++)
  189854. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  189855. }
  189856. }
  189857. #endif
  189858. }
  189859. }
  189860. #endif
  189861. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  189862. png_ptr->background_1 = png_ptr->background;
  189863. #endif
  189864. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  189865. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  189866. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  189867. < PNG_GAMMA_THRESHOLD))
  189868. {
  189869. int i,k;
  189870. k=0;
  189871. for (i=0; i<png_ptr->num_trans; i++)
  189872. {
  189873. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  189874. k=1; /* partial transparency is present */
  189875. }
  189876. if (k == 0)
  189877. png_ptr->transformations &= (~PNG_GAMMA);
  189878. }
  189879. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  189880. png_ptr->gamma != 0.0)
  189881. {
  189882. png_build_gamma_table(png_ptr);
  189883. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  189884. if (png_ptr->transformations & PNG_BACKGROUND)
  189885. {
  189886. if (color_type == PNG_COLOR_TYPE_PALETTE)
  189887. {
  189888. /* could skip if no transparency and
  189889. */
  189890. png_color back, back_1;
  189891. png_colorp palette = png_ptr->palette;
  189892. int num_palette = png_ptr->num_palette;
  189893. int i;
  189894. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  189895. {
  189896. back.red = png_ptr->gamma_table[png_ptr->background.red];
  189897. back.green = png_ptr->gamma_table[png_ptr->background.green];
  189898. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  189899. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  189900. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  189901. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  189902. }
  189903. else
  189904. {
  189905. double g, gs;
  189906. switch (png_ptr->background_gamma_type)
  189907. {
  189908. case PNG_BACKGROUND_GAMMA_SCREEN:
  189909. g = (png_ptr->screen_gamma);
  189910. gs = 1.0;
  189911. break;
  189912. case PNG_BACKGROUND_GAMMA_FILE:
  189913. g = 1.0 / (png_ptr->gamma);
  189914. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  189915. break;
  189916. case PNG_BACKGROUND_GAMMA_UNIQUE:
  189917. g = 1.0 / (png_ptr->background_gamma);
  189918. gs = 1.0 / (png_ptr->background_gamma *
  189919. png_ptr->screen_gamma);
  189920. break;
  189921. default:
  189922. g = 1.0; /* back_1 */
  189923. gs = 1.0; /* back */
  189924. }
  189925. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  189926. {
  189927. back.red = (png_byte)png_ptr->background.red;
  189928. back.green = (png_byte)png_ptr->background.green;
  189929. back.blue = (png_byte)png_ptr->background.blue;
  189930. }
  189931. else
  189932. {
  189933. back.red = (png_byte)(pow(
  189934. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  189935. back.green = (png_byte)(pow(
  189936. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  189937. back.blue = (png_byte)(pow(
  189938. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  189939. }
  189940. back_1.red = (png_byte)(pow(
  189941. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  189942. back_1.green = (png_byte)(pow(
  189943. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  189944. back_1.blue = (png_byte)(pow(
  189945. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  189946. }
  189947. for (i = 0; i < num_palette; i++)
  189948. {
  189949. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  189950. {
  189951. if (png_ptr->trans[i] == 0)
  189952. {
  189953. palette[i] = back;
  189954. }
  189955. else /* if (png_ptr->trans[i] != 0xff) */
  189956. {
  189957. png_byte v, w;
  189958. v = png_ptr->gamma_to_1[palette[i].red];
  189959. png_composite(w, v, png_ptr->trans[i], back_1.red);
  189960. palette[i].red = png_ptr->gamma_from_1[w];
  189961. v = png_ptr->gamma_to_1[palette[i].green];
  189962. png_composite(w, v, png_ptr->trans[i], back_1.green);
  189963. palette[i].green = png_ptr->gamma_from_1[w];
  189964. v = png_ptr->gamma_to_1[palette[i].blue];
  189965. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  189966. palette[i].blue = png_ptr->gamma_from_1[w];
  189967. }
  189968. }
  189969. else
  189970. {
  189971. palette[i].red = png_ptr->gamma_table[palette[i].red];
  189972. palette[i].green = png_ptr->gamma_table[palette[i].green];
  189973. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  189974. }
  189975. }
  189976. }
  189977. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  189978. else
  189979. /* color_type != PNG_COLOR_TYPE_PALETTE */
  189980. {
  189981. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  189982. double g = 1.0;
  189983. double gs = 1.0;
  189984. switch (png_ptr->background_gamma_type)
  189985. {
  189986. case PNG_BACKGROUND_GAMMA_SCREEN:
  189987. g = (png_ptr->screen_gamma);
  189988. gs = 1.0;
  189989. break;
  189990. case PNG_BACKGROUND_GAMMA_FILE:
  189991. g = 1.0 / (png_ptr->gamma);
  189992. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  189993. break;
  189994. case PNG_BACKGROUND_GAMMA_UNIQUE:
  189995. g = 1.0 / (png_ptr->background_gamma);
  189996. gs = 1.0 / (png_ptr->background_gamma *
  189997. png_ptr->screen_gamma);
  189998. break;
  189999. }
  190000. png_ptr->background_1.gray = (png_uint_16)(pow(
  190001. (double)png_ptr->background.gray / m, g) * m + .5);
  190002. png_ptr->background.gray = (png_uint_16)(pow(
  190003. (double)png_ptr->background.gray / m, gs) * m + .5);
  190004. if ((png_ptr->background.red != png_ptr->background.green) ||
  190005. (png_ptr->background.red != png_ptr->background.blue) ||
  190006. (png_ptr->background.red != png_ptr->background.gray))
  190007. {
  190008. /* RGB or RGBA with color background */
  190009. png_ptr->background_1.red = (png_uint_16)(pow(
  190010. (double)png_ptr->background.red / m, g) * m + .5);
  190011. png_ptr->background_1.green = (png_uint_16)(pow(
  190012. (double)png_ptr->background.green / m, g) * m + .5);
  190013. png_ptr->background_1.blue = (png_uint_16)(pow(
  190014. (double)png_ptr->background.blue / m, g) * m + .5);
  190015. png_ptr->background.red = (png_uint_16)(pow(
  190016. (double)png_ptr->background.red / m, gs) * m + .5);
  190017. png_ptr->background.green = (png_uint_16)(pow(
  190018. (double)png_ptr->background.green / m, gs) * m + .5);
  190019. png_ptr->background.blue = (png_uint_16)(pow(
  190020. (double)png_ptr->background.blue / m, gs) * m + .5);
  190021. }
  190022. else
  190023. {
  190024. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  190025. png_ptr->background_1.red = png_ptr->background_1.green
  190026. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  190027. png_ptr->background.red = png_ptr->background.green
  190028. = png_ptr->background.blue = png_ptr->background.gray;
  190029. }
  190030. }
  190031. }
  190032. else
  190033. /* transformation does not include PNG_BACKGROUND */
  190034. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  190035. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190036. {
  190037. png_colorp palette = png_ptr->palette;
  190038. int num_palette = png_ptr->num_palette;
  190039. int i;
  190040. for (i = 0; i < num_palette; i++)
  190041. {
  190042. palette[i].red = png_ptr->gamma_table[palette[i].red];
  190043. palette[i].green = png_ptr->gamma_table[palette[i].green];
  190044. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  190045. }
  190046. }
  190047. }
  190048. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190049. else
  190050. #endif
  190051. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  190052. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190053. /* No GAMMA transformation */
  190054. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190055. (color_type == PNG_COLOR_TYPE_PALETTE))
  190056. {
  190057. int i;
  190058. int istop = (int)png_ptr->num_trans;
  190059. png_color back;
  190060. png_colorp palette = png_ptr->palette;
  190061. back.red = (png_byte)png_ptr->background.red;
  190062. back.green = (png_byte)png_ptr->background.green;
  190063. back.blue = (png_byte)png_ptr->background.blue;
  190064. for (i = 0; i < istop; i++)
  190065. {
  190066. if (png_ptr->trans[i] == 0)
  190067. {
  190068. palette[i] = back;
  190069. }
  190070. else if (png_ptr->trans[i] != 0xff)
  190071. {
  190072. /* The png_composite() macro is defined in png.h */
  190073. png_composite(palette[i].red, palette[i].red,
  190074. png_ptr->trans[i], back.red);
  190075. png_composite(palette[i].green, palette[i].green,
  190076. png_ptr->trans[i], back.green);
  190077. png_composite(palette[i].blue, palette[i].blue,
  190078. png_ptr->trans[i], back.blue);
  190079. }
  190080. }
  190081. }
  190082. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  190083. #if defined(PNG_READ_SHIFT_SUPPORTED)
  190084. if ((png_ptr->transformations & PNG_SHIFT) &&
  190085. (color_type == PNG_COLOR_TYPE_PALETTE))
  190086. {
  190087. png_uint_16 i;
  190088. png_uint_16 istop = png_ptr->num_palette;
  190089. int sr = 8 - png_ptr->sig_bit.red;
  190090. int sg = 8 - png_ptr->sig_bit.green;
  190091. int sb = 8 - png_ptr->sig_bit.blue;
  190092. if (sr < 0 || sr > 8)
  190093. sr = 0;
  190094. if (sg < 0 || sg > 8)
  190095. sg = 0;
  190096. if (sb < 0 || sb > 8)
  190097. sb = 0;
  190098. for (i = 0; i < istop; i++)
  190099. {
  190100. png_ptr->palette[i].red >>= sr;
  190101. png_ptr->palette[i].green >>= sg;
  190102. png_ptr->palette[i].blue >>= sb;
  190103. }
  190104. }
  190105. #endif /* PNG_READ_SHIFT_SUPPORTED */
  190106. }
  190107. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  190108. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  190109. if(png_ptr)
  190110. return;
  190111. #endif
  190112. }
  190113. /* Modify the info structure to reflect the transformations. The
  190114. * info should be updated so a PNG file could be written with it,
  190115. * assuming the transformations result in valid PNG data.
  190116. */
  190117. void /* PRIVATE */
  190118. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  190119. {
  190120. png_debug(1, "in png_read_transform_info\n");
  190121. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190122. if (png_ptr->transformations & PNG_EXPAND)
  190123. {
  190124. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190125. {
  190126. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  190127. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  190128. else
  190129. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  190130. info_ptr->bit_depth = 8;
  190131. info_ptr->num_trans = 0;
  190132. }
  190133. else
  190134. {
  190135. if (png_ptr->num_trans)
  190136. {
  190137. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  190138. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  190139. else
  190140. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  190141. }
  190142. if (info_ptr->bit_depth < 8)
  190143. info_ptr->bit_depth = 8;
  190144. info_ptr->num_trans = 0;
  190145. }
  190146. }
  190147. #endif
  190148. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190149. if (png_ptr->transformations & PNG_BACKGROUND)
  190150. {
  190151. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  190152. info_ptr->num_trans = 0;
  190153. info_ptr->background = png_ptr->background;
  190154. }
  190155. #endif
  190156. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190157. if (png_ptr->transformations & PNG_GAMMA)
  190158. {
  190159. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190160. info_ptr->gamma = png_ptr->gamma;
  190161. #endif
  190162. #ifdef PNG_FIXED_POINT_SUPPORTED
  190163. info_ptr->int_gamma = png_ptr->int_gamma;
  190164. #endif
  190165. }
  190166. #endif
  190167. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190168. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  190169. info_ptr->bit_depth = 8;
  190170. #endif
  190171. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190172. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  190173. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  190174. #endif
  190175. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190176. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  190177. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  190178. #endif
  190179. #if defined(PNG_READ_DITHER_SUPPORTED)
  190180. if (png_ptr->transformations & PNG_DITHER)
  190181. {
  190182. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  190183. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  190184. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  190185. {
  190186. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  190187. }
  190188. }
  190189. #endif
  190190. #if defined(PNG_READ_PACK_SUPPORTED)
  190191. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  190192. info_ptr->bit_depth = 8;
  190193. #endif
  190194. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190195. info_ptr->channels = 1;
  190196. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  190197. info_ptr->channels = 3;
  190198. else
  190199. info_ptr->channels = 1;
  190200. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  190201. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  190202. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  190203. #endif
  190204. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  190205. info_ptr->channels++;
  190206. #if defined(PNG_READ_FILLER_SUPPORTED)
  190207. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  190208. if ((png_ptr->transformations & PNG_FILLER) &&
  190209. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  190210. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  190211. {
  190212. info_ptr->channels++;
  190213. /* if adding a true alpha channel not just filler */
  190214. #if !defined(PNG_1_0_X)
  190215. if (png_ptr->transformations & PNG_ADD_ALPHA)
  190216. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  190217. #endif
  190218. }
  190219. #endif
  190220. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  190221. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190222. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  190223. {
  190224. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  190225. info_ptr->bit_depth = png_ptr->user_transform_depth;
  190226. if(info_ptr->channels < png_ptr->user_transform_channels)
  190227. info_ptr->channels = png_ptr->user_transform_channels;
  190228. }
  190229. #endif
  190230. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  190231. info_ptr->bit_depth);
  190232. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  190233. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  190234. if(png_ptr)
  190235. return;
  190236. #endif
  190237. }
  190238. /* Transform the row. The order of transformations is significant,
  190239. * and is very touchy. If you add a transformation, take care to
  190240. * decide how it fits in with the other transformations here.
  190241. */
  190242. void /* PRIVATE */
  190243. png_do_read_transformations(png_structp png_ptr)
  190244. {
  190245. png_debug(1, "in png_do_read_transformations\n");
  190246. if (png_ptr->row_buf == NULL)
  190247. {
  190248. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  190249. char msg[50];
  190250. png_snprintf2(msg, 50,
  190251. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  190252. png_ptr->pass);
  190253. png_error(png_ptr, msg);
  190254. #else
  190255. png_error(png_ptr, "NULL row buffer");
  190256. #endif
  190257. }
  190258. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190259. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  190260. /* Application has failed to call either png_read_start_image()
  190261. * or png_read_update_info() after setting transforms that expand
  190262. * pixels. This check added to libpng-1.2.19 */
  190263. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  190264. png_error(png_ptr, "Uninitialized row");
  190265. #else
  190266. png_warning(png_ptr, "Uninitialized row");
  190267. #endif
  190268. #endif
  190269. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190270. if (png_ptr->transformations & PNG_EXPAND)
  190271. {
  190272. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  190273. {
  190274. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190275. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  190276. }
  190277. else
  190278. {
  190279. if (png_ptr->num_trans &&
  190280. (png_ptr->transformations & PNG_EXPAND_tRNS))
  190281. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190282. &(png_ptr->trans_values));
  190283. else
  190284. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190285. NULL);
  190286. }
  190287. }
  190288. #endif
  190289. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  190290. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  190291. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190292. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  190293. #endif
  190294. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190295. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  190296. {
  190297. int rgb_error =
  190298. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  190299. if(rgb_error)
  190300. {
  190301. png_ptr->rgb_to_gray_status=1;
  190302. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  190303. PNG_RGB_TO_GRAY_WARN)
  190304. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  190305. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  190306. PNG_RGB_TO_GRAY_ERR)
  190307. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  190308. }
  190309. }
  190310. #endif
  190311. /*
  190312. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  190313. In most cases, the "simple transparency" should be done prior to doing
  190314. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  190315. pixel is transparent. You would also need to make sure that the
  190316. transparency information is upgraded to RGB.
  190317. To summarize, the current flow is:
  190318. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  190319. with background "in place" if transparent,
  190320. convert to RGB if necessary
  190321. - Gray + alpha -> composite with gray background and remove alpha bytes,
  190322. convert to RGB if necessary
  190323. To support RGB backgrounds for gray images we need:
  190324. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  190325. 3 or 6 bytes and composite with background
  190326. "in place" if transparent (3x compare/pixel
  190327. compared to doing composite with gray bkgrnd)
  190328. - Gray + alpha -> convert to RGB + alpha, composite with background and
  190329. remove alpha bytes (3x float operations/pixel
  190330. compared with composite on gray background)
  190331. Greg's change will do this. The reason it wasn't done before is for
  190332. performance, as this increases the per-pixel operations. If we would check
  190333. in advance if the background was gray or RGB, and position the gray-to-RGB
  190334. transform appropriately, then it would save a lot of work/time.
  190335. */
  190336. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190337. /* if gray -> RGB, do so now only if background is non-gray; else do later
  190338. * for performance reasons */
  190339. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190340. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  190341. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190342. #endif
  190343. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190344. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190345. ((png_ptr->num_trans != 0 ) ||
  190346. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  190347. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190348. &(png_ptr->trans_values), &(png_ptr->background)
  190349. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190350. , &(png_ptr->background_1),
  190351. png_ptr->gamma_table, png_ptr->gamma_from_1,
  190352. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  190353. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  190354. png_ptr->gamma_shift
  190355. #endif
  190356. );
  190357. #endif
  190358. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190359. if ((png_ptr->transformations & PNG_GAMMA) &&
  190360. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190361. !((png_ptr->transformations & PNG_BACKGROUND) &&
  190362. ((png_ptr->num_trans != 0) ||
  190363. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  190364. #endif
  190365. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  190366. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190367. png_ptr->gamma_table, png_ptr->gamma_16_table,
  190368. png_ptr->gamma_shift);
  190369. #endif
  190370. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190371. if (png_ptr->transformations & PNG_16_TO_8)
  190372. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190373. #endif
  190374. #if defined(PNG_READ_DITHER_SUPPORTED)
  190375. if (png_ptr->transformations & PNG_DITHER)
  190376. {
  190377. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  190378. png_ptr->palette_lookup, png_ptr->dither_index);
  190379. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  190380. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  190381. }
  190382. #endif
  190383. #if defined(PNG_READ_INVERT_SUPPORTED)
  190384. if (png_ptr->transformations & PNG_INVERT_MONO)
  190385. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190386. #endif
  190387. #if defined(PNG_READ_SHIFT_SUPPORTED)
  190388. if (png_ptr->transformations & PNG_SHIFT)
  190389. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190390. &(png_ptr->shift));
  190391. #endif
  190392. #if defined(PNG_READ_PACK_SUPPORTED)
  190393. if (png_ptr->transformations & PNG_PACK)
  190394. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190395. #endif
  190396. #if defined(PNG_READ_BGR_SUPPORTED)
  190397. if (png_ptr->transformations & PNG_BGR)
  190398. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190399. #endif
  190400. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  190401. if (png_ptr->transformations & PNG_PACKSWAP)
  190402. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190403. #endif
  190404. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190405. /* if gray -> RGB, do so now only if we did not do so above */
  190406. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190407. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  190408. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190409. #endif
  190410. #if defined(PNG_READ_FILLER_SUPPORTED)
  190411. if (png_ptr->transformations & PNG_FILLER)
  190412. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190413. (png_uint_32)png_ptr->filler, png_ptr->flags);
  190414. #endif
  190415. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  190416. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  190417. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190418. #endif
  190419. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  190420. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  190421. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190422. #endif
  190423. #if defined(PNG_READ_SWAP_SUPPORTED)
  190424. if (png_ptr->transformations & PNG_SWAP_BYTES)
  190425. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190426. #endif
  190427. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190428. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  190429. {
  190430. if(png_ptr->read_user_transform_fn != NULL)
  190431. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  190432. (png_ptr, /* png_ptr */
  190433. &(png_ptr->row_info), /* row_info: */
  190434. /* png_uint_32 width; width of row */
  190435. /* png_uint_32 rowbytes; number of bytes in row */
  190436. /* png_byte color_type; color type of pixels */
  190437. /* png_byte bit_depth; bit depth of samples */
  190438. /* png_byte channels; number of channels (1-4) */
  190439. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  190440. png_ptr->row_buf + 1); /* start of pixel data for row */
  190441. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  190442. if(png_ptr->user_transform_depth)
  190443. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  190444. if(png_ptr->user_transform_channels)
  190445. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  190446. #endif
  190447. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  190448. png_ptr->row_info.channels);
  190449. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  190450. png_ptr->row_info.width);
  190451. }
  190452. #endif
  190453. }
  190454. #if defined(PNG_READ_PACK_SUPPORTED)
  190455. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  190456. * without changing the actual values. Thus, if you had a row with
  190457. * a bit depth of 1, you would end up with bytes that only contained
  190458. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  190459. * png_do_shift() after this.
  190460. */
  190461. void /* PRIVATE */
  190462. png_do_unpack(png_row_infop row_info, png_bytep row)
  190463. {
  190464. png_debug(1, "in png_do_unpack\n");
  190465. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190466. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  190467. #else
  190468. if (row_info->bit_depth < 8)
  190469. #endif
  190470. {
  190471. png_uint_32 i;
  190472. png_uint_32 row_width=row_info->width;
  190473. switch (row_info->bit_depth)
  190474. {
  190475. case 1:
  190476. {
  190477. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  190478. png_bytep dp = row + (png_size_t)row_width - 1;
  190479. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  190480. for (i = 0; i < row_width; i++)
  190481. {
  190482. *dp = (png_byte)((*sp >> shift) & 0x01);
  190483. if (shift == 7)
  190484. {
  190485. shift = 0;
  190486. sp--;
  190487. }
  190488. else
  190489. shift++;
  190490. dp--;
  190491. }
  190492. break;
  190493. }
  190494. case 2:
  190495. {
  190496. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  190497. png_bytep dp = row + (png_size_t)row_width - 1;
  190498. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  190499. for (i = 0; i < row_width; i++)
  190500. {
  190501. *dp = (png_byte)((*sp >> shift) & 0x03);
  190502. if (shift == 6)
  190503. {
  190504. shift = 0;
  190505. sp--;
  190506. }
  190507. else
  190508. shift += 2;
  190509. dp--;
  190510. }
  190511. break;
  190512. }
  190513. case 4:
  190514. {
  190515. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  190516. png_bytep dp = row + (png_size_t)row_width - 1;
  190517. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  190518. for (i = 0; i < row_width; i++)
  190519. {
  190520. *dp = (png_byte)((*sp >> shift) & 0x0f);
  190521. if (shift == 4)
  190522. {
  190523. shift = 0;
  190524. sp--;
  190525. }
  190526. else
  190527. shift = 4;
  190528. dp--;
  190529. }
  190530. break;
  190531. }
  190532. }
  190533. row_info->bit_depth = 8;
  190534. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  190535. row_info->rowbytes = row_width * row_info->channels;
  190536. }
  190537. }
  190538. #endif
  190539. #if defined(PNG_READ_SHIFT_SUPPORTED)
  190540. /* Reverse the effects of png_do_shift. This routine merely shifts the
  190541. * pixels back to their significant bits values. Thus, if you have
  190542. * a row of bit depth 8, but only 5 are significant, this will shift
  190543. * the values back to 0 through 31.
  190544. */
  190545. void /* PRIVATE */
  190546. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  190547. {
  190548. png_debug(1, "in png_do_unshift\n");
  190549. if (
  190550. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190551. row != NULL && row_info != NULL && sig_bits != NULL &&
  190552. #endif
  190553. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  190554. {
  190555. int shift[4];
  190556. int channels = 0;
  190557. int c;
  190558. png_uint_16 value = 0;
  190559. png_uint_32 row_width = row_info->width;
  190560. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  190561. {
  190562. shift[channels++] = row_info->bit_depth - sig_bits->red;
  190563. shift[channels++] = row_info->bit_depth - sig_bits->green;
  190564. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  190565. }
  190566. else
  190567. {
  190568. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  190569. }
  190570. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  190571. {
  190572. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  190573. }
  190574. for (c = 0; c < channels; c++)
  190575. {
  190576. if (shift[c] <= 0)
  190577. shift[c] = 0;
  190578. else
  190579. value = 1;
  190580. }
  190581. if (!value)
  190582. return;
  190583. switch (row_info->bit_depth)
  190584. {
  190585. case 2:
  190586. {
  190587. png_bytep bp;
  190588. png_uint_32 i;
  190589. png_uint_32 istop = row_info->rowbytes;
  190590. for (bp = row, i = 0; i < istop; i++)
  190591. {
  190592. *bp >>= 1;
  190593. *bp++ &= 0x55;
  190594. }
  190595. break;
  190596. }
  190597. case 4:
  190598. {
  190599. png_bytep bp = row;
  190600. png_uint_32 i;
  190601. png_uint_32 istop = row_info->rowbytes;
  190602. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  190603. (png_byte)((int)0xf >> shift[0]));
  190604. for (i = 0; i < istop; i++)
  190605. {
  190606. *bp >>= shift[0];
  190607. *bp++ &= mask;
  190608. }
  190609. break;
  190610. }
  190611. case 8:
  190612. {
  190613. png_bytep bp = row;
  190614. png_uint_32 i;
  190615. png_uint_32 istop = row_width * channels;
  190616. for (i = 0; i < istop; i++)
  190617. {
  190618. *bp++ >>= shift[i%channels];
  190619. }
  190620. break;
  190621. }
  190622. case 16:
  190623. {
  190624. png_bytep bp = row;
  190625. png_uint_32 i;
  190626. png_uint_32 istop = channels * row_width;
  190627. for (i = 0; i < istop; i++)
  190628. {
  190629. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  190630. value >>= shift[i%channels];
  190631. *bp++ = (png_byte)(value >> 8);
  190632. *bp++ = (png_byte)(value & 0xff);
  190633. }
  190634. break;
  190635. }
  190636. }
  190637. }
  190638. }
  190639. #endif
  190640. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190641. /* chop rows of bit depth 16 down to 8 */
  190642. void /* PRIVATE */
  190643. png_do_chop(png_row_infop row_info, png_bytep row)
  190644. {
  190645. png_debug(1, "in png_do_chop\n");
  190646. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190647. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  190648. #else
  190649. if (row_info->bit_depth == 16)
  190650. #endif
  190651. {
  190652. png_bytep sp = row;
  190653. png_bytep dp = row;
  190654. png_uint_32 i;
  190655. png_uint_32 istop = row_info->width * row_info->channels;
  190656. for (i = 0; i<istop; i++, sp += 2, dp++)
  190657. {
  190658. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  190659. /* This does a more accurate scaling of the 16-bit color
  190660. * value, rather than a simple low-byte truncation.
  190661. *
  190662. * What the ideal calculation should be:
  190663. * *dp = (((((png_uint_32)(*sp) << 8) |
  190664. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  190665. *
  190666. * GRR: no, I think this is what it really should be:
  190667. * *dp = (((((png_uint_32)(*sp) << 8) |
  190668. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  190669. *
  190670. * GRR: here's the exact calculation with shifts:
  190671. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  190672. * *dp = (temp - (temp >> 8)) >> 8;
  190673. *
  190674. * Approximate calculation with shift/add instead of multiply/divide:
  190675. * *dp = ((((png_uint_32)(*sp) << 8) |
  190676. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  190677. *
  190678. * What we actually do to avoid extra shifting and conversion:
  190679. */
  190680. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  190681. #else
  190682. /* Simply discard the low order byte */
  190683. *dp = *sp;
  190684. #endif
  190685. }
  190686. row_info->bit_depth = 8;
  190687. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  190688. row_info->rowbytes = row_info->width * row_info->channels;
  190689. }
  190690. }
  190691. #endif
  190692. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  190693. void /* PRIVATE */
  190694. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  190695. {
  190696. png_debug(1, "in png_do_read_swap_alpha\n");
  190697. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190698. if (row != NULL && row_info != NULL)
  190699. #endif
  190700. {
  190701. png_uint_32 row_width = row_info->width;
  190702. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  190703. {
  190704. /* This converts from RGBA to ARGB */
  190705. if (row_info->bit_depth == 8)
  190706. {
  190707. png_bytep sp = row + row_info->rowbytes;
  190708. png_bytep dp = sp;
  190709. png_byte save;
  190710. png_uint_32 i;
  190711. for (i = 0; i < row_width; i++)
  190712. {
  190713. save = *(--sp);
  190714. *(--dp) = *(--sp);
  190715. *(--dp) = *(--sp);
  190716. *(--dp) = *(--sp);
  190717. *(--dp) = save;
  190718. }
  190719. }
  190720. /* This converts from RRGGBBAA to AARRGGBB */
  190721. else
  190722. {
  190723. png_bytep sp = row + row_info->rowbytes;
  190724. png_bytep dp = sp;
  190725. png_byte save[2];
  190726. png_uint_32 i;
  190727. for (i = 0; i < row_width; i++)
  190728. {
  190729. save[0] = *(--sp);
  190730. save[1] = *(--sp);
  190731. *(--dp) = *(--sp);
  190732. *(--dp) = *(--sp);
  190733. *(--dp) = *(--sp);
  190734. *(--dp) = *(--sp);
  190735. *(--dp) = *(--sp);
  190736. *(--dp) = *(--sp);
  190737. *(--dp) = save[0];
  190738. *(--dp) = save[1];
  190739. }
  190740. }
  190741. }
  190742. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  190743. {
  190744. /* This converts from GA to AG */
  190745. if (row_info->bit_depth == 8)
  190746. {
  190747. png_bytep sp = row + row_info->rowbytes;
  190748. png_bytep dp = sp;
  190749. png_byte save;
  190750. png_uint_32 i;
  190751. for (i = 0; i < row_width; i++)
  190752. {
  190753. save = *(--sp);
  190754. *(--dp) = *(--sp);
  190755. *(--dp) = save;
  190756. }
  190757. }
  190758. /* This converts from GGAA to AAGG */
  190759. else
  190760. {
  190761. png_bytep sp = row + row_info->rowbytes;
  190762. png_bytep dp = sp;
  190763. png_byte save[2];
  190764. png_uint_32 i;
  190765. for (i = 0; i < row_width; i++)
  190766. {
  190767. save[0] = *(--sp);
  190768. save[1] = *(--sp);
  190769. *(--dp) = *(--sp);
  190770. *(--dp) = *(--sp);
  190771. *(--dp) = save[0];
  190772. *(--dp) = save[1];
  190773. }
  190774. }
  190775. }
  190776. }
  190777. }
  190778. #endif
  190779. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  190780. void /* PRIVATE */
  190781. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  190782. {
  190783. png_debug(1, "in png_do_read_invert_alpha\n");
  190784. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190785. if (row != NULL && row_info != NULL)
  190786. #endif
  190787. {
  190788. png_uint_32 row_width = row_info->width;
  190789. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  190790. {
  190791. /* This inverts the alpha channel in RGBA */
  190792. if (row_info->bit_depth == 8)
  190793. {
  190794. png_bytep sp = row + row_info->rowbytes;
  190795. png_bytep dp = sp;
  190796. png_uint_32 i;
  190797. for (i = 0; i < row_width; i++)
  190798. {
  190799. *(--dp) = (png_byte)(255 - *(--sp));
  190800. /* This does nothing:
  190801. *(--dp) = *(--sp);
  190802. *(--dp) = *(--sp);
  190803. *(--dp) = *(--sp);
  190804. We can replace it with:
  190805. */
  190806. sp-=3;
  190807. dp=sp;
  190808. }
  190809. }
  190810. /* This inverts the alpha channel in RRGGBBAA */
  190811. else
  190812. {
  190813. png_bytep sp = row + row_info->rowbytes;
  190814. png_bytep dp = sp;
  190815. png_uint_32 i;
  190816. for (i = 0; i < row_width; i++)
  190817. {
  190818. *(--dp) = (png_byte)(255 - *(--sp));
  190819. *(--dp) = (png_byte)(255 - *(--sp));
  190820. /* This does nothing:
  190821. *(--dp) = *(--sp);
  190822. *(--dp) = *(--sp);
  190823. *(--dp) = *(--sp);
  190824. *(--dp) = *(--sp);
  190825. *(--dp) = *(--sp);
  190826. *(--dp) = *(--sp);
  190827. We can replace it with:
  190828. */
  190829. sp-=6;
  190830. dp=sp;
  190831. }
  190832. }
  190833. }
  190834. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  190835. {
  190836. /* This inverts the alpha channel in GA */
  190837. if (row_info->bit_depth == 8)
  190838. {
  190839. png_bytep sp = row + row_info->rowbytes;
  190840. png_bytep dp = sp;
  190841. png_uint_32 i;
  190842. for (i = 0; i < row_width; i++)
  190843. {
  190844. *(--dp) = (png_byte)(255 - *(--sp));
  190845. *(--dp) = *(--sp);
  190846. }
  190847. }
  190848. /* This inverts the alpha channel in GGAA */
  190849. else
  190850. {
  190851. png_bytep sp = row + row_info->rowbytes;
  190852. png_bytep dp = sp;
  190853. png_uint_32 i;
  190854. for (i = 0; i < row_width; i++)
  190855. {
  190856. *(--dp) = (png_byte)(255 - *(--sp));
  190857. *(--dp) = (png_byte)(255 - *(--sp));
  190858. /*
  190859. *(--dp) = *(--sp);
  190860. *(--dp) = *(--sp);
  190861. */
  190862. sp-=2;
  190863. dp=sp;
  190864. }
  190865. }
  190866. }
  190867. }
  190868. }
  190869. #endif
  190870. #if defined(PNG_READ_FILLER_SUPPORTED)
  190871. /* Add filler channel if we have RGB color */
  190872. void /* PRIVATE */
  190873. png_do_read_filler(png_row_infop row_info, png_bytep row,
  190874. png_uint_32 filler, png_uint_32 flags)
  190875. {
  190876. png_uint_32 i;
  190877. png_uint_32 row_width = row_info->width;
  190878. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  190879. png_byte lo_filler = (png_byte)(filler & 0xff);
  190880. png_debug(1, "in png_do_read_filler\n");
  190881. if (
  190882. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190883. row != NULL && row_info != NULL &&
  190884. #endif
  190885. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  190886. {
  190887. if(row_info->bit_depth == 8)
  190888. {
  190889. /* This changes the data from G to GX */
  190890. if (flags & PNG_FLAG_FILLER_AFTER)
  190891. {
  190892. png_bytep sp = row + (png_size_t)row_width;
  190893. png_bytep dp = sp + (png_size_t)row_width;
  190894. for (i = 1; i < row_width; i++)
  190895. {
  190896. *(--dp) = lo_filler;
  190897. *(--dp) = *(--sp);
  190898. }
  190899. *(--dp) = lo_filler;
  190900. row_info->channels = 2;
  190901. row_info->pixel_depth = 16;
  190902. row_info->rowbytes = row_width * 2;
  190903. }
  190904. /* This changes the data from G to XG */
  190905. else
  190906. {
  190907. png_bytep sp = row + (png_size_t)row_width;
  190908. png_bytep dp = sp + (png_size_t)row_width;
  190909. for (i = 0; i < row_width; i++)
  190910. {
  190911. *(--dp) = *(--sp);
  190912. *(--dp) = lo_filler;
  190913. }
  190914. row_info->channels = 2;
  190915. row_info->pixel_depth = 16;
  190916. row_info->rowbytes = row_width * 2;
  190917. }
  190918. }
  190919. else if(row_info->bit_depth == 16)
  190920. {
  190921. /* This changes the data from GG to GGXX */
  190922. if (flags & PNG_FLAG_FILLER_AFTER)
  190923. {
  190924. png_bytep sp = row + (png_size_t)row_width * 2;
  190925. png_bytep dp = sp + (png_size_t)row_width * 2;
  190926. for (i = 1; i < row_width; i++)
  190927. {
  190928. *(--dp) = hi_filler;
  190929. *(--dp) = lo_filler;
  190930. *(--dp) = *(--sp);
  190931. *(--dp) = *(--sp);
  190932. }
  190933. *(--dp) = hi_filler;
  190934. *(--dp) = lo_filler;
  190935. row_info->channels = 2;
  190936. row_info->pixel_depth = 32;
  190937. row_info->rowbytes = row_width * 4;
  190938. }
  190939. /* This changes the data from GG to XXGG */
  190940. else
  190941. {
  190942. png_bytep sp = row + (png_size_t)row_width * 2;
  190943. png_bytep dp = sp + (png_size_t)row_width * 2;
  190944. for (i = 0; i < row_width; i++)
  190945. {
  190946. *(--dp) = *(--sp);
  190947. *(--dp) = *(--sp);
  190948. *(--dp) = hi_filler;
  190949. *(--dp) = lo_filler;
  190950. }
  190951. row_info->channels = 2;
  190952. row_info->pixel_depth = 32;
  190953. row_info->rowbytes = row_width * 4;
  190954. }
  190955. }
  190956. } /* COLOR_TYPE == GRAY */
  190957. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  190958. {
  190959. if(row_info->bit_depth == 8)
  190960. {
  190961. /* This changes the data from RGB to RGBX */
  190962. if (flags & PNG_FLAG_FILLER_AFTER)
  190963. {
  190964. png_bytep sp = row + (png_size_t)row_width * 3;
  190965. png_bytep dp = sp + (png_size_t)row_width;
  190966. for (i = 1; i < row_width; i++)
  190967. {
  190968. *(--dp) = lo_filler;
  190969. *(--dp) = *(--sp);
  190970. *(--dp) = *(--sp);
  190971. *(--dp) = *(--sp);
  190972. }
  190973. *(--dp) = lo_filler;
  190974. row_info->channels = 4;
  190975. row_info->pixel_depth = 32;
  190976. row_info->rowbytes = row_width * 4;
  190977. }
  190978. /* This changes the data from RGB to XRGB */
  190979. else
  190980. {
  190981. png_bytep sp = row + (png_size_t)row_width * 3;
  190982. png_bytep dp = sp + (png_size_t)row_width;
  190983. for (i = 0; i < row_width; i++)
  190984. {
  190985. *(--dp) = *(--sp);
  190986. *(--dp) = *(--sp);
  190987. *(--dp) = *(--sp);
  190988. *(--dp) = lo_filler;
  190989. }
  190990. row_info->channels = 4;
  190991. row_info->pixel_depth = 32;
  190992. row_info->rowbytes = row_width * 4;
  190993. }
  190994. }
  190995. else if(row_info->bit_depth == 16)
  190996. {
  190997. /* This changes the data from RRGGBB to RRGGBBXX */
  190998. if (flags & PNG_FLAG_FILLER_AFTER)
  190999. {
  191000. png_bytep sp = row + (png_size_t)row_width * 6;
  191001. png_bytep dp = sp + (png_size_t)row_width * 2;
  191002. for (i = 1; i < row_width; i++)
  191003. {
  191004. *(--dp) = hi_filler;
  191005. *(--dp) = lo_filler;
  191006. *(--dp) = *(--sp);
  191007. *(--dp) = *(--sp);
  191008. *(--dp) = *(--sp);
  191009. *(--dp) = *(--sp);
  191010. *(--dp) = *(--sp);
  191011. *(--dp) = *(--sp);
  191012. }
  191013. *(--dp) = hi_filler;
  191014. *(--dp) = lo_filler;
  191015. row_info->channels = 4;
  191016. row_info->pixel_depth = 64;
  191017. row_info->rowbytes = row_width * 8;
  191018. }
  191019. /* This changes the data from RRGGBB to XXRRGGBB */
  191020. else
  191021. {
  191022. png_bytep sp = row + (png_size_t)row_width * 6;
  191023. png_bytep dp = sp + (png_size_t)row_width * 2;
  191024. for (i = 0; i < row_width; i++)
  191025. {
  191026. *(--dp) = *(--sp);
  191027. *(--dp) = *(--sp);
  191028. *(--dp) = *(--sp);
  191029. *(--dp) = *(--sp);
  191030. *(--dp) = *(--sp);
  191031. *(--dp) = *(--sp);
  191032. *(--dp) = hi_filler;
  191033. *(--dp) = lo_filler;
  191034. }
  191035. row_info->channels = 4;
  191036. row_info->pixel_depth = 64;
  191037. row_info->rowbytes = row_width * 8;
  191038. }
  191039. }
  191040. } /* COLOR_TYPE == RGB */
  191041. }
  191042. #endif
  191043. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191044. /* expand grayscale files to RGB, with or without alpha */
  191045. void /* PRIVATE */
  191046. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  191047. {
  191048. png_uint_32 i;
  191049. png_uint_32 row_width = row_info->width;
  191050. png_debug(1, "in png_do_gray_to_rgb\n");
  191051. if (row_info->bit_depth >= 8 &&
  191052. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191053. row != NULL && row_info != NULL &&
  191054. #endif
  191055. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  191056. {
  191057. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191058. {
  191059. if (row_info->bit_depth == 8)
  191060. {
  191061. png_bytep sp = row + (png_size_t)row_width - 1;
  191062. png_bytep dp = sp + (png_size_t)row_width * 2;
  191063. for (i = 0; i < row_width; i++)
  191064. {
  191065. *(dp--) = *sp;
  191066. *(dp--) = *sp;
  191067. *(dp--) = *(sp--);
  191068. }
  191069. }
  191070. else
  191071. {
  191072. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  191073. png_bytep dp = sp + (png_size_t)row_width * 4;
  191074. for (i = 0; i < row_width; i++)
  191075. {
  191076. *(dp--) = *sp;
  191077. *(dp--) = *(sp - 1);
  191078. *(dp--) = *sp;
  191079. *(dp--) = *(sp - 1);
  191080. *(dp--) = *(sp--);
  191081. *(dp--) = *(sp--);
  191082. }
  191083. }
  191084. }
  191085. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191086. {
  191087. if (row_info->bit_depth == 8)
  191088. {
  191089. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  191090. png_bytep dp = sp + (png_size_t)row_width * 2;
  191091. for (i = 0; i < row_width; i++)
  191092. {
  191093. *(dp--) = *(sp--);
  191094. *(dp--) = *sp;
  191095. *(dp--) = *sp;
  191096. *(dp--) = *(sp--);
  191097. }
  191098. }
  191099. else
  191100. {
  191101. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  191102. png_bytep dp = sp + (png_size_t)row_width * 4;
  191103. for (i = 0; i < row_width; i++)
  191104. {
  191105. *(dp--) = *(sp--);
  191106. *(dp--) = *(sp--);
  191107. *(dp--) = *sp;
  191108. *(dp--) = *(sp - 1);
  191109. *(dp--) = *sp;
  191110. *(dp--) = *(sp - 1);
  191111. *(dp--) = *(sp--);
  191112. *(dp--) = *(sp--);
  191113. }
  191114. }
  191115. }
  191116. row_info->channels += (png_byte)2;
  191117. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  191118. row_info->pixel_depth = (png_byte)(row_info->channels *
  191119. row_info->bit_depth);
  191120. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  191121. }
  191122. }
  191123. #endif
  191124. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191125. /* reduce RGB files to grayscale, with or without alpha
  191126. * using the equation given in Poynton's ColorFAQ at
  191127. * <http://www.inforamp.net/~poynton/>
  191128. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  191129. *
  191130. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  191131. *
  191132. * We approximate this with
  191133. *
  191134. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  191135. *
  191136. * which can be expressed with integers as
  191137. *
  191138. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  191139. *
  191140. * The calculation is to be done in a linear colorspace.
  191141. *
  191142. * Other integer coefficents can be used via png_set_rgb_to_gray().
  191143. */
  191144. int /* PRIVATE */
  191145. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  191146. {
  191147. png_uint_32 i;
  191148. png_uint_32 row_width = row_info->width;
  191149. int rgb_error = 0;
  191150. png_debug(1, "in png_do_rgb_to_gray\n");
  191151. if (
  191152. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191153. row != NULL && row_info != NULL &&
  191154. #endif
  191155. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  191156. {
  191157. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  191158. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  191159. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  191160. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  191161. {
  191162. if (row_info->bit_depth == 8)
  191163. {
  191164. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191165. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  191166. {
  191167. png_bytep sp = row;
  191168. png_bytep dp = row;
  191169. for (i = 0; i < row_width; i++)
  191170. {
  191171. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  191172. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  191173. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  191174. if(red != green || red != blue)
  191175. {
  191176. rgb_error |= 1;
  191177. *(dp++) = png_ptr->gamma_from_1[
  191178. (rc*red+gc*green+bc*blue)>>15];
  191179. }
  191180. else
  191181. *(dp++) = *(sp-1);
  191182. }
  191183. }
  191184. else
  191185. #endif
  191186. {
  191187. png_bytep sp = row;
  191188. png_bytep dp = row;
  191189. for (i = 0; i < row_width; i++)
  191190. {
  191191. png_byte red = *(sp++);
  191192. png_byte green = *(sp++);
  191193. png_byte blue = *(sp++);
  191194. if(red != green || red != blue)
  191195. {
  191196. rgb_error |= 1;
  191197. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  191198. }
  191199. else
  191200. *(dp++) = *(sp-1);
  191201. }
  191202. }
  191203. }
  191204. else /* RGB bit_depth == 16 */
  191205. {
  191206. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191207. if (png_ptr->gamma_16_to_1 != NULL &&
  191208. png_ptr->gamma_16_from_1 != NULL)
  191209. {
  191210. png_bytep sp = row;
  191211. png_bytep dp = row;
  191212. for (i = 0; i < row_width; i++)
  191213. {
  191214. png_uint_16 red, green, blue, w;
  191215. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191216. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191217. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191218. if(red == green && red == blue)
  191219. w = red;
  191220. else
  191221. {
  191222. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  191223. png_ptr->gamma_shift][red>>8];
  191224. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  191225. png_ptr->gamma_shift][green>>8];
  191226. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  191227. png_ptr->gamma_shift][blue>>8];
  191228. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  191229. + bc*blue_1)>>15);
  191230. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  191231. png_ptr->gamma_shift][gray16 >> 8];
  191232. rgb_error |= 1;
  191233. }
  191234. *(dp++) = (png_byte)((w>>8) & 0xff);
  191235. *(dp++) = (png_byte)(w & 0xff);
  191236. }
  191237. }
  191238. else
  191239. #endif
  191240. {
  191241. png_bytep sp = row;
  191242. png_bytep dp = row;
  191243. for (i = 0; i < row_width; i++)
  191244. {
  191245. png_uint_16 red, green, blue, gray16;
  191246. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191247. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191248. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191249. if(red != green || red != blue)
  191250. rgb_error |= 1;
  191251. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  191252. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  191253. *(dp++) = (png_byte)(gray16 & 0xff);
  191254. }
  191255. }
  191256. }
  191257. }
  191258. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191259. {
  191260. if (row_info->bit_depth == 8)
  191261. {
  191262. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191263. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  191264. {
  191265. png_bytep sp = row;
  191266. png_bytep dp = row;
  191267. for (i = 0; i < row_width; i++)
  191268. {
  191269. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  191270. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  191271. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  191272. if(red != green || red != blue)
  191273. rgb_error |= 1;
  191274. *(dp++) = png_ptr->gamma_from_1
  191275. [(rc*red + gc*green + bc*blue)>>15];
  191276. *(dp++) = *(sp++); /* alpha */
  191277. }
  191278. }
  191279. else
  191280. #endif
  191281. {
  191282. png_bytep sp = row;
  191283. png_bytep dp = row;
  191284. for (i = 0; i < row_width; i++)
  191285. {
  191286. png_byte red = *(sp++);
  191287. png_byte green = *(sp++);
  191288. png_byte blue = *(sp++);
  191289. if(red != green || red != blue)
  191290. rgb_error |= 1;
  191291. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  191292. *(dp++) = *(sp++); /* alpha */
  191293. }
  191294. }
  191295. }
  191296. else /* RGBA bit_depth == 16 */
  191297. {
  191298. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191299. if (png_ptr->gamma_16_to_1 != NULL &&
  191300. png_ptr->gamma_16_from_1 != NULL)
  191301. {
  191302. png_bytep sp = row;
  191303. png_bytep dp = row;
  191304. for (i = 0; i < row_width; i++)
  191305. {
  191306. png_uint_16 red, green, blue, w;
  191307. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191308. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191309. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191310. if(red == green && red == blue)
  191311. w = red;
  191312. else
  191313. {
  191314. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  191315. png_ptr->gamma_shift][red>>8];
  191316. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  191317. png_ptr->gamma_shift][green>>8];
  191318. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  191319. png_ptr->gamma_shift][blue>>8];
  191320. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  191321. + gc * green_1 + bc * blue_1)>>15);
  191322. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  191323. png_ptr->gamma_shift][gray16 >> 8];
  191324. rgb_error |= 1;
  191325. }
  191326. *(dp++) = (png_byte)((w>>8) & 0xff);
  191327. *(dp++) = (png_byte)(w & 0xff);
  191328. *(dp++) = *(sp++); /* alpha */
  191329. *(dp++) = *(sp++);
  191330. }
  191331. }
  191332. else
  191333. #endif
  191334. {
  191335. png_bytep sp = row;
  191336. png_bytep dp = row;
  191337. for (i = 0; i < row_width; i++)
  191338. {
  191339. png_uint_16 red, green, blue, gray16;
  191340. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  191341. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  191342. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  191343. if(red != green || red != blue)
  191344. rgb_error |= 1;
  191345. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  191346. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  191347. *(dp++) = (png_byte)(gray16 & 0xff);
  191348. *(dp++) = *(sp++); /* alpha */
  191349. *(dp++) = *(sp++);
  191350. }
  191351. }
  191352. }
  191353. }
  191354. row_info->channels -= (png_byte)2;
  191355. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  191356. row_info->pixel_depth = (png_byte)(row_info->channels *
  191357. row_info->bit_depth);
  191358. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  191359. }
  191360. return rgb_error;
  191361. }
  191362. #endif
  191363. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  191364. * large of png_color. This lets grayscale images be treated as
  191365. * paletted. Most useful for gamma correction and simplification
  191366. * of code.
  191367. */
  191368. void PNGAPI
  191369. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  191370. {
  191371. int num_palette;
  191372. int color_inc;
  191373. int i;
  191374. int v;
  191375. png_debug(1, "in png_do_build_grayscale_palette\n");
  191376. if (palette == NULL)
  191377. return;
  191378. switch (bit_depth)
  191379. {
  191380. case 1:
  191381. num_palette = 2;
  191382. color_inc = 0xff;
  191383. break;
  191384. case 2:
  191385. num_palette = 4;
  191386. color_inc = 0x55;
  191387. break;
  191388. case 4:
  191389. num_palette = 16;
  191390. color_inc = 0x11;
  191391. break;
  191392. case 8:
  191393. num_palette = 256;
  191394. color_inc = 1;
  191395. break;
  191396. default:
  191397. num_palette = 0;
  191398. color_inc = 0;
  191399. break;
  191400. }
  191401. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  191402. {
  191403. palette[i].red = (png_byte)v;
  191404. palette[i].green = (png_byte)v;
  191405. palette[i].blue = (png_byte)v;
  191406. }
  191407. }
  191408. /* This function is currently unused. Do we really need it? */
  191409. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  191410. void /* PRIVATE */
  191411. png_correct_palette(png_structp png_ptr, png_colorp palette,
  191412. int num_palette)
  191413. {
  191414. png_debug(1, "in png_correct_palette\n");
  191415. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  191416. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  191417. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  191418. {
  191419. png_color back, back_1;
  191420. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  191421. {
  191422. back.red = png_ptr->gamma_table[png_ptr->background.red];
  191423. back.green = png_ptr->gamma_table[png_ptr->background.green];
  191424. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  191425. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  191426. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  191427. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  191428. }
  191429. else
  191430. {
  191431. double g;
  191432. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  191433. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  191434. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  191435. {
  191436. back.red = png_ptr->background.red;
  191437. back.green = png_ptr->background.green;
  191438. back.blue = png_ptr->background.blue;
  191439. }
  191440. else
  191441. {
  191442. back.red =
  191443. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  191444. 255.0 + 0.5);
  191445. back.green =
  191446. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  191447. 255.0 + 0.5);
  191448. back.blue =
  191449. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  191450. 255.0 + 0.5);
  191451. }
  191452. g = 1.0 / png_ptr->background_gamma;
  191453. back_1.red =
  191454. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  191455. 255.0 + 0.5);
  191456. back_1.green =
  191457. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  191458. 255.0 + 0.5);
  191459. back_1.blue =
  191460. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  191461. 255.0 + 0.5);
  191462. }
  191463. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191464. {
  191465. png_uint_32 i;
  191466. for (i = 0; i < (png_uint_32)num_palette; i++)
  191467. {
  191468. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  191469. {
  191470. palette[i] = back;
  191471. }
  191472. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  191473. {
  191474. png_byte v, w;
  191475. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  191476. png_composite(w, v, png_ptr->trans[i], back_1.red);
  191477. palette[i].red = png_ptr->gamma_from_1[w];
  191478. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  191479. png_composite(w, v, png_ptr->trans[i], back_1.green);
  191480. palette[i].green = png_ptr->gamma_from_1[w];
  191481. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  191482. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  191483. palette[i].blue = png_ptr->gamma_from_1[w];
  191484. }
  191485. else
  191486. {
  191487. palette[i].red = png_ptr->gamma_table[palette[i].red];
  191488. palette[i].green = png_ptr->gamma_table[palette[i].green];
  191489. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  191490. }
  191491. }
  191492. }
  191493. else
  191494. {
  191495. int i;
  191496. for (i = 0; i < num_palette; i++)
  191497. {
  191498. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  191499. {
  191500. palette[i] = back;
  191501. }
  191502. else
  191503. {
  191504. palette[i].red = png_ptr->gamma_table[palette[i].red];
  191505. palette[i].green = png_ptr->gamma_table[palette[i].green];
  191506. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  191507. }
  191508. }
  191509. }
  191510. }
  191511. else
  191512. #endif
  191513. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191514. if (png_ptr->transformations & PNG_GAMMA)
  191515. {
  191516. int i;
  191517. for (i = 0; i < num_palette; i++)
  191518. {
  191519. palette[i].red = png_ptr->gamma_table[palette[i].red];
  191520. palette[i].green = png_ptr->gamma_table[palette[i].green];
  191521. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  191522. }
  191523. }
  191524. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191525. else
  191526. #endif
  191527. #endif
  191528. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191529. if (png_ptr->transformations & PNG_BACKGROUND)
  191530. {
  191531. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191532. {
  191533. png_color back;
  191534. back.red = (png_byte)png_ptr->background.red;
  191535. back.green = (png_byte)png_ptr->background.green;
  191536. back.blue = (png_byte)png_ptr->background.blue;
  191537. for (i = 0; i < (int)png_ptr->num_trans; i++)
  191538. {
  191539. if (png_ptr->trans[i] == 0)
  191540. {
  191541. palette[i].red = back.red;
  191542. palette[i].green = back.green;
  191543. palette[i].blue = back.blue;
  191544. }
  191545. else if (png_ptr->trans[i] != 0xff)
  191546. {
  191547. png_composite(palette[i].red, png_ptr->palette[i].red,
  191548. png_ptr->trans[i], back.red);
  191549. png_composite(palette[i].green, png_ptr->palette[i].green,
  191550. png_ptr->trans[i], back.green);
  191551. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  191552. png_ptr->trans[i], back.blue);
  191553. }
  191554. }
  191555. }
  191556. else /* assume grayscale palette (what else could it be?) */
  191557. {
  191558. int i;
  191559. for (i = 0; i < num_palette; i++)
  191560. {
  191561. if (i == (png_byte)png_ptr->trans_values.gray)
  191562. {
  191563. palette[i].red = (png_byte)png_ptr->background.red;
  191564. palette[i].green = (png_byte)png_ptr->background.green;
  191565. palette[i].blue = (png_byte)png_ptr->background.blue;
  191566. }
  191567. }
  191568. }
  191569. }
  191570. #endif
  191571. }
  191572. #endif
  191573. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191574. /* Replace any alpha or transparency with the supplied background color.
  191575. * "background" is already in the screen gamma, while "background_1" is
  191576. * at a gamma of 1.0. Paletted files have already been taken care of.
  191577. */
  191578. void /* PRIVATE */
  191579. png_do_background(png_row_infop row_info, png_bytep row,
  191580. png_color_16p trans_values, png_color_16p background
  191581. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191582. , png_color_16p background_1,
  191583. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  191584. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  191585. png_uint_16pp gamma_16_to_1, int gamma_shift
  191586. #endif
  191587. )
  191588. {
  191589. png_bytep sp, dp;
  191590. png_uint_32 i;
  191591. png_uint_32 row_width=row_info->width;
  191592. int shift;
  191593. png_debug(1, "in png_do_background\n");
  191594. if (background != NULL &&
  191595. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191596. row != NULL && row_info != NULL &&
  191597. #endif
  191598. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  191599. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  191600. {
  191601. switch (row_info->color_type)
  191602. {
  191603. case PNG_COLOR_TYPE_GRAY:
  191604. {
  191605. switch (row_info->bit_depth)
  191606. {
  191607. case 1:
  191608. {
  191609. sp = row;
  191610. shift = 7;
  191611. for (i = 0; i < row_width; i++)
  191612. {
  191613. if ((png_uint_16)((*sp >> shift) & 0x01)
  191614. == trans_values->gray)
  191615. {
  191616. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  191617. *sp |= (png_byte)(background->gray << shift);
  191618. }
  191619. if (!shift)
  191620. {
  191621. shift = 7;
  191622. sp++;
  191623. }
  191624. else
  191625. shift--;
  191626. }
  191627. break;
  191628. }
  191629. case 2:
  191630. {
  191631. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191632. if (gamma_table != NULL)
  191633. {
  191634. sp = row;
  191635. shift = 6;
  191636. for (i = 0; i < row_width; i++)
  191637. {
  191638. if ((png_uint_16)((*sp >> shift) & 0x03)
  191639. == trans_values->gray)
  191640. {
  191641. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  191642. *sp |= (png_byte)(background->gray << shift);
  191643. }
  191644. else
  191645. {
  191646. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  191647. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  191648. (p << 4) | (p << 6)] >> 6) & 0x03);
  191649. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  191650. *sp |= (png_byte)(g << shift);
  191651. }
  191652. if (!shift)
  191653. {
  191654. shift = 6;
  191655. sp++;
  191656. }
  191657. else
  191658. shift -= 2;
  191659. }
  191660. }
  191661. else
  191662. #endif
  191663. {
  191664. sp = row;
  191665. shift = 6;
  191666. for (i = 0; i < row_width; i++)
  191667. {
  191668. if ((png_uint_16)((*sp >> shift) & 0x03)
  191669. == trans_values->gray)
  191670. {
  191671. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  191672. *sp |= (png_byte)(background->gray << shift);
  191673. }
  191674. if (!shift)
  191675. {
  191676. shift = 6;
  191677. sp++;
  191678. }
  191679. else
  191680. shift -= 2;
  191681. }
  191682. }
  191683. break;
  191684. }
  191685. case 4:
  191686. {
  191687. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191688. if (gamma_table != NULL)
  191689. {
  191690. sp = row;
  191691. shift = 4;
  191692. for (i = 0; i < row_width; i++)
  191693. {
  191694. if ((png_uint_16)((*sp >> shift) & 0x0f)
  191695. == trans_values->gray)
  191696. {
  191697. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  191698. *sp |= (png_byte)(background->gray << shift);
  191699. }
  191700. else
  191701. {
  191702. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  191703. png_byte g = (png_byte)((gamma_table[p |
  191704. (p << 4)] >> 4) & 0x0f);
  191705. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  191706. *sp |= (png_byte)(g << shift);
  191707. }
  191708. if (!shift)
  191709. {
  191710. shift = 4;
  191711. sp++;
  191712. }
  191713. else
  191714. shift -= 4;
  191715. }
  191716. }
  191717. else
  191718. #endif
  191719. {
  191720. sp = row;
  191721. shift = 4;
  191722. for (i = 0; i < row_width; i++)
  191723. {
  191724. if ((png_uint_16)((*sp >> shift) & 0x0f)
  191725. == trans_values->gray)
  191726. {
  191727. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  191728. *sp |= (png_byte)(background->gray << shift);
  191729. }
  191730. if (!shift)
  191731. {
  191732. shift = 4;
  191733. sp++;
  191734. }
  191735. else
  191736. shift -= 4;
  191737. }
  191738. }
  191739. break;
  191740. }
  191741. case 8:
  191742. {
  191743. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191744. if (gamma_table != NULL)
  191745. {
  191746. sp = row;
  191747. for (i = 0; i < row_width; i++, sp++)
  191748. {
  191749. if (*sp == trans_values->gray)
  191750. {
  191751. *sp = (png_byte)background->gray;
  191752. }
  191753. else
  191754. {
  191755. *sp = gamma_table[*sp];
  191756. }
  191757. }
  191758. }
  191759. else
  191760. #endif
  191761. {
  191762. sp = row;
  191763. for (i = 0; i < row_width; i++, sp++)
  191764. {
  191765. if (*sp == trans_values->gray)
  191766. {
  191767. *sp = (png_byte)background->gray;
  191768. }
  191769. }
  191770. }
  191771. break;
  191772. }
  191773. case 16:
  191774. {
  191775. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191776. if (gamma_16 != NULL)
  191777. {
  191778. sp = row;
  191779. for (i = 0; i < row_width; i++, sp += 2)
  191780. {
  191781. png_uint_16 v;
  191782. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  191783. if (v == trans_values->gray)
  191784. {
  191785. /* background is already in screen gamma */
  191786. *sp = (png_byte)((background->gray >> 8) & 0xff);
  191787. *(sp + 1) = (png_byte)(background->gray & 0xff);
  191788. }
  191789. else
  191790. {
  191791. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  191792. *sp = (png_byte)((v >> 8) & 0xff);
  191793. *(sp + 1) = (png_byte)(v & 0xff);
  191794. }
  191795. }
  191796. }
  191797. else
  191798. #endif
  191799. {
  191800. sp = row;
  191801. for (i = 0; i < row_width; i++, sp += 2)
  191802. {
  191803. png_uint_16 v;
  191804. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  191805. if (v == trans_values->gray)
  191806. {
  191807. *sp = (png_byte)((background->gray >> 8) & 0xff);
  191808. *(sp + 1) = (png_byte)(background->gray & 0xff);
  191809. }
  191810. }
  191811. }
  191812. break;
  191813. }
  191814. }
  191815. break;
  191816. }
  191817. case PNG_COLOR_TYPE_RGB:
  191818. {
  191819. if (row_info->bit_depth == 8)
  191820. {
  191821. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191822. if (gamma_table != NULL)
  191823. {
  191824. sp = row;
  191825. for (i = 0; i < row_width; i++, sp += 3)
  191826. {
  191827. if (*sp == trans_values->red &&
  191828. *(sp + 1) == trans_values->green &&
  191829. *(sp + 2) == trans_values->blue)
  191830. {
  191831. *sp = (png_byte)background->red;
  191832. *(sp + 1) = (png_byte)background->green;
  191833. *(sp + 2) = (png_byte)background->blue;
  191834. }
  191835. else
  191836. {
  191837. *sp = gamma_table[*sp];
  191838. *(sp + 1) = gamma_table[*(sp + 1)];
  191839. *(sp + 2) = gamma_table[*(sp + 2)];
  191840. }
  191841. }
  191842. }
  191843. else
  191844. #endif
  191845. {
  191846. sp = row;
  191847. for (i = 0; i < row_width; i++, sp += 3)
  191848. {
  191849. if (*sp == trans_values->red &&
  191850. *(sp + 1) == trans_values->green &&
  191851. *(sp + 2) == trans_values->blue)
  191852. {
  191853. *sp = (png_byte)background->red;
  191854. *(sp + 1) = (png_byte)background->green;
  191855. *(sp + 2) = (png_byte)background->blue;
  191856. }
  191857. }
  191858. }
  191859. }
  191860. else /* if (row_info->bit_depth == 16) */
  191861. {
  191862. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191863. if (gamma_16 != NULL)
  191864. {
  191865. sp = row;
  191866. for (i = 0; i < row_width; i++, sp += 6)
  191867. {
  191868. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  191869. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  191870. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  191871. if (r == trans_values->red && g == trans_values->green &&
  191872. b == trans_values->blue)
  191873. {
  191874. /* background is already in screen gamma */
  191875. *sp = (png_byte)((background->red >> 8) & 0xff);
  191876. *(sp + 1) = (png_byte)(background->red & 0xff);
  191877. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  191878. *(sp + 3) = (png_byte)(background->green & 0xff);
  191879. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  191880. *(sp + 5) = (png_byte)(background->blue & 0xff);
  191881. }
  191882. else
  191883. {
  191884. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  191885. *sp = (png_byte)((v >> 8) & 0xff);
  191886. *(sp + 1) = (png_byte)(v & 0xff);
  191887. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  191888. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  191889. *(sp + 3) = (png_byte)(v & 0xff);
  191890. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  191891. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  191892. *(sp + 5) = (png_byte)(v & 0xff);
  191893. }
  191894. }
  191895. }
  191896. else
  191897. #endif
  191898. {
  191899. sp = row;
  191900. for (i = 0; i < row_width; i++, sp += 6)
  191901. {
  191902. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  191903. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  191904. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  191905. if (r == trans_values->red && g == trans_values->green &&
  191906. b == trans_values->blue)
  191907. {
  191908. *sp = (png_byte)((background->red >> 8) & 0xff);
  191909. *(sp + 1) = (png_byte)(background->red & 0xff);
  191910. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  191911. *(sp + 3) = (png_byte)(background->green & 0xff);
  191912. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  191913. *(sp + 5) = (png_byte)(background->blue & 0xff);
  191914. }
  191915. }
  191916. }
  191917. }
  191918. break;
  191919. }
  191920. case PNG_COLOR_TYPE_GRAY_ALPHA:
  191921. {
  191922. if (row_info->bit_depth == 8)
  191923. {
  191924. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191925. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  191926. gamma_table != NULL)
  191927. {
  191928. sp = row;
  191929. dp = row;
  191930. for (i = 0; i < row_width; i++, sp += 2, dp++)
  191931. {
  191932. png_uint_16 a = *(sp + 1);
  191933. if (a == 0xff)
  191934. {
  191935. *dp = gamma_table[*sp];
  191936. }
  191937. else if (a == 0)
  191938. {
  191939. /* background is already in screen gamma */
  191940. *dp = (png_byte)background->gray;
  191941. }
  191942. else
  191943. {
  191944. png_byte v, w;
  191945. v = gamma_to_1[*sp];
  191946. png_composite(w, v, a, background_1->gray);
  191947. *dp = gamma_from_1[w];
  191948. }
  191949. }
  191950. }
  191951. else
  191952. #endif
  191953. {
  191954. sp = row;
  191955. dp = row;
  191956. for (i = 0; i < row_width; i++, sp += 2, dp++)
  191957. {
  191958. png_byte a = *(sp + 1);
  191959. if (a == 0xff)
  191960. {
  191961. *dp = *sp;
  191962. }
  191963. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191964. else if (a == 0)
  191965. {
  191966. *dp = (png_byte)background->gray;
  191967. }
  191968. else
  191969. {
  191970. png_composite(*dp, *sp, a, background_1->gray);
  191971. }
  191972. #else
  191973. *dp = (png_byte)background->gray;
  191974. #endif
  191975. }
  191976. }
  191977. }
  191978. else /* if (png_ptr->bit_depth == 16) */
  191979. {
  191980. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191981. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  191982. gamma_16_to_1 != NULL)
  191983. {
  191984. sp = row;
  191985. dp = row;
  191986. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  191987. {
  191988. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  191989. if (a == (png_uint_16)0xffff)
  191990. {
  191991. png_uint_16 v;
  191992. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  191993. *dp = (png_byte)((v >> 8) & 0xff);
  191994. *(dp + 1) = (png_byte)(v & 0xff);
  191995. }
  191996. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191997. else if (a == 0)
  191998. #else
  191999. else
  192000. #endif
  192001. {
  192002. /* background is already in screen gamma */
  192003. *dp = (png_byte)((background->gray >> 8) & 0xff);
  192004. *(dp + 1) = (png_byte)(background->gray & 0xff);
  192005. }
  192006. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192007. else
  192008. {
  192009. png_uint_16 g, v, w;
  192010. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  192011. png_composite_16(v, g, a, background_1->gray);
  192012. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  192013. *dp = (png_byte)((w >> 8) & 0xff);
  192014. *(dp + 1) = (png_byte)(w & 0xff);
  192015. }
  192016. #endif
  192017. }
  192018. }
  192019. else
  192020. #endif
  192021. {
  192022. sp = row;
  192023. dp = row;
  192024. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  192025. {
  192026. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192027. if (a == (png_uint_16)0xffff)
  192028. {
  192029. png_memcpy(dp, sp, 2);
  192030. }
  192031. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192032. else if (a == 0)
  192033. #else
  192034. else
  192035. #endif
  192036. {
  192037. *dp = (png_byte)((background->gray >> 8) & 0xff);
  192038. *(dp + 1) = (png_byte)(background->gray & 0xff);
  192039. }
  192040. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192041. else
  192042. {
  192043. png_uint_16 g, v;
  192044. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192045. png_composite_16(v, g, a, background_1->gray);
  192046. *dp = (png_byte)((v >> 8) & 0xff);
  192047. *(dp + 1) = (png_byte)(v & 0xff);
  192048. }
  192049. #endif
  192050. }
  192051. }
  192052. }
  192053. break;
  192054. }
  192055. case PNG_COLOR_TYPE_RGB_ALPHA:
  192056. {
  192057. if (row_info->bit_depth == 8)
  192058. {
  192059. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192060. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  192061. gamma_table != NULL)
  192062. {
  192063. sp = row;
  192064. dp = row;
  192065. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  192066. {
  192067. png_byte a = *(sp + 3);
  192068. if (a == 0xff)
  192069. {
  192070. *dp = gamma_table[*sp];
  192071. *(dp + 1) = gamma_table[*(sp + 1)];
  192072. *(dp + 2) = gamma_table[*(sp + 2)];
  192073. }
  192074. else if (a == 0)
  192075. {
  192076. /* background is already in screen gamma */
  192077. *dp = (png_byte)background->red;
  192078. *(dp + 1) = (png_byte)background->green;
  192079. *(dp + 2) = (png_byte)background->blue;
  192080. }
  192081. else
  192082. {
  192083. png_byte v, w;
  192084. v = gamma_to_1[*sp];
  192085. png_composite(w, v, a, background_1->red);
  192086. *dp = gamma_from_1[w];
  192087. v = gamma_to_1[*(sp + 1)];
  192088. png_composite(w, v, a, background_1->green);
  192089. *(dp + 1) = gamma_from_1[w];
  192090. v = gamma_to_1[*(sp + 2)];
  192091. png_composite(w, v, a, background_1->blue);
  192092. *(dp + 2) = gamma_from_1[w];
  192093. }
  192094. }
  192095. }
  192096. else
  192097. #endif
  192098. {
  192099. sp = row;
  192100. dp = row;
  192101. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  192102. {
  192103. png_byte a = *(sp + 3);
  192104. if (a == 0xff)
  192105. {
  192106. *dp = *sp;
  192107. *(dp + 1) = *(sp + 1);
  192108. *(dp + 2) = *(sp + 2);
  192109. }
  192110. else if (a == 0)
  192111. {
  192112. *dp = (png_byte)background->red;
  192113. *(dp + 1) = (png_byte)background->green;
  192114. *(dp + 2) = (png_byte)background->blue;
  192115. }
  192116. else
  192117. {
  192118. png_composite(*dp, *sp, a, background->red);
  192119. png_composite(*(dp + 1), *(sp + 1), a,
  192120. background->green);
  192121. png_composite(*(dp + 2), *(sp + 2), a,
  192122. background->blue);
  192123. }
  192124. }
  192125. }
  192126. }
  192127. else /* if (row_info->bit_depth == 16) */
  192128. {
  192129. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192130. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  192131. gamma_16_to_1 != NULL)
  192132. {
  192133. sp = row;
  192134. dp = row;
  192135. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  192136. {
  192137. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  192138. << 8) + (png_uint_16)(*(sp + 7)));
  192139. if (a == (png_uint_16)0xffff)
  192140. {
  192141. png_uint_16 v;
  192142. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192143. *dp = (png_byte)((v >> 8) & 0xff);
  192144. *(dp + 1) = (png_byte)(v & 0xff);
  192145. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192146. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  192147. *(dp + 3) = (png_byte)(v & 0xff);
  192148. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192149. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  192150. *(dp + 5) = (png_byte)(v & 0xff);
  192151. }
  192152. else if (a == 0)
  192153. {
  192154. /* background is already in screen gamma */
  192155. *dp = (png_byte)((background->red >> 8) & 0xff);
  192156. *(dp + 1) = (png_byte)(background->red & 0xff);
  192157. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192158. *(dp + 3) = (png_byte)(background->green & 0xff);
  192159. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192160. *(dp + 5) = (png_byte)(background->blue & 0xff);
  192161. }
  192162. else
  192163. {
  192164. png_uint_16 v, w, x;
  192165. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  192166. png_composite_16(w, v, a, background_1->red);
  192167. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  192168. *dp = (png_byte)((x >> 8) & 0xff);
  192169. *(dp + 1) = (png_byte)(x & 0xff);
  192170. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192171. png_composite_16(w, v, a, background_1->green);
  192172. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  192173. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  192174. *(dp + 3) = (png_byte)(x & 0xff);
  192175. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192176. png_composite_16(w, v, a, background_1->blue);
  192177. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  192178. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  192179. *(dp + 5) = (png_byte)(x & 0xff);
  192180. }
  192181. }
  192182. }
  192183. else
  192184. #endif
  192185. {
  192186. sp = row;
  192187. dp = row;
  192188. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  192189. {
  192190. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  192191. << 8) + (png_uint_16)(*(sp + 7)));
  192192. if (a == (png_uint_16)0xffff)
  192193. {
  192194. png_memcpy(dp, sp, 6);
  192195. }
  192196. else if (a == 0)
  192197. {
  192198. *dp = (png_byte)((background->red >> 8) & 0xff);
  192199. *(dp + 1) = (png_byte)(background->red & 0xff);
  192200. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192201. *(dp + 3) = (png_byte)(background->green & 0xff);
  192202. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192203. *(dp + 5) = (png_byte)(background->blue & 0xff);
  192204. }
  192205. else
  192206. {
  192207. png_uint_16 v;
  192208. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192209. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  192210. + *(sp + 3));
  192211. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  192212. + *(sp + 5));
  192213. png_composite_16(v, r, a, background->red);
  192214. *dp = (png_byte)((v >> 8) & 0xff);
  192215. *(dp + 1) = (png_byte)(v & 0xff);
  192216. png_composite_16(v, g, a, background->green);
  192217. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  192218. *(dp + 3) = (png_byte)(v & 0xff);
  192219. png_composite_16(v, b, a, background->blue);
  192220. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  192221. *(dp + 5) = (png_byte)(v & 0xff);
  192222. }
  192223. }
  192224. }
  192225. }
  192226. break;
  192227. }
  192228. }
  192229. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  192230. {
  192231. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  192232. row_info->channels--;
  192233. row_info->pixel_depth = (png_byte)(row_info->channels *
  192234. row_info->bit_depth);
  192235. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192236. }
  192237. }
  192238. }
  192239. #endif
  192240. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192241. /* Gamma correct the image, avoiding the alpha channel. Make sure
  192242. * you do this after you deal with the transparency issue on grayscale
  192243. * or RGB images. If your bit depth is 8, use gamma_table, if it
  192244. * is 16, use gamma_16_table and gamma_shift. Build these with
  192245. * build_gamma_table().
  192246. */
  192247. void /* PRIVATE */
  192248. png_do_gamma(png_row_infop row_info, png_bytep row,
  192249. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  192250. int gamma_shift)
  192251. {
  192252. png_bytep sp;
  192253. png_uint_32 i;
  192254. png_uint_32 row_width=row_info->width;
  192255. png_debug(1, "in png_do_gamma\n");
  192256. if (
  192257. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192258. row != NULL && row_info != NULL &&
  192259. #endif
  192260. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  192261. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  192262. {
  192263. switch (row_info->color_type)
  192264. {
  192265. case PNG_COLOR_TYPE_RGB:
  192266. {
  192267. if (row_info->bit_depth == 8)
  192268. {
  192269. sp = row;
  192270. for (i = 0; i < row_width; i++)
  192271. {
  192272. *sp = gamma_table[*sp];
  192273. sp++;
  192274. *sp = gamma_table[*sp];
  192275. sp++;
  192276. *sp = gamma_table[*sp];
  192277. sp++;
  192278. }
  192279. }
  192280. else /* if (row_info->bit_depth == 16) */
  192281. {
  192282. sp = row;
  192283. for (i = 0; i < row_width; i++)
  192284. {
  192285. png_uint_16 v;
  192286. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192287. *sp = (png_byte)((v >> 8) & 0xff);
  192288. *(sp + 1) = (png_byte)(v & 0xff);
  192289. sp += 2;
  192290. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192291. *sp = (png_byte)((v >> 8) & 0xff);
  192292. *(sp + 1) = (png_byte)(v & 0xff);
  192293. sp += 2;
  192294. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192295. *sp = (png_byte)((v >> 8) & 0xff);
  192296. *(sp + 1) = (png_byte)(v & 0xff);
  192297. sp += 2;
  192298. }
  192299. }
  192300. break;
  192301. }
  192302. case PNG_COLOR_TYPE_RGB_ALPHA:
  192303. {
  192304. if (row_info->bit_depth == 8)
  192305. {
  192306. sp = row;
  192307. for (i = 0; i < row_width; i++)
  192308. {
  192309. *sp = gamma_table[*sp];
  192310. sp++;
  192311. *sp = gamma_table[*sp];
  192312. sp++;
  192313. *sp = gamma_table[*sp];
  192314. sp++;
  192315. sp++;
  192316. }
  192317. }
  192318. else /* if (row_info->bit_depth == 16) */
  192319. {
  192320. sp = row;
  192321. for (i = 0; i < row_width; i++)
  192322. {
  192323. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192324. *sp = (png_byte)((v >> 8) & 0xff);
  192325. *(sp + 1) = (png_byte)(v & 0xff);
  192326. sp += 2;
  192327. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192328. *sp = (png_byte)((v >> 8) & 0xff);
  192329. *(sp + 1) = (png_byte)(v & 0xff);
  192330. sp += 2;
  192331. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192332. *sp = (png_byte)((v >> 8) & 0xff);
  192333. *(sp + 1) = (png_byte)(v & 0xff);
  192334. sp += 4;
  192335. }
  192336. }
  192337. break;
  192338. }
  192339. case PNG_COLOR_TYPE_GRAY_ALPHA:
  192340. {
  192341. if (row_info->bit_depth == 8)
  192342. {
  192343. sp = row;
  192344. for (i = 0; i < row_width; i++)
  192345. {
  192346. *sp = gamma_table[*sp];
  192347. sp += 2;
  192348. }
  192349. }
  192350. else /* if (row_info->bit_depth == 16) */
  192351. {
  192352. sp = row;
  192353. for (i = 0; i < row_width; i++)
  192354. {
  192355. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192356. *sp = (png_byte)((v >> 8) & 0xff);
  192357. *(sp + 1) = (png_byte)(v & 0xff);
  192358. sp += 4;
  192359. }
  192360. }
  192361. break;
  192362. }
  192363. case PNG_COLOR_TYPE_GRAY:
  192364. {
  192365. if (row_info->bit_depth == 2)
  192366. {
  192367. sp = row;
  192368. for (i = 0; i < row_width; i += 4)
  192369. {
  192370. int a = *sp & 0xc0;
  192371. int b = *sp & 0x30;
  192372. int c = *sp & 0x0c;
  192373. int d = *sp & 0x03;
  192374. *sp = (png_byte)(
  192375. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  192376. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  192377. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  192378. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  192379. sp++;
  192380. }
  192381. }
  192382. if (row_info->bit_depth == 4)
  192383. {
  192384. sp = row;
  192385. for (i = 0; i < row_width; i += 2)
  192386. {
  192387. int msb = *sp & 0xf0;
  192388. int lsb = *sp & 0x0f;
  192389. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  192390. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  192391. sp++;
  192392. }
  192393. }
  192394. else if (row_info->bit_depth == 8)
  192395. {
  192396. sp = row;
  192397. for (i = 0; i < row_width; i++)
  192398. {
  192399. *sp = gamma_table[*sp];
  192400. sp++;
  192401. }
  192402. }
  192403. else if (row_info->bit_depth == 16)
  192404. {
  192405. sp = row;
  192406. for (i = 0; i < row_width; i++)
  192407. {
  192408. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192409. *sp = (png_byte)((v >> 8) & 0xff);
  192410. *(sp + 1) = (png_byte)(v & 0xff);
  192411. sp += 2;
  192412. }
  192413. }
  192414. break;
  192415. }
  192416. }
  192417. }
  192418. }
  192419. #endif
  192420. #if defined(PNG_READ_EXPAND_SUPPORTED)
  192421. /* Expands a palette row to an RGB or RGBA row depending
  192422. * upon whether you supply trans and num_trans.
  192423. */
  192424. void /* PRIVATE */
  192425. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  192426. png_colorp palette, png_bytep trans, int num_trans)
  192427. {
  192428. int shift, value;
  192429. png_bytep sp, dp;
  192430. png_uint_32 i;
  192431. png_uint_32 row_width=row_info->width;
  192432. png_debug(1, "in png_do_expand_palette\n");
  192433. if (
  192434. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192435. row != NULL && row_info != NULL &&
  192436. #endif
  192437. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  192438. {
  192439. if (row_info->bit_depth < 8)
  192440. {
  192441. switch (row_info->bit_depth)
  192442. {
  192443. case 1:
  192444. {
  192445. sp = row + (png_size_t)((row_width - 1) >> 3);
  192446. dp = row + (png_size_t)row_width - 1;
  192447. shift = 7 - (int)((row_width + 7) & 0x07);
  192448. for (i = 0; i < row_width; i++)
  192449. {
  192450. if ((*sp >> shift) & 0x01)
  192451. *dp = 1;
  192452. else
  192453. *dp = 0;
  192454. if (shift == 7)
  192455. {
  192456. shift = 0;
  192457. sp--;
  192458. }
  192459. else
  192460. shift++;
  192461. dp--;
  192462. }
  192463. break;
  192464. }
  192465. case 2:
  192466. {
  192467. sp = row + (png_size_t)((row_width - 1) >> 2);
  192468. dp = row + (png_size_t)row_width - 1;
  192469. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  192470. for (i = 0; i < row_width; i++)
  192471. {
  192472. value = (*sp >> shift) & 0x03;
  192473. *dp = (png_byte)value;
  192474. if (shift == 6)
  192475. {
  192476. shift = 0;
  192477. sp--;
  192478. }
  192479. else
  192480. shift += 2;
  192481. dp--;
  192482. }
  192483. break;
  192484. }
  192485. case 4:
  192486. {
  192487. sp = row + (png_size_t)((row_width - 1) >> 1);
  192488. dp = row + (png_size_t)row_width - 1;
  192489. shift = (int)((row_width & 0x01) << 2);
  192490. for (i = 0; i < row_width; i++)
  192491. {
  192492. value = (*sp >> shift) & 0x0f;
  192493. *dp = (png_byte)value;
  192494. if (shift == 4)
  192495. {
  192496. shift = 0;
  192497. sp--;
  192498. }
  192499. else
  192500. shift += 4;
  192501. dp--;
  192502. }
  192503. break;
  192504. }
  192505. }
  192506. row_info->bit_depth = 8;
  192507. row_info->pixel_depth = 8;
  192508. row_info->rowbytes = row_width;
  192509. }
  192510. switch (row_info->bit_depth)
  192511. {
  192512. case 8:
  192513. {
  192514. if (trans != NULL)
  192515. {
  192516. sp = row + (png_size_t)row_width - 1;
  192517. dp = row + (png_size_t)(row_width << 2) - 1;
  192518. for (i = 0; i < row_width; i++)
  192519. {
  192520. if ((int)(*sp) >= num_trans)
  192521. *dp-- = 0xff;
  192522. else
  192523. *dp-- = trans[*sp];
  192524. *dp-- = palette[*sp].blue;
  192525. *dp-- = palette[*sp].green;
  192526. *dp-- = palette[*sp].red;
  192527. sp--;
  192528. }
  192529. row_info->bit_depth = 8;
  192530. row_info->pixel_depth = 32;
  192531. row_info->rowbytes = row_width * 4;
  192532. row_info->color_type = 6;
  192533. row_info->channels = 4;
  192534. }
  192535. else
  192536. {
  192537. sp = row + (png_size_t)row_width - 1;
  192538. dp = row + (png_size_t)(row_width * 3) - 1;
  192539. for (i = 0; i < row_width; i++)
  192540. {
  192541. *dp-- = palette[*sp].blue;
  192542. *dp-- = palette[*sp].green;
  192543. *dp-- = palette[*sp].red;
  192544. sp--;
  192545. }
  192546. row_info->bit_depth = 8;
  192547. row_info->pixel_depth = 24;
  192548. row_info->rowbytes = row_width * 3;
  192549. row_info->color_type = 2;
  192550. row_info->channels = 3;
  192551. }
  192552. break;
  192553. }
  192554. }
  192555. }
  192556. }
  192557. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  192558. * expanded transparency value is supplied, an alpha channel is built.
  192559. */
  192560. void /* PRIVATE */
  192561. png_do_expand(png_row_infop row_info, png_bytep row,
  192562. png_color_16p trans_value)
  192563. {
  192564. int shift, value;
  192565. png_bytep sp, dp;
  192566. png_uint_32 i;
  192567. png_uint_32 row_width=row_info->width;
  192568. png_debug(1, "in png_do_expand\n");
  192569. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192570. if (row != NULL && row_info != NULL)
  192571. #endif
  192572. {
  192573. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  192574. {
  192575. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  192576. if (row_info->bit_depth < 8)
  192577. {
  192578. switch (row_info->bit_depth)
  192579. {
  192580. case 1:
  192581. {
  192582. gray = (png_uint_16)((gray&0x01)*0xff);
  192583. sp = row + (png_size_t)((row_width - 1) >> 3);
  192584. dp = row + (png_size_t)row_width - 1;
  192585. shift = 7 - (int)((row_width + 7) & 0x07);
  192586. for (i = 0; i < row_width; i++)
  192587. {
  192588. if ((*sp >> shift) & 0x01)
  192589. *dp = 0xff;
  192590. else
  192591. *dp = 0;
  192592. if (shift == 7)
  192593. {
  192594. shift = 0;
  192595. sp--;
  192596. }
  192597. else
  192598. shift++;
  192599. dp--;
  192600. }
  192601. break;
  192602. }
  192603. case 2:
  192604. {
  192605. gray = (png_uint_16)((gray&0x03)*0x55);
  192606. sp = row + (png_size_t)((row_width - 1) >> 2);
  192607. dp = row + (png_size_t)row_width - 1;
  192608. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  192609. for (i = 0; i < row_width; i++)
  192610. {
  192611. value = (*sp >> shift) & 0x03;
  192612. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  192613. (value << 6));
  192614. if (shift == 6)
  192615. {
  192616. shift = 0;
  192617. sp--;
  192618. }
  192619. else
  192620. shift += 2;
  192621. dp--;
  192622. }
  192623. break;
  192624. }
  192625. case 4:
  192626. {
  192627. gray = (png_uint_16)((gray&0x0f)*0x11);
  192628. sp = row + (png_size_t)((row_width - 1) >> 1);
  192629. dp = row + (png_size_t)row_width - 1;
  192630. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  192631. for (i = 0; i < row_width; i++)
  192632. {
  192633. value = (*sp >> shift) & 0x0f;
  192634. *dp = (png_byte)(value | (value << 4));
  192635. if (shift == 4)
  192636. {
  192637. shift = 0;
  192638. sp--;
  192639. }
  192640. else
  192641. shift = 4;
  192642. dp--;
  192643. }
  192644. break;
  192645. }
  192646. }
  192647. row_info->bit_depth = 8;
  192648. row_info->pixel_depth = 8;
  192649. row_info->rowbytes = row_width;
  192650. }
  192651. if (trans_value != NULL)
  192652. {
  192653. if (row_info->bit_depth == 8)
  192654. {
  192655. gray = gray & 0xff;
  192656. sp = row + (png_size_t)row_width - 1;
  192657. dp = row + (png_size_t)(row_width << 1) - 1;
  192658. for (i = 0; i < row_width; i++)
  192659. {
  192660. if (*sp == gray)
  192661. *dp-- = 0;
  192662. else
  192663. *dp-- = 0xff;
  192664. *dp-- = *sp--;
  192665. }
  192666. }
  192667. else if (row_info->bit_depth == 16)
  192668. {
  192669. png_byte gray_high = (gray >> 8) & 0xff;
  192670. png_byte gray_low = gray & 0xff;
  192671. sp = row + row_info->rowbytes - 1;
  192672. dp = row + (row_info->rowbytes << 1) - 1;
  192673. for (i = 0; i < row_width; i++)
  192674. {
  192675. if (*(sp-1) == gray_high && *(sp) == gray_low)
  192676. {
  192677. *dp-- = 0;
  192678. *dp-- = 0;
  192679. }
  192680. else
  192681. {
  192682. *dp-- = 0xff;
  192683. *dp-- = 0xff;
  192684. }
  192685. *dp-- = *sp--;
  192686. *dp-- = *sp--;
  192687. }
  192688. }
  192689. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  192690. row_info->channels = 2;
  192691. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  192692. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  192693. row_width);
  192694. }
  192695. }
  192696. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  192697. {
  192698. if (row_info->bit_depth == 8)
  192699. {
  192700. png_byte red = trans_value->red & 0xff;
  192701. png_byte green = trans_value->green & 0xff;
  192702. png_byte blue = trans_value->blue & 0xff;
  192703. sp = row + (png_size_t)row_info->rowbytes - 1;
  192704. dp = row + (png_size_t)(row_width << 2) - 1;
  192705. for (i = 0; i < row_width; i++)
  192706. {
  192707. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  192708. *dp-- = 0;
  192709. else
  192710. *dp-- = 0xff;
  192711. *dp-- = *sp--;
  192712. *dp-- = *sp--;
  192713. *dp-- = *sp--;
  192714. }
  192715. }
  192716. else if (row_info->bit_depth == 16)
  192717. {
  192718. png_byte red_high = (trans_value->red >> 8) & 0xff;
  192719. png_byte green_high = (trans_value->green >> 8) & 0xff;
  192720. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  192721. png_byte red_low = trans_value->red & 0xff;
  192722. png_byte green_low = trans_value->green & 0xff;
  192723. png_byte blue_low = trans_value->blue & 0xff;
  192724. sp = row + row_info->rowbytes - 1;
  192725. dp = row + (png_size_t)(row_width << 3) - 1;
  192726. for (i = 0; i < row_width; i++)
  192727. {
  192728. if (*(sp - 5) == red_high &&
  192729. *(sp - 4) == red_low &&
  192730. *(sp - 3) == green_high &&
  192731. *(sp - 2) == green_low &&
  192732. *(sp - 1) == blue_high &&
  192733. *(sp ) == blue_low)
  192734. {
  192735. *dp-- = 0;
  192736. *dp-- = 0;
  192737. }
  192738. else
  192739. {
  192740. *dp-- = 0xff;
  192741. *dp-- = 0xff;
  192742. }
  192743. *dp-- = *sp--;
  192744. *dp-- = *sp--;
  192745. *dp-- = *sp--;
  192746. *dp-- = *sp--;
  192747. *dp-- = *sp--;
  192748. *dp-- = *sp--;
  192749. }
  192750. }
  192751. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  192752. row_info->channels = 4;
  192753. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  192754. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192755. }
  192756. }
  192757. }
  192758. #endif
  192759. #if defined(PNG_READ_DITHER_SUPPORTED)
  192760. void /* PRIVATE */
  192761. png_do_dither(png_row_infop row_info, png_bytep row,
  192762. png_bytep palette_lookup, png_bytep dither_lookup)
  192763. {
  192764. png_bytep sp, dp;
  192765. png_uint_32 i;
  192766. png_uint_32 row_width=row_info->width;
  192767. png_debug(1, "in png_do_dither\n");
  192768. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192769. if (row != NULL && row_info != NULL)
  192770. #endif
  192771. {
  192772. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  192773. palette_lookup && row_info->bit_depth == 8)
  192774. {
  192775. int r, g, b, p;
  192776. sp = row;
  192777. dp = row;
  192778. for (i = 0; i < row_width; i++)
  192779. {
  192780. r = *sp++;
  192781. g = *sp++;
  192782. b = *sp++;
  192783. /* this looks real messy, but the compiler will reduce
  192784. it down to a reasonable formula. For example, with
  192785. 5 bits per color, we get:
  192786. p = (((r >> 3) & 0x1f) << 10) |
  192787. (((g >> 3) & 0x1f) << 5) |
  192788. ((b >> 3) & 0x1f);
  192789. */
  192790. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  192791. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  192792. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  192793. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  192794. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  192795. (PNG_DITHER_BLUE_BITS)) |
  192796. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  192797. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  192798. *dp++ = palette_lookup[p];
  192799. }
  192800. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  192801. row_info->channels = 1;
  192802. row_info->pixel_depth = row_info->bit_depth;
  192803. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192804. }
  192805. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  192806. palette_lookup != NULL && row_info->bit_depth == 8)
  192807. {
  192808. int r, g, b, p;
  192809. sp = row;
  192810. dp = row;
  192811. for (i = 0; i < row_width; i++)
  192812. {
  192813. r = *sp++;
  192814. g = *sp++;
  192815. b = *sp++;
  192816. sp++;
  192817. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  192818. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  192819. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  192820. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  192821. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  192822. (PNG_DITHER_BLUE_BITS)) |
  192823. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  192824. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  192825. *dp++ = palette_lookup[p];
  192826. }
  192827. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  192828. row_info->channels = 1;
  192829. row_info->pixel_depth = row_info->bit_depth;
  192830. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192831. }
  192832. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  192833. dither_lookup && row_info->bit_depth == 8)
  192834. {
  192835. sp = row;
  192836. for (i = 0; i < row_width; i++, sp++)
  192837. {
  192838. *sp = dither_lookup[*sp];
  192839. }
  192840. }
  192841. }
  192842. }
  192843. #endif
  192844. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192845. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192846. static PNG_CONST int png_gamma_shift[] =
  192847. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  192848. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  192849. * tables, we don't make a full table if we are reducing to 8-bit in
  192850. * the future. Note also how the gamma_16 tables are segmented so that
  192851. * we don't need to allocate > 64K chunks for a full 16-bit table.
  192852. */
  192853. void /* PRIVATE */
  192854. png_build_gamma_table(png_structp png_ptr)
  192855. {
  192856. png_debug(1, "in png_build_gamma_table\n");
  192857. if (png_ptr->bit_depth <= 8)
  192858. {
  192859. int i;
  192860. double g;
  192861. if (png_ptr->screen_gamma > .000001)
  192862. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  192863. else
  192864. g = 1.0;
  192865. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  192866. (png_uint_32)256);
  192867. for (i = 0; i < 256; i++)
  192868. {
  192869. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  192870. g) * 255.0 + .5);
  192871. }
  192872. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  192873. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  192874. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  192875. {
  192876. g = 1.0 / (png_ptr->gamma);
  192877. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  192878. (png_uint_32)256);
  192879. for (i = 0; i < 256; i++)
  192880. {
  192881. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  192882. g) * 255.0 + .5);
  192883. }
  192884. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  192885. (png_uint_32)256);
  192886. if(png_ptr->screen_gamma > 0.000001)
  192887. g = 1.0 / png_ptr->screen_gamma;
  192888. else
  192889. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  192890. for (i = 0; i < 256; i++)
  192891. {
  192892. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  192893. g) * 255.0 + .5);
  192894. }
  192895. }
  192896. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  192897. }
  192898. else
  192899. {
  192900. double g;
  192901. int i, j, shift, num;
  192902. int sig_bit;
  192903. png_uint_32 ig;
  192904. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  192905. {
  192906. sig_bit = (int)png_ptr->sig_bit.red;
  192907. if ((int)png_ptr->sig_bit.green > sig_bit)
  192908. sig_bit = png_ptr->sig_bit.green;
  192909. if ((int)png_ptr->sig_bit.blue > sig_bit)
  192910. sig_bit = png_ptr->sig_bit.blue;
  192911. }
  192912. else
  192913. {
  192914. sig_bit = (int)png_ptr->sig_bit.gray;
  192915. }
  192916. if (sig_bit > 0)
  192917. shift = 16 - sig_bit;
  192918. else
  192919. shift = 0;
  192920. if (png_ptr->transformations & PNG_16_TO_8)
  192921. {
  192922. if (shift < (16 - PNG_MAX_GAMMA_8))
  192923. shift = (16 - PNG_MAX_GAMMA_8);
  192924. }
  192925. if (shift > 8)
  192926. shift = 8;
  192927. if (shift < 0)
  192928. shift = 0;
  192929. png_ptr->gamma_shift = (png_byte)shift;
  192930. num = (1 << (8 - shift));
  192931. if (png_ptr->screen_gamma > .000001)
  192932. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  192933. else
  192934. g = 1.0;
  192935. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  192936. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  192937. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  192938. {
  192939. double fin, fout;
  192940. png_uint_32 last, max;
  192941. for (i = 0; i < num; i++)
  192942. {
  192943. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  192944. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  192945. }
  192946. g = 1.0 / g;
  192947. last = 0;
  192948. for (i = 0; i < 256; i++)
  192949. {
  192950. fout = ((double)i + 0.5) / 256.0;
  192951. fin = pow(fout, g);
  192952. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  192953. while (last <= max)
  192954. {
  192955. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  192956. [(int)(last >> (8 - shift))] = (png_uint_16)(
  192957. (png_uint_16)i | ((png_uint_16)i << 8));
  192958. last++;
  192959. }
  192960. }
  192961. while (last < ((png_uint_32)num << 8))
  192962. {
  192963. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  192964. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  192965. last++;
  192966. }
  192967. }
  192968. else
  192969. {
  192970. for (i = 0; i < num; i++)
  192971. {
  192972. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  192973. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  192974. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  192975. for (j = 0; j < 256; j++)
  192976. {
  192977. png_ptr->gamma_16_table[i][j] =
  192978. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  192979. 65535.0, g) * 65535.0 + .5);
  192980. }
  192981. }
  192982. }
  192983. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  192984. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  192985. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  192986. {
  192987. g = 1.0 / (png_ptr->gamma);
  192988. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  192989. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  192990. for (i = 0; i < num; i++)
  192991. {
  192992. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  192993. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  192994. ig = (((png_uint_32)i *
  192995. (png_uint_32)png_gamma_shift[shift]) >> 4);
  192996. for (j = 0; j < 256; j++)
  192997. {
  192998. png_ptr->gamma_16_to_1[i][j] =
  192999. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193000. 65535.0, g) * 65535.0 + .5);
  193001. }
  193002. }
  193003. if(png_ptr->screen_gamma > 0.000001)
  193004. g = 1.0 / png_ptr->screen_gamma;
  193005. else
  193006. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193007. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  193008. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  193009. for (i = 0; i < num; i++)
  193010. {
  193011. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  193012. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193013. ig = (((png_uint_32)i *
  193014. (png_uint_32)png_gamma_shift[shift]) >> 4);
  193015. for (j = 0; j < 256; j++)
  193016. {
  193017. png_ptr->gamma_16_from_1[i][j] =
  193018. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193019. 65535.0, g) * 65535.0 + .5);
  193020. }
  193021. }
  193022. }
  193023. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193024. }
  193025. }
  193026. #endif
  193027. /* To do: install integer version of png_build_gamma_table here */
  193028. #endif
  193029. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193030. /* undoes intrapixel differencing */
  193031. void /* PRIVATE */
  193032. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  193033. {
  193034. png_debug(1, "in png_do_read_intrapixel\n");
  193035. if (
  193036. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193037. row != NULL && row_info != NULL &&
  193038. #endif
  193039. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  193040. {
  193041. int bytes_per_pixel;
  193042. png_uint_32 row_width = row_info->width;
  193043. if (row_info->bit_depth == 8)
  193044. {
  193045. png_bytep rp;
  193046. png_uint_32 i;
  193047. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193048. bytes_per_pixel = 3;
  193049. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193050. bytes_per_pixel = 4;
  193051. else
  193052. return;
  193053. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  193054. {
  193055. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  193056. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  193057. }
  193058. }
  193059. else if (row_info->bit_depth == 16)
  193060. {
  193061. png_bytep rp;
  193062. png_uint_32 i;
  193063. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193064. bytes_per_pixel = 6;
  193065. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193066. bytes_per_pixel = 8;
  193067. else
  193068. return;
  193069. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  193070. {
  193071. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  193072. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  193073. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  193074. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  193075. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  193076. *(rp ) = (png_byte)((red >> 8) & 0xff);
  193077. *(rp+1) = (png_byte)(red & 0xff);
  193078. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  193079. *(rp+5) = (png_byte)(blue & 0xff);
  193080. }
  193081. }
  193082. }
  193083. }
  193084. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  193085. #endif /* PNG_READ_SUPPORTED */
  193086. /*** End of inlined file: pngrtran.c ***/
  193087. /*** Start of inlined file: pngrutil.c ***/
  193088. /* pngrutil.c - utilities to read a PNG file
  193089. *
  193090. * Last changed in libpng 1.2.21 [October 4, 2007]
  193091. * For conditions of distribution and use, see copyright notice in png.h
  193092. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  193093. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  193094. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  193095. *
  193096. * This file contains routines that are only called from within
  193097. * libpng itself during the course of reading an image.
  193098. */
  193099. #define PNG_INTERNAL
  193100. #if defined(PNG_READ_SUPPORTED)
  193101. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  193102. # define WIN32_WCE_OLD
  193103. #endif
  193104. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193105. # if defined(WIN32_WCE_OLD)
  193106. /* strtod() function is not supported on WindowsCE */
  193107. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  193108. {
  193109. double result = 0;
  193110. int len;
  193111. wchar_t *str, *end;
  193112. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  193113. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  193114. if ( NULL != str )
  193115. {
  193116. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  193117. result = wcstod(str, &end);
  193118. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  193119. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  193120. png_free(png_ptr, str);
  193121. }
  193122. return result;
  193123. }
  193124. # else
  193125. # define png_strtod(p,a,b) strtod(a,b)
  193126. # endif
  193127. #endif
  193128. png_uint_32 PNGAPI
  193129. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  193130. {
  193131. png_uint_32 i = png_get_uint_32(buf);
  193132. if (i > PNG_UINT_31_MAX)
  193133. png_error(png_ptr, "PNG unsigned integer out of range.");
  193134. return (i);
  193135. }
  193136. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  193137. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  193138. png_uint_32 PNGAPI
  193139. png_get_uint_32(png_bytep buf)
  193140. {
  193141. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  193142. ((png_uint_32)(*(buf + 1)) << 16) +
  193143. ((png_uint_32)(*(buf + 2)) << 8) +
  193144. (png_uint_32)(*(buf + 3));
  193145. return (i);
  193146. }
  193147. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  193148. * data is stored in the PNG file in two's complement format, and it is
  193149. * assumed that the machine format for signed integers is the same. */
  193150. png_int_32 PNGAPI
  193151. png_get_int_32(png_bytep buf)
  193152. {
  193153. png_int_32 i = ((png_int_32)(*buf) << 24) +
  193154. ((png_int_32)(*(buf + 1)) << 16) +
  193155. ((png_int_32)(*(buf + 2)) << 8) +
  193156. (png_int_32)(*(buf + 3));
  193157. return (i);
  193158. }
  193159. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  193160. png_uint_16 PNGAPI
  193161. png_get_uint_16(png_bytep buf)
  193162. {
  193163. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  193164. (png_uint_16)(*(buf + 1)));
  193165. return (i);
  193166. }
  193167. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  193168. /* Read data, and (optionally) run it through the CRC. */
  193169. void /* PRIVATE */
  193170. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  193171. {
  193172. if(png_ptr == NULL) return;
  193173. png_read_data(png_ptr, buf, length);
  193174. png_calculate_crc(png_ptr, buf, length);
  193175. }
  193176. /* Optionally skip data and then check the CRC. Depending on whether we
  193177. are reading a ancillary or critical chunk, and how the program has set
  193178. things up, we may calculate the CRC on the data and print a message.
  193179. Returns '1' if there was a CRC error, '0' otherwise. */
  193180. int /* PRIVATE */
  193181. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  193182. {
  193183. png_size_t i;
  193184. png_size_t istop = png_ptr->zbuf_size;
  193185. for (i = (png_size_t)skip; i > istop; i -= istop)
  193186. {
  193187. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  193188. }
  193189. if (i)
  193190. {
  193191. png_crc_read(png_ptr, png_ptr->zbuf, i);
  193192. }
  193193. if (png_crc_error(png_ptr))
  193194. {
  193195. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  193196. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  193197. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  193198. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  193199. {
  193200. png_chunk_warning(png_ptr, "CRC error");
  193201. }
  193202. else
  193203. {
  193204. png_chunk_error(png_ptr, "CRC error");
  193205. }
  193206. return (1);
  193207. }
  193208. return (0);
  193209. }
  193210. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  193211. the data it has read thus far. */
  193212. int /* PRIVATE */
  193213. png_crc_error(png_structp png_ptr)
  193214. {
  193215. png_byte crc_bytes[4];
  193216. png_uint_32 crc;
  193217. int need_crc = 1;
  193218. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  193219. {
  193220. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  193221. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  193222. need_crc = 0;
  193223. }
  193224. else /* critical */
  193225. {
  193226. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  193227. need_crc = 0;
  193228. }
  193229. png_read_data(png_ptr, crc_bytes, 4);
  193230. if (need_crc)
  193231. {
  193232. crc = png_get_uint_32(crc_bytes);
  193233. return ((int)(crc != png_ptr->crc));
  193234. }
  193235. else
  193236. return (0);
  193237. }
  193238. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  193239. defined(PNG_READ_iCCP_SUPPORTED)
  193240. /*
  193241. * Decompress trailing data in a chunk. The assumption is that chunkdata
  193242. * points at an allocated area holding the contents of a chunk with a
  193243. * trailing compressed part. What we get back is an allocated area
  193244. * holding the original prefix part and an uncompressed version of the
  193245. * trailing part (the malloc area passed in is freed).
  193246. */
  193247. png_charp /* PRIVATE */
  193248. png_decompress_chunk(png_structp png_ptr, int comp_type,
  193249. png_charp chunkdata, png_size_t chunklength,
  193250. png_size_t prefix_size, png_size_t *newlength)
  193251. {
  193252. static PNG_CONST char msg[] = "Error decoding compressed text";
  193253. png_charp text;
  193254. png_size_t text_size;
  193255. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  193256. {
  193257. int ret = Z_OK;
  193258. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  193259. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  193260. png_ptr->zstream.next_out = png_ptr->zbuf;
  193261. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  193262. text_size = 0;
  193263. text = NULL;
  193264. while (png_ptr->zstream.avail_in)
  193265. {
  193266. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  193267. if (ret != Z_OK && ret != Z_STREAM_END)
  193268. {
  193269. if (png_ptr->zstream.msg != NULL)
  193270. png_warning(png_ptr, png_ptr->zstream.msg);
  193271. else
  193272. png_warning(png_ptr, msg);
  193273. inflateReset(&png_ptr->zstream);
  193274. png_ptr->zstream.avail_in = 0;
  193275. if (text == NULL)
  193276. {
  193277. text_size = prefix_size + png_sizeof(msg) + 1;
  193278. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  193279. if (text == NULL)
  193280. {
  193281. png_free(png_ptr,chunkdata);
  193282. png_error(png_ptr,"Not enough memory to decompress chunk");
  193283. }
  193284. png_memcpy(text, chunkdata, prefix_size);
  193285. }
  193286. text[text_size - 1] = 0x00;
  193287. /* Copy what we can of the error message into the text chunk */
  193288. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  193289. text_size = png_sizeof(msg) > text_size ? text_size :
  193290. png_sizeof(msg);
  193291. png_memcpy(text + prefix_size, msg, text_size + 1);
  193292. break;
  193293. }
  193294. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  193295. {
  193296. if (text == NULL)
  193297. {
  193298. text_size = prefix_size +
  193299. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  193300. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  193301. if (text == NULL)
  193302. {
  193303. png_free(png_ptr,chunkdata);
  193304. png_error(png_ptr,"Not enough memory to decompress chunk.");
  193305. }
  193306. png_memcpy(text + prefix_size, png_ptr->zbuf,
  193307. text_size - prefix_size);
  193308. png_memcpy(text, chunkdata, prefix_size);
  193309. *(text + text_size) = 0x00;
  193310. }
  193311. else
  193312. {
  193313. png_charp tmp;
  193314. tmp = text;
  193315. text = (png_charp)png_malloc_warn(png_ptr,
  193316. (png_uint_32)(text_size +
  193317. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  193318. if (text == NULL)
  193319. {
  193320. png_free(png_ptr, tmp);
  193321. png_free(png_ptr, chunkdata);
  193322. png_error(png_ptr,"Not enough memory to decompress chunk..");
  193323. }
  193324. png_memcpy(text, tmp, text_size);
  193325. png_free(png_ptr, tmp);
  193326. png_memcpy(text + text_size, png_ptr->zbuf,
  193327. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  193328. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  193329. *(text + text_size) = 0x00;
  193330. }
  193331. if (ret == Z_STREAM_END)
  193332. break;
  193333. else
  193334. {
  193335. png_ptr->zstream.next_out = png_ptr->zbuf;
  193336. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  193337. }
  193338. }
  193339. }
  193340. if (ret != Z_STREAM_END)
  193341. {
  193342. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  193343. char umsg[52];
  193344. if (ret == Z_BUF_ERROR)
  193345. png_snprintf(umsg, 52,
  193346. "Buffer error in compressed datastream in %s chunk",
  193347. png_ptr->chunk_name);
  193348. else if (ret == Z_DATA_ERROR)
  193349. png_snprintf(umsg, 52,
  193350. "Data error in compressed datastream in %s chunk",
  193351. png_ptr->chunk_name);
  193352. else
  193353. png_snprintf(umsg, 52,
  193354. "Incomplete compressed datastream in %s chunk",
  193355. png_ptr->chunk_name);
  193356. png_warning(png_ptr, umsg);
  193357. #else
  193358. png_warning(png_ptr,
  193359. "Incomplete compressed datastream in chunk other than IDAT");
  193360. #endif
  193361. text_size=prefix_size;
  193362. if (text == NULL)
  193363. {
  193364. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  193365. if (text == NULL)
  193366. {
  193367. png_free(png_ptr, chunkdata);
  193368. png_error(png_ptr,"Not enough memory for text.");
  193369. }
  193370. png_memcpy(text, chunkdata, prefix_size);
  193371. }
  193372. *(text + text_size) = 0x00;
  193373. }
  193374. inflateReset(&png_ptr->zstream);
  193375. png_ptr->zstream.avail_in = 0;
  193376. png_free(png_ptr, chunkdata);
  193377. chunkdata = text;
  193378. *newlength=text_size;
  193379. }
  193380. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  193381. {
  193382. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  193383. char umsg[50];
  193384. png_snprintf(umsg, 50,
  193385. "Unknown zTXt compression type %d", comp_type);
  193386. png_warning(png_ptr, umsg);
  193387. #else
  193388. png_warning(png_ptr, "Unknown zTXt compression type");
  193389. #endif
  193390. *(chunkdata + prefix_size) = 0x00;
  193391. *newlength=prefix_size;
  193392. }
  193393. return chunkdata;
  193394. }
  193395. #endif
  193396. /* read and check the IDHR chunk */
  193397. void /* PRIVATE */
  193398. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193399. {
  193400. png_byte buf[13];
  193401. png_uint_32 width, height;
  193402. int bit_depth, color_type, compression_type, filter_type;
  193403. int interlace_type;
  193404. png_debug(1, "in png_handle_IHDR\n");
  193405. if (png_ptr->mode & PNG_HAVE_IHDR)
  193406. png_error(png_ptr, "Out of place IHDR");
  193407. /* check the length */
  193408. if (length != 13)
  193409. png_error(png_ptr, "Invalid IHDR chunk");
  193410. png_ptr->mode |= PNG_HAVE_IHDR;
  193411. png_crc_read(png_ptr, buf, 13);
  193412. png_crc_finish(png_ptr, 0);
  193413. width = png_get_uint_31(png_ptr, buf);
  193414. height = png_get_uint_31(png_ptr, buf + 4);
  193415. bit_depth = buf[8];
  193416. color_type = buf[9];
  193417. compression_type = buf[10];
  193418. filter_type = buf[11];
  193419. interlace_type = buf[12];
  193420. /* set internal variables */
  193421. png_ptr->width = width;
  193422. png_ptr->height = height;
  193423. png_ptr->bit_depth = (png_byte)bit_depth;
  193424. png_ptr->interlaced = (png_byte)interlace_type;
  193425. png_ptr->color_type = (png_byte)color_type;
  193426. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193427. png_ptr->filter_type = (png_byte)filter_type;
  193428. #endif
  193429. png_ptr->compression_type = (png_byte)compression_type;
  193430. /* find number of channels */
  193431. switch (png_ptr->color_type)
  193432. {
  193433. case PNG_COLOR_TYPE_GRAY:
  193434. case PNG_COLOR_TYPE_PALETTE:
  193435. png_ptr->channels = 1;
  193436. break;
  193437. case PNG_COLOR_TYPE_RGB:
  193438. png_ptr->channels = 3;
  193439. break;
  193440. case PNG_COLOR_TYPE_GRAY_ALPHA:
  193441. png_ptr->channels = 2;
  193442. break;
  193443. case PNG_COLOR_TYPE_RGB_ALPHA:
  193444. png_ptr->channels = 4;
  193445. break;
  193446. }
  193447. /* set up other useful info */
  193448. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  193449. png_ptr->channels);
  193450. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  193451. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  193452. png_debug1(3,"channels = %d\n", png_ptr->channels);
  193453. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  193454. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  193455. color_type, interlace_type, compression_type, filter_type);
  193456. }
  193457. /* read and check the palette */
  193458. void /* PRIVATE */
  193459. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193460. {
  193461. png_color palette[PNG_MAX_PALETTE_LENGTH];
  193462. int num, i;
  193463. #ifndef PNG_NO_POINTER_INDEXING
  193464. png_colorp pal_ptr;
  193465. #endif
  193466. png_debug(1, "in png_handle_PLTE\n");
  193467. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  193468. png_error(png_ptr, "Missing IHDR before PLTE");
  193469. else if (png_ptr->mode & PNG_HAVE_IDAT)
  193470. {
  193471. png_warning(png_ptr, "Invalid PLTE after IDAT");
  193472. png_crc_finish(png_ptr, length);
  193473. return;
  193474. }
  193475. else if (png_ptr->mode & PNG_HAVE_PLTE)
  193476. png_error(png_ptr, "Duplicate PLTE chunk");
  193477. png_ptr->mode |= PNG_HAVE_PLTE;
  193478. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  193479. {
  193480. png_warning(png_ptr,
  193481. "Ignoring PLTE chunk in grayscale PNG");
  193482. png_crc_finish(png_ptr, length);
  193483. return;
  193484. }
  193485. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  193486. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  193487. {
  193488. png_crc_finish(png_ptr, length);
  193489. return;
  193490. }
  193491. #endif
  193492. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  193493. {
  193494. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  193495. {
  193496. png_warning(png_ptr, "Invalid palette chunk");
  193497. png_crc_finish(png_ptr, length);
  193498. return;
  193499. }
  193500. else
  193501. {
  193502. png_error(png_ptr, "Invalid palette chunk");
  193503. }
  193504. }
  193505. num = (int)length / 3;
  193506. #ifndef PNG_NO_POINTER_INDEXING
  193507. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  193508. {
  193509. png_byte buf[3];
  193510. png_crc_read(png_ptr, buf, 3);
  193511. pal_ptr->red = buf[0];
  193512. pal_ptr->green = buf[1];
  193513. pal_ptr->blue = buf[2];
  193514. }
  193515. #else
  193516. for (i = 0; i < num; i++)
  193517. {
  193518. png_byte buf[3];
  193519. png_crc_read(png_ptr, buf, 3);
  193520. /* don't depend upon png_color being any order */
  193521. palette[i].red = buf[0];
  193522. palette[i].green = buf[1];
  193523. palette[i].blue = buf[2];
  193524. }
  193525. #endif
  193526. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  193527. whatever the normal CRC configuration tells us. However, if we
  193528. have an RGB image, the PLTE can be considered ancillary, so
  193529. we will act as though it is. */
  193530. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  193531. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  193532. #endif
  193533. {
  193534. png_crc_finish(png_ptr, 0);
  193535. }
  193536. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  193537. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  193538. {
  193539. /* If we don't want to use the data from an ancillary chunk,
  193540. we have two options: an error abort, or a warning and we
  193541. ignore the data in this chunk (which should be OK, since
  193542. it's considered ancillary for a RGB or RGBA image). */
  193543. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  193544. {
  193545. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  193546. {
  193547. png_chunk_error(png_ptr, "CRC error");
  193548. }
  193549. else
  193550. {
  193551. png_chunk_warning(png_ptr, "CRC error");
  193552. return;
  193553. }
  193554. }
  193555. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  193556. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  193557. {
  193558. png_chunk_warning(png_ptr, "CRC error");
  193559. }
  193560. }
  193561. #endif
  193562. png_set_PLTE(png_ptr, info_ptr, palette, num);
  193563. #if defined(PNG_READ_tRNS_SUPPORTED)
  193564. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  193565. {
  193566. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  193567. {
  193568. if (png_ptr->num_trans > (png_uint_16)num)
  193569. {
  193570. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  193571. png_ptr->num_trans = (png_uint_16)num;
  193572. }
  193573. if (info_ptr->num_trans > (png_uint_16)num)
  193574. {
  193575. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  193576. info_ptr->num_trans = (png_uint_16)num;
  193577. }
  193578. }
  193579. }
  193580. #endif
  193581. }
  193582. void /* PRIVATE */
  193583. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193584. {
  193585. png_debug(1, "in png_handle_IEND\n");
  193586. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  193587. {
  193588. png_error(png_ptr, "No image in file");
  193589. }
  193590. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  193591. if (length != 0)
  193592. {
  193593. png_warning(png_ptr, "Incorrect IEND chunk length");
  193594. }
  193595. png_crc_finish(png_ptr, length);
  193596. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  193597. }
  193598. #if defined(PNG_READ_gAMA_SUPPORTED)
  193599. void /* PRIVATE */
  193600. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193601. {
  193602. png_fixed_point igamma;
  193603. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193604. float file_gamma;
  193605. #endif
  193606. png_byte buf[4];
  193607. png_debug(1, "in png_handle_gAMA\n");
  193608. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  193609. png_error(png_ptr, "Missing IHDR before gAMA");
  193610. else if (png_ptr->mode & PNG_HAVE_IDAT)
  193611. {
  193612. png_warning(png_ptr, "Invalid gAMA after IDAT");
  193613. png_crc_finish(png_ptr, length);
  193614. return;
  193615. }
  193616. else if (png_ptr->mode & PNG_HAVE_PLTE)
  193617. /* Should be an error, but we can cope with it */
  193618. png_warning(png_ptr, "Out of place gAMA chunk");
  193619. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  193620. #if defined(PNG_READ_sRGB_SUPPORTED)
  193621. && !(info_ptr->valid & PNG_INFO_sRGB)
  193622. #endif
  193623. )
  193624. {
  193625. png_warning(png_ptr, "Duplicate gAMA chunk");
  193626. png_crc_finish(png_ptr, length);
  193627. return;
  193628. }
  193629. if (length != 4)
  193630. {
  193631. png_warning(png_ptr, "Incorrect gAMA chunk length");
  193632. png_crc_finish(png_ptr, length);
  193633. return;
  193634. }
  193635. png_crc_read(png_ptr, buf, 4);
  193636. if (png_crc_finish(png_ptr, 0))
  193637. return;
  193638. igamma = (png_fixed_point)png_get_uint_32(buf);
  193639. /* check for zero gamma */
  193640. if (igamma == 0)
  193641. {
  193642. png_warning(png_ptr,
  193643. "Ignoring gAMA chunk with gamma=0");
  193644. return;
  193645. }
  193646. #if defined(PNG_READ_sRGB_SUPPORTED)
  193647. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  193648. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  193649. {
  193650. png_warning(png_ptr,
  193651. "Ignoring incorrect gAMA value when sRGB is also present");
  193652. #ifndef PNG_NO_CONSOLE_IO
  193653. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  193654. #endif
  193655. return;
  193656. }
  193657. #endif /* PNG_READ_sRGB_SUPPORTED */
  193658. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193659. file_gamma = (float)igamma / (float)100000.0;
  193660. # ifdef PNG_READ_GAMMA_SUPPORTED
  193661. png_ptr->gamma = file_gamma;
  193662. # endif
  193663. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  193664. #endif
  193665. #ifdef PNG_FIXED_POINT_SUPPORTED
  193666. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  193667. #endif
  193668. }
  193669. #endif
  193670. #if defined(PNG_READ_sBIT_SUPPORTED)
  193671. void /* PRIVATE */
  193672. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193673. {
  193674. png_size_t truelen;
  193675. png_byte buf[4];
  193676. png_debug(1, "in png_handle_sBIT\n");
  193677. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  193678. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  193679. png_error(png_ptr, "Missing IHDR before sBIT");
  193680. else if (png_ptr->mode & PNG_HAVE_IDAT)
  193681. {
  193682. png_warning(png_ptr, "Invalid sBIT after IDAT");
  193683. png_crc_finish(png_ptr, length);
  193684. return;
  193685. }
  193686. else if (png_ptr->mode & PNG_HAVE_PLTE)
  193687. {
  193688. /* Should be an error, but we can cope with it */
  193689. png_warning(png_ptr, "Out of place sBIT chunk");
  193690. }
  193691. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  193692. {
  193693. png_warning(png_ptr, "Duplicate sBIT chunk");
  193694. png_crc_finish(png_ptr, length);
  193695. return;
  193696. }
  193697. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  193698. truelen = 3;
  193699. else
  193700. truelen = (png_size_t)png_ptr->channels;
  193701. if (length != truelen || length > 4)
  193702. {
  193703. png_warning(png_ptr, "Incorrect sBIT chunk length");
  193704. png_crc_finish(png_ptr, length);
  193705. return;
  193706. }
  193707. png_crc_read(png_ptr, buf, truelen);
  193708. if (png_crc_finish(png_ptr, 0))
  193709. return;
  193710. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  193711. {
  193712. png_ptr->sig_bit.red = buf[0];
  193713. png_ptr->sig_bit.green = buf[1];
  193714. png_ptr->sig_bit.blue = buf[2];
  193715. png_ptr->sig_bit.alpha = buf[3];
  193716. }
  193717. else
  193718. {
  193719. png_ptr->sig_bit.gray = buf[0];
  193720. png_ptr->sig_bit.red = buf[0];
  193721. png_ptr->sig_bit.green = buf[0];
  193722. png_ptr->sig_bit.blue = buf[0];
  193723. png_ptr->sig_bit.alpha = buf[1];
  193724. }
  193725. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  193726. }
  193727. #endif
  193728. #if defined(PNG_READ_cHRM_SUPPORTED)
  193729. void /* PRIVATE */
  193730. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193731. {
  193732. png_byte buf[4];
  193733. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193734. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  193735. #endif
  193736. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  193737. int_y_green, int_x_blue, int_y_blue;
  193738. png_uint_32 uint_x, uint_y;
  193739. png_debug(1, "in png_handle_cHRM\n");
  193740. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  193741. png_error(png_ptr, "Missing IHDR before cHRM");
  193742. else if (png_ptr->mode & PNG_HAVE_IDAT)
  193743. {
  193744. png_warning(png_ptr, "Invalid cHRM after IDAT");
  193745. png_crc_finish(png_ptr, length);
  193746. return;
  193747. }
  193748. else if (png_ptr->mode & PNG_HAVE_PLTE)
  193749. /* Should be an error, but we can cope with it */
  193750. png_warning(png_ptr, "Missing PLTE before cHRM");
  193751. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  193752. #if defined(PNG_READ_sRGB_SUPPORTED)
  193753. && !(info_ptr->valid & PNG_INFO_sRGB)
  193754. #endif
  193755. )
  193756. {
  193757. png_warning(png_ptr, "Duplicate cHRM chunk");
  193758. png_crc_finish(png_ptr, length);
  193759. return;
  193760. }
  193761. if (length != 32)
  193762. {
  193763. png_warning(png_ptr, "Incorrect cHRM chunk length");
  193764. png_crc_finish(png_ptr, length);
  193765. return;
  193766. }
  193767. png_crc_read(png_ptr, buf, 4);
  193768. uint_x = png_get_uint_32(buf);
  193769. png_crc_read(png_ptr, buf, 4);
  193770. uint_y = png_get_uint_32(buf);
  193771. if (uint_x > 80000L || uint_y > 80000L ||
  193772. uint_x + uint_y > 100000L)
  193773. {
  193774. png_warning(png_ptr, "Invalid cHRM white point");
  193775. png_crc_finish(png_ptr, 24);
  193776. return;
  193777. }
  193778. int_x_white = (png_fixed_point)uint_x;
  193779. int_y_white = (png_fixed_point)uint_y;
  193780. png_crc_read(png_ptr, buf, 4);
  193781. uint_x = png_get_uint_32(buf);
  193782. png_crc_read(png_ptr, buf, 4);
  193783. uint_y = png_get_uint_32(buf);
  193784. if (uint_x + uint_y > 100000L)
  193785. {
  193786. png_warning(png_ptr, "Invalid cHRM red point");
  193787. png_crc_finish(png_ptr, 16);
  193788. return;
  193789. }
  193790. int_x_red = (png_fixed_point)uint_x;
  193791. int_y_red = (png_fixed_point)uint_y;
  193792. png_crc_read(png_ptr, buf, 4);
  193793. uint_x = png_get_uint_32(buf);
  193794. png_crc_read(png_ptr, buf, 4);
  193795. uint_y = png_get_uint_32(buf);
  193796. if (uint_x + uint_y > 100000L)
  193797. {
  193798. png_warning(png_ptr, "Invalid cHRM green point");
  193799. png_crc_finish(png_ptr, 8);
  193800. return;
  193801. }
  193802. int_x_green = (png_fixed_point)uint_x;
  193803. int_y_green = (png_fixed_point)uint_y;
  193804. png_crc_read(png_ptr, buf, 4);
  193805. uint_x = png_get_uint_32(buf);
  193806. png_crc_read(png_ptr, buf, 4);
  193807. uint_y = png_get_uint_32(buf);
  193808. if (uint_x + uint_y > 100000L)
  193809. {
  193810. png_warning(png_ptr, "Invalid cHRM blue point");
  193811. png_crc_finish(png_ptr, 0);
  193812. return;
  193813. }
  193814. int_x_blue = (png_fixed_point)uint_x;
  193815. int_y_blue = (png_fixed_point)uint_y;
  193816. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193817. white_x = (float)int_x_white / (float)100000.0;
  193818. white_y = (float)int_y_white / (float)100000.0;
  193819. red_x = (float)int_x_red / (float)100000.0;
  193820. red_y = (float)int_y_red / (float)100000.0;
  193821. green_x = (float)int_x_green / (float)100000.0;
  193822. green_y = (float)int_y_green / (float)100000.0;
  193823. blue_x = (float)int_x_blue / (float)100000.0;
  193824. blue_y = (float)int_y_blue / (float)100000.0;
  193825. #endif
  193826. #if defined(PNG_READ_sRGB_SUPPORTED)
  193827. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  193828. {
  193829. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  193830. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  193831. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  193832. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  193833. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  193834. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  193835. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  193836. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  193837. {
  193838. png_warning(png_ptr,
  193839. "Ignoring incorrect cHRM value when sRGB is also present");
  193840. #ifndef PNG_NO_CONSOLE_IO
  193841. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193842. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  193843. white_x, white_y, red_x, red_y);
  193844. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  193845. green_x, green_y, blue_x, blue_y);
  193846. #else
  193847. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  193848. int_x_white, int_y_white, int_x_red, int_y_red);
  193849. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  193850. int_x_green, int_y_green, int_x_blue, int_y_blue);
  193851. #endif
  193852. #endif /* PNG_NO_CONSOLE_IO */
  193853. }
  193854. png_crc_finish(png_ptr, 0);
  193855. return;
  193856. }
  193857. #endif /* PNG_READ_sRGB_SUPPORTED */
  193858. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193859. png_set_cHRM(png_ptr, info_ptr,
  193860. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  193861. #endif
  193862. #ifdef PNG_FIXED_POINT_SUPPORTED
  193863. png_set_cHRM_fixed(png_ptr, info_ptr,
  193864. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  193865. int_y_green, int_x_blue, int_y_blue);
  193866. #endif
  193867. if (png_crc_finish(png_ptr, 0))
  193868. return;
  193869. }
  193870. #endif
  193871. #if defined(PNG_READ_sRGB_SUPPORTED)
  193872. void /* PRIVATE */
  193873. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193874. {
  193875. int intent;
  193876. png_byte buf[1];
  193877. png_debug(1, "in png_handle_sRGB\n");
  193878. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  193879. png_error(png_ptr, "Missing IHDR before sRGB");
  193880. else if (png_ptr->mode & PNG_HAVE_IDAT)
  193881. {
  193882. png_warning(png_ptr, "Invalid sRGB after IDAT");
  193883. png_crc_finish(png_ptr, length);
  193884. return;
  193885. }
  193886. else if (png_ptr->mode & PNG_HAVE_PLTE)
  193887. /* Should be an error, but we can cope with it */
  193888. png_warning(png_ptr, "Out of place sRGB chunk");
  193889. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  193890. {
  193891. png_warning(png_ptr, "Duplicate sRGB chunk");
  193892. png_crc_finish(png_ptr, length);
  193893. return;
  193894. }
  193895. if (length != 1)
  193896. {
  193897. png_warning(png_ptr, "Incorrect sRGB chunk length");
  193898. png_crc_finish(png_ptr, length);
  193899. return;
  193900. }
  193901. png_crc_read(png_ptr, buf, 1);
  193902. if (png_crc_finish(png_ptr, 0))
  193903. return;
  193904. intent = buf[0];
  193905. /* check for bad intent */
  193906. if (intent >= PNG_sRGB_INTENT_LAST)
  193907. {
  193908. png_warning(png_ptr, "Unknown sRGB intent");
  193909. return;
  193910. }
  193911. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  193912. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  193913. {
  193914. png_fixed_point igamma;
  193915. #ifdef PNG_FIXED_POINT_SUPPORTED
  193916. igamma=info_ptr->int_gamma;
  193917. #else
  193918. # ifdef PNG_FLOATING_POINT_SUPPORTED
  193919. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  193920. # endif
  193921. #endif
  193922. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  193923. {
  193924. png_warning(png_ptr,
  193925. "Ignoring incorrect gAMA value when sRGB is also present");
  193926. #ifndef PNG_NO_CONSOLE_IO
  193927. # ifdef PNG_FIXED_POINT_SUPPORTED
  193928. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  193929. # else
  193930. # ifdef PNG_FLOATING_POINT_SUPPORTED
  193931. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  193932. # endif
  193933. # endif
  193934. #endif
  193935. }
  193936. }
  193937. #endif /* PNG_READ_gAMA_SUPPORTED */
  193938. #ifdef PNG_READ_cHRM_SUPPORTED
  193939. #ifdef PNG_FIXED_POINT_SUPPORTED
  193940. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  193941. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  193942. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  193943. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  193944. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  193945. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  193946. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  193947. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  193948. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  193949. {
  193950. png_warning(png_ptr,
  193951. "Ignoring incorrect cHRM value when sRGB is also present");
  193952. }
  193953. #endif /* PNG_FIXED_POINT_SUPPORTED */
  193954. #endif /* PNG_READ_cHRM_SUPPORTED */
  193955. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  193956. }
  193957. #endif /* PNG_READ_sRGB_SUPPORTED */
  193958. #if defined(PNG_READ_iCCP_SUPPORTED)
  193959. void /* PRIVATE */
  193960. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193961. /* Note: this does not properly handle chunks that are > 64K under DOS */
  193962. {
  193963. png_charp chunkdata;
  193964. png_byte compression_type;
  193965. png_bytep pC;
  193966. png_charp profile;
  193967. png_uint_32 skip = 0;
  193968. png_uint_32 profile_size, profile_length;
  193969. png_size_t slength, prefix_length, data_length;
  193970. png_debug(1, "in png_handle_iCCP\n");
  193971. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  193972. png_error(png_ptr, "Missing IHDR before iCCP");
  193973. else if (png_ptr->mode & PNG_HAVE_IDAT)
  193974. {
  193975. png_warning(png_ptr, "Invalid iCCP after IDAT");
  193976. png_crc_finish(png_ptr, length);
  193977. return;
  193978. }
  193979. else if (png_ptr->mode & PNG_HAVE_PLTE)
  193980. /* Should be an error, but we can cope with it */
  193981. png_warning(png_ptr, "Out of place iCCP chunk");
  193982. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  193983. {
  193984. png_warning(png_ptr, "Duplicate iCCP chunk");
  193985. png_crc_finish(png_ptr, length);
  193986. return;
  193987. }
  193988. #ifdef PNG_MAX_MALLOC_64K
  193989. if (length > (png_uint_32)65535L)
  193990. {
  193991. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  193992. skip = length - (png_uint_32)65535L;
  193993. length = (png_uint_32)65535L;
  193994. }
  193995. #endif
  193996. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  193997. slength = (png_size_t)length;
  193998. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  193999. if (png_crc_finish(png_ptr, skip))
  194000. {
  194001. png_free(png_ptr, chunkdata);
  194002. return;
  194003. }
  194004. chunkdata[slength] = 0x00;
  194005. for (profile = chunkdata; *profile; profile++)
  194006. /* empty loop to find end of name */ ;
  194007. ++profile;
  194008. /* there should be at least one zero (the compression type byte)
  194009. following the separator, and we should be on it */
  194010. if ( profile >= chunkdata + slength - 1)
  194011. {
  194012. png_free(png_ptr, chunkdata);
  194013. png_warning(png_ptr, "Malformed iCCP chunk");
  194014. return;
  194015. }
  194016. /* compression_type should always be zero */
  194017. compression_type = *profile++;
  194018. if (compression_type)
  194019. {
  194020. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  194021. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  194022. wrote nonzero) */
  194023. }
  194024. prefix_length = profile - chunkdata;
  194025. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  194026. slength, prefix_length, &data_length);
  194027. profile_length = data_length - prefix_length;
  194028. if ( prefix_length > data_length || profile_length < 4)
  194029. {
  194030. png_free(png_ptr, chunkdata);
  194031. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  194032. return;
  194033. }
  194034. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  194035. pC = (png_bytep)(chunkdata+prefix_length);
  194036. profile_size = ((*(pC ))<<24) |
  194037. ((*(pC+1))<<16) |
  194038. ((*(pC+2))<< 8) |
  194039. ((*(pC+3)) );
  194040. if(profile_size < profile_length)
  194041. profile_length = profile_size;
  194042. if(profile_size > profile_length)
  194043. {
  194044. png_free(png_ptr, chunkdata);
  194045. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  194046. return;
  194047. }
  194048. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  194049. chunkdata + prefix_length, profile_length);
  194050. png_free(png_ptr, chunkdata);
  194051. }
  194052. #endif /* PNG_READ_iCCP_SUPPORTED */
  194053. #if defined(PNG_READ_sPLT_SUPPORTED)
  194054. void /* PRIVATE */
  194055. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194056. /* Note: this does not properly handle chunks that are > 64K under DOS */
  194057. {
  194058. png_bytep chunkdata;
  194059. png_bytep entry_start;
  194060. png_sPLT_t new_palette;
  194061. #ifdef PNG_NO_POINTER_INDEXING
  194062. png_sPLT_entryp pp;
  194063. #endif
  194064. int data_length, entry_size, i;
  194065. png_uint_32 skip = 0;
  194066. png_size_t slength;
  194067. png_debug(1, "in png_handle_sPLT\n");
  194068. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194069. png_error(png_ptr, "Missing IHDR before sPLT");
  194070. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194071. {
  194072. png_warning(png_ptr, "Invalid sPLT after IDAT");
  194073. png_crc_finish(png_ptr, length);
  194074. return;
  194075. }
  194076. #ifdef PNG_MAX_MALLOC_64K
  194077. if (length > (png_uint_32)65535L)
  194078. {
  194079. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  194080. skip = length - (png_uint_32)65535L;
  194081. length = (png_uint_32)65535L;
  194082. }
  194083. #endif
  194084. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  194085. slength = (png_size_t)length;
  194086. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194087. if (png_crc_finish(png_ptr, skip))
  194088. {
  194089. png_free(png_ptr, chunkdata);
  194090. return;
  194091. }
  194092. chunkdata[slength] = 0x00;
  194093. for (entry_start = chunkdata; *entry_start; entry_start++)
  194094. /* empty loop to find end of name */ ;
  194095. ++entry_start;
  194096. /* a sample depth should follow the separator, and we should be on it */
  194097. if (entry_start > chunkdata + slength - 2)
  194098. {
  194099. png_free(png_ptr, chunkdata);
  194100. png_warning(png_ptr, "malformed sPLT chunk");
  194101. return;
  194102. }
  194103. new_palette.depth = *entry_start++;
  194104. entry_size = (new_palette.depth == 8 ? 6 : 10);
  194105. data_length = (slength - (entry_start - chunkdata));
  194106. /* integrity-check the data length */
  194107. if (data_length % entry_size)
  194108. {
  194109. png_free(png_ptr, chunkdata);
  194110. png_warning(png_ptr, "sPLT chunk has bad length");
  194111. return;
  194112. }
  194113. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  194114. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  194115. png_sizeof(png_sPLT_entry)))
  194116. {
  194117. png_warning(png_ptr, "sPLT chunk too long");
  194118. return;
  194119. }
  194120. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  194121. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  194122. if (new_palette.entries == NULL)
  194123. {
  194124. png_warning(png_ptr, "sPLT chunk requires too much memory");
  194125. return;
  194126. }
  194127. #ifndef PNG_NO_POINTER_INDEXING
  194128. for (i = 0; i < new_palette.nentries; i++)
  194129. {
  194130. png_sPLT_entryp pp = new_palette.entries + i;
  194131. if (new_palette.depth == 8)
  194132. {
  194133. pp->red = *entry_start++;
  194134. pp->green = *entry_start++;
  194135. pp->blue = *entry_start++;
  194136. pp->alpha = *entry_start++;
  194137. }
  194138. else
  194139. {
  194140. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  194141. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  194142. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  194143. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  194144. }
  194145. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  194146. }
  194147. #else
  194148. pp = new_palette.entries;
  194149. for (i = 0; i < new_palette.nentries; i++)
  194150. {
  194151. if (new_palette.depth == 8)
  194152. {
  194153. pp[i].red = *entry_start++;
  194154. pp[i].green = *entry_start++;
  194155. pp[i].blue = *entry_start++;
  194156. pp[i].alpha = *entry_start++;
  194157. }
  194158. else
  194159. {
  194160. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  194161. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  194162. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  194163. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  194164. }
  194165. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  194166. }
  194167. #endif
  194168. /* discard all chunk data except the name and stash that */
  194169. new_palette.name = (png_charp)chunkdata;
  194170. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  194171. png_free(png_ptr, chunkdata);
  194172. png_free(png_ptr, new_palette.entries);
  194173. }
  194174. #endif /* PNG_READ_sPLT_SUPPORTED */
  194175. #if defined(PNG_READ_tRNS_SUPPORTED)
  194176. void /* PRIVATE */
  194177. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194178. {
  194179. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  194180. int bit_mask;
  194181. png_debug(1, "in png_handle_tRNS\n");
  194182. /* For non-indexed color, mask off any bits in the tRNS value that
  194183. * exceed the bit depth. Some creators were writing extra bits there.
  194184. * This is not needed for indexed color. */
  194185. bit_mask = (1 << png_ptr->bit_depth) - 1;
  194186. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194187. png_error(png_ptr, "Missing IHDR before tRNS");
  194188. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194189. {
  194190. png_warning(png_ptr, "Invalid tRNS after IDAT");
  194191. png_crc_finish(png_ptr, length);
  194192. return;
  194193. }
  194194. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  194195. {
  194196. png_warning(png_ptr, "Duplicate tRNS chunk");
  194197. png_crc_finish(png_ptr, length);
  194198. return;
  194199. }
  194200. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  194201. {
  194202. png_byte buf[2];
  194203. if (length != 2)
  194204. {
  194205. png_warning(png_ptr, "Incorrect tRNS chunk length");
  194206. png_crc_finish(png_ptr, length);
  194207. return;
  194208. }
  194209. png_crc_read(png_ptr, buf, 2);
  194210. png_ptr->num_trans = 1;
  194211. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  194212. }
  194213. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  194214. {
  194215. png_byte buf[6];
  194216. if (length != 6)
  194217. {
  194218. png_warning(png_ptr, "Incorrect tRNS chunk length");
  194219. png_crc_finish(png_ptr, length);
  194220. return;
  194221. }
  194222. png_crc_read(png_ptr, buf, (png_size_t)length);
  194223. png_ptr->num_trans = 1;
  194224. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  194225. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  194226. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  194227. }
  194228. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194229. {
  194230. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  194231. {
  194232. /* Should be an error, but we can cope with it. */
  194233. png_warning(png_ptr, "Missing PLTE before tRNS");
  194234. }
  194235. if (length > (png_uint_32)png_ptr->num_palette ||
  194236. length > PNG_MAX_PALETTE_LENGTH)
  194237. {
  194238. png_warning(png_ptr, "Incorrect tRNS chunk length");
  194239. png_crc_finish(png_ptr, length);
  194240. return;
  194241. }
  194242. if (length == 0)
  194243. {
  194244. png_warning(png_ptr, "Zero length tRNS chunk");
  194245. png_crc_finish(png_ptr, length);
  194246. return;
  194247. }
  194248. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  194249. png_ptr->num_trans = (png_uint_16)length;
  194250. }
  194251. else
  194252. {
  194253. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  194254. png_crc_finish(png_ptr, length);
  194255. return;
  194256. }
  194257. if (png_crc_finish(png_ptr, 0))
  194258. {
  194259. png_ptr->num_trans = 0;
  194260. return;
  194261. }
  194262. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  194263. &(png_ptr->trans_values));
  194264. }
  194265. #endif
  194266. #if defined(PNG_READ_bKGD_SUPPORTED)
  194267. void /* PRIVATE */
  194268. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194269. {
  194270. png_size_t truelen;
  194271. png_byte buf[6];
  194272. png_debug(1, "in png_handle_bKGD\n");
  194273. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194274. png_error(png_ptr, "Missing IHDR before bKGD");
  194275. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194276. {
  194277. png_warning(png_ptr, "Invalid bKGD after IDAT");
  194278. png_crc_finish(png_ptr, length);
  194279. return;
  194280. }
  194281. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  194282. !(png_ptr->mode & PNG_HAVE_PLTE))
  194283. {
  194284. png_warning(png_ptr, "Missing PLTE before bKGD");
  194285. png_crc_finish(png_ptr, length);
  194286. return;
  194287. }
  194288. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  194289. {
  194290. png_warning(png_ptr, "Duplicate bKGD chunk");
  194291. png_crc_finish(png_ptr, length);
  194292. return;
  194293. }
  194294. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194295. truelen = 1;
  194296. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  194297. truelen = 6;
  194298. else
  194299. truelen = 2;
  194300. if (length != truelen)
  194301. {
  194302. png_warning(png_ptr, "Incorrect bKGD chunk length");
  194303. png_crc_finish(png_ptr, length);
  194304. return;
  194305. }
  194306. png_crc_read(png_ptr, buf, truelen);
  194307. if (png_crc_finish(png_ptr, 0))
  194308. return;
  194309. /* We convert the index value into RGB components so that we can allow
  194310. * arbitrary RGB values for background when we have transparency, and
  194311. * so it is easy to determine the RGB values of the background color
  194312. * from the info_ptr struct. */
  194313. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194314. {
  194315. png_ptr->background.index = buf[0];
  194316. if(info_ptr->num_palette)
  194317. {
  194318. if(buf[0] > info_ptr->num_palette)
  194319. {
  194320. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  194321. return;
  194322. }
  194323. png_ptr->background.red =
  194324. (png_uint_16)png_ptr->palette[buf[0]].red;
  194325. png_ptr->background.green =
  194326. (png_uint_16)png_ptr->palette[buf[0]].green;
  194327. png_ptr->background.blue =
  194328. (png_uint_16)png_ptr->palette[buf[0]].blue;
  194329. }
  194330. }
  194331. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  194332. {
  194333. png_ptr->background.red =
  194334. png_ptr->background.green =
  194335. png_ptr->background.blue =
  194336. png_ptr->background.gray = png_get_uint_16(buf);
  194337. }
  194338. else
  194339. {
  194340. png_ptr->background.red = png_get_uint_16(buf);
  194341. png_ptr->background.green = png_get_uint_16(buf + 2);
  194342. png_ptr->background.blue = png_get_uint_16(buf + 4);
  194343. }
  194344. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  194345. }
  194346. #endif
  194347. #if defined(PNG_READ_hIST_SUPPORTED)
  194348. void /* PRIVATE */
  194349. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194350. {
  194351. unsigned int num, i;
  194352. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  194353. png_debug(1, "in png_handle_hIST\n");
  194354. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194355. png_error(png_ptr, "Missing IHDR before hIST");
  194356. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194357. {
  194358. png_warning(png_ptr, "Invalid hIST after IDAT");
  194359. png_crc_finish(png_ptr, length);
  194360. return;
  194361. }
  194362. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  194363. {
  194364. png_warning(png_ptr, "Missing PLTE before hIST");
  194365. png_crc_finish(png_ptr, length);
  194366. return;
  194367. }
  194368. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  194369. {
  194370. png_warning(png_ptr, "Duplicate hIST chunk");
  194371. png_crc_finish(png_ptr, length);
  194372. return;
  194373. }
  194374. num = length / 2 ;
  194375. if (num != (unsigned int) png_ptr->num_palette || num >
  194376. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  194377. {
  194378. png_warning(png_ptr, "Incorrect hIST chunk length");
  194379. png_crc_finish(png_ptr, length);
  194380. return;
  194381. }
  194382. for (i = 0; i < num; i++)
  194383. {
  194384. png_byte buf[2];
  194385. png_crc_read(png_ptr, buf, 2);
  194386. readbuf[i] = png_get_uint_16(buf);
  194387. }
  194388. if (png_crc_finish(png_ptr, 0))
  194389. return;
  194390. png_set_hIST(png_ptr, info_ptr, readbuf);
  194391. }
  194392. #endif
  194393. #if defined(PNG_READ_pHYs_SUPPORTED)
  194394. void /* PRIVATE */
  194395. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194396. {
  194397. png_byte buf[9];
  194398. png_uint_32 res_x, res_y;
  194399. int unit_type;
  194400. png_debug(1, "in png_handle_pHYs\n");
  194401. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194402. png_error(png_ptr, "Missing IHDR before pHYs");
  194403. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194404. {
  194405. png_warning(png_ptr, "Invalid pHYs after IDAT");
  194406. png_crc_finish(png_ptr, length);
  194407. return;
  194408. }
  194409. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  194410. {
  194411. png_warning(png_ptr, "Duplicate pHYs chunk");
  194412. png_crc_finish(png_ptr, length);
  194413. return;
  194414. }
  194415. if (length != 9)
  194416. {
  194417. png_warning(png_ptr, "Incorrect pHYs chunk length");
  194418. png_crc_finish(png_ptr, length);
  194419. return;
  194420. }
  194421. png_crc_read(png_ptr, buf, 9);
  194422. if (png_crc_finish(png_ptr, 0))
  194423. return;
  194424. res_x = png_get_uint_32(buf);
  194425. res_y = png_get_uint_32(buf + 4);
  194426. unit_type = buf[8];
  194427. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  194428. }
  194429. #endif
  194430. #if defined(PNG_READ_oFFs_SUPPORTED)
  194431. void /* PRIVATE */
  194432. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194433. {
  194434. png_byte buf[9];
  194435. png_int_32 offset_x, offset_y;
  194436. int unit_type;
  194437. png_debug(1, "in png_handle_oFFs\n");
  194438. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194439. png_error(png_ptr, "Missing IHDR before oFFs");
  194440. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194441. {
  194442. png_warning(png_ptr, "Invalid oFFs after IDAT");
  194443. png_crc_finish(png_ptr, length);
  194444. return;
  194445. }
  194446. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  194447. {
  194448. png_warning(png_ptr, "Duplicate oFFs chunk");
  194449. png_crc_finish(png_ptr, length);
  194450. return;
  194451. }
  194452. if (length != 9)
  194453. {
  194454. png_warning(png_ptr, "Incorrect oFFs chunk length");
  194455. png_crc_finish(png_ptr, length);
  194456. return;
  194457. }
  194458. png_crc_read(png_ptr, buf, 9);
  194459. if (png_crc_finish(png_ptr, 0))
  194460. return;
  194461. offset_x = png_get_int_32(buf);
  194462. offset_y = png_get_int_32(buf + 4);
  194463. unit_type = buf[8];
  194464. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  194465. }
  194466. #endif
  194467. #if defined(PNG_READ_pCAL_SUPPORTED)
  194468. /* read the pCAL chunk (described in the PNG Extensions document) */
  194469. void /* PRIVATE */
  194470. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194471. {
  194472. png_charp purpose;
  194473. png_int_32 X0, X1;
  194474. png_byte type, nparams;
  194475. png_charp buf, units, endptr;
  194476. png_charpp params;
  194477. png_size_t slength;
  194478. int i;
  194479. png_debug(1, "in png_handle_pCAL\n");
  194480. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194481. png_error(png_ptr, "Missing IHDR before pCAL");
  194482. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194483. {
  194484. png_warning(png_ptr, "Invalid pCAL after IDAT");
  194485. png_crc_finish(png_ptr, length);
  194486. return;
  194487. }
  194488. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  194489. {
  194490. png_warning(png_ptr, "Duplicate pCAL chunk");
  194491. png_crc_finish(png_ptr, length);
  194492. return;
  194493. }
  194494. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  194495. length + 1);
  194496. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  194497. if (purpose == NULL)
  194498. {
  194499. png_warning(png_ptr, "No memory for pCAL purpose.");
  194500. return;
  194501. }
  194502. slength = (png_size_t)length;
  194503. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  194504. if (png_crc_finish(png_ptr, 0))
  194505. {
  194506. png_free(png_ptr, purpose);
  194507. return;
  194508. }
  194509. purpose[slength] = 0x00; /* null terminate the last string */
  194510. png_debug(3, "Finding end of pCAL purpose string\n");
  194511. for (buf = purpose; *buf; buf++)
  194512. /* empty loop */ ;
  194513. endptr = purpose + slength;
  194514. /* We need to have at least 12 bytes after the purpose string
  194515. in order to get the parameter information. */
  194516. if (endptr <= buf + 12)
  194517. {
  194518. png_warning(png_ptr, "Invalid pCAL data");
  194519. png_free(png_ptr, purpose);
  194520. return;
  194521. }
  194522. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  194523. X0 = png_get_int_32((png_bytep)buf+1);
  194524. X1 = png_get_int_32((png_bytep)buf+5);
  194525. type = buf[9];
  194526. nparams = buf[10];
  194527. units = buf + 11;
  194528. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  194529. /* Check that we have the right number of parameters for known
  194530. equation types. */
  194531. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  194532. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  194533. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  194534. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  194535. {
  194536. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  194537. png_free(png_ptr, purpose);
  194538. return;
  194539. }
  194540. else if (type >= PNG_EQUATION_LAST)
  194541. {
  194542. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  194543. }
  194544. for (buf = units; *buf; buf++)
  194545. /* Empty loop to move past the units string. */ ;
  194546. png_debug(3, "Allocating pCAL parameters array\n");
  194547. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  194548. *png_sizeof(png_charp))) ;
  194549. if (params == NULL)
  194550. {
  194551. png_free(png_ptr, purpose);
  194552. png_warning(png_ptr, "No memory for pCAL params.");
  194553. return;
  194554. }
  194555. /* Get pointers to the start of each parameter string. */
  194556. for (i = 0; i < (int)nparams; i++)
  194557. {
  194558. buf++; /* Skip the null string terminator from previous parameter. */
  194559. png_debug1(3, "Reading pCAL parameter %d\n", i);
  194560. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  194561. /* Empty loop to move past each parameter string */ ;
  194562. /* Make sure we haven't run out of data yet */
  194563. if (buf > endptr)
  194564. {
  194565. png_warning(png_ptr, "Invalid pCAL data");
  194566. png_free(png_ptr, purpose);
  194567. png_free(png_ptr, params);
  194568. return;
  194569. }
  194570. }
  194571. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  194572. units, params);
  194573. png_free(png_ptr, purpose);
  194574. png_free(png_ptr, params);
  194575. }
  194576. #endif
  194577. #if defined(PNG_READ_sCAL_SUPPORTED)
  194578. /* read the sCAL chunk */
  194579. void /* PRIVATE */
  194580. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194581. {
  194582. png_charp buffer, ep;
  194583. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194584. double width, height;
  194585. png_charp vp;
  194586. #else
  194587. #ifdef PNG_FIXED_POINT_SUPPORTED
  194588. png_charp swidth, sheight;
  194589. #endif
  194590. #endif
  194591. png_size_t slength;
  194592. png_debug(1, "in png_handle_sCAL\n");
  194593. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194594. png_error(png_ptr, "Missing IHDR before sCAL");
  194595. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194596. {
  194597. png_warning(png_ptr, "Invalid sCAL after IDAT");
  194598. png_crc_finish(png_ptr, length);
  194599. return;
  194600. }
  194601. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  194602. {
  194603. png_warning(png_ptr, "Duplicate sCAL chunk");
  194604. png_crc_finish(png_ptr, length);
  194605. return;
  194606. }
  194607. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  194608. length + 1);
  194609. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  194610. if (buffer == NULL)
  194611. {
  194612. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  194613. return;
  194614. }
  194615. slength = (png_size_t)length;
  194616. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  194617. if (png_crc_finish(png_ptr, 0))
  194618. {
  194619. png_free(png_ptr, buffer);
  194620. return;
  194621. }
  194622. buffer[slength] = 0x00; /* null terminate the last string */
  194623. ep = buffer + 1; /* skip unit byte */
  194624. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194625. width = png_strtod(png_ptr, ep, &vp);
  194626. if (*vp)
  194627. {
  194628. png_warning(png_ptr, "malformed width string in sCAL chunk");
  194629. return;
  194630. }
  194631. #else
  194632. #ifdef PNG_FIXED_POINT_SUPPORTED
  194633. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  194634. if (swidth == NULL)
  194635. {
  194636. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  194637. return;
  194638. }
  194639. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  194640. #endif
  194641. #endif
  194642. for (ep = buffer; *ep; ep++)
  194643. /* empty loop */ ;
  194644. ep++;
  194645. if (buffer + slength < ep)
  194646. {
  194647. png_warning(png_ptr, "Truncated sCAL chunk");
  194648. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  194649. !defined(PNG_FLOATING_POINT_SUPPORTED)
  194650. png_free(png_ptr, swidth);
  194651. #endif
  194652. png_free(png_ptr, buffer);
  194653. return;
  194654. }
  194655. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194656. height = png_strtod(png_ptr, ep, &vp);
  194657. if (*vp)
  194658. {
  194659. png_warning(png_ptr, "malformed height string in sCAL chunk");
  194660. return;
  194661. }
  194662. #else
  194663. #ifdef PNG_FIXED_POINT_SUPPORTED
  194664. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  194665. if (swidth == NULL)
  194666. {
  194667. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  194668. return;
  194669. }
  194670. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  194671. #endif
  194672. #endif
  194673. if (buffer + slength < ep
  194674. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194675. || width <= 0. || height <= 0.
  194676. #endif
  194677. )
  194678. {
  194679. png_warning(png_ptr, "Invalid sCAL data");
  194680. png_free(png_ptr, buffer);
  194681. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  194682. png_free(png_ptr, swidth);
  194683. png_free(png_ptr, sheight);
  194684. #endif
  194685. return;
  194686. }
  194687. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194688. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  194689. #else
  194690. #ifdef PNG_FIXED_POINT_SUPPORTED
  194691. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  194692. #endif
  194693. #endif
  194694. png_free(png_ptr, buffer);
  194695. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  194696. png_free(png_ptr, swidth);
  194697. png_free(png_ptr, sheight);
  194698. #endif
  194699. }
  194700. #endif
  194701. #if defined(PNG_READ_tIME_SUPPORTED)
  194702. void /* PRIVATE */
  194703. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194704. {
  194705. png_byte buf[7];
  194706. png_time mod_time;
  194707. png_debug(1, "in png_handle_tIME\n");
  194708. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194709. png_error(png_ptr, "Out of place tIME chunk");
  194710. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  194711. {
  194712. png_warning(png_ptr, "Duplicate tIME chunk");
  194713. png_crc_finish(png_ptr, length);
  194714. return;
  194715. }
  194716. if (png_ptr->mode & PNG_HAVE_IDAT)
  194717. png_ptr->mode |= PNG_AFTER_IDAT;
  194718. if (length != 7)
  194719. {
  194720. png_warning(png_ptr, "Incorrect tIME chunk length");
  194721. png_crc_finish(png_ptr, length);
  194722. return;
  194723. }
  194724. png_crc_read(png_ptr, buf, 7);
  194725. if (png_crc_finish(png_ptr, 0))
  194726. return;
  194727. mod_time.second = buf[6];
  194728. mod_time.minute = buf[5];
  194729. mod_time.hour = buf[4];
  194730. mod_time.day = buf[3];
  194731. mod_time.month = buf[2];
  194732. mod_time.year = png_get_uint_16(buf);
  194733. png_set_tIME(png_ptr, info_ptr, &mod_time);
  194734. }
  194735. #endif
  194736. #if defined(PNG_READ_tEXt_SUPPORTED)
  194737. /* Note: this does not properly handle chunks that are > 64K under DOS */
  194738. void /* PRIVATE */
  194739. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194740. {
  194741. png_textp text_ptr;
  194742. png_charp key;
  194743. png_charp text;
  194744. png_uint_32 skip = 0;
  194745. png_size_t slength;
  194746. int ret;
  194747. png_debug(1, "in png_handle_tEXt\n");
  194748. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194749. png_error(png_ptr, "Missing IHDR before tEXt");
  194750. if (png_ptr->mode & PNG_HAVE_IDAT)
  194751. png_ptr->mode |= PNG_AFTER_IDAT;
  194752. #ifdef PNG_MAX_MALLOC_64K
  194753. if (length > (png_uint_32)65535L)
  194754. {
  194755. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  194756. skip = length - (png_uint_32)65535L;
  194757. length = (png_uint_32)65535L;
  194758. }
  194759. #endif
  194760. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  194761. if (key == NULL)
  194762. {
  194763. png_warning(png_ptr, "No memory to process text chunk.");
  194764. return;
  194765. }
  194766. slength = (png_size_t)length;
  194767. png_crc_read(png_ptr, (png_bytep)key, slength);
  194768. if (png_crc_finish(png_ptr, skip))
  194769. {
  194770. png_free(png_ptr, key);
  194771. return;
  194772. }
  194773. key[slength] = 0x00;
  194774. for (text = key; *text; text++)
  194775. /* empty loop to find end of key */ ;
  194776. if (text != key + slength)
  194777. text++;
  194778. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  194779. (png_uint_32)png_sizeof(png_text));
  194780. if (text_ptr == NULL)
  194781. {
  194782. png_warning(png_ptr, "Not enough memory to process text chunk.");
  194783. png_free(png_ptr, key);
  194784. return;
  194785. }
  194786. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  194787. text_ptr->key = key;
  194788. #ifdef PNG_iTXt_SUPPORTED
  194789. text_ptr->lang = NULL;
  194790. text_ptr->lang_key = NULL;
  194791. text_ptr->itxt_length = 0;
  194792. #endif
  194793. text_ptr->text = text;
  194794. text_ptr->text_length = png_strlen(text);
  194795. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  194796. png_free(png_ptr, key);
  194797. png_free(png_ptr, text_ptr);
  194798. if (ret)
  194799. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  194800. }
  194801. #endif
  194802. #if defined(PNG_READ_zTXt_SUPPORTED)
  194803. /* note: this does not correctly handle chunks that are > 64K under DOS */
  194804. void /* PRIVATE */
  194805. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194806. {
  194807. png_textp text_ptr;
  194808. png_charp chunkdata;
  194809. png_charp text;
  194810. int comp_type;
  194811. int ret;
  194812. png_size_t slength, prefix_len, data_len;
  194813. png_debug(1, "in png_handle_zTXt\n");
  194814. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194815. png_error(png_ptr, "Missing IHDR before zTXt");
  194816. if (png_ptr->mode & PNG_HAVE_IDAT)
  194817. png_ptr->mode |= PNG_AFTER_IDAT;
  194818. #ifdef PNG_MAX_MALLOC_64K
  194819. /* We will no doubt have problems with chunks even half this size, but
  194820. there is no hard and fast rule to tell us where to stop. */
  194821. if (length > (png_uint_32)65535L)
  194822. {
  194823. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  194824. png_crc_finish(png_ptr, length);
  194825. return;
  194826. }
  194827. #endif
  194828. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  194829. if (chunkdata == NULL)
  194830. {
  194831. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  194832. return;
  194833. }
  194834. slength = (png_size_t)length;
  194835. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194836. if (png_crc_finish(png_ptr, 0))
  194837. {
  194838. png_free(png_ptr, chunkdata);
  194839. return;
  194840. }
  194841. chunkdata[slength] = 0x00;
  194842. for (text = chunkdata; *text; text++)
  194843. /* empty loop */ ;
  194844. /* zTXt must have some text after the chunkdataword */
  194845. if (text >= chunkdata + slength - 2)
  194846. {
  194847. png_warning(png_ptr, "Truncated zTXt chunk");
  194848. png_free(png_ptr, chunkdata);
  194849. return;
  194850. }
  194851. else
  194852. {
  194853. comp_type = *(++text);
  194854. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  194855. {
  194856. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  194857. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  194858. }
  194859. text++; /* skip the compression_method byte */
  194860. }
  194861. prefix_len = text - chunkdata;
  194862. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  194863. (png_size_t)length, prefix_len, &data_len);
  194864. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  194865. (png_uint_32)png_sizeof(png_text));
  194866. if (text_ptr == NULL)
  194867. {
  194868. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  194869. png_free(png_ptr, chunkdata);
  194870. return;
  194871. }
  194872. text_ptr->compression = comp_type;
  194873. text_ptr->key = chunkdata;
  194874. #ifdef PNG_iTXt_SUPPORTED
  194875. text_ptr->lang = NULL;
  194876. text_ptr->lang_key = NULL;
  194877. text_ptr->itxt_length = 0;
  194878. #endif
  194879. text_ptr->text = chunkdata + prefix_len;
  194880. text_ptr->text_length = data_len;
  194881. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  194882. png_free(png_ptr, text_ptr);
  194883. png_free(png_ptr, chunkdata);
  194884. if (ret)
  194885. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  194886. }
  194887. #endif
  194888. #if defined(PNG_READ_iTXt_SUPPORTED)
  194889. /* note: this does not correctly handle chunks that are > 64K under DOS */
  194890. void /* PRIVATE */
  194891. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194892. {
  194893. png_textp text_ptr;
  194894. png_charp chunkdata;
  194895. png_charp key, lang, text, lang_key;
  194896. int comp_flag;
  194897. int comp_type = 0;
  194898. int ret;
  194899. png_size_t slength, prefix_len, data_len;
  194900. png_debug(1, "in png_handle_iTXt\n");
  194901. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194902. png_error(png_ptr, "Missing IHDR before iTXt");
  194903. if (png_ptr->mode & PNG_HAVE_IDAT)
  194904. png_ptr->mode |= PNG_AFTER_IDAT;
  194905. #ifdef PNG_MAX_MALLOC_64K
  194906. /* We will no doubt have problems with chunks even half this size, but
  194907. there is no hard and fast rule to tell us where to stop. */
  194908. if (length > (png_uint_32)65535L)
  194909. {
  194910. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  194911. png_crc_finish(png_ptr, length);
  194912. return;
  194913. }
  194914. #endif
  194915. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  194916. if (chunkdata == NULL)
  194917. {
  194918. png_warning(png_ptr, "No memory to process iTXt chunk.");
  194919. return;
  194920. }
  194921. slength = (png_size_t)length;
  194922. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194923. if (png_crc_finish(png_ptr, 0))
  194924. {
  194925. png_free(png_ptr, chunkdata);
  194926. return;
  194927. }
  194928. chunkdata[slength] = 0x00;
  194929. for (lang = chunkdata; *lang; lang++)
  194930. /* empty loop */ ;
  194931. lang++; /* skip NUL separator */
  194932. /* iTXt must have a language tag (possibly empty), two compression bytes,
  194933. translated keyword (possibly empty), and possibly some text after the
  194934. keyword */
  194935. if (lang >= chunkdata + slength - 3)
  194936. {
  194937. png_warning(png_ptr, "Truncated iTXt chunk");
  194938. png_free(png_ptr, chunkdata);
  194939. return;
  194940. }
  194941. else
  194942. {
  194943. comp_flag = *lang++;
  194944. comp_type = *lang++;
  194945. }
  194946. for (lang_key = lang; *lang_key; lang_key++)
  194947. /* empty loop */ ;
  194948. lang_key++; /* skip NUL separator */
  194949. if (lang_key >= chunkdata + slength)
  194950. {
  194951. png_warning(png_ptr, "Truncated iTXt chunk");
  194952. png_free(png_ptr, chunkdata);
  194953. return;
  194954. }
  194955. for (text = lang_key; *text; text++)
  194956. /* empty loop */ ;
  194957. text++; /* skip NUL separator */
  194958. if (text >= chunkdata + slength)
  194959. {
  194960. png_warning(png_ptr, "Malformed iTXt chunk");
  194961. png_free(png_ptr, chunkdata);
  194962. return;
  194963. }
  194964. prefix_len = text - chunkdata;
  194965. key=chunkdata;
  194966. if (comp_flag)
  194967. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  194968. (size_t)length, prefix_len, &data_len);
  194969. else
  194970. data_len=png_strlen(chunkdata + prefix_len);
  194971. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  194972. (png_uint_32)png_sizeof(png_text));
  194973. if (text_ptr == NULL)
  194974. {
  194975. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  194976. png_free(png_ptr, chunkdata);
  194977. return;
  194978. }
  194979. text_ptr->compression = (int)comp_flag + 1;
  194980. text_ptr->lang_key = chunkdata+(lang_key-key);
  194981. text_ptr->lang = chunkdata+(lang-key);
  194982. text_ptr->itxt_length = data_len;
  194983. text_ptr->text_length = 0;
  194984. text_ptr->key = chunkdata;
  194985. text_ptr->text = chunkdata + prefix_len;
  194986. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  194987. png_free(png_ptr, text_ptr);
  194988. png_free(png_ptr, chunkdata);
  194989. if (ret)
  194990. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  194991. }
  194992. #endif
  194993. /* This function is called when we haven't found a handler for a
  194994. chunk. If there isn't a problem with the chunk itself (ie bad
  194995. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  194996. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  194997. case it will be saved away to be written out later. */
  194998. void /* PRIVATE */
  194999. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195000. {
  195001. png_uint_32 skip = 0;
  195002. png_debug(1, "in png_handle_unknown\n");
  195003. if (png_ptr->mode & PNG_HAVE_IDAT)
  195004. {
  195005. #ifdef PNG_USE_LOCAL_ARRAYS
  195006. PNG_CONST PNG_IDAT;
  195007. #endif
  195008. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  195009. png_ptr->mode |= PNG_AFTER_IDAT;
  195010. }
  195011. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  195012. if (!(png_ptr->chunk_name[0] & 0x20))
  195013. {
  195014. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  195015. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  195016. PNG_HANDLE_CHUNK_ALWAYS
  195017. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195018. && png_ptr->read_user_chunk_fn == NULL
  195019. #endif
  195020. )
  195021. #endif
  195022. png_chunk_error(png_ptr, "unknown critical chunk");
  195023. }
  195024. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  195025. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  195026. (png_ptr->read_user_chunk_fn != NULL))
  195027. {
  195028. #ifdef PNG_MAX_MALLOC_64K
  195029. if (length > (png_uint_32)65535L)
  195030. {
  195031. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  195032. skip = length - (png_uint_32)65535L;
  195033. length = (png_uint_32)65535L;
  195034. }
  195035. #endif
  195036. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  195037. (png_charp)png_ptr->chunk_name, 5);
  195038. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  195039. png_ptr->unknown_chunk.size = (png_size_t)length;
  195040. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  195041. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195042. if(png_ptr->read_user_chunk_fn != NULL)
  195043. {
  195044. /* callback to user unknown chunk handler */
  195045. int ret;
  195046. ret = (*(png_ptr->read_user_chunk_fn))
  195047. (png_ptr, &png_ptr->unknown_chunk);
  195048. if (ret < 0)
  195049. png_chunk_error(png_ptr, "error in user chunk");
  195050. if (ret == 0)
  195051. {
  195052. if (!(png_ptr->chunk_name[0] & 0x20))
  195053. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  195054. PNG_HANDLE_CHUNK_ALWAYS)
  195055. png_chunk_error(png_ptr, "unknown critical chunk");
  195056. png_set_unknown_chunks(png_ptr, info_ptr,
  195057. &png_ptr->unknown_chunk, 1);
  195058. }
  195059. }
  195060. #else
  195061. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  195062. #endif
  195063. png_free(png_ptr, png_ptr->unknown_chunk.data);
  195064. png_ptr->unknown_chunk.data = NULL;
  195065. }
  195066. else
  195067. #endif
  195068. skip = length;
  195069. png_crc_finish(png_ptr, skip);
  195070. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195071. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  195072. #endif
  195073. }
  195074. /* This function is called to verify that a chunk name is valid.
  195075. This function can't have the "critical chunk check" incorporated
  195076. into it, since in the future we will need to be able to call user
  195077. functions to handle unknown critical chunks after we check that
  195078. the chunk name itself is valid. */
  195079. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  195080. void /* PRIVATE */
  195081. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  195082. {
  195083. png_debug(1, "in png_check_chunk_name\n");
  195084. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  195085. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  195086. {
  195087. png_chunk_error(png_ptr, "invalid chunk type");
  195088. }
  195089. }
  195090. /* Combines the row recently read in with the existing pixels in the
  195091. row. This routine takes care of alpha and transparency if requested.
  195092. This routine also handles the two methods of progressive display
  195093. of interlaced images, depending on the mask value.
  195094. The mask value describes which pixels are to be combined with
  195095. the row. The pattern always repeats every 8 pixels, so just 8
  195096. bits are needed. A one indicates the pixel is to be combined,
  195097. a zero indicates the pixel is to be skipped. This is in addition
  195098. to any alpha or transparency value associated with the pixel. If
  195099. you want all pixels to be combined, pass 0xff (255) in mask. */
  195100. void /* PRIVATE */
  195101. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  195102. {
  195103. png_debug(1,"in png_combine_row\n");
  195104. if (mask == 0xff)
  195105. {
  195106. png_memcpy(row, png_ptr->row_buf + 1,
  195107. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  195108. }
  195109. else
  195110. {
  195111. switch (png_ptr->row_info.pixel_depth)
  195112. {
  195113. case 1:
  195114. {
  195115. png_bytep sp = png_ptr->row_buf + 1;
  195116. png_bytep dp = row;
  195117. int s_inc, s_start, s_end;
  195118. int m = 0x80;
  195119. int shift;
  195120. png_uint_32 i;
  195121. png_uint_32 row_width = png_ptr->width;
  195122. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195123. if (png_ptr->transformations & PNG_PACKSWAP)
  195124. {
  195125. s_start = 0;
  195126. s_end = 7;
  195127. s_inc = 1;
  195128. }
  195129. else
  195130. #endif
  195131. {
  195132. s_start = 7;
  195133. s_end = 0;
  195134. s_inc = -1;
  195135. }
  195136. shift = s_start;
  195137. for (i = 0; i < row_width; i++)
  195138. {
  195139. if (m & mask)
  195140. {
  195141. int value;
  195142. value = (*sp >> shift) & 0x01;
  195143. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  195144. *dp |= (png_byte)(value << shift);
  195145. }
  195146. if (shift == s_end)
  195147. {
  195148. shift = s_start;
  195149. sp++;
  195150. dp++;
  195151. }
  195152. else
  195153. shift += s_inc;
  195154. if (m == 1)
  195155. m = 0x80;
  195156. else
  195157. m >>= 1;
  195158. }
  195159. break;
  195160. }
  195161. case 2:
  195162. {
  195163. png_bytep sp = png_ptr->row_buf + 1;
  195164. png_bytep dp = row;
  195165. int s_start, s_end, s_inc;
  195166. int m = 0x80;
  195167. int shift;
  195168. png_uint_32 i;
  195169. png_uint_32 row_width = png_ptr->width;
  195170. int value;
  195171. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195172. if (png_ptr->transformations & PNG_PACKSWAP)
  195173. {
  195174. s_start = 0;
  195175. s_end = 6;
  195176. s_inc = 2;
  195177. }
  195178. else
  195179. #endif
  195180. {
  195181. s_start = 6;
  195182. s_end = 0;
  195183. s_inc = -2;
  195184. }
  195185. shift = s_start;
  195186. for (i = 0; i < row_width; i++)
  195187. {
  195188. if (m & mask)
  195189. {
  195190. value = (*sp >> shift) & 0x03;
  195191. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  195192. *dp |= (png_byte)(value << shift);
  195193. }
  195194. if (shift == s_end)
  195195. {
  195196. shift = s_start;
  195197. sp++;
  195198. dp++;
  195199. }
  195200. else
  195201. shift += s_inc;
  195202. if (m == 1)
  195203. m = 0x80;
  195204. else
  195205. m >>= 1;
  195206. }
  195207. break;
  195208. }
  195209. case 4:
  195210. {
  195211. png_bytep sp = png_ptr->row_buf + 1;
  195212. png_bytep dp = row;
  195213. int s_start, s_end, s_inc;
  195214. int m = 0x80;
  195215. int shift;
  195216. png_uint_32 i;
  195217. png_uint_32 row_width = png_ptr->width;
  195218. int value;
  195219. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195220. if (png_ptr->transformations & PNG_PACKSWAP)
  195221. {
  195222. s_start = 0;
  195223. s_end = 4;
  195224. s_inc = 4;
  195225. }
  195226. else
  195227. #endif
  195228. {
  195229. s_start = 4;
  195230. s_end = 0;
  195231. s_inc = -4;
  195232. }
  195233. shift = s_start;
  195234. for (i = 0; i < row_width; i++)
  195235. {
  195236. if (m & mask)
  195237. {
  195238. value = (*sp >> shift) & 0xf;
  195239. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  195240. *dp |= (png_byte)(value << shift);
  195241. }
  195242. if (shift == s_end)
  195243. {
  195244. shift = s_start;
  195245. sp++;
  195246. dp++;
  195247. }
  195248. else
  195249. shift += s_inc;
  195250. if (m == 1)
  195251. m = 0x80;
  195252. else
  195253. m >>= 1;
  195254. }
  195255. break;
  195256. }
  195257. default:
  195258. {
  195259. png_bytep sp = png_ptr->row_buf + 1;
  195260. png_bytep dp = row;
  195261. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  195262. png_uint_32 i;
  195263. png_uint_32 row_width = png_ptr->width;
  195264. png_byte m = 0x80;
  195265. for (i = 0; i < row_width; i++)
  195266. {
  195267. if (m & mask)
  195268. {
  195269. png_memcpy(dp, sp, pixel_bytes);
  195270. }
  195271. sp += pixel_bytes;
  195272. dp += pixel_bytes;
  195273. if (m == 1)
  195274. m = 0x80;
  195275. else
  195276. m >>= 1;
  195277. }
  195278. break;
  195279. }
  195280. }
  195281. }
  195282. }
  195283. #ifdef PNG_READ_INTERLACING_SUPPORTED
  195284. /* OLD pre-1.0.9 interface:
  195285. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  195286. png_uint_32 transformations)
  195287. */
  195288. void /* PRIVATE */
  195289. png_do_read_interlace(png_structp png_ptr)
  195290. {
  195291. png_row_infop row_info = &(png_ptr->row_info);
  195292. png_bytep row = png_ptr->row_buf + 1;
  195293. int pass = png_ptr->pass;
  195294. png_uint_32 transformations = png_ptr->transformations;
  195295. #ifdef PNG_USE_LOCAL_ARRAYS
  195296. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  195297. /* offset to next interlace block */
  195298. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  195299. #endif
  195300. png_debug(1,"in png_do_read_interlace\n");
  195301. if (row != NULL && row_info != NULL)
  195302. {
  195303. png_uint_32 final_width;
  195304. final_width = row_info->width * png_pass_inc[pass];
  195305. switch (row_info->pixel_depth)
  195306. {
  195307. case 1:
  195308. {
  195309. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  195310. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  195311. int sshift, dshift;
  195312. int s_start, s_end, s_inc;
  195313. int jstop = png_pass_inc[pass];
  195314. png_byte v;
  195315. png_uint_32 i;
  195316. int j;
  195317. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195318. if (transformations & PNG_PACKSWAP)
  195319. {
  195320. sshift = (int)((row_info->width + 7) & 0x07);
  195321. dshift = (int)((final_width + 7) & 0x07);
  195322. s_start = 7;
  195323. s_end = 0;
  195324. s_inc = -1;
  195325. }
  195326. else
  195327. #endif
  195328. {
  195329. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  195330. dshift = 7 - (int)((final_width + 7) & 0x07);
  195331. s_start = 0;
  195332. s_end = 7;
  195333. s_inc = 1;
  195334. }
  195335. for (i = 0; i < row_info->width; i++)
  195336. {
  195337. v = (png_byte)((*sp >> sshift) & 0x01);
  195338. for (j = 0; j < jstop; j++)
  195339. {
  195340. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  195341. *dp |= (png_byte)(v << dshift);
  195342. if (dshift == s_end)
  195343. {
  195344. dshift = s_start;
  195345. dp--;
  195346. }
  195347. else
  195348. dshift += s_inc;
  195349. }
  195350. if (sshift == s_end)
  195351. {
  195352. sshift = s_start;
  195353. sp--;
  195354. }
  195355. else
  195356. sshift += s_inc;
  195357. }
  195358. break;
  195359. }
  195360. case 2:
  195361. {
  195362. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  195363. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  195364. int sshift, dshift;
  195365. int s_start, s_end, s_inc;
  195366. int jstop = png_pass_inc[pass];
  195367. png_uint_32 i;
  195368. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195369. if (transformations & PNG_PACKSWAP)
  195370. {
  195371. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  195372. dshift = (int)(((final_width + 3) & 0x03) << 1);
  195373. s_start = 6;
  195374. s_end = 0;
  195375. s_inc = -2;
  195376. }
  195377. else
  195378. #endif
  195379. {
  195380. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  195381. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  195382. s_start = 0;
  195383. s_end = 6;
  195384. s_inc = 2;
  195385. }
  195386. for (i = 0; i < row_info->width; i++)
  195387. {
  195388. png_byte v;
  195389. int j;
  195390. v = (png_byte)((*sp >> sshift) & 0x03);
  195391. for (j = 0; j < jstop; j++)
  195392. {
  195393. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  195394. *dp |= (png_byte)(v << dshift);
  195395. if (dshift == s_end)
  195396. {
  195397. dshift = s_start;
  195398. dp--;
  195399. }
  195400. else
  195401. dshift += s_inc;
  195402. }
  195403. if (sshift == s_end)
  195404. {
  195405. sshift = s_start;
  195406. sp--;
  195407. }
  195408. else
  195409. sshift += s_inc;
  195410. }
  195411. break;
  195412. }
  195413. case 4:
  195414. {
  195415. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  195416. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  195417. int sshift, dshift;
  195418. int s_start, s_end, s_inc;
  195419. png_uint_32 i;
  195420. int jstop = png_pass_inc[pass];
  195421. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195422. if (transformations & PNG_PACKSWAP)
  195423. {
  195424. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  195425. dshift = (int)(((final_width + 1) & 0x01) << 2);
  195426. s_start = 4;
  195427. s_end = 0;
  195428. s_inc = -4;
  195429. }
  195430. else
  195431. #endif
  195432. {
  195433. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  195434. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  195435. s_start = 0;
  195436. s_end = 4;
  195437. s_inc = 4;
  195438. }
  195439. for (i = 0; i < row_info->width; i++)
  195440. {
  195441. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  195442. int j;
  195443. for (j = 0; j < jstop; j++)
  195444. {
  195445. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  195446. *dp |= (png_byte)(v << dshift);
  195447. if (dshift == s_end)
  195448. {
  195449. dshift = s_start;
  195450. dp--;
  195451. }
  195452. else
  195453. dshift += s_inc;
  195454. }
  195455. if (sshift == s_end)
  195456. {
  195457. sshift = s_start;
  195458. sp--;
  195459. }
  195460. else
  195461. sshift += s_inc;
  195462. }
  195463. break;
  195464. }
  195465. default:
  195466. {
  195467. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  195468. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  195469. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  195470. int jstop = png_pass_inc[pass];
  195471. png_uint_32 i;
  195472. for (i = 0; i < row_info->width; i++)
  195473. {
  195474. png_byte v[8];
  195475. int j;
  195476. png_memcpy(v, sp, pixel_bytes);
  195477. for (j = 0; j < jstop; j++)
  195478. {
  195479. png_memcpy(dp, v, pixel_bytes);
  195480. dp -= pixel_bytes;
  195481. }
  195482. sp -= pixel_bytes;
  195483. }
  195484. break;
  195485. }
  195486. }
  195487. row_info->width = final_width;
  195488. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  195489. }
  195490. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  195491. transformations = transformations; /* silence compiler warning */
  195492. #endif
  195493. }
  195494. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  195495. void /* PRIVATE */
  195496. png_read_filter_row(png_structp, png_row_infop row_info, png_bytep row,
  195497. png_bytep prev_row, int filter)
  195498. {
  195499. png_debug(1, "in png_read_filter_row\n");
  195500. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  195501. switch (filter)
  195502. {
  195503. case PNG_FILTER_VALUE_NONE:
  195504. break;
  195505. case PNG_FILTER_VALUE_SUB:
  195506. {
  195507. png_uint_32 i;
  195508. png_uint_32 istop = row_info->rowbytes;
  195509. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  195510. png_bytep rp = row + bpp;
  195511. png_bytep lp = row;
  195512. for (i = bpp; i < istop; i++)
  195513. {
  195514. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  195515. rp++;
  195516. }
  195517. break;
  195518. }
  195519. case PNG_FILTER_VALUE_UP:
  195520. {
  195521. png_uint_32 i;
  195522. png_uint_32 istop = row_info->rowbytes;
  195523. png_bytep rp = row;
  195524. png_bytep pp = prev_row;
  195525. for (i = 0; i < istop; i++)
  195526. {
  195527. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  195528. rp++;
  195529. }
  195530. break;
  195531. }
  195532. case PNG_FILTER_VALUE_AVG:
  195533. {
  195534. png_uint_32 i;
  195535. png_bytep rp = row;
  195536. png_bytep pp = prev_row;
  195537. png_bytep lp = row;
  195538. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  195539. png_uint_32 istop = row_info->rowbytes - bpp;
  195540. for (i = 0; i < bpp; i++)
  195541. {
  195542. *rp = (png_byte)(((int)(*rp) +
  195543. ((int)(*pp++) / 2 )) & 0xff);
  195544. rp++;
  195545. }
  195546. for (i = 0; i < istop; i++)
  195547. {
  195548. *rp = (png_byte)(((int)(*rp) +
  195549. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  195550. rp++;
  195551. }
  195552. break;
  195553. }
  195554. case PNG_FILTER_VALUE_PAETH:
  195555. {
  195556. png_uint_32 i;
  195557. png_bytep rp = row;
  195558. png_bytep pp = prev_row;
  195559. png_bytep lp = row;
  195560. png_bytep cp = prev_row;
  195561. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  195562. png_uint_32 istop=row_info->rowbytes - bpp;
  195563. for (i = 0; i < bpp; i++)
  195564. {
  195565. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  195566. rp++;
  195567. }
  195568. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  195569. {
  195570. int a, b, c, pa, pb, pc, p;
  195571. a = *lp++;
  195572. b = *pp++;
  195573. c = *cp++;
  195574. p = b - c;
  195575. pc = a - c;
  195576. #ifdef PNG_USE_ABS
  195577. pa = abs(p);
  195578. pb = abs(pc);
  195579. pc = abs(p + pc);
  195580. #else
  195581. pa = p < 0 ? -p : p;
  195582. pb = pc < 0 ? -pc : pc;
  195583. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  195584. #endif
  195585. /*
  195586. if (pa <= pb && pa <= pc)
  195587. p = a;
  195588. else if (pb <= pc)
  195589. p = b;
  195590. else
  195591. p = c;
  195592. */
  195593. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  195594. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  195595. rp++;
  195596. }
  195597. break;
  195598. }
  195599. default:
  195600. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  195601. *row=0;
  195602. break;
  195603. }
  195604. }
  195605. void /* PRIVATE */
  195606. png_read_finish_row(png_structp png_ptr)
  195607. {
  195608. #ifdef PNG_USE_LOCAL_ARRAYS
  195609. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  195610. /* start of interlace block */
  195611. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  195612. /* offset to next interlace block */
  195613. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  195614. /* start of interlace block in the y direction */
  195615. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  195616. /* offset to next interlace block in the y direction */
  195617. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  195618. #endif
  195619. png_debug(1, "in png_read_finish_row\n");
  195620. png_ptr->row_number++;
  195621. if (png_ptr->row_number < png_ptr->num_rows)
  195622. return;
  195623. if (png_ptr->interlaced)
  195624. {
  195625. png_ptr->row_number = 0;
  195626. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  195627. png_ptr->rowbytes + 1);
  195628. do
  195629. {
  195630. png_ptr->pass++;
  195631. if (png_ptr->pass >= 7)
  195632. break;
  195633. png_ptr->iwidth = (png_ptr->width +
  195634. png_pass_inc[png_ptr->pass] - 1 -
  195635. png_pass_start[png_ptr->pass]) /
  195636. png_pass_inc[png_ptr->pass];
  195637. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  195638. png_ptr->iwidth) + 1;
  195639. if (!(png_ptr->transformations & PNG_INTERLACE))
  195640. {
  195641. png_ptr->num_rows = (png_ptr->height +
  195642. png_pass_yinc[png_ptr->pass] - 1 -
  195643. png_pass_ystart[png_ptr->pass]) /
  195644. png_pass_yinc[png_ptr->pass];
  195645. if (!(png_ptr->num_rows))
  195646. continue;
  195647. }
  195648. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  195649. break;
  195650. } while (png_ptr->iwidth == 0);
  195651. if (png_ptr->pass < 7)
  195652. return;
  195653. }
  195654. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  195655. {
  195656. #ifdef PNG_USE_LOCAL_ARRAYS
  195657. PNG_CONST PNG_IDAT;
  195658. #endif
  195659. char extra;
  195660. int ret;
  195661. png_ptr->zstream.next_out = (Bytef *)&extra;
  195662. png_ptr->zstream.avail_out = (uInt)1;
  195663. for(;;)
  195664. {
  195665. if (!(png_ptr->zstream.avail_in))
  195666. {
  195667. while (!png_ptr->idat_size)
  195668. {
  195669. png_byte chunk_length[4];
  195670. png_crc_finish(png_ptr, 0);
  195671. png_read_data(png_ptr, chunk_length, 4);
  195672. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  195673. png_reset_crc(png_ptr);
  195674. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  195675. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  195676. png_error(png_ptr, "Not enough image data");
  195677. }
  195678. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  195679. png_ptr->zstream.next_in = png_ptr->zbuf;
  195680. if (png_ptr->zbuf_size > png_ptr->idat_size)
  195681. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  195682. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  195683. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  195684. }
  195685. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  195686. if (ret == Z_STREAM_END)
  195687. {
  195688. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  195689. png_ptr->idat_size)
  195690. png_warning(png_ptr, "Extra compressed data");
  195691. png_ptr->mode |= PNG_AFTER_IDAT;
  195692. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  195693. break;
  195694. }
  195695. if (ret != Z_OK)
  195696. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  195697. "Decompression Error");
  195698. if (!(png_ptr->zstream.avail_out))
  195699. {
  195700. png_warning(png_ptr, "Extra compressed data.");
  195701. png_ptr->mode |= PNG_AFTER_IDAT;
  195702. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  195703. break;
  195704. }
  195705. }
  195706. png_ptr->zstream.avail_out = 0;
  195707. }
  195708. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  195709. png_warning(png_ptr, "Extra compression data");
  195710. inflateReset(&png_ptr->zstream);
  195711. png_ptr->mode |= PNG_AFTER_IDAT;
  195712. }
  195713. void /* PRIVATE */
  195714. png_read_start_row(png_structp png_ptr)
  195715. {
  195716. #ifdef PNG_USE_LOCAL_ARRAYS
  195717. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  195718. /* start of interlace block */
  195719. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  195720. /* offset to next interlace block */
  195721. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  195722. /* start of interlace block in the y direction */
  195723. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  195724. /* offset to next interlace block in the y direction */
  195725. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  195726. #endif
  195727. int max_pixel_depth;
  195728. png_uint_32 row_bytes;
  195729. png_debug(1, "in png_read_start_row\n");
  195730. png_ptr->zstream.avail_in = 0;
  195731. png_init_read_transformations(png_ptr);
  195732. if (png_ptr->interlaced)
  195733. {
  195734. if (!(png_ptr->transformations & PNG_INTERLACE))
  195735. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  195736. png_pass_ystart[0]) / png_pass_yinc[0];
  195737. else
  195738. png_ptr->num_rows = png_ptr->height;
  195739. png_ptr->iwidth = (png_ptr->width +
  195740. png_pass_inc[png_ptr->pass] - 1 -
  195741. png_pass_start[png_ptr->pass]) /
  195742. png_pass_inc[png_ptr->pass];
  195743. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  195744. png_ptr->irowbytes = (png_size_t)row_bytes;
  195745. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  195746. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  195747. }
  195748. else
  195749. {
  195750. png_ptr->num_rows = png_ptr->height;
  195751. png_ptr->iwidth = png_ptr->width;
  195752. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  195753. }
  195754. max_pixel_depth = png_ptr->pixel_depth;
  195755. #if defined(PNG_READ_PACK_SUPPORTED)
  195756. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  195757. max_pixel_depth = 8;
  195758. #endif
  195759. #if defined(PNG_READ_EXPAND_SUPPORTED)
  195760. if (png_ptr->transformations & PNG_EXPAND)
  195761. {
  195762. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195763. {
  195764. if (png_ptr->num_trans)
  195765. max_pixel_depth = 32;
  195766. else
  195767. max_pixel_depth = 24;
  195768. }
  195769. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  195770. {
  195771. if (max_pixel_depth < 8)
  195772. max_pixel_depth = 8;
  195773. if (png_ptr->num_trans)
  195774. max_pixel_depth *= 2;
  195775. }
  195776. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  195777. {
  195778. if (png_ptr->num_trans)
  195779. {
  195780. max_pixel_depth *= 4;
  195781. max_pixel_depth /= 3;
  195782. }
  195783. }
  195784. }
  195785. #endif
  195786. #if defined(PNG_READ_FILLER_SUPPORTED)
  195787. if (png_ptr->transformations & (PNG_FILLER))
  195788. {
  195789. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195790. max_pixel_depth = 32;
  195791. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  195792. {
  195793. if (max_pixel_depth <= 8)
  195794. max_pixel_depth = 16;
  195795. else
  195796. max_pixel_depth = 32;
  195797. }
  195798. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  195799. {
  195800. if (max_pixel_depth <= 32)
  195801. max_pixel_depth = 32;
  195802. else
  195803. max_pixel_depth = 64;
  195804. }
  195805. }
  195806. #endif
  195807. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  195808. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  195809. {
  195810. if (
  195811. #if defined(PNG_READ_EXPAND_SUPPORTED)
  195812. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  195813. #endif
  195814. #if defined(PNG_READ_FILLER_SUPPORTED)
  195815. (png_ptr->transformations & (PNG_FILLER)) ||
  195816. #endif
  195817. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  195818. {
  195819. if (max_pixel_depth <= 16)
  195820. max_pixel_depth = 32;
  195821. else
  195822. max_pixel_depth = 64;
  195823. }
  195824. else
  195825. {
  195826. if (max_pixel_depth <= 8)
  195827. {
  195828. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  195829. max_pixel_depth = 32;
  195830. else
  195831. max_pixel_depth = 24;
  195832. }
  195833. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  195834. max_pixel_depth = 64;
  195835. else
  195836. max_pixel_depth = 48;
  195837. }
  195838. }
  195839. #endif
  195840. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  195841. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  195842. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  195843. {
  195844. int user_pixel_depth=png_ptr->user_transform_depth*
  195845. png_ptr->user_transform_channels;
  195846. if(user_pixel_depth > max_pixel_depth)
  195847. max_pixel_depth=user_pixel_depth;
  195848. }
  195849. #endif
  195850. /* align the width on the next larger 8 pixels. Mainly used
  195851. for interlacing */
  195852. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  195853. /* calculate the maximum bytes needed, adding a byte and a pixel
  195854. for safety's sake */
  195855. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  195856. 1 + ((max_pixel_depth + 7) >> 3);
  195857. #ifdef PNG_MAX_MALLOC_64K
  195858. if (row_bytes > (png_uint_32)65536L)
  195859. png_error(png_ptr, "This image requires a row greater than 64KB");
  195860. #endif
  195861. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  195862. png_ptr->row_buf = png_ptr->big_row_buf+32;
  195863. #ifdef PNG_MAX_MALLOC_64K
  195864. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  195865. png_error(png_ptr, "This image requires a row greater than 64KB");
  195866. #endif
  195867. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  195868. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  195869. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  195870. png_ptr->rowbytes + 1));
  195871. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  195872. png_debug1(3, "width = %lu,\n", png_ptr->width);
  195873. png_debug1(3, "height = %lu,\n", png_ptr->height);
  195874. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  195875. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  195876. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  195877. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  195878. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  195879. }
  195880. #endif /* PNG_READ_SUPPORTED */
  195881. /*** End of inlined file: pngrutil.c ***/
  195882. /*** Start of inlined file: pngset.c ***/
  195883. /* pngset.c - storage of image information into info struct
  195884. *
  195885. * Last changed in libpng 1.2.21 [October 4, 2007]
  195886. * For conditions of distribution and use, see copyright notice in png.h
  195887. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  195888. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  195889. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  195890. *
  195891. * The functions here are used during reads to store data from the file
  195892. * into the info struct, and during writes to store application data
  195893. * into the info struct for writing into the file. This abstracts the
  195894. * info struct and allows us to change the structure in the future.
  195895. */
  195896. #define PNG_INTERNAL
  195897. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  195898. #if defined(PNG_bKGD_SUPPORTED)
  195899. void PNGAPI
  195900. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  195901. {
  195902. png_debug1(1, "in %s storage function\n", "bKGD");
  195903. if (png_ptr == NULL || info_ptr == NULL)
  195904. return;
  195905. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  195906. info_ptr->valid |= PNG_INFO_bKGD;
  195907. }
  195908. #endif
  195909. #if defined(PNG_cHRM_SUPPORTED)
  195910. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195911. void PNGAPI
  195912. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  195913. double white_x, double white_y, double red_x, double red_y,
  195914. double green_x, double green_y, double blue_x, double blue_y)
  195915. {
  195916. png_debug1(1, "in %s storage function\n", "cHRM");
  195917. if (png_ptr == NULL || info_ptr == NULL)
  195918. return;
  195919. if (white_x < 0.0 || white_y < 0.0 ||
  195920. red_x < 0.0 || red_y < 0.0 ||
  195921. green_x < 0.0 || green_y < 0.0 ||
  195922. blue_x < 0.0 || blue_y < 0.0)
  195923. {
  195924. png_warning(png_ptr,
  195925. "Ignoring attempt to set negative chromaticity value");
  195926. return;
  195927. }
  195928. if (white_x > 21474.83 || white_y > 21474.83 ||
  195929. red_x > 21474.83 || red_y > 21474.83 ||
  195930. green_x > 21474.83 || green_y > 21474.83 ||
  195931. blue_x > 21474.83 || blue_y > 21474.83)
  195932. {
  195933. png_warning(png_ptr,
  195934. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  195935. return;
  195936. }
  195937. info_ptr->x_white = (float)white_x;
  195938. info_ptr->y_white = (float)white_y;
  195939. info_ptr->x_red = (float)red_x;
  195940. info_ptr->y_red = (float)red_y;
  195941. info_ptr->x_green = (float)green_x;
  195942. info_ptr->y_green = (float)green_y;
  195943. info_ptr->x_blue = (float)blue_x;
  195944. info_ptr->y_blue = (float)blue_y;
  195945. #ifdef PNG_FIXED_POINT_SUPPORTED
  195946. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  195947. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  195948. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  195949. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  195950. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  195951. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  195952. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  195953. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  195954. #endif
  195955. info_ptr->valid |= PNG_INFO_cHRM;
  195956. }
  195957. #endif
  195958. #ifdef PNG_FIXED_POINT_SUPPORTED
  195959. void PNGAPI
  195960. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  195961. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  195962. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  195963. png_fixed_point blue_x, png_fixed_point blue_y)
  195964. {
  195965. png_debug1(1, "in %s storage function\n", "cHRM");
  195966. if (png_ptr == NULL || info_ptr == NULL)
  195967. return;
  195968. if (white_x < 0 || white_y < 0 ||
  195969. red_x < 0 || red_y < 0 ||
  195970. green_x < 0 || green_y < 0 ||
  195971. blue_x < 0 || blue_y < 0)
  195972. {
  195973. png_warning(png_ptr,
  195974. "Ignoring attempt to set negative chromaticity value");
  195975. return;
  195976. }
  195977. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195978. if (white_x > (double) PNG_UINT_31_MAX ||
  195979. white_y > (double) PNG_UINT_31_MAX ||
  195980. red_x > (double) PNG_UINT_31_MAX ||
  195981. red_y > (double) PNG_UINT_31_MAX ||
  195982. green_x > (double) PNG_UINT_31_MAX ||
  195983. green_y > (double) PNG_UINT_31_MAX ||
  195984. blue_x > (double) PNG_UINT_31_MAX ||
  195985. blue_y > (double) PNG_UINT_31_MAX)
  195986. #else
  195987. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  195988. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  195989. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  195990. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  195991. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  195992. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  195993. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  195994. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  195995. #endif
  195996. {
  195997. png_warning(png_ptr,
  195998. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  195999. return;
  196000. }
  196001. info_ptr->int_x_white = white_x;
  196002. info_ptr->int_y_white = white_y;
  196003. info_ptr->int_x_red = red_x;
  196004. info_ptr->int_y_red = red_y;
  196005. info_ptr->int_x_green = green_x;
  196006. info_ptr->int_y_green = green_y;
  196007. info_ptr->int_x_blue = blue_x;
  196008. info_ptr->int_y_blue = blue_y;
  196009. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196010. info_ptr->x_white = (float)(white_x/100000.);
  196011. info_ptr->y_white = (float)(white_y/100000.);
  196012. info_ptr->x_red = (float)( red_x/100000.);
  196013. info_ptr->y_red = (float)( red_y/100000.);
  196014. info_ptr->x_green = (float)(green_x/100000.);
  196015. info_ptr->y_green = (float)(green_y/100000.);
  196016. info_ptr->x_blue = (float)( blue_x/100000.);
  196017. info_ptr->y_blue = (float)( blue_y/100000.);
  196018. #endif
  196019. info_ptr->valid |= PNG_INFO_cHRM;
  196020. }
  196021. #endif
  196022. #endif
  196023. #if defined(PNG_gAMA_SUPPORTED)
  196024. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196025. void PNGAPI
  196026. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  196027. {
  196028. double gamma;
  196029. png_debug1(1, "in %s storage function\n", "gAMA");
  196030. if (png_ptr == NULL || info_ptr == NULL)
  196031. return;
  196032. /* Check for overflow */
  196033. if (file_gamma > 21474.83)
  196034. {
  196035. png_warning(png_ptr, "Limiting gamma to 21474.83");
  196036. gamma=21474.83;
  196037. }
  196038. else
  196039. gamma=file_gamma;
  196040. info_ptr->gamma = (float)gamma;
  196041. #ifdef PNG_FIXED_POINT_SUPPORTED
  196042. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  196043. #endif
  196044. info_ptr->valid |= PNG_INFO_gAMA;
  196045. if(gamma == 0.0)
  196046. png_warning(png_ptr, "Setting gamma=0");
  196047. }
  196048. #endif
  196049. void PNGAPI
  196050. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  196051. int_gamma)
  196052. {
  196053. png_fixed_point gamma;
  196054. png_debug1(1, "in %s storage function\n", "gAMA");
  196055. if (png_ptr == NULL || info_ptr == NULL)
  196056. return;
  196057. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  196058. {
  196059. png_warning(png_ptr, "Limiting gamma to 21474.83");
  196060. gamma=PNG_UINT_31_MAX;
  196061. }
  196062. else
  196063. {
  196064. if (int_gamma < 0)
  196065. {
  196066. png_warning(png_ptr, "Setting negative gamma to zero");
  196067. gamma=0;
  196068. }
  196069. else
  196070. gamma=int_gamma;
  196071. }
  196072. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196073. info_ptr->gamma = (float)(gamma/100000.);
  196074. #endif
  196075. #ifdef PNG_FIXED_POINT_SUPPORTED
  196076. info_ptr->int_gamma = gamma;
  196077. #endif
  196078. info_ptr->valid |= PNG_INFO_gAMA;
  196079. if(gamma == 0)
  196080. png_warning(png_ptr, "Setting gamma=0");
  196081. }
  196082. #endif
  196083. #if defined(PNG_hIST_SUPPORTED)
  196084. void PNGAPI
  196085. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  196086. {
  196087. int i;
  196088. png_debug1(1, "in %s storage function\n", "hIST");
  196089. if (png_ptr == NULL || info_ptr == NULL)
  196090. return;
  196091. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  196092. > PNG_MAX_PALETTE_LENGTH)
  196093. {
  196094. png_warning(png_ptr,
  196095. "Invalid palette size, hIST allocation skipped.");
  196096. return;
  196097. }
  196098. #ifdef PNG_FREE_ME_SUPPORTED
  196099. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  196100. #endif
  196101. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  196102. 1.2.1 */
  196103. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  196104. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  196105. if (png_ptr->hist == NULL)
  196106. {
  196107. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  196108. return;
  196109. }
  196110. for (i = 0; i < info_ptr->num_palette; i++)
  196111. png_ptr->hist[i] = hist[i];
  196112. info_ptr->hist = png_ptr->hist;
  196113. info_ptr->valid |= PNG_INFO_hIST;
  196114. #ifdef PNG_FREE_ME_SUPPORTED
  196115. info_ptr->free_me |= PNG_FREE_HIST;
  196116. #else
  196117. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  196118. #endif
  196119. }
  196120. #endif
  196121. void PNGAPI
  196122. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  196123. png_uint_32 width, png_uint_32 height, int bit_depth,
  196124. int color_type, int interlace_type, int compression_type,
  196125. int filter_type)
  196126. {
  196127. png_debug1(1, "in %s storage function\n", "IHDR");
  196128. if (png_ptr == NULL || info_ptr == NULL)
  196129. return;
  196130. /* check for width and height valid values */
  196131. if (width == 0 || height == 0)
  196132. png_error(png_ptr, "Image width or height is zero in IHDR");
  196133. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  196134. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  196135. png_error(png_ptr, "image size exceeds user limits in IHDR");
  196136. #else
  196137. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  196138. png_error(png_ptr, "image size exceeds user limits in IHDR");
  196139. #endif
  196140. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  196141. png_error(png_ptr, "Invalid image size in IHDR");
  196142. if ( width > (PNG_UINT_32_MAX
  196143. >> 3) /* 8-byte RGBA pixels */
  196144. - 64 /* bigrowbuf hack */
  196145. - 1 /* filter byte */
  196146. - 7*8 /* rounding of width to multiple of 8 pixels */
  196147. - 8) /* extra max_pixel_depth pad */
  196148. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  196149. /* check other values */
  196150. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  196151. bit_depth != 8 && bit_depth != 16)
  196152. png_error(png_ptr, "Invalid bit depth in IHDR");
  196153. if (color_type < 0 || color_type == 1 ||
  196154. color_type == 5 || color_type > 6)
  196155. png_error(png_ptr, "Invalid color type in IHDR");
  196156. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  196157. ((color_type == PNG_COLOR_TYPE_RGB ||
  196158. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  196159. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  196160. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  196161. if (interlace_type >= PNG_INTERLACE_LAST)
  196162. png_error(png_ptr, "Unknown interlace method in IHDR");
  196163. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  196164. png_error(png_ptr, "Unknown compression method in IHDR");
  196165. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196166. /* Accept filter_method 64 (intrapixel differencing) only if
  196167. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  196168. * 2. Libpng did not read a PNG signature (this filter_method is only
  196169. * used in PNG datastreams that are embedded in MNG datastreams) and
  196170. * 3. The application called png_permit_mng_features with a mask that
  196171. * included PNG_FLAG_MNG_FILTER_64 and
  196172. * 4. The filter_method is 64 and
  196173. * 5. The color_type is RGB or RGBA
  196174. */
  196175. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  196176. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  196177. if(filter_type != PNG_FILTER_TYPE_BASE)
  196178. {
  196179. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  196180. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  196181. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  196182. (color_type == PNG_COLOR_TYPE_RGB ||
  196183. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  196184. png_error(png_ptr, "Unknown filter method in IHDR");
  196185. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  196186. png_warning(png_ptr, "Invalid filter method in IHDR");
  196187. }
  196188. #else
  196189. if(filter_type != PNG_FILTER_TYPE_BASE)
  196190. png_error(png_ptr, "Unknown filter method in IHDR");
  196191. #endif
  196192. info_ptr->width = width;
  196193. info_ptr->height = height;
  196194. info_ptr->bit_depth = (png_byte)bit_depth;
  196195. info_ptr->color_type =(png_byte) color_type;
  196196. info_ptr->compression_type = (png_byte)compression_type;
  196197. info_ptr->filter_type = (png_byte)filter_type;
  196198. info_ptr->interlace_type = (png_byte)interlace_type;
  196199. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196200. info_ptr->channels = 1;
  196201. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  196202. info_ptr->channels = 3;
  196203. else
  196204. info_ptr->channels = 1;
  196205. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  196206. info_ptr->channels++;
  196207. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  196208. /* check for potential overflow */
  196209. if (width > (PNG_UINT_32_MAX
  196210. >> 3) /* 8-byte RGBA pixels */
  196211. - 64 /* bigrowbuf hack */
  196212. - 1 /* filter byte */
  196213. - 7*8 /* rounding of width to multiple of 8 pixels */
  196214. - 8) /* extra max_pixel_depth pad */
  196215. info_ptr->rowbytes = (png_size_t)0;
  196216. else
  196217. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  196218. }
  196219. #if defined(PNG_oFFs_SUPPORTED)
  196220. void PNGAPI
  196221. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  196222. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  196223. {
  196224. png_debug1(1, "in %s storage function\n", "oFFs");
  196225. if (png_ptr == NULL || info_ptr == NULL)
  196226. return;
  196227. info_ptr->x_offset = offset_x;
  196228. info_ptr->y_offset = offset_y;
  196229. info_ptr->offset_unit_type = (png_byte)unit_type;
  196230. info_ptr->valid |= PNG_INFO_oFFs;
  196231. }
  196232. #endif
  196233. #if defined(PNG_pCAL_SUPPORTED)
  196234. void PNGAPI
  196235. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  196236. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  196237. png_charp units, png_charpp params)
  196238. {
  196239. png_uint_32 length;
  196240. int i;
  196241. png_debug1(1, "in %s storage function\n", "pCAL");
  196242. if (png_ptr == NULL || info_ptr == NULL)
  196243. return;
  196244. length = png_strlen(purpose) + 1;
  196245. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  196246. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  196247. if (info_ptr->pcal_purpose == NULL)
  196248. {
  196249. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  196250. return;
  196251. }
  196252. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  196253. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  196254. info_ptr->pcal_X0 = X0;
  196255. info_ptr->pcal_X1 = X1;
  196256. info_ptr->pcal_type = (png_byte)type;
  196257. info_ptr->pcal_nparams = (png_byte)nparams;
  196258. length = png_strlen(units) + 1;
  196259. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  196260. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  196261. if (info_ptr->pcal_units == NULL)
  196262. {
  196263. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  196264. return;
  196265. }
  196266. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  196267. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  196268. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  196269. if (info_ptr->pcal_params == NULL)
  196270. {
  196271. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  196272. return;
  196273. }
  196274. info_ptr->pcal_params[nparams] = NULL;
  196275. for (i = 0; i < nparams; i++)
  196276. {
  196277. length = png_strlen(params[i]) + 1;
  196278. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  196279. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  196280. if (info_ptr->pcal_params[i] == NULL)
  196281. {
  196282. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  196283. return;
  196284. }
  196285. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  196286. }
  196287. info_ptr->valid |= PNG_INFO_pCAL;
  196288. #ifdef PNG_FREE_ME_SUPPORTED
  196289. info_ptr->free_me |= PNG_FREE_PCAL;
  196290. #endif
  196291. }
  196292. #endif
  196293. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  196294. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196295. void PNGAPI
  196296. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  196297. int unit, double width, double height)
  196298. {
  196299. png_debug1(1, "in %s storage function\n", "sCAL");
  196300. if (png_ptr == NULL || info_ptr == NULL)
  196301. return;
  196302. info_ptr->scal_unit = (png_byte)unit;
  196303. info_ptr->scal_pixel_width = width;
  196304. info_ptr->scal_pixel_height = height;
  196305. info_ptr->valid |= PNG_INFO_sCAL;
  196306. }
  196307. #else
  196308. #ifdef PNG_FIXED_POINT_SUPPORTED
  196309. void PNGAPI
  196310. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  196311. int unit, png_charp swidth, png_charp sheight)
  196312. {
  196313. png_uint_32 length;
  196314. png_debug1(1, "in %s storage function\n", "sCAL");
  196315. if (png_ptr == NULL || info_ptr == NULL)
  196316. return;
  196317. info_ptr->scal_unit = (png_byte)unit;
  196318. length = png_strlen(swidth) + 1;
  196319. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  196320. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  196321. if (info_ptr->scal_s_width == NULL)
  196322. {
  196323. png_warning(png_ptr,
  196324. "Memory allocation failed while processing sCAL.");
  196325. }
  196326. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  196327. length = png_strlen(sheight) + 1;
  196328. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  196329. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  196330. if (info_ptr->scal_s_height == NULL)
  196331. {
  196332. png_free (png_ptr, info_ptr->scal_s_width);
  196333. png_warning(png_ptr,
  196334. "Memory allocation failed while processing sCAL.");
  196335. }
  196336. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  196337. info_ptr->valid |= PNG_INFO_sCAL;
  196338. #ifdef PNG_FREE_ME_SUPPORTED
  196339. info_ptr->free_me |= PNG_FREE_SCAL;
  196340. #endif
  196341. }
  196342. #endif
  196343. #endif
  196344. #endif
  196345. #if defined(PNG_pHYs_SUPPORTED)
  196346. void PNGAPI
  196347. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  196348. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  196349. {
  196350. png_debug1(1, "in %s storage function\n", "pHYs");
  196351. if (png_ptr == NULL || info_ptr == NULL)
  196352. return;
  196353. info_ptr->x_pixels_per_unit = res_x;
  196354. info_ptr->y_pixels_per_unit = res_y;
  196355. info_ptr->phys_unit_type = (png_byte)unit_type;
  196356. info_ptr->valid |= PNG_INFO_pHYs;
  196357. }
  196358. #endif
  196359. void PNGAPI
  196360. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  196361. png_colorp palette, int num_palette)
  196362. {
  196363. png_debug1(1, "in %s storage function\n", "PLTE");
  196364. if (png_ptr == NULL || info_ptr == NULL)
  196365. return;
  196366. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  196367. {
  196368. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196369. png_error(png_ptr, "Invalid palette length");
  196370. else
  196371. {
  196372. png_warning(png_ptr, "Invalid palette length");
  196373. return;
  196374. }
  196375. }
  196376. /*
  196377. * It may not actually be necessary to set png_ptr->palette here;
  196378. * we do it for backward compatibility with the way the png_handle_tRNS
  196379. * function used to do the allocation.
  196380. */
  196381. #ifdef PNG_FREE_ME_SUPPORTED
  196382. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  196383. #endif
  196384. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  196385. of num_palette entries,
  196386. in case of an invalid PNG file that has too-large sample values. */
  196387. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  196388. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  196389. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  196390. png_sizeof(png_color));
  196391. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  196392. info_ptr->palette = png_ptr->palette;
  196393. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  196394. #ifdef PNG_FREE_ME_SUPPORTED
  196395. info_ptr->free_me |= PNG_FREE_PLTE;
  196396. #else
  196397. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  196398. #endif
  196399. info_ptr->valid |= PNG_INFO_PLTE;
  196400. }
  196401. #if defined(PNG_sBIT_SUPPORTED)
  196402. void PNGAPI
  196403. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  196404. png_color_8p sig_bit)
  196405. {
  196406. png_debug1(1, "in %s storage function\n", "sBIT");
  196407. if (png_ptr == NULL || info_ptr == NULL)
  196408. return;
  196409. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  196410. info_ptr->valid |= PNG_INFO_sBIT;
  196411. }
  196412. #endif
  196413. #if defined(PNG_sRGB_SUPPORTED)
  196414. void PNGAPI
  196415. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  196416. {
  196417. png_debug1(1, "in %s storage function\n", "sRGB");
  196418. if (png_ptr == NULL || info_ptr == NULL)
  196419. return;
  196420. info_ptr->srgb_intent = (png_byte)intent;
  196421. info_ptr->valid |= PNG_INFO_sRGB;
  196422. }
  196423. void PNGAPI
  196424. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  196425. int intent)
  196426. {
  196427. #if defined(PNG_gAMA_SUPPORTED)
  196428. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196429. float file_gamma;
  196430. #endif
  196431. #ifdef PNG_FIXED_POINT_SUPPORTED
  196432. png_fixed_point int_file_gamma;
  196433. #endif
  196434. #endif
  196435. #if defined(PNG_cHRM_SUPPORTED)
  196436. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196437. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  196438. #endif
  196439. #ifdef PNG_FIXED_POINT_SUPPORTED
  196440. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  196441. int_green_y, int_blue_x, int_blue_y;
  196442. #endif
  196443. #endif
  196444. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  196445. if (png_ptr == NULL || info_ptr == NULL)
  196446. return;
  196447. png_set_sRGB(png_ptr, info_ptr, intent);
  196448. #if defined(PNG_gAMA_SUPPORTED)
  196449. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196450. file_gamma = (float).45455;
  196451. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  196452. #endif
  196453. #ifdef PNG_FIXED_POINT_SUPPORTED
  196454. int_file_gamma = 45455L;
  196455. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  196456. #endif
  196457. #endif
  196458. #if defined(PNG_cHRM_SUPPORTED)
  196459. #ifdef PNG_FIXED_POINT_SUPPORTED
  196460. int_white_x = 31270L;
  196461. int_white_y = 32900L;
  196462. int_red_x = 64000L;
  196463. int_red_y = 33000L;
  196464. int_green_x = 30000L;
  196465. int_green_y = 60000L;
  196466. int_blue_x = 15000L;
  196467. int_blue_y = 6000L;
  196468. png_set_cHRM_fixed(png_ptr, info_ptr,
  196469. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  196470. int_blue_x, int_blue_y);
  196471. #endif
  196472. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196473. white_x = (float).3127;
  196474. white_y = (float).3290;
  196475. red_x = (float).64;
  196476. red_y = (float).33;
  196477. green_x = (float).30;
  196478. green_y = (float).60;
  196479. blue_x = (float).15;
  196480. blue_y = (float).06;
  196481. png_set_cHRM(png_ptr, info_ptr,
  196482. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  196483. #endif
  196484. #endif
  196485. }
  196486. #endif
  196487. #if defined(PNG_iCCP_SUPPORTED)
  196488. void PNGAPI
  196489. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  196490. png_charp name, int compression_type,
  196491. png_charp profile, png_uint_32 proflen)
  196492. {
  196493. png_charp new_iccp_name;
  196494. png_charp new_iccp_profile;
  196495. png_debug1(1, "in %s storage function\n", "iCCP");
  196496. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  196497. return;
  196498. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  196499. if (new_iccp_name == NULL)
  196500. {
  196501. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  196502. return;
  196503. }
  196504. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  196505. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  196506. if (new_iccp_profile == NULL)
  196507. {
  196508. png_free (png_ptr, new_iccp_name);
  196509. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  196510. return;
  196511. }
  196512. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  196513. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  196514. info_ptr->iccp_proflen = proflen;
  196515. info_ptr->iccp_name = new_iccp_name;
  196516. info_ptr->iccp_profile = new_iccp_profile;
  196517. /* Compression is always zero but is here so the API and info structure
  196518. * does not have to change if we introduce multiple compression types */
  196519. info_ptr->iccp_compression = (png_byte)compression_type;
  196520. #ifdef PNG_FREE_ME_SUPPORTED
  196521. info_ptr->free_me |= PNG_FREE_ICCP;
  196522. #endif
  196523. info_ptr->valid |= PNG_INFO_iCCP;
  196524. }
  196525. #endif
  196526. #if defined(PNG_TEXT_SUPPORTED)
  196527. void PNGAPI
  196528. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  196529. int num_text)
  196530. {
  196531. int ret;
  196532. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  196533. if (ret)
  196534. png_error(png_ptr, "Insufficient memory to store text");
  196535. }
  196536. int /* PRIVATE */
  196537. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  196538. int num_text)
  196539. {
  196540. int i;
  196541. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  196542. "text" : (png_const_charp)png_ptr->chunk_name));
  196543. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  196544. return(0);
  196545. /* Make sure we have enough space in the "text" array in info_struct
  196546. * to hold all of the incoming text_ptr objects.
  196547. */
  196548. if (info_ptr->num_text + num_text > info_ptr->max_text)
  196549. {
  196550. if (info_ptr->text != NULL)
  196551. {
  196552. png_textp old_text;
  196553. int old_max;
  196554. old_max = info_ptr->max_text;
  196555. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  196556. old_text = info_ptr->text;
  196557. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  196558. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  196559. if (info_ptr->text == NULL)
  196560. {
  196561. png_free(png_ptr, old_text);
  196562. return(1);
  196563. }
  196564. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  196565. png_sizeof(png_text)));
  196566. png_free(png_ptr, old_text);
  196567. }
  196568. else
  196569. {
  196570. info_ptr->max_text = num_text + 8;
  196571. info_ptr->num_text = 0;
  196572. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  196573. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  196574. if (info_ptr->text == NULL)
  196575. return(1);
  196576. #ifdef PNG_FREE_ME_SUPPORTED
  196577. info_ptr->free_me |= PNG_FREE_TEXT;
  196578. #endif
  196579. }
  196580. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  196581. info_ptr->max_text);
  196582. }
  196583. for (i = 0; i < num_text; i++)
  196584. {
  196585. png_size_t text_length,key_len;
  196586. png_size_t lang_len,lang_key_len;
  196587. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  196588. if (text_ptr[i].key == NULL)
  196589. continue;
  196590. key_len = png_strlen(text_ptr[i].key);
  196591. if(text_ptr[i].compression <= 0)
  196592. {
  196593. lang_len = 0;
  196594. lang_key_len = 0;
  196595. }
  196596. else
  196597. #ifdef PNG_iTXt_SUPPORTED
  196598. {
  196599. /* set iTXt data */
  196600. if (text_ptr[i].lang != NULL)
  196601. lang_len = png_strlen(text_ptr[i].lang);
  196602. else
  196603. lang_len = 0;
  196604. if (text_ptr[i].lang_key != NULL)
  196605. lang_key_len = png_strlen(text_ptr[i].lang_key);
  196606. else
  196607. lang_key_len = 0;
  196608. }
  196609. #else
  196610. {
  196611. png_warning(png_ptr, "iTXt chunk not supported.");
  196612. continue;
  196613. }
  196614. #endif
  196615. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  196616. {
  196617. text_length = 0;
  196618. #ifdef PNG_iTXt_SUPPORTED
  196619. if(text_ptr[i].compression > 0)
  196620. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  196621. else
  196622. #endif
  196623. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  196624. }
  196625. else
  196626. {
  196627. text_length = png_strlen(text_ptr[i].text);
  196628. textp->compression = text_ptr[i].compression;
  196629. }
  196630. textp->key = (png_charp)png_malloc_warn(png_ptr,
  196631. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  196632. if (textp->key == NULL)
  196633. return(1);
  196634. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  196635. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  196636. (int)textp->key);
  196637. png_memcpy(textp->key, text_ptr[i].key,
  196638. (png_size_t)(key_len));
  196639. *(textp->key+key_len) = '\0';
  196640. #ifdef PNG_iTXt_SUPPORTED
  196641. if (text_ptr[i].compression > 0)
  196642. {
  196643. textp->lang=textp->key + key_len + 1;
  196644. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  196645. *(textp->lang+lang_len) = '\0';
  196646. textp->lang_key=textp->lang + lang_len + 1;
  196647. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  196648. *(textp->lang_key+lang_key_len) = '\0';
  196649. textp->text=textp->lang_key + lang_key_len + 1;
  196650. }
  196651. else
  196652. #endif
  196653. {
  196654. #ifdef PNG_iTXt_SUPPORTED
  196655. textp->lang=NULL;
  196656. textp->lang_key=NULL;
  196657. #endif
  196658. textp->text=textp->key + key_len + 1;
  196659. }
  196660. if(text_length)
  196661. png_memcpy(textp->text, text_ptr[i].text,
  196662. (png_size_t)(text_length));
  196663. *(textp->text+text_length) = '\0';
  196664. #ifdef PNG_iTXt_SUPPORTED
  196665. if(textp->compression > 0)
  196666. {
  196667. textp->text_length = 0;
  196668. textp->itxt_length = text_length;
  196669. }
  196670. else
  196671. #endif
  196672. {
  196673. textp->text_length = text_length;
  196674. #ifdef PNG_iTXt_SUPPORTED
  196675. textp->itxt_length = 0;
  196676. #endif
  196677. }
  196678. info_ptr->num_text++;
  196679. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  196680. }
  196681. return(0);
  196682. }
  196683. #endif
  196684. #if defined(PNG_tIME_SUPPORTED)
  196685. void PNGAPI
  196686. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  196687. {
  196688. png_debug1(1, "in %s storage function\n", "tIME");
  196689. if (png_ptr == NULL || info_ptr == NULL ||
  196690. (png_ptr->mode & PNG_WROTE_tIME))
  196691. return;
  196692. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  196693. info_ptr->valid |= PNG_INFO_tIME;
  196694. }
  196695. #endif
  196696. #if defined(PNG_tRNS_SUPPORTED)
  196697. void PNGAPI
  196698. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  196699. png_bytep trans, int num_trans, png_color_16p trans_values)
  196700. {
  196701. png_debug1(1, "in %s storage function\n", "tRNS");
  196702. if (png_ptr == NULL || info_ptr == NULL)
  196703. return;
  196704. if (trans != NULL)
  196705. {
  196706. /*
  196707. * It may not actually be necessary to set png_ptr->trans here;
  196708. * we do it for backward compatibility with the way the png_handle_tRNS
  196709. * function used to do the allocation.
  196710. */
  196711. #ifdef PNG_FREE_ME_SUPPORTED
  196712. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  196713. #endif
  196714. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  196715. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  196716. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  196717. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  196718. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  196719. #ifdef PNG_FREE_ME_SUPPORTED
  196720. info_ptr->free_me |= PNG_FREE_TRNS;
  196721. #else
  196722. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  196723. #endif
  196724. }
  196725. if (trans_values != NULL)
  196726. {
  196727. png_memcpy(&(info_ptr->trans_values), trans_values,
  196728. png_sizeof(png_color_16));
  196729. if (num_trans == 0)
  196730. num_trans = 1;
  196731. }
  196732. info_ptr->num_trans = (png_uint_16)num_trans;
  196733. info_ptr->valid |= PNG_INFO_tRNS;
  196734. }
  196735. #endif
  196736. #if defined(PNG_sPLT_SUPPORTED)
  196737. void PNGAPI
  196738. png_set_sPLT(png_structp png_ptr,
  196739. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  196740. {
  196741. png_sPLT_tp np;
  196742. int i;
  196743. if (png_ptr == NULL || info_ptr == NULL)
  196744. return;
  196745. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  196746. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  196747. if (np == NULL)
  196748. {
  196749. png_warning(png_ptr, "No memory for sPLT palettes.");
  196750. return;
  196751. }
  196752. png_memcpy(np, info_ptr->splt_palettes,
  196753. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  196754. png_free(png_ptr, info_ptr->splt_palettes);
  196755. info_ptr->splt_palettes=NULL;
  196756. for (i = 0; i < nentries; i++)
  196757. {
  196758. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  196759. png_sPLT_tp from = entries + i;
  196760. to->name = (png_charp)png_malloc_warn(png_ptr,
  196761. png_strlen(from->name) + 1);
  196762. if (to->name == NULL)
  196763. {
  196764. png_warning(png_ptr,
  196765. "Out of memory while processing sPLT chunk");
  196766. }
  196767. /* TODO: use png_malloc_warn */
  196768. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  196769. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  196770. from->nentries * png_sizeof(png_sPLT_entry));
  196771. /* TODO: use png_malloc_warn */
  196772. png_memcpy(to->entries, from->entries,
  196773. from->nentries * png_sizeof(png_sPLT_entry));
  196774. if (to->entries == NULL)
  196775. {
  196776. png_warning(png_ptr,
  196777. "Out of memory while processing sPLT chunk");
  196778. png_free(png_ptr,to->name);
  196779. to->name = NULL;
  196780. }
  196781. to->nentries = from->nentries;
  196782. to->depth = from->depth;
  196783. }
  196784. info_ptr->splt_palettes = np;
  196785. info_ptr->splt_palettes_num += nentries;
  196786. info_ptr->valid |= PNG_INFO_sPLT;
  196787. #ifdef PNG_FREE_ME_SUPPORTED
  196788. info_ptr->free_me |= PNG_FREE_SPLT;
  196789. #endif
  196790. }
  196791. #endif /* PNG_sPLT_SUPPORTED */
  196792. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  196793. void PNGAPI
  196794. png_set_unknown_chunks(png_structp png_ptr,
  196795. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  196796. {
  196797. png_unknown_chunkp np;
  196798. int i;
  196799. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  196800. return;
  196801. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  196802. (info_ptr->unknown_chunks_num + num_unknowns) *
  196803. png_sizeof(png_unknown_chunk));
  196804. if (np == NULL)
  196805. {
  196806. png_warning(png_ptr,
  196807. "Out of memory while processing unknown chunk.");
  196808. return;
  196809. }
  196810. png_memcpy(np, info_ptr->unknown_chunks,
  196811. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  196812. png_free(png_ptr, info_ptr->unknown_chunks);
  196813. info_ptr->unknown_chunks=NULL;
  196814. for (i = 0; i < num_unknowns; i++)
  196815. {
  196816. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  196817. png_unknown_chunkp from = unknowns + i;
  196818. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  196819. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  196820. if (to->data == NULL)
  196821. {
  196822. png_warning(png_ptr,
  196823. "Out of memory while processing unknown chunk.");
  196824. }
  196825. else
  196826. {
  196827. png_memcpy(to->data, from->data, from->size);
  196828. to->size = from->size;
  196829. /* note our location in the read or write sequence */
  196830. to->location = (png_byte)(png_ptr->mode & 0xff);
  196831. }
  196832. }
  196833. info_ptr->unknown_chunks = np;
  196834. info_ptr->unknown_chunks_num += num_unknowns;
  196835. #ifdef PNG_FREE_ME_SUPPORTED
  196836. info_ptr->free_me |= PNG_FREE_UNKN;
  196837. #endif
  196838. }
  196839. void PNGAPI
  196840. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  196841. int chunk, int location)
  196842. {
  196843. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  196844. (int)info_ptr->unknown_chunks_num)
  196845. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  196846. }
  196847. #endif
  196848. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  196849. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  196850. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  196851. void PNGAPI
  196852. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  196853. {
  196854. /* This function is deprecated in favor of png_permit_mng_features()
  196855. and will be removed from libpng-1.3.0 */
  196856. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  196857. if (png_ptr == NULL)
  196858. return;
  196859. png_ptr->mng_features_permitted = (png_byte)
  196860. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  196861. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  196862. }
  196863. #endif
  196864. #endif
  196865. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196866. png_uint_32 PNGAPI
  196867. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  196868. {
  196869. png_debug(1, "in png_permit_mng_features\n");
  196870. if (png_ptr == NULL)
  196871. return (png_uint_32)0;
  196872. png_ptr->mng_features_permitted =
  196873. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  196874. return (png_uint_32)png_ptr->mng_features_permitted;
  196875. }
  196876. #endif
  196877. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  196878. void PNGAPI
  196879. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  196880. chunk_list, int num_chunks)
  196881. {
  196882. png_bytep new_list, p;
  196883. int i, old_num_chunks;
  196884. if (png_ptr == NULL)
  196885. return;
  196886. if (num_chunks == 0)
  196887. {
  196888. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  196889. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  196890. else
  196891. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  196892. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  196893. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  196894. else
  196895. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  196896. return;
  196897. }
  196898. if (chunk_list == NULL)
  196899. return;
  196900. old_num_chunks=png_ptr->num_chunk_list;
  196901. new_list=(png_bytep)png_malloc(png_ptr,
  196902. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  196903. if(png_ptr->chunk_list != NULL)
  196904. {
  196905. png_memcpy(new_list, png_ptr->chunk_list,
  196906. (png_size_t)(5*old_num_chunks));
  196907. png_free(png_ptr, png_ptr->chunk_list);
  196908. png_ptr->chunk_list=NULL;
  196909. }
  196910. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  196911. (png_size_t)(5*num_chunks));
  196912. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  196913. *p=(png_byte)keep;
  196914. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  196915. png_ptr->chunk_list=new_list;
  196916. #ifdef PNG_FREE_ME_SUPPORTED
  196917. png_ptr->free_me |= PNG_FREE_LIST;
  196918. #endif
  196919. }
  196920. #endif
  196921. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  196922. void PNGAPI
  196923. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  196924. png_user_chunk_ptr read_user_chunk_fn)
  196925. {
  196926. png_debug(1, "in png_set_read_user_chunk_fn\n");
  196927. if (png_ptr == NULL)
  196928. return;
  196929. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  196930. png_ptr->user_chunk_ptr = user_chunk_ptr;
  196931. }
  196932. #endif
  196933. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  196934. void PNGAPI
  196935. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  196936. {
  196937. png_debug1(1, "in %s storage function\n", "rows");
  196938. if (png_ptr == NULL || info_ptr == NULL)
  196939. return;
  196940. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  196941. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  196942. info_ptr->row_pointers = row_pointers;
  196943. if(row_pointers)
  196944. info_ptr->valid |= PNG_INFO_IDAT;
  196945. }
  196946. #endif
  196947. #ifdef PNG_WRITE_SUPPORTED
  196948. void PNGAPI
  196949. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  196950. {
  196951. if (png_ptr == NULL)
  196952. return;
  196953. if(png_ptr->zbuf)
  196954. png_free(png_ptr, png_ptr->zbuf);
  196955. png_ptr->zbuf_size = (png_size_t)size;
  196956. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  196957. png_ptr->zstream.next_out = png_ptr->zbuf;
  196958. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  196959. }
  196960. #endif
  196961. void PNGAPI
  196962. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  196963. {
  196964. if (png_ptr && info_ptr)
  196965. info_ptr->valid &= ~(mask);
  196966. }
  196967. #ifndef PNG_1_0_X
  196968. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  196969. /* function was added to libpng 1.2.0 and should always exist by default */
  196970. void PNGAPI
  196971. png_set_asm_flags (png_structp png_ptr, png_uint_32)
  196972. {
  196973. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  196974. if (png_ptr != NULL)
  196975. png_ptr->asm_flags = 0;
  196976. }
  196977. /* this function was added to libpng 1.2.0 */
  196978. void PNGAPI
  196979. png_set_mmx_thresholds (png_structp png_ptr,
  196980. png_byte,
  196981. png_uint_32)
  196982. {
  196983. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  196984. if (png_ptr == NULL)
  196985. return;
  196986. }
  196987. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  196988. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  196989. /* this function was added to libpng 1.2.6 */
  196990. void PNGAPI
  196991. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  196992. png_uint_32 user_height_max)
  196993. {
  196994. /* Images with dimensions larger than these limits will be
  196995. * rejected by png_set_IHDR(). To accept any PNG datastream
  196996. * regardless of dimensions, set both limits to 0x7ffffffL.
  196997. */
  196998. if(png_ptr == NULL) return;
  196999. png_ptr->user_width_max = user_width_max;
  197000. png_ptr->user_height_max = user_height_max;
  197001. }
  197002. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  197003. #endif /* ?PNG_1_0_X */
  197004. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  197005. /*** End of inlined file: pngset.c ***/
  197006. /*** Start of inlined file: pngtrans.c ***/
  197007. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  197008. *
  197009. * Last changed in libpng 1.2.17 May 15, 2007
  197010. * For conditions of distribution and use, see copyright notice in png.h
  197011. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  197012. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  197013. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  197014. */
  197015. #define PNG_INTERNAL
  197016. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  197017. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  197018. /* turn on BGR-to-RGB mapping */
  197019. void PNGAPI
  197020. png_set_bgr(png_structp png_ptr)
  197021. {
  197022. png_debug(1, "in png_set_bgr\n");
  197023. if(png_ptr == NULL) return;
  197024. png_ptr->transformations |= PNG_BGR;
  197025. }
  197026. #endif
  197027. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  197028. /* turn on 16 bit byte swapping */
  197029. void PNGAPI
  197030. png_set_swap(png_structp png_ptr)
  197031. {
  197032. png_debug(1, "in png_set_swap\n");
  197033. if(png_ptr == NULL) return;
  197034. if (png_ptr->bit_depth == 16)
  197035. png_ptr->transformations |= PNG_SWAP_BYTES;
  197036. }
  197037. #endif
  197038. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  197039. /* turn on pixel packing */
  197040. void PNGAPI
  197041. png_set_packing(png_structp png_ptr)
  197042. {
  197043. png_debug(1, "in png_set_packing\n");
  197044. if(png_ptr == NULL) return;
  197045. if (png_ptr->bit_depth < 8)
  197046. {
  197047. png_ptr->transformations |= PNG_PACK;
  197048. png_ptr->usr_bit_depth = 8;
  197049. }
  197050. }
  197051. #endif
  197052. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  197053. /* turn on packed pixel swapping */
  197054. void PNGAPI
  197055. png_set_packswap(png_structp png_ptr)
  197056. {
  197057. png_debug(1, "in png_set_packswap\n");
  197058. if(png_ptr == NULL) return;
  197059. if (png_ptr->bit_depth < 8)
  197060. png_ptr->transformations |= PNG_PACKSWAP;
  197061. }
  197062. #endif
  197063. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  197064. void PNGAPI
  197065. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  197066. {
  197067. png_debug(1, "in png_set_shift\n");
  197068. if(png_ptr == NULL) return;
  197069. png_ptr->transformations |= PNG_SHIFT;
  197070. png_ptr->shift = *true_bits;
  197071. }
  197072. #endif
  197073. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  197074. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  197075. int PNGAPI
  197076. png_set_interlace_handling(png_structp png_ptr)
  197077. {
  197078. png_debug(1, "in png_set_interlace handling\n");
  197079. if (png_ptr && png_ptr->interlaced)
  197080. {
  197081. png_ptr->transformations |= PNG_INTERLACE;
  197082. return (7);
  197083. }
  197084. return (1);
  197085. }
  197086. #endif
  197087. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  197088. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  197089. * The filler type has changed in v0.95 to allow future 2-byte fillers
  197090. * for 48-bit input data, as well as to avoid problems with some compilers
  197091. * that don't like bytes as parameters.
  197092. */
  197093. void PNGAPI
  197094. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  197095. {
  197096. png_debug(1, "in png_set_filler\n");
  197097. if(png_ptr == NULL) return;
  197098. png_ptr->transformations |= PNG_FILLER;
  197099. png_ptr->filler = (png_byte)filler;
  197100. if (filler_loc == PNG_FILLER_AFTER)
  197101. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  197102. else
  197103. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  197104. /* This should probably go in the "do_read_filler" routine.
  197105. * I attempted to do that in libpng-1.0.1a but that caused problems
  197106. * so I restored it in libpng-1.0.2a
  197107. */
  197108. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  197109. {
  197110. png_ptr->usr_channels = 4;
  197111. }
  197112. /* Also I added this in libpng-1.0.2a (what happens when we expand
  197113. * a less-than-8-bit grayscale to GA? */
  197114. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  197115. {
  197116. png_ptr->usr_channels = 2;
  197117. }
  197118. }
  197119. #if !defined(PNG_1_0_X)
  197120. /* Added to libpng-1.2.7 */
  197121. void PNGAPI
  197122. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  197123. {
  197124. png_debug(1, "in png_set_add_alpha\n");
  197125. if(png_ptr == NULL) return;
  197126. png_set_filler(png_ptr, filler, filler_loc);
  197127. png_ptr->transformations |= PNG_ADD_ALPHA;
  197128. }
  197129. #endif
  197130. #endif
  197131. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  197132. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  197133. void PNGAPI
  197134. png_set_swap_alpha(png_structp png_ptr)
  197135. {
  197136. png_debug(1, "in png_set_swap_alpha\n");
  197137. if(png_ptr == NULL) return;
  197138. png_ptr->transformations |= PNG_SWAP_ALPHA;
  197139. }
  197140. #endif
  197141. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  197142. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  197143. void PNGAPI
  197144. png_set_invert_alpha(png_structp png_ptr)
  197145. {
  197146. png_debug(1, "in png_set_invert_alpha\n");
  197147. if(png_ptr == NULL) return;
  197148. png_ptr->transformations |= PNG_INVERT_ALPHA;
  197149. }
  197150. #endif
  197151. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  197152. void PNGAPI
  197153. png_set_invert_mono(png_structp png_ptr)
  197154. {
  197155. png_debug(1, "in png_set_invert_mono\n");
  197156. if(png_ptr == NULL) return;
  197157. png_ptr->transformations |= PNG_INVERT_MONO;
  197158. }
  197159. /* invert monochrome grayscale data */
  197160. void /* PRIVATE */
  197161. png_do_invert(png_row_infop row_info, png_bytep row)
  197162. {
  197163. png_debug(1, "in png_do_invert\n");
  197164. /* This test removed from libpng version 1.0.13 and 1.2.0:
  197165. * if (row_info->bit_depth == 1 &&
  197166. */
  197167. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197168. if (row == NULL || row_info == NULL)
  197169. return;
  197170. #endif
  197171. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  197172. {
  197173. png_bytep rp = row;
  197174. png_uint_32 i;
  197175. png_uint_32 istop = row_info->rowbytes;
  197176. for (i = 0; i < istop; i++)
  197177. {
  197178. *rp = (png_byte)(~(*rp));
  197179. rp++;
  197180. }
  197181. }
  197182. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  197183. row_info->bit_depth == 8)
  197184. {
  197185. png_bytep rp = row;
  197186. png_uint_32 i;
  197187. png_uint_32 istop = row_info->rowbytes;
  197188. for (i = 0; i < istop; i+=2)
  197189. {
  197190. *rp = (png_byte)(~(*rp));
  197191. rp+=2;
  197192. }
  197193. }
  197194. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  197195. row_info->bit_depth == 16)
  197196. {
  197197. png_bytep rp = row;
  197198. png_uint_32 i;
  197199. png_uint_32 istop = row_info->rowbytes;
  197200. for (i = 0; i < istop; i+=4)
  197201. {
  197202. *rp = (png_byte)(~(*rp));
  197203. *(rp+1) = (png_byte)(~(*(rp+1)));
  197204. rp+=4;
  197205. }
  197206. }
  197207. }
  197208. #endif
  197209. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  197210. /* swaps byte order on 16 bit depth images */
  197211. void /* PRIVATE */
  197212. png_do_swap(png_row_infop row_info, png_bytep row)
  197213. {
  197214. png_debug(1, "in png_do_swap\n");
  197215. if (
  197216. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197217. row != NULL && row_info != NULL &&
  197218. #endif
  197219. row_info->bit_depth == 16)
  197220. {
  197221. png_bytep rp = row;
  197222. png_uint_32 i;
  197223. png_uint_32 istop= row_info->width * row_info->channels;
  197224. for (i = 0; i < istop; i++, rp += 2)
  197225. {
  197226. png_byte t = *rp;
  197227. *rp = *(rp + 1);
  197228. *(rp + 1) = t;
  197229. }
  197230. }
  197231. }
  197232. #endif
  197233. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  197234. static PNG_CONST png_byte onebppswaptable[256] = {
  197235. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  197236. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  197237. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  197238. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  197239. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  197240. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  197241. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  197242. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  197243. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  197244. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  197245. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  197246. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  197247. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  197248. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  197249. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  197250. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  197251. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  197252. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  197253. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  197254. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  197255. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  197256. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  197257. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  197258. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  197259. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  197260. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  197261. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  197262. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  197263. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  197264. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  197265. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  197266. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  197267. };
  197268. static PNG_CONST png_byte twobppswaptable[256] = {
  197269. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  197270. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  197271. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  197272. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  197273. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  197274. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  197275. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  197276. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  197277. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  197278. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  197279. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  197280. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  197281. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  197282. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  197283. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  197284. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  197285. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  197286. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  197287. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  197288. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  197289. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  197290. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  197291. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  197292. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  197293. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  197294. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  197295. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  197296. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  197297. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  197298. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  197299. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  197300. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  197301. };
  197302. static PNG_CONST png_byte fourbppswaptable[256] = {
  197303. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  197304. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  197305. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  197306. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  197307. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  197308. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  197309. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  197310. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  197311. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  197312. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  197313. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  197314. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  197315. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  197316. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  197317. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  197318. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  197319. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  197320. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  197321. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  197322. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  197323. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  197324. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  197325. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  197326. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  197327. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  197328. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  197329. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  197330. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  197331. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  197332. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  197333. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  197334. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  197335. };
  197336. /* swaps pixel packing order within bytes */
  197337. void /* PRIVATE */
  197338. png_do_packswap(png_row_infop row_info, png_bytep row)
  197339. {
  197340. png_debug(1, "in png_do_packswap\n");
  197341. if (
  197342. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197343. row != NULL && row_info != NULL &&
  197344. #endif
  197345. row_info->bit_depth < 8)
  197346. {
  197347. png_bytep rp, end, table;
  197348. end = row + row_info->rowbytes;
  197349. if (row_info->bit_depth == 1)
  197350. table = (png_bytep)onebppswaptable;
  197351. else if (row_info->bit_depth == 2)
  197352. table = (png_bytep)twobppswaptable;
  197353. else if (row_info->bit_depth == 4)
  197354. table = (png_bytep)fourbppswaptable;
  197355. else
  197356. return;
  197357. for (rp = row; rp < end; rp++)
  197358. *rp = table[*rp];
  197359. }
  197360. }
  197361. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  197362. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  197363. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  197364. /* remove filler or alpha byte(s) */
  197365. void /* PRIVATE */
  197366. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  197367. {
  197368. png_debug(1, "in png_do_strip_filler\n");
  197369. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197370. if (row != NULL && row_info != NULL)
  197371. #endif
  197372. {
  197373. png_bytep sp=row;
  197374. png_bytep dp=row;
  197375. png_uint_32 row_width=row_info->width;
  197376. png_uint_32 i;
  197377. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  197378. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  197379. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  197380. row_info->channels == 4)
  197381. {
  197382. if (row_info->bit_depth == 8)
  197383. {
  197384. /* This converts from RGBX or RGBA to RGB */
  197385. if (flags & PNG_FLAG_FILLER_AFTER)
  197386. {
  197387. dp+=3; sp+=4;
  197388. for (i = 1; i < row_width; i++)
  197389. {
  197390. *dp++ = *sp++;
  197391. *dp++ = *sp++;
  197392. *dp++ = *sp++;
  197393. sp++;
  197394. }
  197395. }
  197396. /* This converts from XRGB or ARGB to RGB */
  197397. else
  197398. {
  197399. for (i = 0; i < row_width; i++)
  197400. {
  197401. sp++;
  197402. *dp++ = *sp++;
  197403. *dp++ = *sp++;
  197404. *dp++ = *sp++;
  197405. }
  197406. }
  197407. row_info->pixel_depth = 24;
  197408. row_info->rowbytes = row_width * 3;
  197409. }
  197410. else /* if (row_info->bit_depth == 16) */
  197411. {
  197412. if (flags & PNG_FLAG_FILLER_AFTER)
  197413. {
  197414. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  197415. sp += 8; dp += 6;
  197416. for (i = 1; i < row_width; i++)
  197417. {
  197418. /* This could be (although png_memcpy is probably slower):
  197419. png_memcpy(dp, sp, 6);
  197420. sp += 8;
  197421. dp += 6;
  197422. */
  197423. *dp++ = *sp++;
  197424. *dp++ = *sp++;
  197425. *dp++ = *sp++;
  197426. *dp++ = *sp++;
  197427. *dp++ = *sp++;
  197428. *dp++ = *sp++;
  197429. sp += 2;
  197430. }
  197431. }
  197432. else
  197433. {
  197434. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  197435. for (i = 0; i < row_width; i++)
  197436. {
  197437. /* This could be (although png_memcpy is probably slower):
  197438. png_memcpy(dp, sp, 6);
  197439. sp += 8;
  197440. dp += 6;
  197441. */
  197442. sp+=2;
  197443. *dp++ = *sp++;
  197444. *dp++ = *sp++;
  197445. *dp++ = *sp++;
  197446. *dp++ = *sp++;
  197447. *dp++ = *sp++;
  197448. *dp++ = *sp++;
  197449. }
  197450. }
  197451. row_info->pixel_depth = 48;
  197452. row_info->rowbytes = row_width * 6;
  197453. }
  197454. row_info->channels = 3;
  197455. }
  197456. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  197457. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  197458. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  197459. row_info->channels == 2)
  197460. {
  197461. if (row_info->bit_depth == 8)
  197462. {
  197463. /* This converts from GX or GA to G */
  197464. if (flags & PNG_FLAG_FILLER_AFTER)
  197465. {
  197466. for (i = 0; i < row_width; i++)
  197467. {
  197468. *dp++ = *sp++;
  197469. sp++;
  197470. }
  197471. }
  197472. /* This converts from XG or AG to G */
  197473. else
  197474. {
  197475. for (i = 0; i < row_width; i++)
  197476. {
  197477. sp++;
  197478. *dp++ = *sp++;
  197479. }
  197480. }
  197481. row_info->pixel_depth = 8;
  197482. row_info->rowbytes = row_width;
  197483. }
  197484. else /* if (row_info->bit_depth == 16) */
  197485. {
  197486. if (flags & PNG_FLAG_FILLER_AFTER)
  197487. {
  197488. /* This converts from GGXX or GGAA to GG */
  197489. sp += 4; dp += 2;
  197490. for (i = 1; i < row_width; i++)
  197491. {
  197492. *dp++ = *sp++;
  197493. *dp++ = *sp++;
  197494. sp += 2;
  197495. }
  197496. }
  197497. else
  197498. {
  197499. /* This converts from XXGG or AAGG to GG */
  197500. for (i = 0; i < row_width; i++)
  197501. {
  197502. sp += 2;
  197503. *dp++ = *sp++;
  197504. *dp++ = *sp++;
  197505. }
  197506. }
  197507. row_info->pixel_depth = 16;
  197508. row_info->rowbytes = row_width * 2;
  197509. }
  197510. row_info->channels = 1;
  197511. }
  197512. if (flags & PNG_FLAG_STRIP_ALPHA)
  197513. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  197514. }
  197515. }
  197516. #endif
  197517. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  197518. /* swaps red and blue bytes within a pixel */
  197519. void /* PRIVATE */
  197520. png_do_bgr(png_row_infop row_info, png_bytep row)
  197521. {
  197522. png_debug(1, "in png_do_bgr\n");
  197523. if (
  197524. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197525. row != NULL && row_info != NULL &&
  197526. #endif
  197527. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  197528. {
  197529. png_uint_32 row_width = row_info->width;
  197530. if (row_info->bit_depth == 8)
  197531. {
  197532. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  197533. {
  197534. png_bytep rp;
  197535. png_uint_32 i;
  197536. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  197537. {
  197538. png_byte save = *rp;
  197539. *rp = *(rp + 2);
  197540. *(rp + 2) = save;
  197541. }
  197542. }
  197543. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  197544. {
  197545. png_bytep rp;
  197546. png_uint_32 i;
  197547. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  197548. {
  197549. png_byte save = *rp;
  197550. *rp = *(rp + 2);
  197551. *(rp + 2) = save;
  197552. }
  197553. }
  197554. }
  197555. else if (row_info->bit_depth == 16)
  197556. {
  197557. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  197558. {
  197559. png_bytep rp;
  197560. png_uint_32 i;
  197561. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  197562. {
  197563. png_byte save = *rp;
  197564. *rp = *(rp + 4);
  197565. *(rp + 4) = save;
  197566. save = *(rp + 1);
  197567. *(rp + 1) = *(rp + 5);
  197568. *(rp + 5) = save;
  197569. }
  197570. }
  197571. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  197572. {
  197573. png_bytep rp;
  197574. png_uint_32 i;
  197575. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  197576. {
  197577. png_byte save = *rp;
  197578. *rp = *(rp + 4);
  197579. *(rp + 4) = save;
  197580. save = *(rp + 1);
  197581. *(rp + 1) = *(rp + 5);
  197582. *(rp + 5) = save;
  197583. }
  197584. }
  197585. }
  197586. }
  197587. }
  197588. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  197589. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  197590. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  197591. defined(PNG_LEGACY_SUPPORTED)
  197592. void PNGAPI
  197593. png_set_user_transform_info(png_structp png_ptr, png_voidp
  197594. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  197595. {
  197596. png_debug(1, "in png_set_user_transform_info\n");
  197597. if(png_ptr == NULL) return;
  197598. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  197599. png_ptr->user_transform_ptr = user_transform_ptr;
  197600. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  197601. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  197602. #else
  197603. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  197604. png_warning(png_ptr,
  197605. "This version of libpng does not support user transform info");
  197606. #endif
  197607. }
  197608. #endif
  197609. /* This function returns a pointer to the user_transform_ptr associated with
  197610. * the user transform functions. The application should free any memory
  197611. * associated with this pointer before png_write_destroy and png_read_destroy
  197612. * are called.
  197613. */
  197614. png_voidp PNGAPI
  197615. png_get_user_transform_ptr(png_structp png_ptr)
  197616. {
  197617. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  197618. if (png_ptr == NULL) return (NULL);
  197619. return ((png_voidp)png_ptr->user_transform_ptr);
  197620. #else
  197621. return (NULL);
  197622. #endif
  197623. }
  197624. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  197625. /*** End of inlined file: pngtrans.c ***/
  197626. /*** Start of inlined file: pngwio.c ***/
  197627. /* pngwio.c - functions for data output
  197628. *
  197629. * Last changed in libpng 1.2.13 November 13, 2006
  197630. * For conditions of distribution and use, see copyright notice in png.h
  197631. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  197632. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  197633. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  197634. *
  197635. * This file provides a location for all output. Users who need
  197636. * special handling are expected to write functions that have the same
  197637. * arguments as these and perform similar functions, but that possibly
  197638. * use different output methods. Note that you shouldn't change these
  197639. * functions, but rather write replacement functions and then change
  197640. * them at run time with png_set_write_fn(...).
  197641. */
  197642. #define PNG_INTERNAL
  197643. #ifdef PNG_WRITE_SUPPORTED
  197644. /* Write the data to whatever output you are using. The default routine
  197645. writes to a file pointer. Note that this routine sometimes gets called
  197646. with very small lengths, so you should implement some kind of simple
  197647. buffering if you are using unbuffered writes. This should never be asked
  197648. to write more than 64K on a 16 bit machine. */
  197649. void /* PRIVATE */
  197650. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  197651. {
  197652. if (png_ptr->write_data_fn != NULL )
  197653. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  197654. else
  197655. png_error(png_ptr, "Call to NULL write function");
  197656. }
  197657. #if !defined(PNG_NO_STDIO)
  197658. /* This is the function that does the actual writing of data. If you are
  197659. not writing to a standard C stream, you should create a replacement
  197660. write_data function and use it at run time with png_set_write_fn(), rather
  197661. than changing the library. */
  197662. #ifndef USE_FAR_KEYWORD
  197663. void PNGAPI
  197664. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  197665. {
  197666. png_uint_32 check;
  197667. if(png_ptr == NULL) return;
  197668. #if defined(_WIN32_WCE)
  197669. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  197670. check = 0;
  197671. #else
  197672. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  197673. #endif
  197674. if (check != length)
  197675. png_error(png_ptr, "Write Error");
  197676. }
  197677. #else
  197678. /* this is the model-independent version. Since the standard I/O library
  197679. can't handle far buffers in the medium and small models, we have to copy
  197680. the data.
  197681. */
  197682. #define NEAR_BUF_SIZE 1024
  197683. #define MIN(a,b) (a <= b ? a : b)
  197684. void PNGAPI
  197685. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  197686. {
  197687. png_uint_32 check;
  197688. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  197689. png_FILE_p io_ptr;
  197690. if(png_ptr == NULL) return;
  197691. /* Check if data really is near. If so, use usual code. */
  197692. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  197693. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  197694. if ((png_bytep)near_data == data)
  197695. {
  197696. #if defined(_WIN32_WCE)
  197697. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  197698. check = 0;
  197699. #else
  197700. check = fwrite(near_data, 1, length, io_ptr);
  197701. #endif
  197702. }
  197703. else
  197704. {
  197705. png_byte buf[NEAR_BUF_SIZE];
  197706. png_size_t written, remaining, err;
  197707. check = 0;
  197708. remaining = length;
  197709. do
  197710. {
  197711. written = MIN(NEAR_BUF_SIZE, remaining);
  197712. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  197713. #if defined(_WIN32_WCE)
  197714. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  197715. err = 0;
  197716. #else
  197717. err = fwrite(buf, 1, written, io_ptr);
  197718. #endif
  197719. if (err != written)
  197720. break;
  197721. else
  197722. check += err;
  197723. data += written;
  197724. remaining -= written;
  197725. }
  197726. while (remaining != 0);
  197727. }
  197728. if (check != length)
  197729. png_error(png_ptr, "Write Error");
  197730. }
  197731. #endif
  197732. #endif
  197733. /* This function is called to output any data pending writing (normally
  197734. to disk). After png_flush is called, there should be no data pending
  197735. writing in any buffers. */
  197736. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  197737. void /* PRIVATE */
  197738. png_flush(png_structp png_ptr)
  197739. {
  197740. if (png_ptr->output_flush_fn != NULL)
  197741. (*(png_ptr->output_flush_fn))(png_ptr);
  197742. }
  197743. #if !defined(PNG_NO_STDIO)
  197744. void PNGAPI
  197745. png_default_flush(png_structp png_ptr)
  197746. {
  197747. #if !defined(_WIN32_WCE)
  197748. png_FILE_p io_ptr;
  197749. #endif
  197750. if(png_ptr == NULL) return;
  197751. #if !defined(_WIN32_WCE)
  197752. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  197753. if (io_ptr != NULL)
  197754. fflush(io_ptr);
  197755. #endif
  197756. }
  197757. #endif
  197758. #endif
  197759. /* This function allows the application to supply new output functions for
  197760. libpng if standard C streams aren't being used.
  197761. This function takes as its arguments:
  197762. png_ptr - pointer to a png output data structure
  197763. io_ptr - pointer to user supplied structure containing info about
  197764. the output functions. May be NULL.
  197765. write_data_fn - pointer to a new output function that takes as its
  197766. arguments a pointer to a png_struct, a pointer to
  197767. data to be written, and a 32-bit unsigned int that is
  197768. the number of bytes to be written. The new write
  197769. function should call png_error(png_ptr, "Error msg")
  197770. to exit and output any fatal error messages.
  197771. flush_data_fn - pointer to a new flush function that takes as its
  197772. arguments a pointer to a png_struct. After a call to
  197773. the flush function, there should be no data in any buffers
  197774. or pending transmission. If the output method doesn't do
  197775. any buffering of ouput, a function prototype must still be
  197776. supplied although it doesn't have to do anything. If
  197777. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  197778. time, output_flush_fn will be ignored, although it must be
  197779. supplied for compatibility. */
  197780. void PNGAPI
  197781. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  197782. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  197783. {
  197784. if(png_ptr == NULL) return;
  197785. png_ptr->io_ptr = io_ptr;
  197786. #if !defined(PNG_NO_STDIO)
  197787. if (write_data_fn != NULL)
  197788. png_ptr->write_data_fn = write_data_fn;
  197789. else
  197790. png_ptr->write_data_fn = png_default_write_data;
  197791. #else
  197792. png_ptr->write_data_fn = write_data_fn;
  197793. #endif
  197794. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  197795. #if !defined(PNG_NO_STDIO)
  197796. if (output_flush_fn != NULL)
  197797. png_ptr->output_flush_fn = output_flush_fn;
  197798. else
  197799. png_ptr->output_flush_fn = png_default_flush;
  197800. #else
  197801. png_ptr->output_flush_fn = output_flush_fn;
  197802. #endif
  197803. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  197804. /* It is an error to read while writing a png file */
  197805. if (png_ptr->read_data_fn != NULL)
  197806. {
  197807. png_ptr->read_data_fn = NULL;
  197808. png_warning(png_ptr,
  197809. "Attempted to set both read_data_fn and write_data_fn in");
  197810. png_warning(png_ptr,
  197811. "the same structure. Resetting read_data_fn to NULL.");
  197812. }
  197813. }
  197814. #if defined(USE_FAR_KEYWORD)
  197815. #if defined(_MSC_VER)
  197816. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  197817. {
  197818. void *near_ptr;
  197819. void FAR *far_ptr;
  197820. FP_OFF(near_ptr) = FP_OFF(ptr);
  197821. far_ptr = (void FAR *)near_ptr;
  197822. if(check != 0)
  197823. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  197824. png_error(png_ptr,"segment lost in conversion");
  197825. return(near_ptr);
  197826. }
  197827. # else
  197828. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  197829. {
  197830. void *near_ptr;
  197831. void FAR *far_ptr;
  197832. near_ptr = (void FAR *)ptr;
  197833. far_ptr = (void FAR *)near_ptr;
  197834. if(check != 0)
  197835. if(far_ptr != ptr)
  197836. png_error(png_ptr,"segment lost in conversion");
  197837. return(near_ptr);
  197838. }
  197839. # endif
  197840. # endif
  197841. #endif /* PNG_WRITE_SUPPORTED */
  197842. /*** End of inlined file: pngwio.c ***/
  197843. /*** Start of inlined file: pngwrite.c ***/
  197844. /* pngwrite.c - general routines to write a PNG file
  197845. *
  197846. * Last changed in libpng 1.2.15 January 5, 2007
  197847. * For conditions of distribution and use, see copyright notice in png.h
  197848. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  197849. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  197850. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  197851. */
  197852. /* get internal access to png.h */
  197853. #define PNG_INTERNAL
  197854. #ifdef PNG_WRITE_SUPPORTED
  197855. /* Writes all the PNG information. This is the suggested way to use the
  197856. * library. If you have a new chunk to add, make a function to write it,
  197857. * and put it in the correct location here. If you want the chunk written
  197858. * after the image data, put it in png_write_end(). I strongly encourage
  197859. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  197860. * the chunk, as that will keep the code from breaking if you want to just
  197861. * write a plain PNG file. If you have long comments, I suggest writing
  197862. * them in png_write_end(), and compressing them.
  197863. */
  197864. void PNGAPI
  197865. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  197866. {
  197867. png_debug(1, "in png_write_info_before_PLTE\n");
  197868. if (png_ptr == NULL || info_ptr == NULL)
  197869. return;
  197870. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  197871. {
  197872. png_write_sig(png_ptr); /* write PNG signature */
  197873. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197874. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  197875. {
  197876. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  197877. png_ptr->mng_features_permitted=0;
  197878. }
  197879. #endif
  197880. /* write IHDR information. */
  197881. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  197882. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  197883. info_ptr->filter_type,
  197884. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  197885. info_ptr->interlace_type);
  197886. #else
  197887. 0);
  197888. #endif
  197889. /* the rest of these check to see if the valid field has the appropriate
  197890. flag set, and if it does, writes the chunk. */
  197891. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  197892. if (info_ptr->valid & PNG_INFO_gAMA)
  197893. {
  197894. # ifdef PNG_FLOATING_POINT_SUPPORTED
  197895. png_write_gAMA(png_ptr, info_ptr->gamma);
  197896. #else
  197897. #ifdef PNG_FIXED_POINT_SUPPORTED
  197898. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  197899. # endif
  197900. #endif
  197901. }
  197902. #endif
  197903. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  197904. if (info_ptr->valid & PNG_INFO_sRGB)
  197905. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  197906. #endif
  197907. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  197908. if (info_ptr->valid & PNG_INFO_iCCP)
  197909. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  197910. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  197911. #endif
  197912. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  197913. if (info_ptr->valid & PNG_INFO_sBIT)
  197914. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  197915. #endif
  197916. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  197917. if (info_ptr->valid & PNG_INFO_cHRM)
  197918. {
  197919. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197920. png_write_cHRM(png_ptr,
  197921. info_ptr->x_white, info_ptr->y_white,
  197922. info_ptr->x_red, info_ptr->y_red,
  197923. info_ptr->x_green, info_ptr->y_green,
  197924. info_ptr->x_blue, info_ptr->y_blue);
  197925. #else
  197926. # ifdef PNG_FIXED_POINT_SUPPORTED
  197927. png_write_cHRM_fixed(png_ptr,
  197928. info_ptr->int_x_white, info_ptr->int_y_white,
  197929. info_ptr->int_x_red, info_ptr->int_y_red,
  197930. info_ptr->int_x_green, info_ptr->int_y_green,
  197931. info_ptr->int_x_blue, info_ptr->int_y_blue);
  197932. # endif
  197933. #endif
  197934. }
  197935. #endif
  197936. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  197937. if (info_ptr->unknown_chunks_num)
  197938. {
  197939. png_unknown_chunk *up;
  197940. png_debug(5, "writing extra chunks\n");
  197941. for (up = info_ptr->unknown_chunks;
  197942. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  197943. up++)
  197944. {
  197945. int keep=png_handle_as_unknown(png_ptr, up->name);
  197946. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  197947. up->location && !(up->location & PNG_HAVE_PLTE) &&
  197948. !(up->location & PNG_HAVE_IDAT) &&
  197949. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  197950. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  197951. {
  197952. png_write_chunk(png_ptr, up->name, up->data, up->size);
  197953. }
  197954. }
  197955. }
  197956. #endif
  197957. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  197958. }
  197959. }
  197960. void PNGAPI
  197961. png_write_info(png_structp png_ptr, png_infop info_ptr)
  197962. {
  197963. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  197964. int i;
  197965. #endif
  197966. png_debug(1, "in png_write_info\n");
  197967. if (png_ptr == NULL || info_ptr == NULL)
  197968. return;
  197969. png_write_info_before_PLTE(png_ptr, info_ptr);
  197970. if (info_ptr->valid & PNG_INFO_PLTE)
  197971. png_write_PLTE(png_ptr, info_ptr->palette,
  197972. (png_uint_32)info_ptr->num_palette);
  197973. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197974. png_error(png_ptr, "Valid palette required for paletted images");
  197975. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  197976. if (info_ptr->valid & PNG_INFO_tRNS)
  197977. {
  197978. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  197979. /* invert the alpha channel (in tRNS) */
  197980. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  197981. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197982. {
  197983. int j;
  197984. for (j=0; j<(int)info_ptr->num_trans; j++)
  197985. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  197986. }
  197987. #endif
  197988. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  197989. info_ptr->num_trans, info_ptr->color_type);
  197990. }
  197991. #endif
  197992. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  197993. if (info_ptr->valid & PNG_INFO_bKGD)
  197994. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  197995. #endif
  197996. #if defined(PNG_WRITE_hIST_SUPPORTED)
  197997. if (info_ptr->valid & PNG_INFO_hIST)
  197998. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  197999. #endif
  198000. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  198001. if (info_ptr->valid & PNG_INFO_oFFs)
  198002. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  198003. info_ptr->offset_unit_type);
  198004. #endif
  198005. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  198006. if (info_ptr->valid & PNG_INFO_pCAL)
  198007. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  198008. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  198009. info_ptr->pcal_units, info_ptr->pcal_params);
  198010. #endif
  198011. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  198012. if (info_ptr->valid & PNG_INFO_sCAL)
  198013. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  198014. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  198015. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  198016. #else
  198017. #ifdef PNG_FIXED_POINT_SUPPORTED
  198018. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  198019. info_ptr->scal_s_width, info_ptr->scal_s_height);
  198020. #else
  198021. png_warning(png_ptr,
  198022. "png_write_sCAL not supported; sCAL chunk not written.");
  198023. #endif
  198024. #endif
  198025. #endif
  198026. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  198027. if (info_ptr->valid & PNG_INFO_pHYs)
  198028. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  198029. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  198030. #endif
  198031. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198032. if (info_ptr->valid & PNG_INFO_tIME)
  198033. {
  198034. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  198035. png_ptr->mode |= PNG_WROTE_tIME;
  198036. }
  198037. #endif
  198038. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  198039. if (info_ptr->valid & PNG_INFO_sPLT)
  198040. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  198041. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  198042. #endif
  198043. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198044. /* Check to see if we need to write text chunks */
  198045. for (i = 0; i < info_ptr->num_text; i++)
  198046. {
  198047. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  198048. info_ptr->text[i].compression);
  198049. /* an internationalized chunk? */
  198050. if (info_ptr->text[i].compression > 0)
  198051. {
  198052. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  198053. /* write international chunk */
  198054. png_write_iTXt(png_ptr,
  198055. info_ptr->text[i].compression,
  198056. info_ptr->text[i].key,
  198057. info_ptr->text[i].lang,
  198058. info_ptr->text[i].lang_key,
  198059. info_ptr->text[i].text);
  198060. #else
  198061. png_warning(png_ptr, "Unable to write international text");
  198062. #endif
  198063. /* Mark this chunk as written */
  198064. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198065. }
  198066. /* If we want a compressed text chunk */
  198067. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  198068. {
  198069. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  198070. /* write compressed chunk */
  198071. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  198072. info_ptr->text[i].text, 0,
  198073. info_ptr->text[i].compression);
  198074. #else
  198075. png_warning(png_ptr, "Unable to write compressed text");
  198076. #endif
  198077. /* Mark this chunk as written */
  198078. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  198079. }
  198080. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  198081. {
  198082. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  198083. /* write uncompressed chunk */
  198084. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  198085. info_ptr->text[i].text,
  198086. 0);
  198087. #else
  198088. png_warning(png_ptr, "Unable to write uncompressed text");
  198089. #endif
  198090. /* Mark this chunk as written */
  198091. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198092. }
  198093. }
  198094. #endif
  198095. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198096. if (info_ptr->unknown_chunks_num)
  198097. {
  198098. png_unknown_chunk *up;
  198099. png_debug(5, "writing extra chunks\n");
  198100. for (up = info_ptr->unknown_chunks;
  198101. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198102. up++)
  198103. {
  198104. int keep=png_handle_as_unknown(png_ptr, up->name);
  198105. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198106. up->location && (up->location & PNG_HAVE_PLTE) &&
  198107. !(up->location & PNG_HAVE_IDAT) &&
  198108. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198109. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198110. {
  198111. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198112. }
  198113. }
  198114. }
  198115. #endif
  198116. }
  198117. /* Writes the end of the PNG file. If you don't want to write comments or
  198118. * time information, you can pass NULL for info. If you already wrote these
  198119. * in png_write_info(), do not write them again here. If you have long
  198120. * comments, I suggest writing them here, and compressing them.
  198121. */
  198122. void PNGAPI
  198123. png_write_end(png_structp png_ptr, png_infop info_ptr)
  198124. {
  198125. png_debug(1, "in png_write_end\n");
  198126. if (png_ptr == NULL)
  198127. return;
  198128. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  198129. png_error(png_ptr, "No IDATs written into file");
  198130. /* see if user wants us to write information chunks */
  198131. if (info_ptr != NULL)
  198132. {
  198133. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198134. int i; /* local index variable */
  198135. #endif
  198136. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198137. /* check to see if user has supplied a time chunk */
  198138. if ((info_ptr->valid & PNG_INFO_tIME) &&
  198139. !(png_ptr->mode & PNG_WROTE_tIME))
  198140. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  198141. #endif
  198142. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198143. /* loop through comment chunks */
  198144. for (i = 0; i < info_ptr->num_text; i++)
  198145. {
  198146. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  198147. info_ptr->text[i].compression);
  198148. /* an internationalized chunk? */
  198149. if (info_ptr->text[i].compression > 0)
  198150. {
  198151. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  198152. /* write international chunk */
  198153. png_write_iTXt(png_ptr,
  198154. info_ptr->text[i].compression,
  198155. info_ptr->text[i].key,
  198156. info_ptr->text[i].lang,
  198157. info_ptr->text[i].lang_key,
  198158. info_ptr->text[i].text);
  198159. #else
  198160. png_warning(png_ptr, "Unable to write international text");
  198161. #endif
  198162. /* Mark this chunk as written */
  198163. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198164. }
  198165. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  198166. {
  198167. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  198168. /* write compressed chunk */
  198169. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  198170. info_ptr->text[i].text, 0,
  198171. info_ptr->text[i].compression);
  198172. #else
  198173. png_warning(png_ptr, "Unable to write compressed text");
  198174. #endif
  198175. /* Mark this chunk as written */
  198176. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  198177. }
  198178. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  198179. {
  198180. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  198181. /* write uncompressed chunk */
  198182. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  198183. info_ptr->text[i].text, 0);
  198184. #else
  198185. png_warning(png_ptr, "Unable to write uncompressed text");
  198186. #endif
  198187. /* Mark this chunk as written */
  198188. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198189. }
  198190. }
  198191. #endif
  198192. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198193. if (info_ptr->unknown_chunks_num)
  198194. {
  198195. png_unknown_chunk *up;
  198196. png_debug(5, "writing extra chunks\n");
  198197. for (up = info_ptr->unknown_chunks;
  198198. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198199. up++)
  198200. {
  198201. int keep=png_handle_as_unknown(png_ptr, up->name);
  198202. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198203. up->location && (up->location & PNG_AFTER_IDAT) &&
  198204. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198205. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198206. {
  198207. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198208. }
  198209. }
  198210. }
  198211. #endif
  198212. }
  198213. png_ptr->mode |= PNG_AFTER_IDAT;
  198214. /* write end of PNG file */
  198215. png_write_IEND(png_ptr);
  198216. }
  198217. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198218. #if !defined(_WIN32_WCE)
  198219. /* "time.h" functions are not supported on WindowsCE */
  198220. void PNGAPI
  198221. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  198222. {
  198223. png_debug(1, "in png_convert_from_struct_tm\n");
  198224. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  198225. ptime->month = (png_byte)(ttime->tm_mon + 1);
  198226. ptime->day = (png_byte)ttime->tm_mday;
  198227. ptime->hour = (png_byte)ttime->tm_hour;
  198228. ptime->minute = (png_byte)ttime->tm_min;
  198229. ptime->second = (png_byte)ttime->tm_sec;
  198230. }
  198231. void PNGAPI
  198232. png_convert_from_time_t(png_timep ptime, time_t ttime)
  198233. {
  198234. struct tm *tbuf;
  198235. png_debug(1, "in png_convert_from_time_t\n");
  198236. tbuf = gmtime(&ttime);
  198237. png_convert_from_struct_tm(ptime, tbuf);
  198238. }
  198239. #endif
  198240. #endif
  198241. /* Initialize png_ptr structure, and allocate any memory needed */
  198242. png_structp PNGAPI
  198243. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  198244. png_error_ptr error_fn, png_error_ptr warn_fn)
  198245. {
  198246. #ifdef PNG_USER_MEM_SUPPORTED
  198247. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  198248. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  198249. }
  198250. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  198251. png_structp PNGAPI
  198252. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  198253. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  198254. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  198255. {
  198256. #endif /* PNG_USER_MEM_SUPPORTED */
  198257. png_structp png_ptr;
  198258. #ifdef PNG_SETJMP_SUPPORTED
  198259. #ifdef USE_FAR_KEYWORD
  198260. jmp_buf jmpbuf;
  198261. #endif
  198262. #endif
  198263. int i;
  198264. png_debug(1, "in png_create_write_struct\n");
  198265. #ifdef PNG_USER_MEM_SUPPORTED
  198266. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  198267. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  198268. #else
  198269. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  198270. #endif /* PNG_USER_MEM_SUPPORTED */
  198271. if (png_ptr == NULL)
  198272. return (NULL);
  198273. /* added at libpng-1.2.6 */
  198274. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  198275. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  198276. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  198277. #endif
  198278. #ifdef PNG_SETJMP_SUPPORTED
  198279. #ifdef USE_FAR_KEYWORD
  198280. if (setjmp(jmpbuf))
  198281. #else
  198282. if (setjmp(png_ptr->jmpbuf))
  198283. #endif
  198284. {
  198285. png_free(png_ptr, png_ptr->zbuf);
  198286. png_ptr->zbuf=NULL;
  198287. png_destroy_struct(png_ptr);
  198288. return (NULL);
  198289. }
  198290. #ifdef USE_FAR_KEYWORD
  198291. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  198292. #endif
  198293. #endif
  198294. #ifdef PNG_USER_MEM_SUPPORTED
  198295. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  198296. #endif /* PNG_USER_MEM_SUPPORTED */
  198297. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  198298. i=0;
  198299. do
  198300. {
  198301. if(user_png_ver[i] != png_libpng_ver[i])
  198302. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  198303. } while (png_libpng_ver[i++]);
  198304. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  198305. {
  198306. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  198307. * we must recompile any applications that use any older library version.
  198308. * For versions after libpng 1.0, we will be compatible, so we need
  198309. * only check the first digit.
  198310. */
  198311. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  198312. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  198313. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  198314. {
  198315. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  198316. char msg[80];
  198317. if (user_png_ver)
  198318. {
  198319. png_snprintf(msg, 80,
  198320. "Application was compiled with png.h from libpng-%.20s",
  198321. user_png_ver);
  198322. png_warning(png_ptr, msg);
  198323. }
  198324. png_snprintf(msg, 80,
  198325. "Application is running with png.c from libpng-%.20s",
  198326. png_libpng_ver);
  198327. png_warning(png_ptr, msg);
  198328. #endif
  198329. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  198330. png_ptr->flags=0;
  198331. #endif
  198332. png_error(png_ptr,
  198333. "Incompatible libpng version in application and library");
  198334. }
  198335. }
  198336. /* initialize zbuf - compression buffer */
  198337. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  198338. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  198339. (png_uint_32)png_ptr->zbuf_size);
  198340. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  198341. png_flush_ptr_NULL);
  198342. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198343. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  198344. 1, png_doublep_NULL, png_doublep_NULL);
  198345. #endif
  198346. #ifdef PNG_SETJMP_SUPPORTED
  198347. /* Applications that neglect to set up their own setjmp() and then encounter
  198348. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  198349. abort instead of returning. */
  198350. #ifdef USE_FAR_KEYWORD
  198351. if (setjmp(jmpbuf))
  198352. PNG_ABORT();
  198353. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  198354. #else
  198355. if (setjmp(png_ptr->jmpbuf))
  198356. PNG_ABORT();
  198357. #endif
  198358. #endif
  198359. return (png_ptr);
  198360. }
  198361. /* Initialize png_ptr structure, and allocate any memory needed */
  198362. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  198363. /* Deprecated. */
  198364. #undef png_write_init
  198365. void PNGAPI
  198366. png_write_init(png_structp png_ptr)
  198367. {
  198368. /* We only come here via pre-1.0.7-compiled applications */
  198369. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  198370. }
  198371. void PNGAPI
  198372. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  198373. png_size_t png_struct_size, png_size_t png_info_size)
  198374. {
  198375. /* We only come here via pre-1.0.12-compiled applications */
  198376. if(png_ptr == NULL) return;
  198377. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  198378. if(png_sizeof(png_struct) > png_struct_size ||
  198379. png_sizeof(png_info) > png_info_size)
  198380. {
  198381. char msg[80];
  198382. png_ptr->warning_fn=NULL;
  198383. if (user_png_ver)
  198384. {
  198385. png_snprintf(msg, 80,
  198386. "Application was compiled with png.h from libpng-%.20s",
  198387. user_png_ver);
  198388. png_warning(png_ptr, msg);
  198389. }
  198390. png_snprintf(msg, 80,
  198391. "Application is running with png.c from libpng-%.20s",
  198392. png_libpng_ver);
  198393. png_warning(png_ptr, msg);
  198394. }
  198395. #endif
  198396. if(png_sizeof(png_struct) > png_struct_size)
  198397. {
  198398. png_ptr->error_fn=NULL;
  198399. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  198400. png_ptr->flags=0;
  198401. #endif
  198402. png_error(png_ptr,
  198403. "The png struct allocated by the application for writing is too small.");
  198404. }
  198405. if(png_sizeof(png_info) > png_info_size)
  198406. {
  198407. png_ptr->error_fn=NULL;
  198408. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  198409. png_ptr->flags=0;
  198410. #endif
  198411. png_error(png_ptr,
  198412. "The info struct allocated by the application for writing is too small.");
  198413. }
  198414. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  198415. }
  198416. #endif /* PNG_1_0_X || PNG_1_2_X */
  198417. void PNGAPI
  198418. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  198419. png_size_t png_struct_size)
  198420. {
  198421. png_structp png_ptr=*ptr_ptr;
  198422. #ifdef PNG_SETJMP_SUPPORTED
  198423. jmp_buf tmp_jmp; /* to save current jump buffer */
  198424. #endif
  198425. int i = 0;
  198426. if (png_ptr == NULL)
  198427. return;
  198428. do
  198429. {
  198430. if (user_png_ver[i] != png_libpng_ver[i])
  198431. {
  198432. #ifdef PNG_LEGACY_SUPPORTED
  198433. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  198434. #else
  198435. png_ptr->warning_fn=NULL;
  198436. png_warning(png_ptr,
  198437. "Application uses deprecated png_write_init() and should be recompiled.");
  198438. break;
  198439. #endif
  198440. }
  198441. } while (png_libpng_ver[i++]);
  198442. png_debug(1, "in png_write_init_3\n");
  198443. #ifdef PNG_SETJMP_SUPPORTED
  198444. /* save jump buffer and error functions */
  198445. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  198446. #endif
  198447. if (png_sizeof(png_struct) > png_struct_size)
  198448. {
  198449. png_destroy_struct(png_ptr);
  198450. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  198451. *ptr_ptr = png_ptr;
  198452. }
  198453. /* reset all variables to 0 */
  198454. png_memset(png_ptr, 0, png_sizeof (png_struct));
  198455. /* added at libpng-1.2.6 */
  198456. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  198457. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  198458. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  198459. #endif
  198460. #ifdef PNG_SETJMP_SUPPORTED
  198461. /* restore jump buffer */
  198462. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  198463. #endif
  198464. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  198465. png_flush_ptr_NULL);
  198466. /* initialize zbuf - compression buffer */
  198467. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  198468. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  198469. (png_uint_32)png_ptr->zbuf_size);
  198470. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198471. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  198472. 1, png_doublep_NULL, png_doublep_NULL);
  198473. #endif
  198474. }
  198475. /* Write a few rows of image data. If the image is interlaced,
  198476. * either you will have to write the 7 sub images, or, if you
  198477. * have called png_set_interlace_handling(), you will have to
  198478. * "write" the image seven times.
  198479. */
  198480. void PNGAPI
  198481. png_write_rows(png_structp png_ptr, png_bytepp row,
  198482. png_uint_32 num_rows)
  198483. {
  198484. png_uint_32 i; /* row counter */
  198485. png_bytepp rp; /* row pointer */
  198486. png_debug(1, "in png_write_rows\n");
  198487. if (png_ptr == NULL)
  198488. return;
  198489. /* loop through the rows */
  198490. for (i = 0, rp = row; i < num_rows; i++, rp++)
  198491. {
  198492. png_write_row(png_ptr, *rp);
  198493. }
  198494. }
  198495. /* Write the image. You only need to call this function once, even
  198496. * if you are writing an interlaced image.
  198497. */
  198498. void PNGAPI
  198499. png_write_image(png_structp png_ptr, png_bytepp image)
  198500. {
  198501. png_uint_32 i; /* row index */
  198502. int pass, num_pass; /* pass variables */
  198503. png_bytepp rp; /* points to current row */
  198504. if (png_ptr == NULL)
  198505. return;
  198506. png_debug(1, "in png_write_image\n");
  198507. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198508. /* intialize interlace handling. If image is not interlaced,
  198509. this will set pass to 1 */
  198510. num_pass = png_set_interlace_handling(png_ptr);
  198511. #else
  198512. num_pass = 1;
  198513. #endif
  198514. /* loop through passes */
  198515. for (pass = 0; pass < num_pass; pass++)
  198516. {
  198517. /* loop through image */
  198518. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  198519. {
  198520. png_write_row(png_ptr, *rp);
  198521. }
  198522. }
  198523. }
  198524. /* called by user to write a row of image data */
  198525. void PNGAPI
  198526. png_write_row(png_structp png_ptr, png_bytep row)
  198527. {
  198528. if (png_ptr == NULL)
  198529. return;
  198530. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  198531. png_ptr->row_number, png_ptr->pass);
  198532. /* initialize transformations and other stuff if first time */
  198533. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  198534. {
  198535. /* make sure we wrote the header info */
  198536. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  198537. png_error(png_ptr,
  198538. "png_write_info was never called before png_write_row.");
  198539. /* check for transforms that have been set but were defined out */
  198540. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  198541. if (png_ptr->transformations & PNG_INVERT_MONO)
  198542. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  198543. #endif
  198544. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  198545. if (png_ptr->transformations & PNG_FILLER)
  198546. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  198547. #endif
  198548. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  198549. if (png_ptr->transformations & PNG_PACKSWAP)
  198550. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  198551. #endif
  198552. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  198553. if (png_ptr->transformations & PNG_PACK)
  198554. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  198555. #endif
  198556. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  198557. if (png_ptr->transformations & PNG_SHIFT)
  198558. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  198559. #endif
  198560. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  198561. if (png_ptr->transformations & PNG_BGR)
  198562. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  198563. #endif
  198564. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  198565. if (png_ptr->transformations & PNG_SWAP_BYTES)
  198566. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  198567. #endif
  198568. png_write_start_row(png_ptr);
  198569. }
  198570. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198571. /* if interlaced and not interested in row, return */
  198572. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  198573. {
  198574. switch (png_ptr->pass)
  198575. {
  198576. case 0:
  198577. if (png_ptr->row_number & 0x07)
  198578. {
  198579. png_write_finish_row(png_ptr);
  198580. return;
  198581. }
  198582. break;
  198583. case 1:
  198584. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  198585. {
  198586. png_write_finish_row(png_ptr);
  198587. return;
  198588. }
  198589. break;
  198590. case 2:
  198591. if ((png_ptr->row_number & 0x07) != 4)
  198592. {
  198593. png_write_finish_row(png_ptr);
  198594. return;
  198595. }
  198596. break;
  198597. case 3:
  198598. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  198599. {
  198600. png_write_finish_row(png_ptr);
  198601. return;
  198602. }
  198603. break;
  198604. case 4:
  198605. if ((png_ptr->row_number & 0x03) != 2)
  198606. {
  198607. png_write_finish_row(png_ptr);
  198608. return;
  198609. }
  198610. break;
  198611. case 5:
  198612. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  198613. {
  198614. png_write_finish_row(png_ptr);
  198615. return;
  198616. }
  198617. break;
  198618. case 6:
  198619. if (!(png_ptr->row_number & 0x01))
  198620. {
  198621. png_write_finish_row(png_ptr);
  198622. return;
  198623. }
  198624. break;
  198625. }
  198626. }
  198627. #endif
  198628. /* set up row info for transformations */
  198629. png_ptr->row_info.color_type = png_ptr->color_type;
  198630. png_ptr->row_info.width = png_ptr->usr_width;
  198631. png_ptr->row_info.channels = png_ptr->usr_channels;
  198632. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  198633. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  198634. png_ptr->row_info.channels);
  198635. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  198636. png_ptr->row_info.width);
  198637. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  198638. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  198639. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  198640. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  198641. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  198642. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  198643. /* Copy user's row into buffer, leaving room for filter byte. */
  198644. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  198645. png_ptr->row_info.rowbytes);
  198646. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198647. /* handle interlacing */
  198648. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  198649. (png_ptr->transformations & PNG_INTERLACE))
  198650. {
  198651. png_do_write_interlace(&(png_ptr->row_info),
  198652. png_ptr->row_buf + 1, png_ptr->pass);
  198653. /* this should always get caught above, but still ... */
  198654. if (!(png_ptr->row_info.width))
  198655. {
  198656. png_write_finish_row(png_ptr);
  198657. return;
  198658. }
  198659. }
  198660. #endif
  198661. /* handle other transformations */
  198662. if (png_ptr->transformations)
  198663. png_do_write_transformations(png_ptr);
  198664. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198665. /* Write filter_method 64 (intrapixel differencing) only if
  198666. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  198667. * 2. Libpng did not write a PNG signature (this filter_method is only
  198668. * used in PNG datastreams that are embedded in MNG datastreams) and
  198669. * 3. The application called png_permit_mng_features with a mask that
  198670. * included PNG_FLAG_MNG_FILTER_64 and
  198671. * 4. The filter_method is 64 and
  198672. * 5. The color_type is RGB or RGBA
  198673. */
  198674. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  198675. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  198676. {
  198677. /* Intrapixel differencing */
  198678. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  198679. }
  198680. #endif
  198681. /* Find a filter if necessary, filter the row and write it out. */
  198682. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  198683. if (png_ptr->write_row_fn != NULL)
  198684. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  198685. }
  198686. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198687. /* Set the automatic flush interval or 0 to turn flushing off */
  198688. void PNGAPI
  198689. png_set_flush(png_structp png_ptr, int nrows)
  198690. {
  198691. png_debug(1, "in png_set_flush\n");
  198692. if (png_ptr == NULL)
  198693. return;
  198694. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  198695. }
  198696. /* flush the current output buffers now */
  198697. void PNGAPI
  198698. png_write_flush(png_structp png_ptr)
  198699. {
  198700. int wrote_IDAT;
  198701. png_debug(1, "in png_write_flush\n");
  198702. if (png_ptr == NULL)
  198703. return;
  198704. /* We have already written out all of the data */
  198705. if (png_ptr->row_number >= png_ptr->num_rows)
  198706. return;
  198707. do
  198708. {
  198709. int ret;
  198710. /* compress the data */
  198711. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  198712. wrote_IDAT = 0;
  198713. /* check for compression errors */
  198714. if (ret != Z_OK)
  198715. {
  198716. if (png_ptr->zstream.msg != NULL)
  198717. png_error(png_ptr, png_ptr->zstream.msg);
  198718. else
  198719. png_error(png_ptr, "zlib error");
  198720. }
  198721. if (!(png_ptr->zstream.avail_out))
  198722. {
  198723. /* write the IDAT and reset the zlib output buffer */
  198724. png_write_IDAT(png_ptr, png_ptr->zbuf,
  198725. png_ptr->zbuf_size);
  198726. png_ptr->zstream.next_out = png_ptr->zbuf;
  198727. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  198728. wrote_IDAT = 1;
  198729. }
  198730. } while(wrote_IDAT == 1);
  198731. /* If there is any data left to be output, write it into a new IDAT */
  198732. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  198733. {
  198734. /* write the IDAT and reset the zlib output buffer */
  198735. png_write_IDAT(png_ptr, png_ptr->zbuf,
  198736. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  198737. png_ptr->zstream.next_out = png_ptr->zbuf;
  198738. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  198739. }
  198740. png_ptr->flush_rows = 0;
  198741. png_flush(png_ptr);
  198742. }
  198743. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  198744. /* free all memory used by the write */
  198745. void PNGAPI
  198746. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  198747. {
  198748. png_structp png_ptr = NULL;
  198749. png_infop info_ptr = NULL;
  198750. #ifdef PNG_USER_MEM_SUPPORTED
  198751. png_free_ptr free_fn = NULL;
  198752. png_voidp mem_ptr = NULL;
  198753. #endif
  198754. png_debug(1, "in png_destroy_write_struct\n");
  198755. if (png_ptr_ptr != NULL)
  198756. {
  198757. png_ptr = *png_ptr_ptr;
  198758. #ifdef PNG_USER_MEM_SUPPORTED
  198759. free_fn = png_ptr->free_fn;
  198760. mem_ptr = png_ptr->mem_ptr;
  198761. #endif
  198762. }
  198763. if (info_ptr_ptr != NULL)
  198764. info_ptr = *info_ptr_ptr;
  198765. if (info_ptr != NULL)
  198766. {
  198767. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  198768. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  198769. if (png_ptr->num_chunk_list)
  198770. {
  198771. png_free(png_ptr, png_ptr->chunk_list);
  198772. png_ptr->chunk_list=NULL;
  198773. png_ptr->num_chunk_list=0;
  198774. }
  198775. #endif
  198776. #ifdef PNG_USER_MEM_SUPPORTED
  198777. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  198778. (png_voidp)mem_ptr);
  198779. #else
  198780. png_destroy_struct((png_voidp)info_ptr);
  198781. #endif
  198782. *info_ptr_ptr = NULL;
  198783. }
  198784. if (png_ptr != NULL)
  198785. {
  198786. png_write_destroy(png_ptr);
  198787. #ifdef PNG_USER_MEM_SUPPORTED
  198788. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  198789. (png_voidp)mem_ptr);
  198790. #else
  198791. png_destroy_struct((png_voidp)png_ptr);
  198792. #endif
  198793. *png_ptr_ptr = NULL;
  198794. }
  198795. }
  198796. /* Free any memory used in png_ptr struct (old method) */
  198797. void /* PRIVATE */
  198798. png_write_destroy(png_structp png_ptr)
  198799. {
  198800. #ifdef PNG_SETJMP_SUPPORTED
  198801. jmp_buf tmp_jmp; /* save jump buffer */
  198802. #endif
  198803. png_error_ptr error_fn;
  198804. png_error_ptr warning_fn;
  198805. png_voidp error_ptr;
  198806. #ifdef PNG_USER_MEM_SUPPORTED
  198807. png_free_ptr free_fn;
  198808. #endif
  198809. png_debug(1, "in png_write_destroy\n");
  198810. /* free any memory zlib uses */
  198811. deflateEnd(&png_ptr->zstream);
  198812. /* free our memory. png_free checks NULL for us. */
  198813. png_free(png_ptr, png_ptr->zbuf);
  198814. png_free(png_ptr, png_ptr->row_buf);
  198815. png_free(png_ptr, png_ptr->prev_row);
  198816. png_free(png_ptr, png_ptr->sub_row);
  198817. png_free(png_ptr, png_ptr->up_row);
  198818. png_free(png_ptr, png_ptr->avg_row);
  198819. png_free(png_ptr, png_ptr->paeth_row);
  198820. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  198821. png_free(png_ptr, png_ptr->time_buffer);
  198822. #endif
  198823. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198824. png_free(png_ptr, png_ptr->prev_filters);
  198825. png_free(png_ptr, png_ptr->filter_weights);
  198826. png_free(png_ptr, png_ptr->inv_filter_weights);
  198827. png_free(png_ptr, png_ptr->filter_costs);
  198828. png_free(png_ptr, png_ptr->inv_filter_costs);
  198829. #endif
  198830. #ifdef PNG_SETJMP_SUPPORTED
  198831. /* reset structure */
  198832. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  198833. #endif
  198834. error_fn = png_ptr->error_fn;
  198835. warning_fn = png_ptr->warning_fn;
  198836. error_ptr = png_ptr->error_ptr;
  198837. #ifdef PNG_USER_MEM_SUPPORTED
  198838. free_fn = png_ptr->free_fn;
  198839. #endif
  198840. png_memset(png_ptr, 0, png_sizeof (png_struct));
  198841. png_ptr->error_fn = error_fn;
  198842. png_ptr->warning_fn = warning_fn;
  198843. png_ptr->error_ptr = error_ptr;
  198844. #ifdef PNG_USER_MEM_SUPPORTED
  198845. png_ptr->free_fn = free_fn;
  198846. #endif
  198847. #ifdef PNG_SETJMP_SUPPORTED
  198848. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  198849. #endif
  198850. }
  198851. /* Allow the application to select one or more row filters to use. */
  198852. void PNGAPI
  198853. png_set_filter(png_structp png_ptr, int method, int filters)
  198854. {
  198855. png_debug(1, "in png_set_filter\n");
  198856. if (png_ptr == NULL)
  198857. return;
  198858. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198859. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  198860. (method == PNG_INTRAPIXEL_DIFFERENCING))
  198861. method = PNG_FILTER_TYPE_BASE;
  198862. #endif
  198863. if (method == PNG_FILTER_TYPE_BASE)
  198864. {
  198865. switch (filters & (PNG_ALL_FILTERS | 0x07))
  198866. {
  198867. #ifndef PNG_NO_WRITE_FILTER
  198868. case 5:
  198869. case 6:
  198870. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  198871. #endif /* PNG_NO_WRITE_FILTER */
  198872. case PNG_FILTER_VALUE_NONE:
  198873. png_ptr->do_filter=PNG_FILTER_NONE; break;
  198874. #ifndef PNG_NO_WRITE_FILTER
  198875. case PNG_FILTER_VALUE_SUB:
  198876. png_ptr->do_filter=PNG_FILTER_SUB; break;
  198877. case PNG_FILTER_VALUE_UP:
  198878. png_ptr->do_filter=PNG_FILTER_UP; break;
  198879. case PNG_FILTER_VALUE_AVG:
  198880. png_ptr->do_filter=PNG_FILTER_AVG; break;
  198881. case PNG_FILTER_VALUE_PAETH:
  198882. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  198883. default: png_ptr->do_filter = (png_byte)filters; break;
  198884. #else
  198885. default: png_warning(png_ptr, "Unknown row filter for method 0");
  198886. #endif /* PNG_NO_WRITE_FILTER */
  198887. }
  198888. /* If we have allocated the row_buf, this means we have already started
  198889. * with the image and we should have allocated all of the filter buffers
  198890. * that have been selected. If prev_row isn't already allocated, then
  198891. * it is too late to start using the filters that need it, since we
  198892. * will be missing the data in the previous row. If an application
  198893. * wants to start and stop using particular filters during compression,
  198894. * it should start out with all of the filters, and then add and
  198895. * remove them after the start of compression.
  198896. */
  198897. if (png_ptr->row_buf != NULL)
  198898. {
  198899. #ifndef PNG_NO_WRITE_FILTER
  198900. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  198901. {
  198902. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  198903. (png_ptr->rowbytes + 1));
  198904. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  198905. }
  198906. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  198907. {
  198908. if (png_ptr->prev_row == NULL)
  198909. {
  198910. png_warning(png_ptr, "Can't add Up filter after starting");
  198911. png_ptr->do_filter &= ~PNG_FILTER_UP;
  198912. }
  198913. else
  198914. {
  198915. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  198916. (png_ptr->rowbytes + 1));
  198917. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  198918. }
  198919. }
  198920. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  198921. {
  198922. if (png_ptr->prev_row == NULL)
  198923. {
  198924. png_warning(png_ptr, "Can't add Average filter after starting");
  198925. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  198926. }
  198927. else
  198928. {
  198929. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  198930. (png_ptr->rowbytes + 1));
  198931. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  198932. }
  198933. }
  198934. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  198935. png_ptr->paeth_row == NULL)
  198936. {
  198937. if (png_ptr->prev_row == NULL)
  198938. {
  198939. png_warning(png_ptr, "Can't add Paeth filter after starting");
  198940. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  198941. }
  198942. else
  198943. {
  198944. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  198945. (png_ptr->rowbytes + 1));
  198946. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  198947. }
  198948. }
  198949. if (png_ptr->do_filter == PNG_NO_FILTERS)
  198950. #endif /* PNG_NO_WRITE_FILTER */
  198951. png_ptr->do_filter = PNG_FILTER_NONE;
  198952. }
  198953. }
  198954. else
  198955. png_error(png_ptr, "Unknown custom filter method");
  198956. }
  198957. /* This allows us to influence the way in which libpng chooses the "best"
  198958. * filter for the current scanline. While the "minimum-sum-of-absolute-
  198959. * differences metric is relatively fast and effective, there is some
  198960. * question as to whether it can be improved upon by trying to keep the
  198961. * filtered data going to zlib more consistent, hopefully resulting in
  198962. * better compression.
  198963. */
  198964. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  198965. void PNGAPI
  198966. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  198967. int num_weights, png_doublep filter_weights,
  198968. png_doublep filter_costs)
  198969. {
  198970. int i;
  198971. png_debug(1, "in png_set_filter_heuristics\n");
  198972. if (png_ptr == NULL)
  198973. return;
  198974. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  198975. {
  198976. png_warning(png_ptr, "Unknown filter heuristic method");
  198977. return;
  198978. }
  198979. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  198980. {
  198981. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  198982. }
  198983. if (num_weights < 0 || filter_weights == NULL ||
  198984. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  198985. {
  198986. num_weights = 0;
  198987. }
  198988. png_ptr->num_prev_filters = (png_byte)num_weights;
  198989. png_ptr->heuristic_method = (png_byte)heuristic_method;
  198990. if (num_weights > 0)
  198991. {
  198992. if (png_ptr->prev_filters == NULL)
  198993. {
  198994. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  198995. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  198996. /* To make sure that the weighting starts out fairly */
  198997. for (i = 0; i < num_weights; i++)
  198998. {
  198999. png_ptr->prev_filters[i] = 255;
  199000. }
  199001. }
  199002. if (png_ptr->filter_weights == NULL)
  199003. {
  199004. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  199005. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  199006. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  199007. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  199008. for (i = 0; i < num_weights; i++)
  199009. {
  199010. png_ptr->inv_filter_weights[i] =
  199011. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  199012. }
  199013. }
  199014. for (i = 0; i < num_weights; i++)
  199015. {
  199016. if (filter_weights[i] < 0.0)
  199017. {
  199018. png_ptr->inv_filter_weights[i] =
  199019. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  199020. }
  199021. else
  199022. {
  199023. png_ptr->inv_filter_weights[i] =
  199024. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  199025. png_ptr->filter_weights[i] =
  199026. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  199027. }
  199028. }
  199029. }
  199030. /* If, in the future, there are other filter methods, this would
  199031. * need to be based on png_ptr->filter.
  199032. */
  199033. if (png_ptr->filter_costs == NULL)
  199034. {
  199035. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  199036. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  199037. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  199038. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  199039. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  199040. {
  199041. png_ptr->inv_filter_costs[i] =
  199042. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  199043. }
  199044. }
  199045. /* Here is where we set the relative costs of the different filters. We
  199046. * should take the desired compression level into account when setting
  199047. * the costs, so that Paeth, for instance, has a high relative cost at low
  199048. * compression levels, while it has a lower relative cost at higher
  199049. * compression settings. The filter types are in order of increasing
  199050. * relative cost, so it would be possible to do this with an algorithm.
  199051. */
  199052. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  199053. {
  199054. if (filter_costs == NULL || filter_costs[i] < 0.0)
  199055. {
  199056. png_ptr->inv_filter_costs[i] =
  199057. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  199058. }
  199059. else if (filter_costs[i] >= 1.0)
  199060. {
  199061. png_ptr->inv_filter_costs[i] =
  199062. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  199063. png_ptr->filter_costs[i] =
  199064. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  199065. }
  199066. }
  199067. }
  199068. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  199069. void PNGAPI
  199070. png_set_compression_level(png_structp png_ptr, int level)
  199071. {
  199072. png_debug(1, "in png_set_compression_level\n");
  199073. if (png_ptr == NULL)
  199074. return;
  199075. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  199076. png_ptr->zlib_level = level;
  199077. }
  199078. void PNGAPI
  199079. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  199080. {
  199081. png_debug(1, "in png_set_compression_mem_level\n");
  199082. if (png_ptr == NULL)
  199083. return;
  199084. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  199085. png_ptr->zlib_mem_level = mem_level;
  199086. }
  199087. void PNGAPI
  199088. png_set_compression_strategy(png_structp png_ptr, int strategy)
  199089. {
  199090. png_debug(1, "in png_set_compression_strategy\n");
  199091. if (png_ptr == NULL)
  199092. return;
  199093. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  199094. png_ptr->zlib_strategy = strategy;
  199095. }
  199096. void PNGAPI
  199097. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  199098. {
  199099. if (png_ptr == NULL)
  199100. return;
  199101. if (window_bits > 15)
  199102. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  199103. else if (window_bits < 8)
  199104. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  199105. #ifndef WBITS_8_OK
  199106. /* avoid libpng bug with 256-byte windows */
  199107. if (window_bits == 8)
  199108. {
  199109. png_warning(png_ptr, "Compression window is being reset to 512");
  199110. window_bits=9;
  199111. }
  199112. #endif
  199113. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  199114. png_ptr->zlib_window_bits = window_bits;
  199115. }
  199116. void PNGAPI
  199117. png_set_compression_method(png_structp png_ptr, int method)
  199118. {
  199119. png_debug(1, "in png_set_compression_method\n");
  199120. if (png_ptr == NULL)
  199121. return;
  199122. if (method != 8)
  199123. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  199124. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  199125. png_ptr->zlib_method = method;
  199126. }
  199127. void PNGAPI
  199128. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  199129. {
  199130. if (png_ptr == NULL)
  199131. return;
  199132. png_ptr->write_row_fn = write_row_fn;
  199133. }
  199134. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  199135. void PNGAPI
  199136. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  199137. write_user_transform_fn)
  199138. {
  199139. png_debug(1, "in png_set_write_user_transform_fn\n");
  199140. if (png_ptr == NULL)
  199141. return;
  199142. png_ptr->transformations |= PNG_USER_TRANSFORM;
  199143. png_ptr->write_user_transform_fn = write_user_transform_fn;
  199144. }
  199145. #endif
  199146. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  199147. void PNGAPI
  199148. png_write_png(png_structp png_ptr, png_infop info_ptr,
  199149. int transforms, voidp params)
  199150. {
  199151. if (png_ptr == NULL || info_ptr == NULL)
  199152. return;
  199153. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  199154. /* invert the alpha channel from opacity to transparency */
  199155. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  199156. png_set_invert_alpha(png_ptr);
  199157. #endif
  199158. /* Write the file header information. */
  199159. png_write_info(png_ptr, info_ptr);
  199160. /* ------ these transformations don't touch the info structure ------- */
  199161. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  199162. /* invert monochrome pixels */
  199163. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  199164. png_set_invert_mono(png_ptr);
  199165. #endif
  199166. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  199167. /* Shift the pixels up to a legal bit depth and fill in
  199168. * as appropriate to correctly scale the image.
  199169. */
  199170. if ((transforms & PNG_TRANSFORM_SHIFT)
  199171. && (info_ptr->valid & PNG_INFO_sBIT))
  199172. png_set_shift(png_ptr, &info_ptr->sig_bit);
  199173. #endif
  199174. #if defined(PNG_WRITE_PACK_SUPPORTED)
  199175. /* pack pixels into bytes */
  199176. if (transforms & PNG_TRANSFORM_PACKING)
  199177. png_set_packing(png_ptr);
  199178. #endif
  199179. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  199180. /* swap location of alpha bytes from ARGB to RGBA */
  199181. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  199182. png_set_swap_alpha(png_ptr);
  199183. #endif
  199184. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  199185. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  199186. * RGB (4 channels -> 3 channels). The second parameter is not used.
  199187. */
  199188. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  199189. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  199190. #endif
  199191. #if defined(PNG_WRITE_BGR_SUPPORTED)
  199192. /* flip BGR pixels to RGB */
  199193. if (transforms & PNG_TRANSFORM_BGR)
  199194. png_set_bgr(png_ptr);
  199195. #endif
  199196. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  199197. /* swap bytes of 16-bit files to most significant byte first */
  199198. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  199199. png_set_swap(png_ptr);
  199200. #endif
  199201. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  199202. /* swap bits of 1, 2, 4 bit packed pixel formats */
  199203. if (transforms & PNG_TRANSFORM_PACKSWAP)
  199204. png_set_packswap(png_ptr);
  199205. #endif
  199206. /* ----------------------- end of transformations ------------------- */
  199207. /* write the bits */
  199208. if (info_ptr->valid & PNG_INFO_IDAT)
  199209. png_write_image(png_ptr, info_ptr->row_pointers);
  199210. /* It is REQUIRED to call this to finish writing the rest of the file */
  199211. png_write_end(png_ptr, info_ptr);
  199212. transforms = transforms; /* quiet compiler warnings */
  199213. params = params;
  199214. }
  199215. #endif
  199216. #endif /* PNG_WRITE_SUPPORTED */
  199217. /*** End of inlined file: pngwrite.c ***/
  199218. /*** Start of inlined file: pngwtran.c ***/
  199219. /* pngwtran.c - transforms the data in a row for PNG writers
  199220. *
  199221. * Last changed in libpng 1.2.9 April 14, 2006
  199222. * For conditions of distribution and use, see copyright notice in png.h
  199223. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  199224. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  199225. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  199226. */
  199227. #define PNG_INTERNAL
  199228. #ifdef PNG_WRITE_SUPPORTED
  199229. /* Transform the data according to the user's wishes. The order of
  199230. * transformations is significant.
  199231. */
  199232. void /* PRIVATE */
  199233. png_do_write_transformations(png_structp png_ptr)
  199234. {
  199235. png_debug(1, "in png_do_write_transformations\n");
  199236. if (png_ptr == NULL)
  199237. return;
  199238. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  199239. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  199240. if(png_ptr->write_user_transform_fn != NULL)
  199241. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  199242. (png_ptr, /* png_ptr */
  199243. &(png_ptr->row_info), /* row_info: */
  199244. /* png_uint_32 width; width of row */
  199245. /* png_uint_32 rowbytes; number of bytes in row */
  199246. /* png_byte color_type; color type of pixels */
  199247. /* png_byte bit_depth; bit depth of samples */
  199248. /* png_byte channels; number of channels (1-4) */
  199249. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  199250. png_ptr->row_buf + 1); /* start of pixel data for row */
  199251. #endif
  199252. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  199253. if (png_ptr->transformations & PNG_FILLER)
  199254. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  199255. png_ptr->flags);
  199256. #endif
  199257. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  199258. if (png_ptr->transformations & PNG_PACKSWAP)
  199259. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199260. #endif
  199261. #if defined(PNG_WRITE_PACK_SUPPORTED)
  199262. if (png_ptr->transformations & PNG_PACK)
  199263. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  199264. (png_uint_32)png_ptr->bit_depth);
  199265. #endif
  199266. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  199267. if (png_ptr->transformations & PNG_SWAP_BYTES)
  199268. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199269. #endif
  199270. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  199271. if (png_ptr->transformations & PNG_SHIFT)
  199272. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  199273. &(png_ptr->shift));
  199274. #endif
  199275. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  199276. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  199277. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199278. #endif
  199279. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  199280. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  199281. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199282. #endif
  199283. #if defined(PNG_WRITE_BGR_SUPPORTED)
  199284. if (png_ptr->transformations & PNG_BGR)
  199285. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199286. #endif
  199287. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  199288. if (png_ptr->transformations & PNG_INVERT_MONO)
  199289. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199290. #endif
  199291. }
  199292. #if defined(PNG_WRITE_PACK_SUPPORTED)
  199293. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  199294. * row_info bit depth should be 8 (one pixel per byte). The channels
  199295. * should be 1 (this only happens on grayscale and paletted images).
  199296. */
  199297. void /* PRIVATE */
  199298. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  199299. {
  199300. png_debug(1, "in png_do_pack\n");
  199301. if (row_info->bit_depth == 8 &&
  199302. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199303. row != NULL && row_info != NULL &&
  199304. #endif
  199305. row_info->channels == 1)
  199306. {
  199307. switch ((int)bit_depth)
  199308. {
  199309. case 1:
  199310. {
  199311. png_bytep sp, dp;
  199312. int mask, v;
  199313. png_uint_32 i;
  199314. png_uint_32 row_width = row_info->width;
  199315. sp = row;
  199316. dp = row;
  199317. mask = 0x80;
  199318. v = 0;
  199319. for (i = 0; i < row_width; i++)
  199320. {
  199321. if (*sp != 0)
  199322. v |= mask;
  199323. sp++;
  199324. if (mask > 1)
  199325. mask >>= 1;
  199326. else
  199327. {
  199328. mask = 0x80;
  199329. *dp = (png_byte)v;
  199330. dp++;
  199331. v = 0;
  199332. }
  199333. }
  199334. if (mask != 0x80)
  199335. *dp = (png_byte)v;
  199336. break;
  199337. }
  199338. case 2:
  199339. {
  199340. png_bytep sp, dp;
  199341. int shift, v;
  199342. png_uint_32 i;
  199343. png_uint_32 row_width = row_info->width;
  199344. sp = row;
  199345. dp = row;
  199346. shift = 6;
  199347. v = 0;
  199348. for (i = 0; i < row_width; i++)
  199349. {
  199350. png_byte value;
  199351. value = (png_byte)(*sp & 0x03);
  199352. v |= (value << shift);
  199353. if (shift == 0)
  199354. {
  199355. shift = 6;
  199356. *dp = (png_byte)v;
  199357. dp++;
  199358. v = 0;
  199359. }
  199360. else
  199361. shift -= 2;
  199362. sp++;
  199363. }
  199364. if (shift != 6)
  199365. *dp = (png_byte)v;
  199366. break;
  199367. }
  199368. case 4:
  199369. {
  199370. png_bytep sp, dp;
  199371. int shift, v;
  199372. png_uint_32 i;
  199373. png_uint_32 row_width = row_info->width;
  199374. sp = row;
  199375. dp = row;
  199376. shift = 4;
  199377. v = 0;
  199378. for (i = 0; i < row_width; i++)
  199379. {
  199380. png_byte value;
  199381. value = (png_byte)(*sp & 0x0f);
  199382. v |= (value << shift);
  199383. if (shift == 0)
  199384. {
  199385. shift = 4;
  199386. *dp = (png_byte)v;
  199387. dp++;
  199388. v = 0;
  199389. }
  199390. else
  199391. shift -= 4;
  199392. sp++;
  199393. }
  199394. if (shift != 4)
  199395. *dp = (png_byte)v;
  199396. break;
  199397. }
  199398. }
  199399. row_info->bit_depth = (png_byte)bit_depth;
  199400. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  199401. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  199402. row_info->width);
  199403. }
  199404. }
  199405. #endif
  199406. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  199407. /* Shift pixel values to take advantage of whole range. Pass the
  199408. * true number of bits in bit_depth. The row should be packed
  199409. * according to row_info->bit_depth. Thus, if you had a row of
  199410. * bit depth 4, but the pixels only had values from 0 to 7, you
  199411. * would pass 3 as bit_depth, and this routine would translate the
  199412. * data to 0 to 15.
  199413. */
  199414. void /* PRIVATE */
  199415. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  199416. {
  199417. png_debug(1, "in png_do_shift\n");
  199418. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199419. if (row != NULL && row_info != NULL &&
  199420. #else
  199421. if (
  199422. #endif
  199423. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  199424. {
  199425. int shift_start[4], shift_dec[4];
  199426. int channels = 0;
  199427. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  199428. {
  199429. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  199430. shift_dec[channels] = bit_depth->red;
  199431. channels++;
  199432. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  199433. shift_dec[channels] = bit_depth->green;
  199434. channels++;
  199435. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  199436. shift_dec[channels] = bit_depth->blue;
  199437. channels++;
  199438. }
  199439. else
  199440. {
  199441. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  199442. shift_dec[channels] = bit_depth->gray;
  199443. channels++;
  199444. }
  199445. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  199446. {
  199447. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  199448. shift_dec[channels] = bit_depth->alpha;
  199449. channels++;
  199450. }
  199451. /* with low row depths, could only be grayscale, so one channel */
  199452. if (row_info->bit_depth < 8)
  199453. {
  199454. png_bytep bp = row;
  199455. png_uint_32 i;
  199456. png_byte mask;
  199457. png_uint_32 row_bytes = row_info->rowbytes;
  199458. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  199459. mask = 0x55;
  199460. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  199461. mask = 0x11;
  199462. else
  199463. mask = 0xff;
  199464. for (i = 0; i < row_bytes; i++, bp++)
  199465. {
  199466. png_uint_16 v;
  199467. int j;
  199468. v = *bp;
  199469. *bp = 0;
  199470. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  199471. {
  199472. if (j > 0)
  199473. *bp |= (png_byte)((v << j) & 0xff);
  199474. else
  199475. *bp |= (png_byte)((v >> (-j)) & mask);
  199476. }
  199477. }
  199478. }
  199479. else if (row_info->bit_depth == 8)
  199480. {
  199481. png_bytep bp = row;
  199482. png_uint_32 i;
  199483. png_uint_32 istop = channels * row_info->width;
  199484. for (i = 0; i < istop; i++, bp++)
  199485. {
  199486. png_uint_16 v;
  199487. int j;
  199488. int c = (int)(i%channels);
  199489. v = *bp;
  199490. *bp = 0;
  199491. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  199492. {
  199493. if (j > 0)
  199494. *bp |= (png_byte)((v << j) & 0xff);
  199495. else
  199496. *bp |= (png_byte)((v >> (-j)) & 0xff);
  199497. }
  199498. }
  199499. }
  199500. else
  199501. {
  199502. png_bytep bp;
  199503. png_uint_32 i;
  199504. png_uint_32 istop = channels * row_info->width;
  199505. for (bp = row, i = 0; i < istop; i++)
  199506. {
  199507. int c = (int)(i%channels);
  199508. png_uint_16 value, v;
  199509. int j;
  199510. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  199511. value = 0;
  199512. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  199513. {
  199514. if (j > 0)
  199515. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  199516. else
  199517. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  199518. }
  199519. *bp++ = (png_byte)(value >> 8);
  199520. *bp++ = (png_byte)(value & 0xff);
  199521. }
  199522. }
  199523. }
  199524. }
  199525. #endif
  199526. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  199527. void /* PRIVATE */
  199528. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  199529. {
  199530. png_debug(1, "in png_do_write_swap_alpha\n");
  199531. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199532. if (row != NULL && row_info != NULL)
  199533. #endif
  199534. {
  199535. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  199536. {
  199537. /* This converts from ARGB to RGBA */
  199538. if (row_info->bit_depth == 8)
  199539. {
  199540. png_bytep sp, dp;
  199541. png_uint_32 i;
  199542. png_uint_32 row_width = row_info->width;
  199543. for (i = 0, sp = dp = row; i < row_width; i++)
  199544. {
  199545. png_byte save = *(sp++);
  199546. *(dp++) = *(sp++);
  199547. *(dp++) = *(sp++);
  199548. *(dp++) = *(sp++);
  199549. *(dp++) = save;
  199550. }
  199551. }
  199552. /* This converts from AARRGGBB to RRGGBBAA */
  199553. else
  199554. {
  199555. png_bytep sp, dp;
  199556. png_uint_32 i;
  199557. png_uint_32 row_width = row_info->width;
  199558. for (i = 0, sp = dp = row; i < row_width; i++)
  199559. {
  199560. png_byte save[2];
  199561. save[0] = *(sp++);
  199562. save[1] = *(sp++);
  199563. *(dp++) = *(sp++);
  199564. *(dp++) = *(sp++);
  199565. *(dp++) = *(sp++);
  199566. *(dp++) = *(sp++);
  199567. *(dp++) = *(sp++);
  199568. *(dp++) = *(sp++);
  199569. *(dp++) = save[0];
  199570. *(dp++) = save[1];
  199571. }
  199572. }
  199573. }
  199574. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  199575. {
  199576. /* This converts from AG to GA */
  199577. if (row_info->bit_depth == 8)
  199578. {
  199579. png_bytep sp, dp;
  199580. png_uint_32 i;
  199581. png_uint_32 row_width = row_info->width;
  199582. for (i = 0, sp = dp = row; i < row_width; i++)
  199583. {
  199584. png_byte save = *(sp++);
  199585. *(dp++) = *(sp++);
  199586. *(dp++) = save;
  199587. }
  199588. }
  199589. /* This converts from AAGG to GGAA */
  199590. else
  199591. {
  199592. png_bytep sp, dp;
  199593. png_uint_32 i;
  199594. png_uint_32 row_width = row_info->width;
  199595. for (i = 0, sp = dp = row; i < row_width; i++)
  199596. {
  199597. png_byte save[2];
  199598. save[0] = *(sp++);
  199599. save[1] = *(sp++);
  199600. *(dp++) = *(sp++);
  199601. *(dp++) = *(sp++);
  199602. *(dp++) = save[0];
  199603. *(dp++) = save[1];
  199604. }
  199605. }
  199606. }
  199607. }
  199608. }
  199609. #endif
  199610. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  199611. void /* PRIVATE */
  199612. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  199613. {
  199614. png_debug(1, "in png_do_write_invert_alpha\n");
  199615. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199616. if (row != NULL && row_info != NULL)
  199617. #endif
  199618. {
  199619. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  199620. {
  199621. /* This inverts the alpha channel in RGBA */
  199622. if (row_info->bit_depth == 8)
  199623. {
  199624. png_bytep sp, dp;
  199625. png_uint_32 i;
  199626. png_uint_32 row_width = row_info->width;
  199627. for (i = 0, sp = dp = row; i < row_width; i++)
  199628. {
  199629. /* does nothing
  199630. *(dp++) = *(sp++);
  199631. *(dp++) = *(sp++);
  199632. *(dp++) = *(sp++);
  199633. */
  199634. sp+=3; dp = sp;
  199635. *(dp++) = (png_byte)(255 - *(sp++));
  199636. }
  199637. }
  199638. /* This inverts the alpha channel in RRGGBBAA */
  199639. else
  199640. {
  199641. png_bytep sp, dp;
  199642. png_uint_32 i;
  199643. png_uint_32 row_width = row_info->width;
  199644. for (i = 0, sp = dp = row; i < row_width; i++)
  199645. {
  199646. /* does nothing
  199647. *(dp++) = *(sp++);
  199648. *(dp++) = *(sp++);
  199649. *(dp++) = *(sp++);
  199650. *(dp++) = *(sp++);
  199651. *(dp++) = *(sp++);
  199652. *(dp++) = *(sp++);
  199653. */
  199654. sp+=6; dp = sp;
  199655. *(dp++) = (png_byte)(255 - *(sp++));
  199656. *(dp++) = (png_byte)(255 - *(sp++));
  199657. }
  199658. }
  199659. }
  199660. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  199661. {
  199662. /* This inverts the alpha channel in GA */
  199663. if (row_info->bit_depth == 8)
  199664. {
  199665. png_bytep sp, dp;
  199666. png_uint_32 i;
  199667. png_uint_32 row_width = row_info->width;
  199668. for (i = 0, sp = dp = row; i < row_width; i++)
  199669. {
  199670. *(dp++) = *(sp++);
  199671. *(dp++) = (png_byte)(255 - *(sp++));
  199672. }
  199673. }
  199674. /* This inverts the alpha channel in GGAA */
  199675. else
  199676. {
  199677. png_bytep sp, dp;
  199678. png_uint_32 i;
  199679. png_uint_32 row_width = row_info->width;
  199680. for (i = 0, sp = dp = row; i < row_width; i++)
  199681. {
  199682. /* does nothing
  199683. *(dp++) = *(sp++);
  199684. *(dp++) = *(sp++);
  199685. */
  199686. sp+=2; dp = sp;
  199687. *(dp++) = (png_byte)(255 - *(sp++));
  199688. *(dp++) = (png_byte)(255 - *(sp++));
  199689. }
  199690. }
  199691. }
  199692. }
  199693. }
  199694. #endif
  199695. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199696. /* undoes intrapixel differencing */
  199697. void /* PRIVATE */
  199698. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  199699. {
  199700. png_debug(1, "in png_do_write_intrapixel\n");
  199701. if (
  199702. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199703. row != NULL && row_info != NULL &&
  199704. #endif
  199705. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  199706. {
  199707. int bytes_per_pixel;
  199708. png_uint_32 row_width = row_info->width;
  199709. if (row_info->bit_depth == 8)
  199710. {
  199711. png_bytep rp;
  199712. png_uint_32 i;
  199713. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  199714. bytes_per_pixel = 3;
  199715. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  199716. bytes_per_pixel = 4;
  199717. else
  199718. return;
  199719. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  199720. {
  199721. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  199722. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  199723. }
  199724. }
  199725. else if (row_info->bit_depth == 16)
  199726. {
  199727. png_bytep rp;
  199728. png_uint_32 i;
  199729. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  199730. bytes_per_pixel = 6;
  199731. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  199732. bytes_per_pixel = 8;
  199733. else
  199734. return;
  199735. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  199736. {
  199737. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  199738. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  199739. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  199740. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  199741. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  199742. *(rp ) = (png_byte)((red >> 8) & 0xff);
  199743. *(rp+1) = (png_byte)(red & 0xff);
  199744. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  199745. *(rp+5) = (png_byte)(blue & 0xff);
  199746. }
  199747. }
  199748. }
  199749. }
  199750. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  199751. #endif /* PNG_WRITE_SUPPORTED */
  199752. /*** End of inlined file: pngwtran.c ***/
  199753. /*** Start of inlined file: pngwutil.c ***/
  199754. /* pngwutil.c - utilities to write a PNG file
  199755. *
  199756. * Last changed in libpng 1.2.20 Septhember 3, 2007
  199757. * For conditions of distribution and use, see copyright notice in png.h
  199758. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  199759. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  199760. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  199761. */
  199762. #define PNG_INTERNAL
  199763. #ifdef PNG_WRITE_SUPPORTED
  199764. /* Place a 32-bit number into a buffer in PNG byte order. We work
  199765. * with unsigned numbers for convenience, although one supported
  199766. * ancillary chunk uses signed (two's complement) numbers.
  199767. */
  199768. void PNGAPI
  199769. png_save_uint_32(png_bytep buf, png_uint_32 i)
  199770. {
  199771. buf[0] = (png_byte)((i >> 24) & 0xff);
  199772. buf[1] = (png_byte)((i >> 16) & 0xff);
  199773. buf[2] = (png_byte)((i >> 8) & 0xff);
  199774. buf[3] = (png_byte)(i & 0xff);
  199775. }
  199776. /* The png_save_int_32 function assumes integers are stored in two's
  199777. * complement format. If this isn't the case, then this routine needs to
  199778. * be modified to write data in two's complement format.
  199779. */
  199780. void PNGAPI
  199781. png_save_int_32(png_bytep buf, png_int_32 i)
  199782. {
  199783. buf[0] = (png_byte)((i >> 24) & 0xff);
  199784. buf[1] = (png_byte)((i >> 16) & 0xff);
  199785. buf[2] = (png_byte)((i >> 8) & 0xff);
  199786. buf[3] = (png_byte)(i & 0xff);
  199787. }
  199788. /* Place a 16-bit number into a buffer in PNG byte order.
  199789. * The parameter is declared unsigned int, not png_uint_16,
  199790. * just to avoid potential problems on pre-ANSI C compilers.
  199791. */
  199792. void PNGAPI
  199793. png_save_uint_16(png_bytep buf, unsigned int i)
  199794. {
  199795. buf[0] = (png_byte)((i >> 8) & 0xff);
  199796. buf[1] = (png_byte)(i & 0xff);
  199797. }
  199798. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  199799. * representing the chunk name. The array must be at least 4 bytes in
  199800. * length, and does not need to be null terminated. To be safe, pass the
  199801. * pre-defined chunk names here, and if you need a new one, define it
  199802. * where the others are defined. The length is the length of the data.
  199803. * All the data must be present. If that is not possible, use the
  199804. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  199805. * functions instead.
  199806. */
  199807. void PNGAPI
  199808. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  199809. png_bytep data, png_size_t length)
  199810. {
  199811. if(png_ptr == NULL) return;
  199812. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  199813. png_write_chunk_data(png_ptr, data, length);
  199814. png_write_chunk_end(png_ptr);
  199815. }
  199816. /* Write the start of a PNG chunk. The type is the chunk type.
  199817. * The total_length is the sum of the lengths of all the data you will be
  199818. * passing in png_write_chunk_data().
  199819. */
  199820. void PNGAPI
  199821. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  199822. png_uint_32 length)
  199823. {
  199824. png_byte buf[4];
  199825. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  199826. if(png_ptr == NULL) return;
  199827. /* write the length */
  199828. png_save_uint_32(buf, length);
  199829. png_write_data(png_ptr, buf, (png_size_t)4);
  199830. /* write the chunk name */
  199831. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  199832. /* reset the crc and run it over the chunk name */
  199833. png_reset_crc(png_ptr);
  199834. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  199835. }
  199836. /* Write the data of a PNG chunk started with png_write_chunk_start().
  199837. * Note that multiple calls to this function are allowed, and that the
  199838. * sum of the lengths from these calls *must* add up to the total_length
  199839. * given to png_write_chunk_start().
  199840. */
  199841. void PNGAPI
  199842. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  199843. {
  199844. /* write the data, and run the CRC over it */
  199845. if(png_ptr == NULL) return;
  199846. if (data != NULL && length > 0)
  199847. {
  199848. png_calculate_crc(png_ptr, data, length);
  199849. png_write_data(png_ptr, data, length);
  199850. }
  199851. }
  199852. /* Finish a chunk started with png_write_chunk_start(). */
  199853. void PNGAPI
  199854. png_write_chunk_end(png_structp png_ptr)
  199855. {
  199856. png_byte buf[4];
  199857. if(png_ptr == NULL) return;
  199858. /* write the crc */
  199859. png_save_uint_32(buf, png_ptr->crc);
  199860. png_write_data(png_ptr, buf, (png_size_t)4);
  199861. }
  199862. /* Simple function to write the signature. If we have already written
  199863. * the magic bytes of the signature, or more likely, the PNG stream is
  199864. * being embedded into another stream and doesn't need its own signature,
  199865. * we should call png_set_sig_bytes() to tell libpng how many of the
  199866. * bytes have already been written.
  199867. */
  199868. void /* PRIVATE */
  199869. png_write_sig(png_structp png_ptr)
  199870. {
  199871. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  199872. /* write the rest of the 8 byte signature */
  199873. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  199874. (png_size_t)8 - png_ptr->sig_bytes);
  199875. if(png_ptr->sig_bytes < 3)
  199876. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  199877. }
  199878. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  199879. /*
  199880. * This pair of functions encapsulates the operation of (a) compressing a
  199881. * text string, and (b) issuing it later as a series of chunk data writes.
  199882. * The compression_state structure is shared context for these functions
  199883. * set up by the caller in order to make the whole mess thread-safe.
  199884. */
  199885. typedef struct
  199886. {
  199887. char *input; /* the uncompressed input data */
  199888. int input_len; /* its length */
  199889. int num_output_ptr; /* number of output pointers used */
  199890. int max_output_ptr; /* size of output_ptr */
  199891. png_charpp output_ptr; /* array of pointers to output */
  199892. } compression_state;
  199893. /* compress given text into storage in the png_ptr structure */
  199894. static int /* PRIVATE */
  199895. png_text_compress(png_structp png_ptr,
  199896. png_charp text, png_size_t text_len, int compression,
  199897. compression_state *comp)
  199898. {
  199899. int ret;
  199900. comp->num_output_ptr = 0;
  199901. comp->max_output_ptr = 0;
  199902. comp->output_ptr = NULL;
  199903. comp->input = NULL;
  199904. comp->input_len = 0;
  199905. /* we may just want to pass the text right through */
  199906. if (compression == PNG_TEXT_COMPRESSION_NONE)
  199907. {
  199908. comp->input = text;
  199909. comp->input_len = text_len;
  199910. return((int)text_len);
  199911. }
  199912. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  199913. {
  199914. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  199915. char msg[50];
  199916. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  199917. png_warning(png_ptr, msg);
  199918. #else
  199919. png_warning(png_ptr, "Unknown compression type");
  199920. #endif
  199921. }
  199922. /* We can't write the chunk until we find out how much data we have,
  199923. * which means we need to run the compressor first and save the
  199924. * output. This shouldn't be a problem, as the vast majority of
  199925. * comments should be reasonable, but we will set up an array of
  199926. * malloc'd pointers to be sure.
  199927. *
  199928. * If we knew the application was well behaved, we could simplify this
  199929. * greatly by assuming we can always malloc an output buffer large
  199930. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  199931. * and malloc this directly. The only time this would be a bad idea is
  199932. * if we can't malloc more than 64K and we have 64K of random input
  199933. * data, or if the input string is incredibly large (although this
  199934. * wouldn't cause a failure, just a slowdown due to swapping).
  199935. */
  199936. /* set up the compression buffers */
  199937. png_ptr->zstream.avail_in = (uInt)text_len;
  199938. png_ptr->zstream.next_in = (Bytef *)text;
  199939. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199940. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  199941. /* this is the same compression loop as in png_write_row() */
  199942. do
  199943. {
  199944. /* compress the data */
  199945. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  199946. if (ret != Z_OK)
  199947. {
  199948. /* error */
  199949. if (png_ptr->zstream.msg != NULL)
  199950. png_error(png_ptr, png_ptr->zstream.msg);
  199951. else
  199952. png_error(png_ptr, "zlib error");
  199953. }
  199954. /* check to see if we need more room */
  199955. if (!(png_ptr->zstream.avail_out))
  199956. {
  199957. /* make sure the output array has room */
  199958. if (comp->num_output_ptr >= comp->max_output_ptr)
  199959. {
  199960. int old_max;
  199961. old_max = comp->max_output_ptr;
  199962. comp->max_output_ptr = comp->num_output_ptr + 4;
  199963. if (comp->output_ptr != NULL)
  199964. {
  199965. png_charpp old_ptr;
  199966. old_ptr = comp->output_ptr;
  199967. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  199968. (png_uint_32)(comp->max_output_ptr *
  199969. png_sizeof (png_charpp)));
  199970. png_memcpy(comp->output_ptr, old_ptr, old_max
  199971. * png_sizeof (png_charp));
  199972. png_free(png_ptr, old_ptr);
  199973. }
  199974. else
  199975. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  199976. (png_uint_32)(comp->max_output_ptr *
  199977. png_sizeof (png_charp)));
  199978. }
  199979. /* save the data */
  199980. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  199981. (png_uint_32)png_ptr->zbuf_size);
  199982. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  199983. png_ptr->zbuf_size);
  199984. comp->num_output_ptr++;
  199985. /* and reset the buffer */
  199986. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199987. png_ptr->zstream.next_out = png_ptr->zbuf;
  199988. }
  199989. /* continue until we don't have any more to compress */
  199990. } while (png_ptr->zstream.avail_in);
  199991. /* finish the compression */
  199992. do
  199993. {
  199994. /* tell zlib we are finished */
  199995. ret = deflate(&png_ptr->zstream, Z_FINISH);
  199996. if (ret == Z_OK)
  199997. {
  199998. /* check to see if we need more room */
  199999. if (!(png_ptr->zstream.avail_out))
  200000. {
  200001. /* check to make sure our output array has room */
  200002. if (comp->num_output_ptr >= comp->max_output_ptr)
  200003. {
  200004. int old_max;
  200005. old_max = comp->max_output_ptr;
  200006. comp->max_output_ptr = comp->num_output_ptr + 4;
  200007. if (comp->output_ptr != NULL)
  200008. {
  200009. png_charpp old_ptr;
  200010. old_ptr = comp->output_ptr;
  200011. /* This could be optimized to realloc() */
  200012. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200013. (png_uint_32)(comp->max_output_ptr *
  200014. png_sizeof (png_charpp)));
  200015. png_memcpy(comp->output_ptr, old_ptr,
  200016. old_max * png_sizeof (png_charp));
  200017. png_free(png_ptr, old_ptr);
  200018. }
  200019. else
  200020. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200021. (png_uint_32)(comp->max_output_ptr *
  200022. png_sizeof (png_charp)));
  200023. }
  200024. /* save off the data */
  200025. comp->output_ptr[comp->num_output_ptr] =
  200026. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  200027. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  200028. png_ptr->zbuf_size);
  200029. comp->num_output_ptr++;
  200030. /* and reset the buffer pointers */
  200031. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200032. png_ptr->zstream.next_out = png_ptr->zbuf;
  200033. }
  200034. }
  200035. else if (ret != Z_STREAM_END)
  200036. {
  200037. /* we got an error */
  200038. if (png_ptr->zstream.msg != NULL)
  200039. png_error(png_ptr, png_ptr->zstream.msg);
  200040. else
  200041. png_error(png_ptr, "zlib error");
  200042. }
  200043. } while (ret != Z_STREAM_END);
  200044. /* text length is number of buffers plus last buffer */
  200045. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  200046. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  200047. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  200048. return((int)text_len);
  200049. }
  200050. /* ship the compressed text out via chunk writes */
  200051. static void /* PRIVATE */
  200052. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  200053. {
  200054. int i;
  200055. /* handle the no-compression case */
  200056. if (comp->input)
  200057. {
  200058. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  200059. (png_size_t)comp->input_len);
  200060. return;
  200061. }
  200062. /* write saved output buffers, if any */
  200063. for (i = 0; i < comp->num_output_ptr; i++)
  200064. {
  200065. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  200066. png_ptr->zbuf_size);
  200067. png_free(png_ptr, comp->output_ptr[i]);
  200068. comp->output_ptr[i]=NULL;
  200069. }
  200070. if (comp->max_output_ptr != 0)
  200071. png_free(png_ptr, comp->output_ptr);
  200072. comp->output_ptr=NULL;
  200073. /* write anything left in zbuf */
  200074. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  200075. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  200076. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  200077. /* reset zlib for another zTXt/iTXt or image data */
  200078. deflateReset(&png_ptr->zstream);
  200079. png_ptr->zstream.data_type = Z_BINARY;
  200080. }
  200081. #endif
  200082. /* Write the IHDR chunk, and update the png_struct with the necessary
  200083. * information. Note that the rest of this code depends upon this
  200084. * information being correct.
  200085. */
  200086. void /* PRIVATE */
  200087. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  200088. int bit_depth, int color_type, int compression_type, int filter_type,
  200089. int interlace_type)
  200090. {
  200091. #ifdef PNG_USE_LOCAL_ARRAYS
  200092. PNG_IHDR;
  200093. #endif
  200094. png_byte buf[13]; /* buffer to store the IHDR info */
  200095. png_debug(1, "in png_write_IHDR\n");
  200096. /* Check that we have valid input data from the application info */
  200097. switch (color_type)
  200098. {
  200099. case PNG_COLOR_TYPE_GRAY:
  200100. switch (bit_depth)
  200101. {
  200102. case 1:
  200103. case 2:
  200104. case 4:
  200105. case 8:
  200106. case 16: png_ptr->channels = 1; break;
  200107. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  200108. }
  200109. break;
  200110. case PNG_COLOR_TYPE_RGB:
  200111. if (bit_depth != 8 && bit_depth != 16)
  200112. png_error(png_ptr, "Invalid bit depth for RGB image");
  200113. png_ptr->channels = 3;
  200114. break;
  200115. case PNG_COLOR_TYPE_PALETTE:
  200116. switch (bit_depth)
  200117. {
  200118. case 1:
  200119. case 2:
  200120. case 4:
  200121. case 8: png_ptr->channels = 1; break;
  200122. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  200123. }
  200124. break;
  200125. case PNG_COLOR_TYPE_GRAY_ALPHA:
  200126. if (bit_depth != 8 && bit_depth != 16)
  200127. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  200128. png_ptr->channels = 2;
  200129. break;
  200130. case PNG_COLOR_TYPE_RGB_ALPHA:
  200131. if (bit_depth != 8 && bit_depth != 16)
  200132. png_error(png_ptr, "Invalid bit depth for RGBA image");
  200133. png_ptr->channels = 4;
  200134. break;
  200135. default:
  200136. png_error(png_ptr, "Invalid image color type specified");
  200137. }
  200138. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  200139. {
  200140. png_warning(png_ptr, "Invalid compression type specified");
  200141. compression_type = PNG_COMPRESSION_TYPE_BASE;
  200142. }
  200143. /* Write filter_method 64 (intrapixel differencing) only if
  200144. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  200145. * 2. Libpng did not write a PNG signature (this filter_method is only
  200146. * used in PNG datastreams that are embedded in MNG datastreams) and
  200147. * 3. The application called png_permit_mng_features with a mask that
  200148. * included PNG_FLAG_MNG_FILTER_64 and
  200149. * 4. The filter_method is 64 and
  200150. * 5. The color_type is RGB or RGBA
  200151. */
  200152. if (
  200153. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200154. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  200155. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  200156. (color_type == PNG_COLOR_TYPE_RGB ||
  200157. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  200158. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  200159. #endif
  200160. filter_type != PNG_FILTER_TYPE_BASE)
  200161. {
  200162. png_warning(png_ptr, "Invalid filter type specified");
  200163. filter_type = PNG_FILTER_TYPE_BASE;
  200164. }
  200165. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  200166. if (interlace_type != PNG_INTERLACE_NONE &&
  200167. interlace_type != PNG_INTERLACE_ADAM7)
  200168. {
  200169. png_warning(png_ptr, "Invalid interlace type specified");
  200170. interlace_type = PNG_INTERLACE_ADAM7;
  200171. }
  200172. #else
  200173. interlace_type=PNG_INTERLACE_NONE;
  200174. #endif
  200175. /* save off the relevent information */
  200176. png_ptr->bit_depth = (png_byte)bit_depth;
  200177. png_ptr->color_type = (png_byte)color_type;
  200178. png_ptr->interlaced = (png_byte)interlace_type;
  200179. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200180. png_ptr->filter_type = (png_byte)filter_type;
  200181. #endif
  200182. png_ptr->compression_type = (png_byte)compression_type;
  200183. png_ptr->width = width;
  200184. png_ptr->height = height;
  200185. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  200186. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  200187. /* set the usr info, so any transformations can modify it */
  200188. png_ptr->usr_width = png_ptr->width;
  200189. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  200190. png_ptr->usr_channels = png_ptr->channels;
  200191. /* pack the header information into the buffer */
  200192. png_save_uint_32(buf, width);
  200193. png_save_uint_32(buf + 4, height);
  200194. buf[8] = (png_byte)bit_depth;
  200195. buf[9] = (png_byte)color_type;
  200196. buf[10] = (png_byte)compression_type;
  200197. buf[11] = (png_byte)filter_type;
  200198. buf[12] = (png_byte)interlace_type;
  200199. /* write the chunk */
  200200. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  200201. /* initialize zlib with PNG info */
  200202. png_ptr->zstream.zalloc = png_zalloc;
  200203. png_ptr->zstream.zfree = png_zfree;
  200204. png_ptr->zstream.opaque = (voidpf)png_ptr;
  200205. if (!(png_ptr->do_filter))
  200206. {
  200207. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  200208. png_ptr->bit_depth < 8)
  200209. png_ptr->do_filter = PNG_FILTER_NONE;
  200210. else
  200211. png_ptr->do_filter = PNG_ALL_FILTERS;
  200212. }
  200213. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  200214. {
  200215. if (png_ptr->do_filter != PNG_FILTER_NONE)
  200216. png_ptr->zlib_strategy = Z_FILTERED;
  200217. else
  200218. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  200219. }
  200220. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  200221. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  200222. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  200223. png_ptr->zlib_mem_level = 8;
  200224. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  200225. png_ptr->zlib_window_bits = 15;
  200226. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  200227. png_ptr->zlib_method = 8;
  200228. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  200229. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  200230. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  200231. png_error(png_ptr, "zlib failed to initialize compressor");
  200232. png_ptr->zstream.next_out = png_ptr->zbuf;
  200233. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200234. /* libpng is not interested in zstream.data_type */
  200235. /* set it to a predefined value, to avoid its evaluation inside zlib */
  200236. png_ptr->zstream.data_type = Z_BINARY;
  200237. png_ptr->mode = PNG_HAVE_IHDR;
  200238. }
  200239. /* write the palette. We are careful not to trust png_color to be in the
  200240. * correct order for PNG, so people can redefine it to any convenient
  200241. * structure.
  200242. */
  200243. void /* PRIVATE */
  200244. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  200245. {
  200246. #ifdef PNG_USE_LOCAL_ARRAYS
  200247. PNG_PLTE;
  200248. #endif
  200249. png_uint_32 i;
  200250. png_colorp pal_ptr;
  200251. png_byte buf[3];
  200252. png_debug(1, "in png_write_PLTE\n");
  200253. if ((
  200254. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200255. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  200256. #endif
  200257. num_pal == 0) || num_pal > 256)
  200258. {
  200259. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  200260. {
  200261. png_error(png_ptr, "Invalid number of colors in palette");
  200262. }
  200263. else
  200264. {
  200265. png_warning(png_ptr, "Invalid number of colors in palette");
  200266. return;
  200267. }
  200268. }
  200269. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  200270. {
  200271. png_warning(png_ptr,
  200272. "Ignoring request to write a PLTE chunk in grayscale PNG");
  200273. return;
  200274. }
  200275. png_ptr->num_palette = (png_uint_16)num_pal;
  200276. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  200277. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  200278. #ifndef PNG_NO_POINTER_INDEXING
  200279. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  200280. {
  200281. buf[0] = pal_ptr->red;
  200282. buf[1] = pal_ptr->green;
  200283. buf[2] = pal_ptr->blue;
  200284. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  200285. }
  200286. #else
  200287. /* This is a little slower but some buggy compilers need to do this instead */
  200288. pal_ptr=palette;
  200289. for (i = 0; i < num_pal; i++)
  200290. {
  200291. buf[0] = pal_ptr[i].red;
  200292. buf[1] = pal_ptr[i].green;
  200293. buf[2] = pal_ptr[i].blue;
  200294. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  200295. }
  200296. #endif
  200297. png_write_chunk_end(png_ptr);
  200298. png_ptr->mode |= PNG_HAVE_PLTE;
  200299. }
  200300. /* write an IDAT chunk */
  200301. void /* PRIVATE */
  200302. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  200303. {
  200304. #ifdef PNG_USE_LOCAL_ARRAYS
  200305. PNG_IDAT;
  200306. #endif
  200307. png_debug(1, "in png_write_IDAT\n");
  200308. /* Optimize the CMF field in the zlib stream. */
  200309. /* This hack of the zlib stream is compliant to the stream specification. */
  200310. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  200311. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  200312. {
  200313. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  200314. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  200315. {
  200316. /* Avoid memory underflows and multiplication overflows. */
  200317. /* The conditions below are practically always satisfied;
  200318. however, they still must be checked. */
  200319. if (length >= 2 &&
  200320. png_ptr->height < 16384 && png_ptr->width < 16384)
  200321. {
  200322. png_uint_32 uncompressed_idat_size = png_ptr->height *
  200323. ((png_ptr->width *
  200324. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  200325. unsigned int z_cinfo = z_cmf >> 4;
  200326. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  200327. while (uncompressed_idat_size <= half_z_window_size &&
  200328. half_z_window_size >= 256)
  200329. {
  200330. z_cinfo--;
  200331. half_z_window_size >>= 1;
  200332. }
  200333. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  200334. if (data[0] != (png_byte)z_cmf)
  200335. {
  200336. data[0] = (png_byte)z_cmf;
  200337. data[1] &= 0xe0;
  200338. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  200339. }
  200340. }
  200341. }
  200342. else
  200343. png_error(png_ptr,
  200344. "Invalid zlib compression method or flags in IDAT");
  200345. }
  200346. png_write_chunk(png_ptr, png_IDAT, data, length);
  200347. png_ptr->mode |= PNG_HAVE_IDAT;
  200348. }
  200349. /* write an IEND chunk */
  200350. void /* PRIVATE */
  200351. png_write_IEND(png_structp png_ptr)
  200352. {
  200353. #ifdef PNG_USE_LOCAL_ARRAYS
  200354. PNG_IEND;
  200355. #endif
  200356. png_debug(1, "in png_write_IEND\n");
  200357. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  200358. (png_size_t)0);
  200359. png_ptr->mode |= PNG_HAVE_IEND;
  200360. }
  200361. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  200362. /* write a gAMA chunk */
  200363. #ifdef PNG_FLOATING_POINT_SUPPORTED
  200364. void /* PRIVATE */
  200365. png_write_gAMA(png_structp png_ptr, double file_gamma)
  200366. {
  200367. #ifdef PNG_USE_LOCAL_ARRAYS
  200368. PNG_gAMA;
  200369. #endif
  200370. png_uint_32 igamma;
  200371. png_byte buf[4];
  200372. png_debug(1, "in png_write_gAMA\n");
  200373. /* file_gamma is saved in 1/100,000ths */
  200374. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  200375. png_save_uint_32(buf, igamma);
  200376. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  200377. }
  200378. #endif
  200379. #ifdef PNG_FIXED_POINT_SUPPORTED
  200380. void /* PRIVATE */
  200381. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  200382. {
  200383. #ifdef PNG_USE_LOCAL_ARRAYS
  200384. PNG_gAMA;
  200385. #endif
  200386. png_byte buf[4];
  200387. png_debug(1, "in png_write_gAMA\n");
  200388. /* file_gamma is saved in 1/100,000ths */
  200389. png_save_uint_32(buf, (png_uint_32)file_gamma);
  200390. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  200391. }
  200392. #endif
  200393. #endif
  200394. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  200395. /* write a sRGB chunk */
  200396. void /* PRIVATE */
  200397. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  200398. {
  200399. #ifdef PNG_USE_LOCAL_ARRAYS
  200400. PNG_sRGB;
  200401. #endif
  200402. png_byte buf[1];
  200403. png_debug(1, "in png_write_sRGB\n");
  200404. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  200405. png_warning(png_ptr,
  200406. "Invalid sRGB rendering intent specified");
  200407. buf[0]=(png_byte)srgb_intent;
  200408. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  200409. }
  200410. #endif
  200411. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  200412. /* write an iCCP chunk */
  200413. void /* PRIVATE */
  200414. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  200415. png_charp profile, int profile_len)
  200416. {
  200417. #ifdef PNG_USE_LOCAL_ARRAYS
  200418. PNG_iCCP;
  200419. #endif
  200420. png_size_t name_len;
  200421. png_charp new_name;
  200422. compression_state comp;
  200423. int embedded_profile_len = 0;
  200424. png_debug(1, "in png_write_iCCP\n");
  200425. comp.num_output_ptr = 0;
  200426. comp.max_output_ptr = 0;
  200427. comp.output_ptr = NULL;
  200428. comp.input = NULL;
  200429. comp.input_len = 0;
  200430. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  200431. &new_name)) == 0)
  200432. {
  200433. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  200434. return;
  200435. }
  200436. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  200437. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  200438. if (profile == NULL)
  200439. profile_len = 0;
  200440. if (profile_len > 3)
  200441. embedded_profile_len =
  200442. ((*( (png_bytep)profile ))<<24) |
  200443. ((*( (png_bytep)profile+1))<<16) |
  200444. ((*( (png_bytep)profile+2))<< 8) |
  200445. ((*( (png_bytep)profile+3)) );
  200446. if (profile_len < embedded_profile_len)
  200447. {
  200448. png_warning(png_ptr,
  200449. "Embedded profile length too large in iCCP chunk");
  200450. return;
  200451. }
  200452. if (profile_len > embedded_profile_len)
  200453. {
  200454. png_warning(png_ptr,
  200455. "Truncating profile to actual length in iCCP chunk");
  200456. profile_len = embedded_profile_len;
  200457. }
  200458. if (profile_len)
  200459. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  200460. PNG_COMPRESSION_TYPE_BASE, &comp);
  200461. /* make sure we include the NULL after the name and the compression type */
  200462. png_write_chunk_start(png_ptr, png_iCCP,
  200463. (png_uint_32)name_len+profile_len+2);
  200464. new_name[name_len+1]=0x00;
  200465. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  200466. if (profile_len)
  200467. png_write_compressed_data_out(png_ptr, &comp);
  200468. png_write_chunk_end(png_ptr);
  200469. png_free(png_ptr, new_name);
  200470. }
  200471. #endif
  200472. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  200473. /* write a sPLT chunk */
  200474. void /* PRIVATE */
  200475. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  200476. {
  200477. #ifdef PNG_USE_LOCAL_ARRAYS
  200478. PNG_sPLT;
  200479. #endif
  200480. png_size_t name_len;
  200481. png_charp new_name;
  200482. png_byte entrybuf[10];
  200483. int entry_size = (spalette->depth == 8 ? 6 : 10);
  200484. int palette_size = entry_size * spalette->nentries;
  200485. png_sPLT_entryp ep;
  200486. #ifdef PNG_NO_POINTER_INDEXING
  200487. int i;
  200488. #endif
  200489. png_debug(1, "in png_write_sPLT\n");
  200490. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  200491. spalette->name, &new_name))==0)
  200492. {
  200493. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  200494. return;
  200495. }
  200496. /* make sure we include the NULL after the name */
  200497. png_write_chunk_start(png_ptr, png_sPLT,
  200498. (png_uint_32)(name_len + 2 + palette_size));
  200499. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  200500. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  200501. /* loop through each palette entry, writing appropriately */
  200502. #ifndef PNG_NO_POINTER_INDEXING
  200503. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  200504. {
  200505. if (spalette->depth == 8)
  200506. {
  200507. entrybuf[0] = (png_byte)ep->red;
  200508. entrybuf[1] = (png_byte)ep->green;
  200509. entrybuf[2] = (png_byte)ep->blue;
  200510. entrybuf[3] = (png_byte)ep->alpha;
  200511. png_save_uint_16(entrybuf + 4, ep->frequency);
  200512. }
  200513. else
  200514. {
  200515. png_save_uint_16(entrybuf + 0, ep->red);
  200516. png_save_uint_16(entrybuf + 2, ep->green);
  200517. png_save_uint_16(entrybuf + 4, ep->blue);
  200518. png_save_uint_16(entrybuf + 6, ep->alpha);
  200519. png_save_uint_16(entrybuf + 8, ep->frequency);
  200520. }
  200521. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  200522. }
  200523. #else
  200524. ep=spalette->entries;
  200525. for (i=0; i>spalette->nentries; i++)
  200526. {
  200527. if (spalette->depth == 8)
  200528. {
  200529. entrybuf[0] = (png_byte)ep[i].red;
  200530. entrybuf[1] = (png_byte)ep[i].green;
  200531. entrybuf[2] = (png_byte)ep[i].blue;
  200532. entrybuf[3] = (png_byte)ep[i].alpha;
  200533. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  200534. }
  200535. else
  200536. {
  200537. png_save_uint_16(entrybuf + 0, ep[i].red);
  200538. png_save_uint_16(entrybuf + 2, ep[i].green);
  200539. png_save_uint_16(entrybuf + 4, ep[i].blue);
  200540. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  200541. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  200542. }
  200543. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  200544. }
  200545. #endif
  200546. png_write_chunk_end(png_ptr);
  200547. png_free(png_ptr, new_name);
  200548. }
  200549. #endif
  200550. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  200551. /* write the sBIT chunk */
  200552. void /* PRIVATE */
  200553. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  200554. {
  200555. #ifdef PNG_USE_LOCAL_ARRAYS
  200556. PNG_sBIT;
  200557. #endif
  200558. png_byte buf[4];
  200559. png_size_t size;
  200560. png_debug(1, "in png_write_sBIT\n");
  200561. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  200562. if (color_type & PNG_COLOR_MASK_COLOR)
  200563. {
  200564. png_byte maxbits;
  200565. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  200566. png_ptr->usr_bit_depth);
  200567. if (sbit->red == 0 || sbit->red > maxbits ||
  200568. sbit->green == 0 || sbit->green > maxbits ||
  200569. sbit->blue == 0 || sbit->blue > maxbits)
  200570. {
  200571. png_warning(png_ptr, "Invalid sBIT depth specified");
  200572. return;
  200573. }
  200574. buf[0] = sbit->red;
  200575. buf[1] = sbit->green;
  200576. buf[2] = sbit->blue;
  200577. size = 3;
  200578. }
  200579. else
  200580. {
  200581. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  200582. {
  200583. png_warning(png_ptr, "Invalid sBIT depth specified");
  200584. return;
  200585. }
  200586. buf[0] = sbit->gray;
  200587. size = 1;
  200588. }
  200589. if (color_type & PNG_COLOR_MASK_ALPHA)
  200590. {
  200591. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  200592. {
  200593. png_warning(png_ptr, "Invalid sBIT depth specified");
  200594. return;
  200595. }
  200596. buf[size++] = sbit->alpha;
  200597. }
  200598. png_write_chunk(png_ptr, png_sBIT, buf, size);
  200599. }
  200600. #endif
  200601. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  200602. /* write the cHRM chunk */
  200603. #ifdef PNG_FLOATING_POINT_SUPPORTED
  200604. void /* PRIVATE */
  200605. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  200606. double red_x, double red_y, double green_x, double green_y,
  200607. double blue_x, double blue_y)
  200608. {
  200609. #ifdef PNG_USE_LOCAL_ARRAYS
  200610. PNG_cHRM;
  200611. #endif
  200612. png_byte buf[32];
  200613. png_uint_32 itemp;
  200614. png_debug(1, "in png_write_cHRM\n");
  200615. /* each value is saved in 1/100,000ths */
  200616. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  200617. white_x + white_y > 1.0)
  200618. {
  200619. png_warning(png_ptr, "Invalid cHRM white point specified");
  200620. #if !defined(PNG_NO_CONSOLE_IO)
  200621. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  200622. #endif
  200623. return;
  200624. }
  200625. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  200626. png_save_uint_32(buf, itemp);
  200627. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  200628. png_save_uint_32(buf + 4, itemp);
  200629. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  200630. {
  200631. png_warning(png_ptr, "Invalid cHRM red point specified");
  200632. return;
  200633. }
  200634. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  200635. png_save_uint_32(buf + 8, itemp);
  200636. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  200637. png_save_uint_32(buf + 12, itemp);
  200638. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  200639. {
  200640. png_warning(png_ptr, "Invalid cHRM green point specified");
  200641. return;
  200642. }
  200643. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  200644. png_save_uint_32(buf + 16, itemp);
  200645. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  200646. png_save_uint_32(buf + 20, itemp);
  200647. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  200648. {
  200649. png_warning(png_ptr, "Invalid cHRM blue point specified");
  200650. return;
  200651. }
  200652. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  200653. png_save_uint_32(buf + 24, itemp);
  200654. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  200655. png_save_uint_32(buf + 28, itemp);
  200656. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  200657. }
  200658. #endif
  200659. #ifdef PNG_FIXED_POINT_SUPPORTED
  200660. void /* PRIVATE */
  200661. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  200662. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  200663. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  200664. png_fixed_point blue_y)
  200665. {
  200666. #ifdef PNG_USE_LOCAL_ARRAYS
  200667. PNG_cHRM;
  200668. #endif
  200669. png_byte buf[32];
  200670. png_debug(1, "in png_write_cHRM\n");
  200671. /* each value is saved in 1/100,000ths */
  200672. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  200673. {
  200674. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  200675. #if !defined(PNG_NO_CONSOLE_IO)
  200676. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  200677. #endif
  200678. return;
  200679. }
  200680. png_save_uint_32(buf, (png_uint_32)white_x);
  200681. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  200682. if (red_x + red_y > 100000L)
  200683. {
  200684. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  200685. return;
  200686. }
  200687. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  200688. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  200689. if (green_x + green_y > 100000L)
  200690. {
  200691. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  200692. return;
  200693. }
  200694. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  200695. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  200696. if (blue_x + blue_y > 100000L)
  200697. {
  200698. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  200699. return;
  200700. }
  200701. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  200702. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  200703. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  200704. }
  200705. #endif
  200706. #endif
  200707. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  200708. /* write the tRNS chunk */
  200709. void /* PRIVATE */
  200710. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  200711. int num_trans, int color_type)
  200712. {
  200713. #ifdef PNG_USE_LOCAL_ARRAYS
  200714. PNG_tRNS;
  200715. #endif
  200716. png_byte buf[6];
  200717. png_debug(1, "in png_write_tRNS\n");
  200718. if (color_type == PNG_COLOR_TYPE_PALETTE)
  200719. {
  200720. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  200721. {
  200722. png_warning(png_ptr,"Invalid number of transparent colors specified");
  200723. return;
  200724. }
  200725. /* write the chunk out as it is */
  200726. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  200727. }
  200728. else if (color_type == PNG_COLOR_TYPE_GRAY)
  200729. {
  200730. /* one 16 bit value */
  200731. if(tran->gray >= (1 << png_ptr->bit_depth))
  200732. {
  200733. png_warning(png_ptr,
  200734. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  200735. return;
  200736. }
  200737. png_save_uint_16(buf, tran->gray);
  200738. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  200739. }
  200740. else if (color_type == PNG_COLOR_TYPE_RGB)
  200741. {
  200742. /* three 16 bit values */
  200743. png_save_uint_16(buf, tran->red);
  200744. png_save_uint_16(buf + 2, tran->green);
  200745. png_save_uint_16(buf + 4, tran->blue);
  200746. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  200747. {
  200748. png_warning(png_ptr,
  200749. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  200750. return;
  200751. }
  200752. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  200753. }
  200754. else
  200755. {
  200756. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  200757. }
  200758. }
  200759. #endif
  200760. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  200761. /* write the background chunk */
  200762. void /* PRIVATE */
  200763. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  200764. {
  200765. #ifdef PNG_USE_LOCAL_ARRAYS
  200766. PNG_bKGD;
  200767. #endif
  200768. png_byte buf[6];
  200769. png_debug(1, "in png_write_bKGD\n");
  200770. if (color_type == PNG_COLOR_TYPE_PALETTE)
  200771. {
  200772. if (
  200773. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200774. (png_ptr->num_palette ||
  200775. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  200776. #endif
  200777. back->index > png_ptr->num_palette)
  200778. {
  200779. png_warning(png_ptr, "Invalid background palette index");
  200780. return;
  200781. }
  200782. buf[0] = back->index;
  200783. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  200784. }
  200785. else if (color_type & PNG_COLOR_MASK_COLOR)
  200786. {
  200787. png_save_uint_16(buf, back->red);
  200788. png_save_uint_16(buf + 2, back->green);
  200789. png_save_uint_16(buf + 4, back->blue);
  200790. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  200791. {
  200792. png_warning(png_ptr,
  200793. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  200794. return;
  200795. }
  200796. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  200797. }
  200798. else
  200799. {
  200800. if(back->gray >= (1 << png_ptr->bit_depth))
  200801. {
  200802. png_warning(png_ptr,
  200803. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  200804. return;
  200805. }
  200806. png_save_uint_16(buf, back->gray);
  200807. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  200808. }
  200809. }
  200810. #endif
  200811. #if defined(PNG_WRITE_hIST_SUPPORTED)
  200812. /* write the histogram */
  200813. void /* PRIVATE */
  200814. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  200815. {
  200816. #ifdef PNG_USE_LOCAL_ARRAYS
  200817. PNG_hIST;
  200818. #endif
  200819. int i;
  200820. png_byte buf[3];
  200821. png_debug(1, "in png_write_hIST\n");
  200822. if (num_hist > (int)png_ptr->num_palette)
  200823. {
  200824. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  200825. png_ptr->num_palette);
  200826. png_warning(png_ptr, "Invalid number of histogram entries specified");
  200827. return;
  200828. }
  200829. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  200830. for (i = 0; i < num_hist; i++)
  200831. {
  200832. png_save_uint_16(buf, hist[i]);
  200833. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  200834. }
  200835. png_write_chunk_end(png_ptr);
  200836. }
  200837. #endif
  200838. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  200839. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  200840. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  200841. * and if invalid, correct the keyword rather than discarding the entire
  200842. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  200843. * length, forbids leading or trailing whitespace, multiple internal spaces,
  200844. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  200845. *
  200846. * The new_key is allocated to hold the corrected keyword and must be freed
  200847. * by the calling routine. This avoids problems with trying to write to
  200848. * static keywords without having to have duplicate copies of the strings.
  200849. */
  200850. png_size_t /* PRIVATE */
  200851. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  200852. {
  200853. png_size_t key_len;
  200854. png_charp kp, dp;
  200855. int kflag;
  200856. int kwarn=0;
  200857. png_debug(1, "in png_check_keyword\n");
  200858. *new_key = NULL;
  200859. if (key == NULL || (key_len = png_strlen(key)) == 0)
  200860. {
  200861. png_warning(png_ptr, "zero length keyword");
  200862. return ((png_size_t)0);
  200863. }
  200864. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  200865. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  200866. if (*new_key == NULL)
  200867. {
  200868. png_warning(png_ptr, "Out of memory while procesing keyword");
  200869. return ((png_size_t)0);
  200870. }
  200871. /* Replace non-printing characters with a blank and print a warning */
  200872. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  200873. {
  200874. if ((png_byte)*kp < 0x20 ||
  200875. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  200876. {
  200877. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  200878. char msg[40];
  200879. png_snprintf(msg, 40,
  200880. "invalid keyword character 0x%02X", (png_byte)*kp);
  200881. png_warning(png_ptr, msg);
  200882. #else
  200883. png_warning(png_ptr, "invalid character in keyword");
  200884. #endif
  200885. *dp = ' ';
  200886. }
  200887. else
  200888. {
  200889. *dp = *kp;
  200890. }
  200891. }
  200892. *dp = '\0';
  200893. /* Remove any trailing white space. */
  200894. kp = *new_key + key_len - 1;
  200895. if (*kp == ' ')
  200896. {
  200897. png_warning(png_ptr, "trailing spaces removed from keyword");
  200898. while (*kp == ' ')
  200899. {
  200900. *(kp--) = '\0';
  200901. key_len--;
  200902. }
  200903. }
  200904. /* Remove any leading white space. */
  200905. kp = *new_key;
  200906. if (*kp == ' ')
  200907. {
  200908. png_warning(png_ptr, "leading spaces removed from keyword");
  200909. while (*kp == ' ')
  200910. {
  200911. kp++;
  200912. key_len--;
  200913. }
  200914. }
  200915. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  200916. /* Remove multiple internal spaces. */
  200917. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  200918. {
  200919. if (*kp == ' ' && kflag == 0)
  200920. {
  200921. *(dp++) = *kp;
  200922. kflag = 1;
  200923. }
  200924. else if (*kp == ' ')
  200925. {
  200926. key_len--;
  200927. kwarn=1;
  200928. }
  200929. else
  200930. {
  200931. *(dp++) = *kp;
  200932. kflag = 0;
  200933. }
  200934. }
  200935. *dp = '\0';
  200936. if(kwarn)
  200937. png_warning(png_ptr, "extra interior spaces removed from keyword");
  200938. if (key_len == 0)
  200939. {
  200940. png_free(png_ptr, *new_key);
  200941. *new_key=NULL;
  200942. png_warning(png_ptr, "Zero length keyword");
  200943. }
  200944. if (key_len > 79)
  200945. {
  200946. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  200947. new_key[79] = '\0';
  200948. key_len = 79;
  200949. }
  200950. return (key_len);
  200951. }
  200952. #endif
  200953. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  200954. /* write a tEXt chunk */
  200955. void /* PRIVATE */
  200956. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  200957. png_size_t text_len)
  200958. {
  200959. #ifdef PNG_USE_LOCAL_ARRAYS
  200960. PNG_tEXt;
  200961. #endif
  200962. png_size_t key_len;
  200963. png_charp new_key;
  200964. png_debug(1, "in png_write_tEXt\n");
  200965. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  200966. {
  200967. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  200968. return;
  200969. }
  200970. if (text == NULL || *text == '\0')
  200971. text_len = 0;
  200972. else
  200973. text_len = png_strlen(text);
  200974. /* make sure we include the 0 after the key */
  200975. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  200976. /*
  200977. * We leave it to the application to meet PNG-1.0 requirements on the
  200978. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  200979. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  200980. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  200981. */
  200982. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  200983. if (text_len)
  200984. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  200985. png_write_chunk_end(png_ptr);
  200986. png_free(png_ptr, new_key);
  200987. }
  200988. #endif
  200989. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  200990. /* write a compressed text chunk */
  200991. void /* PRIVATE */
  200992. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  200993. png_size_t text_len, int compression)
  200994. {
  200995. #ifdef PNG_USE_LOCAL_ARRAYS
  200996. PNG_zTXt;
  200997. #endif
  200998. png_size_t key_len;
  200999. char buf[1];
  201000. png_charp new_key;
  201001. compression_state comp;
  201002. png_debug(1, "in png_write_zTXt\n");
  201003. comp.num_output_ptr = 0;
  201004. comp.max_output_ptr = 0;
  201005. comp.output_ptr = NULL;
  201006. comp.input = NULL;
  201007. comp.input_len = 0;
  201008. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201009. {
  201010. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  201011. return;
  201012. }
  201013. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  201014. {
  201015. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  201016. png_free(png_ptr, new_key);
  201017. return;
  201018. }
  201019. text_len = png_strlen(text);
  201020. /* compute the compressed data; do it now for the length */
  201021. text_len = png_text_compress(png_ptr, text, text_len, compression,
  201022. &comp);
  201023. /* write start of chunk */
  201024. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  201025. (key_len+text_len+2));
  201026. /* write key */
  201027. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201028. png_free(png_ptr, new_key);
  201029. buf[0] = (png_byte)compression;
  201030. /* write compression */
  201031. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  201032. /* write the compressed data */
  201033. png_write_compressed_data_out(png_ptr, &comp);
  201034. /* close the chunk */
  201035. png_write_chunk_end(png_ptr);
  201036. }
  201037. #endif
  201038. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  201039. /* write an iTXt chunk */
  201040. void /* PRIVATE */
  201041. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  201042. png_charp lang, png_charp lang_key, png_charp text)
  201043. {
  201044. #ifdef PNG_USE_LOCAL_ARRAYS
  201045. PNG_iTXt;
  201046. #endif
  201047. png_size_t lang_len, key_len, lang_key_len, text_len;
  201048. png_charp new_lang, new_key;
  201049. png_byte cbuf[2];
  201050. compression_state comp;
  201051. png_debug(1, "in png_write_iTXt\n");
  201052. comp.num_output_ptr = 0;
  201053. comp.max_output_ptr = 0;
  201054. comp.output_ptr = NULL;
  201055. comp.input = NULL;
  201056. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201057. {
  201058. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  201059. return;
  201060. }
  201061. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  201062. {
  201063. png_warning(png_ptr, "Empty language field in iTXt chunk");
  201064. new_lang = NULL;
  201065. lang_len = 0;
  201066. }
  201067. if (lang_key == NULL)
  201068. lang_key_len = 0;
  201069. else
  201070. lang_key_len = png_strlen(lang_key);
  201071. if (text == NULL)
  201072. text_len = 0;
  201073. else
  201074. text_len = png_strlen(text);
  201075. /* compute the compressed data; do it now for the length */
  201076. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  201077. &comp);
  201078. /* make sure we include the compression flag, the compression byte,
  201079. * and the NULs after the key, lang, and lang_key parts */
  201080. png_write_chunk_start(png_ptr, png_iTXt,
  201081. (png_uint_32)(
  201082. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  201083. + key_len
  201084. + lang_len
  201085. + lang_key_len
  201086. + text_len));
  201087. /*
  201088. * We leave it to the application to meet PNG-1.0 requirements on the
  201089. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  201090. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  201091. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  201092. */
  201093. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201094. /* set the compression flag */
  201095. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  201096. compression == PNG_TEXT_COMPRESSION_NONE)
  201097. cbuf[0] = 0;
  201098. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  201099. cbuf[0] = 1;
  201100. /* set the compression method */
  201101. cbuf[1] = 0;
  201102. png_write_chunk_data(png_ptr, cbuf, 2);
  201103. cbuf[0] = 0;
  201104. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  201105. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  201106. png_write_compressed_data_out(png_ptr, &comp);
  201107. png_write_chunk_end(png_ptr);
  201108. png_free(png_ptr, new_key);
  201109. if (new_lang)
  201110. png_free(png_ptr, new_lang);
  201111. }
  201112. #endif
  201113. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  201114. /* write the oFFs chunk */
  201115. void /* PRIVATE */
  201116. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  201117. int unit_type)
  201118. {
  201119. #ifdef PNG_USE_LOCAL_ARRAYS
  201120. PNG_oFFs;
  201121. #endif
  201122. png_byte buf[9];
  201123. png_debug(1, "in png_write_oFFs\n");
  201124. if (unit_type >= PNG_OFFSET_LAST)
  201125. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  201126. png_save_int_32(buf, x_offset);
  201127. png_save_int_32(buf + 4, y_offset);
  201128. buf[8] = (png_byte)unit_type;
  201129. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  201130. }
  201131. #endif
  201132. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  201133. /* write the pCAL chunk (described in the PNG extensions document) */
  201134. void /* PRIVATE */
  201135. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  201136. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  201137. {
  201138. #ifdef PNG_USE_LOCAL_ARRAYS
  201139. PNG_pCAL;
  201140. #endif
  201141. png_size_t purpose_len, units_len, total_len;
  201142. png_uint_32p params_len;
  201143. png_byte buf[10];
  201144. png_charp new_purpose;
  201145. int i;
  201146. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  201147. if (type >= PNG_EQUATION_LAST)
  201148. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  201149. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  201150. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  201151. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  201152. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  201153. total_len = purpose_len + units_len + 10;
  201154. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  201155. *png_sizeof(png_uint_32)));
  201156. /* Find the length of each parameter, making sure we don't count the
  201157. null terminator for the last parameter. */
  201158. for (i = 0; i < nparams; i++)
  201159. {
  201160. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  201161. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  201162. total_len += (png_size_t)params_len[i];
  201163. }
  201164. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  201165. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  201166. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  201167. png_save_int_32(buf, X0);
  201168. png_save_int_32(buf + 4, X1);
  201169. buf[8] = (png_byte)type;
  201170. buf[9] = (png_byte)nparams;
  201171. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  201172. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  201173. png_free(png_ptr, new_purpose);
  201174. for (i = 0; i < nparams; i++)
  201175. {
  201176. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  201177. (png_size_t)params_len[i]);
  201178. }
  201179. png_free(png_ptr, params_len);
  201180. png_write_chunk_end(png_ptr);
  201181. }
  201182. #endif
  201183. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  201184. /* write the sCAL chunk */
  201185. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  201186. void /* PRIVATE */
  201187. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  201188. {
  201189. #ifdef PNG_USE_LOCAL_ARRAYS
  201190. PNG_sCAL;
  201191. #endif
  201192. char buf[64];
  201193. png_size_t total_len;
  201194. png_debug(1, "in png_write_sCAL\n");
  201195. buf[0] = (char)unit;
  201196. #if defined(_WIN32_WCE)
  201197. /* sprintf() function is not supported on WindowsCE */
  201198. {
  201199. wchar_t wc_buf[32];
  201200. size_t wc_len;
  201201. swprintf(wc_buf, TEXT("%12.12e"), width);
  201202. wc_len = wcslen(wc_buf);
  201203. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  201204. total_len = wc_len + 2;
  201205. swprintf(wc_buf, TEXT("%12.12e"), height);
  201206. wc_len = wcslen(wc_buf);
  201207. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  201208. NULL, NULL);
  201209. total_len += wc_len;
  201210. }
  201211. #else
  201212. png_snprintf(buf + 1, 63, "%12.12e", width);
  201213. total_len = 1 + png_strlen(buf + 1) + 1;
  201214. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  201215. total_len += png_strlen(buf + total_len);
  201216. #endif
  201217. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  201218. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  201219. }
  201220. #else
  201221. #ifdef PNG_FIXED_POINT_SUPPORTED
  201222. void /* PRIVATE */
  201223. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  201224. png_charp height)
  201225. {
  201226. #ifdef PNG_USE_LOCAL_ARRAYS
  201227. PNG_sCAL;
  201228. #endif
  201229. png_byte buf[64];
  201230. png_size_t wlen, hlen, total_len;
  201231. png_debug(1, "in png_write_sCAL_s\n");
  201232. wlen = png_strlen(width);
  201233. hlen = png_strlen(height);
  201234. total_len = wlen + hlen + 2;
  201235. if (total_len > 64)
  201236. {
  201237. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  201238. return;
  201239. }
  201240. buf[0] = (png_byte)unit;
  201241. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  201242. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  201243. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  201244. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  201245. }
  201246. #endif
  201247. #endif
  201248. #endif
  201249. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  201250. /* write the pHYs chunk */
  201251. void /* PRIVATE */
  201252. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  201253. png_uint_32 y_pixels_per_unit,
  201254. int unit_type)
  201255. {
  201256. #ifdef PNG_USE_LOCAL_ARRAYS
  201257. PNG_pHYs;
  201258. #endif
  201259. png_byte buf[9];
  201260. png_debug(1, "in png_write_pHYs\n");
  201261. if (unit_type >= PNG_RESOLUTION_LAST)
  201262. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  201263. png_save_uint_32(buf, x_pixels_per_unit);
  201264. png_save_uint_32(buf + 4, y_pixels_per_unit);
  201265. buf[8] = (png_byte)unit_type;
  201266. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  201267. }
  201268. #endif
  201269. #if defined(PNG_WRITE_tIME_SUPPORTED)
  201270. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  201271. * or png_convert_from_time_t(), or fill in the structure yourself.
  201272. */
  201273. void /* PRIVATE */
  201274. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  201275. {
  201276. #ifdef PNG_USE_LOCAL_ARRAYS
  201277. PNG_tIME;
  201278. #endif
  201279. png_byte buf[7];
  201280. png_debug(1, "in png_write_tIME\n");
  201281. if (mod_time->month > 12 || mod_time->month < 1 ||
  201282. mod_time->day > 31 || mod_time->day < 1 ||
  201283. mod_time->hour > 23 || mod_time->second > 60)
  201284. {
  201285. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  201286. return;
  201287. }
  201288. png_save_uint_16(buf, mod_time->year);
  201289. buf[2] = mod_time->month;
  201290. buf[3] = mod_time->day;
  201291. buf[4] = mod_time->hour;
  201292. buf[5] = mod_time->minute;
  201293. buf[6] = mod_time->second;
  201294. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  201295. }
  201296. #endif
  201297. /* initializes the row writing capability of libpng */
  201298. void /* PRIVATE */
  201299. png_write_start_row(png_structp png_ptr)
  201300. {
  201301. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201302. #ifdef PNG_USE_LOCAL_ARRAYS
  201303. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  201304. /* start of interlace block */
  201305. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  201306. /* offset to next interlace block */
  201307. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  201308. /* start of interlace block in the y direction */
  201309. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  201310. /* offset to next interlace block in the y direction */
  201311. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  201312. #endif
  201313. #endif
  201314. png_size_t buf_size;
  201315. png_debug(1, "in png_write_start_row\n");
  201316. buf_size = (png_size_t)(PNG_ROWBYTES(
  201317. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  201318. /* set up row buffer */
  201319. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  201320. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  201321. #ifndef PNG_NO_WRITE_FILTERING
  201322. /* set up filtering buffer, if using this filter */
  201323. if (png_ptr->do_filter & PNG_FILTER_SUB)
  201324. {
  201325. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  201326. (png_ptr->rowbytes + 1));
  201327. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  201328. }
  201329. /* We only need to keep the previous row if we are using one of these. */
  201330. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  201331. {
  201332. /* set up previous row buffer */
  201333. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  201334. png_memset(png_ptr->prev_row, 0, buf_size);
  201335. if (png_ptr->do_filter & PNG_FILTER_UP)
  201336. {
  201337. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  201338. (png_ptr->rowbytes + 1));
  201339. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  201340. }
  201341. if (png_ptr->do_filter & PNG_FILTER_AVG)
  201342. {
  201343. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  201344. (png_ptr->rowbytes + 1));
  201345. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  201346. }
  201347. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  201348. {
  201349. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  201350. (png_ptr->rowbytes + 1));
  201351. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  201352. }
  201353. #endif /* PNG_NO_WRITE_FILTERING */
  201354. }
  201355. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201356. /* if interlaced, we need to set up width and height of pass */
  201357. if (png_ptr->interlaced)
  201358. {
  201359. if (!(png_ptr->transformations & PNG_INTERLACE))
  201360. {
  201361. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  201362. png_pass_ystart[0]) / png_pass_yinc[0];
  201363. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  201364. png_pass_start[0]) / png_pass_inc[0];
  201365. }
  201366. else
  201367. {
  201368. png_ptr->num_rows = png_ptr->height;
  201369. png_ptr->usr_width = png_ptr->width;
  201370. }
  201371. }
  201372. else
  201373. #endif
  201374. {
  201375. png_ptr->num_rows = png_ptr->height;
  201376. png_ptr->usr_width = png_ptr->width;
  201377. }
  201378. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201379. png_ptr->zstream.next_out = png_ptr->zbuf;
  201380. }
  201381. /* Internal use only. Called when finished processing a row of data. */
  201382. void /* PRIVATE */
  201383. png_write_finish_row(png_structp png_ptr)
  201384. {
  201385. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201386. #ifdef PNG_USE_LOCAL_ARRAYS
  201387. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  201388. /* start of interlace block */
  201389. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  201390. /* offset to next interlace block */
  201391. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  201392. /* start of interlace block in the y direction */
  201393. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  201394. /* offset to next interlace block in the y direction */
  201395. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  201396. #endif
  201397. #endif
  201398. int ret;
  201399. png_debug(1, "in png_write_finish_row\n");
  201400. /* next row */
  201401. png_ptr->row_number++;
  201402. /* see if we are done */
  201403. if (png_ptr->row_number < png_ptr->num_rows)
  201404. return;
  201405. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201406. /* if interlaced, go to next pass */
  201407. if (png_ptr->interlaced)
  201408. {
  201409. png_ptr->row_number = 0;
  201410. if (png_ptr->transformations & PNG_INTERLACE)
  201411. {
  201412. png_ptr->pass++;
  201413. }
  201414. else
  201415. {
  201416. /* loop until we find a non-zero width or height pass */
  201417. do
  201418. {
  201419. png_ptr->pass++;
  201420. if (png_ptr->pass >= 7)
  201421. break;
  201422. png_ptr->usr_width = (png_ptr->width +
  201423. png_pass_inc[png_ptr->pass] - 1 -
  201424. png_pass_start[png_ptr->pass]) /
  201425. png_pass_inc[png_ptr->pass];
  201426. png_ptr->num_rows = (png_ptr->height +
  201427. png_pass_yinc[png_ptr->pass] - 1 -
  201428. png_pass_ystart[png_ptr->pass]) /
  201429. png_pass_yinc[png_ptr->pass];
  201430. if (png_ptr->transformations & PNG_INTERLACE)
  201431. break;
  201432. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  201433. }
  201434. /* reset the row above the image for the next pass */
  201435. if (png_ptr->pass < 7)
  201436. {
  201437. if (png_ptr->prev_row != NULL)
  201438. png_memset(png_ptr->prev_row, 0,
  201439. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  201440. png_ptr->usr_bit_depth,png_ptr->width))+1);
  201441. return;
  201442. }
  201443. }
  201444. #endif
  201445. /* if we get here, we've just written the last row, so we need
  201446. to flush the compressor */
  201447. do
  201448. {
  201449. /* tell the compressor we are done */
  201450. ret = deflate(&png_ptr->zstream, Z_FINISH);
  201451. /* check for an error */
  201452. if (ret == Z_OK)
  201453. {
  201454. /* check to see if we need more room */
  201455. if (!(png_ptr->zstream.avail_out))
  201456. {
  201457. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  201458. png_ptr->zstream.next_out = png_ptr->zbuf;
  201459. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201460. }
  201461. }
  201462. else if (ret != Z_STREAM_END)
  201463. {
  201464. if (png_ptr->zstream.msg != NULL)
  201465. png_error(png_ptr, png_ptr->zstream.msg);
  201466. else
  201467. png_error(png_ptr, "zlib error");
  201468. }
  201469. } while (ret != Z_STREAM_END);
  201470. /* write any extra space */
  201471. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  201472. {
  201473. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  201474. png_ptr->zstream.avail_out);
  201475. }
  201476. deflateReset(&png_ptr->zstream);
  201477. png_ptr->zstream.data_type = Z_BINARY;
  201478. }
  201479. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  201480. /* Pick out the correct pixels for the interlace pass.
  201481. * The basic idea here is to go through the row with a source
  201482. * pointer and a destination pointer (sp and dp), and copy the
  201483. * correct pixels for the pass. As the row gets compacted,
  201484. * sp will always be >= dp, so we should never overwrite anything.
  201485. * See the default: case for the easiest code to understand.
  201486. */
  201487. void /* PRIVATE */
  201488. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  201489. {
  201490. #ifdef PNG_USE_LOCAL_ARRAYS
  201491. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  201492. /* start of interlace block */
  201493. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  201494. /* offset to next interlace block */
  201495. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  201496. #endif
  201497. png_debug(1, "in png_do_write_interlace\n");
  201498. /* we don't have to do anything on the last pass (6) */
  201499. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  201500. if (row != NULL && row_info != NULL && pass < 6)
  201501. #else
  201502. if (pass < 6)
  201503. #endif
  201504. {
  201505. /* each pixel depth is handled separately */
  201506. switch (row_info->pixel_depth)
  201507. {
  201508. case 1:
  201509. {
  201510. png_bytep sp;
  201511. png_bytep dp;
  201512. int shift;
  201513. int d;
  201514. int value;
  201515. png_uint_32 i;
  201516. png_uint_32 row_width = row_info->width;
  201517. dp = row;
  201518. d = 0;
  201519. shift = 7;
  201520. for (i = png_pass_start[pass]; i < row_width;
  201521. i += png_pass_inc[pass])
  201522. {
  201523. sp = row + (png_size_t)(i >> 3);
  201524. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  201525. d |= (value << shift);
  201526. if (shift == 0)
  201527. {
  201528. shift = 7;
  201529. *dp++ = (png_byte)d;
  201530. d = 0;
  201531. }
  201532. else
  201533. shift--;
  201534. }
  201535. if (shift != 7)
  201536. *dp = (png_byte)d;
  201537. break;
  201538. }
  201539. case 2:
  201540. {
  201541. png_bytep sp;
  201542. png_bytep dp;
  201543. int shift;
  201544. int d;
  201545. int value;
  201546. png_uint_32 i;
  201547. png_uint_32 row_width = row_info->width;
  201548. dp = row;
  201549. shift = 6;
  201550. d = 0;
  201551. for (i = png_pass_start[pass]; i < row_width;
  201552. i += png_pass_inc[pass])
  201553. {
  201554. sp = row + (png_size_t)(i >> 2);
  201555. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  201556. d |= (value << shift);
  201557. if (shift == 0)
  201558. {
  201559. shift = 6;
  201560. *dp++ = (png_byte)d;
  201561. d = 0;
  201562. }
  201563. else
  201564. shift -= 2;
  201565. }
  201566. if (shift != 6)
  201567. *dp = (png_byte)d;
  201568. break;
  201569. }
  201570. case 4:
  201571. {
  201572. png_bytep sp;
  201573. png_bytep dp;
  201574. int shift;
  201575. int d;
  201576. int value;
  201577. png_uint_32 i;
  201578. png_uint_32 row_width = row_info->width;
  201579. dp = row;
  201580. shift = 4;
  201581. d = 0;
  201582. for (i = png_pass_start[pass]; i < row_width;
  201583. i += png_pass_inc[pass])
  201584. {
  201585. sp = row + (png_size_t)(i >> 1);
  201586. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  201587. d |= (value << shift);
  201588. if (shift == 0)
  201589. {
  201590. shift = 4;
  201591. *dp++ = (png_byte)d;
  201592. d = 0;
  201593. }
  201594. else
  201595. shift -= 4;
  201596. }
  201597. if (shift != 4)
  201598. *dp = (png_byte)d;
  201599. break;
  201600. }
  201601. default:
  201602. {
  201603. png_bytep sp;
  201604. png_bytep dp;
  201605. png_uint_32 i;
  201606. png_uint_32 row_width = row_info->width;
  201607. png_size_t pixel_bytes;
  201608. /* start at the beginning */
  201609. dp = row;
  201610. /* find out how many bytes each pixel takes up */
  201611. pixel_bytes = (row_info->pixel_depth >> 3);
  201612. /* loop through the row, only looking at the pixels that
  201613. matter */
  201614. for (i = png_pass_start[pass]; i < row_width;
  201615. i += png_pass_inc[pass])
  201616. {
  201617. /* find out where the original pixel is */
  201618. sp = row + (png_size_t)i * pixel_bytes;
  201619. /* move the pixel */
  201620. if (dp != sp)
  201621. png_memcpy(dp, sp, pixel_bytes);
  201622. /* next pixel */
  201623. dp += pixel_bytes;
  201624. }
  201625. break;
  201626. }
  201627. }
  201628. /* set new row width */
  201629. row_info->width = (row_info->width +
  201630. png_pass_inc[pass] - 1 -
  201631. png_pass_start[pass]) /
  201632. png_pass_inc[pass];
  201633. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  201634. row_info->width);
  201635. }
  201636. }
  201637. #endif
  201638. /* This filters the row, chooses which filter to use, if it has not already
  201639. * been specified by the application, and then writes the row out with the
  201640. * chosen filter.
  201641. */
  201642. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  201643. #define PNG_HISHIFT 10
  201644. #define PNG_LOMASK ((png_uint_32)0xffffL)
  201645. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  201646. void /* PRIVATE */
  201647. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  201648. {
  201649. png_bytep best_row;
  201650. #ifndef PNG_NO_WRITE_FILTER
  201651. png_bytep prev_row, row_buf;
  201652. png_uint_32 mins, bpp;
  201653. png_byte filter_to_do = png_ptr->do_filter;
  201654. png_uint_32 row_bytes = row_info->rowbytes;
  201655. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  201656. int num_p_filters = (int)png_ptr->num_prev_filters;
  201657. #endif
  201658. png_debug(1, "in png_write_find_filter\n");
  201659. /* find out how many bytes offset each pixel is */
  201660. bpp = (row_info->pixel_depth + 7) >> 3;
  201661. prev_row = png_ptr->prev_row;
  201662. #endif
  201663. best_row = png_ptr->row_buf;
  201664. #ifndef PNG_NO_WRITE_FILTER
  201665. row_buf = best_row;
  201666. mins = PNG_MAXSUM;
  201667. /* The prediction method we use is to find which method provides the
  201668. * smallest value when summing the absolute values of the distances
  201669. * from zero, using anything >= 128 as negative numbers. This is known
  201670. * as the "minimum sum of absolute differences" heuristic. Other
  201671. * heuristics are the "weighted minimum sum of absolute differences"
  201672. * (experimental and can in theory improve compression), and the "zlib
  201673. * predictive" method (not implemented yet), which does test compressions
  201674. * of lines using different filter methods, and then chooses the
  201675. * (series of) filter(s) that give minimum compressed data size (VERY
  201676. * computationally expensive).
  201677. *
  201678. * GRR 980525: consider also
  201679. * (1) minimum sum of absolute differences from running average (i.e.,
  201680. * keep running sum of non-absolute differences & count of bytes)
  201681. * [track dispersion, too? restart average if dispersion too large?]
  201682. * (1b) minimum sum of absolute differences from sliding average, probably
  201683. * with window size <= deflate window (usually 32K)
  201684. * (2) minimum sum of squared differences from zero or running average
  201685. * (i.e., ~ root-mean-square approach)
  201686. */
  201687. /* We don't need to test the 'no filter' case if this is the only filter
  201688. * that has been chosen, as it doesn't actually do anything to the data.
  201689. */
  201690. if ((filter_to_do & PNG_FILTER_NONE) &&
  201691. filter_to_do != PNG_FILTER_NONE)
  201692. {
  201693. png_bytep rp;
  201694. png_uint_32 sum = 0;
  201695. png_uint_32 i;
  201696. int v;
  201697. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  201698. {
  201699. v = *rp;
  201700. sum += (v < 128) ? v : 256 - v;
  201701. }
  201702. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  201703. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  201704. {
  201705. png_uint_32 sumhi, sumlo;
  201706. int j;
  201707. sumlo = sum & PNG_LOMASK;
  201708. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  201709. /* Reduce the sum if we match any of the previous rows */
  201710. for (j = 0; j < num_p_filters; j++)
  201711. {
  201712. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  201713. {
  201714. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  201715. PNG_WEIGHT_SHIFT;
  201716. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  201717. PNG_WEIGHT_SHIFT;
  201718. }
  201719. }
  201720. /* Factor in the cost of this filter (this is here for completeness,
  201721. * but it makes no sense to have a "cost" for the NONE filter, as
  201722. * it has the minimum possible computational cost - none).
  201723. */
  201724. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  201725. PNG_COST_SHIFT;
  201726. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  201727. PNG_COST_SHIFT;
  201728. if (sumhi > PNG_HIMASK)
  201729. sum = PNG_MAXSUM;
  201730. else
  201731. sum = (sumhi << PNG_HISHIFT) + sumlo;
  201732. }
  201733. #endif
  201734. mins = sum;
  201735. }
  201736. /* sub filter */
  201737. if (filter_to_do == PNG_FILTER_SUB)
  201738. /* it's the only filter so no testing is needed */
  201739. {
  201740. png_bytep rp, lp, dp;
  201741. png_uint_32 i;
  201742. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  201743. i++, rp++, dp++)
  201744. {
  201745. *dp = *rp;
  201746. }
  201747. for (lp = row_buf + 1; i < row_bytes;
  201748. i++, rp++, lp++, dp++)
  201749. {
  201750. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  201751. }
  201752. best_row = png_ptr->sub_row;
  201753. }
  201754. else if (filter_to_do & PNG_FILTER_SUB)
  201755. {
  201756. png_bytep rp, dp, lp;
  201757. png_uint_32 sum = 0, lmins = mins;
  201758. png_uint_32 i;
  201759. int v;
  201760. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  201761. /* We temporarily increase the "minimum sum" by the factor we
  201762. * would reduce the sum of this filter, so that we can do the
  201763. * early exit comparison without scaling the sum each time.
  201764. */
  201765. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  201766. {
  201767. int j;
  201768. png_uint_32 lmhi, lmlo;
  201769. lmlo = lmins & PNG_LOMASK;
  201770. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  201771. for (j = 0; j < num_p_filters; j++)
  201772. {
  201773. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  201774. {
  201775. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  201776. PNG_WEIGHT_SHIFT;
  201777. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  201778. PNG_WEIGHT_SHIFT;
  201779. }
  201780. }
  201781. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  201782. PNG_COST_SHIFT;
  201783. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  201784. PNG_COST_SHIFT;
  201785. if (lmhi > PNG_HIMASK)
  201786. lmins = PNG_MAXSUM;
  201787. else
  201788. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  201789. }
  201790. #endif
  201791. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  201792. i++, rp++, dp++)
  201793. {
  201794. v = *dp = *rp;
  201795. sum += (v < 128) ? v : 256 - v;
  201796. }
  201797. for (lp = row_buf + 1; i < row_bytes;
  201798. i++, rp++, lp++, dp++)
  201799. {
  201800. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  201801. sum += (v < 128) ? v : 256 - v;
  201802. if (sum > lmins) /* We are already worse, don't continue. */
  201803. break;
  201804. }
  201805. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  201806. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  201807. {
  201808. int j;
  201809. png_uint_32 sumhi, sumlo;
  201810. sumlo = sum & PNG_LOMASK;
  201811. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  201812. for (j = 0; j < num_p_filters; j++)
  201813. {
  201814. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  201815. {
  201816. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  201817. PNG_WEIGHT_SHIFT;
  201818. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  201819. PNG_WEIGHT_SHIFT;
  201820. }
  201821. }
  201822. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  201823. PNG_COST_SHIFT;
  201824. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  201825. PNG_COST_SHIFT;
  201826. if (sumhi > PNG_HIMASK)
  201827. sum = PNG_MAXSUM;
  201828. else
  201829. sum = (sumhi << PNG_HISHIFT) + sumlo;
  201830. }
  201831. #endif
  201832. if (sum < mins)
  201833. {
  201834. mins = sum;
  201835. best_row = png_ptr->sub_row;
  201836. }
  201837. }
  201838. /* up filter */
  201839. if (filter_to_do == PNG_FILTER_UP)
  201840. {
  201841. png_bytep rp, dp, pp;
  201842. png_uint_32 i;
  201843. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  201844. pp = prev_row + 1; i < row_bytes;
  201845. i++, rp++, pp++, dp++)
  201846. {
  201847. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  201848. }
  201849. best_row = png_ptr->up_row;
  201850. }
  201851. else if (filter_to_do & PNG_FILTER_UP)
  201852. {
  201853. png_bytep rp, dp, pp;
  201854. png_uint_32 sum = 0, lmins = mins;
  201855. png_uint_32 i;
  201856. int v;
  201857. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  201858. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  201859. {
  201860. int j;
  201861. png_uint_32 lmhi, lmlo;
  201862. lmlo = lmins & PNG_LOMASK;
  201863. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  201864. for (j = 0; j < num_p_filters; j++)
  201865. {
  201866. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  201867. {
  201868. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  201869. PNG_WEIGHT_SHIFT;
  201870. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  201871. PNG_WEIGHT_SHIFT;
  201872. }
  201873. }
  201874. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  201875. PNG_COST_SHIFT;
  201876. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  201877. PNG_COST_SHIFT;
  201878. if (lmhi > PNG_HIMASK)
  201879. lmins = PNG_MAXSUM;
  201880. else
  201881. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  201882. }
  201883. #endif
  201884. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  201885. pp = prev_row + 1; i < row_bytes; i++)
  201886. {
  201887. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  201888. sum += (v < 128) ? v : 256 - v;
  201889. if (sum > lmins) /* We are already worse, don't continue. */
  201890. break;
  201891. }
  201892. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  201893. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  201894. {
  201895. int j;
  201896. png_uint_32 sumhi, sumlo;
  201897. sumlo = sum & PNG_LOMASK;
  201898. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  201899. for (j = 0; j < num_p_filters; j++)
  201900. {
  201901. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  201902. {
  201903. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  201904. PNG_WEIGHT_SHIFT;
  201905. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  201906. PNG_WEIGHT_SHIFT;
  201907. }
  201908. }
  201909. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  201910. PNG_COST_SHIFT;
  201911. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  201912. PNG_COST_SHIFT;
  201913. if (sumhi > PNG_HIMASK)
  201914. sum = PNG_MAXSUM;
  201915. else
  201916. sum = (sumhi << PNG_HISHIFT) + sumlo;
  201917. }
  201918. #endif
  201919. if (sum < mins)
  201920. {
  201921. mins = sum;
  201922. best_row = png_ptr->up_row;
  201923. }
  201924. }
  201925. /* avg filter */
  201926. if (filter_to_do == PNG_FILTER_AVG)
  201927. {
  201928. png_bytep rp, dp, pp, lp;
  201929. png_uint_32 i;
  201930. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  201931. pp = prev_row + 1; i < bpp; i++)
  201932. {
  201933. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  201934. }
  201935. for (lp = row_buf + 1; i < row_bytes; i++)
  201936. {
  201937. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  201938. & 0xff);
  201939. }
  201940. best_row = png_ptr->avg_row;
  201941. }
  201942. else if (filter_to_do & PNG_FILTER_AVG)
  201943. {
  201944. png_bytep rp, dp, pp, lp;
  201945. png_uint_32 sum = 0, lmins = mins;
  201946. png_uint_32 i;
  201947. int v;
  201948. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  201949. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  201950. {
  201951. int j;
  201952. png_uint_32 lmhi, lmlo;
  201953. lmlo = lmins & PNG_LOMASK;
  201954. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  201955. for (j = 0; j < num_p_filters; j++)
  201956. {
  201957. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  201958. {
  201959. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  201960. PNG_WEIGHT_SHIFT;
  201961. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  201962. PNG_WEIGHT_SHIFT;
  201963. }
  201964. }
  201965. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  201966. PNG_COST_SHIFT;
  201967. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  201968. PNG_COST_SHIFT;
  201969. if (lmhi > PNG_HIMASK)
  201970. lmins = PNG_MAXSUM;
  201971. else
  201972. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  201973. }
  201974. #endif
  201975. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  201976. pp = prev_row + 1; i < bpp; i++)
  201977. {
  201978. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  201979. sum += (v < 128) ? v : 256 - v;
  201980. }
  201981. for (lp = row_buf + 1; i < row_bytes; i++)
  201982. {
  201983. v = *dp++ =
  201984. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  201985. sum += (v < 128) ? v : 256 - v;
  201986. if (sum > lmins) /* We are already worse, don't continue. */
  201987. break;
  201988. }
  201989. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  201990. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  201991. {
  201992. int j;
  201993. png_uint_32 sumhi, sumlo;
  201994. sumlo = sum & PNG_LOMASK;
  201995. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  201996. for (j = 0; j < num_p_filters; j++)
  201997. {
  201998. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  201999. {
  202000. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202001. PNG_WEIGHT_SHIFT;
  202002. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202003. PNG_WEIGHT_SHIFT;
  202004. }
  202005. }
  202006. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202007. PNG_COST_SHIFT;
  202008. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202009. PNG_COST_SHIFT;
  202010. if (sumhi > PNG_HIMASK)
  202011. sum = PNG_MAXSUM;
  202012. else
  202013. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202014. }
  202015. #endif
  202016. if (sum < mins)
  202017. {
  202018. mins = sum;
  202019. best_row = png_ptr->avg_row;
  202020. }
  202021. }
  202022. /* Paeth filter */
  202023. if (filter_to_do == PNG_FILTER_PAETH)
  202024. {
  202025. png_bytep rp, dp, pp, cp, lp;
  202026. png_uint_32 i;
  202027. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  202028. pp = prev_row + 1; i < bpp; i++)
  202029. {
  202030. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202031. }
  202032. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  202033. {
  202034. int a, b, c, pa, pb, pc, p;
  202035. b = *pp++;
  202036. c = *cp++;
  202037. a = *lp++;
  202038. p = b - c;
  202039. pc = a - c;
  202040. #ifdef PNG_USE_ABS
  202041. pa = abs(p);
  202042. pb = abs(pc);
  202043. pc = abs(p + pc);
  202044. #else
  202045. pa = p < 0 ? -p : p;
  202046. pb = pc < 0 ? -pc : pc;
  202047. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  202048. #endif
  202049. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  202050. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  202051. }
  202052. best_row = png_ptr->paeth_row;
  202053. }
  202054. else if (filter_to_do & PNG_FILTER_PAETH)
  202055. {
  202056. png_bytep rp, dp, pp, cp, lp;
  202057. png_uint_32 sum = 0, lmins = mins;
  202058. png_uint_32 i;
  202059. int v;
  202060. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202061. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202062. {
  202063. int j;
  202064. png_uint_32 lmhi, lmlo;
  202065. lmlo = lmins & PNG_LOMASK;
  202066. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202067. for (j = 0; j < num_p_filters; j++)
  202068. {
  202069. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  202070. {
  202071. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202072. PNG_WEIGHT_SHIFT;
  202073. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202074. PNG_WEIGHT_SHIFT;
  202075. }
  202076. }
  202077. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202078. PNG_COST_SHIFT;
  202079. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202080. PNG_COST_SHIFT;
  202081. if (lmhi > PNG_HIMASK)
  202082. lmins = PNG_MAXSUM;
  202083. else
  202084. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202085. }
  202086. #endif
  202087. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  202088. pp = prev_row + 1; i < bpp; i++)
  202089. {
  202090. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202091. sum += (v < 128) ? v : 256 - v;
  202092. }
  202093. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  202094. {
  202095. int a, b, c, pa, pb, pc, p;
  202096. b = *pp++;
  202097. c = *cp++;
  202098. a = *lp++;
  202099. #ifndef PNG_SLOW_PAETH
  202100. p = b - c;
  202101. pc = a - c;
  202102. #ifdef PNG_USE_ABS
  202103. pa = abs(p);
  202104. pb = abs(pc);
  202105. pc = abs(p + pc);
  202106. #else
  202107. pa = p < 0 ? -p : p;
  202108. pb = pc < 0 ? -pc : pc;
  202109. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  202110. #endif
  202111. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  202112. #else /* PNG_SLOW_PAETH */
  202113. p = a + b - c;
  202114. pa = abs(p - a);
  202115. pb = abs(p - b);
  202116. pc = abs(p - c);
  202117. if (pa <= pb && pa <= pc)
  202118. p = a;
  202119. else if (pb <= pc)
  202120. p = b;
  202121. else
  202122. p = c;
  202123. #endif /* PNG_SLOW_PAETH */
  202124. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  202125. sum += (v < 128) ? v : 256 - v;
  202126. if (sum > lmins) /* We are already worse, don't continue. */
  202127. break;
  202128. }
  202129. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202130. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202131. {
  202132. int j;
  202133. png_uint_32 sumhi, sumlo;
  202134. sumlo = sum & PNG_LOMASK;
  202135. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202136. for (j = 0; j < num_p_filters; j++)
  202137. {
  202138. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  202139. {
  202140. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202141. PNG_WEIGHT_SHIFT;
  202142. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202143. PNG_WEIGHT_SHIFT;
  202144. }
  202145. }
  202146. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202147. PNG_COST_SHIFT;
  202148. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202149. PNG_COST_SHIFT;
  202150. if (sumhi > PNG_HIMASK)
  202151. sum = PNG_MAXSUM;
  202152. else
  202153. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202154. }
  202155. #endif
  202156. if (sum < mins)
  202157. {
  202158. best_row = png_ptr->paeth_row;
  202159. }
  202160. }
  202161. #endif /* PNG_NO_WRITE_FILTER */
  202162. /* Do the actual writing of the filtered row data from the chosen filter. */
  202163. png_write_filtered_row(png_ptr, best_row);
  202164. #ifndef PNG_NO_WRITE_FILTER
  202165. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202166. /* Save the type of filter we picked this time for future calculations */
  202167. if (png_ptr->num_prev_filters > 0)
  202168. {
  202169. int j;
  202170. for (j = 1; j < num_p_filters; j++)
  202171. {
  202172. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  202173. }
  202174. png_ptr->prev_filters[j] = best_row[0];
  202175. }
  202176. #endif
  202177. #endif /* PNG_NO_WRITE_FILTER */
  202178. }
  202179. /* Do the actual writing of a previously filtered row. */
  202180. void /* PRIVATE */
  202181. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  202182. {
  202183. png_debug(1, "in png_write_filtered_row\n");
  202184. png_debug1(2, "filter = %d\n", filtered_row[0]);
  202185. /* set up the zlib input buffer */
  202186. png_ptr->zstream.next_in = filtered_row;
  202187. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  202188. /* repeat until we have compressed all the data */
  202189. do
  202190. {
  202191. int ret; /* return of zlib */
  202192. /* compress the data */
  202193. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  202194. /* check for compression errors */
  202195. if (ret != Z_OK)
  202196. {
  202197. if (png_ptr->zstream.msg != NULL)
  202198. png_error(png_ptr, png_ptr->zstream.msg);
  202199. else
  202200. png_error(png_ptr, "zlib error");
  202201. }
  202202. /* see if it is time to write another IDAT */
  202203. if (!(png_ptr->zstream.avail_out))
  202204. {
  202205. /* write the IDAT and reset the zlib output buffer */
  202206. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  202207. png_ptr->zstream.next_out = png_ptr->zbuf;
  202208. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202209. }
  202210. /* repeat until all data has been compressed */
  202211. } while (png_ptr->zstream.avail_in);
  202212. /* swap the current and previous rows */
  202213. if (png_ptr->prev_row != NULL)
  202214. {
  202215. png_bytep tptr;
  202216. tptr = png_ptr->prev_row;
  202217. png_ptr->prev_row = png_ptr->row_buf;
  202218. png_ptr->row_buf = tptr;
  202219. }
  202220. /* finish row - updates counters and flushes zlib if last row */
  202221. png_write_finish_row(png_ptr);
  202222. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  202223. png_ptr->flush_rows++;
  202224. if (png_ptr->flush_dist > 0 &&
  202225. png_ptr->flush_rows >= png_ptr->flush_dist)
  202226. {
  202227. png_write_flush(png_ptr);
  202228. }
  202229. #endif
  202230. }
  202231. #endif /* PNG_WRITE_SUPPORTED */
  202232. /*** End of inlined file: pngwutil.c ***/
  202233. }
  202234. #else
  202235. extern "C"
  202236. {
  202237. #include <png.h>
  202238. #include <pngconf.h>
  202239. }
  202240. #endif
  202241. }
  202242. #undef max
  202243. #undef min
  202244. #if JUCE_MSVC
  202245. #pragma warning (pop)
  202246. #endif
  202247. BEGIN_JUCE_NAMESPACE
  202248. using ::calloc;
  202249. using ::malloc;
  202250. using ::free;
  202251. namespace PNGHelpers
  202252. {
  202253. using namespace pnglibNamespace;
  202254. static void readCallback (png_structp png, png_bytep data, png_size_t length)
  202255. {
  202256. static_cast<InputStream*> (png_get_io_ptr (png))->read (data, (int) length);
  202257. }
  202258. static void writeDataCallback (png_structp png, png_bytep data, png_size_t length)
  202259. {
  202260. static_cast<OutputStream*> (png_get_io_ptr (png))->write (data, (int) length);
  202261. }
  202262. struct PNGErrorStruct {};
  202263. static void errorCallback (png_structp, png_const_charp)
  202264. {
  202265. throw PNGErrorStruct();
  202266. }
  202267. }
  202268. PNGImageFormat::PNGImageFormat() {}
  202269. PNGImageFormat::~PNGImageFormat() {}
  202270. const String PNGImageFormat::getFormatName()
  202271. {
  202272. return "PNG";
  202273. }
  202274. bool PNGImageFormat::canUnderstand (InputStream& in)
  202275. {
  202276. const int bytesNeeded = 4;
  202277. char header [bytesNeeded];
  202278. return in.read (header, bytesNeeded) == bytesNeeded
  202279. && header[1] == 'P'
  202280. && header[2] == 'N'
  202281. && header[3] == 'G';
  202282. }
  202283. const Image PNGImageFormat::decodeImage (InputStream& in)
  202284. {
  202285. using namespace pnglibNamespace;
  202286. Image image;
  202287. png_structp pngReadStruct;
  202288. png_infop pngInfoStruct;
  202289. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  202290. if (pngReadStruct != 0)
  202291. {
  202292. pngInfoStruct = png_create_info_struct (pngReadStruct);
  202293. if (pngInfoStruct == 0)
  202294. {
  202295. png_destroy_read_struct (&pngReadStruct, 0, 0);
  202296. return Image();
  202297. }
  202298. png_set_error_fn (pngReadStruct, 0, PNGHelpers::errorCallback, PNGHelpers::errorCallback );
  202299. // read the header..
  202300. png_set_read_fn (pngReadStruct, &in, PNGHelpers::readCallback);
  202301. png_uint_32 width, height;
  202302. int bitDepth, colorType, interlaceType;
  202303. png_read_info (pngReadStruct, pngInfoStruct);
  202304. png_get_IHDR (pngReadStruct, pngInfoStruct,
  202305. &width, &height,
  202306. &bitDepth, &colorType,
  202307. &interlaceType, 0, 0);
  202308. if (bitDepth == 16)
  202309. png_set_strip_16 (pngReadStruct);
  202310. if (colorType == PNG_COLOR_TYPE_PALETTE)
  202311. png_set_expand (pngReadStruct);
  202312. if (bitDepth < 8)
  202313. png_set_expand (pngReadStruct);
  202314. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  202315. png_set_expand (pngReadStruct);
  202316. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  202317. png_set_gray_to_rgb (pngReadStruct);
  202318. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  202319. bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  202320. || pngInfoStruct->num_trans > 0;
  202321. // Load the image into a temp buffer in the pnglib format..
  202322. HeapBlock <uint8> tempBuffer (height * (width << 2));
  202323. {
  202324. HeapBlock <png_bytep> rows (height);
  202325. for (int y = (int) height; --y >= 0;)
  202326. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  202327. png_read_image (pngReadStruct, rows);
  202328. png_read_end (pngReadStruct, pngInfoStruct);
  202329. }
  202330. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  202331. // now convert the data to a juce image format..
  202332. image = Image (hasAlphaChan ? Image::ARGB : Image::RGB,
  202333. (int) width, (int) height, hasAlphaChan);
  202334. hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  202335. const Image::BitmapData destData (image, 0, 0, (int) width, (int) height, true);
  202336. uint8* srcRow = tempBuffer;
  202337. uint8* destRow = destData.data;
  202338. for (int y = 0; y < (int) height; ++y)
  202339. {
  202340. const uint8* src = srcRow;
  202341. srcRow += (width << 2);
  202342. uint8* dest = destRow;
  202343. destRow += destData.lineStride;
  202344. if (hasAlphaChan)
  202345. {
  202346. for (int i = (int) width; --i >= 0;)
  202347. {
  202348. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  202349. ((PixelARGB*) dest)->premultiply();
  202350. dest += destData.pixelStride;
  202351. src += 4;
  202352. }
  202353. }
  202354. else
  202355. {
  202356. for (int i = (int) width; --i >= 0;)
  202357. {
  202358. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  202359. dest += destData.pixelStride;
  202360. src += 4;
  202361. }
  202362. }
  202363. }
  202364. }
  202365. return image;
  202366. }
  202367. bool PNGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  202368. {
  202369. using namespace pnglibNamespace;
  202370. const int width = image.getWidth();
  202371. const int height = image.getHeight();
  202372. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  202373. if (pngWriteStruct == 0)
  202374. return false;
  202375. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  202376. if (pngInfoStruct == 0)
  202377. {
  202378. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  202379. return false;
  202380. }
  202381. png_set_write_fn (pngWriteStruct, &out, PNGHelpers::writeDataCallback, 0);
  202382. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  202383. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  202384. : PNG_COLOR_TYPE_RGB,
  202385. PNG_INTERLACE_NONE,
  202386. PNG_COMPRESSION_TYPE_BASE,
  202387. PNG_FILTER_TYPE_BASE);
  202388. HeapBlock <uint8> rowData (width * 4);
  202389. png_color_8 sig_bit;
  202390. sig_bit.red = 8;
  202391. sig_bit.green = 8;
  202392. sig_bit.blue = 8;
  202393. sig_bit.alpha = 8;
  202394. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  202395. png_write_info (pngWriteStruct, pngInfoStruct);
  202396. png_set_shift (pngWriteStruct, &sig_bit);
  202397. png_set_packing (pngWriteStruct);
  202398. const Image::BitmapData srcData (image, 0, 0, width, height);
  202399. for (int y = 0; y < height; ++y)
  202400. {
  202401. uint8* dst = rowData;
  202402. const uint8* src = srcData.getLinePointer (y);
  202403. if (image.hasAlphaChannel())
  202404. {
  202405. for (int i = width; --i >= 0;)
  202406. {
  202407. PixelARGB p (*(const PixelARGB*) src);
  202408. p.unpremultiply();
  202409. *dst++ = p.getRed();
  202410. *dst++ = p.getGreen();
  202411. *dst++ = p.getBlue();
  202412. *dst++ = p.getAlpha();
  202413. src += srcData.pixelStride;
  202414. }
  202415. }
  202416. else
  202417. {
  202418. for (int i = width; --i >= 0;)
  202419. {
  202420. *dst++ = ((const PixelRGB*) src)->getRed();
  202421. *dst++ = ((const PixelRGB*) src)->getGreen();
  202422. *dst++ = ((const PixelRGB*) src)->getBlue();
  202423. src += srcData.pixelStride;
  202424. }
  202425. }
  202426. png_write_rows (pngWriteStruct, &rowData, 1);
  202427. }
  202428. png_write_end (pngWriteStruct, pngInfoStruct);
  202429. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  202430. out.flush();
  202431. return true;
  202432. }
  202433. END_JUCE_NAMESPACE
  202434. /*** End of inlined file: juce_PNGLoader.cpp ***/
  202435. #endif
  202436. //==============================================================================
  202437. #if JUCE_BUILD_NATIVE
  202438. #if JUCE_WINDOWS
  202439. /*** Start of inlined file: juce_win32_NativeCode.cpp ***/
  202440. /*
  202441. This file wraps together all the win32-specific code, so that
  202442. we can include all the native headers just once, and compile all our
  202443. platform-specific stuff in one big lump, keeping it out of the way of
  202444. the rest of the codebase.
  202445. */
  202446. #if JUCE_WINDOWS
  202447. BEGIN_JUCE_NAMESPACE
  202448. #define JUCE_INCLUDED_FILE 1
  202449. // Now include the actual code files..
  202450. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  202451. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  202452. // compiled on its own).
  202453. #if JUCE_INCLUDED_FILE
  202454. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  202455. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  202456. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  202457. #ifndef DOXYGEN
  202458. // use with DynamicLibraryLoader to simplify importing functions
  202459. //
  202460. // functionName: function to import
  202461. // localFunctionName: name you want to use to actually call it (must be different)
  202462. // returnType: the return type
  202463. // object: the DynamicLibraryLoader to use
  202464. // params: list of params (bracketed)
  202465. //
  202466. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  202467. typedef returnType (WINAPI *type##localFunctionName) params; \
  202468. type##localFunctionName localFunctionName \
  202469. = (type##localFunctionName)object.findProcAddress (#functionName);
  202470. // loads and unloads a DLL automatically
  202471. class JUCE_API DynamicLibraryLoader
  202472. {
  202473. public:
  202474. DynamicLibraryLoader (const String& name);
  202475. ~DynamicLibraryLoader();
  202476. void* findProcAddress (const String& functionName);
  202477. private:
  202478. void* libHandle;
  202479. };
  202480. #endif
  202481. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  202482. /*** End of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  202483. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  202484. {
  202485. libHandle = LoadLibrary (name);
  202486. }
  202487. DynamicLibraryLoader::~DynamicLibraryLoader()
  202488. {
  202489. FreeLibrary ((HMODULE) libHandle);
  202490. }
  202491. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  202492. {
  202493. return GetProcAddress ((HMODULE) libHandle, functionName.toCString());
  202494. }
  202495. #endif
  202496. /*** End of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  202497. /*** Start of inlined file: juce_win32_SystemStats.cpp ***/
  202498. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  202499. // compiled on its own).
  202500. #if JUCE_INCLUDED_FILE
  202501. extern void juce_initialiseThreadEvents();
  202502. void Logger::outputDebugString (const String& text)
  202503. {
  202504. OutputDebugString (text + "\n");
  202505. }
  202506. static int64 hiResTicksPerSecond;
  202507. static double hiResTicksScaleFactor;
  202508. #if JUCE_USE_INTRINSICS
  202509. // CPU info functions using intrinsics...
  202510. #pragma intrinsic (__cpuid)
  202511. #pragma intrinsic (__rdtsc)
  202512. const String SystemStats::getCpuVendor()
  202513. {
  202514. int info [4];
  202515. __cpuid (info, 0);
  202516. char v [12];
  202517. memcpy (v, info + 1, 4);
  202518. memcpy (v + 4, info + 3, 4);
  202519. memcpy (v + 8, info + 2, 4);
  202520. return String (v, 12);
  202521. }
  202522. #else
  202523. // CPU info functions using old fashioned inline asm...
  202524. static void juce_getCpuVendor (char* const v)
  202525. {
  202526. int vendor[4];
  202527. zeromem (vendor, 16);
  202528. #ifdef JUCE_64BIT
  202529. #else
  202530. #ifndef __MINGW32__
  202531. __try
  202532. #endif
  202533. {
  202534. #if JUCE_GCC
  202535. unsigned int dummy = 0;
  202536. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  202537. #else
  202538. __asm
  202539. {
  202540. mov eax, 0
  202541. cpuid
  202542. mov [vendor], ebx
  202543. mov [vendor + 4], edx
  202544. mov [vendor + 8], ecx
  202545. }
  202546. #endif
  202547. }
  202548. #ifndef __MINGW32__
  202549. __except (EXCEPTION_EXECUTE_HANDLER)
  202550. {
  202551. *v = 0;
  202552. }
  202553. #endif
  202554. #endif
  202555. memcpy (v, vendor, 16);
  202556. }
  202557. const String SystemStats::getCpuVendor()
  202558. {
  202559. char v [16];
  202560. juce_getCpuVendor (v);
  202561. return String (v, 16);
  202562. }
  202563. #endif
  202564. void SystemStats::initialiseStats()
  202565. {
  202566. juce_initialiseThreadEvents();
  202567. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  202568. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  202569. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  202570. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  202571. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  202572. #else
  202573. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  202574. #endif
  202575. {
  202576. SYSTEM_INFO systemInfo;
  202577. GetSystemInfo (&systemInfo);
  202578. cpuFlags.numCpus = systemInfo.dwNumberOfProcessors;
  202579. }
  202580. LARGE_INTEGER f;
  202581. QueryPerformanceFrequency (&f);
  202582. hiResTicksPerSecond = f.QuadPart;
  202583. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  202584. String s (SystemStats::getJUCEVersion());
  202585. const MMRESULT res = timeBeginPeriod (1);
  202586. (void) res;
  202587. jassert (res == TIMERR_NOERROR);
  202588. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  202589. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  202590. #endif
  202591. }
  202592. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  202593. {
  202594. OSVERSIONINFO info;
  202595. info.dwOSVersionInfoSize = sizeof (info);
  202596. GetVersionEx (&info);
  202597. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  202598. {
  202599. switch (info.dwMajorVersion)
  202600. {
  202601. case 5: return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  202602. case 6: return (info.dwMinorVersion == 0) ? WinVista : Windows7;
  202603. default: jassertfalse; break; // !! not a supported OS!
  202604. }
  202605. }
  202606. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  202607. {
  202608. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  202609. return Win98;
  202610. }
  202611. return UnknownOS;
  202612. }
  202613. const String SystemStats::getOperatingSystemName()
  202614. {
  202615. const char* name = "Unknown OS";
  202616. switch (getOperatingSystemType())
  202617. {
  202618. case Windows7: name = "Windows 7"; break;
  202619. case WinVista: name = "Windows Vista"; break;
  202620. case WinXP: name = "Windows XP"; break;
  202621. case Win2000: name = "Windows 2000"; break;
  202622. case Win98: name = "Windows 98"; break;
  202623. default: jassertfalse; break; // !! new type of OS?
  202624. }
  202625. return name;
  202626. }
  202627. bool SystemStats::isOperatingSystem64Bit()
  202628. {
  202629. #ifdef _WIN64
  202630. return true;
  202631. #else
  202632. typedef BOOL (WINAPI* LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  202633. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  202634. BOOL isWow64 = FALSE;
  202635. return (fnIsWow64Process != 0)
  202636. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  202637. && (isWow64 != FALSE);
  202638. #endif
  202639. }
  202640. int SystemStats::getMemorySizeInMegabytes()
  202641. {
  202642. MEMORYSTATUSEX mem;
  202643. mem.dwLength = sizeof (mem);
  202644. GlobalMemoryStatusEx (&mem);
  202645. return (int) (mem.ullTotalPhys / (1024 * 1024)) + 1;
  202646. }
  202647. uint32 juce_millisecondsSinceStartup() throw()
  202648. {
  202649. return (uint32) GetTickCount();
  202650. }
  202651. int64 Time::getHighResolutionTicks() throw()
  202652. {
  202653. LARGE_INTEGER ticks;
  202654. QueryPerformanceCounter (&ticks);
  202655. const int64 mainCounterAsHiResTicks = (GetTickCount() * hiResTicksPerSecond) / 1000;
  202656. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  202657. // fix for a very obscure PCI hardware bug that can make the counter
  202658. // sometimes jump forwards by a few seconds..
  202659. static int64 hiResTicksOffset = 0;
  202660. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  202661. if (offsetDrift > (hiResTicksPerSecond >> 1))
  202662. hiResTicksOffset = newOffset;
  202663. return ticks.QuadPart + hiResTicksOffset;
  202664. }
  202665. double Time::getMillisecondCounterHiRes() throw()
  202666. {
  202667. return getHighResolutionTicks() * hiResTicksScaleFactor;
  202668. }
  202669. int64 Time::getHighResolutionTicksPerSecond() throw()
  202670. {
  202671. return hiResTicksPerSecond;
  202672. }
  202673. static int64 juce_getClockCycleCounter() throw()
  202674. {
  202675. #if JUCE_USE_INTRINSICS
  202676. // MS intrinsics version...
  202677. return __rdtsc();
  202678. #elif JUCE_GCC
  202679. // GNU inline asm version...
  202680. unsigned int hi = 0, lo = 0;
  202681. __asm__ __volatile__ (
  202682. "xor %%eax, %%eax \n\
  202683. xor %%edx, %%edx \n\
  202684. rdtsc \n\
  202685. movl %%eax, %[lo] \n\
  202686. movl %%edx, %[hi]"
  202687. :
  202688. : [hi] "m" (hi),
  202689. [lo] "m" (lo)
  202690. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  202691. return (int64) ((((uint64) hi) << 32) | lo);
  202692. #else
  202693. // MSVC inline asm version...
  202694. unsigned int hi = 0, lo = 0;
  202695. __asm
  202696. {
  202697. xor eax, eax
  202698. xor edx, edx
  202699. rdtsc
  202700. mov lo, eax
  202701. mov hi, edx
  202702. }
  202703. return (int64) ((((uint64) hi) << 32) | lo);
  202704. #endif
  202705. }
  202706. int SystemStats::getCpuSpeedInMegaherz()
  202707. {
  202708. const int64 cycles = juce_getClockCycleCounter();
  202709. const uint32 millis = Time::getMillisecondCounter();
  202710. int lastResult = 0;
  202711. for (;;)
  202712. {
  202713. int n = 1000000;
  202714. while (--n > 0) {}
  202715. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  202716. const int64 cyclesNow = juce_getClockCycleCounter();
  202717. if (millisElapsed > 80)
  202718. {
  202719. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  202720. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  202721. return newResult;
  202722. lastResult = newResult;
  202723. }
  202724. }
  202725. }
  202726. bool Time::setSystemTimeToThisTime() const
  202727. {
  202728. SYSTEMTIME st;
  202729. st.wDayOfWeek = 0;
  202730. st.wYear = (WORD) getYear();
  202731. st.wMonth = (WORD) (getMonth() + 1);
  202732. st.wDay = (WORD) getDayOfMonth();
  202733. st.wHour = (WORD) getHours();
  202734. st.wMinute = (WORD) getMinutes();
  202735. st.wSecond = (WORD) getSeconds();
  202736. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  202737. // do this twice because of daylight saving conversion problems - the
  202738. // first one sets it up, the second one kicks it in.
  202739. return SetLocalTime (&st) != 0
  202740. && SetLocalTime (&st) != 0;
  202741. }
  202742. int SystemStats::getPageSize()
  202743. {
  202744. SYSTEM_INFO systemInfo;
  202745. GetSystemInfo (&systemInfo);
  202746. return systemInfo.dwPageSize;
  202747. }
  202748. const String SystemStats::getLogonName()
  202749. {
  202750. TCHAR text [256];
  202751. DWORD len = numElementsInArray (text) - 2;
  202752. zerostruct (text);
  202753. GetUserName (text, &len);
  202754. return String (text, len);
  202755. }
  202756. const String SystemStats::getFullUserName()
  202757. {
  202758. return getLogonName();
  202759. }
  202760. #endif
  202761. /*** End of inlined file: juce_win32_SystemStats.cpp ***/
  202762. /*** Start of inlined file: juce_win32_Threads.cpp ***/
  202763. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  202764. // compiled on its own).
  202765. #if JUCE_INCLUDED_FILE
  202766. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  202767. extern HWND juce_messageWindowHandle;
  202768. #endif
  202769. #if ! JUCE_USE_INTRINSICS
  202770. // In newer compilers, the inline versions of these are used (in juce_Atomic.h), but in
  202771. // older ones we have to actually call the ops as win32 functions..
  202772. long juce_InterlockedExchange (volatile long* a, long b) throw() { return InterlockedExchange (a, b); }
  202773. long juce_InterlockedIncrement (volatile long* a) throw() { return InterlockedIncrement (a); }
  202774. long juce_InterlockedDecrement (volatile long* a) throw() { return InterlockedDecrement (a); }
  202775. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw() { return InterlockedExchangeAdd (a, b); }
  202776. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw() { return InterlockedCompareExchange (a, b, c); }
  202777. __int64 juce_InterlockedCompareExchange64 (volatile __int64* value, __int64 newValue, __int64 valueToCompare) throw()
  202778. {
  202779. jassertfalse; // This operation isn't available in old MS compiler versions!
  202780. __int64 oldValue = *value;
  202781. if (oldValue == valueToCompare)
  202782. *value = newValue;
  202783. return oldValue;
  202784. }
  202785. #endif
  202786. CriticalSection::CriticalSection() throw()
  202787. {
  202788. // (just to check the MS haven't changed this structure and broken things...)
  202789. #if _MSC_VER >= 1400
  202790. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  202791. #else
  202792. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  202793. #endif
  202794. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  202795. }
  202796. CriticalSection::~CriticalSection() throw()
  202797. {
  202798. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  202799. }
  202800. void CriticalSection::enter() const throw()
  202801. {
  202802. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  202803. }
  202804. bool CriticalSection::tryEnter() const throw()
  202805. {
  202806. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  202807. }
  202808. void CriticalSection::exit() const throw()
  202809. {
  202810. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  202811. }
  202812. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  202813. : internal (CreateEvent (0, manualReset ? TRUE : FALSE, FALSE, 0))
  202814. {
  202815. }
  202816. WaitableEvent::~WaitableEvent() throw()
  202817. {
  202818. CloseHandle (internal);
  202819. }
  202820. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  202821. {
  202822. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  202823. }
  202824. void WaitableEvent::signal() const throw()
  202825. {
  202826. SetEvent (internal);
  202827. }
  202828. void WaitableEvent::reset() const throw()
  202829. {
  202830. ResetEvent (internal);
  202831. }
  202832. void JUCE_API juce_threadEntryPoint (void*);
  202833. static unsigned int __stdcall threadEntryProc (void* userData)
  202834. {
  202835. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  202836. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  202837. GetCurrentThreadId(), TRUE);
  202838. #endif
  202839. juce_threadEntryPoint (userData);
  202840. _endthreadex (0);
  202841. return 0;
  202842. }
  202843. void juce_CloseThreadHandle (void* handle)
  202844. {
  202845. CloseHandle ((HANDLE) handle);
  202846. }
  202847. void* juce_createThread (void* userData)
  202848. {
  202849. unsigned int threadId;
  202850. return (void*) _beginthreadex (0, 0, &threadEntryProc, userData, 0, &threadId);
  202851. }
  202852. void juce_killThread (void* handle)
  202853. {
  202854. if (handle != 0)
  202855. {
  202856. #if JUCE_DEBUG
  202857. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  202858. #endif
  202859. TerminateThread (handle, 0);
  202860. }
  202861. }
  202862. void juce_setCurrentThreadName (const String& name)
  202863. {
  202864. #if JUCE_DEBUG && JUCE_MSVC
  202865. struct
  202866. {
  202867. DWORD dwType;
  202868. LPCSTR szName;
  202869. DWORD dwThreadID;
  202870. DWORD dwFlags;
  202871. } info;
  202872. info.dwType = 0x1000;
  202873. info.szName = name.toCString();
  202874. info.dwThreadID = GetCurrentThreadId();
  202875. info.dwFlags = 0;
  202876. __try
  202877. {
  202878. RaiseException (0x406d1388 /*MS_VC_EXCEPTION*/, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  202879. }
  202880. __except (EXCEPTION_CONTINUE_EXECUTION)
  202881. {}
  202882. #else
  202883. (void) name;
  202884. #endif
  202885. }
  202886. Thread::ThreadID Thread::getCurrentThreadId()
  202887. {
  202888. return (ThreadID) (pointer_sized_int) GetCurrentThreadId();
  202889. }
  202890. // priority 1 to 10 where 5=normal, 1=low
  202891. bool juce_setThreadPriority (void* threadHandle, int priority)
  202892. {
  202893. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  202894. if (priority < 1)
  202895. pri = THREAD_PRIORITY_IDLE;
  202896. else if (priority < 2)
  202897. pri = THREAD_PRIORITY_LOWEST;
  202898. else if (priority < 5)
  202899. pri = THREAD_PRIORITY_BELOW_NORMAL;
  202900. else if (priority < 7)
  202901. pri = THREAD_PRIORITY_NORMAL;
  202902. else if (priority < 9)
  202903. pri = THREAD_PRIORITY_ABOVE_NORMAL;
  202904. else if (priority < 10)
  202905. pri = THREAD_PRIORITY_HIGHEST;
  202906. if (threadHandle == 0)
  202907. threadHandle = GetCurrentThread();
  202908. return SetThreadPriority (threadHandle, pri) != FALSE;
  202909. }
  202910. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  202911. {
  202912. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  202913. }
  202914. static HANDLE sleepEvent = 0;
  202915. void juce_initialiseThreadEvents()
  202916. {
  202917. if (sleepEvent == 0)
  202918. #if JUCE_DEBUG
  202919. sleepEvent = CreateEvent (0, 0, 0, _T("Juce Sleep Event"));
  202920. #else
  202921. sleepEvent = CreateEvent (0, 0, 0, 0);
  202922. #endif
  202923. }
  202924. void Thread::yield()
  202925. {
  202926. Sleep (0);
  202927. }
  202928. void JUCE_CALLTYPE Thread::sleep (const int millisecs)
  202929. {
  202930. if (millisecs >= 10)
  202931. {
  202932. Sleep (millisecs);
  202933. }
  202934. else
  202935. {
  202936. jassert (sleepEvent != 0);
  202937. // unlike Sleep() this is guaranteed to return to the current thread after
  202938. // the time expires, so we'll use this for short waits, which are more likely
  202939. // to need to be accurate
  202940. WaitForSingleObject (sleepEvent, millisecs);
  202941. }
  202942. }
  202943. static int lastProcessPriority = -1;
  202944. // called by WindowDriver because Windows does wierd things to process priority
  202945. // when you swap apps, and this forces an update when the app is brought to the front.
  202946. void juce_repeatLastProcessPriority()
  202947. {
  202948. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  202949. {
  202950. DWORD p;
  202951. switch (lastProcessPriority)
  202952. {
  202953. case Process::LowPriority: p = IDLE_PRIORITY_CLASS; break;
  202954. case Process::NormalPriority: p = NORMAL_PRIORITY_CLASS; break;
  202955. case Process::HighPriority: p = HIGH_PRIORITY_CLASS; break;
  202956. case Process::RealtimePriority: p = REALTIME_PRIORITY_CLASS; break;
  202957. default: jassertfalse; return; // bad priority value
  202958. }
  202959. SetPriorityClass (GetCurrentProcess(), p);
  202960. }
  202961. }
  202962. void Process::setPriority (ProcessPriority prior)
  202963. {
  202964. if (lastProcessPriority != (int) prior)
  202965. {
  202966. lastProcessPriority = (int) prior;
  202967. juce_repeatLastProcessPriority();
  202968. }
  202969. }
  202970. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  202971. {
  202972. return IsDebuggerPresent() != FALSE;
  202973. }
  202974. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  202975. {
  202976. return juce_isRunningUnderDebugger();
  202977. }
  202978. void Process::raisePrivilege()
  202979. {
  202980. jassertfalse; // xxx not implemented
  202981. }
  202982. void Process::lowerPrivilege()
  202983. {
  202984. jassertfalse; // xxx not implemented
  202985. }
  202986. void Process::terminate()
  202987. {
  202988. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  202989. _CrtDumpMemoryLeaks();
  202990. #endif
  202991. // bullet in the head in case there's a problem shutting down..
  202992. ExitProcess (0);
  202993. }
  202994. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  202995. {
  202996. void* result = 0;
  202997. JUCE_TRY
  202998. {
  202999. result = LoadLibrary (name);
  203000. }
  203001. JUCE_CATCH_ALL
  203002. return result;
  203003. }
  203004. void PlatformUtilities::freeDynamicLibrary (void* h)
  203005. {
  203006. JUCE_TRY
  203007. {
  203008. if (h != 0)
  203009. FreeLibrary ((HMODULE) h);
  203010. }
  203011. JUCE_CATCH_ALL
  203012. }
  203013. void* PlatformUtilities::getProcedureEntryPoint (void* h, const String& name)
  203014. {
  203015. return (h != 0) ? GetProcAddress ((HMODULE) h, name.toCString()) : 0;
  203016. }
  203017. class InterProcessLock::Pimpl
  203018. {
  203019. public:
  203020. Pimpl (const String& name, const int timeOutMillisecs)
  203021. : handle (0), refCount (1)
  203022. {
  203023. handle = CreateMutex (0, TRUE, "Global\\" + name.replaceCharacter ('\\','/'));
  203024. if (handle != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  203025. {
  203026. if (timeOutMillisecs == 0)
  203027. {
  203028. close();
  203029. return;
  203030. }
  203031. switch (WaitForSingleObject (handle, timeOutMillisecs < 0 ? INFINITE : timeOutMillisecs))
  203032. {
  203033. case WAIT_OBJECT_0:
  203034. case WAIT_ABANDONED:
  203035. break;
  203036. case WAIT_TIMEOUT:
  203037. default:
  203038. close();
  203039. break;
  203040. }
  203041. }
  203042. }
  203043. ~Pimpl()
  203044. {
  203045. close();
  203046. }
  203047. void close()
  203048. {
  203049. if (handle != 0)
  203050. {
  203051. ReleaseMutex (handle);
  203052. CloseHandle (handle);
  203053. handle = 0;
  203054. }
  203055. }
  203056. HANDLE handle;
  203057. int refCount;
  203058. };
  203059. InterProcessLock::InterProcessLock (const String& name_)
  203060. : name (name_)
  203061. {
  203062. }
  203063. InterProcessLock::~InterProcessLock()
  203064. {
  203065. }
  203066. bool InterProcessLock::enter (const int timeOutMillisecs)
  203067. {
  203068. const ScopedLock sl (lock);
  203069. if (pimpl == 0)
  203070. {
  203071. pimpl = new Pimpl (name, timeOutMillisecs);
  203072. if (pimpl->handle == 0)
  203073. pimpl = 0;
  203074. }
  203075. else
  203076. {
  203077. pimpl->refCount++;
  203078. }
  203079. return pimpl != 0;
  203080. }
  203081. void InterProcessLock::exit()
  203082. {
  203083. const ScopedLock sl (lock);
  203084. // Trying to release the lock too many times!
  203085. jassert (pimpl != 0);
  203086. if (pimpl != 0 && --(pimpl->refCount) == 0)
  203087. pimpl = 0;
  203088. }
  203089. #endif
  203090. /*** End of inlined file: juce_win32_Threads.cpp ***/
  203091. /*** Start of inlined file: juce_win32_Files.cpp ***/
  203092. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203093. // compiled on its own).
  203094. #if JUCE_INCLUDED_FILE
  203095. #ifndef CSIDL_MYMUSIC
  203096. #define CSIDL_MYMUSIC 0x000d
  203097. #endif
  203098. #ifndef CSIDL_MYVIDEO
  203099. #define CSIDL_MYVIDEO 0x000e
  203100. #endif
  203101. #ifndef INVALID_FILE_ATTRIBUTES
  203102. #define INVALID_FILE_ATTRIBUTES ((DWORD) -1)
  203103. #endif
  203104. const juce_wchar File::separator = '\\';
  203105. const String File::separatorString ("\\");
  203106. bool File::exists() const
  203107. {
  203108. return fullPath.isNotEmpty()
  203109. && GetFileAttributes (fullPath) != INVALID_FILE_ATTRIBUTES;
  203110. }
  203111. bool File::existsAsFile() const
  203112. {
  203113. return fullPath.isNotEmpty()
  203114. && (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_DIRECTORY) == 0;
  203115. }
  203116. bool File::isDirectory() const
  203117. {
  203118. const DWORD attr = GetFileAttributes (fullPath);
  203119. return ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) && (attr != INVALID_FILE_ATTRIBUTES);
  203120. }
  203121. bool File::hasWriteAccess() const
  203122. {
  203123. if (exists())
  203124. return (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_READONLY) == 0;
  203125. // on windows, it seems that even read-only directories can still be written into,
  203126. // so checking the parent directory's permissions would return the wrong result..
  203127. return true;
  203128. }
  203129. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  203130. {
  203131. DWORD attr = GetFileAttributes (fullPath);
  203132. if (attr == INVALID_FILE_ATTRIBUTES)
  203133. return false;
  203134. if (shouldBeReadOnly == ((attr & FILE_ATTRIBUTE_READONLY) != 0))
  203135. return true;
  203136. if (shouldBeReadOnly)
  203137. attr |= FILE_ATTRIBUTE_READONLY;
  203138. else
  203139. attr &= ~FILE_ATTRIBUTE_READONLY;
  203140. return SetFileAttributes (fullPath, attr) != FALSE;
  203141. }
  203142. bool File::isHidden() const
  203143. {
  203144. return (GetFileAttributes (getFullPathName()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  203145. }
  203146. bool File::deleteFile() const
  203147. {
  203148. if (! exists())
  203149. return true;
  203150. else if (isDirectory())
  203151. return RemoveDirectory (fullPath) != 0;
  203152. else
  203153. return DeleteFile (fullPath) != 0;
  203154. }
  203155. bool File::moveToTrash() const
  203156. {
  203157. if (! exists())
  203158. return true;
  203159. SHFILEOPSTRUCT fos;
  203160. zerostruct (fos);
  203161. // The string we pass in must be double null terminated..
  203162. String doubleNullTermPath (getFullPathName() + " ");
  203163. TCHAR* const p = const_cast <TCHAR*> (static_cast <const TCHAR*> (doubleNullTermPath));
  203164. p [getFullPathName().length()] = 0;
  203165. fos.wFunc = FO_DELETE;
  203166. fos.pFrom = p;
  203167. fos.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION
  203168. | FOF_NOCONFIRMMKDIR | FOF_RENAMEONCOLLISION;
  203169. return SHFileOperation (&fos) == 0;
  203170. }
  203171. bool File::copyInternal (const File& dest) const
  203172. {
  203173. return CopyFile (fullPath, dest.getFullPathName(), false) != 0;
  203174. }
  203175. bool File::moveInternal (const File& dest) const
  203176. {
  203177. return MoveFile (fullPath, dest.getFullPathName()) != 0;
  203178. }
  203179. void File::createDirectoryInternal (const String& fileName) const
  203180. {
  203181. CreateDirectory (fileName, 0);
  203182. }
  203183. // return 0 if not possible
  203184. void* juce_fileOpen (const File& file, bool forWriting)
  203185. {
  203186. HANDLE h;
  203187. if (forWriting)
  203188. {
  203189. h = CreateFile (file.getFullPathName(), GENERIC_WRITE, FILE_SHARE_READ, 0,
  203190. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  203191. if (h != INVALID_HANDLE_VALUE)
  203192. SetFilePointer (h, 0, 0, FILE_END);
  203193. else
  203194. h = 0;
  203195. }
  203196. else
  203197. {
  203198. h = CreateFile (file.getFullPathName(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  203199. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  203200. if (h == INVALID_HANDLE_VALUE)
  203201. h = 0;
  203202. }
  203203. return h;
  203204. }
  203205. void juce_fileClose (void* handle)
  203206. {
  203207. CloseHandle (handle);
  203208. }
  203209. int juce_fileRead (void* handle, void* buffer, int size)
  203210. {
  203211. DWORD num = 0;
  203212. ReadFile ((HANDLE) handle, buffer, size, &num, 0);
  203213. return (int) num;
  203214. }
  203215. int juce_fileWrite (void* handle, const void* buffer, int size)
  203216. {
  203217. DWORD num;
  203218. WriteFile ((HANDLE) handle, buffer, size, &num, 0);
  203219. return (int) num;
  203220. }
  203221. int64 juce_fileSetPosition (void* handle, int64 pos)
  203222. {
  203223. LARGE_INTEGER li;
  203224. li.QuadPart = pos;
  203225. li.LowPart = SetFilePointer ((HANDLE) handle, li.LowPart, &li.HighPart, FILE_BEGIN); // (returns -1 if it fails)
  203226. return li.QuadPart;
  203227. }
  203228. int64 FileOutputStream::getPositionInternal() const
  203229. {
  203230. if (fileHandle == 0)
  203231. return -1;
  203232. LARGE_INTEGER li;
  203233. li.QuadPart = 0;
  203234. li.LowPart = SetFilePointer ((HANDLE) fileHandle, 0, &li.HighPart, FILE_CURRENT); // (returns -1 if it fails)
  203235. return jmax ((int64) 0, li.QuadPart);
  203236. }
  203237. void FileOutputStream::flushInternal()
  203238. {
  203239. if (fileHandle != 0)
  203240. FlushFileBuffers ((HANDLE) fileHandle);
  203241. }
  203242. int64 File::getSize() const
  203243. {
  203244. WIN32_FILE_ATTRIBUTE_DATA attributes;
  203245. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  203246. return (((int64) attributes.nFileSizeHigh) << 32) | attributes.nFileSizeLow;
  203247. return 0;
  203248. }
  203249. static int64 fileTimeToTime (const FILETIME* const ft)
  203250. {
  203251. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME)); // tell me if this fails!
  203252. return (reinterpret_cast<const ULARGE_INTEGER*> (ft)->QuadPart - literal64bit (116444736000000000)) / 10000;
  203253. }
  203254. static void timeToFileTime (const int64 time, FILETIME* const ft)
  203255. {
  203256. reinterpret_cast<ULARGE_INTEGER*> (ft)->QuadPart = time * 10000 + literal64bit (116444736000000000);
  203257. }
  203258. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  203259. {
  203260. WIN32_FILE_ATTRIBUTE_DATA attributes;
  203261. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  203262. {
  203263. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  203264. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  203265. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  203266. }
  203267. else
  203268. {
  203269. creationTime = accessTime = modificationTime = 0;
  203270. }
  203271. }
  203272. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const
  203273. {
  203274. void* const h = juce_fileOpen (fullPath, true);
  203275. bool ok = false;
  203276. if (h != 0)
  203277. {
  203278. FILETIME m, a, c;
  203279. timeToFileTime (modificationTime, &m);
  203280. timeToFileTime (accessTime, &a);
  203281. timeToFileTime (creationTime, &c);
  203282. ok = SetFileTime ((HANDLE) h,
  203283. creationTime > 0 ? &c : 0,
  203284. accessTime > 0 ? &a : 0,
  203285. modificationTime > 0 ? &m : 0) != 0;
  203286. juce_fileClose (h);
  203287. }
  203288. return ok;
  203289. }
  203290. void File::findFileSystemRoots (Array<File>& destArray)
  203291. {
  203292. TCHAR buffer [2048];
  203293. buffer[0] = 0;
  203294. buffer[1] = 0;
  203295. GetLogicalDriveStrings (2048, buffer);
  203296. const TCHAR* n = buffer;
  203297. StringArray roots;
  203298. while (*n != 0)
  203299. {
  203300. roots.add (String (n));
  203301. while (*n++ != 0)
  203302. {}
  203303. }
  203304. roots.sort (true);
  203305. for (int i = 0; i < roots.size(); ++i)
  203306. destArray.add (roots [i]);
  203307. }
  203308. static const String getDriveFromPath (const String& path)
  203309. {
  203310. if (path.isNotEmpty() && path[1] == ':')
  203311. return path.substring (0, 2) + '\\';
  203312. return path;
  203313. }
  203314. const String File::getVolumeLabel() const
  203315. {
  203316. TCHAR dest[64];
  203317. if (! GetVolumeInformation (getDriveFromPath (getFullPathName()), dest,
  203318. numElementsInArray (dest), 0, 0, 0, 0, 0))
  203319. dest[0] = 0;
  203320. return dest;
  203321. }
  203322. int File::getVolumeSerialNumber() const
  203323. {
  203324. TCHAR dest[64];
  203325. DWORD serialNum;
  203326. if (! GetVolumeInformation (getDriveFromPath (getFullPathName()), dest,
  203327. numElementsInArray (dest), &serialNum, 0, 0, 0, 0))
  203328. return 0;
  203329. return (int) serialNum;
  203330. }
  203331. static int64 getDiskSpaceInfo (const String& path, const bool total)
  203332. {
  203333. ULARGE_INTEGER spc, tot, totFree;
  203334. if (GetDiskFreeSpaceEx (getDriveFromPath (path), &spc, &tot, &totFree))
  203335. return total ? (int64) tot.QuadPart
  203336. : (int64) spc.QuadPart;
  203337. return 0;
  203338. }
  203339. int64 File::getBytesFreeOnVolume() const
  203340. {
  203341. return getDiskSpaceInfo (getFullPathName(), false);
  203342. }
  203343. int64 File::getVolumeTotalSize() const
  203344. {
  203345. return getDiskSpaceInfo (getFullPathName(), true);
  203346. }
  203347. static unsigned int getWindowsDriveType (const String& path)
  203348. {
  203349. return GetDriveType (getDriveFromPath (path));
  203350. }
  203351. bool File::isOnCDRomDrive() const
  203352. {
  203353. return getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  203354. }
  203355. bool File::isOnHardDisk() const
  203356. {
  203357. if (fullPath.isEmpty())
  203358. return false;
  203359. const unsigned int n = getWindowsDriveType (getFullPathName());
  203360. if (fullPath.toLowerCase()[0] <= 'b' && fullPath[1] == ':')
  203361. return n != DRIVE_REMOVABLE;
  203362. else
  203363. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  203364. }
  203365. bool File::isOnRemovableDrive() const
  203366. {
  203367. if (fullPath.isEmpty())
  203368. return false;
  203369. const unsigned int n = getWindowsDriveType (getFullPathName());
  203370. return n == DRIVE_CDROM
  203371. || n == DRIVE_REMOTE
  203372. || n == DRIVE_REMOVABLE
  203373. || n == DRIVE_RAMDISK;
  203374. }
  203375. static const File juce_getSpecialFolderPath (int type)
  203376. {
  203377. WCHAR path [MAX_PATH + 256];
  203378. if (SHGetSpecialFolderPath (0, path, type, FALSE))
  203379. return File (String (path));
  203380. return File::nonexistent;
  203381. }
  203382. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  203383. {
  203384. int csidlType = 0;
  203385. switch (type)
  203386. {
  203387. case userHomeDirectory: csidlType = CSIDL_PROFILE; break;
  203388. case userDocumentsDirectory: csidlType = CSIDL_PERSONAL; break;
  203389. case userDesktopDirectory: csidlType = CSIDL_DESKTOP; break;
  203390. case userApplicationDataDirectory: csidlType = CSIDL_APPDATA; break;
  203391. case commonApplicationDataDirectory: csidlType = CSIDL_COMMON_APPDATA; break;
  203392. case globalApplicationsDirectory: csidlType = CSIDL_PROGRAM_FILES; break;
  203393. case userMusicDirectory: csidlType = CSIDL_MYMUSIC; break;
  203394. case userMoviesDirectory: csidlType = CSIDL_MYVIDEO; break;
  203395. case tempDirectory:
  203396. {
  203397. WCHAR dest [2048];
  203398. dest[0] = 0;
  203399. GetTempPath (numElementsInArray (dest), dest);
  203400. return File (String (dest));
  203401. }
  203402. case invokedExecutableFile:
  203403. case currentExecutableFile:
  203404. case currentApplicationFile:
  203405. {
  203406. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  203407. WCHAR dest [MAX_PATH + 256];
  203408. dest[0] = 0;
  203409. GetModuleFileName (moduleHandle, dest, numElementsInArray (dest));
  203410. return File (String (dest));
  203411. }
  203412. break;
  203413. default:
  203414. jassertfalse; // unknown type?
  203415. return File::nonexistent;
  203416. }
  203417. return juce_getSpecialFolderPath (csidlType);
  203418. }
  203419. const File File::getCurrentWorkingDirectory()
  203420. {
  203421. WCHAR dest [MAX_PATH + 256];
  203422. dest[0] = 0;
  203423. GetCurrentDirectory (numElementsInArray (dest), dest);
  203424. return File (String (dest));
  203425. }
  203426. bool File::setAsCurrentWorkingDirectory() const
  203427. {
  203428. return SetCurrentDirectory (getFullPathName()) != FALSE;
  203429. }
  203430. const String File::getVersion() const
  203431. {
  203432. String result;
  203433. DWORD handle = 0;
  203434. DWORD bufferSize = GetFileVersionInfoSize (getFullPathName(), &handle);
  203435. HeapBlock<char> buffer;
  203436. buffer.calloc (bufferSize);
  203437. if (GetFileVersionInfo (getFullPathName(), 0, bufferSize, buffer))
  203438. {
  203439. VS_FIXEDFILEINFO* vffi;
  203440. UINT len = 0;
  203441. if (VerQueryValue (buffer, (LPTSTR) _T("\\"), (LPVOID*) &vffi, &len))
  203442. {
  203443. result << (int) HIWORD (vffi->dwFileVersionMS) << '.'
  203444. << (int) LOWORD (vffi->dwFileVersionMS) << '.'
  203445. << (int) HIWORD (vffi->dwFileVersionLS) << '.'
  203446. << (int) LOWORD (vffi->dwFileVersionLS);
  203447. }
  203448. }
  203449. return result;
  203450. }
  203451. const File File::getLinkedTarget() const
  203452. {
  203453. File result (*this);
  203454. String p (getFullPathName());
  203455. if (! exists())
  203456. p += ".lnk";
  203457. else if (getFileExtension() != ".lnk")
  203458. return result;
  203459. ComSmartPtr <IShellLink> shellLink;
  203460. if (SUCCEEDED (shellLink.CoCreateInstance (CLSID_ShellLink)))
  203461. {
  203462. ComSmartPtr <IPersistFile> persistFile;
  203463. if (SUCCEEDED (shellLink->QueryInterface (IID_IPersistFile, (LPVOID*) &persistFile)))
  203464. {
  203465. if (SUCCEEDED (persistFile->Load ((const WCHAR*) p, STGM_READ))
  203466. && SUCCEEDED (shellLink->Resolve (0, SLR_ANY_MATCH | SLR_NO_UI)))
  203467. {
  203468. WIN32_FIND_DATA winFindData;
  203469. WCHAR resolvedPath [MAX_PATH];
  203470. if (SUCCEEDED (shellLink->GetPath (resolvedPath, MAX_PATH, &winFindData, SLGP_UNCPRIORITY)))
  203471. result = File (resolvedPath);
  203472. }
  203473. }
  203474. }
  203475. return result;
  203476. }
  203477. class DirectoryIterator::NativeIterator::Pimpl
  203478. {
  203479. public:
  203480. Pimpl (const File& directory, const String& wildCard)
  203481. : directoryWithWildCard (File::addTrailingSeparator (directory.getFullPathName()) + wildCard),
  203482. handle (INVALID_HANDLE_VALUE)
  203483. {
  203484. }
  203485. ~Pimpl()
  203486. {
  203487. if (handle != INVALID_HANDLE_VALUE)
  203488. FindClose (handle);
  203489. }
  203490. bool next (String& filenameFound,
  203491. bool* const isDir, bool* const isHidden, int64* const fileSize,
  203492. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  203493. {
  203494. WIN32_FIND_DATA findData;
  203495. if (handle == INVALID_HANDLE_VALUE)
  203496. {
  203497. handle = FindFirstFile (directoryWithWildCard, &findData);
  203498. if (handle == INVALID_HANDLE_VALUE)
  203499. return false;
  203500. }
  203501. else
  203502. {
  203503. if (FindNextFile (handle, &findData) == 0)
  203504. return false;
  203505. }
  203506. filenameFound = findData.cFileName;
  203507. if (isDir != 0) *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  203508. if (isHidden != 0) *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  203509. if (fileSize != 0) *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  203510. if (modTime != 0) *modTime = fileTimeToTime (&findData.ftLastWriteTime);
  203511. if (creationTime != 0) *creationTime = fileTimeToTime (&findData.ftCreationTime);
  203512. if (isReadOnly != 0) *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  203513. return true;
  203514. }
  203515. juce_UseDebuggingNewOperator
  203516. private:
  203517. const String directoryWithWildCard;
  203518. HANDLE handle;
  203519. Pimpl (const Pimpl&);
  203520. Pimpl& operator= (const Pimpl&);
  203521. };
  203522. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  203523. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  203524. {
  203525. }
  203526. DirectoryIterator::NativeIterator::~NativeIterator()
  203527. {
  203528. }
  203529. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  203530. bool* const isDir, bool* const isHidden, int64* const fileSize,
  203531. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  203532. {
  203533. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  203534. }
  203535. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  203536. {
  203537. HINSTANCE hInstance = 0;
  203538. JUCE_TRY
  203539. {
  203540. hInstance = ShellExecute (0, 0, fileName, parameters, 0, SW_SHOWDEFAULT);
  203541. }
  203542. JUCE_CATCH_ALL
  203543. return hInstance > (HINSTANCE) 32;
  203544. }
  203545. void File::revealToUser() const
  203546. {
  203547. if (isDirectory())
  203548. startAsProcess();
  203549. else if (getParentDirectory().exists())
  203550. getParentDirectory().startAsProcess();
  203551. }
  203552. class NamedPipeInternal
  203553. {
  203554. public:
  203555. NamedPipeInternal (const String& file, const bool isPipe_)
  203556. : pipeH (0),
  203557. cancelEvent (0),
  203558. connected (false),
  203559. isPipe (isPipe_)
  203560. {
  203561. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  203562. pipeH = isPipe ? CreateNamedPipe (file, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  203563. PIPE_UNLIMITED_INSTANCES, 4096, 4096, 0, 0)
  203564. : CreateFile (file, GENERIC_READ | GENERIC_WRITE, 0, 0,
  203565. OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
  203566. }
  203567. ~NamedPipeInternal()
  203568. {
  203569. disconnectPipe();
  203570. if (pipeH != 0)
  203571. CloseHandle (pipeH);
  203572. CloseHandle (cancelEvent);
  203573. }
  203574. bool connect (const int timeOutMs)
  203575. {
  203576. if (! isPipe)
  203577. return true;
  203578. if (! connected)
  203579. {
  203580. OVERLAPPED over;
  203581. zerostruct (over);
  203582. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  203583. if (ConnectNamedPipe (pipeH, &over))
  203584. {
  203585. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  203586. }
  203587. else
  203588. {
  203589. const int err = GetLastError();
  203590. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  203591. {
  203592. HANDLE handles[] = { over.hEvent, cancelEvent };
  203593. if (WaitForMultipleObjects (2, handles, FALSE,
  203594. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  203595. connected = true;
  203596. }
  203597. else if (err == ERROR_PIPE_CONNECTED)
  203598. {
  203599. connected = true;
  203600. }
  203601. }
  203602. CloseHandle (over.hEvent);
  203603. }
  203604. return connected;
  203605. }
  203606. void disconnectPipe()
  203607. {
  203608. if (connected)
  203609. {
  203610. DisconnectNamedPipe (pipeH);
  203611. connected = false;
  203612. }
  203613. }
  203614. HANDLE pipeH;
  203615. HANDLE cancelEvent;
  203616. bool connected, isPipe;
  203617. };
  203618. void NamedPipe::close()
  203619. {
  203620. cancelPendingReads();
  203621. const ScopedLock sl (lock);
  203622. delete static_cast<NamedPipeInternal*> (internal);
  203623. internal = 0;
  203624. }
  203625. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  203626. {
  203627. close();
  203628. ScopedPointer<NamedPipeInternal> intern (new NamedPipeInternal ("\\\\.\\pipe\\" + pipeName, createPipe));
  203629. if (intern->pipeH != INVALID_HANDLE_VALUE)
  203630. {
  203631. internal = intern.release();
  203632. return true;
  203633. }
  203634. return false;
  203635. }
  203636. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  203637. {
  203638. const ScopedLock sl (lock);
  203639. int bytesRead = -1;
  203640. bool waitAgain = true;
  203641. while (waitAgain && internal != 0)
  203642. {
  203643. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  203644. waitAgain = false;
  203645. if (! intern->connect (timeOutMilliseconds))
  203646. break;
  203647. if (maxBytesToRead <= 0)
  203648. return 0;
  203649. OVERLAPPED over;
  203650. zerostruct (over);
  203651. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  203652. unsigned long numRead;
  203653. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  203654. {
  203655. bytesRead = (int) numRead;
  203656. }
  203657. else if (GetLastError() == ERROR_IO_PENDING)
  203658. {
  203659. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  203660. DWORD waitResult = WaitForMultipleObjects (2, handles, FALSE,
  203661. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  203662. : INFINITE);
  203663. if (waitResult != WAIT_OBJECT_0)
  203664. {
  203665. // if the operation timed out, let's cancel it...
  203666. CancelIo (intern->pipeH);
  203667. WaitForSingleObject (over.hEvent, INFINITE); // makes sure cancel is complete
  203668. }
  203669. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  203670. {
  203671. bytesRead = (int) numRead;
  203672. }
  203673. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  203674. {
  203675. intern->disconnectPipe();
  203676. waitAgain = true;
  203677. }
  203678. }
  203679. else
  203680. {
  203681. waitAgain = internal != 0;
  203682. Sleep (5);
  203683. }
  203684. CloseHandle (over.hEvent);
  203685. }
  203686. return bytesRead;
  203687. }
  203688. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  203689. {
  203690. int bytesWritten = -1;
  203691. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  203692. if (intern != 0 && intern->connect (timeOutMilliseconds))
  203693. {
  203694. if (numBytesToWrite <= 0)
  203695. return 0;
  203696. OVERLAPPED over;
  203697. zerostruct (over);
  203698. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  203699. unsigned long numWritten;
  203700. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  203701. {
  203702. bytesWritten = (int) numWritten;
  203703. }
  203704. else if (GetLastError() == ERROR_IO_PENDING)
  203705. {
  203706. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  203707. DWORD waitResult;
  203708. waitResult = WaitForMultipleObjects (2, handles, FALSE,
  203709. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  203710. : INFINITE);
  203711. if (waitResult != WAIT_OBJECT_0)
  203712. {
  203713. CancelIo (intern->pipeH);
  203714. WaitForSingleObject (over.hEvent, INFINITE);
  203715. }
  203716. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  203717. {
  203718. bytesWritten = (int) numWritten;
  203719. }
  203720. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  203721. {
  203722. intern->disconnectPipe();
  203723. }
  203724. }
  203725. CloseHandle (over.hEvent);
  203726. }
  203727. return bytesWritten;
  203728. }
  203729. void NamedPipe::cancelPendingReads()
  203730. {
  203731. if (internal != 0)
  203732. SetEvent (static_cast<NamedPipeInternal*> (internal)->cancelEvent);
  203733. }
  203734. #endif
  203735. /*** End of inlined file: juce_win32_Files.cpp ***/
  203736. /*** Start of inlined file: juce_win32_Network.cpp ***/
  203737. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203738. // compiled on its own).
  203739. #if JUCE_INCLUDED_FILE
  203740. #ifndef INTERNET_FLAG_NEED_FILE
  203741. #define INTERNET_FLAG_NEED_FILE 0x00000010
  203742. #endif
  203743. #ifndef INTERNET_OPTION_DISABLE_AUTODIAL
  203744. #define INTERNET_OPTION_DISABLE_AUTODIAL 70
  203745. #endif
  203746. struct ConnectionAndRequestStruct
  203747. {
  203748. HINTERNET connection, request;
  203749. };
  203750. static HINTERNET sessionHandle = 0;
  203751. #ifndef WORKAROUND_TIMEOUT_BUG
  203752. //#define WORKAROUND_TIMEOUT_BUG 1
  203753. #endif
  203754. #if WORKAROUND_TIMEOUT_BUG
  203755. // Required because of a Microsoft bug in setting a timeout
  203756. class InternetConnectThread : public Thread
  203757. {
  203758. public:
  203759. InternetConnectThread (URL_COMPONENTS& uc_, HINTERNET& connection_, const bool isFtp_)
  203760. : Thread ("Internet"), uc (uc_), connection (connection_), isFtp (isFtp_)
  203761. {
  203762. startThread();
  203763. }
  203764. ~InternetConnectThread()
  203765. {
  203766. stopThread (60000);
  203767. }
  203768. void run()
  203769. {
  203770. connection = InternetConnect (sessionHandle, uc.lpszHostName,
  203771. uc.nPort, _T(""), _T(""),
  203772. isFtp ? INTERNET_SERVICE_FTP
  203773. : INTERNET_SERVICE_HTTP,
  203774. 0, 0);
  203775. notify();
  203776. }
  203777. juce_UseDebuggingNewOperator
  203778. private:
  203779. URL_COMPONENTS& uc;
  203780. HINTERNET& connection;
  203781. const bool isFtp;
  203782. InternetConnectThread (const InternetConnectThread&);
  203783. InternetConnectThread& operator= (const InternetConnectThread&);
  203784. };
  203785. #endif
  203786. void* juce_openInternetFile (const String& url,
  203787. const String& headers,
  203788. const MemoryBlock& postData,
  203789. const bool isPost,
  203790. URL::OpenStreamProgressCallback* callback,
  203791. void* callbackContext,
  203792. int timeOutMs)
  203793. {
  203794. if (sessionHandle == 0)
  203795. sessionHandle = InternetOpen (_T("juce"),
  203796. INTERNET_OPEN_TYPE_PRECONFIG,
  203797. 0, 0, 0);
  203798. if (sessionHandle != 0)
  203799. {
  203800. // break up the url..
  203801. TCHAR file[1024], server[1024];
  203802. URL_COMPONENTS uc;
  203803. zerostruct (uc);
  203804. uc.dwStructSize = sizeof (uc);
  203805. uc.dwUrlPathLength = sizeof (file);
  203806. uc.dwHostNameLength = sizeof (server);
  203807. uc.lpszUrlPath = file;
  203808. uc.lpszHostName = server;
  203809. if (InternetCrackUrl (url, 0, 0, &uc))
  203810. {
  203811. int disable = 1;
  203812. InternetSetOption (sessionHandle, INTERNET_OPTION_DISABLE_AUTODIAL, &disable, sizeof (disable));
  203813. if (timeOutMs == 0)
  203814. timeOutMs = 30000;
  203815. else if (timeOutMs < 0)
  203816. timeOutMs = -1;
  203817. InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));
  203818. const bool isFtp = url.startsWithIgnoreCase ("ftp:");
  203819. #if WORKAROUND_TIMEOUT_BUG
  203820. HINTERNET connection = 0;
  203821. {
  203822. InternetConnectThread connectThread (uc, connection, isFtp);
  203823. connectThread.wait (timeOutMs);
  203824. if (connection == 0)
  203825. {
  203826. InternetCloseHandle (sessionHandle);
  203827. sessionHandle = 0;
  203828. }
  203829. }
  203830. #else
  203831. HINTERNET connection = InternetConnect (sessionHandle,
  203832. uc.lpszHostName,
  203833. uc.nPort,
  203834. _T(""), _T(""),
  203835. isFtp ? INTERNET_SERVICE_FTP
  203836. : INTERNET_SERVICE_HTTP,
  203837. 0, 0);
  203838. #endif
  203839. if (connection != 0)
  203840. {
  203841. if (isFtp)
  203842. {
  203843. HINTERNET request = FtpOpenFile (connection,
  203844. uc.lpszUrlPath,
  203845. GENERIC_READ,
  203846. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE,
  203847. 0);
  203848. ConnectionAndRequestStruct* const result = new ConnectionAndRequestStruct();
  203849. result->connection = connection;
  203850. result->request = request;
  203851. return result;
  203852. }
  203853. else
  203854. {
  203855. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  203856. DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_COOKIES;
  203857. if (url.startsWithIgnoreCase ("https:"))
  203858. flags |= INTERNET_FLAG_SECURE; // (this flag only seems necessary if the OS is running IE6 -
  203859. // IE7 seems to automatically work out when it's https)
  203860. HINTERNET request = HttpOpenRequest (connection,
  203861. isPost ? _T("POST")
  203862. : _T("GET"),
  203863. uc.lpszUrlPath,
  203864. 0, 0, mimeTypes, flags, 0);
  203865. if (request != 0)
  203866. {
  203867. INTERNET_BUFFERS buffers;
  203868. zerostruct (buffers);
  203869. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  203870. buffers.lpcszHeader = (LPCTSTR) headers;
  203871. buffers.dwHeadersLength = headers.length();
  203872. buffers.dwBufferTotal = (DWORD) postData.getSize();
  203873. ConnectionAndRequestStruct* result = 0;
  203874. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  203875. {
  203876. int bytesSent = 0;
  203877. for (;;)
  203878. {
  203879. const int bytesToDo = jmin (1024, (int) postData.getSize() - bytesSent);
  203880. DWORD bytesDone = 0;
  203881. if (bytesToDo > 0
  203882. && ! InternetWriteFile (request,
  203883. static_cast <const char*> (postData.getData()) + bytesSent,
  203884. bytesToDo, &bytesDone))
  203885. {
  203886. break;
  203887. }
  203888. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  203889. {
  203890. result = new ConnectionAndRequestStruct();
  203891. result->connection = connection;
  203892. result->request = request;
  203893. if (! HttpEndRequest (request, 0, 0, 0))
  203894. break;
  203895. return result;
  203896. }
  203897. bytesSent += bytesDone;
  203898. if (callback != 0 && ! callback (callbackContext, bytesSent, postData.getSize()))
  203899. break;
  203900. }
  203901. }
  203902. InternetCloseHandle (request);
  203903. }
  203904. InternetCloseHandle (connection);
  203905. }
  203906. }
  203907. }
  203908. }
  203909. return 0;
  203910. }
  203911. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  203912. {
  203913. DWORD bytesRead = 0;
  203914. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  203915. if (crs != 0)
  203916. InternetReadFile (crs->request,
  203917. buffer, bytesToRead,
  203918. &bytesRead);
  203919. return bytesRead;
  203920. }
  203921. int juce_seekInInternetFile (void* handle, int newPosition)
  203922. {
  203923. if (handle != 0)
  203924. {
  203925. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  203926. return InternetSetFilePointer (crs->request, newPosition, 0, FILE_BEGIN, 0);
  203927. }
  203928. return -1;
  203929. }
  203930. int64 juce_getInternetFileContentLength (void* handle)
  203931. {
  203932. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  203933. if (crs != 0)
  203934. {
  203935. DWORD index = 0, result = 0, size = sizeof (result);
  203936. if (HttpQueryInfo (crs->request, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &result, &size, &index))
  203937. return (int64) result;
  203938. }
  203939. return -1;
  203940. }
  203941. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  203942. {
  203943. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  203944. if (crs != 0)
  203945. {
  203946. DWORD bufferSizeBytes = 4096;
  203947. for (;;)
  203948. {
  203949. HeapBlock<char> buffer ((size_t) bufferSizeBytes);
  203950. if (HttpQueryInfo (crs->request, HTTP_QUERY_RAW_HEADERS_CRLF, buffer.getData(), &bufferSizeBytes, 0))
  203951. {
  203952. StringArray headersArray;
  203953. headersArray.addLines (reinterpret_cast <const WCHAR*> (buffer.getData()));
  203954. for (int i = 0; i < headersArray.size(); ++i)
  203955. {
  203956. const String& header = headersArray[i];
  203957. const String key (header.upToFirstOccurrenceOf (": ", false, false));
  203958. const String value (header.fromFirstOccurrenceOf (": ", false, false));
  203959. const String previousValue (headers [key]);
  203960. headers.set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  203961. }
  203962. break;
  203963. }
  203964. if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
  203965. break;
  203966. }
  203967. }
  203968. }
  203969. void juce_closeInternetFile (void* handle)
  203970. {
  203971. if (handle != 0)
  203972. {
  203973. ScopedPointer <ConnectionAndRequestStruct> crs (static_cast <ConnectionAndRequestStruct*> (handle));
  203974. InternetCloseHandle (crs->request);
  203975. InternetCloseHandle (crs->connection);
  203976. }
  203977. }
  203978. static int getMACAddressViaGetAdaptersInfo (int64* addresses, int maxNum, const bool littleEndian) throw()
  203979. {
  203980. int numFound = 0;
  203981. DynamicLibraryLoader dll ("iphlpapi.dll");
  203982. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  203983. if (getAdaptersInfo != 0)
  203984. {
  203985. ULONG len = sizeof (IP_ADAPTER_INFO);
  203986. MemoryBlock mb;
  203987. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  203988. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  203989. {
  203990. mb.setSize (len);
  203991. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  203992. }
  203993. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  203994. {
  203995. PIP_ADAPTER_INFO adapter = adapterInfo;
  203996. while (adapter != 0)
  203997. {
  203998. int64 mac = 0;
  203999. for (unsigned int i = 0; i < adapter->AddressLength; ++i)
  204000. mac = (mac << 8) | adapter->Address[i];
  204001. if (littleEndian)
  204002. mac = (int64) ByteOrder::swap ((uint64) mac);
  204003. if (numFound < maxNum && mac != 0)
  204004. addresses [numFound++] = mac;
  204005. adapter = adapter->Next;
  204006. }
  204007. }
  204008. }
  204009. return numFound;
  204010. }
  204011. static int getMACAddressesViaNetBios (int64* addresses, int maxNum, const bool littleEndian) throw()
  204012. {
  204013. int numFound = 0;
  204014. DynamicLibraryLoader dll ("netapi32.dll");
  204015. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  204016. if (NetbiosCall != 0)
  204017. {
  204018. NCB ncb;
  204019. zerostruct (ncb);
  204020. struct ASTAT
  204021. {
  204022. ADAPTER_STATUS adapt;
  204023. NAME_BUFFER NameBuff [30];
  204024. };
  204025. ASTAT astat;
  204026. zeromem (&astat, sizeof (astat)); // (can't use zerostruct here in VC6)
  204027. LANA_ENUM enums;
  204028. zerostruct (enums);
  204029. ncb.ncb_command = NCBENUM;
  204030. ncb.ncb_buffer = (unsigned char*) &enums;
  204031. ncb.ncb_length = sizeof (LANA_ENUM);
  204032. NetbiosCall (&ncb);
  204033. for (int i = 0; i < enums.length; ++i)
  204034. {
  204035. zerostruct (ncb);
  204036. ncb.ncb_command = NCBRESET;
  204037. ncb.ncb_lana_num = enums.lana[i];
  204038. if (NetbiosCall (&ncb) == 0)
  204039. {
  204040. zerostruct (ncb);
  204041. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  204042. ncb.ncb_command = NCBASTAT;
  204043. ncb.ncb_lana_num = enums.lana[i];
  204044. ncb.ncb_buffer = (unsigned char*) &astat;
  204045. ncb.ncb_length = sizeof (ASTAT);
  204046. if (NetbiosCall (&ncb) == 0)
  204047. {
  204048. if (astat.adapt.adapter_type == 0xfe)
  204049. {
  204050. uint64 mac = 0;
  204051. for (int i = 6; --i >= 0;)
  204052. mac = (mac << 8) | astat.adapt.adapter_address [littleEndian ? i : (5 - i)];
  204053. if (numFound < maxNum && mac != 0)
  204054. addresses [numFound++] = mac;
  204055. }
  204056. }
  204057. }
  204058. }
  204059. }
  204060. return numFound;
  204061. }
  204062. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  204063. {
  204064. int numFound = getMACAddressViaGetAdaptersInfo (addresses, maxNum, littleEndian);
  204065. if (numFound == 0)
  204066. numFound = getMACAddressesViaNetBios (addresses, maxNum, littleEndian);
  204067. return numFound;
  204068. }
  204069. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  204070. const String& emailSubject,
  204071. const String& bodyText,
  204072. const StringArray& filesToAttach)
  204073. {
  204074. HMODULE h = LoadLibraryA ("MAPI32.dll");
  204075. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  204076. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  204077. bool ok = false;
  204078. if (mapiSendMail != 0)
  204079. {
  204080. MapiMessage message;
  204081. zerostruct (message);
  204082. message.lpszSubject = (LPSTR) emailSubject.toCString();
  204083. message.lpszNoteText = (LPSTR) bodyText.toCString();
  204084. MapiRecipDesc recip;
  204085. zerostruct (recip);
  204086. recip.ulRecipClass = MAPI_TO;
  204087. String targetEmailAddress_ (targetEmailAddress);
  204088. if (targetEmailAddress_.isEmpty())
  204089. targetEmailAddress_ = " "; // (Windows Mail can't deal with a blank address)
  204090. recip.lpszName = (LPSTR) targetEmailAddress_.toCString();
  204091. message.nRecipCount = 1;
  204092. message.lpRecips = &recip;
  204093. HeapBlock <MapiFileDesc> files;
  204094. files.calloc (filesToAttach.size());
  204095. message.nFileCount = filesToAttach.size();
  204096. message.lpFiles = files;
  204097. for (int i = 0; i < filesToAttach.size(); ++i)
  204098. {
  204099. files[i].nPosition = (ULONG) -1;
  204100. files[i].lpszPathName = (LPSTR) filesToAttach[i].toCString();
  204101. }
  204102. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  204103. }
  204104. FreeLibrary (h);
  204105. return ok;
  204106. }
  204107. #endif
  204108. /*** End of inlined file: juce_win32_Network.cpp ***/
  204109. /*** Start of inlined file: juce_win32_PlatformUtils.cpp ***/
  204110. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204111. // compiled on its own).
  204112. #if JUCE_INCLUDED_FILE
  204113. static HKEY findKeyForPath (String name,
  204114. const bool createForWriting,
  204115. String& valueName)
  204116. {
  204117. HKEY rootKey = 0;
  204118. if (name.startsWithIgnoreCase ("HKEY_CURRENT_USER\\"))
  204119. rootKey = HKEY_CURRENT_USER;
  204120. else if (name.startsWithIgnoreCase ("HKEY_LOCAL_MACHINE\\"))
  204121. rootKey = HKEY_LOCAL_MACHINE;
  204122. else if (name.startsWithIgnoreCase ("HKEY_CLASSES_ROOT\\"))
  204123. rootKey = HKEY_CLASSES_ROOT;
  204124. if (rootKey != 0)
  204125. {
  204126. name = name.substring (name.indexOfChar ('\\') + 1);
  204127. const int lastSlash = name.lastIndexOfChar ('\\');
  204128. valueName = name.substring (lastSlash + 1);
  204129. name = name.substring (0, lastSlash);
  204130. HKEY key;
  204131. DWORD result;
  204132. if (createForWriting)
  204133. {
  204134. if (RegCreateKeyEx (rootKey, name, 0, 0, REG_OPTION_NON_VOLATILE,
  204135. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  204136. return key;
  204137. }
  204138. else
  204139. {
  204140. if (RegOpenKeyEx (rootKey, name, 0, KEY_READ, &key) == ERROR_SUCCESS)
  204141. return key;
  204142. }
  204143. }
  204144. return 0;
  204145. }
  204146. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  204147. const String& defaultValue)
  204148. {
  204149. String valueName, result (defaultValue);
  204150. HKEY k = findKeyForPath (regValuePath, false, valueName);
  204151. if (k != 0)
  204152. {
  204153. WCHAR buffer [2048];
  204154. unsigned long bufferSize = sizeof (buffer);
  204155. DWORD type = REG_SZ;
  204156. if (RegQueryValueEx (k, valueName, 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  204157. {
  204158. if (type == REG_SZ)
  204159. result = buffer;
  204160. else if (type == REG_DWORD)
  204161. result = String ((int) *(DWORD*) buffer);
  204162. }
  204163. RegCloseKey (k);
  204164. }
  204165. return result;
  204166. }
  204167. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  204168. const String& value)
  204169. {
  204170. String valueName;
  204171. HKEY k = findKeyForPath (regValuePath, true, valueName);
  204172. if (k != 0)
  204173. {
  204174. RegSetValueEx (k, valueName, 0, REG_SZ,
  204175. (const BYTE*) (const WCHAR*) value,
  204176. sizeof (WCHAR) * (value.length() + 1));
  204177. RegCloseKey (k);
  204178. }
  204179. }
  204180. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  204181. {
  204182. bool exists = false;
  204183. String valueName;
  204184. HKEY k = findKeyForPath (regValuePath, false, valueName);
  204185. if (k != 0)
  204186. {
  204187. unsigned char buffer [2048];
  204188. unsigned long bufferSize = sizeof (buffer);
  204189. DWORD type = 0;
  204190. if (RegQueryValueEx (k, valueName, 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  204191. exists = true;
  204192. RegCloseKey (k);
  204193. }
  204194. return exists;
  204195. }
  204196. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  204197. {
  204198. String valueName;
  204199. HKEY k = findKeyForPath (regValuePath, true, valueName);
  204200. if (k != 0)
  204201. {
  204202. RegDeleteValue (k, valueName);
  204203. RegCloseKey (k);
  204204. }
  204205. }
  204206. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  204207. {
  204208. String valueName;
  204209. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  204210. if (k != 0)
  204211. {
  204212. RegDeleteKey (k, valueName);
  204213. RegCloseKey (k);
  204214. }
  204215. }
  204216. void PlatformUtilities::registerFileAssociation (const String& fileExtension,
  204217. const String& symbolicDescription,
  204218. const String& fullDescription,
  204219. const File& targetExecutable,
  204220. int iconResourceNumber)
  204221. {
  204222. setRegistryValue ("HKEY_CLASSES_ROOT\\" + fileExtension + "\\", symbolicDescription);
  204223. const String key ("HKEY_CLASSES_ROOT\\" + symbolicDescription);
  204224. if (iconResourceNumber != 0)
  204225. setRegistryValue (key + "\\DefaultIcon\\",
  204226. targetExecutable.getFullPathName() + "," + String (-iconResourceNumber));
  204227. setRegistryValue (key + "\\", fullDescription);
  204228. setRegistryValue (key + "\\shell\\open\\command\\",
  204229. targetExecutable.getFullPathName() + " %1");
  204230. }
  204231. bool juce_IsRunningInWine()
  204232. {
  204233. HKEY key;
  204234. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  204235. {
  204236. RegCloseKey (key);
  204237. return true;
  204238. }
  204239. return false;
  204240. }
  204241. const String JUCE_CALLTYPE PlatformUtilities::getCurrentCommandLineParams()
  204242. {
  204243. String s (::GetCommandLineW());
  204244. StringArray tokens;
  204245. tokens.addTokens (s, true); // tokenise so that we can remove the initial filename argument
  204246. return tokens.joinIntoString (" ", 1);
  204247. }
  204248. static void* currentModuleHandle = 0;
  204249. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  204250. {
  204251. if (currentModuleHandle == 0)
  204252. currentModuleHandle = GetModuleHandle (0);
  204253. return currentModuleHandle;
  204254. }
  204255. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  204256. {
  204257. currentModuleHandle = newHandle;
  204258. }
  204259. void PlatformUtilities::fpuReset()
  204260. {
  204261. #if JUCE_MSVC
  204262. _clearfp();
  204263. #endif
  204264. }
  204265. void PlatformUtilities::beep()
  204266. {
  204267. MessageBeep (MB_OK);
  204268. }
  204269. #endif
  204270. /*** End of inlined file: juce_win32_PlatformUtils.cpp ***/
  204271. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  204272. /*** Start of inlined file: juce_win32_Messaging.cpp ***/
  204273. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204274. // compiled on its own).
  204275. #if JUCE_INCLUDED_FILE
  204276. static const unsigned int specialId = WM_APP + 0x4400;
  204277. static const unsigned int broadcastId = WM_APP + 0x4403;
  204278. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  204279. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  204280. HWND juce_messageWindowHandle = 0;
  204281. extern long improbableWindowNumber; // defined in windowing.cpp
  204282. #ifndef WM_APPCOMMAND
  204283. #define WM_APPCOMMAND 0x0319
  204284. #endif
  204285. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  204286. const UINT message,
  204287. const WPARAM wParam,
  204288. const LPARAM lParam) throw()
  204289. {
  204290. JUCE_TRY
  204291. {
  204292. if (h == juce_messageWindowHandle)
  204293. {
  204294. if (message == specialCallbackId)
  204295. {
  204296. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  204297. return (LRESULT) (*func) ((void*) lParam);
  204298. }
  204299. else if (message == specialId)
  204300. {
  204301. // these are trapped early in the dispatch call, but must also be checked
  204302. // here in case there are windows modal dialog boxes doing their own
  204303. // dispatch loop and not calling our version
  204304. MessageManager::getInstance()->deliverMessage ((void*) lParam);
  204305. return 0;
  204306. }
  204307. else if (message == broadcastId)
  204308. {
  204309. const ScopedPointer <String> messageString ((String*) lParam);
  204310. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  204311. return 0;
  204312. }
  204313. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  204314. {
  204315. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  204316. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  204317. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  204318. return 0;
  204319. }
  204320. }
  204321. }
  204322. JUCE_CATCH_EXCEPTION
  204323. return DefWindowProc (h, message, wParam, lParam);
  204324. }
  204325. static bool isEventBlockedByModalComps (MSG& m)
  204326. {
  204327. if (Component::getNumCurrentlyModalComponents() == 0
  204328. || GetWindowLong (m.hwnd, GWLP_USERDATA) == improbableWindowNumber)
  204329. return false;
  204330. switch (m.message)
  204331. {
  204332. case WM_MOUSEMOVE:
  204333. case WM_NCMOUSEMOVE:
  204334. case 0x020A: /* WM_MOUSEWHEEL */
  204335. case 0x020E: /* WM_MOUSEHWHEEL */
  204336. case WM_KEYUP:
  204337. case WM_SYSKEYUP:
  204338. case WM_CHAR:
  204339. case WM_APPCOMMAND:
  204340. case WM_LBUTTONUP:
  204341. case WM_MBUTTONUP:
  204342. case WM_RBUTTONUP:
  204343. case WM_MOUSEACTIVATE:
  204344. case WM_NCMOUSEHOVER:
  204345. case WM_MOUSEHOVER:
  204346. return true;
  204347. case WM_NCLBUTTONDOWN:
  204348. case WM_NCLBUTTONDBLCLK:
  204349. case WM_NCRBUTTONDOWN:
  204350. case WM_NCRBUTTONDBLCLK:
  204351. case WM_NCMBUTTONDOWN:
  204352. case WM_NCMBUTTONDBLCLK:
  204353. case WM_LBUTTONDOWN:
  204354. case WM_LBUTTONDBLCLK:
  204355. case WM_MBUTTONDOWN:
  204356. case WM_MBUTTONDBLCLK:
  204357. case WM_RBUTTONDOWN:
  204358. case WM_RBUTTONDBLCLK:
  204359. case WM_KEYDOWN:
  204360. case WM_SYSKEYDOWN:
  204361. {
  204362. Component* const modal = Component::getCurrentlyModalComponent (0);
  204363. if (modal != 0)
  204364. modal->inputAttemptWhenModal();
  204365. return true;
  204366. }
  204367. default:
  204368. break;
  204369. }
  204370. return false;
  204371. }
  204372. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  204373. {
  204374. MSG m;
  204375. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  204376. return false;
  204377. if (GetMessage (&m, (HWND) 0, 0, 0) >= 0)
  204378. {
  204379. if (m.message == specialId && m.hwnd == juce_messageWindowHandle)
  204380. {
  204381. MessageManager::getInstance()->deliverMessage ((void*) m.lParam);
  204382. }
  204383. else if (m.message == WM_QUIT)
  204384. {
  204385. if (JUCEApplication::getInstance())
  204386. JUCEApplication::getInstance()->systemRequestedQuit();
  204387. }
  204388. else if (! isEventBlockedByModalComps (m))
  204389. {
  204390. if ((m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN)
  204391. && GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber)
  204392. {
  204393. // if it's someone else's window being clicked on, and the focus is
  204394. // currently on a juce window, pass the kb focus over..
  204395. HWND currentFocus = GetFocus();
  204396. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  204397. SetFocus (m.hwnd);
  204398. }
  204399. TranslateMessage (&m);
  204400. DispatchMessage (&m);
  204401. }
  204402. }
  204403. return true;
  204404. }
  204405. bool juce_postMessageToSystemQueue (void* message)
  204406. {
  204407. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  204408. }
  204409. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  204410. void* userData)
  204411. {
  204412. if (MessageManager::getInstance()->isThisTheMessageThread())
  204413. {
  204414. return (*callback) (userData);
  204415. }
  204416. else
  204417. {
  204418. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  204419. // deadlock because the message manager is blocked from running, and can't
  204420. // call your function..
  204421. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  204422. return (void*) SendMessage (juce_messageWindowHandle,
  204423. specialCallbackId,
  204424. (WPARAM) callback,
  204425. (LPARAM) userData);
  204426. }
  204427. }
  204428. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  204429. {
  204430. if (hwnd != juce_messageWindowHandle)
  204431. reinterpret_cast <Array<void*>*> (lParam)->add ((void*) hwnd);
  204432. return TRUE;
  204433. }
  204434. void MessageManager::broadcastMessage (const String& value) throw()
  204435. {
  204436. Array<void*> windows;
  204437. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  204438. const String localCopy (value);
  204439. COPYDATASTRUCT data;
  204440. data.dwData = broadcastId;
  204441. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  204442. data.lpData = (void*) static_cast <const juce_wchar*> (localCopy);
  204443. for (int i = windows.size(); --i >= 0;)
  204444. {
  204445. HWND hwnd = (HWND) windows.getUnchecked(i);
  204446. TCHAR windowName [64]; // no need to read longer strings than this
  204447. GetWindowText (hwnd, windowName, 64);
  204448. windowName [63] = 0;
  204449. if (String (windowName) == messageWindowName)
  204450. {
  204451. DWORD_PTR result;
  204452. SendMessageTimeout (hwnd, WM_COPYDATA,
  204453. (WPARAM) juce_messageWindowHandle,
  204454. (LPARAM) &data,
  204455. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  204456. 8000,
  204457. &result);
  204458. }
  204459. }
  204460. }
  204461. static const String getMessageWindowClassName()
  204462. {
  204463. // this name has to be different for each app/dll instance because otherwise
  204464. // poor old Win32 can get a bit confused (even despite it not being a process-global
  204465. // window class).
  204466. static int number = 0;
  204467. if (number == 0)
  204468. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  204469. return "JUCEcs_" + String (number);
  204470. }
  204471. void MessageManager::doPlatformSpecificInitialisation()
  204472. {
  204473. OleInitialize (0);
  204474. const String className (getMessageWindowClassName());
  204475. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  204476. WNDCLASSEX wc;
  204477. zerostruct (wc);
  204478. wc.cbSize = sizeof (wc);
  204479. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  204480. wc.cbWndExtra = 4;
  204481. wc.hInstance = hmod;
  204482. wc.lpszClassName = className;
  204483. RegisterClassEx (&wc);
  204484. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  204485. messageWindowName,
  204486. 0, 0, 0, 0, 0, 0, 0,
  204487. hmod, 0);
  204488. }
  204489. void MessageManager::doPlatformSpecificShutdown()
  204490. {
  204491. DestroyWindow (juce_messageWindowHandle);
  204492. UnregisterClass (getMessageWindowClassName(), 0);
  204493. OleUninitialize();
  204494. }
  204495. #endif
  204496. /*** End of inlined file: juce_win32_Messaging.cpp ***/
  204497. /*** Start of inlined file: juce_win32_Windowing.cpp ***/
  204498. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204499. // compiled on its own).
  204500. #if JUCE_INCLUDED_FILE
  204501. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  204502. // these are in the windows SDK, but need to be repeated here for GCC..
  204503. #ifndef GET_APPCOMMAND_LPARAM
  204504. #define FAPPCOMMAND_MASK 0xF000
  204505. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  204506. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  204507. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  204508. #define APPCOMMAND_MEDIA_STOP 13
  204509. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  204510. #define WM_APPCOMMAND 0x0319
  204511. #endif
  204512. extern void juce_repeatLastProcessPriority(); // in juce_win32_Threads.cpp
  204513. extern void juce_CheckCurrentlyFocusedTopLevelWindow(); // in juce_TopLevelWindow.cpp
  204514. extern bool juce_IsRunningInWine();
  204515. #ifndef ULW_ALPHA
  204516. #define ULW_ALPHA 0x00000002
  204517. #endif
  204518. #ifndef AC_SRC_ALPHA
  204519. #define AC_SRC_ALPHA 0x01
  204520. #endif
  204521. static HPALETTE palette = 0;
  204522. static bool createPaletteIfNeeded = true;
  204523. static bool shouldDeactivateTitleBar = true;
  204524. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw();
  204525. #define WM_TRAYNOTIFY WM_USER + 100
  204526. using ::abs;
  204527. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  204528. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  204529. bool Desktop::canUseSemiTransparentWindows() throw()
  204530. {
  204531. if (updateLayeredWindow == 0)
  204532. {
  204533. if (! juce_IsRunningInWine())
  204534. {
  204535. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  204536. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  204537. }
  204538. }
  204539. return updateLayeredWindow != 0;
  204540. }
  204541. const int extendedKeyModifier = 0x10000;
  204542. const int KeyPress::spaceKey = VK_SPACE;
  204543. const int KeyPress::returnKey = VK_RETURN;
  204544. const int KeyPress::escapeKey = VK_ESCAPE;
  204545. const int KeyPress::backspaceKey = VK_BACK;
  204546. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  204547. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  204548. const int KeyPress::tabKey = VK_TAB;
  204549. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  204550. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  204551. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  204552. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  204553. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  204554. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  204555. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  204556. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  204557. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  204558. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  204559. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  204560. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  204561. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  204562. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  204563. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  204564. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  204565. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  204566. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  204567. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  204568. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  204569. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  204570. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  204571. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  204572. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  204573. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  204574. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  204575. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  204576. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  204577. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  204578. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  204579. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  204580. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  204581. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  204582. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  204583. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  204584. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  204585. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  204586. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  204587. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  204588. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  204589. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  204590. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  204591. const int KeyPress::playKey = 0x30000;
  204592. const int KeyPress::stopKey = 0x30001;
  204593. const int KeyPress::fastForwardKey = 0x30002;
  204594. const int KeyPress::rewindKey = 0x30003;
  204595. class WindowsBitmapImage : public Image::SharedImage
  204596. {
  204597. public:
  204598. HBITMAP hBitmap;
  204599. BITMAPV4HEADER bitmapInfo;
  204600. HDC hdc;
  204601. unsigned char* bitmapData;
  204602. WindowsBitmapImage (const Image::PixelFormat format_,
  204603. const int w, const int h, const bool clearImage)
  204604. : Image::SharedImage (format_, w, h)
  204605. {
  204606. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  204607. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  204608. zerostruct (bitmapInfo);
  204609. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  204610. bitmapInfo.bV4Width = w;
  204611. bitmapInfo.bV4Height = h;
  204612. bitmapInfo.bV4Planes = 1;
  204613. bitmapInfo.bV4CSType = 1;
  204614. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  204615. if (format_ == Image::ARGB)
  204616. {
  204617. bitmapInfo.bV4AlphaMask = 0xff000000;
  204618. bitmapInfo.bV4RedMask = 0xff0000;
  204619. bitmapInfo.bV4GreenMask = 0xff00;
  204620. bitmapInfo.bV4BlueMask = 0xff;
  204621. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  204622. }
  204623. else
  204624. {
  204625. bitmapInfo.bV4V4Compression = BI_RGB;
  204626. }
  204627. lineStride = -((w * pixelStride + 3) & ~3);
  204628. HDC dc = GetDC (0);
  204629. hdc = CreateCompatibleDC (dc);
  204630. ReleaseDC (0, dc);
  204631. SetMapMode (hdc, MM_TEXT);
  204632. hBitmap = CreateDIBSection (hdc,
  204633. (BITMAPINFO*) &(bitmapInfo),
  204634. DIB_RGB_COLORS,
  204635. (void**) &bitmapData,
  204636. 0, 0);
  204637. SelectObject (hdc, hBitmap);
  204638. if (format_ == Image::ARGB && clearImage)
  204639. zeromem (bitmapData, abs (h * lineStride));
  204640. imageData = bitmapData - (lineStride * (h - 1));
  204641. }
  204642. ~WindowsBitmapImage()
  204643. {
  204644. DeleteDC (hdc);
  204645. DeleteObject (hBitmap);
  204646. }
  204647. Image::ImageType getType() const { return Image::NativeImage; }
  204648. LowLevelGraphicsContext* createLowLevelContext()
  204649. {
  204650. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  204651. }
  204652. SharedImage* clone()
  204653. {
  204654. WindowsBitmapImage* im = new WindowsBitmapImage (format, width, height, false);
  204655. for (int i = 0; i < height; ++i)
  204656. memcpy (im->imageData + i * lineStride, imageData + i * lineStride, lineStride);
  204657. return im;
  204658. }
  204659. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  204660. const int x, const int y,
  204661. const RectangleList& maskedRegion) throw()
  204662. {
  204663. static HDRAWDIB hdd = 0;
  204664. static bool needToCreateDrawDib = true;
  204665. if (needToCreateDrawDib)
  204666. {
  204667. needToCreateDrawDib = false;
  204668. HDC dc = GetDC (0);
  204669. const int n = GetDeviceCaps (dc, BITSPIXEL);
  204670. ReleaseDC (0, dc);
  204671. // only open if we're not palettised
  204672. if (n > 8)
  204673. hdd = DrawDibOpen();
  204674. }
  204675. if (createPaletteIfNeeded)
  204676. {
  204677. HDC dc = GetDC (0);
  204678. const int n = GetDeviceCaps (dc, BITSPIXEL);
  204679. ReleaseDC (0, dc);
  204680. if (n <= 8)
  204681. palette = CreateHalftonePalette (dc);
  204682. createPaletteIfNeeded = false;
  204683. }
  204684. if (palette != 0)
  204685. {
  204686. SelectPalette (dc, palette, FALSE);
  204687. RealizePalette (dc);
  204688. SetStretchBltMode (dc, HALFTONE);
  204689. }
  204690. SetMapMode (dc, MM_TEXT);
  204691. if (transparent)
  204692. {
  204693. POINT p, pos;
  204694. SIZE size;
  204695. RECT windowBounds;
  204696. GetWindowRect (hwnd, &windowBounds);
  204697. p.x = -x;
  204698. p.y = -y;
  204699. pos.x = windowBounds.left;
  204700. pos.y = windowBounds.top;
  204701. size.cx = windowBounds.right - windowBounds.left;
  204702. size.cy = windowBounds.bottom - windowBounds.top;
  204703. BLENDFUNCTION bf;
  204704. bf.AlphaFormat = AC_SRC_ALPHA;
  204705. bf.BlendFlags = 0;
  204706. bf.BlendOp = AC_SRC_OVER;
  204707. bf.SourceConstantAlpha = 0xff;
  204708. if (! maskedRegion.isEmpty())
  204709. {
  204710. for (RectangleList::Iterator i (maskedRegion); i.next();)
  204711. {
  204712. const Rectangle<int>& r = *i.getRectangle();
  204713. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  204714. }
  204715. }
  204716. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  204717. }
  204718. else
  204719. {
  204720. int savedDC = 0;
  204721. if (! maskedRegion.isEmpty())
  204722. {
  204723. savedDC = SaveDC (dc);
  204724. for (RectangleList::Iterator i (maskedRegion); i.next();)
  204725. {
  204726. const Rectangle<int>& r = *i.getRectangle();
  204727. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  204728. }
  204729. }
  204730. if (hdd == 0)
  204731. {
  204732. StretchDIBits (dc,
  204733. x, y, width, height,
  204734. 0, 0, width, height,
  204735. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  204736. DIB_RGB_COLORS, SRCCOPY);
  204737. }
  204738. else
  204739. {
  204740. DrawDibDraw (hdd, dc, x, y, -1, -1,
  204741. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  204742. 0, 0, width, height, 0);
  204743. }
  204744. if (! maskedRegion.isEmpty())
  204745. RestoreDC (dc, savedDC);
  204746. }
  204747. }
  204748. juce_UseDebuggingNewOperator
  204749. private:
  204750. WindowsBitmapImage (const WindowsBitmapImage&);
  204751. WindowsBitmapImage& operator= (const WindowsBitmapImage&);
  204752. };
  204753. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  204754. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  204755. {
  204756. SHORT k = (SHORT) keyCode;
  204757. if ((keyCode & extendedKeyModifier) == 0
  204758. && (k >= (SHORT) 'a' && k <= (SHORT) 'z'))
  204759. k += (SHORT) 'A' - (SHORT) 'a';
  204760. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  204761. (SHORT) '+', VK_OEM_PLUS,
  204762. (SHORT) '-', VK_OEM_MINUS,
  204763. (SHORT) '.', VK_OEM_PERIOD,
  204764. (SHORT) ';', VK_OEM_1,
  204765. (SHORT) ':', VK_OEM_1,
  204766. (SHORT) '/', VK_OEM_2,
  204767. (SHORT) '?', VK_OEM_2,
  204768. (SHORT) '[', VK_OEM_4,
  204769. (SHORT) ']', VK_OEM_6 };
  204770. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  204771. if (k == translatedValues [i])
  204772. k = translatedValues [i + 1];
  204773. return (GetKeyState (k) & 0x8000) != 0;
  204774. }
  204775. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  204776. {
  204777. if (MessageManager::getInstance()->currentThreadHasLockedMessageManager())
  204778. return callback (userData);
  204779. else
  204780. return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData);
  204781. }
  204782. class Win32ComponentPeer : public ComponentPeer
  204783. {
  204784. public:
  204785. Win32ComponentPeer (Component* const component,
  204786. const int windowStyleFlags)
  204787. : ComponentPeer (component, windowStyleFlags),
  204788. dontRepaint (false),
  204789. fullScreen (false),
  204790. isDragging (false),
  204791. isMouseOver (false),
  204792. hasCreatedCaret (false),
  204793. currentWindowIcon (0),
  204794. taskBarIcon (0),
  204795. dropTarget (0)
  204796. {
  204797. callFunctionIfNotLocked (&createWindowCallback, this);
  204798. setTitle (component->getName());
  204799. if ((windowStyleFlags & windowHasDropShadow) != 0
  204800. && Desktop::canUseSemiTransparentWindows())
  204801. {
  204802. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  204803. if (shadower != 0)
  204804. shadower->setOwner (component);
  204805. }
  204806. else
  204807. {
  204808. shadower = 0;
  204809. }
  204810. }
  204811. ~Win32ComponentPeer()
  204812. {
  204813. setTaskBarIcon (Image());
  204814. deleteAndZero (shadower);
  204815. // do this before the next bit to avoid messages arriving for this window
  204816. // before it's destroyed
  204817. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  204818. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  204819. if (currentWindowIcon != 0)
  204820. DestroyIcon (currentWindowIcon);
  204821. if (dropTarget != 0)
  204822. {
  204823. dropTarget->Release();
  204824. dropTarget = 0;
  204825. }
  204826. }
  204827. void* getNativeHandle() const
  204828. {
  204829. return hwnd;
  204830. }
  204831. void setVisible (bool shouldBeVisible)
  204832. {
  204833. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  204834. if (shouldBeVisible)
  204835. InvalidateRect (hwnd, 0, 0);
  204836. else
  204837. lastPaintTime = 0;
  204838. }
  204839. void setTitle (const String& title)
  204840. {
  204841. SetWindowText (hwnd, title);
  204842. }
  204843. void setPosition (int x, int y)
  204844. {
  204845. offsetWithinParent (x, y);
  204846. SetWindowPos (hwnd, 0,
  204847. x - windowBorder.getLeft(),
  204848. y - windowBorder.getTop(),
  204849. 0, 0,
  204850. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  204851. }
  204852. void repaintNowIfTransparent()
  204853. {
  204854. if (isTransparent() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  204855. handlePaintMessage();
  204856. }
  204857. void updateBorderSize()
  204858. {
  204859. WINDOWINFO info;
  204860. info.cbSize = sizeof (info);
  204861. if (GetWindowInfo (hwnd, &info))
  204862. {
  204863. windowBorder = BorderSize (info.rcClient.top - info.rcWindow.top,
  204864. info.rcClient.left - info.rcWindow.left,
  204865. info.rcWindow.bottom - info.rcClient.bottom,
  204866. info.rcWindow.right - info.rcClient.right);
  204867. }
  204868. }
  204869. void setSize (int w, int h)
  204870. {
  204871. SetWindowPos (hwnd, 0, 0, 0,
  204872. w + windowBorder.getLeftAndRight(),
  204873. h + windowBorder.getTopAndBottom(),
  204874. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  204875. updateBorderSize();
  204876. repaintNowIfTransparent();
  204877. }
  204878. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  204879. {
  204880. fullScreen = isNowFullScreen;
  204881. offsetWithinParent (x, y);
  204882. SetWindowPos (hwnd, 0,
  204883. x - windowBorder.getLeft(),
  204884. y - windowBorder.getTop(),
  204885. w + windowBorder.getLeftAndRight(),
  204886. h + windowBorder.getTopAndBottom(),
  204887. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  204888. updateBorderSize();
  204889. repaintNowIfTransparent();
  204890. }
  204891. const Rectangle<int> getBounds() const
  204892. {
  204893. RECT r;
  204894. GetWindowRect (hwnd, &r);
  204895. Rectangle<int> bounds (r.left, r.top, r.right - r.left, r.bottom - r.top);
  204896. HWND parentH = GetParent (hwnd);
  204897. if (parentH != 0)
  204898. {
  204899. GetWindowRect (parentH, &r);
  204900. bounds.translate (-r.left, -r.top);
  204901. }
  204902. return windowBorder.subtractedFrom (bounds);
  204903. }
  204904. const Point<int> getScreenPosition() const
  204905. {
  204906. RECT r;
  204907. GetWindowRect (hwnd, &r);
  204908. return Point<int> (r.left + windowBorder.getLeft(),
  204909. r.top + windowBorder.getTop());
  204910. }
  204911. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  204912. {
  204913. return relativePosition + getScreenPosition();
  204914. }
  204915. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  204916. {
  204917. return screenPosition - getScreenPosition();
  204918. }
  204919. void setMinimised (bool shouldBeMinimised)
  204920. {
  204921. if (shouldBeMinimised != isMinimised())
  204922. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  204923. }
  204924. bool isMinimised() const
  204925. {
  204926. WINDOWPLACEMENT wp;
  204927. wp.length = sizeof (WINDOWPLACEMENT);
  204928. GetWindowPlacement (hwnd, &wp);
  204929. return wp.showCmd == SW_SHOWMINIMIZED;
  204930. }
  204931. void setFullScreen (bool shouldBeFullScreen)
  204932. {
  204933. setMinimised (false);
  204934. if (fullScreen != shouldBeFullScreen)
  204935. {
  204936. fullScreen = shouldBeFullScreen;
  204937. const Component::SafePointer<Component> deletionChecker (component);
  204938. if (! fullScreen)
  204939. {
  204940. const Rectangle<int> boundsCopy (lastNonFullscreenBounds);
  204941. if (hasTitleBar())
  204942. ShowWindow (hwnd, SW_SHOWNORMAL);
  204943. if (! boundsCopy.isEmpty())
  204944. {
  204945. setBounds (boundsCopy.getX(),
  204946. boundsCopy.getY(),
  204947. boundsCopy.getWidth(),
  204948. boundsCopy.getHeight(),
  204949. false);
  204950. }
  204951. }
  204952. else
  204953. {
  204954. if (hasTitleBar())
  204955. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  204956. else
  204957. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  204958. }
  204959. if (deletionChecker != 0)
  204960. handleMovedOrResized();
  204961. }
  204962. }
  204963. bool isFullScreen() const
  204964. {
  204965. if (! hasTitleBar())
  204966. return fullScreen;
  204967. WINDOWPLACEMENT wp;
  204968. wp.length = sizeof (wp);
  204969. GetWindowPlacement (hwnd, &wp);
  204970. return wp.showCmd == SW_SHOWMAXIMIZED;
  204971. }
  204972. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  204973. {
  204974. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  204975. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  204976. return false;
  204977. RECT r;
  204978. GetWindowRect (hwnd, &r);
  204979. POINT p;
  204980. p.x = position.getX() + r.left + windowBorder.getLeft();
  204981. p.y = position.getY() + r.top + windowBorder.getTop();
  204982. HWND w = WindowFromPoint (p);
  204983. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  204984. }
  204985. const BorderSize getFrameSize() const
  204986. {
  204987. return windowBorder;
  204988. }
  204989. bool setAlwaysOnTop (bool alwaysOnTop)
  204990. {
  204991. const bool oldDeactivate = shouldDeactivateTitleBar;
  204992. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  204993. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  204994. 0, 0, 0, 0,
  204995. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  204996. shouldDeactivateTitleBar = oldDeactivate;
  204997. if (shadower != 0)
  204998. shadower->componentBroughtToFront (*component);
  204999. return true;
  205000. }
  205001. void toFront (bool makeActive)
  205002. {
  205003. setMinimised (false);
  205004. const bool oldDeactivate = shouldDeactivateTitleBar;
  205005. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  205006. callFunctionIfNotLocked (makeActive ? &toFrontCallback1 : &toFrontCallback2, hwnd);
  205007. shouldDeactivateTitleBar = oldDeactivate;
  205008. if (! makeActive)
  205009. {
  205010. // in this case a broughttofront call won't have occured, so do it now..
  205011. handleBroughtToFront();
  205012. }
  205013. }
  205014. void toBehind (ComponentPeer* other)
  205015. {
  205016. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  205017. jassert (otherPeer != 0); // wrong type of window?
  205018. if (otherPeer != 0)
  205019. {
  205020. setMinimised (false);
  205021. // must be careful not to try to put a topmost window behind a normal one, or win32
  205022. // promotes the normal one to be topmost!
  205023. if (getComponent()->isAlwaysOnTop() == otherPeer->getComponent()->isAlwaysOnTop())
  205024. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  205025. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  205026. else if (otherPeer->getComponent()->isAlwaysOnTop())
  205027. SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
  205028. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  205029. }
  205030. }
  205031. bool isFocused() const
  205032. {
  205033. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  205034. }
  205035. void grabFocus()
  205036. {
  205037. const bool oldDeactivate = shouldDeactivateTitleBar;
  205038. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  205039. callFunctionIfNotLocked (&setFocusCallback, hwnd);
  205040. shouldDeactivateTitleBar = oldDeactivate;
  205041. }
  205042. void textInputRequired (const Point<int>&)
  205043. {
  205044. if (! hasCreatedCaret)
  205045. {
  205046. hasCreatedCaret = true;
  205047. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  205048. }
  205049. ShowCaret (hwnd);
  205050. SetCaretPos (0, 0);
  205051. }
  205052. void repaint (const Rectangle<int>& area)
  205053. {
  205054. const RECT r = { area.getX(), area.getY(), area.getRight(), area.getBottom() };
  205055. InvalidateRect (hwnd, &r, FALSE);
  205056. }
  205057. void performAnyPendingRepaintsNow()
  205058. {
  205059. MSG m;
  205060. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  205061. DispatchMessage (&m);
  205062. }
  205063. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  205064. {
  205065. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  205066. return (Win32ComponentPeer*) (pointer_sized_int) GetWindowLongPtr (h, 8);
  205067. return 0;
  205068. }
  205069. void setTaskBarIcon (const Image& image)
  205070. {
  205071. if (image.isValid())
  205072. {
  205073. HICON hicon = createHICONFromImage (image, TRUE, 0, 0);
  205074. if (taskBarIcon == 0)
  205075. {
  205076. taskBarIcon = new NOTIFYICONDATA();
  205077. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  205078. taskBarIcon->hWnd = (HWND) hwnd;
  205079. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  205080. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  205081. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  205082. taskBarIcon->hIcon = hicon;
  205083. taskBarIcon->szTip[0] = 0;
  205084. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  205085. }
  205086. else
  205087. {
  205088. HICON oldIcon = taskBarIcon->hIcon;
  205089. taskBarIcon->hIcon = hicon;
  205090. taskBarIcon->uFlags = NIF_ICON;
  205091. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  205092. DestroyIcon (oldIcon);
  205093. }
  205094. DestroyIcon (hicon);
  205095. }
  205096. else if (taskBarIcon != 0)
  205097. {
  205098. taskBarIcon->uFlags = 0;
  205099. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  205100. DestroyIcon (taskBarIcon->hIcon);
  205101. deleteAndZero (taskBarIcon);
  205102. }
  205103. }
  205104. void setTaskBarIconToolTip (const String& toolTip) const
  205105. {
  205106. if (taskBarIcon != 0)
  205107. {
  205108. taskBarIcon->uFlags = NIF_TIP;
  205109. toolTip.copyToUnicode (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  205110. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  205111. }
  205112. }
  205113. bool isInside (HWND h) const
  205114. {
  205115. return GetAncestor (hwnd, GA_ROOT) == h;
  205116. }
  205117. static void updateKeyModifiers() throw()
  205118. {
  205119. int keyMods = 0;
  205120. if (GetKeyState (VK_SHIFT) & 0x8000) keyMods |= ModifierKeys::shiftModifier;
  205121. if (GetKeyState (VK_CONTROL) & 0x8000) keyMods |= ModifierKeys::ctrlModifier;
  205122. if (GetKeyState (VK_MENU) & 0x8000) keyMods |= ModifierKeys::altModifier;
  205123. if (GetKeyState (VK_RMENU) & 0x8000) keyMods &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  205124. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  205125. }
  205126. static void updateModifiersFromWParam (const WPARAM wParam)
  205127. {
  205128. int mouseMods = 0;
  205129. if (wParam & MK_LBUTTON) mouseMods |= ModifierKeys::leftButtonModifier;
  205130. if (wParam & MK_RBUTTON) mouseMods |= ModifierKeys::rightButtonModifier;
  205131. if (wParam & MK_MBUTTON) mouseMods |= ModifierKeys::middleButtonModifier;
  205132. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  205133. updateKeyModifiers();
  205134. }
  205135. static int64 getMouseEventTime()
  205136. {
  205137. static int64 eventTimeOffset = 0;
  205138. static DWORD lastMessageTime = 0;
  205139. const DWORD thisMessageTime = GetMessageTime();
  205140. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  205141. {
  205142. lastMessageTime = thisMessageTime;
  205143. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  205144. }
  205145. return eventTimeOffset + thisMessageTime;
  205146. }
  205147. juce_UseDebuggingNewOperator
  205148. bool dontRepaint;
  205149. static ModifierKeys currentModifiers;
  205150. static ModifierKeys modifiersAtLastCallback;
  205151. private:
  205152. HWND hwnd;
  205153. DropShadower* shadower;
  205154. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret;
  205155. BorderSize windowBorder;
  205156. HICON currentWindowIcon;
  205157. NOTIFYICONDATA* taskBarIcon;
  205158. IDropTarget* dropTarget;
  205159. class TemporaryImage : public Timer
  205160. {
  205161. public:
  205162. TemporaryImage() {}
  205163. ~TemporaryImage() {}
  205164. const Image& getImage (const bool transparent, const int w, const int h)
  205165. {
  205166. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  205167. if ((! image.isValid()) || image.getWidth() < w || image.getHeight() < h || image.getFormat() != format)
  205168. image = Image (new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false));
  205169. startTimer (3000);
  205170. return image;
  205171. }
  205172. void timerCallback()
  205173. {
  205174. stopTimer();
  205175. image = Image();
  205176. }
  205177. private:
  205178. Image image;
  205179. TemporaryImage (const TemporaryImage&);
  205180. TemporaryImage& operator= (const TemporaryImage&);
  205181. };
  205182. TemporaryImage offscreenImageGenerator;
  205183. class WindowClassHolder : public DeletedAtShutdown
  205184. {
  205185. public:
  205186. WindowClassHolder()
  205187. : windowClassName ("JUCE_")
  205188. {
  205189. // this name has to be different for each app/dll instance because otherwise
  205190. // poor old Win32 can get a bit confused (even despite it not being a process-global
  205191. // window class).
  205192. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  205193. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  205194. TCHAR moduleFile [1024];
  205195. moduleFile[0] = 0;
  205196. GetModuleFileName (moduleHandle, moduleFile, 1024);
  205197. WORD iconNum = 0;
  205198. WNDCLASSEX wcex;
  205199. wcex.cbSize = sizeof (wcex);
  205200. wcex.style = CS_OWNDC;
  205201. wcex.lpfnWndProc = (WNDPROC) windowProc;
  205202. wcex.lpszClassName = windowClassName;
  205203. wcex.cbClsExtra = 0;
  205204. wcex.cbWndExtra = 32;
  205205. wcex.hInstance = moduleHandle;
  205206. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  205207. iconNum = 1;
  205208. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  205209. wcex.hCursor = 0;
  205210. wcex.hbrBackground = 0;
  205211. wcex.lpszMenuName = 0;
  205212. RegisterClassEx (&wcex);
  205213. }
  205214. ~WindowClassHolder()
  205215. {
  205216. if (ComponentPeer::getNumPeers() == 0)
  205217. UnregisterClass (windowClassName, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  205218. clearSingletonInstance();
  205219. }
  205220. String windowClassName;
  205221. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  205222. };
  205223. static void* createWindowCallback (void* userData)
  205224. {
  205225. static_cast <Win32ComponentPeer*> (userData)->createWindow();
  205226. return 0;
  205227. }
  205228. void createWindow()
  205229. {
  205230. DWORD exstyle = WS_EX_ACCEPTFILES;
  205231. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  205232. if (hasTitleBar())
  205233. {
  205234. type |= WS_OVERLAPPED;
  205235. if ((styleFlags & windowHasCloseButton) != 0)
  205236. {
  205237. type |= WS_SYSMENU;
  205238. }
  205239. else
  205240. {
  205241. // annoyingly, windows won't let you have a min/max button without a close button
  205242. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  205243. }
  205244. if ((styleFlags & windowIsResizable) != 0)
  205245. type |= WS_THICKFRAME;
  205246. }
  205247. else
  205248. {
  205249. type |= WS_POPUP | WS_SYSMENU;
  205250. }
  205251. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  205252. exstyle |= WS_EX_TOOLWINDOW;
  205253. else
  205254. exstyle |= WS_EX_APPWINDOW;
  205255. if ((styleFlags & windowHasMinimiseButton) != 0)
  205256. type |= WS_MINIMIZEBOX;
  205257. if ((styleFlags & windowHasMaximiseButton) != 0)
  205258. type |= WS_MAXIMIZEBOX;
  205259. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  205260. exstyle |= WS_EX_TRANSPARENT;
  205261. if ((styleFlags & windowIsSemiTransparent) != 0
  205262. && Desktop::canUseSemiTransparentWindows())
  205263. exstyle |= WS_EX_LAYERED;
  205264. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName, L"", type, 0, 0, 0, 0, 0, 0, 0, 0);
  205265. if (hwnd != 0)
  205266. {
  205267. SetWindowLongPtr (hwnd, 0, 0);
  205268. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  205269. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  205270. if (dropTarget == 0)
  205271. dropTarget = new JuceDropTarget (this);
  205272. RegisterDragDrop (hwnd, dropTarget);
  205273. updateBorderSize();
  205274. // Calling this function here is (for some reason) necessary to make Windows
  205275. // correctly enable the menu items that we specify in the wm_initmenu message.
  205276. GetSystemMenu (hwnd, false);
  205277. }
  205278. else
  205279. {
  205280. jassertfalse;
  205281. }
  205282. }
  205283. static void* destroyWindowCallback (void* handle)
  205284. {
  205285. RevokeDragDrop ((HWND) handle);
  205286. DestroyWindow ((HWND) handle);
  205287. return 0;
  205288. }
  205289. static void* toFrontCallback1 (void* h)
  205290. {
  205291. SetForegroundWindow ((HWND) h);
  205292. return 0;
  205293. }
  205294. static void* toFrontCallback2 (void* h)
  205295. {
  205296. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  205297. return 0;
  205298. }
  205299. static void* setFocusCallback (void* h)
  205300. {
  205301. SetFocus ((HWND) h);
  205302. return 0;
  205303. }
  205304. static void* getFocusCallback (void*)
  205305. {
  205306. return GetFocus();
  205307. }
  205308. void offsetWithinParent (int& x, int& y) const
  205309. {
  205310. if (isTransparent())
  205311. {
  205312. HWND parentHwnd = GetParent (hwnd);
  205313. if (parentHwnd != 0)
  205314. {
  205315. RECT parentRect;
  205316. GetWindowRect (parentHwnd, &parentRect);
  205317. x += parentRect.left;
  205318. y += parentRect.top;
  205319. }
  205320. }
  205321. }
  205322. bool isTransparent() const
  205323. {
  205324. return (GetWindowLong (hwnd, GWL_EXSTYLE) & WS_EX_LAYERED) != 0;
  205325. }
  205326. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  205327. void setIcon (const Image& newIcon)
  205328. {
  205329. HICON hicon = createHICONFromImage (newIcon, TRUE, 0, 0);
  205330. if (hicon != 0)
  205331. {
  205332. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  205333. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  205334. if (currentWindowIcon != 0)
  205335. DestroyIcon (currentWindowIcon);
  205336. currentWindowIcon = hicon;
  205337. }
  205338. }
  205339. void handlePaintMessage()
  205340. {
  205341. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  205342. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  205343. PAINTSTRUCT paintStruct;
  205344. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  205345. // message and become re-entrant, but that's OK
  205346. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  205347. // corrupt the image it's using to paint into, so do a check here.
  205348. static bool reentrant = false;
  205349. if (reentrant)
  205350. {
  205351. DeleteObject (rgn);
  205352. EndPaint (hwnd, &paintStruct);
  205353. return;
  205354. }
  205355. reentrant = true;
  205356. // this is the rectangle to update..
  205357. int x = paintStruct.rcPaint.left;
  205358. int y = paintStruct.rcPaint.top;
  205359. int w = paintStruct.rcPaint.right - x;
  205360. int h = paintStruct.rcPaint.bottom - y;
  205361. const bool transparent = isTransparent();
  205362. if (transparent)
  205363. {
  205364. // it's not possible to have a transparent window with a title bar at the moment!
  205365. jassert (! hasTitleBar());
  205366. RECT r;
  205367. GetWindowRect (hwnd, &r);
  205368. x = y = 0;
  205369. w = r.right - r.left;
  205370. h = r.bottom - r.top;
  205371. }
  205372. if (w > 0 && h > 0)
  205373. {
  205374. clearMaskedRegion();
  205375. Image offscreenImage (offscreenImageGenerator.getImage (transparent, w, h));
  205376. RectangleList contextClip;
  205377. const Rectangle<int> clipBounds (0, 0, w, h);
  205378. bool needToPaintAll = true;
  205379. if (regionType == COMPLEXREGION && ! transparent)
  205380. {
  205381. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  205382. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  205383. DeleteObject (clipRgn);
  205384. char rgnData [8192];
  205385. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  205386. if (res > 0 && res <= sizeof (rgnData))
  205387. {
  205388. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  205389. if (hdr->iType == RDH_RECTANGLES
  205390. && hdr->rcBound.right - hdr->rcBound.left >= w
  205391. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  205392. {
  205393. needToPaintAll = false;
  205394. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  205395. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  205396. while (--num >= 0)
  205397. {
  205398. if (rects->right <= x + w && rects->bottom <= y + h)
  205399. {
  205400. // (need to move this one pixel to the left because of a win32 bug)
  205401. const int cx = jmax (x, (int) rects->left - 1);
  205402. contextClip.addWithoutMerging (Rectangle<int> (cx - x, rects->top - y, rects->right - cx, rects->bottom - rects->top)
  205403. .getIntersection (clipBounds));
  205404. }
  205405. else
  205406. {
  205407. needToPaintAll = true;
  205408. break;
  205409. }
  205410. ++rects;
  205411. }
  205412. }
  205413. }
  205414. }
  205415. if (needToPaintAll)
  205416. {
  205417. contextClip.clear();
  205418. contextClip.addWithoutMerging (Rectangle<int> (0, 0, w, h));
  205419. }
  205420. if (transparent)
  205421. {
  205422. RectangleList::Iterator i (contextClip);
  205423. while (i.next())
  205424. offscreenImage.clear (*i.getRectangle());
  205425. }
  205426. // if the component's not opaque, this won't draw properly unless the platform can support this
  205427. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  205428. updateCurrentModifiers();
  205429. LowLevelGraphicsSoftwareRenderer context (offscreenImage, -x, -y, contextClip);
  205430. handlePaint (context);
  205431. if (! dontRepaint)
  205432. static_cast <WindowsBitmapImage*> (offscreenImage.getSharedImage())
  205433. ->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion);
  205434. }
  205435. DeleteObject (rgn);
  205436. EndPaint (hwnd, &paintStruct);
  205437. reentrant = false;
  205438. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  205439. _fpreset(); // because some graphics cards can unmask FP exceptions
  205440. #endif
  205441. lastPaintTime = Time::getMillisecondCounter();
  205442. }
  205443. void doMouseEvent (const Point<int>& position)
  205444. {
  205445. handleMouseEvent (0, position, currentModifiers, getMouseEventTime());
  205446. }
  205447. void doMouseMove (const Point<int>& position)
  205448. {
  205449. if (! isMouseOver)
  205450. {
  205451. isMouseOver = true;
  205452. updateKeyModifiers();
  205453. TRACKMOUSEEVENT tme;
  205454. tme.cbSize = sizeof (tme);
  205455. tme.dwFlags = TME_LEAVE;
  205456. tme.hwndTrack = hwnd;
  205457. tme.dwHoverTime = 0;
  205458. if (! TrackMouseEvent (&tme))
  205459. jassertfalse;
  205460. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  205461. }
  205462. else if (! isDragging)
  205463. {
  205464. if (! contains (position, false))
  205465. return;
  205466. }
  205467. // (Throttling the incoming queue of mouse-events seems to still be required in XP..)
  205468. static uint32 lastMouseTime = 0;
  205469. const uint32 now = Time::getMillisecondCounter();
  205470. const int maxMouseMovesPerSecond = 60;
  205471. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  205472. {
  205473. lastMouseTime = now;
  205474. doMouseEvent (position);
  205475. }
  205476. }
  205477. void doMouseDown (const Point<int>& position, const WPARAM wParam)
  205478. {
  205479. if (GetCapture() != hwnd)
  205480. SetCapture (hwnd);
  205481. doMouseMove (position);
  205482. updateModifiersFromWParam (wParam);
  205483. isDragging = true;
  205484. doMouseEvent (position);
  205485. }
  205486. void doMouseUp (const Point<int>& position, const WPARAM wParam)
  205487. {
  205488. updateModifiersFromWParam (wParam);
  205489. isDragging = false;
  205490. // release the mouse capture if the user has released all buttons
  205491. if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) == 0 && hwnd == GetCapture())
  205492. ReleaseCapture();
  205493. doMouseEvent (position);
  205494. }
  205495. void doCaptureChanged()
  205496. {
  205497. if (isDragging)
  205498. doMouseUp (getCurrentMousePos(), (WPARAM) 0);
  205499. }
  205500. void doMouseExit()
  205501. {
  205502. isMouseOver = false;
  205503. doMouseEvent (getCurrentMousePos());
  205504. }
  205505. void doMouseWheel (const Point<int>& position, const WPARAM wParam, const bool isVertical)
  205506. {
  205507. updateKeyModifiers();
  205508. const float amount = jlimit (-1000.0f, 1000.0f, 0.75f * (short) HIWORD (wParam));
  205509. handleMouseWheel (0, position, getMouseEventTime(),
  205510. isVertical ? 0.0f : amount,
  205511. isVertical ? amount : 0.0f);
  205512. }
  205513. void sendModifierKeyChangeIfNeeded()
  205514. {
  205515. if (modifiersAtLastCallback != currentModifiers)
  205516. {
  205517. modifiersAtLastCallback = currentModifiers;
  205518. handleModifierKeysChange();
  205519. }
  205520. }
  205521. bool doKeyUp (const WPARAM key)
  205522. {
  205523. updateKeyModifiers();
  205524. switch (key)
  205525. {
  205526. case VK_SHIFT:
  205527. case VK_CONTROL:
  205528. case VK_MENU:
  205529. case VK_CAPITAL:
  205530. case VK_LWIN:
  205531. case VK_RWIN:
  205532. case VK_APPS:
  205533. case VK_NUMLOCK:
  205534. case VK_SCROLL:
  205535. case VK_LSHIFT:
  205536. case VK_RSHIFT:
  205537. case VK_LCONTROL:
  205538. case VK_LMENU:
  205539. case VK_RCONTROL:
  205540. case VK_RMENU:
  205541. sendModifierKeyChangeIfNeeded();
  205542. }
  205543. return handleKeyUpOrDown (false)
  205544. || Component::getCurrentlyModalComponent() != 0;
  205545. }
  205546. bool doKeyDown (const WPARAM key)
  205547. {
  205548. updateKeyModifiers();
  205549. bool used = false;
  205550. switch (key)
  205551. {
  205552. case VK_SHIFT:
  205553. case VK_LSHIFT:
  205554. case VK_RSHIFT:
  205555. case VK_CONTROL:
  205556. case VK_LCONTROL:
  205557. case VK_RCONTROL:
  205558. case VK_MENU:
  205559. case VK_LMENU:
  205560. case VK_RMENU:
  205561. case VK_LWIN:
  205562. case VK_RWIN:
  205563. case VK_CAPITAL:
  205564. case VK_NUMLOCK:
  205565. case VK_SCROLL:
  205566. case VK_APPS:
  205567. sendModifierKeyChangeIfNeeded();
  205568. break;
  205569. case VK_LEFT:
  205570. case VK_RIGHT:
  205571. case VK_UP:
  205572. case VK_DOWN:
  205573. case VK_PRIOR:
  205574. case VK_NEXT:
  205575. case VK_HOME:
  205576. case VK_END:
  205577. case VK_DELETE:
  205578. case VK_INSERT:
  205579. case VK_F1:
  205580. case VK_F2:
  205581. case VK_F3:
  205582. case VK_F4:
  205583. case VK_F5:
  205584. case VK_F6:
  205585. case VK_F7:
  205586. case VK_F8:
  205587. case VK_F9:
  205588. case VK_F10:
  205589. case VK_F11:
  205590. case VK_F12:
  205591. case VK_F13:
  205592. case VK_F14:
  205593. case VK_F15:
  205594. case VK_F16:
  205595. used = handleKeyUpOrDown (true);
  205596. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  205597. break;
  205598. case VK_ADD:
  205599. case VK_SUBTRACT:
  205600. case VK_MULTIPLY:
  205601. case VK_DIVIDE:
  205602. case VK_SEPARATOR:
  205603. case VK_DECIMAL:
  205604. used = handleKeyUpOrDown (true);
  205605. break;
  205606. default:
  205607. used = handleKeyUpOrDown (true);
  205608. {
  205609. MSG msg;
  205610. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  205611. {
  205612. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  205613. // manually generate the key-press event that matches this key-down.
  205614. const UINT keyChar = MapVirtualKey (key, 2);
  205615. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  205616. }
  205617. }
  205618. break;
  205619. }
  205620. if (Component::getCurrentlyModalComponent() != 0)
  205621. used = true;
  205622. return used;
  205623. }
  205624. bool doKeyChar (int key, const LPARAM flags)
  205625. {
  205626. updateKeyModifiers();
  205627. juce_wchar textChar = (juce_wchar) key;
  205628. const int virtualScanCode = (flags >> 16) & 0xff;
  205629. if (key >= '0' && key <= '9')
  205630. {
  205631. switch (virtualScanCode) // check for a numeric keypad scan-code
  205632. {
  205633. case 0x52:
  205634. case 0x4f:
  205635. case 0x50:
  205636. case 0x51:
  205637. case 0x4b:
  205638. case 0x4c:
  205639. case 0x4d:
  205640. case 0x47:
  205641. case 0x48:
  205642. case 0x49:
  205643. key = (key - '0') + KeyPress::numberPad0;
  205644. break;
  205645. default:
  205646. break;
  205647. }
  205648. }
  205649. else
  205650. {
  205651. // convert the scan code to an unmodified character code..
  205652. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  205653. UINT keyChar = MapVirtualKey (virtualKey, 2);
  205654. keyChar = LOWORD (keyChar);
  205655. if (keyChar != 0)
  205656. key = (int) keyChar;
  205657. // avoid sending junk text characters for some control-key combinations
  205658. if (textChar < ' ' && currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  205659. textChar = 0;
  205660. }
  205661. return handleKeyPress (key, textChar);
  205662. }
  205663. bool doAppCommand (const LPARAM lParam)
  205664. {
  205665. int key = 0;
  205666. switch (GET_APPCOMMAND_LPARAM (lParam))
  205667. {
  205668. case APPCOMMAND_MEDIA_PLAY_PAUSE:
  205669. key = KeyPress::playKey;
  205670. break;
  205671. case APPCOMMAND_MEDIA_STOP:
  205672. key = KeyPress::stopKey;
  205673. break;
  205674. case APPCOMMAND_MEDIA_NEXTTRACK:
  205675. key = KeyPress::fastForwardKey;
  205676. break;
  205677. case APPCOMMAND_MEDIA_PREVIOUSTRACK:
  205678. key = KeyPress::rewindKey;
  205679. break;
  205680. }
  205681. if (key != 0)
  205682. {
  205683. updateKeyModifiers();
  205684. if (hwnd == GetActiveWindow())
  205685. {
  205686. handleKeyPress (key, 0);
  205687. return true;
  205688. }
  205689. }
  205690. return false;
  205691. }
  205692. class JuceDropTarget : public ComBaseClassHelper <IDropTarget>
  205693. {
  205694. public:
  205695. JuceDropTarget (Win32ComponentPeer* const owner_)
  205696. : owner (owner_)
  205697. {
  205698. }
  205699. ~JuceDropTarget() {}
  205700. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  205701. {
  205702. updateFileList (pDataObject);
  205703. owner->handleFileDragMove (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  205704. *pdwEffect = DROPEFFECT_COPY;
  205705. return S_OK;
  205706. }
  205707. HRESULT __stdcall DragLeave()
  205708. {
  205709. owner->handleFileDragExit (files);
  205710. return S_OK;
  205711. }
  205712. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  205713. {
  205714. owner->handleFileDragMove (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  205715. *pdwEffect = DROPEFFECT_COPY;
  205716. return S_OK;
  205717. }
  205718. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  205719. {
  205720. updateFileList (pDataObject);
  205721. owner->handleFileDragDrop (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  205722. *pdwEffect = DROPEFFECT_COPY;
  205723. return S_OK;
  205724. }
  205725. private:
  205726. Win32ComponentPeer* const owner;
  205727. StringArray files;
  205728. void updateFileList (IDataObject* const pDataObject)
  205729. {
  205730. files.clear();
  205731. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  205732. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  205733. if (pDataObject->GetData (&format, &medium) == S_OK)
  205734. {
  205735. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  205736. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  205737. unsigned int i = 0;
  205738. if (pDropFiles->fWide)
  205739. {
  205740. const WCHAR* const fname = (WCHAR*) (((const char*) pDropFiles) + sizeof (DROPFILES));
  205741. for (;;)
  205742. {
  205743. unsigned int len = 0;
  205744. while (i + len < totalLen && fname [i + len] != 0)
  205745. ++len;
  205746. if (len == 0)
  205747. break;
  205748. files.add (String (fname + i, len));
  205749. i += len + 1;
  205750. }
  205751. }
  205752. else
  205753. {
  205754. const char* const fname = ((const char*) pDropFiles) + sizeof (DROPFILES);
  205755. for (;;)
  205756. {
  205757. unsigned int len = 0;
  205758. while (i + len < totalLen && fname [i + len] != 0)
  205759. ++len;
  205760. if (len == 0)
  205761. break;
  205762. files.add (String (fname + i, len));
  205763. i += len + 1;
  205764. }
  205765. }
  205766. GlobalUnlock (medium.hGlobal);
  205767. }
  205768. }
  205769. JuceDropTarget (const JuceDropTarget&);
  205770. JuceDropTarget& operator= (const JuceDropTarget&);
  205771. };
  205772. void doSettingChange()
  205773. {
  205774. Desktop::getInstance().refreshMonitorSizes();
  205775. if (fullScreen && ! isMinimised())
  205776. {
  205777. const Rectangle<int> r (component->getParentMonitorArea());
  205778. SetWindowPos (hwnd, 0,
  205779. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  205780. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  205781. }
  205782. }
  205783. public:
  205784. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  205785. {
  205786. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  205787. if (peer != 0)
  205788. return peer->peerWindowProc (h, message, wParam, lParam);
  205789. return DefWindowProcW (h, message, wParam, lParam);
  205790. }
  205791. private:
  205792. static const Point<int> getPointFromLParam (LPARAM lParam) throw()
  205793. {
  205794. return Point<int> (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  205795. }
  205796. const Point<int> getCurrentMousePos() throw()
  205797. {
  205798. RECT wr;
  205799. GetWindowRect (hwnd, &wr);
  205800. const DWORD mp = GetMessagePos();
  205801. return Point<int> (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  205802. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop());
  205803. }
  205804. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  205805. {
  205806. if (isValidPeer (this))
  205807. {
  205808. switch (message)
  205809. {
  205810. case WM_NCHITTEST:
  205811. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  205812. return HTTRANSPARENT;
  205813. if (hasTitleBar())
  205814. break;
  205815. return HTCLIENT;
  205816. case WM_PAINT:
  205817. handlePaintMessage();
  205818. return 0;
  205819. case WM_NCPAINT:
  205820. if (wParam != 1)
  205821. handlePaintMessage();
  205822. if (hasTitleBar())
  205823. break;
  205824. return 0;
  205825. case WM_ERASEBKGND:
  205826. case WM_NCCALCSIZE:
  205827. if (hasTitleBar())
  205828. break;
  205829. return 1;
  205830. case WM_MOUSEMOVE:
  205831. doMouseMove (getPointFromLParam (lParam));
  205832. return 0;
  205833. case WM_MOUSELEAVE:
  205834. doMouseExit();
  205835. return 0;
  205836. case WM_LBUTTONDOWN:
  205837. case WM_MBUTTONDOWN:
  205838. case WM_RBUTTONDOWN:
  205839. doMouseDown (getPointFromLParam (lParam), wParam);
  205840. return 0;
  205841. case WM_LBUTTONUP:
  205842. case WM_MBUTTONUP:
  205843. case WM_RBUTTONUP:
  205844. doMouseUp (getPointFromLParam (lParam), wParam);
  205845. return 0;
  205846. case WM_CAPTURECHANGED:
  205847. doCaptureChanged();
  205848. return 0;
  205849. case WM_NCMOUSEMOVE:
  205850. if (hasTitleBar())
  205851. break;
  205852. return 0;
  205853. case 0x020A: /* WM_MOUSEWHEEL */
  205854. doMouseWheel (getCurrentMousePos(), wParam, true);
  205855. return 0;
  205856. case 0x020E: /* WM_MOUSEHWHEEL */
  205857. doMouseWheel (getCurrentMousePos(), wParam, false);
  205858. return 0;
  205859. case WM_WINDOWPOSCHANGING:
  205860. if ((styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  205861. {
  205862. WINDOWPOS* const wp = (WINDOWPOS*) lParam;
  205863. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE))
  205864. {
  205865. if (constrainer != 0)
  205866. {
  205867. const Rectangle<int> current (component->getX() - windowBorder.getLeft(),
  205868. component->getY() - windowBorder.getTop(),
  205869. component->getWidth() + windowBorder.getLeftAndRight(),
  205870. component->getHeight() + windowBorder.getTopAndBottom());
  205871. Rectangle<int> pos (wp->x, wp->y, wp->cx, wp->cy);
  205872. constrainer->checkBounds (pos, current,
  205873. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  205874. pos.getY() != current.getY() && pos.getBottom() == current.getBottom(),
  205875. pos.getX() != current.getX() && pos.getRight() == current.getRight(),
  205876. pos.getY() == current.getY() && pos.getBottom() != current.getBottom(),
  205877. pos.getX() == current.getX() && pos.getRight() != current.getRight());
  205878. wp->x = pos.getX();
  205879. wp->y = pos.getY();
  205880. wp->cx = pos.getWidth();
  205881. wp->cy = pos.getHeight();
  205882. }
  205883. }
  205884. }
  205885. return 0;
  205886. case WM_WINDOWPOSCHANGED:
  205887. handleMovedOrResized();
  205888. if (dontRepaint)
  205889. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  205890. return 0;
  205891. case WM_KEYDOWN:
  205892. case WM_SYSKEYDOWN:
  205893. if (doKeyDown (wParam))
  205894. return 0;
  205895. break;
  205896. case WM_KEYUP:
  205897. case WM_SYSKEYUP:
  205898. if (doKeyUp (wParam))
  205899. return 0;
  205900. break;
  205901. case WM_CHAR:
  205902. if (doKeyChar ((int) wParam, lParam))
  205903. return 0;
  205904. break;
  205905. case WM_APPCOMMAND:
  205906. if (doAppCommand (lParam))
  205907. return TRUE;
  205908. break;
  205909. case WM_SETFOCUS:
  205910. updateKeyModifiers();
  205911. handleFocusGain();
  205912. break;
  205913. case WM_KILLFOCUS:
  205914. if (hasCreatedCaret)
  205915. {
  205916. hasCreatedCaret = false;
  205917. DestroyCaret();
  205918. }
  205919. handleFocusLoss();
  205920. break;
  205921. case WM_ACTIVATEAPP:
  205922. // Windows does weird things to process priority when you swap apps,
  205923. // so this forces an update when the app is brought to the front
  205924. if (wParam != FALSE)
  205925. juce_repeatLastProcessPriority();
  205926. else
  205927. Desktop::getInstance().setKioskModeComponent (0); // turn kiosk mode off if we lose focus
  205928. juce_CheckCurrentlyFocusedTopLevelWindow();
  205929. modifiersAtLastCallback = -1;
  205930. return 0;
  205931. case WM_ACTIVATE:
  205932. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  205933. {
  205934. modifiersAtLastCallback = -1;
  205935. updateKeyModifiers();
  205936. if (isMinimised())
  205937. {
  205938. component->repaint();
  205939. handleMovedOrResized();
  205940. if (! ComponentPeer::isValidPeer (this))
  205941. return 0;
  205942. }
  205943. if (LOWORD (wParam) == WA_CLICKACTIVE
  205944. && component->isCurrentlyBlockedByAnotherModalComponent())
  205945. {
  205946. const Point<int> mousePos (component->getMouseXYRelative());
  205947. Component* const underMouse = component->getComponentAt (mousePos.getX(), mousePos.getY());
  205948. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  205949. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  205950. return 0;
  205951. }
  205952. handleBroughtToFront();
  205953. if (component->isCurrentlyBlockedByAnotherModalComponent())
  205954. Component::getCurrentlyModalComponent()->toFront (true);
  205955. return 0;
  205956. }
  205957. break;
  205958. case WM_NCACTIVATE:
  205959. // while a temporary window is being shown, prevent Windows from deactivating the
  205960. // title bars of our main windows.
  205961. if (wParam == 0 && ! shouldDeactivateTitleBar)
  205962. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  205963. break;
  205964. case WM_MOUSEACTIVATE:
  205965. if (! component->getMouseClickGrabsKeyboardFocus())
  205966. return MA_NOACTIVATE;
  205967. break;
  205968. case WM_SHOWWINDOW:
  205969. if (wParam != 0)
  205970. handleBroughtToFront();
  205971. break;
  205972. case WM_CLOSE:
  205973. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  205974. handleUserClosingWindow();
  205975. return 0;
  205976. case WM_QUERYENDSESSION:
  205977. if (JUCEApplication::getInstance() != 0)
  205978. {
  205979. JUCEApplication::getInstance()->systemRequestedQuit();
  205980. return MessageManager::getInstance()->hasStopMessageBeenSent();
  205981. }
  205982. return TRUE;
  205983. case WM_TRAYNOTIFY:
  205984. if (component->isCurrentlyBlockedByAnotherModalComponent())
  205985. {
  205986. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  205987. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  205988. {
  205989. Component* const current = Component::getCurrentlyModalComponent();
  205990. if (current != 0)
  205991. current->inputAttemptWhenModal();
  205992. }
  205993. }
  205994. else
  205995. {
  205996. ModifierKeys eventMods (ModifierKeys::getCurrentModifiersRealtime());
  205997. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  205998. eventMods = eventMods.withFlags (ModifierKeys::leftButtonModifier);
  205999. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  206000. eventMods = eventMods.withFlags (ModifierKeys::rightButtonModifier);
  206001. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  206002. eventMods = eventMods.withoutMouseButtons();
  206003. const MouseEvent e (Desktop::getInstance().getMainMouseSource(),
  206004. Point<int>(), eventMods, component, component, getMouseEventTime(),
  206005. Point<int>(), getMouseEventTime(), 1, false);
  206006. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  206007. {
  206008. SetFocus (hwnd);
  206009. SetForegroundWindow (hwnd);
  206010. component->mouseDown (e);
  206011. }
  206012. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  206013. {
  206014. component->mouseUp (e);
  206015. }
  206016. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  206017. {
  206018. component->mouseDoubleClick (e);
  206019. }
  206020. else if (lParam == WM_MOUSEMOVE)
  206021. {
  206022. component->mouseMove (e);
  206023. }
  206024. }
  206025. break;
  206026. case WM_SYNCPAINT:
  206027. return 0;
  206028. case WM_PALETTECHANGED:
  206029. InvalidateRect (h, 0, 0);
  206030. break;
  206031. case WM_DISPLAYCHANGE:
  206032. InvalidateRect (h, 0, 0);
  206033. createPaletteIfNeeded = true;
  206034. // intentional fall-through...
  206035. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  206036. doSettingChange();
  206037. break;
  206038. case WM_INITMENU:
  206039. if (! hasTitleBar())
  206040. {
  206041. if (isFullScreen())
  206042. {
  206043. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  206044. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  206045. }
  206046. else if (! isMinimised())
  206047. {
  206048. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  206049. }
  206050. }
  206051. break;
  206052. case WM_SYSCOMMAND:
  206053. switch (wParam & 0xfff0)
  206054. {
  206055. case SC_CLOSE:
  206056. if (sendInputAttemptWhenModalMessage())
  206057. return 0;
  206058. if (hasTitleBar())
  206059. {
  206060. PostMessage (h, WM_CLOSE, 0, 0);
  206061. return 0;
  206062. }
  206063. break;
  206064. case SC_KEYMENU:
  206065. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very
  206066. // obscure situations that can arise if a modal loop is started from an alt-key
  206067. // keypress).
  206068. if (hasTitleBar() && h == GetCapture())
  206069. ReleaseCapture();
  206070. break;
  206071. case SC_MAXIMIZE:
  206072. if (sendInputAttemptWhenModalMessage())
  206073. return 0;
  206074. setFullScreen (true);
  206075. return 0;
  206076. case SC_MINIMIZE:
  206077. if (sendInputAttemptWhenModalMessage())
  206078. return 0;
  206079. if (! hasTitleBar())
  206080. {
  206081. setMinimised (true);
  206082. return 0;
  206083. }
  206084. break;
  206085. case SC_RESTORE:
  206086. if (sendInputAttemptWhenModalMessage())
  206087. return 0;
  206088. if (hasTitleBar())
  206089. {
  206090. if (isFullScreen())
  206091. {
  206092. setFullScreen (false);
  206093. return 0;
  206094. }
  206095. }
  206096. else
  206097. {
  206098. if (isMinimised())
  206099. setMinimised (false);
  206100. else if (isFullScreen())
  206101. setFullScreen (false);
  206102. return 0;
  206103. }
  206104. break;
  206105. }
  206106. break;
  206107. case WM_NCLBUTTONDOWN:
  206108. case WM_NCRBUTTONDOWN:
  206109. case WM_NCMBUTTONDOWN:
  206110. sendInputAttemptWhenModalMessage();
  206111. break;
  206112. //case WM_IME_STARTCOMPOSITION;
  206113. // return 0;
  206114. case WM_GETDLGCODE:
  206115. return DLGC_WANTALLKEYS;
  206116. default:
  206117. break;
  206118. }
  206119. }
  206120. return DefWindowProcW (h, message, wParam, lParam);
  206121. }
  206122. bool sendInputAttemptWhenModalMessage()
  206123. {
  206124. if (component->isCurrentlyBlockedByAnotherModalComponent())
  206125. {
  206126. Component* const current = Component::getCurrentlyModalComponent();
  206127. if (current != 0)
  206128. current->inputAttemptWhenModal();
  206129. return true;
  206130. }
  206131. return false;
  206132. }
  206133. Win32ComponentPeer (const Win32ComponentPeer&);
  206134. Win32ComponentPeer& operator= (const Win32ComponentPeer&);
  206135. };
  206136. ModifierKeys Win32ComponentPeer::currentModifiers;
  206137. ModifierKeys Win32ComponentPeer::modifiersAtLastCallback;
  206138. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  206139. {
  206140. return new Win32ComponentPeer (this, styleFlags);
  206141. }
  206142. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  206143. void ModifierKeys::updateCurrentModifiers() throw()
  206144. {
  206145. currentModifiers = Win32ComponentPeer::currentModifiers;
  206146. }
  206147. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  206148. {
  206149. Win32ComponentPeer::updateKeyModifiers();
  206150. int keyMods = 0;
  206151. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::leftButtonModifier;
  206152. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::rightButtonModifier;
  206153. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::middleButtonModifier;
  206154. Win32ComponentPeer::currentModifiers
  206155. = Win32ComponentPeer::currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  206156. return Win32ComponentPeer::currentModifiers;
  206157. }
  206158. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  206159. {
  206160. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  206161. if (wp != 0)
  206162. wp->setTaskBarIcon (newImage);
  206163. }
  206164. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  206165. {
  206166. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  206167. if (wp != 0)
  206168. wp->setTaskBarIconToolTip (tooltip);
  206169. }
  206170. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  206171. {
  206172. DWORD val = GetWindowLong (h, styleType);
  206173. if (bitIsSet)
  206174. val |= feature;
  206175. else
  206176. val &= ~feature;
  206177. SetWindowLongPtr (h, styleType, val);
  206178. SetWindowPos (h, 0, 0, 0, 0, 0,
  206179. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  206180. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  206181. }
  206182. bool Process::isForegroundProcess()
  206183. {
  206184. HWND fg = GetForegroundWindow();
  206185. if (fg == 0)
  206186. return true;
  206187. // when running as a plugin in IE8, the browser UI runs in a different process to the plugin, so
  206188. // process ID isn't a reliable way to check if the foreground window belongs to us - instead, we
  206189. // have to see if any of our windows are children of the foreground window
  206190. fg = GetAncestor (fg, GA_ROOT);
  206191. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  206192. {
  206193. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (ComponentPeer::getPeer (i));
  206194. if (wp != 0 && wp->isInside (fg))
  206195. return true;
  206196. }
  206197. return false;
  206198. }
  206199. bool AlertWindow::showNativeDialogBox (const String& title,
  206200. const String& bodyText,
  206201. bool isOkCancel)
  206202. {
  206203. return MessageBox (0, bodyText, title,
  206204. MB_SETFOREGROUND | (isOkCancel ? MB_OKCANCEL
  206205. : MB_OK)) == IDOK;
  206206. }
  206207. void Desktop::createMouseInputSources()
  206208. {
  206209. mouseSources.add (new MouseInputSource (0, true));
  206210. }
  206211. const Point<int> Desktop::getMousePosition()
  206212. {
  206213. POINT mousePos;
  206214. GetCursorPos (&mousePos);
  206215. return Point<int> (mousePos.x, mousePos.y);
  206216. }
  206217. void Desktop::setMousePosition (const Point<int>& newPosition)
  206218. {
  206219. SetCursorPos (newPosition.getX(), newPosition.getY());
  206220. }
  206221. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  206222. {
  206223. return createSoftwareImage (format, width, height, clearImage);
  206224. }
  206225. class ScreenSaverDefeater : public Timer,
  206226. public DeletedAtShutdown
  206227. {
  206228. public:
  206229. ScreenSaverDefeater()
  206230. {
  206231. startTimer (10000);
  206232. timerCallback();
  206233. }
  206234. ~ScreenSaverDefeater() {}
  206235. void timerCallback()
  206236. {
  206237. if (Process::isForegroundProcess())
  206238. {
  206239. // simulate a shift key getting pressed..
  206240. INPUT input[2];
  206241. input[0].type = INPUT_KEYBOARD;
  206242. input[0].ki.wVk = VK_SHIFT;
  206243. input[0].ki.dwFlags = 0;
  206244. input[0].ki.dwExtraInfo = 0;
  206245. input[1].type = INPUT_KEYBOARD;
  206246. input[1].ki.wVk = VK_SHIFT;
  206247. input[1].ki.dwFlags = KEYEVENTF_KEYUP;
  206248. input[1].ki.dwExtraInfo = 0;
  206249. SendInput (2, input, sizeof (INPUT));
  206250. }
  206251. }
  206252. };
  206253. static ScreenSaverDefeater* screenSaverDefeater = 0;
  206254. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  206255. {
  206256. if (isEnabled)
  206257. deleteAndZero (screenSaverDefeater);
  206258. else if (screenSaverDefeater == 0)
  206259. screenSaverDefeater = new ScreenSaverDefeater();
  206260. }
  206261. bool Desktop::isScreenSaverEnabled()
  206262. {
  206263. return screenSaverDefeater == 0;
  206264. }
  206265. /* (The code below is the "correct" way to disable the screen saver, but it
  206266. completely fails on winXP when the saver is password-protected...)
  206267. static bool juce_screenSaverEnabled = true;
  206268. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  206269. {
  206270. juce_screenSaverEnabled = isEnabled;
  206271. SetThreadExecutionState (isEnabled ? ES_CONTINUOUS
  206272. : (ES_DISPLAY_REQUIRED | ES_CONTINUOUS));
  206273. }
  206274. bool Desktop::isScreenSaverEnabled() throw()
  206275. {
  206276. return juce_screenSaverEnabled;
  206277. }
  206278. */
  206279. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  206280. {
  206281. if (enableOrDisable)
  206282. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  206283. }
  206284. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  206285. {
  206286. Array <Rectangle<int> >* const monitorCoords = (Array <Rectangle<int> >*) userInfo;
  206287. monitorCoords->add (Rectangle<int> (r->left, r->top, r->right - r->left, r->bottom - r->top));
  206288. return TRUE;
  206289. }
  206290. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  206291. {
  206292. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  206293. // make sure the first in the list is the main monitor
  206294. for (int i = 1; i < monitorCoords.size(); ++i)
  206295. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  206296. monitorCoords.swap (i, 0);
  206297. if (monitorCoords.size() == 0)
  206298. {
  206299. RECT r;
  206300. GetWindowRect (GetDesktopWindow(), &r);
  206301. monitorCoords.add (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  206302. }
  206303. if (clipToWorkArea)
  206304. {
  206305. // clip the main monitor to the active non-taskbar area
  206306. RECT r;
  206307. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  206308. Rectangle<int>& screen = monitorCoords.getReference (0);
  206309. screen.setPosition (jmax (screen.getX(), (int) r.left),
  206310. jmax (screen.getY(), (int) r.top));
  206311. screen.setSize (jmin (screen.getRight(), (int) r.right) - screen.getX(),
  206312. jmin (screen.getBottom(), (int) r.bottom) - screen.getY());
  206313. }
  206314. }
  206315. static const Image createImageFromHBITMAP (HBITMAP bitmap) throw()
  206316. {
  206317. Image im;
  206318. if (bitmap != 0)
  206319. {
  206320. BITMAP bm;
  206321. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  206322. && bm.bmWidth > 0 && bm.bmHeight > 0)
  206323. {
  206324. HDC tempDC = GetDC (0);
  206325. HDC dc = CreateCompatibleDC (tempDC);
  206326. ReleaseDC (0, tempDC);
  206327. SelectObject (dc, bitmap);
  206328. im = Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  206329. Image::BitmapData imageData (im, 0, 0, bm.bmWidth, bm.bmHeight, true);
  206330. for (int y = bm.bmHeight; --y >= 0;)
  206331. {
  206332. for (int x = bm.bmWidth; --x >= 0;)
  206333. {
  206334. COLORREF col = GetPixel (dc, x, y);
  206335. imageData.setPixelColour (x, y, Colour ((uint8) GetRValue (col),
  206336. (uint8) GetGValue (col),
  206337. (uint8) GetBValue (col)));
  206338. }
  206339. }
  206340. DeleteDC (dc);
  206341. }
  206342. }
  206343. return im;
  206344. }
  206345. static const Image createImageFromHICON (HICON icon) throw()
  206346. {
  206347. ICONINFO info;
  206348. if (GetIconInfo (icon, &info))
  206349. {
  206350. Image mask (createImageFromHBITMAP (info.hbmMask));
  206351. Image image (createImageFromHBITMAP (info.hbmColor));
  206352. if (mask.isValid() && image.isValid())
  206353. {
  206354. for (int y = image.getHeight(); --y >= 0;)
  206355. {
  206356. for (int x = image.getWidth(); --x >= 0;)
  206357. {
  206358. const float brightness = mask.getPixelAt (x, y).getBrightness();
  206359. if (brightness > 0.0f)
  206360. image.multiplyAlphaAt (x, y, 1.0f - brightness);
  206361. }
  206362. }
  206363. return image;
  206364. }
  206365. }
  206366. return Image();
  206367. }
  206368. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw()
  206369. {
  206370. WindowsBitmapImage* nativeBitmap = new WindowsBitmapImage (Image::ARGB, image.getWidth(), image.getHeight(), true);
  206371. Image bitmap (nativeBitmap);
  206372. {
  206373. Graphics g (bitmap);
  206374. g.drawImageAt (image, 0, 0);
  206375. }
  206376. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  206377. ICONINFO info;
  206378. info.fIcon = isIcon;
  206379. info.xHotspot = hotspotX;
  206380. info.yHotspot = hotspotY;
  206381. info.hbmMask = mask;
  206382. info.hbmColor = nativeBitmap->hBitmap;
  206383. HICON hi = CreateIconIndirect (&info);
  206384. DeleteObject (mask);
  206385. return hi;
  206386. }
  206387. const Image juce_createIconForFile (const File& file)
  206388. {
  206389. Image image;
  206390. WCHAR filename [1024];
  206391. file.getFullPathName().copyToUnicode (filename, 1023);
  206392. WORD iconNum = 0;
  206393. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  206394. filename, &iconNum);
  206395. if (icon != 0)
  206396. {
  206397. image = createImageFromHICON (icon);
  206398. DestroyIcon (icon);
  206399. }
  206400. return image;
  206401. }
  206402. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  206403. {
  206404. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  206405. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  206406. Image im (image);
  206407. if (im.getWidth() > maxW || im.getHeight() > maxH)
  206408. {
  206409. im = im.rescaled (maxW, maxH);
  206410. hotspotX = (hotspotX * maxW) / image.getWidth();
  206411. hotspotY = (hotspotY * maxH) / image.getHeight();
  206412. }
  206413. return createHICONFromImage (im, FALSE, hotspotX, hotspotY);
  206414. }
  206415. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  206416. {
  206417. if (cursorHandle != 0 && ! isStandard)
  206418. DestroyCursor ((HCURSOR) cursorHandle);
  206419. }
  206420. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  206421. {
  206422. LPCTSTR cursorName = IDC_ARROW;
  206423. switch (type)
  206424. {
  206425. case NormalCursor: break;
  206426. case NoCursor: return 0;
  206427. case WaitCursor: cursorName = IDC_WAIT; break;
  206428. case IBeamCursor: cursorName = IDC_IBEAM; break;
  206429. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  206430. case CrosshairCursor: cursorName = IDC_CROSS; break;
  206431. case CopyingCursor: break; // can't seem to find one of these in the win32 list..
  206432. case LeftRightResizeCursor:
  206433. case LeftEdgeResizeCursor:
  206434. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  206435. case UpDownResizeCursor:
  206436. case TopEdgeResizeCursor:
  206437. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  206438. case TopLeftCornerResizeCursor:
  206439. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  206440. case TopRightCornerResizeCursor:
  206441. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  206442. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  206443. case DraggingHandCursor:
  206444. {
  206445. static void* dragHandCursor = 0;
  206446. if (dragHandCursor == 0)
  206447. {
  206448. static const unsigned char dragHandData[] =
  206449. { 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,
  206450. 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,
  206451. 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 };
  206452. dragHandCursor = createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData)), 8, 7);
  206453. }
  206454. return dragHandCursor;
  206455. }
  206456. default:
  206457. jassertfalse; break;
  206458. }
  206459. HCURSOR cursorH = LoadCursor (0, cursorName);
  206460. if (cursorH == 0)
  206461. cursorH = LoadCursor (0, IDC_ARROW);
  206462. return cursorH;
  206463. }
  206464. void MouseCursor::showInWindow (ComponentPeer*) const
  206465. {
  206466. SetCursor ((HCURSOR) getHandle());
  206467. }
  206468. void MouseCursor::showInAllWindows() const
  206469. {
  206470. showInWindow (0);
  206471. }
  206472. class JuceDropSource : public ComBaseClassHelper <IDropSource>
  206473. {
  206474. public:
  206475. JuceDropSource() {}
  206476. ~JuceDropSource() {}
  206477. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  206478. {
  206479. if (escapePressed)
  206480. return DRAGDROP_S_CANCEL;
  206481. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  206482. return DRAGDROP_S_DROP;
  206483. return S_OK;
  206484. }
  206485. HRESULT __stdcall GiveFeedback (DWORD)
  206486. {
  206487. return DRAGDROP_S_USEDEFAULTCURSORS;
  206488. }
  206489. };
  206490. class JuceEnumFormatEtc : public ComBaseClassHelper <IEnumFORMATETC>
  206491. {
  206492. public:
  206493. JuceEnumFormatEtc (const FORMATETC* const format_)
  206494. : format (format_),
  206495. index (0)
  206496. {
  206497. }
  206498. ~JuceEnumFormatEtc() {}
  206499. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  206500. {
  206501. if (result == 0)
  206502. return E_POINTER;
  206503. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  206504. newOne->index = index;
  206505. *result = newOne;
  206506. return S_OK;
  206507. }
  206508. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  206509. {
  206510. if (pceltFetched != 0)
  206511. *pceltFetched = 0;
  206512. else if (celt != 1)
  206513. return S_FALSE;
  206514. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  206515. {
  206516. copyFormatEtc (lpFormatEtc [0], *format);
  206517. ++index;
  206518. if (pceltFetched != 0)
  206519. *pceltFetched = 1;
  206520. return S_OK;
  206521. }
  206522. return S_FALSE;
  206523. }
  206524. HRESULT __stdcall Skip (ULONG celt)
  206525. {
  206526. if (index + (int) celt >= 1)
  206527. return S_FALSE;
  206528. index += celt;
  206529. return S_OK;
  206530. }
  206531. HRESULT __stdcall Reset()
  206532. {
  206533. index = 0;
  206534. return S_OK;
  206535. }
  206536. private:
  206537. const FORMATETC* const format;
  206538. int index;
  206539. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  206540. {
  206541. dest = source;
  206542. if (source.ptd != 0)
  206543. {
  206544. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  206545. *(dest.ptd) = *(source.ptd);
  206546. }
  206547. }
  206548. JuceEnumFormatEtc (const JuceEnumFormatEtc&);
  206549. JuceEnumFormatEtc& operator= (const JuceEnumFormatEtc&);
  206550. };
  206551. class JuceDataObject : public ComBaseClassHelper <IDataObject>
  206552. {
  206553. public:
  206554. JuceDataObject (JuceDropSource* const dropSource_,
  206555. const FORMATETC* const format_,
  206556. const STGMEDIUM* const medium_)
  206557. : dropSource (dropSource_),
  206558. format (format_),
  206559. medium (medium_)
  206560. {
  206561. }
  206562. virtual ~JuceDataObject()
  206563. {
  206564. jassert (refCount == 0);
  206565. }
  206566. HRESULT __stdcall GetData (FORMATETC __RPC_FAR* pFormatEtc, STGMEDIUM __RPC_FAR* pMedium)
  206567. {
  206568. if ((pFormatEtc->tymed & format->tymed) != 0
  206569. && pFormatEtc->cfFormat == format->cfFormat
  206570. && pFormatEtc->dwAspect == format->dwAspect)
  206571. {
  206572. pMedium->tymed = format->tymed;
  206573. pMedium->pUnkForRelease = 0;
  206574. if (format->tymed == TYMED_HGLOBAL)
  206575. {
  206576. const SIZE_T len = GlobalSize (medium->hGlobal);
  206577. void* const src = GlobalLock (medium->hGlobal);
  206578. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  206579. memcpy (dst, src, len);
  206580. GlobalUnlock (medium->hGlobal);
  206581. pMedium->hGlobal = dst;
  206582. return S_OK;
  206583. }
  206584. }
  206585. return DV_E_FORMATETC;
  206586. }
  206587. HRESULT __stdcall QueryGetData (FORMATETC __RPC_FAR* f)
  206588. {
  206589. if (f == 0)
  206590. return E_INVALIDARG;
  206591. if (f->tymed == format->tymed
  206592. && f->cfFormat == format->cfFormat
  206593. && f->dwAspect == format->dwAspect)
  206594. return S_OK;
  206595. return DV_E_FORMATETC;
  206596. }
  206597. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC __RPC_FAR*, FORMATETC __RPC_FAR* pFormatEtcOut)
  206598. {
  206599. pFormatEtcOut->ptd = 0;
  206600. return E_NOTIMPL;
  206601. }
  206602. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC __RPC_FAR *__RPC_FAR *result)
  206603. {
  206604. if (result == 0)
  206605. return E_POINTER;
  206606. if (direction == DATADIR_GET)
  206607. {
  206608. *result = new JuceEnumFormatEtc (format);
  206609. return S_OK;
  206610. }
  206611. *result = 0;
  206612. return E_NOTIMPL;
  206613. }
  206614. HRESULT __stdcall GetDataHere (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*) { return DATA_E_FORMATETC; }
  206615. HRESULT __stdcall SetData (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*, BOOL) { return E_NOTIMPL; }
  206616. HRESULT __stdcall DAdvise (FORMATETC __RPC_FAR*, DWORD, IAdviseSink __RPC_FAR*, DWORD __RPC_FAR*) { return OLE_E_ADVISENOTSUPPORTED; }
  206617. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  206618. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA __RPC_FAR *__RPC_FAR *) { return OLE_E_ADVISENOTSUPPORTED; }
  206619. private:
  206620. JuceDropSource* const dropSource;
  206621. const FORMATETC* const format;
  206622. const STGMEDIUM* const medium;
  206623. JuceDataObject (const JuceDataObject&);
  206624. JuceDataObject& operator= (const JuceDataObject&);
  206625. };
  206626. static HDROP createHDrop (const StringArray& fileNames) throw()
  206627. {
  206628. int totalChars = 0;
  206629. for (int i = fileNames.size(); --i >= 0;)
  206630. totalChars += fileNames[i].length() + 1;
  206631. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  206632. sizeof (DROPFILES)
  206633. + sizeof (WCHAR) * (totalChars + 2));
  206634. if (hDrop != 0)
  206635. {
  206636. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  206637. pDropFiles->pFiles = sizeof (DROPFILES);
  206638. pDropFiles->fWide = true;
  206639. WCHAR* fname = (WCHAR*) (((char*) pDropFiles) + sizeof (DROPFILES));
  206640. for (int i = 0; i < fileNames.size(); ++i)
  206641. {
  206642. fileNames[i].copyToUnicode (fname, 2048);
  206643. fname += fileNames[i].length() + 1;
  206644. }
  206645. *fname = 0;
  206646. GlobalUnlock (hDrop);
  206647. }
  206648. return hDrop;
  206649. }
  206650. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo) throw()
  206651. {
  206652. JuceDropSource* const source = new JuceDropSource();
  206653. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  206654. DWORD effect;
  206655. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  206656. data->Release();
  206657. source->Release();
  206658. return res == DRAGDROP_S_DROP;
  206659. }
  206660. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  206661. {
  206662. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  206663. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  206664. medium.hGlobal = createHDrop (files);
  206665. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  206666. : DROPEFFECT_COPY);
  206667. }
  206668. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  206669. {
  206670. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  206671. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  206672. const int numChars = text.length();
  206673. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  206674. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (medium.hGlobal));
  206675. text.copyToUnicode (data, numChars + 1);
  206676. format.cfFormat = CF_UNICODETEXT;
  206677. GlobalUnlock (medium.hGlobal);
  206678. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  206679. }
  206680. #endif
  206681. /*** End of inlined file: juce_win32_Windowing.cpp ***/
  206682. /*** Start of inlined file: juce_win32_Fonts.cpp ***/
  206683. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206684. // compiled on its own).
  206685. #if JUCE_INCLUDED_FILE
  206686. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  206687. NEWTEXTMETRICEXW*,
  206688. int type,
  206689. LPARAM lParam)
  206690. {
  206691. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  206692. {
  206693. const String fontName (lpelfe->elfLogFont.lfFaceName);
  206694. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters ("@"));
  206695. }
  206696. return 1;
  206697. }
  206698. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  206699. NEWTEXTMETRICEXW*,
  206700. int type,
  206701. LPARAM lParam)
  206702. {
  206703. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  206704. {
  206705. LOGFONTW lf;
  206706. zerostruct (lf);
  206707. lf.lfWeight = FW_DONTCARE;
  206708. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  206709. lf.lfQuality = DEFAULT_QUALITY;
  206710. lf.lfCharSet = DEFAULT_CHARSET;
  206711. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  206712. lf.lfPitchAndFamily = FF_DONTCARE;
  206713. const String fontName (lpelfe->elfLogFont.lfFaceName);
  206714. fontName.copyToUnicode (lf.lfFaceName, LF_FACESIZE - 1);
  206715. HDC dc = CreateCompatibleDC (0);
  206716. EnumFontFamiliesEx (dc, &lf,
  206717. (FONTENUMPROCW) &wfontEnum2,
  206718. lParam, 0);
  206719. DeleteDC (dc);
  206720. }
  206721. return 1;
  206722. }
  206723. const StringArray Font::findAllTypefaceNames()
  206724. {
  206725. StringArray results;
  206726. HDC dc = CreateCompatibleDC (0);
  206727. {
  206728. LOGFONTW lf;
  206729. zerostruct (lf);
  206730. lf.lfWeight = FW_DONTCARE;
  206731. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  206732. lf.lfQuality = DEFAULT_QUALITY;
  206733. lf.lfCharSet = DEFAULT_CHARSET;
  206734. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  206735. lf.lfPitchAndFamily = FF_DONTCARE;
  206736. lf.lfFaceName[0] = 0;
  206737. EnumFontFamiliesEx (dc, &lf,
  206738. (FONTENUMPROCW) &wfontEnum1,
  206739. (LPARAM) &results, 0);
  206740. }
  206741. DeleteDC (dc);
  206742. results.sort (true);
  206743. return results;
  206744. }
  206745. extern bool juce_IsRunningInWine();
  206746. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  206747. {
  206748. if (juce_IsRunningInWine())
  206749. {
  206750. // If we're running in Wine, then use fonts that might be available on Linux..
  206751. defaultSans = "Bitstream Vera Sans";
  206752. defaultSerif = "Bitstream Vera Serif";
  206753. defaultFixed = "Bitstream Vera Sans Mono";
  206754. }
  206755. else
  206756. {
  206757. defaultSans = "Verdana";
  206758. defaultSerif = "Times";
  206759. defaultFixed = "Lucida Console";
  206760. }
  206761. }
  206762. class FontDCHolder : private DeletedAtShutdown
  206763. {
  206764. public:
  206765. FontDCHolder()
  206766. : dc (0), numKPs (0), size (0),
  206767. bold (false), italic (false)
  206768. {
  206769. }
  206770. ~FontDCHolder()
  206771. {
  206772. if (dc != 0)
  206773. {
  206774. DeleteDC (dc);
  206775. DeleteObject (fontH);
  206776. }
  206777. clearSingletonInstance();
  206778. }
  206779. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  206780. HDC loadFont (const String& fontName_, const bool bold_, const bool italic_, const int size_)
  206781. {
  206782. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  206783. {
  206784. fontName = fontName_;
  206785. bold = bold_;
  206786. italic = italic_;
  206787. size = size_;
  206788. if (dc != 0)
  206789. {
  206790. DeleteDC (dc);
  206791. DeleteObject (fontH);
  206792. kps.free();
  206793. }
  206794. fontH = 0;
  206795. dc = CreateCompatibleDC (0);
  206796. SetMapperFlags (dc, 0);
  206797. SetMapMode (dc, MM_TEXT);
  206798. LOGFONTW lfw;
  206799. zerostruct (lfw);
  206800. lfw.lfCharSet = DEFAULT_CHARSET;
  206801. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  206802. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  206803. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  206804. lfw.lfQuality = PROOF_QUALITY;
  206805. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  206806. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  206807. fontName.copyToUnicode (lfw.lfFaceName, LF_FACESIZE - 1);
  206808. lfw.lfHeight = size > 0 ? size : -256;
  206809. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  206810. if (standardSizedFont != 0)
  206811. {
  206812. if (SelectObject (dc, standardSizedFont) != 0)
  206813. {
  206814. fontH = standardSizedFont;
  206815. if (size == 0)
  206816. {
  206817. OUTLINETEXTMETRIC otm;
  206818. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  206819. {
  206820. lfw.lfHeight = -(int) otm.otmEMSquare;
  206821. fontH = CreateFontIndirect (&lfw);
  206822. SelectObject (dc, fontH);
  206823. DeleteObject (standardSizedFont);
  206824. }
  206825. }
  206826. }
  206827. else
  206828. {
  206829. jassertfalse;
  206830. }
  206831. }
  206832. else
  206833. {
  206834. jassertfalse;
  206835. }
  206836. }
  206837. return dc;
  206838. }
  206839. KERNINGPAIR* getKerningPairs (int& numKPs_)
  206840. {
  206841. if (kps == 0)
  206842. {
  206843. numKPs = GetKerningPairs (dc, 0, 0);
  206844. kps.calloc (numKPs);
  206845. GetKerningPairs (dc, numKPs, kps);
  206846. }
  206847. numKPs_ = numKPs;
  206848. return kps;
  206849. }
  206850. private:
  206851. HFONT fontH;
  206852. HDC dc;
  206853. String fontName;
  206854. HeapBlock <KERNINGPAIR> kps;
  206855. int numKPs, size;
  206856. bool bold, italic;
  206857. FontDCHolder (const FontDCHolder&);
  206858. FontDCHolder& operator= (const FontDCHolder&);
  206859. };
  206860. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  206861. class WindowsTypeface : public CustomTypeface
  206862. {
  206863. public:
  206864. WindowsTypeface (const Font& font)
  206865. {
  206866. HDC dc = FontDCHolder::getInstance()->loadFont (font.getTypefaceName(),
  206867. font.isBold(), font.isItalic(), 0);
  206868. TEXTMETRIC tm;
  206869. tm.tmAscent = tm.tmHeight = 1;
  206870. tm.tmDefaultChar = 0;
  206871. GetTextMetrics (dc, &tm);
  206872. setCharacteristics (font.getTypefaceName(),
  206873. tm.tmAscent / (float) tm.tmHeight,
  206874. font.isBold(), font.isItalic(),
  206875. tm.tmDefaultChar);
  206876. }
  206877. bool loadGlyphIfPossible (juce_wchar character)
  206878. {
  206879. HDC dc = FontDCHolder::getInstance()->loadFont (name, isBold, isItalic, 0);
  206880. GLYPHMETRICS gm;
  206881. {
  206882. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  206883. WORD index = 0;
  206884. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  206885. && index == 0xffff)
  206886. {
  206887. return false;
  206888. }
  206889. }
  206890. Path glyphPath;
  206891. TEXTMETRIC tm;
  206892. if (! GetTextMetrics (dc, &tm))
  206893. {
  206894. addGlyph (character, glyphPath, 0);
  206895. return true;
  206896. }
  206897. const float height = (float) tm.tmHeight;
  206898. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  206899. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  206900. &gm, 0, 0, &identityMatrix);
  206901. if (bufSize > 0)
  206902. {
  206903. HeapBlock<char> data (bufSize);
  206904. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  206905. bufSize, data, &identityMatrix);
  206906. const TTPOLYGONHEADER* pheader = reinterpret_cast<TTPOLYGONHEADER*> (data.getData());
  206907. const float scaleX = 1.0f / height;
  206908. const float scaleY = -1.0f / height;
  206909. while ((char*) pheader < data + bufSize)
  206910. {
  206911. float x = scaleX * pheader->pfxStart.x.value;
  206912. float y = scaleY * pheader->pfxStart.y.value;
  206913. glyphPath.startNewSubPath (x, y);
  206914. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  206915. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  206916. while ((const char*) curve < curveEnd)
  206917. {
  206918. if (curve->wType == TT_PRIM_LINE)
  206919. {
  206920. for (int i = 0; i < curve->cpfx; ++i)
  206921. {
  206922. x = scaleX * curve->apfx[i].x.value;
  206923. y = scaleY * curve->apfx[i].y.value;
  206924. glyphPath.lineTo (x, y);
  206925. }
  206926. }
  206927. else if (curve->wType == TT_PRIM_QSPLINE)
  206928. {
  206929. for (int i = 0; i < curve->cpfx - 1; ++i)
  206930. {
  206931. const float x2 = scaleX * curve->apfx[i].x.value;
  206932. const float y2 = scaleY * curve->apfx[i].y.value;
  206933. float x3, y3;
  206934. if (i < curve->cpfx - 2)
  206935. {
  206936. x3 = 0.5f * (x2 + scaleX * curve->apfx[i + 1].x.value);
  206937. y3 = 0.5f * (y2 + scaleY * curve->apfx[i + 1].y.value);
  206938. }
  206939. else
  206940. {
  206941. x3 = scaleX * curve->apfx[i + 1].x.value;
  206942. y3 = scaleY * curve->apfx[i + 1].y.value;
  206943. }
  206944. glyphPath.quadraticTo (x2, y2, x3, y3);
  206945. x = x3;
  206946. y = y3;
  206947. }
  206948. }
  206949. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  206950. }
  206951. pheader = (const TTPOLYGONHEADER*) curve;
  206952. glyphPath.closeSubPath();
  206953. }
  206954. }
  206955. addGlyph (character, glyphPath, gm.gmCellIncX / height);
  206956. int numKPs;
  206957. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  206958. for (int i = 0; i < numKPs; ++i)
  206959. {
  206960. if (kps[i].wFirst == character)
  206961. addKerningPair (kps[i].wFirst, kps[i].wSecond,
  206962. kps[i].iKernAmount / height);
  206963. }
  206964. return true;
  206965. }
  206966. juce_UseDebuggingNewOperator
  206967. };
  206968. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  206969. {
  206970. return new WindowsTypeface (font);
  206971. }
  206972. #endif
  206973. /*** End of inlined file: juce_win32_Fonts.cpp ***/
  206974. /*** Start of inlined file: juce_win32_FileChooser.cpp ***/
  206975. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206976. // compiled on its own).
  206977. #if JUCE_INCLUDED_FILE
  206978. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw();
  206979. namespace FileChooserHelpers
  206980. {
  206981. static const void* defaultDirPath = 0;
  206982. static String returnedString; // need this to get non-existent pathnames from the directory chooser
  206983. static Component* currentExtraFileWin = 0;
  206984. static bool areThereAnyAlwaysOnTopWindows()
  206985. {
  206986. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  206987. {
  206988. Component* c = Desktop::getInstance().getComponent (i);
  206989. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  206990. return true;
  206991. }
  206992. return false;
  206993. }
  206994. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM /*lpData*/)
  206995. {
  206996. if (msg == BFFM_INITIALIZED)
  206997. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) defaultDirPath);
  206998. else if (msg == BFFM_VALIDATEFAILEDW)
  206999. returnedString = (LPCWSTR) lParam;
  207000. else if (msg == BFFM_VALIDATEFAILEDA)
  207001. returnedString = (const char*) lParam;
  207002. return 0;
  207003. }
  207004. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  207005. {
  207006. if (currentExtraFileWin != 0)
  207007. {
  207008. if (uiMsg == WM_INITDIALOG)
  207009. {
  207010. HWND dialogH = GetParent (hdlg);
  207011. jassert (dialogH != 0);
  207012. if (dialogH == 0)
  207013. dialogH = hdlg;
  207014. RECT r, cr;
  207015. GetWindowRect (dialogH, &r);
  207016. GetClientRect (dialogH, &cr);
  207017. SetWindowPos (dialogH, 0,
  207018. r.left, r.top,
  207019. currentExtraFileWin->getWidth() + jmax (150, (int) (r.right - r.left)),
  207020. jmax (150, (int) (r.bottom - r.top)),
  207021. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  207022. currentExtraFileWin->setBounds (cr.right, cr.top, currentExtraFileWin->getWidth(), cr.bottom - cr.top);
  207023. currentExtraFileWin->getChildComponent(0)->setBounds (0, 0, currentExtraFileWin->getWidth(), currentExtraFileWin->getHeight());
  207024. SetParent ((HWND) currentExtraFileWin->getWindowHandle(), (HWND) dialogH);
  207025. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_CHILD, (dialogH != 0));
  207026. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_POPUP, (dialogH == 0));
  207027. }
  207028. else if (uiMsg == WM_NOTIFY)
  207029. {
  207030. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  207031. if (ofn->hdr.code == CDN_SELCHANGE)
  207032. {
  207033. FilePreviewComponent* comp = (FilePreviewComponent*) currentExtraFileWin->getChildComponent(0);
  207034. if (comp != 0)
  207035. {
  207036. TCHAR path [MAX_PATH * 2];
  207037. path[0] = 0;
  207038. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  207039. const String fn ((const WCHAR*) path);
  207040. comp->selectedFileChanged (File (fn));
  207041. }
  207042. }
  207043. }
  207044. }
  207045. return 0;
  207046. }
  207047. class FPComponentHolder : public Component
  207048. {
  207049. public:
  207050. FPComponentHolder()
  207051. {
  207052. setVisible (true);
  207053. setOpaque (true);
  207054. }
  207055. ~FPComponentHolder()
  207056. {
  207057. }
  207058. void paint (Graphics& g)
  207059. {
  207060. g.fillAll (Colours::lightgrey);
  207061. }
  207062. private:
  207063. FPComponentHolder (const FPComponentHolder&);
  207064. FPComponentHolder& operator= (const FPComponentHolder&);
  207065. };
  207066. }
  207067. void FileChooser::showPlatformDialog (Array<File>& results,
  207068. const String& title,
  207069. const File& currentFileOrDirectory,
  207070. const String& filter,
  207071. bool selectsDirectory,
  207072. bool /*selectsFiles*/,
  207073. bool isSaveDialogue,
  207074. bool warnAboutOverwritingExistingFiles,
  207075. bool selectMultipleFiles,
  207076. FilePreviewComponent* extraInfoComponent)
  207077. {
  207078. using namespace FileChooserHelpers;
  207079. const int numCharsAvailable = 32768;
  207080. MemoryBlock filenameSpace ((numCharsAvailable + 1) * sizeof (WCHAR), true);
  207081. WCHAR* const fname = (WCHAR*) filenameSpace.getData();
  207082. int fnameIdx = 0;
  207083. JUCE_TRY
  207084. {
  207085. // use a modal window as the parent for this dialog box
  207086. // to block input from other app windows
  207087. const Rectangle<int> mainMon (Desktop::getInstance().getMainMonitorArea());
  207088. Component w (String::empty);
  207089. w.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  207090. mainMon.getY() + mainMon.getHeight() / 4,
  207091. 0, 0);
  207092. w.setOpaque (true);
  207093. w.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  207094. w.addToDesktop (0);
  207095. if (extraInfoComponent == 0)
  207096. w.enterModalState();
  207097. String initialDir;
  207098. if (currentFileOrDirectory.isDirectory())
  207099. {
  207100. initialDir = currentFileOrDirectory.getFullPathName();
  207101. }
  207102. else
  207103. {
  207104. currentFileOrDirectory.getFileName().copyToUnicode (fname, numCharsAvailable);
  207105. initialDir = currentFileOrDirectory.getParentDirectory().getFullPathName();
  207106. }
  207107. if (currentExtraFileWin->isValidComponent())
  207108. {
  207109. jassertfalse;
  207110. return;
  207111. }
  207112. if (selectsDirectory)
  207113. {
  207114. LPITEMIDLIST list = 0;
  207115. filenameSpace.fillWith (0);
  207116. {
  207117. BROWSEINFO bi;
  207118. zerostruct (bi);
  207119. bi.hwndOwner = (HWND) w.getWindowHandle();
  207120. bi.pszDisplayName = fname;
  207121. bi.lpszTitle = title;
  207122. bi.lpfn = browseCallbackProc;
  207123. #ifdef BIF_USENEWUI
  207124. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  207125. #else
  207126. bi.ulFlags = 0x50;
  207127. #endif
  207128. defaultDirPath = (const WCHAR*) initialDir;
  207129. list = SHBrowseForFolder (&bi);
  207130. if (! SHGetPathFromIDListW (list, fname))
  207131. {
  207132. fname[0] = 0;
  207133. returnedString = String::empty;
  207134. }
  207135. }
  207136. LPMALLOC al;
  207137. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  207138. al->Free (list);
  207139. defaultDirPath = 0;
  207140. if (returnedString.isNotEmpty())
  207141. {
  207142. const String stringFName (fname);
  207143. results.add (File (stringFName).getSiblingFile (returnedString));
  207144. returnedString = String::empty;
  207145. return;
  207146. }
  207147. }
  207148. else
  207149. {
  207150. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  207151. if (warnAboutOverwritingExistingFiles)
  207152. flags |= OFN_OVERWRITEPROMPT;
  207153. if (selectMultipleFiles)
  207154. flags |= OFN_ALLOWMULTISELECT;
  207155. if (extraInfoComponent != 0)
  207156. {
  207157. flags |= OFN_ENABLEHOOK;
  207158. currentExtraFileWin = new FPComponentHolder();
  207159. currentExtraFileWin->addAndMakeVisible (extraInfoComponent);
  207160. currentExtraFileWin->setSize (jlimit (20, 800, extraInfoComponent->getWidth()),
  207161. extraInfoComponent->getHeight());
  207162. currentExtraFileWin->addToDesktop (0);
  207163. currentExtraFileWin->enterModalState();
  207164. }
  207165. {
  207166. WCHAR filters [1024];
  207167. zeromem (filters, sizeof (filters));
  207168. filter.copyToUnicode (filters, 1024);
  207169. filter.copyToUnicode (filters + filter.length() + 1,
  207170. 1022 - filter.length());
  207171. OPENFILENAMEW of;
  207172. zerostruct (of);
  207173. #ifdef OPENFILENAME_SIZE_VERSION_400W
  207174. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  207175. #else
  207176. of.lStructSize = sizeof (of);
  207177. #endif
  207178. of.hwndOwner = (HWND) w.getWindowHandle();
  207179. of.lpstrFilter = filters;
  207180. of.nFilterIndex = 1;
  207181. of.lpstrFile = fname;
  207182. of.nMaxFile = numCharsAvailable;
  207183. of.lpstrInitialDir = initialDir;
  207184. of.lpstrTitle = title;
  207185. of.Flags = flags;
  207186. if (extraInfoComponent != 0)
  207187. of.lpfnHook = &openCallback;
  207188. if (isSaveDialogue)
  207189. {
  207190. if (! GetSaveFileName (&of))
  207191. fname[0] = 0;
  207192. else
  207193. fnameIdx = of.nFileOffset;
  207194. }
  207195. else
  207196. {
  207197. if (! GetOpenFileName (&of))
  207198. fname[0] = 0;
  207199. else
  207200. fnameIdx = of.nFileOffset;
  207201. }
  207202. }
  207203. }
  207204. }
  207205. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  207206. catch (...)
  207207. {
  207208. fname[0] = 0;
  207209. }
  207210. #endif
  207211. deleteAndZero (currentExtraFileWin);
  207212. const WCHAR* const files = fname;
  207213. if (selectMultipleFiles && fnameIdx > 0 && files [fnameIdx - 1] == 0)
  207214. {
  207215. const WCHAR* filename = files + fnameIdx;
  207216. while (*filename != 0)
  207217. {
  207218. const String filepath (String (files) + "\\" + String (filename));
  207219. results.add (File (filepath));
  207220. filename += CharacterFunctions::length (filename) + 1;
  207221. }
  207222. }
  207223. else if (files[0] != 0)
  207224. {
  207225. results.add (File (files));
  207226. }
  207227. }
  207228. #endif
  207229. /*** End of inlined file: juce_win32_FileChooser.cpp ***/
  207230. /*** Start of inlined file: juce_win32_Misc.cpp ***/
  207231. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  207232. // compiled on its own).
  207233. #if JUCE_INCLUDED_FILE
  207234. void SystemClipboard::copyTextToClipboard (const String& text)
  207235. {
  207236. if (OpenClipboard (0) != 0)
  207237. {
  207238. if (EmptyClipboard() != 0)
  207239. {
  207240. const int len = text.length();
  207241. if (len > 0)
  207242. {
  207243. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE,
  207244. (len + 1) * sizeof (wchar_t));
  207245. if (bufH != 0)
  207246. {
  207247. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (bufH));
  207248. text.copyToUnicode (data, len);
  207249. GlobalUnlock (bufH);
  207250. SetClipboardData (CF_UNICODETEXT, bufH);
  207251. }
  207252. }
  207253. }
  207254. CloseClipboard();
  207255. }
  207256. }
  207257. const String SystemClipboard::getTextFromClipboard()
  207258. {
  207259. String result;
  207260. if (OpenClipboard (0) != 0)
  207261. {
  207262. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  207263. if (bufH != 0)
  207264. {
  207265. const wchar_t* const data = (const wchar_t*) GlobalLock (bufH);
  207266. if (data != 0)
  207267. {
  207268. result = String (data, (int) (GlobalSize (bufH) / sizeof (wchar_t)));
  207269. GlobalUnlock (bufH);
  207270. }
  207271. }
  207272. CloseClipboard();
  207273. }
  207274. return result;
  207275. }
  207276. #endif
  207277. /*** End of inlined file: juce_win32_Misc.cpp ***/
  207278. /*** Start of inlined file: juce_win32_ActiveXComponent.cpp ***/
  207279. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  207280. // compiled on its own).
  207281. #if JUCE_INCLUDED_FILE
  207282. namespace ActiveXHelpers
  207283. {
  207284. class JuceIStorage : public ComBaseClassHelper <IStorage>
  207285. {
  207286. public:
  207287. JuceIStorage() {}
  207288. ~JuceIStorage() {}
  207289. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  207290. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  207291. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  207292. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  207293. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  207294. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  207295. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  207296. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  207297. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  207298. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  207299. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  207300. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  207301. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  207302. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  207303. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  207304. juce_UseDebuggingNewOperator
  207305. };
  207306. class JuceOleInPlaceFrame : public ComBaseClassHelper <IOleInPlaceFrame>
  207307. {
  207308. HWND window;
  207309. public:
  207310. JuceOleInPlaceFrame (HWND window_) : window (window_) {}
  207311. ~JuceOleInPlaceFrame() {}
  207312. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  207313. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  207314. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  207315. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  207316. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  207317. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  207318. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  207319. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  207320. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  207321. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  207322. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  207323. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  207324. juce_UseDebuggingNewOperator
  207325. };
  207326. class JuceIOleInPlaceSite : public ComBaseClassHelper <IOleInPlaceSite>
  207327. {
  207328. HWND window;
  207329. JuceOleInPlaceFrame* frame;
  207330. public:
  207331. JuceIOleInPlaceSite (HWND window_)
  207332. : window (window_),
  207333. frame (new JuceOleInPlaceFrame (window))
  207334. {}
  207335. ~JuceIOleInPlaceSite()
  207336. {
  207337. frame->Release();
  207338. }
  207339. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  207340. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  207341. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  207342. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  207343. HRESULT __stdcall OnUIActivate() { return S_OK; }
  207344. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  207345. {
  207346. *lplpFrame = frame;
  207347. *lplpDoc = 0;
  207348. lpFrameInfo->fMDIApp = FALSE;
  207349. lpFrameInfo->hwndFrame = window;
  207350. lpFrameInfo->haccel = 0;
  207351. lpFrameInfo->cAccelEntries = 0;
  207352. return S_OK;
  207353. }
  207354. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  207355. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  207356. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  207357. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  207358. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  207359. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  207360. juce_UseDebuggingNewOperator
  207361. };
  207362. class JuceIOleClientSite : public ComBaseClassHelper <IOleClientSite>
  207363. {
  207364. JuceIOleInPlaceSite* inplaceSite;
  207365. public:
  207366. JuceIOleClientSite (HWND window)
  207367. : inplaceSite (new JuceIOleInPlaceSite (window))
  207368. {}
  207369. ~JuceIOleClientSite()
  207370. {
  207371. inplaceSite->Release();
  207372. }
  207373. HRESULT __stdcall QueryInterface (REFIID type, void __RPC_FAR* __RPC_FAR* result)
  207374. {
  207375. if (type == IID_IOleInPlaceSite)
  207376. {
  207377. inplaceSite->AddRef();
  207378. *result = static_cast <IOleInPlaceSite*> (inplaceSite);
  207379. return S_OK;
  207380. }
  207381. return ComBaseClassHelper <IOleClientSite>::QueryInterface (type, result);
  207382. }
  207383. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  207384. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  207385. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  207386. HRESULT __stdcall ShowObject() { return S_OK; }
  207387. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  207388. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  207389. juce_UseDebuggingNewOperator
  207390. };
  207391. static Array<ActiveXControlComponent*> activeXComps;
  207392. static HWND getHWND (const ActiveXControlComponent* const component)
  207393. {
  207394. HWND hwnd = 0;
  207395. const IID iid = IID_IOleWindow;
  207396. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  207397. if (window != 0)
  207398. {
  207399. window->GetWindow (&hwnd);
  207400. window->Release();
  207401. }
  207402. return hwnd;
  207403. }
  207404. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  207405. {
  207406. RECT activeXRect, peerRect;
  207407. GetWindowRect (hwnd, &activeXRect);
  207408. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  207409. const Point<int> mousePos (GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left,
  207410. GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top);
  207411. const int64 mouseEventTime = Win32ComponentPeer::getMouseEventTime();
  207412. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  207413. switch (message)
  207414. {
  207415. case WM_MOUSEMOVE:
  207416. case WM_LBUTTONDOWN:
  207417. case WM_MBUTTONDOWN:
  207418. case WM_RBUTTONDOWN:
  207419. case WM_LBUTTONUP:
  207420. case WM_MBUTTONUP:
  207421. case WM_RBUTTONUP:
  207422. peer->handleMouseEvent (0, mousePos, Win32ComponentPeer::currentModifiers, mouseEventTime);
  207423. break;
  207424. default:
  207425. break;
  207426. }
  207427. }
  207428. }
  207429. class ActiveXControlComponent::Pimpl : public ComponentMovementWatcher
  207430. {
  207431. ActiveXControlComponent* const owner;
  207432. bool wasShowing;
  207433. public:
  207434. HWND controlHWND;
  207435. IStorage* storage;
  207436. IOleClientSite* clientSite;
  207437. IOleObject* control;
  207438. Pimpl (HWND hwnd, ActiveXControlComponent* const owner_)
  207439. : ComponentMovementWatcher (owner_),
  207440. owner (owner_),
  207441. wasShowing (owner_ != 0 && owner_->isShowing()),
  207442. controlHWND (0),
  207443. storage (new ActiveXHelpers::JuceIStorage()),
  207444. clientSite (new ActiveXHelpers::JuceIOleClientSite (hwnd)),
  207445. control (0)
  207446. {
  207447. }
  207448. ~Pimpl()
  207449. {
  207450. if (control != 0)
  207451. {
  207452. control->Close (OLECLOSE_NOSAVE);
  207453. control->Release();
  207454. }
  207455. clientSite->Release();
  207456. storage->Release();
  207457. }
  207458. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  207459. {
  207460. Component* const topComp = owner->getTopLevelComponent();
  207461. if (topComp->getPeer() != 0)
  207462. {
  207463. const Point<int> pos (owner->relativePositionToOtherComponent (topComp, Point<int>()));
  207464. owner->setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), owner->getWidth(), owner->getHeight()));
  207465. }
  207466. }
  207467. void componentPeerChanged()
  207468. {
  207469. const bool isShowingNow = owner->isShowing();
  207470. if (wasShowing != isShowingNow)
  207471. {
  207472. wasShowing = isShowingNow;
  207473. owner->setControlVisible (isShowingNow);
  207474. }
  207475. componentMovedOrResized (true, true);
  207476. }
  207477. void componentVisibilityChanged (Component&)
  207478. {
  207479. componentPeerChanged();
  207480. }
  207481. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  207482. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  207483. {
  207484. for (int i = ActiveXHelpers::activeXComps.size(); --i >= 0;)
  207485. {
  207486. const ActiveXControlComponent* const ax = ActiveXHelpers::activeXComps.getUnchecked(i);
  207487. if (ax->control != 0 && ax->control->controlHWND == hwnd)
  207488. {
  207489. switch (message)
  207490. {
  207491. case WM_MOUSEMOVE:
  207492. case WM_LBUTTONDOWN:
  207493. case WM_MBUTTONDOWN:
  207494. case WM_RBUTTONDOWN:
  207495. case WM_LBUTTONUP:
  207496. case WM_MBUTTONUP:
  207497. case WM_RBUTTONUP:
  207498. case WM_LBUTTONDBLCLK:
  207499. case WM_MBUTTONDBLCLK:
  207500. case WM_RBUTTONDBLCLK:
  207501. if (ax->isShowing())
  207502. {
  207503. ComponentPeer* const peer = ax->getPeer();
  207504. if (peer != 0)
  207505. {
  207506. ActiveXHelpers::offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  207507. if (! ax->areMouseEventsAllowed())
  207508. return 0;
  207509. }
  207510. }
  207511. break;
  207512. default:
  207513. break;
  207514. }
  207515. return CallWindowProc ((WNDPROC) ax->originalWndProc, hwnd, message, wParam, lParam);
  207516. }
  207517. }
  207518. return DefWindowProc (hwnd, message, wParam, lParam);
  207519. }
  207520. };
  207521. ActiveXControlComponent::ActiveXControlComponent()
  207522. : originalWndProc (0),
  207523. mouseEventsAllowed (true)
  207524. {
  207525. ActiveXHelpers::activeXComps.add (this);
  207526. }
  207527. ActiveXControlComponent::~ActiveXControlComponent()
  207528. {
  207529. deleteControl();
  207530. ActiveXHelpers::activeXComps.removeValue (this);
  207531. }
  207532. void ActiveXControlComponent::paint (Graphics& g)
  207533. {
  207534. if (control == 0)
  207535. g.fillAll (Colours::lightgrey);
  207536. }
  207537. bool ActiveXControlComponent::createControl (const void* controlIID)
  207538. {
  207539. deleteControl();
  207540. ComponentPeer* const peer = getPeer();
  207541. // the component must have already been added to a real window when you call this!
  207542. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  207543. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  207544. {
  207545. const Point<int> pos (relativePositionToOtherComponent (getTopLevelComponent(), Point<int>()));
  207546. HWND hwnd = (HWND) peer->getNativeHandle();
  207547. ScopedPointer<Pimpl> newControl (new Pimpl (hwnd, this));
  207548. HRESULT hr;
  207549. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  207550. newControl->clientSite, newControl->storage,
  207551. (void**) &(newControl->control))) == S_OK)
  207552. {
  207553. newControl->control->SetHostNames (L"Juce", 0);
  207554. if (OleSetContainedObject (newControl->control, TRUE) == S_OK)
  207555. {
  207556. RECT rect;
  207557. rect.left = pos.getX();
  207558. rect.top = pos.getY();
  207559. rect.right = pos.getX() + getWidth();
  207560. rect.bottom = pos.getY() + getHeight();
  207561. if (newControl->control->DoVerb (OLEIVERB_SHOW, 0, newControl->clientSite, 0, hwnd, &rect) == S_OK)
  207562. {
  207563. control = newControl;
  207564. setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), getWidth(), getHeight()));
  207565. control->controlHWND = ActiveXHelpers::getHWND (this);
  207566. if (control->controlHWND != 0)
  207567. {
  207568. originalWndProc = (void*) (pointer_sized_int) GetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC);
  207569. SetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC, (LONG_PTR) Pimpl::activeXHookWndProc);
  207570. }
  207571. return true;
  207572. }
  207573. }
  207574. }
  207575. }
  207576. return false;
  207577. }
  207578. void ActiveXControlComponent::deleteControl()
  207579. {
  207580. control = 0;
  207581. originalWndProc = 0;
  207582. }
  207583. void* ActiveXControlComponent::queryInterface (const void* iid) const
  207584. {
  207585. void* result = 0;
  207586. if (control != 0 && control->control != 0
  207587. && SUCCEEDED (control->control->QueryInterface (*(const IID*) iid, &result)))
  207588. return result;
  207589. return 0;
  207590. }
  207591. void ActiveXControlComponent::setControlBounds (const Rectangle<int>& newBounds) const
  207592. {
  207593. if (control->controlHWND != 0)
  207594. MoveWindow (control->controlHWND, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  207595. }
  207596. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  207597. {
  207598. if (control->controlHWND != 0)
  207599. ShowWindow (control->controlHWND, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  207600. }
  207601. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  207602. {
  207603. mouseEventsAllowed = eventsCanReachControl;
  207604. }
  207605. #endif
  207606. /*** End of inlined file: juce_win32_ActiveXComponent.cpp ***/
  207607. /*** Start of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  207608. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  207609. // compiled on its own).
  207610. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  207611. using namespace QTOLibrary;
  207612. using namespace QTOControlLib;
  207613. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  207614. static bool isQTAvailable = false;
  207615. class QuickTimeMovieComponent::Pimpl
  207616. {
  207617. public:
  207618. Pimpl() : dataHandle (0)
  207619. {
  207620. }
  207621. ~Pimpl()
  207622. {
  207623. clearHandle();
  207624. }
  207625. void clearHandle()
  207626. {
  207627. if (dataHandle != 0)
  207628. {
  207629. DisposeHandle (dataHandle);
  207630. dataHandle = 0;
  207631. }
  207632. }
  207633. IQTControlPtr qtControl;
  207634. IQTMoviePtr qtMovie;
  207635. Handle dataHandle;
  207636. };
  207637. QuickTimeMovieComponent::QuickTimeMovieComponent()
  207638. : movieLoaded (false),
  207639. controllerVisible (true)
  207640. {
  207641. pimpl = new Pimpl();
  207642. setMouseEventsAllowed (false);
  207643. }
  207644. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  207645. {
  207646. closeMovie();
  207647. pimpl->qtControl = 0;
  207648. deleteControl();
  207649. pimpl = 0;
  207650. }
  207651. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  207652. {
  207653. if (! isQTAvailable)
  207654. isQTAvailable = (InitializeQTML (0) == noErr) && (EnterMovies() == noErr);
  207655. return isQTAvailable;
  207656. }
  207657. void QuickTimeMovieComponent::createControlIfNeeded()
  207658. {
  207659. if (isShowing() && ! isControlCreated())
  207660. {
  207661. const IID qtIID = __uuidof (QTControl);
  207662. if (createControl (&qtIID))
  207663. {
  207664. const IID qtInterfaceIID = __uuidof (IQTControl);
  207665. pimpl->qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  207666. if (pimpl->qtControl != 0)
  207667. {
  207668. pimpl->qtControl->Release(); // it has one ref too many at this point
  207669. pimpl->qtControl->QuickTimeInitialize();
  207670. pimpl->qtControl->PutSizing (qtMovieFitsControl);
  207671. if (movieFile != File::nonexistent)
  207672. loadMovie (movieFile, controllerVisible);
  207673. }
  207674. }
  207675. }
  207676. }
  207677. bool QuickTimeMovieComponent::isControlCreated() const
  207678. {
  207679. return isControlOpen();
  207680. }
  207681. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  207682. const bool isControllerVisible)
  207683. {
  207684. const ScopedPointer<InputStream> movieStreamDeleter (movieStream);
  207685. movieFile = File::nonexistent;
  207686. movieLoaded = false;
  207687. pimpl->qtMovie = 0;
  207688. controllerVisible = isControllerVisible;
  207689. createControlIfNeeded();
  207690. if (isControlCreated())
  207691. {
  207692. if (pimpl->qtControl != 0)
  207693. {
  207694. pimpl->qtControl->Put_MovieHandle (0);
  207695. pimpl->clearHandle();
  207696. Movie movie;
  207697. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, pimpl->dataHandle))
  207698. {
  207699. pimpl->qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  207700. pimpl->qtMovie = pimpl->qtControl->GetMovie();
  207701. if (pimpl->qtMovie != 0)
  207702. pimpl->qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  207703. : qtMovieControllerTypeNone);
  207704. }
  207705. if (movie == 0)
  207706. pimpl->clearHandle();
  207707. }
  207708. movieLoaded = (pimpl->qtMovie != 0);
  207709. }
  207710. else
  207711. {
  207712. // You're trying to open a movie when the control hasn't yet been created, probably because
  207713. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  207714. jassertfalse;
  207715. }
  207716. return movieLoaded;
  207717. }
  207718. void QuickTimeMovieComponent::closeMovie()
  207719. {
  207720. stop();
  207721. movieFile = File::nonexistent;
  207722. movieLoaded = false;
  207723. pimpl->qtMovie = 0;
  207724. if (pimpl->qtControl != 0)
  207725. pimpl->qtControl->Put_MovieHandle (0);
  207726. pimpl->clearHandle();
  207727. }
  207728. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  207729. {
  207730. return movieFile;
  207731. }
  207732. bool QuickTimeMovieComponent::isMovieOpen() const
  207733. {
  207734. return movieLoaded;
  207735. }
  207736. double QuickTimeMovieComponent::getMovieDuration() const
  207737. {
  207738. if (pimpl->qtMovie != 0)
  207739. return pimpl->qtMovie->GetDuration() / (double) pimpl->qtMovie->GetTimeScale();
  207740. return 0.0;
  207741. }
  207742. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  207743. {
  207744. if (pimpl->qtMovie != 0)
  207745. {
  207746. struct QTRECT r = pimpl->qtMovie->GetNaturalRect();
  207747. width = r.right - r.left;
  207748. height = r.bottom - r.top;
  207749. }
  207750. else
  207751. {
  207752. width = height = 0;
  207753. }
  207754. }
  207755. void QuickTimeMovieComponent::play()
  207756. {
  207757. if (pimpl->qtMovie != 0)
  207758. pimpl->qtMovie->Play();
  207759. }
  207760. void QuickTimeMovieComponent::stop()
  207761. {
  207762. if (pimpl->qtMovie != 0)
  207763. pimpl->qtMovie->Stop();
  207764. }
  207765. bool QuickTimeMovieComponent::isPlaying() const
  207766. {
  207767. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetRate() != 0.0f;
  207768. }
  207769. void QuickTimeMovieComponent::setPosition (const double seconds)
  207770. {
  207771. if (pimpl->qtMovie != 0)
  207772. pimpl->qtMovie->PutTime ((long) (seconds * pimpl->qtMovie->GetTimeScale()));
  207773. }
  207774. double QuickTimeMovieComponent::getPosition() const
  207775. {
  207776. if (pimpl->qtMovie != 0)
  207777. return pimpl->qtMovie->GetTime() / (double) pimpl->qtMovie->GetTimeScale();
  207778. return 0.0;
  207779. }
  207780. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  207781. {
  207782. if (pimpl->qtMovie != 0)
  207783. pimpl->qtMovie->PutRate (newSpeed);
  207784. }
  207785. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  207786. {
  207787. if (pimpl->qtMovie != 0)
  207788. {
  207789. pimpl->qtMovie->PutAudioVolume (newVolume);
  207790. pimpl->qtMovie->PutAudioMute (newVolume <= 0);
  207791. }
  207792. }
  207793. float QuickTimeMovieComponent::getMovieVolume() const
  207794. {
  207795. if (pimpl->qtMovie != 0)
  207796. return pimpl->qtMovie->GetAudioVolume();
  207797. return 0.0f;
  207798. }
  207799. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  207800. {
  207801. if (pimpl->qtMovie != 0)
  207802. pimpl->qtMovie->PutLoop (shouldLoop);
  207803. }
  207804. bool QuickTimeMovieComponent::isLooping() const
  207805. {
  207806. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetLoop();
  207807. }
  207808. bool QuickTimeMovieComponent::isControllerVisible() const
  207809. {
  207810. return controllerVisible;
  207811. }
  207812. void QuickTimeMovieComponent::parentHierarchyChanged()
  207813. {
  207814. createControlIfNeeded();
  207815. QTCompBaseClass::parentHierarchyChanged();
  207816. }
  207817. void QuickTimeMovieComponent::visibilityChanged()
  207818. {
  207819. createControlIfNeeded();
  207820. QTCompBaseClass::visibilityChanged();
  207821. }
  207822. void QuickTimeMovieComponent::paint (Graphics& g)
  207823. {
  207824. if (! isControlCreated())
  207825. g.fillAll (Colours::black);
  207826. }
  207827. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  207828. {
  207829. Handle dataRef = 0;
  207830. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  207831. if (err == noErr)
  207832. {
  207833. Str255 suffix;
  207834. CharacterFunctions::copy ((char*) suffix, fileName, 128);
  207835. StringPtr name = suffix;
  207836. err = PtrAndHand (name, dataRef, name[0] + 1);
  207837. if (err == noErr)
  207838. {
  207839. long atoms[3];
  207840. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  207841. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  207842. atoms[2] = EndianU32_NtoB (MovieFileType);
  207843. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  207844. if (err == noErr)
  207845. return dataRef;
  207846. }
  207847. DisposeHandle (dataRef);
  207848. }
  207849. return 0;
  207850. }
  207851. static CFStringRef juceStringToCFString (const String& s)
  207852. {
  207853. const int len = s.length();
  207854. const juce_wchar* const t = s;
  207855. HeapBlock <UniChar> temp (len + 2);
  207856. for (int i = 0; i <= len; ++i)
  207857. temp[i] = t[i];
  207858. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  207859. }
  207860. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  207861. {
  207862. Boolean trueBool = true;
  207863. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  207864. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  207865. props[prop].propValueSize = sizeof (trueBool);
  207866. props[prop].propValueAddress = &trueBool;
  207867. ++prop;
  207868. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  207869. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  207870. props[prop].propValueSize = sizeof (trueBool);
  207871. props[prop].propValueAddress = &trueBool;
  207872. ++prop;
  207873. Boolean isActive = true;
  207874. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  207875. props[prop].propID = kQTNewMoviePropertyID_Active;
  207876. props[prop].propValueSize = sizeof (isActive);
  207877. props[prop].propValueAddress = &isActive;
  207878. ++prop;
  207879. MacSetPort (0);
  207880. jassert (prop <= 5);
  207881. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  207882. return err == noErr;
  207883. }
  207884. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  207885. {
  207886. if (input == 0)
  207887. return false;
  207888. dataHandle = 0;
  207889. bool ok = false;
  207890. QTNewMoviePropertyElement props[5];
  207891. zeromem (props, sizeof (props));
  207892. int prop = 0;
  207893. DataReferenceRecord dr;
  207894. props[prop].propClass = kQTPropertyClass_DataLocation;
  207895. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  207896. props[prop].propValueSize = sizeof (dr);
  207897. props[prop].propValueAddress = &dr;
  207898. ++prop;
  207899. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  207900. if (fin != 0)
  207901. {
  207902. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  207903. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  207904. &dr.dataRef, &dr.dataRefType);
  207905. ok = openMovie (props, prop, movie);
  207906. DisposeHandle (dr.dataRef);
  207907. CFRelease (filePath);
  207908. }
  207909. else
  207910. {
  207911. // sanity-check because this currently needs to load the whole stream into memory..
  207912. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  207913. dataHandle = NewHandle ((Size) input->getTotalLength());
  207914. HLock (dataHandle);
  207915. // read the entire stream into memory - this is a pain, but can't get it to work
  207916. // properly using a custom callback to supply the data.
  207917. input->read (*dataHandle, (int) input->getTotalLength());
  207918. HUnlock (dataHandle);
  207919. // different types to get QT to try. (We should really be a bit smarter here by
  207920. // working out in advance which one the stream contains, rather than just trying
  207921. // each one)
  207922. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  207923. "\04.avi", "\04.m4a" };
  207924. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  207925. {
  207926. /* // this fails for some bizarre reason - it can be bodged to work with
  207927. // movies, but can't seem to do it for other file types..
  207928. QTNewMovieUserProcRecord procInfo;
  207929. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  207930. procInfo.getMovieUserProcRefcon = this;
  207931. procInfo.defaultDataRef.dataRef = dataRef;
  207932. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  207933. props[prop].propClass = kQTPropertyClass_DataLocation;
  207934. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  207935. props[prop].propValueSize = sizeof (procInfo);
  207936. props[prop].propValueAddress = (void*) &procInfo;
  207937. ++prop; */
  207938. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  207939. dr.dataRefType = HandleDataHandlerSubType;
  207940. ok = openMovie (props, prop, movie);
  207941. DisposeHandle (dr.dataRef);
  207942. }
  207943. }
  207944. return ok;
  207945. }
  207946. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  207947. const bool isControllerVisible)
  207948. {
  207949. const bool ok = loadMovie (static_cast <InputStream*> (movieFile_.createInputStream()), isControllerVisible);
  207950. movieFile = movieFile_;
  207951. return ok;
  207952. }
  207953. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  207954. const bool isControllerVisible)
  207955. {
  207956. return loadMovie (static_cast <InputStream*> (movieURL.createInputStream (false)), isControllerVisible);
  207957. }
  207958. void QuickTimeMovieComponent::goToStart()
  207959. {
  207960. setPosition (0.0);
  207961. }
  207962. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  207963. const RectanglePlacement& placement)
  207964. {
  207965. int normalWidth, normalHeight;
  207966. getMovieNormalSize (normalWidth, normalHeight);
  207967. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  207968. {
  207969. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  207970. placement.applyTo (x, y, w, h,
  207971. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  207972. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  207973. if (w > 0 && h > 0)
  207974. {
  207975. setBounds (roundToInt (x), roundToInt (y),
  207976. roundToInt (w), roundToInt (h));
  207977. }
  207978. }
  207979. else
  207980. {
  207981. setBounds (spaceToFitWithin);
  207982. }
  207983. }
  207984. #endif
  207985. /*** End of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  207986. /*** Start of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  207987. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  207988. // compiled on its own).
  207989. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  207990. class WebBrowserComponentInternal : public ActiveXControlComponent
  207991. {
  207992. public:
  207993. WebBrowserComponentInternal()
  207994. : browser (0),
  207995. connectionPoint (0),
  207996. adviseCookie (0)
  207997. {
  207998. }
  207999. ~WebBrowserComponentInternal()
  208000. {
  208001. if (connectionPoint != 0)
  208002. connectionPoint->Unadvise (adviseCookie);
  208003. if (browser != 0)
  208004. browser->Release();
  208005. }
  208006. void createBrowser()
  208007. {
  208008. createControl (&CLSID_WebBrowser);
  208009. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  208010. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  208011. if (connectionPointContainer != 0)
  208012. {
  208013. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  208014. &connectionPoint);
  208015. if (connectionPoint != 0)
  208016. {
  208017. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  208018. jassert (owner != 0);
  208019. EventHandler* handler = new EventHandler (owner);
  208020. connectionPoint->Advise (handler, &adviseCookie);
  208021. handler->Release();
  208022. }
  208023. }
  208024. }
  208025. void goToURL (const String& url,
  208026. const StringArray* headers,
  208027. const MemoryBlock* postData)
  208028. {
  208029. if (browser != 0)
  208030. {
  208031. LPSAFEARRAY sa = 0;
  208032. VARIANT flags, frame, postDataVar, headersVar; // (_variant_t isn't available in all compilers)
  208033. VariantInit (&flags);
  208034. VariantInit (&frame);
  208035. VariantInit (&postDataVar);
  208036. VariantInit (&headersVar);
  208037. if (headers != 0)
  208038. {
  208039. V_VT (&headersVar) = VT_BSTR;
  208040. V_BSTR (&headersVar) = SysAllocString ((const OLECHAR*) headers->joinIntoString ("\r\n"));
  208041. }
  208042. if (postData != 0 && postData->getSize() > 0)
  208043. {
  208044. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  208045. if (sa != 0)
  208046. {
  208047. void* data = 0;
  208048. SafeArrayAccessData (sa, &data);
  208049. jassert (data != 0);
  208050. if (data != 0)
  208051. {
  208052. postData->copyTo (data, 0, postData->getSize());
  208053. SafeArrayUnaccessData (sa);
  208054. VARIANT postDataVar2;
  208055. VariantInit (&postDataVar2);
  208056. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  208057. V_ARRAY (&postDataVar2) = sa;
  208058. postDataVar = postDataVar2;
  208059. }
  208060. }
  208061. }
  208062. browser->Navigate ((BSTR) (const OLECHAR*) url,
  208063. &flags, &frame,
  208064. &postDataVar, &headersVar);
  208065. if (sa != 0)
  208066. SafeArrayDestroy (sa);
  208067. VariantClear (&flags);
  208068. VariantClear (&frame);
  208069. VariantClear (&postDataVar);
  208070. VariantClear (&headersVar);
  208071. }
  208072. }
  208073. IWebBrowser2* browser;
  208074. juce_UseDebuggingNewOperator
  208075. private:
  208076. IConnectionPoint* connectionPoint;
  208077. DWORD adviseCookie;
  208078. class EventHandler : public ComBaseClassHelper <IDispatch>,
  208079. public ComponentMovementWatcher
  208080. {
  208081. public:
  208082. EventHandler (WebBrowserComponent* owner_)
  208083. : ComponentMovementWatcher (owner_),
  208084. owner (owner_)
  208085. {
  208086. }
  208087. ~EventHandler()
  208088. {
  208089. }
  208090. HRESULT __stdcall GetTypeInfoCount (UINT __RPC_FAR*) { return E_NOTIMPL; }
  208091. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo __RPC_FAR *__RPC_FAR*) { return E_NOTIMPL; }
  208092. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR __RPC_FAR*, UINT, LCID, DISPID __RPC_FAR*) { return E_NOTIMPL; }
  208093. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/,
  208094. WORD /*wFlags*/, DISPPARAMS __RPC_FAR* pDispParams,
  208095. VARIANT __RPC_FAR* /*pVarResult*/, EXCEPINFO __RPC_FAR* /*pExcepInfo*/,
  208096. UINT __RPC_FAR* /*puArgErr*/)
  208097. {
  208098. switch (dispIdMember)
  208099. {
  208100. case DISPID_BEFORENAVIGATE2:
  208101. {
  208102. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  208103. String url;
  208104. if ((vurl->vt & VT_BYREF) != 0)
  208105. url = *vurl->pbstrVal;
  208106. else
  208107. url = vurl->bstrVal;
  208108. *pDispParams->rgvarg->pboolVal
  208109. = owner->pageAboutToLoad (url) ? VARIANT_FALSE
  208110. : VARIANT_TRUE;
  208111. return S_OK;
  208112. }
  208113. default:
  208114. break;
  208115. }
  208116. return E_NOTIMPL;
  208117. }
  208118. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/) {}
  208119. void componentPeerChanged() {}
  208120. void componentVisibilityChanged (Component&)
  208121. {
  208122. owner->visibilityChanged();
  208123. }
  208124. juce_UseDebuggingNewOperator
  208125. private:
  208126. WebBrowserComponent* const owner;
  208127. EventHandler (const EventHandler&);
  208128. EventHandler& operator= (const EventHandler&);
  208129. };
  208130. };
  208131. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  208132. : browser (0),
  208133. blankPageShown (false),
  208134. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  208135. {
  208136. setOpaque (true);
  208137. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  208138. }
  208139. WebBrowserComponent::~WebBrowserComponent()
  208140. {
  208141. delete browser;
  208142. }
  208143. void WebBrowserComponent::goToURL (const String& url,
  208144. const StringArray* headers,
  208145. const MemoryBlock* postData)
  208146. {
  208147. lastURL = url;
  208148. lastHeaders.clear();
  208149. if (headers != 0)
  208150. lastHeaders = *headers;
  208151. lastPostData.setSize (0);
  208152. if (postData != 0)
  208153. lastPostData = *postData;
  208154. blankPageShown = false;
  208155. browser->goToURL (url, headers, postData);
  208156. }
  208157. void WebBrowserComponent::stop()
  208158. {
  208159. if (browser->browser != 0)
  208160. browser->browser->Stop();
  208161. }
  208162. void WebBrowserComponent::goBack()
  208163. {
  208164. lastURL = String::empty;
  208165. blankPageShown = false;
  208166. if (browser->browser != 0)
  208167. browser->browser->GoBack();
  208168. }
  208169. void WebBrowserComponent::goForward()
  208170. {
  208171. lastURL = String::empty;
  208172. if (browser->browser != 0)
  208173. browser->browser->GoForward();
  208174. }
  208175. void WebBrowserComponent::refresh()
  208176. {
  208177. if (browser->browser != 0)
  208178. browser->browser->Refresh();
  208179. }
  208180. void WebBrowserComponent::paint (Graphics& g)
  208181. {
  208182. if (browser->browser == 0)
  208183. g.fillAll (Colours::white);
  208184. }
  208185. void WebBrowserComponent::checkWindowAssociation()
  208186. {
  208187. if (isShowing())
  208188. {
  208189. if (browser->browser == 0 && getPeer() != 0)
  208190. {
  208191. browser->createBrowser();
  208192. reloadLastURL();
  208193. }
  208194. else
  208195. {
  208196. if (blankPageShown)
  208197. goBack();
  208198. }
  208199. }
  208200. else
  208201. {
  208202. if (browser != 0 && unloadPageWhenBrowserIsHidden && ! blankPageShown)
  208203. {
  208204. // when the component becomes invisible, some stuff like flash
  208205. // carries on playing audio, so we need to force it onto a blank
  208206. // page to avoid this..
  208207. blankPageShown = true;
  208208. browser->goToURL ("about:blank", 0, 0);
  208209. }
  208210. }
  208211. }
  208212. void WebBrowserComponent::reloadLastURL()
  208213. {
  208214. if (lastURL.isNotEmpty())
  208215. {
  208216. goToURL (lastURL, &lastHeaders, &lastPostData);
  208217. lastURL = String::empty;
  208218. }
  208219. }
  208220. void WebBrowserComponent::parentHierarchyChanged()
  208221. {
  208222. checkWindowAssociation();
  208223. }
  208224. void WebBrowserComponent::resized()
  208225. {
  208226. browser->setSize (getWidth(), getHeight());
  208227. }
  208228. void WebBrowserComponent::visibilityChanged()
  208229. {
  208230. checkWindowAssociation();
  208231. }
  208232. bool WebBrowserComponent::pageAboutToLoad (const String&)
  208233. {
  208234. return true;
  208235. }
  208236. #endif
  208237. /*** End of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  208238. /*** Start of inlined file: juce_win32_OpenGLComponent.cpp ***/
  208239. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208240. // compiled on its own).
  208241. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  208242. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  208243. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  208244. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  208245. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  208246. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  208247. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  208248. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  208249. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  208250. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  208251. #define WGL_ACCELERATION_ARB 0x2003
  208252. #define WGL_SWAP_METHOD_ARB 0x2007
  208253. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  208254. #define WGL_PIXEL_TYPE_ARB 0x2013
  208255. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  208256. #define WGL_COLOR_BITS_ARB 0x2014
  208257. #define WGL_RED_BITS_ARB 0x2015
  208258. #define WGL_GREEN_BITS_ARB 0x2017
  208259. #define WGL_BLUE_BITS_ARB 0x2019
  208260. #define WGL_ALPHA_BITS_ARB 0x201B
  208261. #define WGL_DEPTH_BITS_ARB 0x2022
  208262. #define WGL_STENCIL_BITS_ARB 0x2023
  208263. #define WGL_FULL_ACCELERATION_ARB 0x2027
  208264. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  208265. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  208266. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  208267. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  208268. #define WGL_STEREO_ARB 0x2012
  208269. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  208270. #define WGL_SAMPLES_ARB 0x2042
  208271. #define WGL_TYPE_RGBA_ARB 0x202B
  208272. static void getWglExtensions (HDC dc, StringArray& result) throw()
  208273. {
  208274. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  208275. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  208276. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  208277. else
  208278. jassertfalse; // If this fails, it may be because you didn't activate the openGL context
  208279. }
  208280. class WindowedGLContext : public OpenGLContext
  208281. {
  208282. public:
  208283. WindowedGLContext (Component* const component_,
  208284. HGLRC contextToShareWith,
  208285. const OpenGLPixelFormat& pixelFormat)
  208286. : renderContext (0),
  208287. nativeWindow (0),
  208288. dc (0),
  208289. component (component_)
  208290. {
  208291. jassert (component != 0);
  208292. createNativeWindow();
  208293. // Use a default pixel format that should be supported everywhere
  208294. PIXELFORMATDESCRIPTOR pfd;
  208295. zerostruct (pfd);
  208296. pfd.nSize = sizeof (pfd);
  208297. pfd.nVersion = 1;
  208298. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  208299. pfd.iPixelType = PFD_TYPE_RGBA;
  208300. pfd.cColorBits = 24;
  208301. pfd.cDepthBits = 16;
  208302. const int format = ChoosePixelFormat (dc, &pfd);
  208303. if (format != 0)
  208304. SetPixelFormat (dc, format, &pfd);
  208305. renderContext = wglCreateContext (dc);
  208306. makeActive();
  208307. setPixelFormat (pixelFormat);
  208308. if (contextToShareWith != 0 && renderContext != 0)
  208309. wglShareLists (contextToShareWith, renderContext);
  208310. }
  208311. ~WindowedGLContext()
  208312. {
  208313. makeInactive();
  208314. wglDeleteContext (renderContext);
  208315. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  208316. delete nativeWindow;
  208317. }
  208318. bool makeActive() const throw()
  208319. {
  208320. jassert (renderContext != 0);
  208321. return wglMakeCurrent (dc, renderContext) != 0;
  208322. }
  208323. bool makeInactive() const throw()
  208324. {
  208325. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  208326. }
  208327. bool isActive() const throw()
  208328. {
  208329. return wglGetCurrentContext() == renderContext;
  208330. }
  208331. const OpenGLPixelFormat getPixelFormat() const
  208332. {
  208333. OpenGLPixelFormat pf;
  208334. makeActive();
  208335. StringArray availableExtensions;
  208336. getWglExtensions (dc, availableExtensions);
  208337. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  208338. return pf;
  208339. }
  208340. void* getRawContext() const throw()
  208341. {
  208342. return renderContext;
  208343. }
  208344. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  208345. {
  208346. makeActive();
  208347. PIXELFORMATDESCRIPTOR pfd;
  208348. zerostruct (pfd);
  208349. pfd.nSize = sizeof (pfd);
  208350. pfd.nVersion = 1;
  208351. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  208352. pfd.iPixelType = PFD_TYPE_RGBA;
  208353. pfd.iLayerType = PFD_MAIN_PLANE;
  208354. pfd.cColorBits = (BYTE) (pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits);
  208355. pfd.cRedBits = (BYTE) pixelFormat.redBits;
  208356. pfd.cGreenBits = (BYTE) pixelFormat.greenBits;
  208357. pfd.cBlueBits = (BYTE) pixelFormat.blueBits;
  208358. pfd.cAlphaBits = (BYTE) pixelFormat.alphaBits;
  208359. pfd.cDepthBits = (BYTE) pixelFormat.depthBufferBits;
  208360. pfd.cStencilBits = (BYTE) pixelFormat.stencilBufferBits;
  208361. pfd.cAccumBits = (BYTE) (pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  208362. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits);
  208363. pfd.cAccumRedBits = (BYTE) pixelFormat.accumulationBufferRedBits;
  208364. pfd.cAccumGreenBits = (BYTE) pixelFormat.accumulationBufferGreenBits;
  208365. pfd.cAccumBlueBits = (BYTE) pixelFormat.accumulationBufferBlueBits;
  208366. pfd.cAccumAlphaBits = (BYTE) pixelFormat.accumulationBufferAlphaBits;
  208367. int format = 0;
  208368. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  208369. StringArray availableExtensions;
  208370. getWglExtensions (dc, availableExtensions);
  208371. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  208372. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  208373. {
  208374. int attributes[64];
  208375. int n = 0;
  208376. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  208377. attributes[n++] = GL_TRUE;
  208378. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  208379. attributes[n++] = GL_TRUE;
  208380. attributes[n++] = WGL_ACCELERATION_ARB;
  208381. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  208382. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  208383. attributes[n++] = GL_TRUE;
  208384. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  208385. attributes[n++] = WGL_TYPE_RGBA_ARB;
  208386. attributes[n++] = WGL_COLOR_BITS_ARB;
  208387. attributes[n++] = pfd.cColorBits;
  208388. attributes[n++] = WGL_RED_BITS_ARB;
  208389. attributes[n++] = pixelFormat.redBits;
  208390. attributes[n++] = WGL_GREEN_BITS_ARB;
  208391. attributes[n++] = pixelFormat.greenBits;
  208392. attributes[n++] = WGL_BLUE_BITS_ARB;
  208393. attributes[n++] = pixelFormat.blueBits;
  208394. attributes[n++] = WGL_ALPHA_BITS_ARB;
  208395. attributes[n++] = pixelFormat.alphaBits;
  208396. attributes[n++] = WGL_DEPTH_BITS_ARB;
  208397. attributes[n++] = pixelFormat.depthBufferBits;
  208398. if (pixelFormat.stencilBufferBits > 0)
  208399. {
  208400. attributes[n++] = WGL_STENCIL_BITS_ARB;
  208401. attributes[n++] = pixelFormat.stencilBufferBits;
  208402. }
  208403. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  208404. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  208405. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  208406. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  208407. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  208408. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  208409. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  208410. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  208411. if (availableExtensions.contains ("WGL_ARB_multisample")
  208412. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  208413. {
  208414. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  208415. attributes[n++] = 1;
  208416. attributes[n++] = WGL_SAMPLES_ARB;
  208417. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  208418. }
  208419. attributes[n++] = 0;
  208420. UINT formatsCount;
  208421. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  208422. (void) ok;
  208423. jassert (ok);
  208424. }
  208425. else
  208426. {
  208427. format = ChoosePixelFormat (dc, &pfd);
  208428. }
  208429. if (format != 0)
  208430. {
  208431. makeInactive();
  208432. // win32 can't change the pixel format of a window, so need to delete the
  208433. // old one and create a new one..
  208434. jassert (nativeWindow != 0);
  208435. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  208436. delete nativeWindow;
  208437. createNativeWindow();
  208438. if (SetPixelFormat (dc, format, &pfd))
  208439. {
  208440. wglDeleteContext (renderContext);
  208441. renderContext = wglCreateContext (dc);
  208442. jassert (renderContext != 0);
  208443. return renderContext != 0;
  208444. }
  208445. }
  208446. return false;
  208447. }
  208448. void updateWindowPosition (int x, int y, int w, int h, int)
  208449. {
  208450. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  208451. x, y, w, h,
  208452. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  208453. }
  208454. void repaint()
  208455. {
  208456. nativeWindow->repaint (nativeWindow->getBounds().withPosition (Point<int>()));
  208457. }
  208458. void swapBuffers()
  208459. {
  208460. SwapBuffers (dc);
  208461. }
  208462. bool setSwapInterval (int numFramesPerSwap)
  208463. {
  208464. makeActive();
  208465. StringArray availableExtensions;
  208466. getWglExtensions (dc, availableExtensions);
  208467. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  208468. return availableExtensions.contains ("WGL_EXT_swap_control")
  208469. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  208470. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  208471. }
  208472. int getSwapInterval() const
  208473. {
  208474. makeActive();
  208475. StringArray availableExtensions;
  208476. getWglExtensions (dc, availableExtensions);
  208477. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  208478. if (availableExtensions.contains ("WGL_EXT_swap_control")
  208479. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  208480. return wglGetSwapIntervalEXT();
  208481. return 0;
  208482. }
  208483. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  208484. {
  208485. jassert (isActive());
  208486. StringArray availableExtensions;
  208487. getWglExtensions (dc, availableExtensions);
  208488. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  208489. int numTypes = 0;
  208490. if (availableExtensions.contains("WGL_ARB_pixel_format")
  208491. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  208492. {
  208493. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  208494. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  208495. jassertfalse;
  208496. }
  208497. else
  208498. {
  208499. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  208500. }
  208501. OpenGLPixelFormat pf;
  208502. for (int i = 0; i < numTypes; ++i)
  208503. {
  208504. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  208505. {
  208506. bool alreadyListed = false;
  208507. for (int j = results.size(); --j >= 0;)
  208508. if (pf == *results.getUnchecked(j))
  208509. alreadyListed = true;
  208510. if (! alreadyListed)
  208511. results.add (new OpenGLPixelFormat (pf));
  208512. }
  208513. }
  208514. }
  208515. void* getNativeWindowHandle() const
  208516. {
  208517. return nativeWindow != 0 ? nativeWindow->getNativeHandle() : 0;
  208518. }
  208519. juce_UseDebuggingNewOperator
  208520. HGLRC renderContext;
  208521. private:
  208522. Win32ComponentPeer* nativeWindow;
  208523. Component* const component;
  208524. HDC dc;
  208525. void createNativeWindow()
  208526. {
  208527. nativeWindow = new Win32ComponentPeer (component, 0);
  208528. nativeWindow->dontRepaint = true;
  208529. nativeWindow->setVisible (true);
  208530. HWND hwnd = (HWND) nativeWindow->getNativeHandle();
  208531. Win32ComponentPeer* const peer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  208532. if (peer != 0)
  208533. {
  208534. SetParent (hwnd, (HWND) peer->getNativeHandle());
  208535. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_CHILD, true);
  208536. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_POPUP, false);
  208537. }
  208538. dc = GetDC (hwnd);
  208539. }
  208540. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  208541. OpenGLPixelFormat& result,
  208542. const StringArray& availableExtensions) const throw()
  208543. {
  208544. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  208545. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  208546. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  208547. {
  208548. int attributes[32];
  208549. int numAttributes = 0;
  208550. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  208551. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  208552. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  208553. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  208554. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  208555. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  208556. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  208557. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  208558. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  208559. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  208560. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  208561. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  208562. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  208563. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  208564. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  208565. if (availableExtensions.contains ("WGL_ARB_multisample"))
  208566. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  208567. int values[32];
  208568. zeromem (values, sizeof (values));
  208569. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  208570. {
  208571. int n = 0;
  208572. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  208573. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  208574. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  208575. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  208576. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  208577. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  208578. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  208579. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  208580. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  208581. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  208582. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  208583. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  208584. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  208585. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  208586. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  208587. result.fullSceneAntiAliasingNumSamples = (uint8) values[n++]; // WGL_SAMPLES_ARB
  208588. return isValidFormat;
  208589. }
  208590. else
  208591. {
  208592. jassertfalse;
  208593. }
  208594. }
  208595. else
  208596. {
  208597. PIXELFORMATDESCRIPTOR pfd;
  208598. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  208599. {
  208600. result.redBits = pfd.cRedBits;
  208601. result.greenBits = pfd.cGreenBits;
  208602. result.blueBits = pfd.cBlueBits;
  208603. result.alphaBits = pfd.cAlphaBits;
  208604. result.depthBufferBits = pfd.cDepthBits;
  208605. result.stencilBufferBits = pfd.cStencilBits;
  208606. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  208607. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  208608. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  208609. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  208610. result.fullSceneAntiAliasingNumSamples = 0;
  208611. return true;
  208612. }
  208613. else
  208614. {
  208615. jassertfalse;
  208616. }
  208617. }
  208618. return false;
  208619. }
  208620. WindowedGLContext (const WindowedGLContext&);
  208621. WindowedGLContext& operator= (const WindowedGLContext&);
  208622. };
  208623. OpenGLContext* OpenGLComponent::createContext()
  208624. {
  208625. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this,
  208626. contextToShareListsWith != 0 ? (HGLRC) contextToShareListsWith->getRawContext() : 0,
  208627. preferredPixelFormat));
  208628. return (c->renderContext != 0) ? c.release() : 0;
  208629. }
  208630. void* OpenGLComponent::getNativeWindowHandle() const
  208631. {
  208632. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle() : 0;
  208633. }
  208634. void juce_glViewport (const int w, const int h)
  208635. {
  208636. glViewport (0, 0, w, h);
  208637. }
  208638. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  208639. OwnedArray <OpenGLPixelFormat>& results)
  208640. {
  208641. Component tempComp;
  208642. {
  208643. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  208644. wc.makeActive();
  208645. wc.findAlternativeOpenGLPixelFormats (results);
  208646. }
  208647. }
  208648. #endif
  208649. /*** End of inlined file: juce_win32_OpenGLComponent.cpp ***/
  208650. /*** Start of inlined file: juce_win32_AudioCDReader.cpp ***/
  208651. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208652. // compiled on its own).
  208653. #if JUCE_INCLUDED_FILE
  208654. #if JUCE_USE_CDREADER
  208655. namespace CDReaderHelpers
  208656. {
  208657. //***************************************************************************
  208658. // %%% TARGET STATUS VALUES %%%
  208659. //***************************************************************************
  208660. #define STATUS_GOOD 0x00 // Status Good
  208661. #define STATUS_CHKCOND 0x02 // Check Condition
  208662. #define STATUS_CONDMET 0x04 // Condition Met
  208663. #define STATUS_BUSY 0x08 // Busy
  208664. #define STATUS_INTERM 0x10 // Intermediate
  208665. #define STATUS_INTCDMET 0x14 // Intermediate-condition met
  208666. #define STATUS_RESCONF 0x18 // Reservation conflict
  208667. #define STATUS_COMTERM 0x22 // Command Terminated
  208668. #define STATUS_QFULL 0x28 // Queue full
  208669. //***************************************************************************
  208670. // %%% SCSI MISCELLANEOUS EQUATES %%%
  208671. //***************************************************************************
  208672. #define MAXLUN 7 // Maximum Logical Unit Id
  208673. #define MAXTARG 7 // Maximum Target Id
  208674. #define MAX_SCSI_LUNS 64 // Maximum Number of SCSI LUNs
  208675. #define MAX_NUM_HA 8 // Maximum Number of SCSI HA's
  208676. //***************************************************************************
  208677. // %%% Commands for all Device Types %%%
  208678. //***************************************************************************
  208679. #define SCSI_CHANGE_DEF 0x40 // Change Definition (Optional)
  208680. #define SCSI_COMPARE 0x39 // Compare (O)
  208681. #define SCSI_COPY 0x18 // Copy (O)
  208682. #define SCSI_COP_VERIFY 0x3A // Copy and Verify (O)
  208683. #define SCSI_INQUIRY 0x12 // Inquiry (MANDATORY)
  208684. #define SCSI_LOG_SELECT 0x4C // Log Select (O)
  208685. #define SCSI_LOG_SENSE 0x4D // Log Sense (O)
  208686. #define SCSI_MODE_SEL6 0x15 // Mode Select 6-byte (Device Specific)
  208687. #define SCSI_MODE_SEL10 0x55 // Mode Select 10-byte (Device Specific)
  208688. #define SCSI_MODE_SEN6 0x1A // Mode Sense 6-byte (Device Specific)
  208689. #define SCSI_MODE_SEN10 0x5A // Mode Sense 10-byte (Device Specific)
  208690. #define SCSI_READ_BUFF 0x3C // Read Buffer (O)
  208691. #define SCSI_REQ_SENSE 0x03 // Request Sense (MANDATORY)
  208692. #define SCSI_SEND_DIAG 0x1D // Send Diagnostic (O)
  208693. #define SCSI_TST_U_RDY 0x00 // Test Unit Ready (MANDATORY)
  208694. #define SCSI_WRITE_BUFF 0x3B // Write Buffer (O)
  208695. //***************************************************************************
  208696. // %%% Commands Unique to Direct Access Devices %%%
  208697. //***************************************************************************
  208698. #define SCSI_COMPARE 0x39 // Compare (O)
  208699. #define SCSI_FORMAT 0x04 // Format Unit (MANDATORY)
  208700. #define SCSI_LCK_UN_CAC 0x36 // Lock Unlock Cache (O)
  208701. #define SCSI_PREFETCH 0x34 // Prefetch (O)
  208702. #define SCSI_MED_REMOVL 0x1E // Prevent/Allow medium Removal (O)
  208703. #define SCSI_READ6 0x08 // Read 6-byte (MANDATORY)
  208704. #define SCSI_READ10 0x28 // Read 10-byte (MANDATORY)
  208705. #define SCSI_RD_CAPAC 0x25 // Read Capacity (MANDATORY)
  208706. #define SCSI_RD_DEFECT 0x37 // Read Defect Data (O)
  208707. #define SCSI_READ_LONG 0x3E // Read Long (O)
  208708. #define SCSI_REASS_BLK 0x07 // Reassign Blocks (O)
  208709. #define SCSI_RCV_DIAG 0x1C // Receive Diagnostic Results (O)
  208710. #define SCSI_RELEASE 0x17 // Release Unit (MANDATORY)
  208711. #define SCSI_REZERO 0x01 // Rezero Unit (O)
  208712. #define SCSI_SRCH_DAT_E 0x31 // Search Data Equal (O)
  208713. #define SCSI_SRCH_DAT_H 0x30 // Search Data High (O)
  208714. #define SCSI_SRCH_DAT_L 0x32 // Search Data Low (O)
  208715. #define SCSI_SEEK6 0x0B // Seek 6-Byte (O)
  208716. #define SCSI_SEEK10 0x2B // Seek 10-Byte (O)
  208717. #define SCSI_SEND_DIAG 0x1D // Send Diagnostics (MANDATORY)
  208718. #define SCSI_SET_LIMIT 0x33 // Set Limits (O)
  208719. #define SCSI_START_STP 0x1B // Start/Stop Unit (O)
  208720. #define SCSI_SYNC_CACHE 0x35 // Synchronize Cache (O)
  208721. #define SCSI_VERIFY 0x2F // Verify (O)
  208722. #define SCSI_WRITE6 0x0A // Write 6-Byte (MANDATORY)
  208723. #define SCSI_WRITE10 0x2A // Write 10-Byte (MANDATORY)
  208724. #define SCSI_WRT_VERIFY 0x2E // Write and Verify (O)
  208725. #define SCSI_WRITE_LONG 0x3F // Write Long (O)
  208726. #define SCSI_WRITE_SAME 0x41 // Write Same (O)
  208727. //***************************************************************************
  208728. // %%% Commands Unique to Sequential Access Devices %%%
  208729. //***************************************************************************
  208730. #define SCSI_ERASE 0x19 // Erase (MANDATORY)
  208731. #define SCSI_LOAD_UN 0x1b // Load/Unload (O)
  208732. #define SCSI_LOCATE 0x2B // Locate (O)
  208733. #define SCSI_RD_BLK_LIM 0x05 // Read Block Limits (MANDATORY)
  208734. #define SCSI_READ_POS 0x34 // Read Position (O)
  208735. #define SCSI_READ_REV 0x0F // Read Reverse (O)
  208736. #define SCSI_REC_BF_DAT 0x14 // Recover Buffer Data (O)
  208737. #define SCSI_RESERVE 0x16 // Reserve Unit (MANDATORY)
  208738. #define SCSI_REWIND 0x01 // Rewind (MANDATORY)
  208739. #define SCSI_SPACE 0x11 // Space (MANDATORY)
  208740. #define SCSI_VERIFY_T 0x13 // Verify (Tape) (O)
  208741. #define SCSI_WRT_FILE 0x10 // Write Filemarks (MANDATORY)
  208742. //***************************************************************************
  208743. // %%% Commands Unique to Printer Devices %%%
  208744. //***************************************************************************
  208745. #define SCSI_PRINT 0x0A // Print (MANDATORY)
  208746. #define SCSI_SLEW_PNT 0x0B // Slew and Print (O)
  208747. #define SCSI_STOP_PNT 0x1B // Stop Print (O)
  208748. #define SCSI_SYNC_BUFF 0x10 // Synchronize Buffer (O)
  208749. //***************************************************************************
  208750. // %%% Commands Unique to Processor Devices %%%
  208751. //***************************************************************************
  208752. #define SCSI_RECEIVE 0x08 // Receive (O)
  208753. #define SCSI_SEND 0x0A // Send (O)
  208754. //***************************************************************************
  208755. // %%% Commands Unique to Write-Once Devices %%%
  208756. //***************************************************************************
  208757. #define SCSI_MEDIUM_SCN 0x38 // Medium Scan (O)
  208758. #define SCSI_SRCHDATE10 0x31 // Search Data Equal 10-Byte (O)
  208759. #define SCSI_SRCHDATE12 0xB1 // Search Data Equal 12-Byte (O)
  208760. #define SCSI_SRCHDATH10 0x30 // Search Data High 10-Byte (O)
  208761. #define SCSI_SRCHDATH12 0xB0 // Search Data High 12-Byte (O)
  208762. #define SCSI_SRCHDATL10 0x32 // Search Data Low 10-Byte (O)
  208763. #define SCSI_SRCHDATL12 0xB2 // Search Data Low 12-Byte (O)
  208764. #define SCSI_SET_LIM_10 0x33 // Set Limits 10-Byte (O)
  208765. #define SCSI_SET_LIM_12 0xB3 // Set Limits 10-Byte (O)
  208766. #define SCSI_VERIFY10 0x2F // Verify 10-Byte (O)
  208767. #define SCSI_VERIFY12 0xAF // Verify 12-Byte (O)
  208768. #define SCSI_WRITE12 0xAA // Write 12-Byte (O)
  208769. #define SCSI_WRT_VER10 0x2E // Write and Verify 10-Byte (O)
  208770. #define SCSI_WRT_VER12 0xAE // Write and Verify 12-Byte (O)
  208771. //***************************************************************************
  208772. // %%% Commands Unique to CD-ROM Devices %%%
  208773. //***************************************************************************
  208774. #define SCSI_PLAYAUD_10 0x45 // Play Audio 10-Byte (O)
  208775. #define SCSI_PLAYAUD_12 0xA5 // Play Audio 12-Byte 12-Byte (O)
  208776. #define SCSI_PLAYAUDMSF 0x47 // Play Audio MSF (O)
  208777. #define SCSI_PLAYA_TKIN 0x48 // Play Audio Track/Index (O)
  208778. #define SCSI_PLYTKREL10 0x49 // Play Track Relative 10-Byte (O)
  208779. #define SCSI_PLYTKREL12 0xA9 // Play Track Relative 12-Byte (O)
  208780. #define SCSI_READCDCAP 0x25 // Read CD-ROM Capacity (MANDATORY)
  208781. #define SCSI_READHEADER 0x44 // Read Header (O)
  208782. #define SCSI_SUBCHANNEL 0x42 // Read Subchannel (O)
  208783. #define SCSI_READ_TOC 0x43 // Read TOC (O)
  208784. //***************************************************************************
  208785. // %%% Commands Unique to Scanner Devices %%%
  208786. //***************************************************************************
  208787. #define SCSI_GETDBSTAT 0x34 // Get Data Buffer Status (O)
  208788. #define SCSI_GETWINDOW 0x25 // Get Window (O)
  208789. #define SCSI_OBJECTPOS 0x31 // Object Postion (O)
  208790. #define SCSI_SCAN 0x1B // Scan (O)
  208791. #define SCSI_SETWINDOW 0x24 // Set Window (MANDATORY)
  208792. //***************************************************************************
  208793. // %%% Commands Unique to Optical Memory Devices %%%
  208794. //***************************************************************************
  208795. #define SCSI_UpdateBlk 0x3D // Update Block (O)
  208796. //***************************************************************************
  208797. // %%% Commands Unique to Medium Changer Devices %%%
  208798. //***************************************************************************
  208799. #define SCSI_EXCHMEDIUM 0xA6 // Exchange Medium (O)
  208800. #define SCSI_INITELSTAT 0x07 // Initialize Element Status (O)
  208801. #define SCSI_POSTOELEM 0x2B // Position to Element (O)
  208802. #define SCSI_REQ_VE_ADD 0xB5 // Request Volume Element Address (O)
  208803. #define SCSI_SENDVOLTAG 0xB6 // Send Volume Tag (O)
  208804. //***************************************************************************
  208805. // %%% Commands Unique to Communication Devices %%%
  208806. //***************************************************************************
  208807. #define SCSI_GET_MSG_6 0x08 // Get Message 6-Byte (MANDATORY)
  208808. #define SCSI_GET_MSG_10 0x28 // Get Message 10-Byte (O)
  208809. #define SCSI_GET_MSG_12 0xA8 // Get Message 12-Byte (O)
  208810. #define SCSI_SND_MSG_6 0x0A // Send Message 6-Byte (MANDATORY)
  208811. #define SCSI_SND_MSG_10 0x2A // Send Message 10-Byte (O)
  208812. #define SCSI_SND_MSG_12 0xAA // Send Message 12-Byte (O)
  208813. //***************************************************************************
  208814. // %%% Request Sense Data Format %%%
  208815. //***************************************************************************
  208816. typedef struct {
  208817. BYTE ErrorCode; // Error Code (70H or 71H)
  208818. BYTE SegmentNum; // Number of current segment descriptor
  208819. BYTE SenseKey; // Sense Key(See bit definitions too)
  208820. BYTE InfoByte0; // Information MSB
  208821. BYTE InfoByte1; // Information MID
  208822. BYTE InfoByte2; // Information MID
  208823. BYTE InfoByte3; // Information LSB
  208824. BYTE AddSenLen; // Additional Sense Length
  208825. BYTE ComSpecInf0; // Command Specific Information MSB
  208826. BYTE ComSpecInf1; // Command Specific Information MID
  208827. BYTE ComSpecInf2; // Command Specific Information MID
  208828. BYTE ComSpecInf3; // Command Specific Information LSB
  208829. BYTE AddSenseCode; // Additional Sense Code
  208830. BYTE AddSenQual; // Additional Sense Code Qualifier
  208831. BYTE FieldRepUCode; // Field Replaceable Unit Code
  208832. BYTE SenKeySpec15; // Sense Key Specific 15th byte
  208833. BYTE SenKeySpec16; // Sense Key Specific 16th byte
  208834. BYTE SenKeySpec17; // Sense Key Specific 17th byte
  208835. BYTE AddSenseBytes; // Additional Sense Bytes
  208836. } SENSE_DATA_FMT;
  208837. //***************************************************************************
  208838. // %%% REQUEST SENSE ERROR CODE %%%
  208839. //***************************************************************************
  208840. #define SERROR_CURRENT 0x70 // Current Errors
  208841. #define SERROR_DEFERED 0x71 // Deferred Errors
  208842. //***************************************************************************
  208843. // %%% REQUEST SENSE BIT DEFINITIONS %%%
  208844. //***************************************************************************
  208845. #define SENSE_VALID 0x80 // Byte 0 Bit 7
  208846. #define SENSE_FILEMRK 0x80 // Byte 2 Bit 7
  208847. #define SENSE_EOM 0x40 // Byte 2 Bit 6
  208848. #define SENSE_ILI 0x20 // Byte 2 Bit 5
  208849. //***************************************************************************
  208850. // %%% REQUEST SENSE SENSE KEY DEFINITIONS %%%
  208851. //***************************************************************************
  208852. #define KEY_NOSENSE 0x00 // No Sense
  208853. #define KEY_RECERROR 0x01 // Recovered Error
  208854. #define KEY_NOTREADY 0x02 // Not Ready
  208855. #define KEY_MEDIUMERR 0x03 // Medium Error
  208856. #define KEY_HARDERROR 0x04 // Hardware Error
  208857. #define KEY_ILLGLREQ 0x05 // Illegal Request
  208858. #define KEY_UNITATT 0x06 // Unit Attention
  208859. #define KEY_DATAPROT 0x07 // Data Protect
  208860. #define KEY_BLANKCHK 0x08 // Blank Check
  208861. #define KEY_VENDSPEC 0x09 // Vendor Specific
  208862. #define KEY_COPYABORT 0x0A // Copy Abort
  208863. #define KEY_EQUAL 0x0C // Equal (Search)
  208864. #define KEY_VOLOVRFLW 0x0D // Volume Overflow
  208865. #define KEY_MISCOMP 0x0E // Miscompare (Search)
  208866. #define KEY_RESERVED 0x0F // Reserved
  208867. //***************************************************************************
  208868. // %%% PERIPHERAL DEVICE TYPE DEFINITIONS %%%
  208869. //***************************************************************************
  208870. #define DTYPE_DASD 0x00 // Disk Device
  208871. #define DTYPE_SEQD 0x01 // Tape Device
  208872. #define DTYPE_PRNT 0x02 // Printer
  208873. #define DTYPE_PROC 0x03 // Processor
  208874. #define DTYPE_WORM 0x04 // Write-once read-multiple
  208875. #define DTYPE_CROM 0x05 // CD-ROM device
  208876. #define DTYPE_SCAN 0x06 // Scanner device
  208877. #define DTYPE_OPTI 0x07 // Optical memory device
  208878. #define DTYPE_JUKE 0x08 // Medium Changer device
  208879. #define DTYPE_COMM 0x09 // Communications device
  208880. #define DTYPE_RESL 0x0A // Reserved (low)
  208881. #define DTYPE_RESH 0x1E // Reserved (high)
  208882. #define DTYPE_UNKNOWN 0x1F // Unknown or no device type
  208883. //***************************************************************************
  208884. // %%% ANSI APPROVED VERSION DEFINITIONS %%%
  208885. //***************************************************************************
  208886. #define ANSI_MAYBE 0x0 // Device may or may not be ANSI approved stand
  208887. #define ANSI_SCSI1 0x1 // Device complies to ANSI X3.131-1986 (SCSI-1)
  208888. #define ANSI_SCSI2 0x2 // Device complies to SCSI-2
  208889. #define ANSI_RESLO 0x3 // Reserved (low)
  208890. #define ANSI_RESHI 0x7 // Reserved (high)
  208891. typedef struct
  208892. {
  208893. USHORT Length;
  208894. UCHAR ScsiStatus;
  208895. UCHAR PathId;
  208896. UCHAR TargetId;
  208897. UCHAR Lun;
  208898. UCHAR CdbLength;
  208899. UCHAR SenseInfoLength;
  208900. UCHAR DataIn;
  208901. ULONG DataTransferLength;
  208902. ULONG TimeOutValue;
  208903. ULONG DataBufferOffset;
  208904. ULONG SenseInfoOffset;
  208905. UCHAR Cdb[16];
  208906. } SCSI_PASS_THROUGH, *PSCSI_PASS_THROUGH;
  208907. typedef struct
  208908. {
  208909. USHORT Length;
  208910. UCHAR ScsiStatus;
  208911. UCHAR PathId;
  208912. UCHAR TargetId;
  208913. UCHAR Lun;
  208914. UCHAR CdbLength;
  208915. UCHAR SenseInfoLength;
  208916. UCHAR DataIn;
  208917. ULONG DataTransferLength;
  208918. ULONG TimeOutValue;
  208919. PVOID DataBuffer;
  208920. ULONG SenseInfoOffset;
  208921. UCHAR Cdb[16];
  208922. } SCSI_PASS_THROUGH_DIRECT, *PSCSI_PASS_THROUGH_DIRECT;
  208923. typedef struct
  208924. {
  208925. SCSI_PASS_THROUGH_DIRECT spt;
  208926. ULONG Filler;
  208927. UCHAR ucSenseBuf[32];
  208928. } SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, *PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER;
  208929. typedef struct
  208930. {
  208931. ULONG Length;
  208932. UCHAR PortNumber;
  208933. UCHAR PathId;
  208934. UCHAR TargetId;
  208935. UCHAR Lun;
  208936. } SCSI_ADDRESS, *PSCSI_ADDRESS;
  208937. #define METHOD_BUFFERED 0
  208938. #define METHOD_IN_DIRECT 1
  208939. #define METHOD_OUT_DIRECT 2
  208940. #define METHOD_NEITHER 3
  208941. #define FILE_ANY_ACCESS 0
  208942. #ifndef FILE_READ_ACCESS
  208943. #define FILE_READ_ACCESS (0x0001)
  208944. #endif
  208945. #ifndef FILE_WRITE_ACCESS
  208946. #define FILE_WRITE_ACCESS (0x0002)
  208947. #endif
  208948. #define IOCTL_SCSI_BASE 0x00000004
  208949. #define SCSI_IOCTL_DATA_OUT 0
  208950. #define SCSI_IOCTL_DATA_IN 1
  208951. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  208952. #define CTL_CODE2( DevType, Function, Method, Access ) ( \
  208953. ((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \
  208954. )
  208955. #define IOCTL_SCSI_PASS_THROUGH CTL_CODE2( IOCTL_SCSI_BASE, 0x0401, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  208956. #define IOCTL_SCSI_GET_CAPABILITIES CTL_CODE2( IOCTL_SCSI_BASE, 0x0404, METHOD_BUFFERED, FILE_ANY_ACCESS)
  208957. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  208958. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  208959. #define SENSE_LEN 14
  208960. #define SRB_DIR_SCSI 0x00
  208961. #define SRB_POSTING 0x01
  208962. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  208963. #define SRB_DIR_IN 0x08
  208964. #define SRB_DIR_OUT 0x10
  208965. #define SRB_EVENT_NOTIFY 0x40
  208966. #define RESIDUAL_COUNT_SUPPORTED 0x02
  208967. #define MAX_SRB_TIMEOUT 1080001u
  208968. #define DEFAULT_SRB_TIMEOUT 1080001u
  208969. #define SC_HA_INQUIRY 0x00
  208970. #define SC_GET_DEV_TYPE 0x01
  208971. #define SC_EXEC_SCSI_CMD 0x02
  208972. #define SC_ABORT_SRB 0x03
  208973. #define SC_RESET_DEV 0x04
  208974. #define SC_SET_HA_PARMS 0x05
  208975. #define SC_GET_DISK_INFO 0x06
  208976. #define SC_RESCAN_SCSI_BUS 0x07
  208977. #define SC_GETSET_TIMEOUTS 0x08
  208978. #define SS_PENDING 0x00
  208979. #define SS_COMP 0x01
  208980. #define SS_ABORTED 0x02
  208981. #define SS_ABORT_FAIL 0x03
  208982. #define SS_ERR 0x04
  208983. #define SS_INVALID_CMD 0x80
  208984. #define SS_INVALID_HA 0x81
  208985. #define SS_NO_DEVICE 0x82
  208986. #define SS_INVALID_SRB 0xE0
  208987. #define SS_OLD_MANAGER 0xE1
  208988. #define SS_BUFFER_ALIGN 0xE1
  208989. #define SS_ILLEGAL_MODE 0xE2
  208990. #define SS_NO_ASPI 0xE3
  208991. #define SS_FAILED_INIT 0xE4
  208992. #define SS_ASPI_IS_BUSY 0xE5
  208993. #define SS_BUFFER_TO_BIG 0xE6
  208994. #define SS_BUFFER_TOO_BIG 0xE6
  208995. #define SS_MISMATCHED_COMPONENTS 0xE7
  208996. #define SS_NO_ADAPTERS 0xE8
  208997. #define SS_INSUFFICIENT_RESOURCES 0xE9
  208998. #define SS_ASPI_IS_SHUTDOWN 0xEA
  208999. #define SS_BAD_INSTALL 0xEB
  209000. #define HASTAT_OK 0x00
  209001. #define HASTAT_SEL_TO 0x11
  209002. #define HASTAT_DO_DU 0x12
  209003. #define HASTAT_BUS_FREE 0x13
  209004. #define HASTAT_PHASE_ERR 0x14
  209005. #define HASTAT_TIMEOUT 0x09
  209006. #define HASTAT_COMMAND_TIMEOUT 0x0B
  209007. #define HASTAT_MESSAGE_REJECT 0x0D
  209008. #define HASTAT_BUS_RESET 0x0E
  209009. #define HASTAT_PARITY_ERROR 0x0F
  209010. #define HASTAT_REQUEST_SENSE_FAILED 0x10
  209011. #define PACKED
  209012. #pragma pack(1)
  209013. typedef struct
  209014. {
  209015. BYTE SRB_Cmd;
  209016. BYTE SRB_Status;
  209017. BYTE SRB_HaID;
  209018. BYTE SRB_Flags;
  209019. DWORD SRB_Hdr_Rsvd;
  209020. BYTE HA_Count;
  209021. BYTE HA_SCSI_ID;
  209022. BYTE HA_ManagerId[16];
  209023. BYTE HA_Identifier[16];
  209024. BYTE HA_Unique[16];
  209025. WORD HA_Rsvd1;
  209026. BYTE pad[20];
  209027. } PACKED SRB_HAInquiry, *PSRB_HAInquiry, FAR *LPSRB_HAInquiry;
  209028. typedef struct
  209029. {
  209030. BYTE SRB_Cmd;
  209031. BYTE SRB_Status;
  209032. BYTE SRB_HaID;
  209033. BYTE SRB_Flags;
  209034. DWORD SRB_Hdr_Rsvd;
  209035. BYTE SRB_Target;
  209036. BYTE SRB_Lun;
  209037. BYTE SRB_DeviceType;
  209038. BYTE SRB_Rsvd1;
  209039. BYTE pad[68];
  209040. } PACKED SRB_GDEVBlock, *PSRB_GDEVBlock, FAR *LPSRB_GDEVBlock;
  209041. typedef struct
  209042. {
  209043. BYTE SRB_Cmd;
  209044. BYTE SRB_Status;
  209045. BYTE SRB_HaID;
  209046. BYTE SRB_Flags;
  209047. DWORD SRB_Hdr_Rsvd;
  209048. BYTE SRB_Target;
  209049. BYTE SRB_Lun;
  209050. WORD SRB_Rsvd1;
  209051. DWORD SRB_BufLen;
  209052. BYTE FAR *SRB_BufPointer;
  209053. BYTE SRB_SenseLen;
  209054. BYTE SRB_CDBLen;
  209055. BYTE SRB_HaStat;
  209056. BYTE SRB_TargStat;
  209057. VOID FAR *SRB_PostProc;
  209058. BYTE SRB_Rsvd2[20];
  209059. BYTE CDBByte[16];
  209060. BYTE SenseArea[SENSE_LEN+2];
  209061. } PACKED SRB_ExecSCSICmd, *PSRB_ExecSCSICmd, FAR *LPSRB_ExecSCSICmd;
  209062. typedef struct
  209063. {
  209064. BYTE SRB_Cmd;
  209065. BYTE SRB_Status;
  209066. BYTE SRB_HaId;
  209067. BYTE SRB_Flags;
  209068. DWORD SRB_Hdr_Rsvd;
  209069. } PACKED SRB, *PSRB, FAR *LPSRB;
  209070. #pragma pack()
  209071. struct CDDeviceInfo
  209072. {
  209073. char vendor[9];
  209074. char productId[17];
  209075. char rev[5];
  209076. char vendorSpec[21];
  209077. BYTE ha;
  209078. BYTE tgt;
  209079. BYTE lun;
  209080. char scsiDriveLetter; // will be 0 if not using scsi
  209081. };
  209082. class CDReadBuffer
  209083. {
  209084. public:
  209085. int startFrame;
  209086. int numFrames;
  209087. int dataStartOffset;
  209088. int dataLength;
  209089. int bufferSize;
  209090. HeapBlock<BYTE> buffer;
  209091. int index;
  209092. bool wantsIndex;
  209093. CDReadBuffer (const int numberOfFrames)
  209094. : startFrame (0),
  209095. numFrames (0),
  209096. dataStartOffset (0),
  209097. dataLength (0),
  209098. bufferSize (2352 * numberOfFrames),
  209099. buffer (bufferSize),
  209100. index (0),
  209101. wantsIndex (false)
  209102. {
  209103. }
  209104. bool isZero() const throw()
  209105. {
  209106. BYTE* p = buffer + dataStartOffset;
  209107. for (int i = dataLength; --i >= 0;)
  209108. if (*p++ != 0)
  209109. return false;
  209110. return true;
  209111. }
  209112. };
  209113. class CDDeviceHandle;
  209114. class CDController
  209115. {
  209116. public:
  209117. CDController();
  209118. virtual ~CDController();
  209119. virtual bool read (CDReadBuffer* t) = 0;
  209120. virtual void shutDown();
  209121. bool readAudio (CDReadBuffer* t, CDReadBuffer* overlapBuffer = 0);
  209122. int getLastIndex();
  209123. public:
  209124. bool initialised;
  209125. CDDeviceHandle* deviceInfo;
  209126. int framesToCheck, framesOverlap;
  209127. void prepare (SRB_ExecSCSICmd& s);
  209128. void perform (SRB_ExecSCSICmd& s);
  209129. void setPaused (bool paused);
  209130. };
  209131. #pragma pack(1)
  209132. struct TOCTRACK
  209133. {
  209134. BYTE rsvd;
  209135. BYTE ADR;
  209136. BYTE trackNumber;
  209137. BYTE rsvd2;
  209138. BYTE addr[4];
  209139. };
  209140. struct TOC
  209141. {
  209142. WORD tocLen;
  209143. BYTE firstTrack;
  209144. BYTE lastTrack;
  209145. TOCTRACK tracks[100];
  209146. };
  209147. #pragma pack()
  209148. enum
  209149. {
  209150. READTYPE_ANY = 0,
  209151. READTYPE_ATAPI1 = 1,
  209152. READTYPE_ATAPI2 = 2,
  209153. READTYPE_READ6 = 3,
  209154. READTYPE_READ10 = 4,
  209155. READTYPE_READ_D8 = 5,
  209156. READTYPE_READ_D4 = 6,
  209157. READTYPE_READ_D4_1 = 7,
  209158. READTYPE_READ10_2 = 8
  209159. };
  209160. class CDDeviceHandle
  209161. {
  209162. public:
  209163. CDDeviceHandle (const CDDeviceInfo* const device)
  209164. : scsiHandle (0),
  209165. readType (READTYPE_ANY),
  209166. controller (0)
  209167. {
  209168. memcpy (&info, device, sizeof (info));
  209169. }
  209170. ~CDDeviceHandle()
  209171. {
  209172. if (controller != 0)
  209173. {
  209174. controller->shutDown();
  209175. controller = 0;
  209176. }
  209177. if (scsiHandle != 0)
  209178. CloseHandle (scsiHandle);
  209179. }
  209180. bool readTOC (TOC* lpToc, bool useMSF);
  209181. bool readAudio (CDReadBuffer* buffer, CDReadBuffer* overlapBuffer = 0);
  209182. void openDrawer (bool shouldBeOpen);
  209183. CDDeviceInfo info;
  209184. HANDLE scsiHandle;
  209185. BYTE readType;
  209186. private:
  209187. ScopedPointer<CDController> controller;
  209188. bool testController (const int readType,
  209189. CDController* const newController,
  209190. CDReadBuffer* const bufferToUse);
  209191. };
  209192. DWORD (*fGetASPI32SupportInfo)(void);
  209193. DWORD (*fSendASPI32Command)(LPSRB);
  209194. static HINSTANCE winAspiLib = 0;
  209195. static bool usingScsi = false;
  209196. static bool initialised = false;
  209197. static bool InitialiseCDRipper()
  209198. {
  209199. if (! initialised)
  209200. {
  209201. initialised = true;
  209202. OSVERSIONINFO info;
  209203. info.dwOSVersionInfoSize = sizeof (info);
  209204. GetVersionEx (&info);
  209205. usingScsi = (info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4);
  209206. if (! usingScsi)
  209207. {
  209208. fGetASPI32SupportInfo = 0;
  209209. fSendASPI32Command = 0;
  209210. winAspiLib = LoadLibrary (_T("WNASPI32.DLL"));
  209211. if (winAspiLib != 0)
  209212. {
  209213. fGetASPI32SupportInfo = (DWORD(*)(void)) GetProcAddress (winAspiLib, "GetASPI32SupportInfo");
  209214. fSendASPI32Command = (DWORD(*)(LPSRB)) GetProcAddress (winAspiLib, "SendASPI32Command");
  209215. if (fGetASPI32SupportInfo == 0 || fSendASPI32Command == 0)
  209216. return false;
  209217. }
  209218. else
  209219. {
  209220. usingScsi = true;
  209221. }
  209222. }
  209223. }
  209224. return true;
  209225. }
  209226. static void DeinitialiseCDRipper()
  209227. {
  209228. if (winAspiLib != 0)
  209229. {
  209230. fGetASPI32SupportInfo = 0;
  209231. fSendASPI32Command = 0;
  209232. FreeLibrary (winAspiLib);
  209233. winAspiLib = 0;
  209234. }
  209235. initialised = false;
  209236. }
  209237. static HANDLE CreateSCSIDeviceHandle (char driveLetter)
  209238. {
  209239. TCHAR devicePath[] = { '\\', '\\', '.', '\\', driveLetter, ':', 0, 0 };
  209240. OSVERSIONINFO info;
  209241. info.dwOSVersionInfoSize = sizeof (info);
  209242. GetVersionEx (&info);
  209243. DWORD flags = GENERIC_READ;
  209244. if ((info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4))
  209245. flags = GENERIC_READ | GENERIC_WRITE;
  209246. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  209247. if (h == INVALID_HANDLE_VALUE)
  209248. {
  209249. flags ^= GENERIC_WRITE;
  209250. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  209251. }
  209252. return h;
  209253. }
  209254. static DWORD performScsiPassThroughCommand (const LPSRB_ExecSCSICmd srb,
  209255. const char driveLetter,
  209256. HANDLE& deviceHandle,
  209257. const bool retryOnFailure = true)
  209258. {
  209259. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  209260. zerostruct (s);
  209261. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  209262. s.spt.CdbLength = srb->SRB_CDBLen;
  209263. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  209264. ? SCSI_IOCTL_DATA_IN
  209265. : ((srb->SRB_Flags & SRB_DIR_OUT)
  209266. ? SCSI_IOCTL_DATA_OUT
  209267. : SCSI_IOCTL_DATA_UNSPECIFIED));
  209268. s.spt.DataTransferLength = srb->SRB_BufLen;
  209269. s.spt.TimeOutValue = 5;
  209270. s.spt.DataBuffer = srb->SRB_BufPointer;
  209271. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  209272. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  209273. srb->SRB_Status = SS_ERR;
  209274. srb->SRB_TargStat = 0x0004;
  209275. DWORD bytesReturned = 0;
  209276. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  209277. &s, sizeof (s),
  209278. &s, sizeof (s),
  209279. &bytesReturned, 0) != 0)
  209280. {
  209281. srb->SRB_Status = SS_COMP;
  209282. }
  209283. else if (retryOnFailure)
  209284. {
  209285. const DWORD error = GetLastError();
  209286. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  209287. {
  209288. if (error != ERROR_INVALID_HANDLE)
  209289. CloseHandle (deviceHandle);
  209290. deviceHandle = CreateSCSIDeviceHandle (driveLetter);
  209291. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  209292. }
  209293. }
  209294. return srb->SRB_Status;
  209295. }
  209296. // Controller types..
  209297. class ControllerType1 : public CDController
  209298. {
  209299. public:
  209300. ControllerType1() {}
  209301. ~ControllerType1() {}
  209302. bool read (CDReadBuffer* rb)
  209303. {
  209304. if (rb->numFrames * 2352 > rb->bufferSize)
  209305. return false;
  209306. SRB_ExecSCSICmd s;
  209307. prepare (s);
  209308. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209309. s.SRB_BufLen = rb->bufferSize;
  209310. s.SRB_BufPointer = rb->buffer;
  209311. s.SRB_CDBLen = 12;
  209312. s.CDBByte[0] = 0xBE;
  209313. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  209314. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  209315. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  209316. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  209317. s.CDBByte[9] = (BYTE)((deviceInfo->readType == READTYPE_ATAPI1) ? 0x10 : 0xF0);
  209318. perform (s);
  209319. if (s.SRB_Status != SS_COMP)
  209320. return false;
  209321. rb->dataLength = rb->numFrames * 2352;
  209322. rb->dataStartOffset = 0;
  209323. return true;
  209324. }
  209325. };
  209326. class ControllerType2 : public CDController
  209327. {
  209328. public:
  209329. ControllerType2() {}
  209330. ~ControllerType2() {}
  209331. void shutDown()
  209332. {
  209333. if (initialised)
  209334. {
  209335. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  209336. SRB_ExecSCSICmd s;
  209337. prepare (s);
  209338. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  209339. s.SRB_BufLen = 0x0C;
  209340. s.SRB_BufPointer = bufPointer;
  209341. s.SRB_CDBLen = 6;
  209342. s.CDBByte[0] = 0x15;
  209343. s.CDBByte[4] = 0x0C;
  209344. perform (s);
  209345. }
  209346. }
  209347. bool init()
  209348. {
  209349. SRB_ExecSCSICmd s;
  209350. s.SRB_Status = SS_ERR;
  209351. if (deviceInfo->readType == READTYPE_READ10_2)
  209352. {
  209353. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  209354. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  209355. for (int i = 0; i < 2; ++i)
  209356. {
  209357. prepare (s);
  209358. s.SRB_Flags = SRB_EVENT_NOTIFY;
  209359. s.SRB_BufLen = 0x14;
  209360. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  209361. s.SRB_CDBLen = 6;
  209362. s.CDBByte[0] = 0x15;
  209363. s.CDBByte[1] = 0x10;
  209364. s.CDBByte[4] = 0x14;
  209365. perform (s);
  209366. if (s.SRB_Status != SS_COMP)
  209367. return false;
  209368. }
  209369. }
  209370. else
  209371. {
  209372. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  209373. prepare (s);
  209374. s.SRB_Flags = SRB_EVENT_NOTIFY;
  209375. s.SRB_BufLen = 0x0C;
  209376. s.SRB_BufPointer = bufPointer;
  209377. s.SRB_CDBLen = 6;
  209378. s.CDBByte[0] = 0x15;
  209379. s.CDBByte[4] = 0x0C;
  209380. perform (s);
  209381. }
  209382. return s.SRB_Status == SS_COMP;
  209383. }
  209384. bool read (CDReadBuffer* rb)
  209385. {
  209386. if (rb->numFrames * 2352 > rb->bufferSize)
  209387. return false;
  209388. if (!initialised)
  209389. {
  209390. initialised = init();
  209391. if (!initialised)
  209392. return false;
  209393. }
  209394. SRB_ExecSCSICmd s;
  209395. prepare (s);
  209396. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209397. s.SRB_BufLen = rb->bufferSize;
  209398. s.SRB_BufPointer = rb->buffer;
  209399. s.SRB_CDBLen = 10;
  209400. s.CDBByte[0] = 0x28;
  209401. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  209402. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  209403. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  209404. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  209405. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  209406. perform (s);
  209407. if (s.SRB_Status != SS_COMP)
  209408. return false;
  209409. rb->dataLength = rb->numFrames * 2352;
  209410. rb->dataStartOffset = 0;
  209411. return true;
  209412. }
  209413. };
  209414. class ControllerType3 : public CDController
  209415. {
  209416. public:
  209417. ControllerType3() {}
  209418. ~ControllerType3() {}
  209419. bool read (CDReadBuffer* rb)
  209420. {
  209421. if (rb->numFrames * 2352 > rb->bufferSize)
  209422. return false;
  209423. if (!initialised)
  209424. {
  209425. setPaused (false);
  209426. initialised = true;
  209427. }
  209428. SRB_ExecSCSICmd s;
  209429. prepare (s);
  209430. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209431. s.SRB_BufLen = rb->numFrames * 2352;
  209432. s.SRB_BufPointer = rb->buffer;
  209433. s.SRB_CDBLen = 12;
  209434. s.CDBByte[0] = 0xD8;
  209435. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  209436. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  209437. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  209438. s.CDBByte[9] = (BYTE)(rb->numFrames & 0xFF);
  209439. perform (s);
  209440. if (s.SRB_Status != SS_COMP)
  209441. return false;
  209442. rb->dataLength = rb->numFrames * 2352;
  209443. rb->dataStartOffset = 0;
  209444. return true;
  209445. }
  209446. };
  209447. class ControllerType4 : public CDController
  209448. {
  209449. public:
  209450. ControllerType4() {}
  209451. ~ControllerType4() {}
  209452. bool selectD4Mode()
  209453. {
  209454. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  209455. SRB_ExecSCSICmd s;
  209456. prepare (s);
  209457. s.SRB_Flags = SRB_EVENT_NOTIFY;
  209458. s.SRB_CDBLen = 6;
  209459. s.SRB_BufLen = 12;
  209460. s.SRB_BufPointer = bufPointer;
  209461. s.CDBByte[0] = 0x15;
  209462. s.CDBByte[1] = 0x10;
  209463. s.CDBByte[4] = 0x08;
  209464. perform (s);
  209465. return s.SRB_Status == SS_COMP;
  209466. }
  209467. bool read (CDReadBuffer* rb)
  209468. {
  209469. if (rb->numFrames * 2352 > rb->bufferSize)
  209470. return false;
  209471. if (!initialised)
  209472. {
  209473. setPaused (true);
  209474. if (deviceInfo->readType == READTYPE_READ_D4_1)
  209475. selectD4Mode();
  209476. initialised = true;
  209477. }
  209478. SRB_ExecSCSICmd s;
  209479. prepare (s);
  209480. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209481. s.SRB_BufLen = rb->bufferSize;
  209482. s.SRB_BufPointer = rb->buffer;
  209483. s.SRB_CDBLen = 10;
  209484. s.CDBByte[0] = 0xD4;
  209485. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  209486. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  209487. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  209488. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  209489. perform (s);
  209490. if (s.SRB_Status != SS_COMP)
  209491. return false;
  209492. rb->dataLength = rb->numFrames * 2352;
  209493. rb->dataStartOffset = 0;
  209494. return true;
  209495. }
  209496. };
  209497. CDController::CDController() : initialised (false)
  209498. {
  209499. }
  209500. CDController::~CDController()
  209501. {
  209502. }
  209503. void CDController::prepare (SRB_ExecSCSICmd& s)
  209504. {
  209505. zerostruct (s);
  209506. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  209507. s.SRB_HaID = deviceInfo->info.ha;
  209508. s.SRB_Target = deviceInfo->info.tgt;
  209509. s.SRB_Lun = deviceInfo->info.lun;
  209510. s.SRB_SenseLen = SENSE_LEN;
  209511. }
  209512. void CDController::perform (SRB_ExecSCSICmd& s)
  209513. {
  209514. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  209515. s.SRB_PostProc = event;
  209516. ResetEvent (event);
  209517. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s,
  209518. deviceInfo->info.scsiDriveLetter,
  209519. deviceInfo->scsiHandle)
  209520. : fSendASPI32Command ((LPSRB)&s);
  209521. if (status == SS_PENDING)
  209522. WaitForSingleObject (event, 4000);
  209523. CloseHandle (event);
  209524. }
  209525. void CDController::setPaused (bool paused)
  209526. {
  209527. SRB_ExecSCSICmd s;
  209528. prepare (s);
  209529. s.SRB_Flags = SRB_EVENT_NOTIFY;
  209530. s.SRB_CDBLen = 10;
  209531. s.CDBByte[0] = 0x4B;
  209532. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  209533. perform (s);
  209534. }
  209535. void CDController::shutDown()
  209536. {
  209537. }
  209538. bool CDController::readAudio (CDReadBuffer* rb, CDReadBuffer* overlapBuffer)
  209539. {
  209540. if (overlapBuffer != 0)
  209541. {
  209542. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  209543. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  209544. if (doJitter
  209545. && overlapBuffer->startFrame > 0
  209546. && overlapBuffer->numFrames > 0
  209547. && overlapBuffer->dataLength > 0)
  209548. {
  209549. const int numFrames = rb->numFrames;
  209550. if (overlapBuffer->startFrame == (rb->startFrame - framesToCheck))
  209551. {
  209552. rb->startFrame -= framesOverlap;
  209553. if (framesToCheck < framesOverlap
  209554. && numFrames + framesOverlap <= rb->bufferSize / 2352)
  209555. rb->numFrames += framesOverlap;
  209556. }
  209557. else
  209558. {
  209559. overlapBuffer->dataLength = 0;
  209560. overlapBuffer->startFrame = 0;
  209561. overlapBuffer->numFrames = 0;
  209562. }
  209563. }
  209564. if (! read (rb))
  209565. return false;
  209566. if (doJitter)
  209567. {
  209568. const int checkLen = framesToCheck * 2352;
  209569. const int maxToCheck = rb->dataLength - checkLen;
  209570. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  209571. return true;
  209572. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  209573. bool found = false;
  209574. for (int i = 0; i < maxToCheck; ++i)
  209575. {
  209576. if (memcmp (p, rb->buffer + i, checkLen) == 0)
  209577. {
  209578. i += checkLen;
  209579. rb->dataStartOffset = i;
  209580. rb->dataLength -= i;
  209581. rb->startFrame = overlapBuffer->startFrame + framesToCheck;
  209582. found = true;
  209583. break;
  209584. }
  209585. }
  209586. rb->numFrames = rb->dataLength / 2352;
  209587. rb->dataLength = 2352 * rb->numFrames;
  209588. if (!found)
  209589. return false;
  209590. }
  209591. if (canDoJitter)
  209592. {
  209593. memcpy (overlapBuffer->buffer,
  209594. rb->buffer + rb->dataStartOffset + 2352 * (rb->numFrames - framesToCheck),
  209595. 2352 * framesToCheck);
  209596. overlapBuffer->startFrame = rb->startFrame + rb->numFrames - framesToCheck;
  209597. overlapBuffer->numFrames = framesToCheck;
  209598. overlapBuffer->dataLength = 2352 * framesToCheck;
  209599. overlapBuffer->dataStartOffset = 0;
  209600. }
  209601. else
  209602. {
  209603. overlapBuffer->startFrame = 0;
  209604. overlapBuffer->numFrames = 0;
  209605. overlapBuffer->dataLength = 0;
  209606. }
  209607. return true;
  209608. }
  209609. else
  209610. {
  209611. return read (rb);
  209612. }
  209613. }
  209614. int CDController::getLastIndex()
  209615. {
  209616. char qdata[100];
  209617. SRB_ExecSCSICmd s;
  209618. prepare (s);
  209619. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209620. s.SRB_BufLen = sizeof (qdata);
  209621. s.SRB_BufPointer = (BYTE*)qdata;
  209622. s.SRB_CDBLen = 12;
  209623. s.CDBByte[0] = 0x42;
  209624. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  209625. s.CDBByte[2] = 64;
  209626. s.CDBByte[3] = 1; // get current position
  209627. s.CDBByte[7] = 0;
  209628. s.CDBByte[8] = (BYTE)sizeof (qdata);
  209629. perform (s);
  209630. if (s.SRB_Status == SS_COMP)
  209631. return qdata[7];
  209632. return 0;
  209633. }
  209634. bool CDDeviceHandle::readTOC (TOC* lpToc, bool useMSF)
  209635. {
  209636. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  209637. SRB_ExecSCSICmd s;
  209638. zerostruct (s);
  209639. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  209640. s.SRB_HaID = info.ha;
  209641. s.SRB_Target = info.tgt;
  209642. s.SRB_Lun = info.lun;
  209643. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209644. s.SRB_BufLen = 0x324;
  209645. s.SRB_BufPointer = (BYTE*)lpToc;
  209646. s.SRB_SenseLen = 0x0E;
  209647. s.SRB_CDBLen = 0x0A;
  209648. s.SRB_PostProc = event;
  209649. s.CDBByte[0] = 0x43;
  209650. s.CDBByte[1] = (BYTE)(useMSF ? 0x02 : 0x00);
  209651. s.CDBByte[7] = 0x03;
  209652. s.CDBByte[8] = 0x24;
  209653. ResetEvent (event);
  209654. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  209655. : fSendASPI32Command ((LPSRB)&s);
  209656. if (status == SS_PENDING)
  209657. WaitForSingleObject (event, 4000);
  209658. CloseHandle (event);
  209659. return (s.SRB_Status == SS_COMP);
  209660. }
  209661. bool CDDeviceHandle::readAudio (CDReadBuffer* const buffer,
  209662. CDReadBuffer* const overlapBuffer)
  209663. {
  209664. if (controller == 0)
  209665. {
  209666. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  209667. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  209668. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  209669. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  209670. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  209671. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  209672. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  209673. }
  209674. buffer->index = 0;
  209675. if ((controller != 0)
  209676. && controller->readAudio (buffer, overlapBuffer))
  209677. {
  209678. if (buffer->wantsIndex)
  209679. buffer->index = controller->getLastIndex();
  209680. return true;
  209681. }
  209682. return false;
  209683. }
  209684. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  209685. {
  209686. if (shouldBeOpen)
  209687. {
  209688. if (controller != 0)
  209689. {
  209690. controller->shutDown();
  209691. controller = 0;
  209692. }
  209693. if (scsiHandle != 0)
  209694. {
  209695. CloseHandle (scsiHandle);
  209696. scsiHandle = 0;
  209697. }
  209698. }
  209699. SRB_ExecSCSICmd s;
  209700. zerostruct (s);
  209701. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  209702. s.SRB_HaID = info.ha;
  209703. s.SRB_Target = info.tgt;
  209704. s.SRB_Lun = info.lun;
  209705. s.SRB_SenseLen = SENSE_LEN;
  209706. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209707. s.SRB_BufLen = 0;
  209708. s.SRB_BufPointer = 0;
  209709. s.SRB_CDBLen = 12;
  209710. s.CDBByte[0] = 0x1b;
  209711. s.CDBByte[1] = (BYTE)(info.lun << 5);
  209712. s.CDBByte[4] = (BYTE)((shouldBeOpen) ? 2 : 3);
  209713. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  209714. s.SRB_PostProc = event;
  209715. ResetEvent (event);
  209716. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  209717. : fSendASPI32Command ((LPSRB)&s);
  209718. if (status == SS_PENDING)
  209719. WaitForSingleObject (event, 4000);
  209720. CloseHandle (event);
  209721. }
  209722. bool CDDeviceHandle::testController (const int type,
  209723. CDController* const newController,
  209724. CDReadBuffer* const rb)
  209725. {
  209726. controller = newController;
  209727. readType = (BYTE)type;
  209728. controller->deviceInfo = this;
  209729. controller->framesToCheck = 1;
  209730. controller->framesOverlap = 3;
  209731. bool passed = false;
  209732. memset (rb->buffer, 0xcd, rb->bufferSize);
  209733. if (controller->read (rb))
  209734. {
  209735. passed = true;
  209736. int* p = (int*) (rb->buffer + rb->dataStartOffset);
  209737. int wrong = 0;
  209738. for (int i = rb->dataLength / 4; --i >= 0;)
  209739. {
  209740. if (*p++ == (int) 0xcdcdcdcd)
  209741. {
  209742. if (++wrong == 4)
  209743. {
  209744. passed = false;
  209745. break;
  209746. }
  209747. }
  209748. else
  209749. {
  209750. wrong = 0;
  209751. }
  209752. }
  209753. }
  209754. if (! passed)
  209755. {
  209756. controller->shutDown();
  209757. controller = 0;
  209758. }
  209759. return passed;
  209760. }
  209761. static void GetAspiDeviceInfo (CDDeviceInfo* dev, BYTE ha, BYTE tgt, BYTE lun)
  209762. {
  209763. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  209764. const int bufSize = 128;
  209765. BYTE buffer[bufSize];
  209766. zeromem (buffer, bufSize);
  209767. SRB_ExecSCSICmd s;
  209768. zerostruct (s);
  209769. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  209770. s.SRB_HaID = ha;
  209771. s.SRB_Target = tgt;
  209772. s.SRB_Lun = lun;
  209773. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  209774. s.SRB_BufLen = bufSize;
  209775. s.SRB_BufPointer = buffer;
  209776. s.SRB_SenseLen = SENSE_LEN;
  209777. s.SRB_CDBLen = 6;
  209778. s.SRB_PostProc = event;
  209779. s.CDBByte[0] = SCSI_INQUIRY;
  209780. s.CDBByte[4] = 100;
  209781. ResetEvent (event);
  209782. if (fSendASPI32Command ((LPSRB)&s) == SS_PENDING)
  209783. WaitForSingleObject (event, 4000);
  209784. CloseHandle (event);
  209785. if (s.SRB_Status == SS_COMP)
  209786. {
  209787. memcpy (dev->vendor, &buffer[8], 8);
  209788. memcpy (dev->productId, &buffer[16], 16);
  209789. memcpy (dev->rev, &buffer[32], 4);
  209790. memcpy (dev->vendorSpec, &buffer[36], 20);
  209791. }
  209792. }
  209793. static int FindCDDevices (CDDeviceInfo* const list,
  209794. int maxItems)
  209795. {
  209796. int count = 0;
  209797. if (usingScsi)
  209798. {
  209799. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  209800. {
  209801. TCHAR drivePath[8];
  209802. drivePath[0] = driveLetter;
  209803. drivePath[1] = ':';
  209804. drivePath[2] = '\\';
  209805. drivePath[3] = 0;
  209806. if (GetDriveType (drivePath) == DRIVE_CDROM)
  209807. {
  209808. HANDLE h = CreateSCSIDeviceHandle (driveLetter);
  209809. if (h != INVALID_HANDLE_VALUE)
  209810. {
  209811. BYTE buffer[100], passThroughStruct[1024];
  209812. zeromem (buffer, sizeof (buffer));
  209813. zeromem (passThroughStruct, sizeof (passThroughStruct));
  209814. PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p = (PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER)passThroughStruct;
  209815. p->spt.Length = sizeof (SCSI_PASS_THROUGH);
  209816. p->spt.CdbLength = 6;
  209817. p->spt.SenseInfoLength = 24;
  209818. p->spt.DataIn = SCSI_IOCTL_DATA_IN;
  209819. p->spt.DataTransferLength = 100;
  209820. p->spt.TimeOutValue = 2;
  209821. p->spt.DataBuffer = buffer;
  209822. p->spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  209823. p->spt.Cdb[0] = 0x12;
  209824. p->spt.Cdb[4] = 100;
  209825. DWORD bytesReturned = 0;
  209826. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  209827. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  209828. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  209829. &bytesReturned, 0) != 0)
  209830. {
  209831. zeromem (&list[count], sizeof (CDDeviceInfo));
  209832. list[count].scsiDriveLetter = driveLetter;
  209833. memcpy (list[count].vendor, &buffer[8], 8);
  209834. memcpy (list[count].productId, &buffer[16], 16);
  209835. memcpy (list[count].rev, &buffer[32], 4);
  209836. memcpy (list[count].vendorSpec, &buffer[36], 20);
  209837. zeromem (passThroughStruct, sizeof (passThroughStruct));
  209838. PSCSI_ADDRESS scsiAddr = (PSCSI_ADDRESS)passThroughStruct;
  209839. scsiAddr->Length = sizeof (SCSI_ADDRESS);
  209840. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  209841. 0, 0, scsiAddr, sizeof (SCSI_ADDRESS),
  209842. &bytesReturned, 0) != 0)
  209843. {
  209844. list[count].ha = scsiAddr->PortNumber;
  209845. list[count].tgt = scsiAddr->TargetId;
  209846. list[count].lun = scsiAddr->Lun;
  209847. ++count;
  209848. }
  209849. }
  209850. CloseHandle (h);
  209851. }
  209852. }
  209853. }
  209854. }
  209855. else
  209856. {
  209857. const DWORD d = fGetASPI32SupportInfo();
  209858. BYTE status = HIBYTE (LOWORD (d));
  209859. if (status != SS_COMP || status == SS_NO_ADAPTERS)
  209860. return 0;
  209861. const int numAdapters = LOBYTE (LOWORD (d));
  209862. for (BYTE ha = 0; ha < numAdapters; ++ha)
  209863. {
  209864. SRB_HAInquiry s;
  209865. zerostruct (s);
  209866. s.SRB_Cmd = SC_HA_INQUIRY;
  209867. s.SRB_HaID = ha;
  209868. fSendASPI32Command ((LPSRB)&s);
  209869. if (s.SRB_Status == SS_COMP)
  209870. {
  209871. maxItems = (int)s.HA_Unique[3];
  209872. if (maxItems == 0)
  209873. maxItems = 8;
  209874. for (BYTE tgt = 0; tgt < maxItems; ++tgt)
  209875. {
  209876. for (BYTE lun = 0; lun < 8; ++lun)
  209877. {
  209878. SRB_GDEVBlock sb;
  209879. zerostruct (sb);
  209880. sb.SRB_Cmd = SC_GET_DEV_TYPE;
  209881. sb.SRB_HaID = ha;
  209882. sb.SRB_Target = tgt;
  209883. sb.SRB_Lun = lun;
  209884. fSendASPI32Command ((LPSRB) &sb);
  209885. if (sb.SRB_Status == SS_COMP
  209886. && sb.SRB_DeviceType == DTYPE_CROM)
  209887. {
  209888. zeromem (&list[count], sizeof (CDDeviceInfo));
  209889. list[count].ha = ha;
  209890. list[count].tgt = tgt;
  209891. list[count].lun = lun;
  209892. GetAspiDeviceInfo (&(list[count]), ha, tgt, lun);
  209893. ++count;
  209894. }
  209895. }
  209896. }
  209897. }
  209898. }
  209899. }
  209900. return count;
  209901. }
  209902. static int ripperUsers = 0;
  209903. static bool initialisedOk = false;
  209904. class DeinitialiseTimer : private Timer,
  209905. private DeletedAtShutdown
  209906. {
  209907. DeinitialiseTimer (const DeinitialiseTimer&);
  209908. DeinitialiseTimer& operator= (const DeinitialiseTimer&);
  209909. public:
  209910. DeinitialiseTimer()
  209911. {
  209912. startTimer (4000);
  209913. }
  209914. ~DeinitialiseTimer()
  209915. {
  209916. if (--ripperUsers == 0)
  209917. DeinitialiseCDRipper();
  209918. }
  209919. void timerCallback()
  209920. {
  209921. delete this;
  209922. }
  209923. juce_UseDebuggingNewOperator
  209924. };
  209925. static void incUserCount()
  209926. {
  209927. if (ripperUsers++ == 0)
  209928. initialisedOk = InitialiseCDRipper();
  209929. }
  209930. static void decUserCount()
  209931. {
  209932. new DeinitialiseTimer();
  209933. }
  209934. struct CDDeviceWrapper
  209935. {
  209936. ScopedPointer<CDDeviceHandle> cdH;
  209937. ScopedPointer<CDReadBuffer> overlapBuffer;
  209938. bool jitter;
  209939. };
  209940. static int getAddressOf (const TOCTRACK* const t)
  209941. {
  209942. return (((DWORD)t->addr[0]) << 24) + (((DWORD)t->addr[1]) << 16) +
  209943. (((DWORD)t->addr[2]) << 8) + ((DWORD)t->addr[3]);
  209944. }
  209945. static int getMSFAddressOf (const TOCTRACK* const t)
  209946. {
  209947. return 60 * t->addr[1] + t->addr[2];
  209948. }
  209949. static const int samplesPerFrame = 44100 / 75;
  209950. static const int bytesPerFrame = samplesPerFrame * 4;
  209951. static CDDeviceHandle* openHandle (const CDDeviceInfo* const device)
  209952. {
  209953. SRB_GDEVBlock s;
  209954. zerostruct (s);
  209955. s.SRB_Cmd = SC_GET_DEV_TYPE;
  209956. s.SRB_HaID = device->ha;
  209957. s.SRB_Target = device->tgt;
  209958. s.SRB_Lun = device->lun;
  209959. if (usingScsi)
  209960. {
  209961. HANDLE h = CreateSCSIDeviceHandle (device->scsiDriveLetter);
  209962. if (h != INVALID_HANDLE_VALUE)
  209963. {
  209964. CDDeviceHandle* cdh = new CDDeviceHandle (device);
  209965. cdh->scsiHandle = h;
  209966. return cdh;
  209967. }
  209968. }
  209969. else
  209970. {
  209971. if (fSendASPI32Command ((LPSRB)&s) == SS_COMP
  209972. && s.SRB_DeviceType == DTYPE_CROM)
  209973. {
  209974. return new CDDeviceHandle (device);
  209975. }
  209976. }
  209977. return 0;
  209978. }
  209979. }
  209980. const StringArray AudioCDReader::getAvailableCDNames()
  209981. {
  209982. using namespace CDReaderHelpers;
  209983. StringArray results;
  209984. incUserCount();
  209985. if (initialisedOk)
  209986. {
  209987. CDDeviceInfo list[8];
  209988. const int num = FindCDDevices (list, 8);
  209989. decUserCount();
  209990. for (int i = 0; i < num; ++i)
  209991. {
  209992. String s;
  209993. if (list[i].scsiDriveLetter > 0)
  209994. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << ": ";
  209995. s << String (list[i].vendor).trim()
  209996. << ' ' << String (list[i].productId).trim()
  209997. << ' ' << String (list[i].rev).trim();
  209998. results.add (s);
  209999. }
  210000. }
  210001. return results;
  210002. }
  210003. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  210004. {
  210005. using namespace CDReaderHelpers;
  210006. incUserCount();
  210007. if (initialisedOk)
  210008. {
  210009. CDDeviceInfo list[8];
  210010. const int num = FindCDDevices (list, 8);
  210011. if (((unsigned int) deviceIndex) < (unsigned int) num)
  210012. {
  210013. CDDeviceHandle* const handle = openHandle (&(list[deviceIndex]));
  210014. if (handle != 0)
  210015. {
  210016. CDDeviceWrapper* const d = new CDDeviceWrapper();
  210017. d->cdH = handle;
  210018. d->overlapBuffer = new CDReadBuffer(3);
  210019. return new AudioCDReader (d);
  210020. }
  210021. }
  210022. }
  210023. decUserCount();
  210024. return 0;
  210025. }
  210026. AudioCDReader::AudioCDReader (void* handle_)
  210027. : AudioFormatReader (0, "CD Audio"),
  210028. handle (handle_),
  210029. indexingEnabled (false),
  210030. lastIndex (0),
  210031. firstFrameInBuffer (0),
  210032. samplesInBuffer (0)
  210033. {
  210034. using namespace CDReaderHelpers;
  210035. jassert (handle_ != 0);
  210036. refreshTrackLengths();
  210037. sampleRate = 44100.0;
  210038. bitsPerSample = 16;
  210039. lengthInSamples = getPositionOfTrackStart (numTracks);
  210040. numChannels = 2;
  210041. usesFloatingPointData = false;
  210042. buffer.setSize (4 * bytesPerFrame, true);
  210043. }
  210044. AudioCDReader::~AudioCDReader()
  210045. {
  210046. using namespace CDReaderHelpers;
  210047. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  210048. delete device;
  210049. decUserCount();
  210050. }
  210051. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  210052. int64 startSampleInFile, int numSamples)
  210053. {
  210054. using namespace CDReaderHelpers;
  210055. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  210056. bool ok = true;
  210057. while (numSamples > 0)
  210058. {
  210059. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  210060. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  210061. if (startSampleInFile >= bufferStartSample
  210062. && startSampleInFile < bufferEndSample)
  210063. {
  210064. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  210065. int* const l = destSamples[0] + startOffsetInDestBuffer;
  210066. int* const r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  210067. const short* src = (const short*) buffer.getData();
  210068. src += 2 * (startSampleInFile - bufferStartSample);
  210069. for (int i = 0; i < toDo; ++i)
  210070. {
  210071. l[i] = src [i << 1] << 16;
  210072. if (r != 0)
  210073. r[i] = src [(i << 1) + 1] << 16;
  210074. }
  210075. startOffsetInDestBuffer += toDo;
  210076. startSampleInFile += toDo;
  210077. numSamples -= toDo;
  210078. }
  210079. else
  210080. {
  210081. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  210082. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  210083. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  210084. {
  210085. device->overlapBuffer->dataLength = 0;
  210086. device->overlapBuffer->startFrame = 0;
  210087. device->overlapBuffer->numFrames = 0;
  210088. device->jitter = false;
  210089. }
  210090. firstFrameInBuffer = frameNeeded;
  210091. lastIndex = 0;
  210092. CDReadBuffer readBuffer (framesInBuffer + 4);
  210093. readBuffer.wantsIndex = indexingEnabled;
  210094. int i;
  210095. for (i = 5; --i >= 0;)
  210096. {
  210097. readBuffer.startFrame = frameNeeded;
  210098. readBuffer.numFrames = framesInBuffer;
  210099. if (device->cdH->readAudio (&readBuffer, (device->jitter) ? device->overlapBuffer : 0))
  210100. break;
  210101. else
  210102. device->overlapBuffer->dataLength = 0;
  210103. }
  210104. if (i >= 0)
  210105. {
  210106. memcpy ((char*) buffer.getData(),
  210107. readBuffer.buffer + readBuffer.dataStartOffset,
  210108. readBuffer.dataLength);
  210109. samplesInBuffer = readBuffer.dataLength >> 2;
  210110. lastIndex = readBuffer.index;
  210111. }
  210112. else
  210113. {
  210114. int* l = destSamples[0] + startOffsetInDestBuffer;
  210115. int* r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  210116. while (--numSamples >= 0)
  210117. {
  210118. *l++ = 0;
  210119. if (r != 0)
  210120. *r++ = 0;
  210121. }
  210122. // sometimes the read fails for just the very last couple of blocks, so
  210123. // we'll ignore and errors in the last half-second of the disk..
  210124. ok = startSampleInFile > (trackStarts [numTracks] - 20000);
  210125. break;
  210126. }
  210127. }
  210128. }
  210129. return ok;
  210130. }
  210131. bool AudioCDReader::isCDStillPresent() const
  210132. {
  210133. using namespace CDReaderHelpers;
  210134. TOC toc;
  210135. zerostruct (toc);
  210136. return ((CDDeviceWrapper*) handle)->cdH->readTOC (&toc, false);
  210137. }
  210138. int AudioCDReader::getNumTracks() const
  210139. {
  210140. return numTracks;
  210141. }
  210142. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  210143. {
  210144. using namespace CDReaderHelpers;
  210145. return (trackNum >= 0 && trackNum <= numTracks) ? trackStarts [trackNum] * samplesPerFrame
  210146. : 0;
  210147. }
  210148. void AudioCDReader::refreshTrackLengths()
  210149. {
  210150. using namespace CDReaderHelpers;
  210151. zeromem (trackStarts, sizeof (trackStarts));
  210152. zeromem (audioTracks, sizeof (audioTracks));
  210153. TOC toc;
  210154. zerostruct (toc);
  210155. if (((CDDeviceWrapper*)handle)->cdH->readTOC (&toc, false))
  210156. {
  210157. numTracks = 1 + toc.lastTrack - toc.firstTrack;
  210158. for (int i = 0; i <= numTracks; ++i)
  210159. {
  210160. trackStarts[i] = getAddressOf (&toc.tracks[i]);
  210161. audioTracks[i] = ((toc.tracks[i].ADR & 4) == 0);
  210162. }
  210163. }
  210164. else
  210165. {
  210166. numTracks = 0;
  210167. }
  210168. }
  210169. bool AudioCDReader::isTrackAudio (int trackNum) const
  210170. {
  210171. return (trackNum >= 0 && trackNum <= numTracks) ? audioTracks [trackNum]
  210172. : false;
  210173. }
  210174. void AudioCDReader::enableIndexScanning (bool b)
  210175. {
  210176. indexingEnabled = b;
  210177. }
  210178. int AudioCDReader::getLastIndex() const
  210179. {
  210180. return lastIndex;
  210181. }
  210182. const int framesPerIndexRead = 4;
  210183. int AudioCDReader::getIndexAt (int samplePos)
  210184. {
  210185. using namespace CDReaderHelpers;
  210186. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  210187. const int frameNeeded = samplePos / samplesPerFrame;
  210188. device->overlapBuffer->dataLength = 0;
  210189. device->overlapBuffer->startFrame = 0;
  210190. device->overlapBuffer->numFrames = 0;
  210191. device->jitter = false;
  210192. firstFrameInBuffer = 0;
  210193. lastIndex = 0;
  210194. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  210195. readBuffer.wantsIndex = true;
  210196. int i;
  210197. for (i = 5; --i >= 0;)
  210198. {
  210199. readBuffer.startFrame = frameNeeded;
  210200. readBuffer.numFrames = framesPerIndexRead;
  210201. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  210202. break;
  210203. }
  210204. if (i >= 0)
  210205. return readBuffer.index;
  210206. return -1;
  210207. }
  210208. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  210209. {
  210210. using namespace CDReaderHelpers;
  210211. Array <int> indexes;
  210212. const int trackStart = getPositionOfTrackStart (trackNumber);
  210213. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  210214. bool needToScan = true;
  210215. if (trackEnd - trackStart > 20 * 44100)
  210216. {
  210217. // check the end of the track for indexes before scanning the whole thing
  210218. needToScan = false;
  210219. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  210220. bool seenAnIndex = false;
  210221. while (pos <= trackEnd - samplesPerFrame)
  210222. {
  210223. const int index = getIndexAt (pos);
  210224. if (index == 0)
  210225. {
  210226. // lead-out, so skip back a bit if we've not found any indexes yet..
  210227. if (seenAnIndex)
  210228. break;
  210229. pos -= 44100 * 5;
  210230. if (pos < trackStart)
  210231. break;
  210232. }
  210233. else
  210234. {
  210235. if (index > 0)
  210236. seenAnIndex = true;
  210237. if (index > 1)
  210238. {
  210239. needToScan = true;
  210240. break;
  210241. }
  210242. pos += samplesPerFrame * framesPerIndexRead;
  210243. }
  210244. }
  210245. }
  210246. if (needToScan)
  210247. {
  210248. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  210249. int pos = trackStart;
  210250. int last = -1;
  210251. while (pos < trackEnd - samplesPerFrame * 10)
  210252. {
  210253. const int frameNeeded = pos / samplesPerFrame;
  210254. device->overlapBuffer->dataLength = 0;
  210255. device->overlapBuffer->startFrame = 0;
  210256. device->overlapBuffer->numFrames = 0;
  210257. device->jitter = false;
  210258. firstFrameInBuffer = 0;
  210259. CDReadBuffer readBuffer (4);
  210260. readBuffer.wantsIndex = true;
  210261. int i;
  210262. for (i = 5; --i >= 0;)
  210263. {
  210264. readBuffer.startFrame = frameNeeded;
  210265. readBuffer.numFrames = framesPerIndexRead;
  210266. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  210267. break;
  210268. }
  210269. if (i < 0)
  210270. break;
  210271. if (readBuffer.index > last && readBuffer.index > 1)
  210272. {
  210273. last = readBuffer.index;
  210274. indexes.add (pos);
  210275. }
  210276. pos += samplesPerFrame * framesPerIndexRead;
  210277. }
  210278. indexes.removeValue (trackStart);
  210279. }
  210280. return indexes;
  210281. }
  210282. int AudioCDReader::getCDDBId()
  210283. {
  210284. using namespace CDReaderHelpers;
  210285. refreshTrackLengths();
  210286. if (numTracks > 0)
  210287. {
  210288. TOC toc;
  210289. zerostruct (toc);
  210290. if (((CDDeviceWrapper*) handle)->cdH->readTOC (&toc, true))
  210291. {
  210292. int n = 0;
  210293. for (int i = numTracks; --i >= 0;)
  210294. {
  210295. int j = getMSFAddressOf (&toc.tracks[i]);
  210296. while (j > 0)
  210297. {
  210298. n += (j % 10);
  210299. j /= 10;
  210300. }
  210301. }
  210302. if (n != 0)
  210303. {
  210304. const int t = getMSFAddressOf (&toc.tracks[numTracks])
  210305. - getMSFAddressOf (&toc.tracks[0]);
  210306. return ((n % 0xff) << 24) | (t << 8) | numTracks;
  210307. }
  210308. }
  210309. }
  210310. return 0;
  210311. }
  210312. void AudioCDReader::ejectDisk()
  210313. {
  210314. using namespace CDReaderHelpers;
  210315. ((CDDeviceWrapper*) handle)->cdH->openDrawer (true);
  210316. }
  210317. #endif
  210318. #if JUCE_USE_CDBURNER
  210319. static IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  210320. {
  210321. CoInitialize (0);
  210322. IDiscMaster* dm;
  210323. IDiscRecorder* result = 0;
  210324. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  210325. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  210326. IID_IDiscMaster,
  210327. (void**) &dm)))
  210328. {
  210329. if (SUCCEEDED (dm->Open()))
  210330. {
  210331. IEnumDiscRecorders* drEnum = 0;
  210332. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  210333. {
  210334. IDiscRecorder* dr = 0;
  210335. DWORD dummy;
  210336. int index = 0;
  210337. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  210338. {
  210339. if (indexToOpen == index)
  210340. {
  210341. result = dr;
  210342. break;
  210343. }
  210344. else if (list != 0)
  210345. {
  210346. BSTR path;
  210347. if (SUCCEEDED (dr->GetPath (&path)))
  210348. list->add ((const WCHAR*) path);
  210349. }
  210350. ++index;
  210351. dr->Release();
  210352. }
  210353. drEnum->Release();
  210354. }
  210355. if (master == 0)
  210356. dm->Close();
  210357. }
  210358. if (master != 0)
  210359. *master = dm;
  210360. else
  210361. dm->Release();
  210362. }
  210363. return result;
  210364. }
  210365. class AudioCDBurner::Pimpl : public ComBaseClassHelper <IDiscMasterProgressEvents>,
  210366. public Timer
  210367. {
  210368. public:
  210369. Pimpl (AudioCDBurner& owner_, IDiscMaster* discMaster_, IDiscRecorder* discRecorder_)
  210370. : owner (owner_), discMaster (discMaster_), discRecorder (discRecorder_), redbook (0),
  210371. listener (0), progress (0), shouldCancel (false)
  210372. {
  210373. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  210374. jassert (SUCCEEDED (hr));
  210375. hr = discMaster->SetActiveDiscRecorder (discRecorder);
  210376. //jassert (SUCCEEDED (hr));
  210377. lastState = getDiskState();
  210378. startTimer (2000);
  210379. }
  210380. ~Pimpl() {}
  210381. void releaseObjects()
  210382. {
  210383. discRecorder->Close();
  210384. if (redbook != 0)
  210385. redbook->Release();
  210386. discRecorder->Release();
  210387. discMaster->Release();
  210388. Release();
  210389. }
  210390. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  210391. {
  210392. if (listener != 0 && ! shouldCancel)
  210393. shouldCancel = listener->audioCDBurnProgress (progress);
  210394. *pbCancel = shouldCancel;
  210395. return S_OK;
  210396. }
  210397. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  210398. {
  210399. progress = nCompleted / (float) nTotal;
  210400. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  210401. return E_NOTIMPL;
  210402. }
  210403. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  210404. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  210405. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  210406. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  210407. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  210408. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  210409. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  210410. class ScopedDiscOpener
  210411. {
  210412. public:
  210413. ScopedDiscOpener (Pimpl& p) : pimpl (p) { pimpl.discRecorder->OpenExclusive(); }
  210414. ~ScopedDiscOpener() { pimpl.discRecorder->Close(); }
  210415. private:
  210416. Pimpl& pimpl;
  210417. ScopedDiscOpener (const ScopedDiscOpener&);
  210418. ScopedDiscOpener& operator= (const ScopedDiscOpener&);
  210419. };
  210420. DiskState getDiskState()
  210421. {
  210422. const ScopedDiscOpener opener (*this);
  210423. long type, flags;
  210424. HRESULT hr = discRecorder->QueryMediaType (&type, &flags);
  210425. if (FAILED (hr))
  210426. return unknown;
  210427. if (type != 0 && (flags & MEDIA_WRITABLE) != 0)
  210428. return writableDiskPresent;
  210429. if (type == 0)
  210430. return noDisc;
  210431. else
  210432. return readOnlyDiskPresent;
  210433. }
  210434. int getIntProperty (const LPOLESTR name, const int defaultReturn) const
  210435. {
  210436. ComSmartPtr<IPropertyStorage> prop;
  210437. if (FAILED (discRecorder->GetRecorderProperties (&prop)))
  210438. return defaultReturn;
  210439. PROPSPEC iPropSpec;
  210440. iPropSpec.ulKind = PRSPEC_LPWSTR;
  210441. iPropSpec.lpwstr = name;
  210442. PROPVARIANT iPropVariant;
  210443. return FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant))
  210444. ? defaultReturn : (int) iPropVariant.lVal;
  210445. }
  210446. bool setIntProperty (const LPOLESTR name, const int value) const
  210447. {
  210448. ComSmartPtr<IPropertyStorage> prop;
  210449. if (FAILED (discRecorder->GetRecorderProperties (&prop)))
  210450. return false;
  210451. PROPSPEC iPropSpec;
  210452. iPropSpec.ulKind = PRSPEC_LPWSTR;
  210453. iPropSpec.lpwstr = name;
  210454. PROPVARIANT iPropVariant;
  210455. if (FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant)))
  210456. return false;
  210457. iPropVariant.lVal = (long) value;
  210458. return SUCCEEDED (prop->WriteMultiple (1, &iPropSpec, &iPropVariant, iPropVariant.vt))
  210459. && SUCCEEDED (discRecorder->SetRecorderProperties (prop));
  210460. }
  210461. void timerCallback()
  210462. {
  210463. const DiskState state = getDiskState();
  210464. if (state != lastState)
  210465. {
  210466. lastState = state;
  210467. owner.sendChangeMessage (&owner);
  210468. }
  210469. }
  210470. AudioCDBurner& owner;
  210471. DiskState lastState;
  210472. IDiscMaster* discMaster;
  210473. IDiscRecorder* discRecorder;
  210474. IRedbookDiscMaster* redbook;
  210475. AudioCDBurner::BurnProgressListener* listener;
  210476. float progress;
  210477. bool shouldCancel;
  210478. };
  210479. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  210480. {
  210481. IDiscMaster* discMaster = 0;
  210482. IDiscRecorder* discRecorder = enumCDBurners (0, deviceIndex, &discMaster);
  210483. if (discRecorder != 0)
  210484. pimpl = new Pimpl (*this, discMaster, discRecorder);
  210485. }
  210486. AudioCDBurner::~AudioCDBurner()
  210487. {
  210488. if (pimpl != 0)
  210489. pimpl.release()->releaseObjects();
  210490. }
  210491. const StringArray AudioCDBurner::findAvailableDevices()
  210492. {
  210493. StringArray devs;
  210494. enumCDBurners (&devs, -1, 0);
  210495. return devs;
  210496. }
  210497. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  210498. {
  210499. ScopedPointer<AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  210500. if (b->pimpl == 0)
  210501. b = 0;
  210502. return b.release();
  210503. }
  210504. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  210505. {
  210506. return pimpl->getDiskState();
  210507. }
  210508. bool AudioCDBurner::isDiskPresent() const
  210509. {
  210510. return getDiskState() == writableDiskPresent;
  210511. }
  210512. bool AudioCDBurner::openTray()
  210513. {
  210514. const Pimpl::ScopedDiscOpener opener (*pimpl);
  210515. return SUCCEEDED (pimpl->discRecorder->Eject());
  210516. }
  210517. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  210518. {
  210519. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  210520. DiskState oldState = getDiskState();
  210521. DiskState newState = oldState;
  210522. while (newState == oldState && Time::currentTimeMillis() < timeout)
  210523. {
  210524. newState = getDiskState();
  210525. Thread::sleep (jmin (250, (int) (timeout - Time::currentTimeMillis())));
  210526. }
  210527. return newState;
  210528. }
  210529. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  210530. {
  210531. Array<int> results;
  210532. const int maxSpeed = pimpl->getIntProperty (L"MaxWriteSpeed", 1);
  210533. const int speeds[] = { 1, 2, 4, 8, 12, 16, 20, 24, 32, 40, 64, 80 };
  210534. for (int i = 0; i < numElementsInArray (speeds); ++i)
  210535. if (speeds[i] <= maxSpeed)
  210536. results.add (speeds[i]);
  210537. results.addIfNotAlreadyThere (maxSpeed);
  210538. return results;
  210539. }
  210540. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  210541. {
  210542. if (pimpl->getIntProperty (L"BufferUnderrunFreeCapable", 0) == 0)
  210543. return false;
  210544. pimpl->setIntProperty (L"EnableBufferUnderrunFree", shouldBeEnabled ? -1 : 0);
  210545. return pimpl->getIntProperty (L"EnableBufferUnderrunFree", 0) != 0;
  210546. }
  210547. int AudioCDBurner::getNumAvailableAudioBlocks() const
  210548. {
  210549. long blocksFree = 0;
  210550. pimpl->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  210551. return blocksFree;
  210552. }
  210553. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener, bool ejectDiscAfterwards,
  210554. bool performFakeBurnForTesting, int writeSpeed)
  210555. {
  210556. pimpl->setIntProperty (L"WriteSpeed", writeSpeed > 0 ? writeSpeed : -1);
  210557. pimpl->listener = listener;
  210558. pimpl->progress = 0;
  210559. pimpl->shouldCancel = false;
  210560. UINT_PTR cookie;
  210561. HRESULT hr = pimpl->discMaster->ProgressAdvise ((AudioCDBurner::Pimpl*) pimpl, &cookie);
  210562. hr = pimpl->discMaster->RecordDisc (performFakeBurnForTesting,
  210563. ejectDiscAfterwards);
  210564. String error;
  210565. if (hr != S_OK)
  210566. {
  210567. const char* e = "Couldn't open or write to the CD device";
  210568. if (hr == IMAPI_E_USERABORT)
  210569. e = "User cancelled the write operation";
  210570. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  210571. e = "No Disk present";
  210572. error = e;
  210573. }
  210574. pimpl->discMaster->ProgressUnadvise (cookie);
  210575. pimpl->listener = 0;
  210576. return error;
  210577. }
  210578. bool AudioCDBurner::addAudioTrack (AudioSource* audioSource, int numSamples)
  210579. {
  210580. if (audioSource == 0)
  210581. return false;
  210582. ScopedPointer<AudioSource> source (audioSource);
  210583. long bytesPerBlock;
  210584. HRESULT hr = pimpl->redbook->GetAudioBlockSize (&bytesPerBlock);
  210585. const int samplesPerBlock = bytesPerBlock / 4;
  210586. bool ok = true;
  210587. hr = pimpl->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  210588. HeapBlock <byte> buffer (bytesPerBlock);
  210589. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  210590. int samplesDone = 0;
  210591. source->prepareToPlay (samplesPerBlock, 44100.0);
  210592. while (ok)
  210593. {
  210594. {
  210595. AudioSourceChannelInfo info;
  210596. info.buffer = &sourceBuffer;
  210597. info.numSamples = samplesPerBlock;
  210598. info.startSample = 0;
  210599. sourceBuffer.clear();
  210600. source->getNextAudioBlock (info);
  210601. }
  210602. zeromem (buffer, bytesPerBlock);
  210603. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (0, 0),
  210604. buffer, samplesPerBlock, 4);
  210605. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (1, 0),
  210606. buffer + 2, samplesPerBlock, 4);
  210607. hr = pimpl->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  210608. if (FAILED (hr))
  210609. ok = false;
  210610. samplesDone += samplesPerBlock;
  210611. if (samplesDone >= numSamples)
  210612. break;
  210613. }
  210614. hr = pimpl->redbook->CloseAudioTrack();
  210615. return ok && hr == S_OK;
  210616. }
  210617. #endif
  210618. #endif
  210619. /*** End of inlined file: juce_win32_AudioCDReader.cpp ***/
  210620. /*** Start of inlined file: juce_win32_Midi.cpp ***/
  210621. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210622. // compiled on its own).
  210623. #if JUCE_INCLUDED_FILE
  210624. using ::free;
  210625. namespace MidiConstants
  210626. {
  210627. static const int midiBufferSize = 1024 * 10;
  210628. static const int numInHeaders = 32;
  210629. static const int inBufferSize = 256;
  210630. }
  210631. class MidiInThread : public Thread
  210632. {
  210633. public:
  210634. MidiInThread (MidiInput* const input_,
  210635. MidiInputCallback* const callback_)
  210636. : Thread ("Juce Midi"),
  210637. hIn (0),
  210638. input (input_),
  210639. callback (callback_),
  210640. isStarted (false),
  210641. startTime (0),
  210642. pendingLength(0)
  210643. {
  210644. for (int i = MidiConstants::numInHeaders; --i >= 0;)
  210645. {
  210646. zeromem (&hdr[i], sizeof (MIDIHDR));
  210647. hdr[i].lpData = inData[i];
  210648. hdr[i].dwBufferLength = MidiConstants::inBufferSize;
  210649. }
  210650. };
  210651. ~MidiInThread()
  210652. {
  210653. stop();
  210654. if (hIn != 0)
  210655. {
  210656. int count = 5;
  210657. while (--count >= 0)
  210658. {
  210659. if (midiInClose (hIn) == MMSYSERR_NOERROR)
  210660. break;
  210661. Sleep (20);
  210662. }
  210663. }
  210664. }
  210665. void handle (const uint32 message, const uint32 timeStamp)
  210666. {
  210667. const int byte = message & 0xff;
  210668. if (byte < 0x80)
  210669. return;
  210670. const int numBytes = MidiMessage::getMessageLengthFromFirstByte ((uint8) byte);
  210671. const double time = timeStampToTime (timeStamp);
  210672. {
  210673. const ScopedLock sl (lock);
  210674. if (pendingLength < MidiConstants::midiBufferSize - 12)
  210675. {
  210676. char* const p = pending + pendingLength;
  210677. *(double*) p = time;
  210678. *(uint32*) (p + 8) = numBytes;
  210679. *(uint32*) (p + 12) = message;
  210680. pendingLength += 12 + numBytes;
  210681. }
  210682. else
  210683. {
  210684. jassertfalse; // midi buffer overflow! You might need to increase the size..
  210685. }
  210686. }
  210687. notify();
  210688. }
  210689. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp)
  210690. {
  210691. const int num = hdr->dwBytesRecorded;
  210692. if (num > 0)
  210693. {
  210694. const double time = timeStampToTime (timeStamp);
  210695. {
  210696. const ScopedLock sl (lock);
  210697. if (pendingLength < MidiConstants::midiBufferSize - (8 + num))
  210698. {
  210699. char* const p = pending + pendingLength;
  210700. *(double*) p = time;
  210701. *(uint32*) (p + 8) = num;
  210702. memcpy (p + 12, hdr->lpData, num);
  210703. pendingLength += 12 + num;
  210704. }
  210705. else
  210706. {
  210707. jassertfalse; // midi buffer overflow! You might need to increase the size..
  210708. }
  210709. }
  210710. notify();
  210711. }
  210712. }
  210713. void writeBlock (const int i)
  210714. {
  210715. hdr[i].dwBytesRecorded = 0;
  210716. MMRESULT res = midiInPrepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  210717. jassert (res == MMSYSERR_NOERROR);
  210718. res = midiInAddBuffer (hIn, &hdr[i], sizeof (MIDIHDR));
  210719. jassert (res == MMSYSERR_NOERROR);
  210720. }
  210721. void run()
  210722. {
  210723. MemoryBlock pendingCopy (64);
  210724. while (! threadShouldExit())
  210725. {
  210726. for (int i = 0; i < MidiConstants::numInHeaders; ++i)
  210727. {
  210728. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  210729. {
  210730. MMRESULT res = midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  210731. (void) res;
  210732. jassert (res == MMSYSERR_NOERROR);
  210733. writeBlock (i);
  210734. }
  210735. }
  210736. int len;
  210737. {
  210738. const ScopedLock sl (lock);
  210739. len = pendingLength;
  210740. if (len > 0)
  210741. {
  210742. pendingCopy.ensureSize (len);
  210743. pendingCopy.copyFrom (pending, 0, len);
  210744. pendingLength = 0;
  210745. }
  210746. }
  210747. //xxx needs to figure out if blocks are broken up or not
  210748. if (len == 0)
  210749. {
  210750. wait (500);
  210751. }
  210752. else
  210753. {
  210754. const char* p = (const char*) pendingCopy.getData();
  210755. while (len > 0)
  210756. {
  210757. const double time = *(const double*) p;
  210758. const int messageLen = *(const int*) (p + 8);
  210759. const MidiMessage message ((const uint8*) (p + 12), messageLen, time);
  210760. callback->handleIncomingMidiMessage (input, message);
  210761. p += 12 + messageLen;
  210762. len -= 12 + messageLen;
  210763. }
  210764. }
  210765. }
  210766. }
  210767. void start()
  210768. {
  210769. jassert (hIn != 0);
  210770. if (hIn != 0 && ! isStarted)
  210771. {
  210772. stop();
  210773. activeMidiThreads.addIfNotAlreadyThere (this);
  210774. int i;
  210775. for (i = 0; i < MidiConstants::numInHeaders; ++i)
  210776. writeBlock (i);
  210777. startTime = Time::getMillisecondCounter();
  210778. MMRESULT res = midiInStart (hIn);
  210779. jassert (res == MMSYSERR_NOERROR);
  210780. if (res == MMSYSERR_NOERROR)
  210781. {
  210782. isStarted = true;
  210783. pendingLength = 0;
  210784. startThread (6);
  210785. }
  210786. }
  210787. }
  210788. void stop()
  210789. {
  210790. if (isStarted)
  210791. {
  210792. stopThread (5000);
  210793. midiInReset (hIn);
  210794. midiInStop (hIn);
  210795. activeMidiThreads.removeValue (this);
  210796. { const ScopedLock sl (lock); }
  210797. for (int i = MidiConstants::numInHeaders; --i >= 0;)
  210798. {
  210799. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  210800. {
  210801. int c = 10;
  210802. while (--c >= 0 && midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR)) == MIDIERR_STILLPLAYING)
  210803. Sleep (20);
  210804. jassert (c >= 0);
  210805. }
  210806. }
  210807. isStarted = false;
  210808. pendingLength = 0;
  210809. }
  210810. }
  210811. static void CALLBACK midiInCallback (HMIDIIN, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR midiMessage, DWORD_PTR timeStamp)
  210812. {
  210813. MidiInThread* const thread = reinterpret_cast <MidiInThread*> (dwInstance);
  210814. if (thread != 0 && activeMidiThreads.contains (thread))
  210815. {
  210816. if (uMsg == MIM_DATA)
  210817. thread->handle ((uint32) midiMessage, (uint32) timeStamp);
  210818. else if (uMsg == MIM_LONGDATA)
  210819. thread->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  210820. }
  210821. }
  210822. juce_UseDebuggingNewOperator
  210823. HMIDIIN hIn;
  210824. private:
  210825. static Array <void*, CriticalSection> activeMidiThreads;
  210826. MidiInput* input;
  210827. MidiInputCallback* callback;
  210828. bool isStarted;
  210829. uint32 startTime;
  210830. CriticalSection lock;
  210831. MIDIHDR hdr [MidiConstants::numInHeaders];
  210832. char inData [MidiConstants::numInHeaders] [MidiConstants::inBufferSize];
  210833. int pendingLength;
  210834. char pending [MidiConstants::midiBufferSize];
  210835. double timeStampToTime (uint32 timeStamp)
  210836. {
  210837. timeStamp += startTime;
  210838. const uint32 now = Time::getMillisecondCounter();
  210839. if (timeStamp > now)
  210840. {
  210841. if (timeStamp > now + 2)
  210842. --startTime;
  210843. timeStamp = now;
  210844. }
  210845. return 0.001 * timeStamp;
  210846. }
  210847. MidiInThread (const MidiInThread&);
  210848. MidiInThread& operator= (const MidiInThread&);
  210849. };
  210850. Array <void*, CriticalSection> MidiInThread::activeMidiThreads;
  210851. const StringArray MidiInput::getDevices()
  210852. {
  210853. StringArray s;
  210854. const int num = midiInGetNumDevs();
  210855. for (int i = 0; i < num; ++i)
  210856. {
  210857. MIDIINCAPS mc;
  210858. zerostruct (mc);
  210859. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  210860. s.add (String (mc.szPname, sizeof (mc.szPname)));
  210861. }
  210862. return s;
  210863. }
  210864. int MidiInput::getDefaultDeviceIndex()
  210865. {
  210866. return 0;
  210867. }
  210868. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  210869. {
  210870. if (callback == 0)
  210871. return 0;
  210872. UINT deviceId = MIDI_MAPPER;
  210873. int n = 0;
  210874. String name;
  210875. const int num = midiInGetNumDevs();
  210876. for (int i = 0; i < num; ++i)
  210877. {
  210878. MIDIINCAPS mc;
  210879. zerostruct (mc);
  210880. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  210881. {
  210882. if (index == n)
  210883. {
  210884. deviceId = i;
  210885. name = String (mc.szPname, sizeof (mc.szPname));
  210886. break;
  210887. }
  210888. ++n;
  210889. }
  210890. }
  210891. ScopedPointer <MidiInput> in (new MidiInput (name));
  210892. ScopedPointer <MidiInThread> thread (new MidiInThread (in, callback));
  210893. HMIDIIN h;
  210894. HRESULT err = midiInOpen (&h, deviceId,
  210895. (DWORD_PTR) &MidiInThread::midiInCallback,
  210896. (DWORD_PTR) (MidiInThread*) thread,
  210897. CALLBACK_FUNCTION);
  210898. if (err == MMSYSERR_NOERROR)
  210899. {
  210900. thread->hIn = h;
  210901. in->internal = thread.release();
  210902. return in.release();
  210903. }
  210904. return 0;
  210905. }
  210906. MidiInput::MidiInput (const String& name_)
  210907. : name (name_),
  210908. internal (0)
  210909. {
  210910. }
  210911. MidiInput::~MidiInput()
  210912. {
  210913. delete static_cast <MidiInThread*> (internal);
  210914. }
  210915. void MidiInput::start()
  210916. {
  210917. static_cast <MidiInThread*> (internal)->start();
  210918. }
  210919. void MidiInput::stop()
  210920. {
  210921. static_cast <MidiInThread*> (internal)->stop();
  210922. }
  210923. struct MidiOutHandle
  210924. {
  210925. int refCount;
  210926. UINT deviceId;
  210927. HMIDIOUT handle;
  210928. static Array<MidiOutHandle*> activeHandles;
  210929. juce_UseDebuggingNewOperator
  210930. };
  210931. Array<MidiOutHandle*> MidiOutHandle::activeHandles;
  210932. const StringArray MidiOutput::getDevices()
  210933. {
  210934. StringArray s;
  210935. const int num = midiOutGetNumDevs();
  210936. for (int i = 0; i < num; ++i)
  210937. {
  210938. MIDIOUTCAPS mc;
  210939. zerostruct (mc);
  210940. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  210941. s.add (String (mc.szPname, sizeof (mc.szPname)));
  210942. }
  210943. return s;
  210944. }
  210945. int MidiOutput::getDefaultDeviceIndex()
  210946. {
  210947. const int num = midiOutGetNumDevs();
  210948. int n = 0;
  210949. for (int i = 0; i < num; ++i)
  210950. {
  210951. MIDIOUTCAPS mc;
  210952. zerostruct (mc);
  210953. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  210954. {
  210955. if ((mc.wTechnology & MOD_MAPPER) != 0)
  210956. return n;
  210957. ++n;
  210958. }
  210959. }
  210960. return 0;
  210961. }
  210962. MidiOutput* MidiOutput::openDevice (int index)
  210963. {
  210964. UINT deviceId = MIDI_MAPPER;
  210965. const int num = midiOutGetNumDevs();
  210966. int i, n = 0;
  210967. for (i = 0; i < num; ++i)
  210968. {
  210969. MIDIOUTCAPS mc;
  210970. zerostruct (mc);
  210971. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  210972. {
  210973. // use the microsoft sw synth as a default - best not to allow deviceId
  210974. // to be MIDI_MAPPER, or else device sharing breaks
  210975. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase ("microsoft"))
  210976. deviceId = i;
  210977. if (index == n)
  210978. {
  210979. deviceId = i;
  210980. break;
  210981. }
  210982. ++n;
  210983. }
  210984. }
  210985. for (i = MidiOutHandle::activeHandles.size(); --i >= 0;)
  210986. {
  210987. MidiOutHandle* const han = MidiOutHandle::activeHandles.getUnchecked(i);
  210988. if (han != 0 && han->deviceId == deviceId)
  210989. {
  210990. han->refCount++;
  210991. MidiOutput* const out = new MidiOutput();
  210992. out->internal = han;
  210993. return out;
  210994. }
  210995. }
  210996. for (i = 4; --i >= 0;)
  210997. {
  210998. HMIDIOUT h = 0;
  210999. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  211000. if (res == MMSYSERR_NOERROR)
  211001. {
  211002. MidiOutHandle* const han = new MidiOutHandle();
  211003. han->deviceId = deviceId;
  211004. han->refCount = 1;
  211005. han->handle = h;
  211006. MidiOutHandle::activeHandles.add (han);
  211007. MidiOutput* const out = new MidiOutput();
  211008. out->internal = han;
  211009. return out;
  211010. }
  211011. else if (res == MMSYSERR_ALLOCATED)
  211012. {
  211013. Sleep (100);
  211014. }
  211015. else
  211016. {
  211017. break;
  211018. }
  211019. }
  211020. return 0;
  211021. }
  211022. MidiOutput::~MidiOutput()
  211023. {
  211024. MidiOutHandle* const h = static_cast <MidiOutHandle*> (internal);
  211025. if (MidiOutHandle::activeHandles.contains (h) && --(h->refCount) == 0)
  211026. {
  211027. midiOutClose (h->handle);
  211028. MidiOutHandle::activeHandles.removeValue (h);
  211029. delete h;
  211030. }
  211031. }
  211032. void MidiOutput::reset()
  211033. {
  211034. const MidiOutHandle* const h = static_cast <const MidiOutHandle*> (internal);
  211035. midiOutReset (h->handle);
  211036. }
  211037. bool MidiOutput::getVolume (float& leftVol,
  211038. float& rightVol)
  211039. {
  211040. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  211041. DWORD n;
  211042. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  211043. {
  211044. const unsigned short* const nn = (const unsigned short*) &n;
  211045. rightVol = nn[0] / (float) 0xffff;
  211046. leftVol = nn[1] / (float) 0xffff;
  211047. return true;
  211048. }
  211049. else
  211050. {
  211051. rightVol = leftVol = 1.0f;
  211052. return false;
  211053. }
  211054. }
  211055. void MidiOutput::setVolume (float leftVol,
  211056. float rightVol)
  211057. {
  211058. const MidiOutHandle* const handle = static_cast <MidiOutHandle*> (internal);
  211059. DWORD n;
  211060. unsigned short* const nn = (unsigned short*) &n;
  211061. nn[0] = (unsigned short) jlimit (0, 0xffff, (int) (rightVol * 0xffff));
  211062. nn[1] = (unsigned short) jlimit (0, 0xffff, (int) (leftVol * 0xffff));
  211063. midiOutSetVolume (handle->handle, n);
  211064. }
  211065. void MidiOutput::sendMessageNow (const MidiMessage& message)
  211066. {
  211067. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  211068. if (message.getRawDataSize() > 3
  211069. || message.isSysEx())
  211070. {
  211071. MIDIHDR h;
  211072. zerostruct (h);
  211073. h.lpData = (char*) message.getRawData();
  211074. h.dwBufferLength = message.getRawDataSize();
  211075. h.dwBytesRecorded = message.getRawDataSize();
  211076. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  211077. {
  211078. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  211079. if (res == MMSYSERR_NOERROR)
  211080. {
  211081. while ((h.dwFlags & MHDR_DONE) == 0)
  211082. Sleep (1);
  211083. int count = 500; // 1 sec timeout
  211084. while (--count >= 0)
  211085. {
  211086. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  211087. if (res == MIDIERR_STILLPLAYING)
  211088. Sleep (2);
  211089. else
  211090. break;
  211091. }
  211092. }
  211093. }
  211094. }
  211095. else
  211096. {
  211097. midiOutShortMsg (handle->handle,
  211098. *(unsigned int*) message.getRawData());
  211099. }
  211100. }
  211101. #endif
  211102. /*** End of inlined file: juce_win32_Midi.cpp ***/
  211103. /*** Start of inlined file: juce_win32_ASIO.cpp ***/
  211104. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  211105. // compiled on its own).
  211106. #if JUCE_INCLUDED_FILE && JUCE_ASIO
  211107. #undef WINDOWS
  211108. // #define ASIO_DEBUGGING
  211109. #ifdef ASIO_DEBUGGING
  211110. #define log(a) { Logger::writeToLog (a); DBG (a) }
  211111. #else
  211112. #define log(a) {}
  211113. #endif
  211114. #ifdef ASIO_DEBUGGING
  211115. static void logError (const String& context, long error)
  211116. {
  211117. String err ("unknown error");
  211118. if (error == ASE_NotPresent)
  211119. err = "Not Present";
  211120. else if (error == ASE_HWMalfunction)
  211121. err = "Hardware Malfunction";
  211122. else if (error == ASE_InvalidParameter)
  211123. err = "Invalid Parameter";
  211124. else if (error == ASE_InvalidMode)
  211125. err = "Invalid Mode";
  211126. else if (error == ASE_SPNotAdvancing)
  211127. err = "Sample position not advancing";
  211128. else if (error == ASE_NoClock)
  211129. err = "No Clock";
  211130. else if (error == ASE_NoMemory)
  211131. err = "Out of memory";
  211132. log ("!!error: " + context + " - " + err);
  211133. }
  211134. #else
  211135. #define logError(a, b) {}
  211136. #endif
  211137. class ASIOAudioIODevice;
  211138. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  211139. static const int maxASIOChannels = 160;
  211140. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  211141. private Timer
  211142. {
  211143. public:
  211144. Component ourWindow;
  211145. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber,
  211146. const String& optionalDllForDirectLoading_)
  211147. : AudioIODevice (name_, "ASIO"),
  211148. asioObject (0),
  211149. classId (classId_),
  211150. optionalDllForDirectLoading (optionalDllForDirectLoading_),
  211151. currentBitDepth (16),
  211152. currentSampleRate (0),
  211153. isOpen_ (false),
  211154. isStarted (false),
  211155. postOutput (true),
  211156. insideControlPanelModalLoop (false),
  211157. shouldUsePreferredSize (false)
  211158. {
  211159. name = name_;
  211160. ourWindow.addToDesktop (0);
  211161. windowHandle = ourWindow.getWindowHandle();
  211162. jassert (currentASIODev [slotNumber] == 0);
  211163. currentASIODev [slotNumber] = this;
  211164. openDevice();
  211165. }
  211166. ~ASIOAudioIODevice()
  211167. {
  211168. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  211169. if (currentASIODev[i] == this)
  211170. currentASIODev[i] = 0;
  211171. close();
  211172. log ("ASIO - exiting");
  211173. removeCurrentDriver();
  211174. }
  211175. void updateSampleRates()
  211176. {
  211177. // find a list of sample rates..
  211178. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  211179. sampleRates.clear();
  211180. if (asioObject != 0)
  211181. {
  211182. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  211183. {
  211184. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  211185. if (err == 0)
  211186. {
  211187. sampleRates.add ((int) possibleSampleRates[index]);
  211188. log ("rate: " + String ((int) possibleSampleRates[index]));
  211189. }
  211190. else if (err != ASE_NoClock)
  211191. {
  211192. logError ("CanSampleRate", err);
  211193. }
  211194. }
  211195. if (sampleRates.size() == 0)
  211196. {
  211197. double cr = 0;
  211198. const long err = asioObject->getSampleRate (&cr);
  211199. log ("No sample rates supported - current rate: " + String ((int) cr));
  211200. if (err == 0)
  211201. sampleRates.add ((int) cr);
  211202. }
  211203. }
  211204. }
  211205. const StringArray getOutputChannelNames()
  211206. {
  211207. return outputChannelNames;
  211208. }
  211209. const StringArray getInputChannelNames()
  211210. {
  211211. return inputChannelNames;
  211212. }
  211213. int getNumSampleRates()
  211214. {
  211215. return sampleRates.size();
  211216. }
  211217. double getSampleRate (int index)
  211218. {
  211219. return sampleRates [index];
  211220. }
  211221. int getNumBufferSizesAvailable()
  211222. {
  211223. return bufferSizes.size();
  211224. }
  211225. int getBufferSizeSamples (int index)
  211226. {
  211227. return bufferSizes [index];
  211228. }
  211229. int getDefaultBufferSize()
  211230. {
  211231. return preferredSize;
  211232. }
  211233. const String open (const BigInteger& inputChannels,
  211234. const BigInteger& outputChannels,
  211235. double sr,
  211236. int bufferSizeSamples)
  211237. {
  211238. close();
  211239. currentCallback = 0;
  211240. if (bufferSizeSamples <= 0)
  211241. shouldUsePreferredSize = true;
  211242. if (asioObject == 0 || ! isASIOOpen)
  211243. {
  211244. log ("Warning: device not open");
  211245. const String err (openDevice());
  211246. if (asioObject == 0 || ! isASIOOpen)
  211247. return err;
  211248. }
  211249. isStarted = false;
  211250. bufferIndex = -1;
  211251. long err = 0;
  211252. long newPreferredSize = 0;
  211253. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  211254. minSize = 0;
  211255. maxSize = 0;
  211256. newPreferredSize = 0;
  211257. granularity = 0;
  211258. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  211259. {
  211260. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  211261. shouldUsePreferredSize = true;
  211262. preferredSize = newPreferredSize;
  211263. }
  211264. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  211265. // dynamic changes to the buffer size...
  211266. shouldUsePreferredSize = shouldUsePreferredSize
  211267. || getName().containsIgnoreCase ("Digidesign");
  211268. if (shouldUsePreferredSize)
  211269. {
  211270. log ("Using preferred size for buffer..");
  211271. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  211272. {
  211273. bufferSizeSamples = preferredSize;
  211274. }
  211275. else
  211276. {
  211277. bufferSizeSamples = 1024;
  211278. logError ("GetBufferSize1", err);
  211279. }
  211280. shouldUsePreferredSize = false;
  211281. }
  211282. int sampleRate = roundDoubleToInt (sr);
  211283. currentSampleRate = sampleRate;
  211284. currentBlockSizeSamples = bufferSizeSamples;
  211285. currentChansOut.clear();
  211286. currentChansIn.clear();
  211287. zeromem (inBuffers, sizeof (inBuffers));
  211288. zeromem (outBuffers, sizeof (outBuffers));
  211289. updateSampleRates();
  211290. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  211291. sampleRate = sampleRates[0];
  211292. jassert (sampleRate != 0);
  211293. if (sampleRate == 0)
  211294. sampleRate = 44100;
  211295. long numSources = 32;
  211296. ASIOClockSource clocks[32];
  211297. zeromem (clocks, sizeof (clocks));
  211298. asioObject->getClockSources (clocks, &numSources);
  211299. bool isSourceSet = false;
  211300. // careful not to remove this loop because it does more than just logging!
  211301. int i;
  211302. for (i = 0; i < numSources; ++i)
  211303. {
  211304. String s ("clock: ");
  211305. s += clocks[i].name;
  211306. if (clocks[i].isCurrentSource)
  211307. {
  211308. isSourceSet = true;
  211309. s << " (cur)";
  211310. }
  211311. log (s);
  211312. }
  211313. if (numSources > 1 && ! isSourceSet)
  211314. {
  211315. log ("setting clock source");
  211316. asioObject->setClockSource (clocks[0].index);
  211317. Thread::sleep (20);
  211318. }
  211319. else
  211320. {
  211321. if (numSources == 0)
  211322. {
  211323. log ("ASIO - no clock sources!");
  211324. }
  211325. }
  211326. double cr = 0;
  211327. err = asioObject->getSampleRate (&cr);
  211328. if (err == 0)
  211329. {
  211330. currentSampleRate = cr;
  211331. }
  211332. else
  211333. {
  211334. logError ("GetSampleRate", err);
  211335. currentSampleRate = 0;
  211336. }
  211337. error = String::empty;
  211338. needToReset = false;
  211339. isReSync = false;
  211340. err = 0;
  211341. bool buffersCreated = false;
  211342. if (currentSampleRate != sampleRate)
  211343. {
  211344. log ("ASIO samplerate: " + String (currentSampleRate) + " to " + String (sampleRate));
  211345. err = asioObject->setSampleRate (sampleRate);
  211346. if (err == ASE_NoClock && numSources > 0)
  211347. {
  211348. log ("trying to set a clock source..");
  211349. Thread::sleep (10);
  211350. err = asioObject->setClockSource (clocks[0].index);
  211351. if (err != 0)
  211352. {
  211353. logError ("SetClock", err);
  211354. }
  211355. Thread::sleep (10);
  211356. err = asioObject->setSampleRate (sampleRate);
  211357. }
  211358. }
  211359. if (err == 0)
  211360. {
  211361. currentSampleRate = sampleRate;
  211362. if (needToReset)
  211363. {
  211364. if (isReSync)
  211365. {
  211366. log ("Resync request");
  211367. }
  211368. log ("! Resetting ASIO after sample rate change");
  211369. removeCurrentDriver();
  211370. loadDriver();
  211371. const String error (initDriver());
  211372. if (error.isNotEmpty())
  211373. {
  211374. log ("ASIOInit: " + error);
  211375. }
  211376. needToReset = false;
  211377. isReSync = false;
  211378. }
  211379. numActiveInputChans = 0;
  211380. numActiveOutputChans = 0;
  211381. ASIOBufferInfo* info = bufferInfos;
  211382. int i;
  211383. for (i = 0; i < totalNumInputChans; ++i)
  211384. {
  211385. if (inputChannels[i])
  211386. {
  211387. currentChansIn.setBit (i);
  211388. info->isInput = 1;
  211389. info->channelNum = i;
  211390. info->buffers[0] = info->buffers[1] = 0;
  211391. ++info;
  211392. ++numActiveInputChans;
  211393. }
  211394. }
  211395. for (i = 0; i < totalNumOutputChans; ++i)
  211396. {
  211397. if (outputChannels[i])
  211398. {
  211399. currentChansOut.setBit (i);
  211400. info->isInput = 0;
  211401. info->channelNum = i;
  211402. info->buffers[0] = info->buffers[1] = 0;
  211403. ++info;
  211404. ++numActiveOutputChans;
  211405. }
  211406. }
  211407. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  211408. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  211409. if (currentASIODev[0] == this)
  211410. {
  211411. callbacks.bufferSwitch = &bufferSwitchCallback0;
  211412. callbacks.asioMessage = &asioMessagesCallback0;
  211413. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  211414. }
  211415. else if (currentASIODev[1] == this)
  211416. {
  211417. callbacks.bufferSwitch = &bufferSwitchCallback1;
  211418. callbacks.asioMessage = &asioMessagesCallback1;
  211419. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  211420. }
  211421. else if (currentASIODev[2] == this)
  211422. {
  211423. callbacks.bufferSwitch = &bufferSwitchCallback2;
  211424. callbacks.asioMessage = &asioMessagesCallback2;
  211425. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  211426. }
  211427. else
  211428. {
  211429. jassertfalse;
  211430. }
  211431. log ("disposing buffers");
  211432. err = asioObject->disposeBuffers();
  211433. log ("creating buffers: " + String (totalBuffers) + ", " + String (currentBlockSizeSamples));
  211434. err = asioObject->createBuffers (bufferInfos,
  211435. totalBuffers,
  211436. currentBlockSizeSamples,
  211437. &callbacks);
  211438. if (err != 0)
  211439. {
  211440. currentBlockSizeSamples = preferredSize;
  211441. logError ("create buffers 2", err);
  211442. asioObject->disposeBuffers();
  211443. err = asioObject->createBuffers (bufferInfos,
  211444. totalBuffers,
  211445. currentBlockSizeSamples,
  211446. &callbacks);
  211447. }
  211448. if (err == 0)
  211449. {
  211450. buffersCreated = true;
  211451. tempBuffer.calloc (totalBuffers * currentBlockSizeSamples + 32);
  211452. int n = 0;
  211453. Array <int> types;
  211454. currentBitDepth = 16;
  211455. for (i = 0; i < jmin ((int) totalNumInputChans, maxASIOChannels); ++i)
  211456. {
  211457. if (inputChannels[i])
  211458. {
  211459. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  211460. ASIOChannelInfo channelInfo;
  211461. zerostruct (channelInfo);
  211462. channelInfo.channel = i;
  211463. channelInfo.isInput = 1;
  211464. asioObject->getChannelInfo (&channelInfo);
  211465. types.addIfNotAlreadyThere (channelInfo.type);
  211466. typeToFormatParameters (channelInfo.type,
  211467. inputChannelBitDepths[n],
  211468. inputChannelBytesPerSample[n],
  211469. inputChannelIsFloat[n],
  211470. inputChannelLittleEndian[n]);
  211471. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  211472. ++n;
  211473. }
  211474. }
  211475. jassert (numActiveInputChans == n);
  211476. n = 0;
  211477. for (i = 0; i < jmin ((int) totalNumOutputChans, maxASIOChannels); ++i)
  211478. {
  211479. if (outputChannels[i])
  211480. {
  211481. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  211482. ASIOChannelInfo channelInfo;
  211483. zerostruct (channelInfo);
  211484. channelInfo.channel = i;
  211485. channelInfo.isInput = 0;
  211486. asioObject->getChannelInfo (&channelInfo);
  211487. types.addIfNotAlreadyThere (channelInfo.type);
  211488. typeToFormatParameters (channelInfo.type,
  211489. outputChannelBitDepths[n],
  211490. outputChannelBytesPerSample[n],
  211491. outputChannelIsFloat[n],
  211492. outputChannelLittleEndian[n]);
  211493. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  211494. ++n;
  211495. }
  211496. }
  211497. jassert (numActiveOutputChans == n);
  211498. for (i = types.size(); --i >= 0;)
  211499. {
  211500. log ("channel format: " + String (types[i]));
  211501. }
  211502. jassert (n <= totalBuffers);
  211503. for (i = 0; i < numActiveOutputChans; ++i)
  211504. {
  211505. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  211506. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  211507. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  211508. {
  211509. log ("!! Null buffers");
  211510. }
  211511. else
  211512. {
  211513. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  211514. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  211515. }
  211516. }
  211517. inputLatency = outputLatency = 0;
  211518. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  211519. {
  211520. log ("ASIO - no latencies");
  211521. }
  211522. else
  211523. {
  211524. log ("ASIO latencies: " + String ((int) outputLatency) + ", " + String ((int) inputLatency));
  211525. }
  211526. isOpen_ = true;
  211527. log ("starting ASIO");
  211528. calledback = false;
  211529. err = asioObject->start();
  211530. if (err != 0)
  211531. {
  211532. isOpen_ = false;
  211533. log ("ASIO - stop on failure");
  211534. Thread::sleep (10);
  211535. asioObject->stop();
  211536. error = "Can't start device";
  211537. Thread::sleep (10);
  211538. }
  211539. else
  211540. {
  211541. int count = 300;
  211542. while (--count > 0 && ! calledback)
  211543. Thread::sleep (10);
  211544. isStarted = true;
  211545. if (! calledback)
  211546. {
  211547. error = "Device didn't start correctly";
  211548. log ("ASIO didn't callback - stopping..");
  211549. asioObject->stop();
  211550. }
  211551. }
  211552. }
  211553. else
  211554. {
  211555. error = "Can't create i/o buffers";
  211556. }
  211557. }
  211558. else
  211559. {
  211560. error = "Can't set sample rate: ";
  211561. error << sampleRate;
  211562. }
  211563. if (error.isNotEmpty())
  211564. {
  211565. logError (error, err);
  211566. if (asioObject != 0 && buffersCreated)
  211567. asioObject->disposeBuffers();
  211568. Thread::sleep (20);
  211569. isStarted = false;
  211570. isOpen_ = false;
  211571. const String errorCopy (error);
  211572. close(); // (this resets the error string)
  211573. error = errorCopy;
  211574. }
  211575. needToReset = false;
  211576. isReSync = false;
  211577. return error;
  211578. }
  211579. void close()
  211580. {
  211581. error = String::empty;
  211582. stopTimer();
  211583. stop();
  211584. if (isASIOOpen && isOpen_)
  211585. {
  211586. const ScopedLock sl (callbackLock);
  211587. isOpen_ = false;
  211588. isStarted = false;
  211589. needToReset = false;
  211590. isReSync = false;
  211591. log ("ASIO - stopping");
  211592. if (asioObject != 0)
  211593. {
  211594. Thread::sleep (20);
  211595. asioObject->stop();
  211596. Thread::sleep (10);
  211597. asioObject->disposeBuffers();
  211598. }
  211599. Thread::sleep (10);
  211600. }
  211601. }
  211602. bool isOpen()
  211603. {
  211604. return isOpen_ || insideControlPanelModalLoop;
  211605. }
  211606. int getCurrentBufferSizeSamples()
  211607. {
  211608. return currentBlockSizeSamples;
  211609. }
  211610. double getCurrentSampleRate()
  211611. {
  211612. return currentSampleRate;
  211613. }
  211614. const BigInteger getActiveOutputChannels() const
  211615. {
  211616. return currentChansOut;
  211617. }
  211618. const BigInteger getActiveInputChannels() const
  211619. {
  211620. return currentChansIn;
  211621. }
  211622. int getCurrentBitDepth()
  211623. {
  211624. return currentBitDepth;
  211625. }
  211626. int getOutputLatencyInSamples()
  211627. {
  211628. return outputLatency + currentBlockSizeSamples / 4;
  211629. }
  211630. int getInputLatencyInSamples()
  211631. {
  211632. return inputLatency + currentBlockSizeSamples / 4;
  211633. }
  211634. void start (AudioIODeviceCallback* callback)
  211635. {
  211636. if (callback != 0)
  211637. {
  211638. callback->audioDeviceAboutToStart (this);
  211639. const ScopedLock sl (callbackLock);
  211640. currentCallback = callback;
  211641. }
  211642. }
  211643. void stop()
  211644. {
  211645. AudioIODeviceCallback* const lastCallback = currentCallback;
  211646. {
  211647. const ScopedLock sl (callbackLock);
  211648. currentCallback = 0;
  211649. }
  211650. if (lastCallback != 0)
  211651. lastCallback->audioDeviceStopped();
  211652. }
  211653. bool isPlaying()
  211654. {
  211655. return isASIOOpen && (currentCallback != 0);
  211656. }
  211657. const String getLastError()
  211658. {
  211659. return error;
  211660. }
  211661. bool hasControlPanel() const
  211662. {
  211663. return true;
  211664. }
  211665. bool showControlPanel()
  211666. {
  211667. log ("ASIO - showing control panel");
  211668. Component modalWindow (String::empty);
  211669. modalWindow.setOpaque (true);
  211670. modalWindow.addToDesktop (0);
  211671. modalWindow.enterModalState();
  211672. bool done = false;
  211673. JUCE_TRY
  211674. {
  211675. // are there are devices that need to be closed before showing their control panel?
  211676. // close();
  211677. insideControlPanelModalLoop = true;
  211678. const uint32 started = Time::getMillisecondCounter();
  211679. if (asioObject != 0)
  211680. {
  211681. asioObject->controlPanel();
  211682. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  211683. log ("spent: " + String (spent));
  211684. if (spent > 300)
  211685. {
  211686. shouldUsePreferredSize = true;
  211687. done = true;
  211688. }
  211689. }
  211690. }
  211691. JUCE_CATCH_ALL
  211692. insideControlPanelModalLoop = false;
  211693. return done;
  211694. }
  211695. void resetRequest() throw()
  211696. {
  211697. needToReset = true;
  211698. }
  211699. void resyncRequest() throw()
  211700. {
  211701. needToReset = true;
  211702. isReSync = true;
  211703. }
  211704. void timerCallback()
  211705. {
  211706. if (! insideControlPanelModalLoop)
  211707. {
  211708. stopTimer();
  211709. // used to cause a reset
  211710. log ("! ASIO restart request!");
  211711. if (isOpen_)
  211712. {
  211713. AudioIODeviceCallback* const oldCallback = currentCallback;
  211714. close();
  211715. open (BigInteger (currentChansIn), BigInteger (currentChansOut),
  211716. currentSampleRate, currentBlockSizeSamples);
  211717. if (oldCallback != 0)
  211718. start (oldCallback);
  211719. }
  211720. }
  211721. else
  211722. {
  211723. startTimer (100);
  211724. }
  211725. }
  211726. juce_UseDebuggingNewOperator
  211727. private:
  211728. IASIO* volatile asioObject;
  211729. ASIOCallbacks callbacks;
  211730. void* windowHandle;
  211731. CLSID classId;
  211732. const String optionalDllForDirectLoading;
  211733. String error;
  211734. long totalNumInputChans, totalNumOutputChans;
  211735. StringArray inputChannelNames, outputChannelNames;
  211736. Array<int> sampleRates, bufferSizes;
  211737. long inputLatency, outputLatency;
  211738. long minSize, maxSize, preferredSize, granularity;
  211739. int volatile currentBlockSizeSamples;
  211740. int volatile currentBitDepth;
  211741. double volatile currentSampleRate;
  211742. BigInteger currentChansOut, currentChansIn;
  211743. AudioIODeviceCallback* volatile currentCallback;
  211744. CriticalSection callbackLock;
  211745. ASIOBufferInfo bufferInfos [maxASIOChannels];
  211746. float* inBuffers [maxASIOChannels];
  211747. float* outBuffers [maxASIOChannels];
  211748. int inputChannelBitDepths [maxASIOChannels];
  211749. int outputChannelBitDepths [maxASIOChannels];
  211750. int inputChannelBytesPerSample [maxASIOChannels];
  211751. int outputChannelBytesPerSample [maxASIOChannels];
  211752. bool inputChannelIsFloat [maxASIOChannels];
  211753. bool outputChannelIsFloat [maxASIOChannels];
  211754. bool inputChannelLittleEndian [maxASIOChannels];
  211755. bool outputChannelLittleEndian [maxASIOChannels];
  211756. WaitableEvent event1;
  211757. HeapBlock <float> tempBuffer;
  211758. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  211759. bool isOpen_, isStarted;
  211760. bool volatile isASIOOpen;
  211761. bool volatile calledback;
  211762. bool volatile littleEndian, postOutput, needToReset, isReSync;
  211763. bool volatile insideControlPanelModalLoop;
  211764. bool volatile shouldUsePreferredSize;
  211765. void removeCurrentDriver()
  211766. {
  211767. if (asioObject != 0)
  211768. {
  211769. asioObject->Release();
  211770. asioObject = 0;
  211771. }
  211772. }
  211773. bool loadDriver()
  211774. {
  211775. removeCurrentDriver();
  211776. JUCE_TRY
  211777. {
  211778. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  211779. classId, (void**) &asioObject) == S_OK)
  211780. {
  211781. return true;
  211782. }
  211783. // If a class isn't registered but we have a path for it, we can fallback to
  211784. // doing a direct load of the COM object (only available via the juce_createASIOAudioIODeviceForGUID function).
  211785. if (optionalDllForDirectLoading.isNotEmpty())
  211786. {
  211787. HMODULE h = LoadLibrary (optionalDllForDirectLoading);
  211788. if (h != 0)
  211789. {
  211790. typedef HRESULT (CALLBACK* DllGetClassObjectFunc) (REFCLSID clsid, REFIID iid, LPVOID* ppv);
  211791. DllGetClassObjectFunc dllGetClassObject = (DllGetClassObjectFunc) GetProcAddress (h, "DllGetClassObject");
  211792. if (dllGetClassObject != 0)
  211793. {
  211794. IClassFactory* classFactory = 0;
  211795. HRESULT hr = dllGetClassObject (classId, IID_IClassFactory, (void**) &classFactory);
  211796. if (classFactory != 0)
  211797. {
  211798. hr = classFactory->CreateInstance (0, classId, (void**) &asioObject);
  211799. classFactory->Release();
  211800. }
  211801. return asioObject != 0;
  211802. }
  211803. }
  211804. }
  211805. }
  211806. JUCE_CATCH_ALL
  211807. asioObject = 0;
  211808. return false;
  211809. }
  211810. const String initDriver()
  211811. {
  211812. if (asioObject != 0)
  211813. {
  211814. char buffer [256];
  211815. zeromem (buffer, sizeof (buffer));
  211816. if (! asioObject->init (windowHandle))
  211817. {
  211818. asioObject->getErrorMessage (buffer);
  211819. return String (buffer, sizeof (buffer) - 1);
  211820. }
  211821. // just in case any daft drivers expect this to be called..
  211822. asioObject->getDriverName (buffer);
  211823. return String::empty;
  211824. }
  211825. return "No Driver";
  211826. }
  211827. const String openDevice()
  211828. {
  211829. // use this in case the driver starts opening dialog boxes..
  211830. Component modalWindow (String::empty);
  211831. modalWindow.setOpaque (true);
  211832. modalWindow.addToDesktop (0);
  211833. modalWindow.enterModalState();
  211834. // open the device and get its info..
  211835. log ("opening ASIO device: " + getName());
  211836. needToReset = false;
  211837. isReSync = false;
  211838. outputChannelNames.clear();
  211839. inputChannelNames.clear();
  211840. bufferSizes.clear();
  211841. sampleRates.clear();
  211842. isASIOOpen = false;
  211843. isOpen_ = false;
  211844. totalNumInputChans = 0;
  211845. totalNumOutputChans = 0;
  211846. numActiveInputChans = 0;
  211847. numActiveOutputChans = 0;
  211848. currentCallback = 0;
  211849. error = String::empty;
  211850. if (getName().isEmpty())
  211851. return error;
  211852. long err = 0;
  211853. if (loadDriver())
  211854. {
  211855. if ((error = initDriver()).isEmpty())
  211856. {
  211857. numActiveInputChans = 0;
  211858. numActiveOutputChans = 0;
  211859. totalNumInputChans = 0;
  211860. totalNumOutputChans = 0;
  211861. if (asioObject != 0
  211862. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  211863. {
  211864. log (String ((int) totalNumInputChans) + " in, " + String ((int) totalNumOutputChans) + " out");
  211865. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  211866. {
  211867. // find a list of buffer sizes..
  211868. log (String ((int) minSize) + " " + String ((int) maxSize) + " " + String ((int) preferredSize) + " " + String ((int) granularity));
  211869. if (granularity >= 0)
  211870. {
  211871. granularity = jmax (1, (int) granularity);
  211872. for (int i = jmax ((int) minSize, (int) granularity); i < jmin (6400, (int) maxSize); i += granularity)
  211873. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  211874. }
  211875. else if (granularity < 0)
  211876. {
  211877. for (int i = 0; i < 18; ++i)
  211878. {
  211879. const int s = (1 << i);
  211880. if (s >= minSize && s <= maxSize)
  211881. bufferSizes.add (s);
  211882. }
  211883. }
  211884. if (! bufferSizes.contains (preferredSize))
  211885. bufferSizes.insert (0, preferredSize);
  211886. double currentRate = 0;
  211887. asioObject->getSampleRate (&currentRate);
  211888. if (currentRate <= 0.0 || currentRate > 192001.0)
  211889. {
  211890. log ("setting sample rate");
  211891. err = asioObject->setSampleRate (44100.0);
  211892. if (err != 0)
  211893. {
  211894. logError ("setting sample rate", err);
  211895. }
  211896. asioObject->getSampleRate (&currentRate);
  211897. }
  211898. currentSampleRate = currentRate;
  211899. postOutput = (asioObject->outputReady() == 0);
  211900. if (postOutput)
  211901. {
  211902. log ("ASIO outputReady = ok");
  211903. }
  211904. updateSampleRates();
  211905. // ..because cubase does it at this point
  211906. inputLatency = outputLatency = 0;
  211907. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  211908. {
  211909. log ("ASIO - no latencies");
  211910. }
  211911. log ("latencies: " + String ((int) inputLatency) + ", " + String ((int) outputLatency));
  211912. // create some dummy buffers now.. because cubase does..
  211913. numActiveInputChans = 0;
  211914. numActiveOutputChans = 0;
  211915. ASIOBufferInfo* info = bufferInfos;
  211916. int i, numChans = 0;
  211917. for (i = 0; i < jmin (2, (int) totalNumInputChans); ++i)
  211918. {
  211919. info->isInput = 1;
  211920. info->channelNum = i;
  211921. info->buffers[0] = info->buffers[1] = 0;
  211922. ++info;
  211923. ++numChans;
  211924. }
  211925. const int outputBufferIndex = numChans;
  211926. for (i = 0; i < jmin (2, (int) totalNumOutputChans); ++i)
  211927. {
  211928. info->isInput = 0;
  211929. info->channelNum = i;
  211930. info->buffers[0] = info->buffers[1] = 0;
  211931. ++info;
  211932. ++numChans;
  211933. }
  211934. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  211935. if (currentASIODev[0] == this)
  211936. {
  211937. callbacks.bufferSwitch = &bufferSwitchCallback0;
  211938. callbacks.asioMessage = &asioMessagesCallback0;
  211939. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  211940. }
  211941. else if (currentASIODev[1] == this)
  211942. {
  211943. callbacks.bufferSwitch = &bufferSwitchCallback1;
  211944. callbacks.asioMessage = &asioMessagesCallback1;
  211945. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  211946. }
  211947. else if (currentASIODev[2] == this)
  211948. {
  211949. callbacks.bufferSwitch = &bufferSwitchCallback2;
  211950. callbacks.asioMessage = &asioMessagesCallback2;
  211951. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  211952. }
  211953. else
  211954. {
  211955. jassertfalse;
  211956. }
  211957. log ("creating buffers (dummy): " + String (numChans) + ", " + String ((int) preferredSize));
  211958. if (preferredSize > 0)
  211959. {
  211960. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  211961. if (err != 0)
  211962. {
  211963. logError ("dummy buffers", err);
  211964. }
  211965. }
  211966. long newInps = 0, newOuts = 0;
  211967. asioObject->getChannels (&newInps, &newOuts);
  211968. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  211969. {
  211970. totalNumInputChans = newInps;
  211971. totalNumOutputChans = newOuts;
  211972. log (String ((int) totalNumInputChans) + " in; " + String ((int) totalNumOutputChans) + " out");
  211973. }
  211974. updateSampleRates();
  211975. ASIOChannelInfo channelInfo;
  211976. channelInfo.type = 0;
  211977. for (i = 0; i < totalNumInputChans; ++i)
  211978. {
  211979. zerostruct (channelInfo);
  211980. channelInfo.channel = i;
  211981. channelInfo.isInput = 1;
  211982. asioObject->getChannelInfo (&channelInfo);
  211983. inputChannelNames.add (String (channelInfo.name));
  211984. }
  211985. for (i = 0; i < totalNumOutputChans; ++i)
  211986. {
  211987. zerostruct (channelInfo);
  211988. channelInfo.channel = i;
  211989. channelInfo.isInput = 0;
  211990. asioObject->getChannelInfo (&channelInfo);
  211991. outputChannelNames.add (String (channelInfo.name));
  211992. typeToFormatParameters (channelInfo.type,
  211993. outputChannelBitDepths[i],
  211994. outputChannelBytesPerSample[i],
  211995. outputChannelIsFloat[i],
  211996. outputChannelLittleEndian[i]);
  211997. if (i < 2)
  211998. {
  211999. // clear the channels that are used with the dummy stuff
  212000. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  212001. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  212002. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  212003. }
  212004. }
  212005. outputChannelNames.trim();
  212006. inputChannelNames.trim();
  212007. outputChannelNames.appendNumbersToDuplicates (false, true);
  212008. inputChannelNames.appendNumbersToDuplicates (false, true);
  212009. // start and stop because cubase does it..
  212010. asioObject->getLatencies (&inputLatency, &outputLatency);
  212011. if ((err = asioObject->start()) != 0)
  212012. {
  212013. // ignore an error here, as it might start later after setting other stuff up
  212014. logError ("ASIO start", err);
  212015. }
  212016. Thread::sleep (100);
  212017. asioObject->stop();
  212018. }
  212019. else
  212020. {
  212021. error = "Can't detect buffer sizes";
  212022. }
  212023. }
  212024. else
  212025. {
  212026. error = "Can't detect asio channels";
  212027. }
  212028. }
  212029. }
  212030. else
  212031. {
  212032. error = "No such device";
  212033. }
  212034. if (error.isNotEmpty())
  212035. {
  212036. logError (error, err);
  212037. if (asioObject != 0)
  212038. asioObject->disposeBuffers();
  212039. removeCurrentDriver();
  212040. isASIOOpen = false;
  212041. }
  212042. else
  212043. {
  212044. isASIOOpen = true;
  212045. log ("ASIO device open");
  212046. }
  212047. isOpen_ = false;
  212048. needToReset = false;
  212049. isReSync = false;
  212050. return error;
  212051. }
  212052. void callback (const long index)
  212053. {
  212054. if (isStarted)
  212055. {
  212056. bufferIndex = index;
  212057. processBuffer();
  212058. }
  212059. else
  212060. {
  212061. if (postOutput && (asioObject != 0))
  212062. asioObject->outputReady();
  212063. }
  212064. calledback = true;
  212065. }
  212066. void processBuffer()
  212067. {
  212068. const ASIOBufferInfo* const infos = bufferInfos;
  212069. const int bi = bufferIndex;
  212070. const ScopedLock sl (callbackLock);
  212071. if (needToReset)
  212072. {
  212073. needToReset = false;
  212074. if (isReSync)
  212075. {
  212076. log ("! ASIO resync");
  212077. isReSync = false;
  212078. }
  212079. else
  212080. {
  212081. startTimer (20);
  212082. }
  212083. }
  212084. if (bi >= 0)
  212085. {
  212086. const int samps = currentBlockSizeSamples;
  212087. if (currentCallback != 0)
  212088. {
  212089. int i;
  212090. for (i = 0; i < numActiveInputChans; ++i)
  212091. {
  212092. float* const dst = inBuffers[i];
  212093. jassert (dst != 0);
  212094. const char* const src = (const char*) (infos[i].buffers[bi]);
  212095. if (inputChannelIsFloat[i])
  212096. {
  212097. memcpy (dst, src, samps * sizeof (float));
  212098. }
  212099. else
  212100. {
  212101. jassert (dst == tempBuffer + (samps * i));
  212102. switch (inputChannelBitDepths[i])
  212103. {
  212104. case 16:
  212105. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  212106. samps, inputChannelLittleEndian[i]);
  212107. break;
  212108. case 24:
  212109. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  212110. samps, inputChannelLittleEndian[i]);
  212111. break;
  212112. case 32:
  212113. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  212114. samps, inputChannelLittleEndian[i]);
  212115. break;
  212116. case 64:
  212117. jassertfalse;
  212118. break;
  212119. }
  212120. }
  212121. }
  212122. currentCallback->audioDeviceIOCallback ((const float**) inBuffers,
  212123. numActiveInputChans,
  212124. outBuffers,
  212125. numActiveOutputChans,
  212126. samps);
  212127. for (i = 0; i < numActiveOutputChans; ++i)
  212128. {
  212129. float* const src = outBuffers[i];
  212130. jassert (src != 0);
  212131. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  212132. if (outputChannelIsFloat[i])
  212133. {
  212134. memcpy (dst, src, samps * sizeof (float));
  212135. }
  212136. else
  212137. {
  212138. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  212139. switch (outputChannelBitDepths[i])
  212140. {
  212141. case 16:
  212142. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  212143. samps, outputChannelLittleEndian[i]);
  212144. break;
  212145. case 24:
  212146. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  212147. samps, outputChannelLittleEndian[i]);
  212148. break;
  212149. case 32:
  212150. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  212151. samps, outputChannelLittleEndian[i]);
  212152. break;
  212153. case 64:
  212154. jassertfalse;
  212155. break;
  212156. }
  212157. }
  212158. }
  212159. }
  212160. else
  212161. {
  212162. for (int i = 0; i < numActiveOutputChans; ++i)
  212163. {
  212164. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  212165. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  212166. }
  212167. }
  212168. }
  212169. if (postOutput)
  212170. asioObject->outputReady();
  212171. }
  212172. static ASIOTime* bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long)
  212173. {
  212174. if (currentASIODev[0] != 0)
  212175. currentASIODev[0]->callback (index);
  212176. return 0;
  212177. }
  212178. static ASIOTime* bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long)
  212179. {
  212180. if (currentASIODev[1] != 0)
  212181. currentASIODev[1]->callback (index);
  212182. return 0;
  212183. }
  212184. static ASIOTime* bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long)
  212185. {
  212186. if (currentASIODev[2] != 0)
  212187. currentASIODev[2]->callback (index);
  212188. return 0;
  212189. }
  212190. static void bufferSwitchCallback0 (long index, long)
  212191. {
  212192. if (currentASIODev[0] != 0)
  212193. currentASIODev[0]->callback (index);
  212194. }
  212195. static void bufferSwitchCallback1 (long index, long)
  212196. {
  212197. if (currentASIODev[1] != 0)
  212198. currentASIODev[1]->callback (index);
  212199. }
  212200. static void bufferSwitchCallback2 (long index, long)
  212201. {
  212202. if (currentASIODev[2] != 0)
  212203. currentASIODev[2]->callback (index);
  212204. }
  212205. static long asioMessagesCallback0 (long selector, long value, void*, double*)
  212206. {
  212207. return asioMessagesCallback (selector, value, 0);
  212208. }
  212209. static long asioMessagesCallback1 (long selector, long value, void*, double*)
  212210. {
  212211. return asioMessagesCallback (selector, value, 1);
  212212. }
  212213. static long asioMessagesCallback2 (long selector, long value, void*, double*)
  212214. {
  212215. return asioMessagesCallback (selector, value, 2);
  212216. }
  212217. static long asioMessagesCallback (long selector, long value, const int deviceIndex)
  212218. {
  212219. switch (selector)
  212220. {
  212221. case kAsioSelectorSupported:
  212222. if (value == kAsioResetRequest
  212223. || value == kAsioEngineVersion
  212224. || value == kAsioResyncRequest
  212225. || value == kAsioLatenciesChanged
  212226. || value == kAsioSupportsInputMonitor)
  212227. return 1;
  212228. break;
  212229. case kAsioBufferSizeChange:
  212230. break;
  212231. case kAsioResetRequest:
  212232. if (currentASIODev[deviceIndex] != 0)
  212233. currentASIODev[deviceIndex]->resetRequest();
  212234. return 1;
  212235. case kAsioResyncRequest:
  212236. if (currentASIODev[deviceIndex] != 0)
  212237. currentASIODev[deviceIndex]->resyncRequest();
  212238. return 1;
  212239. case kAsioLatenciesChanged:
  212240. return 1;
  212241. case kAsioEngineVersion:
  212242. return 2;
  212243. case kAsioSupportsTimeInfo:
  212244. case kAsioSupportsTimeCode:
  212245. return 0;
  212246. }
  212247. return 0;
  212248. }
  212249. static void sampleRateChangedCallback (ASIOSampleRate) throw()
  212250. {
  212251. }
  212252. static void convertInt16ToFloat (const char* src,
  212253. float* dest,
  212254. const int srcStrideBytes,
  212255. int numSamples,
  212256. const bool littleEndian) throw()
  212257. {
  212258. const double g = 1.0 / 32768.0;
  212259. if (littleEndian)
  212260. {
  212261. while (--numSamples >= 0)
  212262. {
  212263. *dest++ = (float) (g * (short) ByteOrder::littleEndianShort (src));
  212264. src += srcStrideBytes;
  212265. }
  212266. }
  212267. else
  212268. {
  212269. while (--numSamples >= 0)
  212270. {
  212271. *dest++ = (float) (g * (short) ByteOrder::bigEndianShort (src));
  212272. src += srcStrideBytes;
  212273. }
  212274. }
  212275. }
  212276. static void convertFloatToInt16 (const float* src,
  212277. char* dest,
  212278. const int dstStrideBytes,
  212279. int numSamples,
  212280. const bool littleEndian) throw()
  212281. {
  212282. const double maxVal = (double) 0x7fff;
  212283. if (littleEndian)
  212284. {
  212285. while (--numSamples >= 0)
  212286. {
  212287. *(uint16*) dest = ByteOrder::swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  212288. dest += dstStrideBytes;
  212289. }
  212290. }
  212291. else
  212292. {
  212293. while (--numSamples >= 0)
  212294. {
  212295. *(uint16*) dest = ByteOrder::swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  212296. dest += dstStrideBytes;
  212297. }
  212298. }
  212299. }
  212300. static void convertInt24ToFloat (const char* src,
  212301. float* dest,
  212302. const int srcStrideBytes,
  212303. int numSamples,
  212304. const bool littleEndian) throw()
  212305. {
  212306. const double g = 1.0 / 0x7fffff;
  212307. if (littleEndian)
  212308. {
  212309. while (--numSamples >= 0)
  212310. {
  212311. *dest++ = (float) (g * ByteOrder::littleEndian24Bit (src));
  212312. src += srcStrideBytes;
  212313. }
  212314. }
  212315. else
  212316. {
  212317. while (--numSamples >= 0)
  212318. {
  212319. *dest++ = (float) (g * ByteOrder::bigEndian24Bit (src));
  212320. src += srcStrideBytes;
  212321. }
  212322. }
  212323. }
  212324. static void convertFloatToInt24 (const float* src,
  212325. char* dest,
  212326. const int dstStrideBytes,
  212327. int numSamples,
  212328. const bool littleEndian) throw()
  212329. {
  212330. const double maxVal = (double) 0x7fffff;
  212331. if (littleEndian)
  212332. {
  212333. while (--numSamples >= 0)
  212334. {
  212335. ByteOrder::littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  212336. dest += dstStrideBytes;
  212337. }
  212338. }
  212339. else
  212340. {
  212341. while (--numSamples >= 0)
  212342. {
  212343. ByteOrder::bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  212344. dest += dstStrideBytes;
  212345. }
  212346. }
  212347. }
  212348. static void convertInt32ToFloat (const char* src,
  212349. float* dest,
  212350. const int srcStrideBytes,
  212351. int numSamples,
  212352. const bool littleEndian) throw()
  212353. {
  212354. const double g = 1.0 / 0x7fffffff;
  212355. if (littleEndian)
  212356. {
  212357. while (--numSamples >= 0)
  212358. {
  212359. *dest++ = (float) (g * (int) ByteOrder::littleEndianInt (src));
  212360. src += srcStrideBytes;
  212361. }
  212362. }
  212363. else
  212364. {
  212365. while (--numSamples >= 0)
  212366. {
  212367. *dest++ = (float) (g * (int) ByteOrder::bigEndianInt (src));
  212368. src += srcStrideBytes;
  212369. }
  212370. }
  212371. }
  212372. static void convertFloatToInt32 (const float* src,
  212373. char* dest,
  212374. const int dstStrideBytes,
  212375. int numSamples,
  212376. const bool littleEndian) throw()
  212377. {
  212378. const double maxVal = (double) 0x7fffffff;
  212379. if (littleEndian)
  212380. {
  212381. while (--numSamples >= 0)
  212382. {
  212383. *(uint32*) dest = ByteOrder::swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  212384. dest += dstStrideBytes;
  212385. }
  212386. }
  212387. else
  212388. {
  212389. while (--numSamples >= 0)
  212390. {
  212391. *(uint32*) dest = ByteOrder::swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  212392. dest += dstStrideBytes;
  212393. }
  212394. }
  212395. }
  212396. static void typeToFormatParameters (const long type,
  212397. int& bitDepth,
  212398. int& byteStride,
  212399. bool& formatIsFloat,
  212400. bool& littleEndian) throw()
  212401. {
  212402. bitDepth = 0;
  212403. littleEndian = false;
  212404. formatIsFloat = false;
  212405. switch (type)
  212406. {
  212407. case ASIOSTInt16MSB:
  212408. case ASIOSTInt16LSB:
  212409. case ASIOSTInt32MSB16:
  212410. case ASIOSTInt32LSB16:
  212411. bitDepth = 16; break;
  212412. case ASIOSTFloat32MSB:
  212413. case ASIOSTFloat32LSB:
  212414. formatIsFloat = true;
  212415. bitDepth = 32; break;
  212416. case ASIOSTInt32MSB:
  212417. case ASIOSTInt32LSB:
  212418. bitDepth = 32; break;
  212419. case ASIOSTInt24MSB:
  212420. case ASIOSTInt24LSB:
  212421. case ASIOSTInt32MSB24:
  212422. case ASIOSTInt32LSB24:
  212423. case ASIOSTInt32MSB18:
  212424. case ASIOSTInt32MSB20:
  212425. case ASIOSTInt32LSB18:
  212426. case ASIOSTInt32LSB20:
  212427. bitDepth = 24; break;
  212428. case ASIOSTFloat64MSB:
  212429. case ASIOSTFloat64LSB:
  212430. default:
  212431. bitDepth = 64;
  212432. break;
  212433. }
  212434. switch (type)
  212435. {
  212436. case ASIOSTInt16MSB:
  212437. case ASIOSTInt32MSB16:
  212438. case ASIOSTFloat32MSB:
  212439. case ASIOSTFloat64MSB:
  212440. case ASIOSTInt32MSB:
  212441. case ASIOSTInt32MSB18:
  212442. case ASIOSTInt32MSB20:
  212443. case ASIOSTInt32MSB24:
  212444. case ASIOSTInt24MSB:
  212445. littleEndian = false; break;
  212446. case ASIOSTInt16LSB:
  212447. case ASIOSTInt32LSB16:
  212448. case ASIOSTFloat32LSB:
  212449. case ASIOSTFloat64LSB:
  212450. case ASIOSTInt32LSB:
  212451. case ASIOSTInt32LSB18:
  212452. case ASIOSTInt32LSB20:
  212453. case ASIOSTInt32LSB24:
  212454. case ASIOSTInt24LSB:
  212455. littleEndian = true; break;
  212456. default:
  212457. break;
  212458. }
  212459. switch (type)
  212460. {
  212461. case ASIOSTInt16LSB:
  212462. case ASIOSTInt16MSB:
  212463. byteStride = 2; break;
  212464. case ASIOSTInt24LSB:
  212465. case ASIOSTInt24MSB:
  212466. byteStride = 3; break;
  212467. case ASIOSTInt32MSB16:
  212468. case ASIOSTInt32LSB16:
  212469. case ASIOSTInt32MSB:
  212470. case ASIOSTInt32MSB18:
  212471. case ASIOSTInt32MSB20:
  212472. case ASIOSTInt32MSB24:
  212473. case ASIOSTInt32LSB:
  212474. case ASIOSTInt32LSB18:
  212475. case ASIOSTInt32LSB20:
  212476. case ASIOSTInt32LSB24:
  212477. case ASIOSTFloat32LSB:
  212478. case ASIOSTFloat32MSB:
  212479. byteStride = 4; break;
  212480. case ASIOSTFloat64MSB:
  212481. case ASIOSTFloat64LSB:
  212482. byteStride = 8; break;
  212483. default:
  212484. break;
  212485. }
  212486. }
  212487. };
  212488. class ASIOAudioIODeviceType : public AudioIODeviceType
  212489. {
  212490. public:
  212491. ASIOAudioIODeviceType()
  212492. : AudioIODeviceType ("ASIO"),
  212493. hasScanned (false)
  212494. {
  212495. CoInitialize (0);
  212496. }
  212497. ~ASIOAudioIODeviceType()
  212498. {
  212499. }
  212500. void scanForDevices()
  212501. {
  212502. hasScanned = true;
  212503. deviceNames.clear();
  212504. classIds.clear();
  212505. HKEY hk = 0;
  212506. int index = 0;
  212507. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  212508. {
  212509. for (;;)
  212510. {
  212511. char name [256];
  212512. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  212513. {
  212514. addDriverInfo (name, hk);
  212515. }
  212516. else
  212517. {
  212518. break;
  212519. }
  212520. }
  212521. RegCloseKey (hk);
  212522. }
  212523. }
  212524. const StringArray getDeviceNames (bool /*wantInputNames*/) const
  212525. {
  212526. jassert (hasScanned); // need to call scanForDevices() before doing this
  212527. return deviceNames;
  212528. }
  212529. int getDefaultDeviceIndex (bool) const
  212530. {
  212531. jassert (hasScanned); // need to call scanForDevices() before doing this
  212532. for (int i = deviceNames.size(); --i >= 0;)
  212533. if (deviceNames[i].containsIgnoreCase ("asio4all"))
  212534. return i; // asio4all is a safe choice for a default..
  212535. #if JUCE_DEBUG
  212536. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase ("digidesign"))
  212537. return 1; // (the digi m-box driver crashes the app when you run
  212538. // it in the debugger, which can be a bit annoying)
  212539. #endif
  212540. return 0;
  212541. }
  212542. static int findFreeSlot()
  212543. {
  212544. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  212545. if (currentASIODev[i] == 0)
  212546. return i;
  212547. jassertfalse; // unfortunately you can only have a finite number
  212548. // of ASIO devices open at the same time..
  212549. return -1;
  212550. }
  212551. int getIndexOfDevice (AudioIODevice* d, bool /*asInput*/) const
  212552. {
  212553. jassert (hasScanned); // need to call scanForDevices() before doing this
  212554. return d == 0 ? -1 : deviceNames.indexOf (d->getName());
  212555. }
  212556. bool hasSeparateInputsAndOutputs() const { return false; }
  212557. AudioIODevice* createDevice (const String& outputDeviceName,
  212558. const String& inputDeviceName)
  212559. {
  212560. // ASIO can't open two different devices for input and output - they must be the same one.
  212561. jassert (inputDeviceName == outputDeviceName || outputDeviceName.isEmpty() || inputDeviceName.isEmpty());
  212562. jassert (hasScanned); // need to call scanForDevices() before doing this
  212563. const int index = deviceNames.indexOf (outputDeviceName.isNotEmpty() ? outputDeviceName
  212564. : inputDeviceName);
  212565. if (index >= 0)
  212566. {
  212567. const int freeSlot = findFreeSlot();
  212568. if (freeSlot >= 0)
  212569. return new ASIOAudioIODevice (outputDeviceName, *(classIds [index]), freeSlot, String::empty);
  212570. }
  212571. return 0;
  212572. }
  212573. juce_UseDebuggingNewOperator
  212574. private:
  212575. StringArray deviceNames;
  212576. OwnedArray <CLSID> classIds;
  212577. bool hasScanned;
  212578. static bool checkClassIsOk (const String& classId)
  212579. {
  212580. HKEY hk = 0;
  212581. bool ok = false;
  212582. if (RegOpenKey (HKEY_CLASSES_ROOT, _T("clsid"), &hk) == ERROR_SUCCESS)
  212583. {
  212584. int index = 0;
  212585. for (;;)
  212586. {
  212587. WCHAR buf [512];
  212588. if (RegEnumKey (hk, index++, buf, 512) == ERROR_SUCCESS)
  212589. {
  212590. if (classId.equalsIgnoreCase (buf))
  212591. {
  212592. HKEY subKey, pathKey;
  212593. if (RegOpenKeyEx (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  212594. {
  212595. if (RegOpenKeyEx (subKey, _T("InprocServer32"), 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  212596. {
  212597. WCHAR pathName [1024];
  212598. DWORD dtype = REG_SZ;
  212599. DWORD dsize = sizeof (pathName);
  212600. if (RegQueryValueEx (pathKey, 0, 0, &dtype, (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  212601. ok = File (pathName).exists();
  212602. RegCloseKey (pathKey);
  212603. }
  212604. RegCloseKey (subKey);
  212605. }
  212606. break;
  212607. }
  212608. }
  212609. else
  212610. {
  212611. break;
  212612. }
  212613. }
  212614. RegCloseKey (hk);
  212615. }
  212616. return ok;
  212617. }
  212618. void addDriverInfo (const String& keyName, HKEY hk)
  212619. {
  212620. HKEY subKey;
  212621. if (RegOpenKeyEx (hk, keyName, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  212622. {
  212623. WCHAR buf [256];
  212624. zerostruct (buf);
  212625. DWORD dtype = REG_SZ;
  212626. DWORD dsize = sizeof (buf);
  212627. if (RegQueryValueEx (subKey, _T("clsid"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  212628. {
  212629. if (dsize > 0 && checkClassIsOk (buf))
  212630. {
  212631. CLSID classId;
  212632. if (CLSIDFromString ((LPOLESTR) buf, &classId) == S_OK)
  212633. {
  212634. dtype = REG_SZ;
  212635. dsize = sizeof (buf);
  212636. String deviceName;
  212637. if (RegQueryValueEx (subKey, _T("description"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  212638. deviceName = buf;
  212639. else
  212640. deviceName = keyName;
  212641. log ("found " + deviceName);
  212642. deviceNames.add (deviceName);
  212643. classIds.add (new CLSID (classId));
  212644. }
  212645. }
  212646. RegCloseKey (subKey);
  212647. }
  212648. }
  212649. }
  212650. ASIOAudioIODeviceType (const ASIOAudioIODeviceType&);
  212651. ASIOAudioIODeviceType& operator= (const ASIOAudioIODeviceType&);
  212652. };
  212653. AudioIODeviceType* juce_createAudioIODeviceType_ASIO()
  212654. {
  212655. return new ASIOAudioIODeviceType();
  212656. }
  212657. AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name,
  212658. void* guid,
  212659. const String& optionalDllForDirectLoading)
  212660. {
  212661. const int freeSlot = ASIOAudioIODeviceType::findFreeSlot();
  212662. if (freeSlot < 0)
  212663. return 0;
  212664. return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot, optionalDllForDirectLoading);
  212665. }
  212666. #undef log
  212667. #endif
  212668. /*** End of inlined file: juce_win32_ASIO.cpp ***/
  212669. /*** Start of inlined file: juce_win32_DirectSound.cpp ***/
  212670. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212671. // compiled on its own).
  212672. #if JUCE_INCLUDED_FILE && JUCE_DIRECTSOUND
  212673. END_JUCE_NAMESPACE
  212674. extern "C"
  212675. {
  212676. // Declare just the minimum number of interfaces for the DSound objects that we need..
  212677. typedef struct typeDSBUFFERDESC
  212678. {
  212679. DWORD dwSize;
  212680. DWORD dwFlags;
  212681. DWORD dwBufferBytes;
  212682. DWORD dwReserved;
  212683. LPWAVEFORMATEX lpwfxFormat;
  212684. GUID guid3DAlgorithm;
  212685. } DSBUFFERDESC;
  212686. struct IDirectSoundBuffer;
  212687. #undef INTERFACE
  212688. #define INTERFACE IDirectSound
  212689. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  212690. {
  212691. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  212692. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  212693. STDMETHOD_(ULONG,Release) (THIS) PURE;
  212694. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  212695. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  212696. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  212697. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  212698. STDMETHOD(Compact) (THIS) PURE;
  212699. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  212700. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  212701. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  212702. };
  212703. #undef INTERFACE
  212704. #define INTERFACE IDirectSoundBuffer
  212705. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  212706. {
  212707. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  212708. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  212709. STDMETHOD_(ULONG,Release) (THIS) PURE;
  212710. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  212711. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  212712. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  212713. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  212714. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  212715. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  212716. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  212717. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  212718. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  212719. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  212720. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  212721. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  212722. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  212723. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  212724. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  212725. STDMETHOD(Stop) (THIS) PURE;
  212726. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  212727. STDMETHOD(Restore) (THIS) PURE;
  212728. };
  212729. typedef struct typeDSCBUFFERDESC
  212730. {
  212731. DWORD dwSize;
  212732. DWORD dwFlags;
  212733. DWORD dwBufferBytes;
  212734. DWORD dwReserved;
  212735. LPWAVEFORMATEX lpwfxFormat;
  212736. } DSCBUFFERDESC;
  212737. struct IDirectSoundCaptureBuffer;
  212738. #undef INTERFACE
  212739. #define INTERFACE IDirectSoundCapture
  212740. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  212741. {
  212742. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  212743. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  212744. STDMETHOD_(ULONG,Release) (THIS) PURE;
  212745. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  212746. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  212747. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  212748. };
  212749. #undef INTERFACE
  212750. #define INTERFACE IDirectSoundCaptureBuffer
  212751. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  212752. {
  212753. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  212754. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  212755. STDMETHOD_(ULONG,Release) (THIS) PURE;
  212756. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  212757. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  212758. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  212759. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  212760. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  212761. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  212762. STDMETHOD(Start) (THIS_ DWORD) PURE;
  212763. STDMETHOD(Stop) (THIS) PURE;
  212764. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  212765. };
  212766. };
  212767. BEGIN_JUCE_NAMESPACE
  212768. static const String getDSErrorMessage (HRESULT hr)
  212769. {
  212770. const char* result = 0;
  212771. switch (hr)
  212772. {
  212773. case MAKE_HRESULT(1, 0x878, 10): result = "Device already allocated"; break;
  212774. case MAKE_HRESULT(1, 0x878, 30): result = "Control unavailable"; break;
  212775. case E_INVALIDARG: result = "Invalid parameter"; break;
  212776. case MAKE_HRESULT(1, 0x878, 50): result = "Invalid call"; break;
  212777. case E_FAIL: result = "Generic error"; break;
  212778. case MAKE_HRESULT(1, 0x878, 70): result = "Priority level error"; break;
  212779. case E_OUTOFMEMORY: result = "Out of memory"; break;
  212780. case MAKE_HRESULT(1, 0x878, 100): result = "Bad format"; break;
  212781. case E_NOTIMPL: result = "Unsupported function"; break;
  212782. case MAKE_HRESULT(1, 0x878, 120): result = "No driver"; break;
  212783. case MAKE_HRESULT(1, 0x878, 130): result = "Already initialised"; break;
  212784. case CLASS_E_NOAGGREGATION: result = "No aggregation"; break;
  212785. case MAKE_HRESULT(1, 0x878, 150): result = "Buffer lost"; break;
  212786. case MAKE_HRESULT(1, 0x878, 160): result = "Another app has priority"; break;
  212787. case MAKE_HRESULT(1, 0x878, 170): result = "Uninitialised"; break;
  212788. case E_NOINTERFACE: result = "No interface"; break;
  212789. case S_OK: result = "No error"; break;
  212790. default: return "Unknown error: " + String ((int) hr);
  212791. }
  212792. return result;
  212793. }
  212794. #define DS_DEBUGGING 1
  212795. #ifdef DS_DEBUGGING
  212796. #define CATCH JUCE_CATCH_EXCEPTION
  212797. #undef log
  212798. #define log(a) Logger::writeToLog(a);
  212799. #undef logError
  212800. #define logError(a) logDSError(a, __LINE__);
  212801. static void logDSError (HRESULT hr, int lineNum)
  212802. {
  212803. if (hr != S_OK)
  212804. {
  212805. String error ("DS error at line ");
  212806. error << lineNum << " - " << getDSErrorMessage (hr);
  212807. log (error);
  212808. }
  212809. }
  212810. #else
  212811. #define CATCH JUCE_CATCH_ALL
  212812. #define log(a)
  212813. #define logError(a)
  212814. #endif
  212815. #define DSOUND_FUNCTION(functionName, params) \
  212816. typedef HRESULT (WINAPI *type##functionName) params; \
  212817. static type##functionName ds##functionName = 0;
  212818. #define DSOUND_FUNCTION_LOAD(functionName) \
  212819. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  212820. jassert (ds##functionName != 0);
  212821. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  212822. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  212823. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  212824. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  212825. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  212826. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  212827. static void initialiseDSoundFunctions()
  212828. {
  212829. if (dsDirectSoundCreate == 0)
  212830. {
  212831. HMODULE h = LoadLibraryA ("dsound.dll");
  212832. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  212833. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  212834. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  212835. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  212836. }
  212837. }
  212838. class DSoundInternalOutChannel
  212839. {
  212840. String name;
  212841. LPGUID guid;
  212842. int sampleRate, bufferSizeSamples;
  212843. float* leftBuffer;
  212844. float* rightBuffer;
  212845. IDirectSound* pDirectSound;
  212846. IDirectSoundBuffer* pOutputBuffer;
  212847. DWORD writeOffset;
  212848. int totalBytesPerBuffer;
  212849. int bytesPerBuffer;
  212850. unsigned int lastPlayCursor;
  212851. public:
  212852. int bitDepth;
  212853. bool doneFlag;
  212854. DSoundInternalOutChannel (const String& name_,
  212855. LPGUID guid_,
  212856. int rate,
  212857. int bufferSize,
  212858. float* left,
  212859. float* right)
  212860. : name (name_),
  212861. guid (guid_),
  212862. sampleRate (rate),
  212863. bufferSizeSamples (bufferSize),
  212864. leftBuffer (left),
  212865. rightBuffer (right),
  212866. pDirectSound (0),
  212867. pOutputBuffer (0),
  212868. bitDepth (16)
  212869. {
  212870. }
  212871. ~DSoundInternalOutChannel()
  212872. {
  212873. close();
  212874. }
  212875. void close()
  212876. {
  212877. HRESULT hr;
  212878. if (pOutputBuffer != 0)
  212879. {
  212880. JUCE_TRY
  212881. {
  212882. log ("closing dsound out: " + name);
  212883. hr = pOutputBuffer->Stop();
  212884. logError (hr);
  212885. }
  212886. CATCH
  212887. JUCE_TRY
  212888. {
  212889. hr = pOutputBuffer->Release();
  212890. logError (hr);
  212891. }
  212892. CATCH
  212893. pOutputBuffer = 0;
  212894. }
  212895. if (pDirectSound != 0)
  212896. {
  212897. JUCE_TRY
  212898. {
  212899. hr = pDirectSound->Release();
  212900. logError (hr);
  212901. }
  212902. CATCH
  212903. pDirectSound = 0;
  212904. }
  212905. }
  212906. const String open()
  212907. {
  212908. log ("opening dsound out device: " + name + " rate=" + String (sampleRate)
  212909. + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  212910. pDirectSound = 0;
  212911. pOutputBuffer = 0;
  212912. writeOffset = 0;
  212913. String error;
  212914. HRESULT hr = E_NOINTERFACE;
  212915. if (dsDirectSoundCreate != 0)
  212916. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  212917. if (hr == S_OK)
  212918. {
  212919. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  212920. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  212921. const int numChannels = 2;
  212922. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  212923. logError (hr);
  212924. if (hr == S_OK)
  212925. {
  212926. IDirectSoundBuffer* pPrimaryBuffer;
  212927. DSBUFFERDESC primaryDesc;
  212928. zerostruct (primaryDesc);
  212929. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  212930. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  212931. primaryDesc.dwBufferBytes = 0;
  212932. primaryDesc.lpwfxFormat = 0;
  212933. log ("opening dsound out step 2");
  212934. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  212935. logError (hr);
  212936. if (hr == S_OK)
  212937. {
  212938. WAVEFORMATEX wfFormat;
  212939. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  212940. wfFormat.nChannels = (unsigned short) numChannels;
  212941. wfFormat.nSamplesPerSec = sampleRate;
  212942. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  212943. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  212944. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  212945. wfFormat.cbSize = 0;
  212946. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  212947. logError (hr);
  212948. if (hr == S_OK)
  212949. {
  212950. DSBUFFERDESC secondaryDesc;
  212951. zerostruct (secondaryDesc);
  212952. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  212953. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  212954. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  212955. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  212956. secondaryDesc.lpwfxFormat = &wfFormat;
  212957. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  212958. logError (hr);
  212959. if (hr == S_OK)
  212960. {
  212961. log ("opening dsound out step 3");
  212962. DWORD dwDataLen;
  212963. unsigned char* pDSBuffData;
  212964. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  212965. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  212966. logError (hr);
  212967. if (hr == S_OK)
  212968. {
  212969. zeromem (pDSBuffData, dwDataLen);
  212970. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  212971. if (hr == S_OK)
  212972. {
  212973. hr = pOutputBuffer->SetCurrentPosition (0);
  212974. if (hr == S_OK)
  212975. {
  212976. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  212977. if (hr == S_OK)
  212978. return String::empty;
  212979. }
  212980. }
  212981. }
  212982. }
  212983. }
  212984. }
  212985. }
  212986. }
  212987. error = getDSErrorMessage (hr);
  212988. close();
  212989. return error;
  212990. }
  212991. void synchronisePosition()
  212992. {
  212993. if (pOutputBuffer != 0)
  212994. {
  212995. DWORD playCursor;
  212996. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  212997. }
  212998. }
  212999. bool service()
  213000. {
  213001. if (pOutputBuffer == 0)
  213002. return true;
  213003. DWORD playCursor, writeCursor;
  213004. for (;;)
  213005. {
  213006. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  213007. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  213008. {
  213009. pOutputBuffer->Restore();
  213010. continue;
  213011. }
  213012. if (hr == S_OK)
  213013. break;
  213014. logError (hr);
  213015. jassertfalse;
  213016. return true;
  213017. }
  213018. int playWriteGap = writeCursor - playCursor;
  213019. if (playWriteGap < 0)
  213020. playWriteGap += totalBytesPerBuffer;
  213021. int bytesEmpty = playCursor - writeOffset;
  213022. if (bytesEmpty < 0)
  213023. bytesEmpty += totalBytesPerBuffer;
  213024. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  213025. {
  213026. writeOffset = writeCursor;
  213027. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  213028. }
  213029. if (bytesEmpty >= bytesPerBuffer)
  213030. {
  213031. LPBYTE lpbuf1 = 0;
  213032. LPBYTE lpbuf2 = 0;
  213033. DWORD dwSize1 = 0;
  213034. DWORD dwSize2 = 0;
  213035. HRESULT hr = pOutputBuffer->Lock (writeOffset,
  213036. bytesPerBuffer,
  213037. (void**) &lpbuf1, &dwSize1,
  213038. (void**) &lpbuf2, &dwSize2, 0);
  213039. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  213040. {
  213041. pOutputBuffer->Restore();
  213042. hr = pOutputBuffer->Lock (writeOffset,
  213043. bytesPerBuffer,
  213044. (void**) &lpbuf1, &dwSize1,
  213045. (void**) &lpbuf2, &dwSize2, 0);
  213046. }
  213047. if (hr == S_OK)
  213048. {
  213049. if (bitDepth == 16)
  213050. {
  213051. const float gainL = 32767.0f;
  213052. const float gainR = 32767.0f;
  213053. int* dest = (int*)lpbuf1;
  213054. const float* left = leftBuffer;
  213055. const float* right = rightBuffer;
  213056. int samples1 = dwSize1 >> 2;
  213057. int samples2 = dwSize2 >> 2;
  213058. if (left == 0)
  213059. {
  213060. while (--samples1 >= 0)
  213061. {
  213062. int r = roundToInt (gainR * *right++);
  213063. if (r < -32768)
  213064. r = -32768;
  213065. else if (r > 32767)
  213066. r = 32767;
  213067. *dest++ = (r << 16);
  213068. }
  213069. dest = (int*)lpbuf2;
  213070. while (--samples2 >= 0)
  213071. {
  213072. int r = roundToInt (gainR * *right++);
  213073. if (r < -32768)
  213074. r = -32768;
  213075. else if (r > 32767)
  213076. r = 32767;
  213077. *dest++ = (r << 16);
  213078. }
  213079. }
  213080. else if (right == 0)
  213081. {
  213082. while (--samples1 >= 0)
  213083. {
  213084. int l = roundToInt (gainL * *left++);
  213085. if (l < -32768)
  213086. l = -32768;
  213087. else if (l > 32767)
  213088. l = 32767;
  213089. l &= 0xffff;
  213090. *dest++ = l;
  213091. }
  213092. dest = (int*)lpbuf2;
  213093. while (--samples2 >= 0)
  213094. {
  213095. int l = roundToInt (gainL * *left++);
  213096. if (l < -32768)
  213097. l = -32768;
  213098. else if (l > 32767)
  213099. l = 32767;
  213100. l &= 0xffff;
  213101. *dest++ = l;
  213102. }
  213103. }
  213104. else
  213105. {
  213106. while (--samples1 >= 0)
  213107. {
  213108. int l = roundToInt (gainL * *left++);
  213109. if (l < -32768)
  213110. l = -32768;
  213111. else if (l > 32767)
  213112. l = 32767;
  213113. l &= 0xffff;
  213114. int r = roundToInt (gainR * *right++);
  213115. if (r < -32768)
  213116. r = -32768;
  213117. else if (r > 32767)
  213118. r = 32767;
  213119. *dest++ = (r << 16) | l;
  213120. }
  213121. dest = (int*)lpbuf2;
  213122. while (--samples2 >= 0)
  213123. {
  213124. int l = roundToInt (gainL * *left++);
  213125. if (l < -32768)
  213126. l = -32768;
  213127. else if (l > 32767)
  213128. l = 32767;
  213129. l &= 0xffff;
  213130. int r = roundToInt (gainR * *right++);
  213131. if (r < -32768)
  213132. r = -32768;
  213133. else if (r > 32767)
  213134. r = 32767;
  213135. *dest++ = (r << 16) | l;
  213136. }
  213137. }
  213138. }
  213139. else
  213140. {
  213141. jassertfalse;
  213142. }
  213143. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  213144. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  213145. }
  213146. else
  213147. {
  213148. jassertfalse;
  213149. logError (hr);
  213150. }
  213151. bytesEmpty -= bytesPerBuffer;
  213152. return true;
  213153. }
  213154. else
  213155. {
  213156. return false;
  213157. }
  213158. }
  213159. };
  213160. struct DSoundInternalInChannel
  213161. {
  213162. String name;
  213163. LPGUID guid;
  213164. int sampleRate, bufferSizeSamples;
  213165. float* leftBuffer;
  213166. float* rightBuffer;
  213167. IDirectSound* pDirectSound;
  213168. IDirectSoundCapture* pDirectSoundCapture;
  213169. IDirectSoundCaptureBuffer* pInputBuffer;
  213170. public:
  213171. unsigned int readOffset;
  213172. int bytesPerBuffer, totalBytesPerBuffer;
  213173. int bitDepth;
  213174. bool doneFlag;
  213175. DSoundInternalInChannel (const String& name_,
  213176. LPGUID guid_,
  213177. int rate,
  213178. int bufferSize,
  213179. float* left,
  213180. float* right)
  213181. : name (name_),
  213182. guid (guid_),
  213183. sampleRate (rate),
  213184. bufferSizeSamples (bufferSize),
  213185. leftBuffer (left),
  213186. rightBuffer (right),
  213187. pDirectSound (0),
  213188. pDirectSoundCapture (0),
  213189. pInputBuffer (0),
  213190. bitDepth (16)
  213191. {
  213192. }
  213193. ~DSoundInternalInChannel()
  213194. {
  213195. close();
  213196. }
  213197. void close()
  213198. {
  213199. HRESULT hr;
  213200. if (pInputBuffer != 0)
  213201. {
  213202. JUCE_TRY
  213203. {
  213204. log ("closing dsound in: " + name);
  213205. hr = pInputBuffer->Stop();
  213206. logError (hr);
  213207. }
  213208. CATCH
  213209. JUCE_TRY
  213210. {
  213211. hr = pInputBuffer->Release();
  213212. logError (hr);
  213213. }
  213214. CATCH
  213215. pInputBuffer = 0;
  213216. }
  213217. if (pDirectSoundCapture != 0)
  213218. {
  213219. JUCE_TRY
  213220. {
  213221. hr = pDirectSoundCapture->Release();
  213222. logError (hr);
  213223. }
  213224. CATCH
  213225. pDirectSoundCapture = 0;
  213226. }
  213227. if (pDirectSound != 0)
  213228. {
  213229. JUCE_TRY
  213230. {
  213231. hr = pDirectSound->Release();
  213232. logError (hr);
  213233. }
  213234. CATCH
  213235. pDirectSound = 0;
  213236. }
  213237. }
  213238. const String open()
  213239. {
  213240. log ("opening dsound in device: " + name
  213241. + " rate=" + String (sampleRate) + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  213242. pDirectSound = 0;
  213243. pDirectSoundCapture = 0;
  213244. pInputBuffer = 0;
  213245. readOffset = 0;
  213246. totalBytesPerBuffer = 0;
  213247. String error;
  213248. HRESULT hr = E_NOINTERFACE;
  213249. if (dsDirectSoundCaptureCreate != 0)
  213250. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  213251. logError (hr);
  213252. if (hr == S_OK)
  213253. {
  213254. const int numChannels = 2;
  213255. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  213256. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  213257. WAVEFORMATEX wfFormat;
  213258. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  213259. wfFormat.nChannels = (unsigned short)numChannels;
  213260. wfFormat.nSamplesPerSec = sampleRate;
  213261. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  213262. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  213263. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  213264. wfFormat.cbSize = 0;
  213265. DSCBUFFERDESC captureDesc;
  213266. zerostruct (captureDesc);
  213267. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  213268. captureDesc.dwFlags = 0;
  213269. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  213270. captureDesc.lpwfxFormat = &wfFormat;
  213271. log ("opening dsound in step 2");
  213272. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  213273. logError (hr);
  213274. if (hr == S_OK)
  213275. {
  213276. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  213277. logError (hr);
  213278. if (hr == S_OK)
  213279. return String::empty;
  213280. }
  213281. }
  213282. error = getDSErrorMessage (hr);
  213283. close();
  213284. return error;
  213285. }
  213286. void synchronisePosition()
  213287. {
  213288. if (pInputBuffer != 0)
  213289. {
  213290. DWORD capturePos;
  213291. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  213292. }
  213293. }
  213294. bool service()
  213295. {
  213296. if (pInputBuffer == 0)
  213297. return true;
  213298. DWORD capturePos, readPos;
  213299. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  213300. logError (hr);
  213301. if (hr != S_OK)
  213302. return true;
  213303. int bytesFilled = readPos - readOffset;
  213304. if (bytesFilled < 0)
  213305. bytesFilled += totalBytesPerBuffer;
  213306. if (bytesFilled >= bytesPerBuffer)
  213307. {
  213308. LPBYTE lpbuf1 = 0;
  213309. LPBYTE lpbuf2 = 0;
  213310. DWORD dwsize1 = 0;
  213311. DWORD dwsize2 = 0;
  213312. HRESULT hr = pInputBuffer->Lock (readOffset,
  213313. bytesPerBuffer,
  213314. (void**) &lpbuf1, &dwsize1,
  213315. (void**) &lpbuf2, &dwsize2, 0);
  213316. if (hr == S_OK)
  213317. {
  213318. if (bitDepth == 16)
  213319. {
  213320. const float g = 1.0f / 32768.0f;
  213321. float* destL = leftBuffer;
  213322. float* destR = rightBuffer;
  213323. int samples1 = dwsize1 >> 2;
  213324. int samples2 = dwsize2 >> 2;
  213325. const short* src = (const short*)lpbuf1;
  213326. if (destL == 0)
  213327. {
  213328. while (--samples1 >= 0)
  213329. {
  213330. ++src;
  213331. *destR++ = *src++ * g;
  213332. }
  213333. src = (const short*)lpbuf2;
  213334. while (--samples2 >= 0)
  213335. {
  213336. ++src;
  213337. *destR++ = *src++ * g;
  213338. }
  213339. }
  213340. else if (destR == 0)
  213341. {
  213342. while (--samples1 >= 0)
  213343. {
  213344. *destL++ = *src++ * g;
  213345. ++src;
  213346. }
  213347. src = (const short*)lpbuf2;
  213348. while (--samples2 >= 0)
  213349. {
  213350. *destL++ = *src++ * g;
  213351. ++src;
  213352. }
  213353. }
  213354. else
  213355. {
  213356. while (--samples1 >= 0)
  213357. {
  213358. *destL++ = *src++ * g;
  213359. *destR++ = *src++ * g;
  213360. }
  213361. src = (const short*)lpbuf2;
  213362. while (--samples2 >= 0)
  213363. {
  213364. *destL++ = *src++ * g;
  213365. *destR++ = *src++ * g;
  213366. }
  213367. }
  213368. }
  213369. else
  213370. {
  213371. jassertfalse;
  213372. }
  213373. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  213374. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  213375. }
  213376. else
  213377. {
  213378. logError (hr);
  213379. jassertfalse;
  213380. }
  213381. bytesFilled -= bytesPerBuffer;
  213382. return true;
  213383. }
  213384. else
  213385. {
  213386. return false;
  213387. }
  213388. }
  213389. };
  213390. class DSoundAudioIODevice : public AudioIODevice,
  213391. public Thread
  213392. {
  213393. public:
  213394. DSoundAudioIODevice (const String& deviceName,
  213395. const int outputDeviceIndex_,
  213396. const int inputDeviceIndex_)
  213397. : AudioIODevice (deviceName, "DirectSound"),
  213398. Thread ("Juce DSound"),
  213399. isOpen_ (false),
  213400. isStarted (false),
  213401. outputDeviceIndex (outputDeviceIndex_),
  213402. inputDeviceIndex (inputDeviceIndex_),
  213403. totalSamplesOut (0),
  213404. sampleRate (0.0),
  213405. inputBuffers (1, 1),
  213406. outputBuffers (1, 1),
  213407. callback (0),
  213408. bufferSizeSamples (0)
  213409. {
  213410. if (outputDeviceIndex_ >= 0)
  213411. {
  213412. outChannels.add (TRANS("Left"));
  213413. outChannels.add (TRANS("Right"));
  213414. }
  213415. if (inputDeviceIndex_ >= 0)
  213416. {
  213417. inChannels.add (TRANS("Left"));
  213418. inChannels.add (TRANS("Right"));
  213419. }
  213420. }
  213421. ~DSoundAudioIODevice()
  213422. {
  213423. close();
  213424. }
  213425. const StringArray getOutputChannelNames()
  213426. {
  213427. return outChannels;
  213428. }
  213429. const StringArray getInputChannelNames()
  213430. {
  213431. return inChannels;
  213432. }
  213433. int getNumSampleRates()
  213434. {
  213435. return 4;
  213436. }
  213437. double getSampleRate (int index)
  213438. {
  213439. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  213440. return samps [jlimit (0, 3, index)];
  213441. }
  213442. int getNumBufferSizesAvailable()
  213443. {
  213444. return 50;
  213445. }
  213446. int getBufferSizeSamples (int index)
  213447. {
  213448. int n = 64;
  213449. for (int i = 0; i < index; ++i)
  213450. n += (n < 512) ? 32
  213451. : ((n < 1024) ? 64
  213452. : ((n < 2048) ? 128 : 256));
  213453. return n;
  213454. }
  213455. int getDefaultBufferSize()
  213456. {
  213457. return 2560;
  213458. }
  213459. const String open (const BigInteger& inputChannels,
  213460. const BigInteger& outputChannels,
  213461. double sampleRate,
  213462. int bufferSizeSamples)
  213463. {
  213464. lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  213465. isOpen_ = lastError.isEmpty();
  213466. return lastError;
  213467. }
  213468. void close()
  213469. {
  213470. stop();
  213471. if (isOpen_)
  213472. {
  213473. closeDevice();
  213474. isOpen_ = false;
  213475. }
  213476. }
  213477. bool isOpen()
  213478. {
  213479. return isOpen_ && isThreadRunning();
  213480. }
  213481. int getCurrentBufferSizeSamples()
  213482. {
  213483. return bufferSizeSamples;
  213484. }
  213485. double getCurrentSampleRate()
  213486. {
  213487. return sampleRate;
  213488. }
  213489. int getCurrentBitDepth()
  213490. {
  213491. int i, bits = 256;
  213492. for (i = inChans.size(); --i >= 0;)
  213493. bits = jmin (bits, inChans[i]->bitDepth);
  213494. for (i = outChans.size(); --i >= 0;)
  213495. bits = jmin (bits, outChans[i]->bitDepth);
  213496. if (bits > 32)
  213497. bits = 16;
  213498. return bits;
  213499. }
  213500. const BigInteger getActiveOutputChannels() const
  213501. {
  213502. return enabledOutputs;
  213503. }
  213504. const BigInteger getActiveInputChannels() const
  213505. {
  213506. return enabledInputs;
  213507. }
  213508. int getOutputLatencyInSamples()
  213509. {
  213510. return (int) (getCurrentBufferSizeSamples() * 1.5);
  213511. }
  213512. int getInputLatencyInSamples()
  213513. {
  213514. return getOutputLatencyInSamples();
  213515. }
  213516. void start (AudioIODeviceCallback* call)
  213517. {
  213518. if (isOpen_ && call != 0 && ! isStarted)
  213519. {
  213520. if (! isThreadRunning())
  213521. {
  213522. // something gone wrong and the thread's stopped..
  213523. isOpen_ = false;
  213524. return;
  213525. }
  213526. call->audioDeviceAboutToStart (this);
  213527. const ScopedLock sl (startStopLock);
  213528. callback = call;
  213529. isStarted = true;
  213530. }
  213531. }
  213532. void stop()
  213533. {
  213534. if (isStarted)
  213535. {
  213536. AudioIODeviceCallback* const callbackLocal = callback;
  213537. {
  213538. const ScopedLock sl (startStopLock);
  213539. isStarted = false;
  213540. }
  213541. if (callbackLocal != 0)
  213542. callbackLocal->audioDeviceStopped();
  213543. }
  213544. }
  213545. bool isPlaying()
  213546. {
  213547. return isStarted && isOpen_ && isThreadRunning();
  213548. }
  213549. const String getLastError()
  213550. {
  213551. return lastError;
  213552. }
  213553. juce_UseDebuggingNewOperator
  213554. StringArray inChannels, outChannels;
  213555. int outputDeviceIndex, inputDeviceIndex;
  213556. private:
  213557. bool isOpen_;
  213558. bool isStarted;
  213559. String lastError;
  213560. OwnedArray <DSoundInternalInChannel> inChans;
  213561. OwnedArray <DSoundInternalOutChannel> outChans;
  213562. WaitableEvent startEvent;
  213563. int bufferSizeSamples;
  213564. int volatile totalSamplesOut;
  213565. int64 volatile lastBlockTime;
  213566. double sampleRate;
  213567. BigInteger enabledInputs, enabledOutputs;
  213568. AudioSampleBuffer inputBuffers, outputBuffers;
  213569. AudioIODeviceCallback* callback;
  213570. CriticalSection startStopLock;
  213571. DSoundAudioIODevice (const DSoundAudioIODevice&);
  213572. DSoundAudioIODevice& operator= (const DSoundAudioIODevice&);
  213573. const String openDevice (const BigInteger& inputChannels,
  213574. const BigInteger& outputChannels,
  213575. double sampleRate_,
  213576. int bufferSizeSamples_);
  213577. void closeDevice()
  213578. {
  213579. isStarted = false;
  213580. stopThread (5000);
  213581. inChans.clear();
  213582. outChans.clear();
  213583. inputBuffers.setSize (1, 1);
  213584. outputBuffers.setSize (1, 1);
  213585. }
  213586. void resync()
  213587. {
  213588. if (! threadShouldExit())
  213589. {
  213590. sleep (5);
  213591. int i;
  213592. for (i = 0; i < outChans.size(); ++i)
  213593. outChans.getUnchecked(i)->synchronisePosition();
  213594. for (i = 0; i < inChans.size(); ++i)
  213595. inChans.getUnchecked(i)->synchronisePosition();
  213596. }
  213597. }
  213598. public:
  213599. void run()
  213600. {
  213601. while (! threadShouldExit())
  213602. {
  213603. if (wait (100))
  213604. break;
  213605. }
  213606. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  213607. const int maxTimeMS = jmax (5, 3 * latencyMs);
  213608. while (! threadShouldExit())
  213609. {
  213610. int numToDo = 0;
  213611. uint32 startTime = Time::getMillisecondCounter();
  213612. int i;
  213613. for (i = inChans.size(); --i >= 0;)
  213614. {
  213615. inChans.getUnchecked(i)->doneFlag = false;
  213616. ++numToDo;
  213617. }
  213618. for (i = outChans.size(); --i >= 0;)
  213619. {
  213620. outChans.getUnchecked(i)->doneFlag = false;
  213621. ++numToDo;
  213622. }
  213623. if (numToDo > 0)
  213624. {
  213625. const int maxCount = 3;
  213626. int count = maxCount;
  213627. for (;;)
  213628. {
  213629. for (i = inChans.size(); --i >= 0;)
  213630. {
  213631. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  213632. if ((! in->doneFlag) && in->service())
  213633. {
  213634. in->doneFlag = true;
  213635. --numToDo;
  213636. }
  213637. }
  213638. for (i = outChans.size(); --i >= 0;)
  213639. {
  213640. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  213641. if ((! out->doneFlag) && out->service())
  213642. {
  213643. out->doneFlag = true;
  213644. --numToDo;
  213645. }
  213646. }
  213647. if (numToDo <= 0)
  213648. break;
  213649. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  213650. {
  213651. resync();
  213652. break;
  213653. }
  213654. if (--count <= 0)
  213655. {
  213656. Sleep (1);
  213657. count = maxCount;
  213658. }
  213659. if (threadShouldExit())
  213660. return;
  213661. }
  213662. }
  213663. else
  213664. {
  213665. sleep (1);
  213666. }
  213667. const ScopedLock sl (startStopLock);
  213668. if (isStarted)
  213669. {
  213670. JUCE_TRY
  213671. {
  213672. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers.getArrayOfChannels()),
  213673. inputBuffers.getNumChannels(),
  213674. outputBuffers.getArrayOfChannels(),
  213675. outputBuffers.getNumChannels(),
  213676. bufferSizeSamples);
  213677. }
  213678. JUCE_CATCH_EXCEPTION
  213679. totalSamplesOut += bufferSizeSamples;
  213680. }
  213681. else
  213682. {
  213683. outputBuffers.clear();
  213684. totalSamplesOut = 0;
  213685. sleep (1);
  213686. }
  213687. }
  213688. }
  213689. };
  213690. class DSoundAudioIODeviceType : public AudioIODeviceType
  213691. {
  213692. public:
  213693. DSoundAudioIODeviceType()
  213694. : AudioIODeviceType ("DirectSound"),
  213695. hasScanned (false)
  213696. {
  213697. initialiseDSoundFunctions();
  213698. }
  213699. ~DSoundAudioIODeviceType()
  213700. {
  213701. }
  213702. void scanForDevices()
  213703. {
  213704. hasScanned = true;
  213705. outputDeviceNames.clear();
  213706. outputGuids.clear();
  213707. inputDeviceNames.clear();
  213708. inputGuids.clear();
  213709. if (dsDirectSoundEnumerateW != 0)
  213710. {
  213711. dsDirectSoundEnumerateW (outputEnumProcW, this);
  213712. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  213713. }
  213714. }
  213715. const StringArray getDeviceNames (bool wantInputNames) const
  213716. {
  213717. jassert (hasScanned); // need to call scanForDevices() before doing this
  213718. return wantInputNames ? inputDeviceNames
  213719. : outputDeviceNames;
  213720. }
  213721. int getDefaultDeviceIndex (bool /*forInput*/) const
  213722. {
  213723. jassert (hasScanned); // need to call scanForDevices() before doing this
  213724. return 0;
  213725. }
  213726. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  213727. {
  213728. jassert (hasScanned); // need to call scanForDevices() before doing this
  213729. DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device);
  213730. if (d == 0)
  213731. return -1;
  213732. return asInput ? d->inputDeviceIndex
  213733. : d->outputDeviceIndex;
  213734. }
  213735. bool hasSeparateInputsAndOutputs() const { return true; }
  213736. AudioIODevice* createDevice (const String& outputDeviceName,
  213737. const String& inputDeviceName)
  213738. {
  213739. jassert (hasScanned); // need to call scanForDevices() before doing this
  213740. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  213741. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  213742. if (outputIndex >= 0 || inputIndex >= 0)
  213743. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  213744. : inputDeviceName,
  213745. outputIndex, inputIndex);
  213746. return 0;
  213747. }
  213748. juce_UseDebuggingNewOperator
  213749. StringArray outputDeviceNames;
  213750. OwnedArray <GUID> outputGuids;
  213751. StringArray inputDeviceNames;
  213752. OwnedArray <GUID> inputGuids;
  213753. private:
  213754. bool hasScanned;
  213755. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  213756. {
  213757. desc = desc.trim();
  213758. if (desc.isNotEmpty())
  213759. {
  213760. const String origDesc (desc);
  213761. int n = 2;
  213762. while (outputDeviceNames.contains (desc))
  213763. desc = origDesc + " (" + String (n++) + ")";
  213764. outputDeviceNames.add (desc);
  213765. if (lpGUID != 0)
  213766. outputGuids.add (new GUID (*lpGUID));
  213767. else
  213768. outputGuids.add (0);
  213769. }
  213770. return TRUE;
  213771. }
  213772. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  213773. {
  213774. return ((DSoundAudioIODeviceType*) object)
  213775. ->outputEnumProc (lpGUID, String (description));
  213776. }
  213777. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  213778. {
  213779. return ((DSoundAudioIODeviceType*) object)
  213780. ->outputEnumProc (lpGUID, String (description));
  213781. }
  213782. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  213783. {
  213784. desc = desc.trim();
  213785. if (desc.isNotEmpty())
  213786. {
  213787. const String origDesc (desc);
  213788. int n = 2;
  213789. while (inputDeviceNames.contains (desc))
  213790. desc = origDesc + " (" + String (n++) + ")";
  213791. inputDeviceNames.add (desc);
  213792. if (lpGUID != 0)
  213793. inputGuids.add (new GUID (*lpGUID));
  213794. else
  213795. inputGuids.add (0);
  213796. }
  213797. return TRUE;
  213798. }
  213799. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  213800. {
  213801. return ((DSoundAudioIODeviceType*) object)
  213802. ->inputEnumProc (lpGUID, String (description));
  213803. }
  213804. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  213805. {
  213806. return ((DSoundAudioIODeviceType*) object)
  213807. ->inputEnumProc (lpGUID, String (description));
  213808. }
  213809. DSoundAudioIODeviceType (const DSoundAudioIODeviceType&);
  213810. DSoundAudioIODeviceType& operator= (const DSoundAudioIODeviceType&);
  213811. };
  213812. const String DSoundAudioIODevice::openDevice (const BigInteger& inputChannels,
  213813. const BigInteger& outputChannels,
  213814. double sampleRate_,
  213815. int bufferSizeSamples_)
  213816. {
  213817. closeDevice();
  213818. totalSamplesOut = 0;
  213819. sampleRate = sampleRate_;
  213820. if (bufferSizeSamples_ <= 0)
  213821. bufferSizeSamples_ = 960; // use as a default size if none is set.
  213822. bufferSizeSamples = bufferSizeSamples_ & ~7;
  213823. DSoundAudioIODeviceType dlh;
  213824. dlh.scanForDevices();
  213825. enabledInputs = inputChannels;
  213826. enabledInputs.setRange (inChannels.size(),
  213827. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  213828. false);
  213829. inputBuffers.setSize (jmax (1, enabledInputs.countNumberOfSetBits()), bufferSizeSamples);
  213830. int i, numIns = 0;
  213831. for (i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  213832. {
  213833. float* left = 0;
  213834. if (enabledInputs[i])
  213835. left = inputBuffers.getSampleData (numIns++);
  213836. float* right = 0;
  213837. if (enabledInputs[i + 1])
  213838. right = inputBuffers.getSampleData (numIns++);
  213839. if (left != 0 || right != 0)
  213840. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  213841. dlh.inputGuids [inputDeviceIndex],
  213842. (int) sampleRate, bufferSizeSamples,
  213843. left, right));
  213844. }
  213845. enabledOutputs = outputChannels;
  213846. enabledOutputs.setRange (outChannels.size(),
  213847. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  213848. false);
  213849. outputBuffers.setSize (jmax (1, enabledOutputs.countNumberOfSetBits()), bufferSizeSamples);
  213850. int numOuts = 0;
  213851. for (i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  213852. {
  213853. float* left = 0;
  213854. if (enabledOutputs[i])
  213855. left = outputBuffers.getSampleData (numOuts++);
  213856. float* right = 0;
  213857. if (enabledOutputs[i + 1])
  213858. right = outputBuffers.getSampleData (numOuts++);
  213859. if (left != 0 || right != 0)
  213860. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  213861. dlh.outputGuids [outputDeviceIndex],
  213862. (int) sampleRate, bufferSizeSamples,
  213863. left, right));
  213864. }
  213865. String error;
  213866. // boost our priority while opening the devices to try to get better sync between them
  213867. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  213868. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  213869. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  213870. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  213871. for (i = 0; i < outChans.size(); ++i)
  213872. {
  213873. error = outChans[i]->open();
  213874. if (error.isNotEmpty())
  213875. {
  213876. error = "Error opening " + dlh.outputDeviceNames[i] + ": \"" + error + "\"";
  213877. break;
  213878. }
  213879. }
  213880. if (error.isEmpty())
  213881. {
  213882. for (i = 0; i < inChans.size(); ++i)
  213883. {
  213884. error = inChans[i]->open();
  213885. if (error.isNotEmpty())
  213886. {
  213887. error = "Error opening " + dlh.inputDeviceNames[i] + ": \"" + error + "\"";
  213888. break;
  213889. }
  213890. }
  213891. }
  213892. if (error.isEmpty())
  213893. {
  213894. totalSamplesOut = 0;
  213895. for (i = 0; i < outChans.size(); ++i)
  213896. outChans.getUnchecked(i)->synchronisePosition();
  213897. for (i = 0; i < inChans.size(); ++i)
  213898. inChans.getUnchecked(i)->synchronisePosition();
  213899. startThread (9);
  213900. sleep (10);
  213901. notify();
  213902. }
  213903. else
  213904. {
  213905. log (error);
  213906. }
  213907. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  213908. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  213909. return error;
  213910. }
  213911. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound()
  213912. {
  213913. return new DSoundAudioIODeviceType();
  213914. }
  213915. #undef log
  213916. #endif
  213917. /*** End of inlined file: juce_win32_DirectSound.cpp ***/
  213918. /*** Start of inlined file: juce_win32_WASAPI.cpp ***/
  213919. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  213920. // compiled on its own).
  213921. #if JUCE_INCLUDED_FILE && JUCE_WASAPI
  213922. #if 1
  213923. const String getAudioErrorDesc (HRESULT hr)
  213924. {
  213925. const char* e = 0;
  213926. switch (hr)
  213927. {
  213928. case E_POINTER: e = "E_POINTER"; break;
  213929. case E_INVALIDARG: e = "E_INVALIDARG"; break;
  213930. case AUDCLNT_E_NOT_INITIALIZED: e = "AUDCLNT_E_NOT_INITIALIZED"; break;
  213931. case AUDCLNT_E_ALREADY_INITIALIZED: e = "AUDCLNT_E_ALREADY_INITIALIZED"; break;
  213932. case AUDCLNT_E_WRONG_ENDPOINT_TYPE: e = "AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break;
  213933. case AUDCLNT_E_DEVICE_INVALIDATED: e = "AUDCLNT_E_DEVICE_INVALIDATED"; break;
  213934. case AUDCLNT_E_NOT_STOPPED: e = "AUDCLNT_E_NOT_STOPPED"; break;
  213935. case AUDCLNT_E_BUFFER_TOO_LARGE: e = "AUDCLNT_E_BUFFER_TOO_LARGE"; break;
  213936. case AUDCLNT_E_OUT_OF_ORDER: e = "AUDCLNT_E_OUT_OF_ORDER"; break;
  213937. case AUDCLNT_E_UNSUPPORTED_FORMAT: e = "AUDCLNT_E_UNSUPPORTED_FORMAT"; break;
  213938. case AUDCLNT_E_INVALID_SIZE: e = "AUDCLNT_E_INVALID_SIZE"; break;
  213939. case AUDCLNT_E_DEVICE_IN_USE: e = "AUDCLNT_E_DEVICE_IN_USE"; break;
  213940. case AUDCLNT_E_BUFFER_OPERATION_PENDING: e = "AUDCLNT_E_BUFFER_OPERATION_PENDING"; break;
  213941. case AUDCLNT_E_THREAD_NOT_REGISTERED: e = "AUDCLNT_E_THREAD_NOT_REGISTERED"; break;
  213942. case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: e = "AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break;
  213943. case AUDCLNT_E_ENDPOINT_CREATE_FAILED: e = "AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break;
  213944. case AUDCLNT_E_SERVICE_NOT_RUNNING: e = "AUDCLNT_E_SERVICE_NOT_RUNNING"; break;
  213945. case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: e = "AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break;
  213946. case AUDCLNT_E_EXCLUSIVE_MODE_ONLY: e = "AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break;
  213947. case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: e = "AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break;
  213948. case AUDCLNT_E_EVENTHANDLE_NOT_SET: e = "AUDCLNT_E_EVENTHANDLE_NOT_SET"; break;
  213949. case AUDCLNT_E_INCORRECT_BUFFER_SIZE: e = "AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break;
  213950. case AUDCLNT_E_BUFFER_SIZE_ERROR: e = "AUDCLNT_E_BUFFER_SIZE_ERROR"; break;
  213951. case AUDCLNT_S_BUFFER_EMPTY: e = "AUDCLNT_S_BUFFER_EMPTY"; break;
  213952. case AUDCLNT_S_THREAD_ALREADY_REGISTERED: e = "AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break;
  213953. default: return String::toHexString ((int) hr);
  213954. }
  213955. return e;
  213956. }
  213957. #define logFailure(hr) { if (FAILED (hr)) { DBG ("WASAPI FAIL! " + getAudioErrorDesc (hr)); jassertfalse; } }
  213958. #define OK(a) wasapi_checkResult(a)
  213959. static bool wasapi_checkResult (HRESULT hr)
  213960. {
  213961. logFailure (hr);
  213962. return SUCCEEDED (hr);
  213963. }
  213964. #else
  213965. #define logFailure(hr) {}
  213966. #define OK(a) SUCCEEDED(a)
  213967. #endif
  213968. static const String wasapi_getDeviceID (IMMDevice* const device)
  213969. {
  213970. String s;
  213971. WCHAR* deviceId = 0;
  213972. if (OK (device->GetId (&deviceId)))
  213973. {
  213974. s = String (deviceId);
  213975. CoTaskMemFree (deviceId);
  213976. }
  213977. return s;
  213978. }
  213979. static EDataFlow wasapi_getDataFlow (IMMDevice* const device)
  213980. {
  213981. EDataFlow flow = eRender;
  213982. ComSmartPtr <IMMEndpoint> endPoint;
  213983. if (OK (device->QueryInterface (__uuidof (IMMEndpoint), (void**) &endPoint)))
  213984. (void) OK (endPoint->GetDataFlow (&flow));
  213985. return flow;
  213986. }
  213987. static int wasapi_refTimeToSamples (const REFERENCE_TIME& t, const double sampleRate) throw()
  213988. {
  213989. return roundDoubleToInt (sampleRate * ((double) t) * 0.0000001);
  213990. }
  213991. static void wasapi_copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* const src) throw()
  213992. {
  213993. memcpy (&dest, src, src->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? sizeof (WAVEFORMATEXTENSIBLE)
  213994. : sizeof (WAVEFORMATEX));
  213995. }
  213996. class WASAPIDeviceBase
  213997. {
  213998. public:
  213999. WASAPIDeviceBase (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  214000. : device (device_),
  214001. sampleRate (0),
  214002. numChannels (0),
  214003. actualNumChannels (0),
  214004. defaultSampleRate (0),
  214005. minBufferSize (0),
  214006. defaultBufferSize (0),
  214007. latencySamples (0),
  214008. useExclusiveMode (useExclusiveMode_)
  214009. {
  214010. clientEvent = CreateEvent (0, false, false, _T("JuceWASAPI"));
  214011. ComSmartPtr <IAudioClient> tempClient (createClient());
  214012. if (tempClient == 0)
  214013. return;
  214014. REFERENCE_TIME defaultPeriod, minPeriod;
  214015. if (! OK (tempClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
  214016. return;
  214017. WAVEFORMATEX* mixFormat = 0;
  214018. if (! OK (tempClient->GetMixFormat (&mixFormat)))
  214019. return;
  214020. WAVEFORMATEXTENSIBLE format;
  214021. wasapi_copyWavFormat (format, mixFormat);
  214022. CoTaskMemFree (mixFormat);
  214023. actualNumChannels = numChannels = format.Format.nChannels;
  214024. defaultSampleRate = format.Format.nSamplesPerSec;
  214025. minBufferSize = wasapi_refTimeToSamples (minPeriod, defaultSampleRate);
  214026. defaultBufferSize = wasapi_refTimeToSamples (defaultPeriod, defaultSampleRate);
  214027. rates.addUsingDefaultSort (defaultSampleRate);
  214028. static const double ratesToTest[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  214029. for (int i = 0; i < numElementsInArray (ratesToTest); ++i)
  214030. {
  214031. if (ratesToTest[i] == defaultSampleRate)
  214032. continue;
  214033. format.Format.nSamplesPerSec = roundDoubleToInt (ratesToTest[i]);
  214034. if (SUCCEEDED (tempClient->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  214035. (WAVEFORMATEX*) &format, 0)))
  214036. if (! rates.contains (ratesToTest[i]))
  214037. rates.addUsingDefaultSort (ratesToTest[i]);
  214038. }
  214039. }
  214040. ~WASAPIDeviceBase()
  214041. {
  214042. device = 0;
  214043. CloseHandle (clientEvent);
  214044. }
  214045. bool isOk() const throw() { return defaultBufferSize > 0 && defaultSampleRate > 0; }
  214046. bool openClient (const double newSampleRate, const BigInteger& newChannels)
  214047. {
  214048. sampleRate = newSampleRate;
  214049. channels = newChannels;
  214050. channels.setRange (actualNumChannels, channels.getHighestBit() + 1 - actualNumChannels, false);
  214051. numChannels = channels.getHighestBit() + 1;
  214052. if (numChannels == 0)
  214053. return true;
  214054. client = createClient();
  214055. if (client != 0
  214056. && (tryInitialisingWithFormat (true, 4) || tryInitialisingWithFormat (false, 4)
  214057. || tryInitialisingWithFormat (false, 3) || tryInitialisingWithFormat (false, 2)))
  214058. {
  214059. channelMaps.clear();
  214060. for (int i = 0; i <= channels.getHighestBit(); ++i)
  214061. if (channels[i])
  214062. channelMaps.add (i);
  214063. REFERENCE_TIME latency;
  214064. if (OK (client->GetStreamLatency (&latency)))
  214065. latencySamples = wasapi_refTimeToSamples (latency, sampleRate);
  214066. (void) OK (client->GetBufferSize (&actualBufferSize));
  214067. return OK (client->SetEventHandle (clientEvent));
  214068. }
  214069. return false;
  214070. }
  214071. void closeClient()
  214072. {
  214073. if (client != 0)
  214074. client->Stop();
  214075. client = 0;
  214076. ResetEvent (clientEvent);
  214077. }
  214078. ComSmartPtr <IMMDevice> device;
  214079. ComSmartPtr <IAudioClient> client;
  214080. double sampleRate, defaultSampleRate;
  214081. int numChannels, actualNumChannels;
  214082. int minBufferSize, defaultBufferSize, latencySamples;
  214083. const bool useExclusiveMode;
  214084. Array <double> rates;
  214085. HANDLE clientEvent;
  214086. BigInteger channels;
  214087. AudioDataConverters::DataFormat dataFormat;
  214088. Array <int> channelMaps;
  214089. UINT32 actualBufferSize;
  214090. int bytesPerSample;
  214091. private:
  214092. const ComSmartPtr <IAudioClient> createClient()
  214093. {
  214094. ComSmartPtr <IAudioClient> client;
  214095. if (device != 0)
  214096. {
  214097. HRESULT hr = device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER, 0, (void**) &client);
  214098. logFailure (hr);
  214099. }
  214100. return client;
  214101. }
  214102. bool tryInitialisingWithFormat (const bool useFloat, const int bytesPerSampleToTry)
  214103. {
  214104. WAVEFORMATEXTENSIBLE format;
  214105. zerostruct (format);
  214106. if (numChannels <= 2 && bytesPerSampleToTry <= 2)
  214107. {
  214108. format.Format.wFormatTag = WAVE_FORMAT_PCM;
  214109. }
  214110. else
  214111. {
  214112. format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  214113. format.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  214114. }
  214115. format.Format.nSamplesPerSec = roundDoubleToInt (sampleRate);
  214116. format.Format.nChannels = (WORD) numChannels;
  214117. format.Format.wBitsPerSample = (WORD) (8 * bytesPerSampleToTry);
  214118. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * numChannels * bytesPerSampleToTry);
  214119. format.Format.nBlockAlign = (WORD) (numChannels * bytesPerSampleToTry);
  214120. format.SubFormat = useFloat ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  214121. format.Samples.wValidBitsPerSample = format.Format.wBitsPerSample;
  214122. switch (numChannels)
  214123. {
  214124. case 1: format.dwChannelMask = SPEAKER_FRONT_CENTER; break;
  214125. case 2: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  214126. case 4: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  214127. case 6: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  214128. 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;
  214129. default: break;
  214130. }
  214131. WAVEFORMATEXTENSIBLE* nearestFormat = 0;
  214132. HRESULT hr = client->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  214133. (WAVEFORMATEX*) &format, useExclusiveMode ? 0 : (WAVEFORMATEX**) &nearestFormat);
  214134. logFailure (hr);
  214135. if (hr == S_FALSE && format.Format.nSamplesPerSec == nearestFormat->Format.nSamplesPerSec)
  214136. {
  214137. wasapi_copyWavFormat (format, (WAVEFORMATEX*) nearestFormat);
  214138. hr = S_OK;
  214139. }
  214140. CoTaskMemFree (nearestFormat);
  214141. REFERENCE_TIME defaultPeriod = 0, minPeriod = 0;
  214142. if (useExclusiveMode)
  214143. OK (client->GetDevicePeriod (&defaultPeriod, &minPeriod));
  214144. GUID session;
  214145. if (hr == S_OK
  214146. && OK (client->Initialize (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  214147. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  214148. defaultPeriod, defaultPeriod, (WAVEFORMATEX*) &format, &session)))
  214149. {
  214150. actualNumChannels = format.Format.nChannels;
  214151. const bool isFloat = format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && format.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  214152. bytesPerSample = format.Format.wBitsPerSample / 8;
  214153. dataFormat = isFloat ? AudioDataConverters::float32LE
  214154. : (bytesPerSample == 4 ? AudioDataConverters::int32LE
  214155. : ((bytesPerSample == 3 ? AudioDataConverters::int24LE
  214156. : AudioDataConverters::int16LE)));
  214157. return true;
  214158. }
  214159. return false;
  214160. }
  214161. WASAPIDeviceBase (const WASAPIDeviceBase&);
  214162. WASAPIDeviceBase& operator= (const WASAPIDeviceBase&);
  214163. };
  214164. class WASAPIInputDevice : public WASAPIDeviceBase
  214165. {
  214166. public:
  214167. WASAPIInputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  214168. : WASAPIDeviceBase (device_, useExclusiveMode_),
  214169. reservoir (1, 1)
  214170. {
  214171. }
  214172. ~WASAPIInputDevice()
  214173. {
  214174. close();
  214175. }
  214176. bool open (const double newSampleRate, const BigInteger& newChannels)
  214177. {
  214178. reservoirSize = 0;
  214179. reservoirCapacity = 16384;
  214180. reservoir.setSize (actualNumChannels * reservoirCapacity * sizeof (float));
  214181. return openClient (newSampleRate, newChannels)
  214182. && (numChannels == 0 || OK (client->GetService (__uuidof (IAudioCaptureClient), (void**) &captureClient)));
  214183. }
  214184. void close()
  214185. {
  214186. closeClient();
  214187. captureClient = 0;
  214188. reservoir.setSize (0);
  214189. }
  214190. void copyBuffers (float** destBuffers, int numDestBuffers, int bufferSize, Thread& thread)
  214191. {
  214192. if (numChannels <= 0)
  214193. return;
  214194. int offset = 0;
  214195. while (bufferSize > 0)
  214196. {
  214197. if (reservoirSize > 0) // There's stuff in the reservoir, so use that...
  214198. {
  214199. const int samplesToDo = jmin (bufferSize, (int) reservoirSize);
  214200. for (int i = 0; i < numDestBuffers; ++i)
  214201. {
  214202. float* const dest = destBuffers[i] + offset;
  214203. const int srcChan = channelMaps.getUnchecked(i);
  214204. switch (dataFormat)
  214205. {
  214206. case AudioDataConverters::float32LE:
  214207. AudioDataConverters::convertFloat32LEToFloat (((uint8*) reservoir.getData()) + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  214208. break;
  214209. case AudioDataConverters::int32LE:
  214210. AudioDataConverters::convertInt32LEToFloat (((uint8*) reservoir.getData()) + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  214211. break;
  214212. case AudioDataConverters::int24LE:
  214213. AudioDataConverters::convertInt24LEToFloat (((uint8*) reservoir.getData()) + 3 * srcChan, dest, samplesToDo, 3 * actualNumChannels);
  214214. break;
  214215. case AudioDataConverters::int16LE:
  214216. AudioDataConverters::convertInt16LEToFloat (((uint8*) reservoir.getData()) + 2 * srcChan, dest, samplesToDo, 2 * actualNumChannels);
  214217. break;
  214218. default: jassertfalse; break;
  214219. }
  214220. }
  214221. bufferSize -= samplesToDo;
  214222. offset += samplesToDo;
  214223. reservoirSize -= samplesToDo;
  214224. }
  214225. else
  214226. {
  214227. UINT32 packetLength = 0;
  214228. if (! OK (captureClient->GetNextPacketSize (&packetLength)))
  214229. break;
  214230. if (packetLength == 0)
  214231. {
  214232. if (thread.threadShouldExit())
  214233. break;
  214234. Thread::sleep (1);
  214235. continue;
  214236. }
  214237. uint8* inputData = 0;
  214238. UINT32 numSamplesAvailable;
  214239. DWORD flags;
  214240. if (OK (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, 0, 0)))
  214241. {
  214242. const int samplesToDo = jmin (bufferSize, (int) numSamplesAvailable);
  214243. for (int i = 0; i < numDestBuffers; ++i)
  214244. {
  214245. float* const dest = destBuffers[i] + offset;
  214246. const int srcChan = channelMaps.getUnchecked(i);
  214247. switch (dataFormat)
  214248. {
  214249. case AudioDataConverters::float32LE:
  214250. AudioDataConverters::convertFloat32LEToFloat (inputData + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  214251. break;
  214252. case AudioDataConverters::int32LE:
  214253. AudioDataConverters::convertInt32LEToFloat (inputData + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  214254. break;
  214255. case AudioDataConverters::int24LE:
  214256. AudioDataConverters::convertInt24LEToFloat (inputData + 3 * srcChan, dest, samplesToDo, 3 * actualNumChannels);
  214257. break;
  214258. case AudioDataConverters::int16LE:
  214259. AudioDataConverters::convertInt16LEToFloat (inputData + 2 * srcChan, dest, samplesToDo, 2 * actualNumChannels);
  214260. break;
  214261. default: jassertfalse; break;
  214262. }
  214263. }
  214264. bufferSize -= samplesToDo;
  214265. offset += samplesToDo;
  214266. if (samplesToDo < (int) numSamplesAvailable)
  214267. {
  214268. reservoirSize = jmin ((int) (numSamplesAvailable - samplesToDo), reservoirCapacity);
  214269. memcpy ((uint8*) reservoir.getData(), inputData + bytesPerSample * actualNumChannels * samplesToDo,
  214270. bytesPerSample * actualNumChannels * reservoirSize);
  214271. }
  214272. captureClient->ReleaseBuffer (numSamplesAvailable);
  214273. }
  214274. }
  214275. }
  214276. }
  214277. ComSmartPtr <IAudioCaptureClient> captureClient;
  214278. MemoryBlock reservoir;
  214279. int reservoirSize, reservoirCapacity;
  214280. private:
  214281. WASAPIInputDevice (const WASAPIInputDevice&);
  214282. WASAPIInputDevice& operator= (const WASAPIInputDevice&);
  214283. };
  214284. class WASAPIOutputDevice : public WASAPIDeviceBase
  214285. {
  214286. public:
  214287. WASAPIOutputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  214288. : WASAPIDeviceBase (device_, useExclusiveMode_)
  214289. {
  214290. }
  214291. ~WASAPIOutputDevice()
  214292. {
  214293. close();
  214294. }
  214295. bool open (const double newSampleRate, const BigInteger& newChannels)
  214296. {
  214297. return openClient (newSampleRate, newChannels)
  214298. && (numChannels == 0 || OK (client->GetService (__uuidof (IAudioRenderClient), (void**) &renderClient)));
  214299. }
  214300. void close()
  214301. {
  214302. closeClient();
  214303. renderClient = 0;
  214304. }
  214305. void copyBuffers (const float** const srcBuffers, const int numSrcBuffers, int bufferSize, Thread& thread)
  214306. {
  214307. if (numChannels <= 0)
  214308. return;
  214309. int offset = 0;
  214310. while (bufferSize > 0)
  214311. {
  214312. UINT32 padding = 0;
  214313. if (! OK (client->GetCurrentPadding (&padding)))
  214314. return;
  214315. int samplesToDo = useExclusiveMode ? bufferSize
  214316. : jmin ((int) (actualBufferSize - padding), bufferSize);
  214317. if (samplesToDo <= 0)
  214318. {
  214319. if (thread.threadShouldExit())
  214320. break;
  214321. Thread::sleep (0);
  214322. continue;
  214323. }
  214324. uint8* outputData = 0;
  214325. if (OK (renderClient->GetBuffer (samplesToDo, &outputData)))
  214326. {
  214327. for (int i = 0; i < numSrcBuffers; ++i)
  214328. {
  214329. const float* const source = srcBuffers[i] + offset;
  214330. const int destChan = channelMaps.getUnchecked(i);
  214331. switch (dataFormat)
  214332. {
  214333. case AudioDataConverters::float32LE:
  214334. AudioDataConverters::convertFloatToFloat32LE (source, outputData + 4 * destChan, samplesToDo, 4 * actualNumChannels);
  214335. break;
  214336. case AudioDataConverters::int32LE:
  214337. AudioDataConverters::convertFloatToInt32LE (source, outputData + 4 * destChan, samplesToDo, 4 * actualNumChannels);
  214338. break;
  214339. case AudioDataConverters::int24LE:
  214340. AudioDataConverters::convertFloatToInt24LE (source, outputData + 3 * destChan, samplesToDo, 3 * actualNumChannels);
  214341. break;
  214342. case AudioDataConverters::int16LE:
  214343. AudioDataConverters::convertFloatToInt16LE (source, outputData + 2 * destChan, samplesToDo, 2 * actualNumChannels);
  214344. break;
  214345. default: jassertfalse; break;
  214346. }
  214347. }
  214348. renderClient->ReleaseBuffer (samplesToDo, 0);
  214349. offset += samplesToDo;
  214350. bufferSize -= samplesToDo;
  214351. }
  214352. }
  214353. }
  214354. ComSmartPtr <IAudioRenderClient> renderClient;
  214355. private:
  214356. WASAPIOutputDevice (const WASAPIOutputDevice&);
  214357. WASAPIOutputDevice& operator= (const WASAPIOutputDevice&);
  214358. };
  214359. class WASAPIAudioIODevice : public AudioIODevice,
  214360. public Thread
  214361. {
  214362. public:
  214363. WASAPIAudioIODevice (const String& deviceName,
  214364. const String& outputDeviceId_,
  214365. const String& inputDeviceId_,
  214366. const bool useExclusiveMode_)
  214367. : AudioIODevice (deviceName, "Windows Audio"),
  214368. Thread ("Juce WASAPI"),
  214369. isOpen_ (false),
  214370. isStarted (false),
  214371. outputDevice (0),
  214372. outputDeviceId (outputDeviceId_),
  214373. inputDevice (0),
  214374. inputDeviceId (inputDeviceId_),
  214375. useExclusiveMode (useExclusiveMode_),
  214376. currentBufferSizeSamples (0),
  214377. currentSampleRate (0),
  214378. callback (0)
  214379. {
  214380. }
  214381. ~WASAPIAudioIODevice()
  214382. {
  214383. close();
  214384. deleteAndZero (inputDevice);
  214385. deleteAndZero (outputDevice);
  214386. }
  214387. bool initialise()
  214388. {
  214389. double defaultSampleRateIn = 0, defaultSampleRateOut = 0;
  214390. int minBufferSizeIn = 0, defaultBufferSizeIn = 0, minBufferSizeOut = 0, defaultBufferSizeOut = 0;
  214391. latencyIn = latencyOut = 0;
  214392. Array <double> ratesIn, ratesOut;
  214393. if (createDevices())
  214394. {
  214395. jassert (inputDevice != 0 || outputDevice != 0);
  214396. if (inputDevice != 0 && outputDevice != 0)
  214397. {
  214398. defaultSampleRate = jmin (inputDevice->defaultSampleRate, outputDevice->defaultSampleRate);
  214399. minBufferSize = jmin (inputDevice->minBufferSize, outputDevice->minBufferSize);
  214400. defaultBufferSize = jmax (inputDevice->defaultBufferSize, outputDevice->defaultBufferSize);
  214401. sampleRates = inputDevice->rates;
  214402. sampleRates.removeValuesNotIn (outputDevice->rates);
  214403. }
  214404. else
  214405. {
  214406. WASAPIDeviceBase* const d = inputDevice != 0 ? (WASAPIDeviceBase*) inputDevice : (WASAPIDeviceBase*) outputDevice;
  214407. defaultSampleRate = d->defaultSampleRate;
  214408. minBufferSize = d->minBufferSize;
  214409. defaultBufferSize = d->defaultBufferSize;
  214410. sampleRates = d->rates;
  214411. }
  214412. bufferSizes.addUsingDefaultSort (defaultBufferSize);
  214413. if (minBufferSize != defaultBufferSize)
  214414. bufferSizes.addUsingDefaultSort (minBufferSize);
  214415. int n = 64;
  214416. for (int i = 0; i < 40; ++i)
  214417. {
  214418. if (n >= minBufferSize && n <= 2048 && ! bufferSizes.contains (n))
  214419. bufferSizes.addUsingDefaultSort (n);
  214420. n += (n < 512) ? 32 : (n < 1024 ? 64 : 128);
  214421. }
  214422. return true;
  214423. }
  214424. return false;
  214425. }
  214426. const StringArray getOutputChannelNames()
  214427. {
  214428. StringArray outChannels;
  214429. if (outputDevice != 0)
  214430. for (int i = 1; i <= outputDevice->actualNumChannels; ++i)
  214431. outChannels.add ("Output channel " + String (i));
  214432. return outChannels;
  214433. }
  214434. const StringArray getInputChannelNames()
  214435. {
  214436. StringArray inChannels;
  214437. if (inputDevice != 0)
  214438. for (int i = 1; i <= inputDevice->actualNumChannels; ++i)
  214439. inChannels.add ("Input channel " + String (i));
  214440. return inChannels;
  214441. }
  214442. int getNumSampleRates() { return sampleRates.size(); }
  214443. double getSampleRate (int index) { return sampleRates [index]; }
  214444. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  214445. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  214446. int getDefaultBufferSize() { return defaultBufferSize; }
  214447. int getCurrentBufferSizeSamples() { return currentBufferSizeSamples; }
  214448. double getCurrentSampleRate() { return currentSampleRate; }
  214449. int getCurrentBitDepth() { return 32; }
  214450. int getOutputLatencyInSamples() { return latencyOut; }
  214451. int getInputLatencyInSamples() { return latencyIn; }
  214452. const BigInteger getActiveOutputChannels() const { return outputDevice != 0 ? outputDevice->channels : BigInteger(); }
  214453. const BigInteger getActiveInputChannels() const { return inputDevice != 0 ? inputDevice->channels : BigInteger(); }
  214454. const String getLastError() { return lastError; }
  214455. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  214456. double sampleRate, int bufferSizeSamples)
  214457. {
  214458. close();
  214459. lastError = String::empty;
  214460. if (sampleRates.size() == 0 && inputDevice != 0 && outputDevice != 0)
  214461. {
  214462. lastError = "The input and output devices don't share a common sample rate!";
  214463. return lastError;
  214464. }
  214465. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  214466. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  214467. if (inputDevice != 0 && ! inputDevice->open (currentSampleRate, inputChannels))
  214468. {
  214469. lastError = "Couldn't open the input device!";
  214470. return lastError;
  214471. }
  214472. if (outputDevice != 0 && ! outputDevice->open (currentSampleRate, outputChannels))
  214473. {
  214474. close();
  214475. lastError = "Couldn't open the output device!";
  214476. return lastError;
  214477. }
  214478. if (inputDevice != 0)
  214479. ResetEvent (inputDevice->clientEvent);
  214480. if (outputDevice != 0)
  214481. ResetEvent (outputDevice->clientEvent);
  214482. startThread (8);
  214483. Thread::sleep (5);
  214484. if (inputDevice != 0 && inputDevice->client != 0)
  214485. {
  214486. latencyIn = inputDevice->latencySamples + inputDevice->actualBufferSize + inputDevice->minBufferSize;
  214487. HRESULT hr = inputDevice->client->Start();
  214488. logFailure (hr); //xxx handle this
  214489. }
  214490. if (outputDevice != 0 && outputDevice->client != 0)
  214491. {
  214492. latencyOut = outputDevice->latencySamples + outputDevice->actualBufferSize + outputDevice->minBufferSize;
  214493. HRESULT hr = outputDevice->client->Start();
  214494. logFailure (hr); //xxx handle this
  214495. }
  214496. isOpen_ = true;
  214497. return lastError;
  214498. }
  214499. void close()
  214500. {
  214501. stop();
  214502. if (inputDevice != 0)
  214503. SetEvent (inputDevice->clientEvent);
  214504. if (outputDevice != 0)
  214505. SetEvent (outputDevice->clientEvent);
  214506. stopThread (5000);
  214507. if (inputDevice != 0)
  214508. inputDevice->close();
  214509. if (outputDevice != 0)
  214510. outputDevice->close();
  214511. isOpen_ = false;
  214512. }
  214513. bool isOpen() { return isOpen_ && isThreadRunning(); }
  214514. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  214515. void start (AudioIODeviceCallback* call)
  214516. {
  214517. if (isOpen_ && call != 0 && ! isStarted)
  214518. {
  214519. if (! isThreadRunning())
  214520. {
  214521. // something's gone wrong and the thread's stopped..
  214522. isOpen_ = false;
  214523. return;
  214524. }
  214525. call->audioDeviceAboutToStart (this);
  214526. const ScopedLock sl (startStopLock);
  214527. callback = call;
  214528. isStarted = true;
  214529. }
  214530. }
  214531. void stop()
  214532. {
  214533. if (isStarted)
  214534. {
  214535. AudioIODeviceCallback* const callbackLocal = callback;
  214536. {
  214537. const ScopedLock sl (startStopLock);
  214538. isStarted = false;
  214539. }
  214540. if (callbackLocal != 0)
  214541. callbackLocal->audioDeviceStopped();
  214542. }
  214543. }
  214544. void setMMThreadPriority()
  214545. {
  214546. DynamicLibraryLoader dll ("avrt.dll");
  214547. DynamicLibraryImport (AvSetMmThreadCharacteristics, avSetMmThreadCharacteristics, HANDLE, dll, (LPCTSTR, LPDWORD))
  214548. DynamicLibraryImport (AvSetMmThreadPriority, avSetMmThreadPriority, HANDLE, dll, (HANDLE, AVRT_PRIORITY))
  214549. if (avSetMmThreadCharacteristics != 0 && avSetMmThreadPriority != 0)
  214550. {
  214551. DWORD dummy = 0;
  214552. HANDLE h = avSetMmThreadCharacteristics (_T("Pro Audio"), &dummy);
  214553. if (h != 0)
  214554. avSetMmThreadPriority (h, AVRT_PRIORITY_NORMAL);
  214555. }
  214556. }
  214557. void run()
  214558. {
  214559. setMMThreadPriority();
  214560. const int bufferSize = currentBufferSizeSamples;
  214561. HANDLE events[2];
  214562. int numEvents = 0;
  214563. if (inputDevice != 0)
  214564. events [numEvents++] = inputDevice->clientEvent;
  214565. if (outputDevice != 0)
  214566. events [numEvents++] = outputDevice->clientEvent;
  214567. const int numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  214568. const int numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  214569. AudioSampleBuffer ins (jmax (1, numInputBuffers), bufferSize + 32);
  214570. AudioSampleBuffer outs (jmax (1, numOutputBuffers), bufferSize + 32);
  214571. float** const inputBuffers = ins.getArrayOfChannels();
  214572. float** const outputBuffers = outs.getArrayOfChannels();
  214573. ins.clear();
  214574. while (! threadShouldExit())
  214575. {
  214576. const DWORD result = useExclusiveMode ? WaitForSingleObject (inputDevice->clientEvent, 1000)
  214577. : WaitForMultipleObjects (numEvents, events, true, 1000);
  214578. if (result == WAIT_TIMEOUT)
  214579. continue;
  214580. if (threadShouldExit())
  214581. break;
  214582. if (inputDevice != 0)
  214583. inputDevice->copyBuffers (inputBuffers, numInputBuffers, bufferSize, *this);
  214584. // Make the callback..
  214585. {
  214586. const ScopedLock sl (startStopLock);
  214587. if (isStarted)
  214588. {
  214589. JUCE_TRY
  214590. {
  214591. callback->audioDeviceIOCallback ((const float**) inputBuffers,
  214592. numInputBuffers,
  214593. outputBuffers,
  214594. numOutputBuffers,
  214595. bufferSize);
  214596. }
  214597. JUCE_CATCH_EXCEPTION
  214598. }
  214599. else
  214600. {
  214601. outs.clear();
  214602. }
  214603. }
  214604. if (useExclusiveMode && WaitForSingleObject (outputDevice->clientEvent, 1000) == WAIT_TIMEOUT)
  214605. continue;
  214606. if (outputDevice != 0)
  214607. outputDevice->copyBuffers ((const float**) outputBuffers, numOutputBuffers, bufferSize, *this);
  214608. }
  214609. }
  214610. juce_UseDebuggingNewOperator
  214611. String outputDeviceId, inputDeviceId;
  214612. String lastError;
  214613. private:
  214614. // Device stats...
  214615. WASAPIInputDevice* inputDevice;
  214616. WASAPIOutputDevice* outputDevice;
  214617. const bool useExclusiveMode;
  214618. double defaultSampleRate;
  214619. int minBufferSize, defaultBufferSize;
  214620. int latencyIn, latencyOut;
  214621. Array <double> sampleRates;
  214622. Array <int> bufferSizes;
  214623. // Active state...
  214624. bool isOpen_, isStarted;
  214625. int currentBufferSizeSamples;
  214626. double currentSampleRate;
  214627. AudioIODeviceCallback* callback;
  214628. CriticalSection startStopLock;
  214629. bool createDevices()
  214630. {
  214631. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  214632. if (! OK (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  214633. return false;
  214634. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  214635. if (! OK (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, &deviceCollection)))
  214636. return false;
  214637. UINT32 numDevices = 0;
  214638. if (! OK (deviceCollection->GetCount (&numDevices)))
  214639. return false;
  214640. for (UINT32 i = 0; i < numDevices; ++i)
  214641. {
  214642. ComSmartPtr <IMMDevice> device;
  214643. if (! OK (deviceCollection->Item (i, &device)))
  214644. continue;
  214645. const String deviceId (wasapi_getDeviceID (device));
  214646. if (deviceId.isEmpty())
  214647. continue;
  214648. const EDataFlow flow = wasapi_getDataFlow (device);
  214649. if (deviceId == inputDeviceId && flow == eCapture)
  214650. inputDevice = new WASAPIInputDevice (device, useExclusiveMode);
  214651. else if (deviceId == outputDeviceId && flow == eRender)
  214652. outputDevice = new WASAPIOutputDevice (device, useExclusiveMode);
  214653. }
  214654. return (outputDeviceId.isEmpty() || (outputDevice != 0 && outputDevice->isOk()))
  214655. && (inputDeviceId.isEmpty() || (inputDevice != 0 && inputDevice->isOk()));
  214656. }
  214657. WASAPIAudioIODevice (const WASAPIAudioIODevice&);
  214658. WASAPIAudioIODevice& operator= (const WASAPIAudioIODevice&);
  214659. };
  214660. class WASAPIAudioIODeviceType : public AudioIODeviceType
  214661. {
  214662. public:
  214663. WASAPIAudioIODeviceType()
  214664. : AudioIODeviceType ("Windows Audio"),
  214665. hasScanned (false)
  214666. {
  214667. }
  214668. ~WASAPIAudioIODeviceType()
  214669. {
  214670. }
  214671. void scanForDevices()
  214672. {
  214673. hasScanned = true;
  214674. outputDeviceNames.clear();
  214675. inputDeviceNames.clear();
  214676. outputDeviceIds.clear();
  214677. inputDeviceIds.clear();
  214678. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  214679. if (! OK (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  214680. return;
  214681. const String defaultRenderer = getDefaultEndpoint (enumerator, false);
  214682. const String defaultCapture = getDefaultEndpoint (enumerator, true);
  214683. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  214684. UINT32 numDevices = 0;
  214685. if (! (OK (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, &deviceCollection))
  214686. && OK (deviceCollection->GetCount (&numDevices))))
  214687. return;
  214688. for (UINT32 i = 0; i < numDevices; ++i)
  214689. {
  214690. ComSmartPtr <IMMDevice> device;
  214691. if (! OK (deviceCollection->Item (i, &device)))
  214692. continue;
  214693. const String deviceId (wasapi_getDeviceID (device));
  214694. DWORD state = 0;
  214695. if (! OK (device->GetState (&state)))
  214696. continue;
  214697. if (state != DEVICE_STATE_ACTIVE)
  214698. continue;
  214699. String name;
  214700. {
  214701. ComSmartPtr <IPropertyStore> properties;
  214702. if (! OK (device->OpenPropertyStore (STGM_READ, &properties)))
  214703. continue;
  214704. PROPVARIANT value;
  214705. PropVariantInit (&value);
  214706. if (OK (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  214707. name = value.pwszVal;
  214708. PropVariantClear (&value);
  214709. }
  214710. const EDataFlow flow = wasapi_getDataFlow (device);
  214711. if (flow == eRender)
  214712. {
  214713. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  214714. outputDeviceIds.insert (index, deviceId);
  214715. outputDeviceNames.insert (index, name);
  214716. }
  214717. else if (flow == eCapture)
  214718. {
  214719. const int index = (deviceId == defaultCapture) ? 0 : -1;
  214720. inputDeviceIds.insert (index, deviceId);
  214721. inputDeviceNames.insert (index, name);
  214722. }
  214723. }
  214724. inputDeviceNames.appendNumbersToDuplicates (false, false);
  214725. outputDeviceNames.appendNumbersToDuplicates (false, false);
  214726. }
  214727. const StringArray getDeviceNames (bool wantInputNames) const
  214728. {
  214729. jassert (hasScanned); // need to call scanForDevices() before doing this
  214730. return wantInputNames ? inputDeviceNames
  214731. : outputDeviceNames;
  214732. }
  214733. int getDefaultDeviceIndex (bool /*forInput*/) const
  214734. {
  214735. jassert (hasScanned); // need to call scanForDevices() before doing this
  214736. return 0;
  214737. }
  214738. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  214739. {
  214740. jassert (hasScanned); // need to call scanForDevices() before doing this
  214741. WASAPIAudioIODevice* const d = dynamic_cast <WASAPIAudioIODevice*> (device);
  214742. return d == 0 ? -1 : (asInput ? inputDeviceIds.indexOf (d->inputDeviceId)
  214743. : outputDeviceIds.indexOf (d->outputDeviceId));
  214744. }
  214745. bool hasSeparateInputsAndOutputs() const { return true; }
  214746. AudioIODevice* createDevice (const String& outputDeviceName,
  214747. const String& inputDeviceName)
  214748. {
  214749. jassert (hasScanned); // need to call scanForDevices() before doing this
  214750. const bool useExclusiveMode = false;
  214751. ScopedPointer<WASAPIAudioIODevice> device;
  214752. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  214753. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  214754. if (outputIndex >= 0 || inputIndex >= 0)
  214755. {
  214756. device = new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  214757. : inputDeviceName,
  214758. outputDeviceIds [outputIndex],
  214759. inputDeviceIds [inputIndex],
  214760. useExclusiveMode);
  214761. if (! device->initialise())
  214762. device = 0;
  214763. }
  214764. return device.release();
  214765. }
  214766. juce_UseDebuggingNewOperator
  214767. StringArray outputDeviceNames, outputDeviceIds;
  214768. StringArray inputDeviceNames, inputDeviceIds;
  214769. private:
  214770. bool hasScanned;
  214771. static const String getDefaultEndpoint (IMMDeviceEnumerator* const enumerator, const bool forCapture)
  214772. {
  214773. String s;
  214774. IMMDevice* dev = 0;
  214775. if (OK (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  214776. eMultimedia, &dev)))
  214777. {
  214778. WCHAR* deviceId = 0;
  214779. if (OK (dev->GetId (&deviceId)))
  214780. {
  214781. s = String (deviceId);
  214782. CoTaskMemFree (deviceId);
  214783. }
  214784. dev->Release();
  214785. }
  214786. return s;
  214787. }
  214788. WASAPIAudioIODeviceType (const WASAPIAudioIODeviceType&);
  214789. WASAPIAudioIODeviceType& operator= (const WASAPIAudioIODeviceType&);
  214790. };
  214791. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI()
  214792. {
  214793. return new WASAPIAudioIODeviceType();
  214794. }
  214795. #undef logFailure
  214796. #undef OK
  214797. #endif
  214798. /*** End of inlined file: juce_win32_WASAPI.cpp ***/
  214799. /*** Start of inlined file: juce_win32_CameraDevice.cpp ***/
  214800. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  214801. // compiled on its own).
  214802. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  214803. class DShowCameraDeviceInteral : public ChangeBroadcaster
  214804. {
  214805. public:
  214806. DShowCameraDeviceInteral (CameraDevice* const owner_,
  214807. const ComSmartPtr <ICaptureGraphBuilder2>& captureGraphBuilder_,
  214808. const ComSmartPtr <IBaseFilter>& filter_,
  214809. int minWidth, int minHeight,
  214810. int maxWidth, int maxHeight)
  214811. : owner (owner_),
  214812. captureGraphBuilder (captureGraphBuilder_),
  214813. filter (filter_),
  214814. ok (false),
  214815. imageNeedsFlipping (false),
  214816. width (0),
  214817. height (0),
  214818. activeUsers (0),
  214819. recordNextFrameTime (false)
  214820. {
  214821. HRESULT hr = graphBuilder.CoCreateInstance (CLSID_FilterGraph);
  214822. if (FAILED (hr))
  214823. return;
  214824. hr = captureGraphBuilder->SetFiltergraph (graphBuilder);
  214825. if (FAILED (hr))
  214826. return;
  214827. hr = graphBuilder->QueryInterface (IID_IMediaControl, (void**) &mediaControl);
  214828. if (FAILED (hr))
  214829. return;
  214830. {
  214831. ComSmartPtr <IAMStreamConfig> streamConfig;
  214832. hr = captureGraphBuilder->FindInterface (&PIN_CATEGORY_CAPTURE, 0, filter,
  214833. IID_IAMStreamConfig, (void**) &streamConfig);
  214834. if (streamConfig != 0)
  214835. {
  214836. getVideoSizes (streamConfig);
  214837. if (! selectVideoSize (streamConfig, minWidth, minHeight, maxWidth, maxHeight))
  214838. return;
  214839. }
  214840. }
  214841. hr = graphBuilder->AddFilter (filter, _T("Video Capture"));
  214842. if (FAILED (hr))
  214843. return;
  214844. hr = smartTee.CoCreateInstance (CLSID_SmartTee);
  214845. if (FAILED (hr))
  214846. return;
  214847. hr = graphBuilder->AddFilter (smartTee, _T("Smart Tee"));
  214848. if (FAILED (hr))
  214849. return;
  214850. if (! connectFilters (filter, smartTee))
  214851. return;
  214852. ComSmartPtr <IBaseFilter> sampleGrabberBase;
  214853. hr = sampleGrabberBase.CoCreateInstance (CLSID_SampleGrabber);
  214854. if (FAILED (hr))
  214855. return;
  214856. hr = sampleGrabberBase->QueryInterface (IID_ISampleGrabber, (void**) &sampleGrabber);
  214857. if (FAILED (hr))
  214858. return;
  214859. AM_MEDIA_TYPE mt;
  214860. zerostruct (mt);
  214861. mt.majortype = MEDIATYPE_Video;
  214862. mt.subtype = MEDIASUBTYPE_RGB24;
  214863. mt.formattype = FORMAT_VideoInfo;
  214864. sampleGrabber->SetMediaType (&mt);
  214865. callback = new GrabberCallback (*this);
  214866. sampleGrabber->SetCallback (callback, 1);
  214867. hr = graphBuilder->AddFilter (sampleGrabberBase, _T("Sample Grabber"));
  214868. if (FAILED (hr))
  214869. return;
  214870. ComSmartPtr <IPin> grabberInputPin;
  214871. if (! (getPin (smartTee, PINDIR_OUTPUT, &smartTeeCaptureOutputPin, "capture")
  214872. && getPin (smartTee, PINDIR_OUTPUT, &smartTeePreviewOutputPin, "preview")
  214873. && getPin (sampleGrabberBase, PINDIR_INPUT, &grabberInputPin)))
  214874. return;
  214875. hr = graphBuilder->Connect (smartTeePreviewOutputPin, grabberInputPin);
  214876. if (FAILED (hr))
  214877. return;
  214878. zerostruct (mt);
  214879. hr = sampleGrabber->GetConnectedMediaType (&mt);
  214880. VIDEOINFOHEADER* pVih = (VIDEOINFOHEADER*) (mt.pbFormat);
  214881. width = pVih->bmiHeader.biWidth;
  214882. height = pVih->bmiHeader.biHeight;
  214883. ComSmartPtr <IBaseFilter> nullFilter;
  214884. hr = nullFilter.CoCreateInstance (CLSID_NullRenderer);
  214885. hr = graphBuilder->AddFilter (nullFilter, _T("Null Renderer"));
  214886. if (connectFilters (sampleGrabberBase, nullFilter)
  214887. && addGraphToRot())
  214888. {
  214889. activeImage = Image (Image::RGB, width, height, true);
  214890. loadingImage = Image (Image::RGB, width, height, true);
  214891. ok = true;
  214892. }
  214893. }
  214894. ~DShowCameraDeviceInteral()
  214895. {
  214896. if (mediaControl != 0)
  214897. mediaControl->Stop();
  214898. removeGraphFromRot();
  214899. for (int i = viewerComps.size(); --i >= 0;)
  214900. viewerComps.getUnchecked(i)->ownerDeleted();
  214901. callback = 0;
  214902. graphBuilder = 0;
  214903. sampleGrabber = 0;
  214904. mediaControl = 0;
  214905. filter = 0;
  214906. captureGraphBuilder = 0;
  214907. smartTee = 0;
  214908. smartTeePreviewOutputPin = 0;
  214909. smartTeeCaptureOutputPin = 0;
  214910. asfWriter = 0;
  214911. }
  214912. void addUser()
  214913. {
  214914. if (ok && activeUsers++ == 0)
  214915. mediaControl->Run();
  214916. }
  214917. void removeUser()
  214918. {
  214919. if (ok && --activeUsers == 0)
  214920. mediaControl->Stop();
  214921. }
  214922. void handleFrame (double /*time*/, BYTE* buffer, long /*bufferSize*/)
  214923. {
  214924. if (recordNextFrameTime)
  214925. {
  214926. const double defaultCameraLatency = 0.1;
  214927. firstRecordedTime = Time::getCurrentTime() - RelativeTime (defaultCameraLatency);
  214928. recordNextFrameTime = false;
  214929. ComSmartPtr <IPin> pin;
  214930. if (getPin (filter, PINDIR_OUTPUT, &pin))
  214931. {
  214932. ComSmartPtr <IAMPushSource> pushSource;
  214933. HRESULT hr = pin->QueryInterface (IID_IAMPushSource, (void**) &pushSource);
  214934. if (pushSource != 0)
  214935. {
  214936. REFERENCE_TIME latency = 0;
  214937. hr = pushSource->GetLatency (&latency);
  214938. firstRecordedTime = firstRecordedTime - RelativeTime ((double) latency);
  214939. }
  214940. }
  214941. }
  214942. {
  214943. const int lineStride = width * 3;
  214944. const ScopedLock sl (imageSwapLock);
  214945. {
  214946. const Image::BitmapData destData (loadingImage, 0, 0, width, height, true);
  214947. for (int i = 0; i < height; ++i)
  214948. memcpy (destData.getLinePointer ((height - 1) - i),
  214949. buffer + lineStride * i,
  214950. lineStride);
  214951. }
  214952. imageNeedsFlipping = true;
  214953. }
  214954. if (listeners.size() > 0)
  214955. callListeners (loadingImage);
  214956. sendChangeMessage (this);
  214957. }
  214958. void drawCurrentImage (Graphics& g, int x, int y, int w, int h)
  214959. {
  214960. if (imageNeedsFlipping)
  214961. {
  214962. const ScopedLock sl (imageSwapLock);
  214963. swapVariables (loadingImage, activeImage);
  214964. imageNeedsFlipping = false;
  214965. }
  214966. RectanglePlacement rp (RectanglePlacement::centred);
  214967. double dx = 0, dy = 0, dw = width, dh = height;
  214968. rp.applyTo (dx, dy, dw, dh, x, y, w, h);
  214969. const int rx = roundToInt (dx), ry = roundToInt (dy);
  214970. const int rw = roundToInt (dw), rh = roundToInt (dh);
  214971. g.saveState();
  214972. g.excludeClipRegion (Rectangle<int> (rx, ry, rw, rh));
  214973. g.fillAll (Colours::black);
  214974. g.restoreState();
  214975. g.drawImage (activeImage, rx, ry, rw, rh, 0, 0, width, height);
  214976. }
  214977. bool createFileCaptureFilter (const File& file)
  214978. {
  214979. removeFileCaptureFilter();
  214980. file.deleteFile();
  214981. mediaControl->Stop();
  214982. firstRecordedTime = Time();
  214983. recordNextFrameTime = true;
  214984. HRESULT hr = asfWriter.CoCreateInstance (CLSID_WMAsfWriter);
  214985. if (SUCCEEDED (hr))
  214986. {
  214987. ComSmartPtr <IFileSinkFilter> fileSink;
  214988. hr = asfWriter->QueryInterface (IID_IFileSinkFilter, (void**) &fileSink);
  214989. if (SUCCEEDED (hr))
  214990. {
  214991. hr = fileSink->SetFileName (file.getFullPathName(), 0);
  214992. if (SUCCEEDED (hr))
  214993. {
  214994. hr = graphBuilder->AddFilter (asfWriter, _T("AsfWriter"));
  214995. if (SUCCEEDED (hr))
  214996. {
  214997. ComSmartPtr <IConfigAsfWriter> asfConfig;
  214998. hr = asfWriter->QueryInterface (IID_IConfigAsfWriter, (void**) &asfConfig);
  214999. asfConfig->SetIndexMode (true);
  215000. ComSmartPtr <IWMProfileManager> profileManager;
  215001. hr = WMCreateProfileManager (&profileManager);
  215002. // This gibberish is the DirectShow profile for a video-only wmv file.
  215003. String prof ("<profile version=\"589824\" storageformat=\"1\" name=\"Quality\" description=\"Quality type for output.\"><streamconfig "
  215004. "majortype=\"{73646976-0000-0010-8000-00AA00389B71}\" streamnumber=\"1\" streamname=\"Video Stream\" inputname=\"Video409\" bitrate=\"894960\" "
  215005. "bufferwindow=\"0\" reliabletransport=\"1\" decodercomplexity=\"AU\" rfc1766langid=\"en-us\"><videomediaprops maxkeyframespacing=\"50000000\" quality=\"90\"/>"
  215006. "<wmmediatype subtype=\"{33564D57-0000-0010-8000-00AA00389B71}\" bfixedsizesamples=\"0\" btemporalcompression=\"1\" lsamplesize=\"0\"> <videoinfoheader "
  215007. "dwbitrate=\"894960\" dwbiterrorrate=\"0\" avgtimeperframe=\"100000\"><rcsource left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/> <rctarget "
  215008. "left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/> <bitmapinfoheader biwidth=\"$WIDTH\" biheight=\"$HEIGHT\" biplanes=\"1\" bibitcount=\"24\" "
  215009. "bicompression=\"WMV3\" bisizeimage=\"0\" bixpelspermeter=\"0\" biypelspermeter=\"0\" biclrused=\"0\" biclrimportant=\"0\"/> "
  215010. "</videoinfoheader></wmmediatype></streamconfig></profile>");
  215011. prof = prof.replace ("$WIDTH", String (width))
  215012. .replace ("$HEIGHT", String (height));
  215013. ComSmartPtr <IWMProfile> currentProfile;
  215014. hr = profileManager->LoadProfileByData ((const WCHAR*) prof, &currentProfile);
  215015. hr = asfConfig->ConfigureFilterUsingProfile (currentProfile);
  215016. if (SUCCEEDED (hr))
  215017. {
  215018. ComSmartPtr <IPin> asfWriterInputPin;
  215019. if (getPin (asfWriter, PINDIR_INPUT, &asfWriterInputPin, "Video Input 01"))
  215020. {
  215021. hr = graphBuilder->Connect (smartTeeCaptureOutputPin, asfWriterInputPin);
  215022. if (SUCCEEDED (hr)
  215023. && ok && activeUsers > 0
  215024. && SUCCEEDED (mediaControl->Run()))
  215025. {
  215026. return true;
  215027. }
  215028. }
  215029. }
  215030. }
  215031. }
  215032. }
  215033. }
  215034. removeFileCaptureFilter();
  215035. if (ok && activeUsers > 0)
  215036. mediaControl->Run();
  215037. return false;
  215038. }
  215039. void removeFileCaptureFilter()
  215040. {
  215041. mediaControl->Stop();
  215042. if (asfWriter != 0)
  215043. {
  215044. graphBuilder->RemoveFilter (asfWriter);
  215045. asfWriter = 0;
  215046. }
  215047. if (ok && activeUsers > 0)
  215048. mediaControl->Run();
  215049. }
  215050. void addListener (CameraImageListener* listenerToAdd)
  215051. {
  215052. const ScopedLock sl (listenerLock);
  215053. if (listeners.size() == 0)
  215054. addUser();
  215055. listeners.addIfNotAlreadyThere (listenerToAdd);
  215056. }
  215057. void removeListener (CameraImageListener* listenerToRemove)
  215058. {
  215059. const ScopedLock sl (listenerLock);
  215060. listeners.removeValue (listenerToRemove);
  215061. if (listeners.size() == 0)
  215062. removeUser();
  215063. }
  215064. void callListeners (const Image& image)
  215065. {
  215066. const ScopedLock sl (listenerLock);
  215067. for (int i = listeners.size(); --i >= 0;)
  215068. {
  215069. CameraImageListener* const l = listeners[i];
  215070. if (l != 0)
  215071. l->imageReceived (image);
  215072. }
  215073. }
  215074. class DShowCaptureViewerComp : public Component,
  215075. public ChangeListener
  215076. {
  215077. public:
  215078. DShowCaptureViewerComp (DShowCameraDeviceInteral* const owner_)
  215079. : owner (owner_)
  215080. {
  215081. setOpaque (true);
  215082. owner->addChangeListener (this);
  215083. owner->addUser();
  215084. owner->viewerComps.add (this);
  215085. setSize (owner_->width, owner_->height);
  215086. }
  215087. ~DShowCaptureViewerComp()
  215088. {
  215089. if (owner != 0)
  215090. {
  215091. owner->viewerComps.removeValue (this);
  215092. owner->removeUser();
  215093. owner->removeChangeListener (this);
  215094. }
  215095. }
  215096. void ownerDeleted()
  215097. {
  215098. owner = 0;
  215099. }
  215100. void paint (Graphics& g)
  215101. {
  215102. g.setColour (Colours::black);
  215103. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  215104. if (owner != 0)
  215105. owner->drawCurrentImage (g, 0, 0, getWidth(), getHeight());
  215106. else
  215107. g.fillAll (Colours::black);
  215108. }
  215109. void changeListenerCallback (void*)
  215110. {
  215111. repaint();
  215112. }
  215113. private:
  215114. DShowCameraDeviceInteral* owner;
  215115. };
  215116. bool ok;
  215117. int width, height;
  215118. Time firstRecordedTime;
  215119. Array <DShowCaptureViewerComp*> viewerComps;
  215120. private:
  215121. CameraDevice* const owner;
  215122. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  215123. ComSmartPtr <IBaseFilter> filter;
  215124. ComSmartPtr <IBaseFilter> smartTee;
  215125. ComSmartPtr <IGraphBuilder> graphBuilder;
  215126. ComSmartPtr <ISampleGrabber> sampleGrabber;
  215127. ComSmartPtr <IMediaControl> mediaControl;
  215128. ComSmartPtr <IPin> smartTeePreviewOutputPin;
  215129. ComSmartPtr <IPin> smartTeeCaptureOutputPin;
  215130. ComSmartPtr <IBaseFilter> asfWriter;
  215131. int activeUsers;
  215132. Array <int> widths, heights;
  215133. DWORD graphRegistrationID;
  215134. CriticalSection imageSwapLock;
  215135. bool imageNeedsFlipping;
  215136. Image loadingImage;
  215137. Image activeImage;
  215138. bool recordNextFrameTime;
  215139. void getVideoSizes (IAMStreamConfig* const streamConfig)
  215140. {
  215141. widths.clear();
  215142. heights.clear();
  215143. int count = 0, size = 0;
  215144. streamConfig->GetNumberOfCapabilities (&count, &size);
  215145. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  215146. {
  215147. for (int i = 0; i < count; ++i)
  215148. {
  215149. VIDEO_STREAM_CONFIG_CAPS scc;
  215150. AM_MEDIA_TYPE* config;
  215151. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  215152. if (SUCCEEDED (hr))
  215153. {
  215154. const int w = scc.InputSize.cx;
  215155. const int h = scc.InputSize.cy;
  215156. bool duplicate = false;
  215157. for (int j = widths.size(); --j >= 0;)
  215158. {
  215159. if (w == widths.getUnchecked (j) && h == heights.getUnchecked (j))
  215160. {
  215161. duplicate = true;
  215162. break;
  215163. }
  215164. }
  215165. if (! duplicate)
  215166. {
  215167. DBG ("Camera capture size: " + String (w) + ", " + String (h));
  215168. widths.add (w);
  215169. heights.add (h);
  215170. }
  215171. deleteMediaType (config);
  215172. }
  215173. }
  215174. }
  215175. }
  215176. bool selectVideoSize (IAMStreamConfig* const streamConfig,
  215177. const int minWidth, const int minHeight,
  215178. const int maxWidth, const int maxHeight)
  215179. {
  215180. int count = 0, size = 0, bestArea = 0, bestIndex = -1;
  215181. streamConfig->GetNumberOfCapabilities (&count, &size);
  215182. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  215183. {
  215184. AM_MEDIA_TYPE* config;
  215185. VIDEO_STREAM_CONFIG_CAPS scc;
  215186. for (int i = 0; i < count; ++i)
  215187. {
  215188. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  215189. if (SUCCEEDED (hr))
  215190. {
  215191. if (scc.InputSize.cx >= minWidth
  215192. && scc.InputSize.cy >= minHeight
  215193. && scc.InputSize.cx <= maxWidth
  215194. && scc.InputSize.cy <= maxHeight)
  215195. {
  215196. int area = scc.InputSize.cx * scc.InputSize.cy;
  215197. if (area > bestArea)
  215198. {
  215199. bestIndex = i;
  215200. bestArea = area;
  215201. }
  215202. }
  215203. deleteMediaType (config);
  215204. }
  215205. }
  215206. if (bestIndex >= 0)
  215207. {
  215208. HRESULT hr = streamConfig->GetStreamCaps (bestIndex, &config, (BYTE*) &scc);
  215209. hr = streamConfig->SetFormat (config);
  215210. deleteMediaType (config);
  215211. return SUCCEEDED (hr);
  215212. }
  215213. }
  215214. return false;
  215215. }
  215216. static bool getPin (IBaseFilter* filter, const PIN_DIRECTION wantedDirection, IPin** result, const char* pinName = 0)
  215217. {
  215218. ComSmartPtr <IEnumPins> enumerator;
  215219. ComSmartPtr <IPin> pin;
  215220. filter->EnumPins (&enumerator);
  215221. while (enumerator->Next (1, &pin, 0) == S_OK)
  215222. {
  215223. PIN_DIRECTION dir;
  215224. pin->QueryDirection (&dir);
  215225. if (wantedDirection == dir)
  215226. {
  215227. PIN_INFO info;
  215228. zerostruct (info);
  215229. pin->QueryPinInfo (&info);
  215230. if (pinName == 0 || String (pinName).equalsIgnoreCase (String (info.achName)))
  215231. {
  215232. pin->AddRef();
  215233. *result = pin;
  215234. return true;
  215235. }
  215236. }
  215237. }
  215238. return false;
  215239. }
  215240. bool connectFilters (IBaseFilter* const first, IBaseFilter* const second) const
  215241. {
  215242. ComSmartPtr <IPin> in, out;
  215243. return getPin (first, PINDIR_OUTPUT, &out)
  215244. && getPin (second, PINDIR_INPUT, &in)
  215245. && SUCCEEDED (graphBuilder->Connect (out, in));
  215246. }
  215247. bool addGraphToRot()
  215248. {
  215249. ComSmartPtr <IRunningObjectTable> rot;
  215250. if (FAILED (GetRunningObjectTable (0, &rot)))
  215251. return false;
  215252. ComSmartPtr <IMoniker> moniker;
  215253. WCHAR buffer[128];
  215254. HRESULT hr = CreateItemMoniker (_T("!"), buffer, &moniker);
  215255. if (FAILED (hr))
  215256. return false;
  215257. graphRegistrationID = 0;
  215258. return SUCCEEDED (rot->Register (0, graphBuilder, moniker, &graphRegistrationID));
  215259. }
  215260. void removeGraphFromRot()
  215261. {
  215262. ComSmartPtr <IRunningObjectTable> rot;
  215263. if (SUCCEEDED (GetRunningObjectTable (0, &rot)))
  215264. rot->Revoke (graphRegistrationID);
  215265. }
  215266. static void deleteMediaType (AM_MEDIA_TYPE* const pmt)
  215267. {
  215268. if (pmt->cbFormat != 0)
  215269. CoTaskMemFree ((PVOID) pmt->pbFormat);
  215270. if (pmt->pUnk != 0)
  215271. pmt->pUnk->Release();
  215272. CoTaskMemFree (pmt);
  215273. }
  215274. class GrabberCallback : public ComBaseClassHelper <ISampleGrabberCB>
  215275. {
  215276. public:
  215277. GrabberCallback (DShowCameraDeviceInteral& owner_)
  215278. : owner (owner_)
  215279. {
  215280. }
  215281. STDMETHODIMP SampleCB (double /*SampleTime*/, IMediaSample* /*pSample*/)
  215282. {
  215283. return E_FAIL;
  215284. }
  215285. STDMETHODIMP BufferCB (double time, BYTE* buffer, long bufferSize)
  215286. {
  215287. owner.handleFrame (time, buffer, bufferSize);
  215288. return S_OK;
  215289. }
  215290. private:
  215291. DShowCameraDeviceInteral& owner;
  215292. GrabberCallback (const GrabberCallback&);
  215293. GrabberCallback& operator= (const GrabberCallback&);
  215294. };
  215295. ComSmartPtr <GrabberCallback> callback;
  215296. Array <CameraImageListener*> listeners;
  215297. CriticalSection listenerLock;
  215298. DShowCameraDeviceInteral (const DShowCameraDeviceInteral&);
  215299. DShowCameraDeviceInteral& operator= (const DShowCameraDeviceInteral&);
  215300. };
  215301. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  215302. : name (name_)
  215303. {
  215304. isRecording = false;
  215305. }
  215306. CameraDevice::~CameraDevice()
  215307. {
  215308. stopRecording();
  215309. delete static_cast <DShowCameraDeviceInteral*> (internal);
  215310. internal = 0;
  215311. }
  215312. Component* CameraDevice::createViewerComponent()
  215313. {
  215314. return new DShowCameraDeviceInteral::DShowCaptureViewerComp (static_cast <DShowCameraDeviceInteral*> (internal));
  215315. }
  215316. const String CameraDevice::getFileExtension()
  215317. {
  215318. return ".wmv";
  215319. }
  215320. void CameraDevice::startRecordingToFile (const File& file, int quality)
  215321. {
  215322. stopRecording();
  215323. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215324. d->addUser();
  215325. isRecording = d->createFileCaptureFilter (file);
  215326. }
  215327. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  215328. {
  215329. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215330. return d->firstRecordedTime;
  215331. }
  215332. void CameraDevice::stopRecording()
  215333. {
  215334. if (isRecording)
  215335. {
  215336. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215337. d->removeFileCaptureFilter();
  215338. d->removeUser();
  215339. isRecording = false;
  215340. }
  215341. }
  215342. void CameraDevice::addListener (CameraImageListener* listenerToAdd)
  215343. {
  215344. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215345. if (listenerToAdd != 0)
  215346. d->addListener (listenerToAdd);
  215347. }
  215348. void CameraDevice::removeListener (CameraImageListener* listenerToRemove)
  215349. {
  215350. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215351. if (listenerToRemove != 0)
  215352. d->removeListener (listenerToRemove);
  215353. }
  215354. static ComSmartPtr <IBaseFilter> enumerateCameras (StringArray* const names,
  215355. const int deviceIndexToOpen,
  215356. String& name)
  215357. {
  215358. int index = 0;
  215359. ComSmartPtr <IBaseFilter> result;
  215360. ComSmartPtr <ICreateDevEnum> pDevEnum;
  215361. HRESULT hr = pDevEnum.CoCreateInstance (CLSID_SystemDeviceEnum);
  215362. if (SUCCEEDED (hr))
  215363. {
  215364. ComSmartPtr <IEnumMoniker> enumerator;
  215365. hr = pDevEnum->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, &enumerator, 0);
  215366. if (SUCCEEDED (hr) && enumerator != 0)
  215367. {
  215368. ComSmartPtr <IBaseFilter> captureFilter;
  215369. ComSmartPtr <IMoniker> moniker;
  215370. ULONG fetched;
  215371. while (enumerator->Next (1, &moniker, &fetched) == S_OK)
  215372. {
  215373. hr = moniker->BindToObject (0, 0, IID_IBaseFilter, (void**) &captureFilter);
  215374. if (SUCCEEDED (hr))
  215375. {
  215376. ComSmartPtr <IPropertyBag> propertyBag;
  215377. hr = moniker->BindToStorage (0, 0, IID_IPropertyBag, (void**) &propertyBag);
  215378. if (SUCCEEDED (hr))
  215379. {
  215380. VARIANT var;
  215381. var.vt = VT_BSTR;
  215382. hr = propertyBag->Read (_T("FriendlyName"), &var, 0);
  215383. propertyBag = 0;
  215384. if (SUCCEEDED (hr))
  215385. {
  215386. if (names != 0)
  215387. names->add (var.bstrVal);
  215388. if (index == deviceIndexToOpen)
  215389. {
  215390. name = var.bstrVal;
  215391. result = captureFilter;
  215392. captureFilter = 0;
  215393. break;
  215394. }
  215395. ++index;
  215396. }
  215397. moniker = 0;
  215398. }
  215399. captureFilter = 0;
  215400. }
  215401. }
  215402. }
  215403. }
  215404. return result;
  215405. }
  215406. const StringArray CameraDevice::getAvailableDevices()
  215407. {
  215408. StringArray devs;
  215409. String dummy;
  215410. enumerateCameras (&devs, -1, dummy);
  215411. return devs;
  215412. }
  215413. CameraDevice* CameraDevice::openDevice (int index,
  215414. int minWidth, int minHeight,
  215415. int maxWidth, int maxHeight)
  215416. {
  215417. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  215418. HRESULT hr = captureGraphBuilder.CoCreateInstance (CLSID_CaptureGraphBuilder2);
  215419. if (SUCCEEDED (hr))
  215420. {
  215421. String name;
  215422. const ComSmartPtr <IBaseFilter> filter (enumerateCameras (0, index, name));
  215423. if (filter != 0)
  215424. {
  215425. ScopedPointer <CameraDevice> cam (new CameraDevice (name, index));
  215426. DShowCameraDeviceInteral* const intern
  215427. = new DShowCameraDeviceInteral (cam, captureGraphBuilder, filter,
  215428. minWidth, minHeight, maxWidth, maxHeight);
  215429. cam->internal = intern;
  215430. if (intern->ok)
  215431. return cam.release();
  215432. }
  215433. }
  215434. return 0;
  215435. }
  215436. #endif
  215437. /*** End of inlined file: juce_win32_CameraDevice.cpp ***/
  215438. #endif
  215439. // Auto-link the other win32 libs that are needed by library calls..
  215440. #if (JUCE_AMALGAMATED_TEMPLATE || defined (JUCE_DLL_BUILD)) && JUCE_MSVC && ! DONT_AUTOLINK_TO_WIN32_LIBRARIES
  215441. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  215442. // Auto-links to various win32 libs that are needed by library calls..
  215443. #pragma comment(lib, "kernel32.lib")
  215444. #pragma comment(lib, "user32.lib")
  215445. #pragma comment(lib, "shell32.lib")
  215446. #pragma comment(lib, "gdi32.lib")
  215447. #pragma comment(lib, "vfw32.lib")
  215448. #pragma comment(lib, "comdlg32.lib")
  215449. #pragma comment(lib, "winmm.lib")
  215450. #pragma comment(lib, "wininet.lib")
  215451. #pragma comment(lib, "ole32.lib")
  215452. #pragma comment(lib, "oleaut32.lib")
  215453. #pragma comment(lib, "advapi32.lib")
  215454. #pragma comment(lib, "ws2_32.lib")
  215455. #pragma comment(lib, "comsupp.lib")
  215456. #pragma comment(lib, "version.lib")
  215457. #if JUCE_OPENGL
  215458. #pragma comment(lib, "OpenGL32.Lib")
  215459. #pragma comment(lib, "GlU32.Lib")
  215460. #endif
  215461. #if JUCE_QUICKTIME
  215462. #pragma comment (lib, "QTMLClient.lib")
  215463. #endif
  215464. #if JUCE_USE_CAMERA
  215465. #pragma comment (lib, "Strmiids.lib")
  215466. #pragma comment (lib, "wmvcore.lib")
  215467. #endif
  215468. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  215469. #endif
  215470. END_JUCE_NAMESPACE
  215471. #endif
  215472. /*** End of inlined file: juce_win32_NativeCode.cpp ***/
  215473. #endif
  215474. #if JUCE_LINUX
  215475. /*** Start of inlined file: juce_linux_NativeCode.cpp ***/
  215476. /*
  215477. This file wraps together all the mac-specific code, so that
  215478. we can include all the native headers just once, and compile all our
  215479. platform-specific stuff in one big lump, keeping it out of the way of
  215480. the rest of the codebase.
  215481. */
  215482. #if JUCE_LINUX
  215483. BEGIN_JUCE_NAMESPACE
  215484. #define JUCE_INCLUDED_FILE 1
  215485. // Now include the actual code files..
  215486. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  215487. /*
  215488. This file contains posix routines that are common to both the Linux and Mac builds.
  215489. It gets included directly in the cpp files for these platforms.
  215490. */
  215491. CriticalSection::CriticalSection() throw()
  215492. {
  215493. pthread_mutexattr_t atts;
  215494. pthread_mutexattr_init (&atts);
  215495. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  215496. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  215497. pthread_mutex_init (&internal, &atts);
  215498. }
  215499. CriticalSection::~CriticalSection() throw()
  215500. {
  215501. pthread_mutex_destroy (&internal);
  215502. }
  215503. void CriticalSection::enter() const throw()
  215504. {
  215505. pthread_mutex_lock (&internal);
  215506. }
  215507. bool CriticalSection::tryEnter() const throw()
  215508. {
  215509. return pthread_mutex_trylock (&internal) == 0;
  215510. }
  215511. void CriticalSection::exit() const throw()
  215512. {
  215513. pthread_mutex_unlock (&internal);
  215514. }
  215515. class WaitableEventImpl
  215516. {
  215517. public:
  215518. WaitableEventImpl (const bool manualReset_)
  215519. : triggered (false),
  215520. manualReset (manualReset_)
  215521. {
  215522. pthread_cond_init (&condition, 0);
  215523. pthread_mutexattr_t atts;
  215524. pthread_mutexattr_init (&atts);
  215525. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  215526. pthread_mutex_init (&mutex, &atts);
  215527. }
  215528. ~WaitableEventImpl()
  215529. {
  215530. pthread_cond_destroy (&condition);
  215531. pthread_mutex_destroy (&mutex);
  215532. }
  215533. bool wait (const int timeOutMillisecs) throw()
  215534. {
  215535. pthread_mutex_lock (&mutex);
  215536. if (! triggered)
  215537. {
  215538. if (timeOutMillisecs < 0)
  215539. {
  215540. do
  215541. {
  215542. pthread_cond_wait (&condition, &mutex);
  215543. }
  215544. while (! triggered);
  215545. }
  215546. else
  215547. {
  215548. struct timeval now;
  215549. gettimeofday (&now, 0);
  215550. struct timespec time;
  215551. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  215552. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  215553. if (time.tv_nsec >= 1000000000)
  215554. {
  215555. time.tv_nsec -= 1000000000;
  215556. time.tv_sec++;
  215557. }
  215558. do
  215559. {
  215560. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  215561. {
  215562. pthread_mutex_unlock (&mutex);
  215563. return false;
  215564. }
  215565. }
  215566. while (! triggered);
  215567. }
  215568. }
  215569. if (! manualReset)
  215570. triggered = false;
  215571. pthread_mutex_unlock (&mutex);
  215572. return true;
  215573. }
  215574. void signal() throw()
  215575. {
  215576. pthread_mutex_lock (&mutex);
  215577. triggered = true;
  215578. pthread_cond_broadcast (&condition);
  215579. pthread_mutex_unlock (&mutex);
  215580. }
  215581. void reset() throw()
  215582. {
  215583. pthread_mutex_lock (&mutex);
  215584. triggered = false;
  215585. pthread_mutex_unlock (&mutex);
  215586. }
  215587. private:
  215588. pthread_cond_t condition;
  215589. pthread_mutex_t mutex;
  215590. bool triggered;
  215591. const bool manualReset;
  215592. WaitableEventImpl (const WaitableEventImpl&);
  215593. WaitableEventImpl& operator= (const WaitableEventImpl&);
  215594. };
  215595. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  215596. : internal (new WaitableEventImpl (manualReset))
  215597. {
  215598. }
  215599. WaitableEvent::~WaitableEvent() throw()
  215600. {
  215601. delete static_cast <WaitableEventImpl*> (internal);
  215602. }
  215603. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  215604. {
  215605. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  215606. }
  215607. void WaitableEvent::signal() const throw()
  215608. {
  215609. static_cast <WaitableEventImpl*> (internal)->signal();
  215610. }
  215611. void WaitableEvent::reset() const throw()
  215612. {
  215613. static_cast <WaitableEventImpl*> (internal)->reset();
  215614. }
  215615. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  215616. {
  215617. struct timespec time;
  215618. time.tv_sec = millisecs / 1000;
  215619. time.tv_nsec = (millisecs % 1000) * 1000000;
  215620. nanosleep (&time, 0);
  215621. }
  215622. const juce_wchar File::separator = '/';
  215623. const String File::separatorString ("/");
  215624. const File File::getCurrentWorkingDirectory()
  215625. {
  215626. HeapBlock<char> heapBuffer;
  215627. char localBuffer [1024];
  215628. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  215629. int bufferSize = 4096;
  215630. while (cwd == 0 && errno == ERANGE)
  215631. {
  215632. heapBuffer.malloc (bufferSize);
  215633. cwd = getcwd (heapBuffer, bufferSize - 1);
  215634. bufferSize += 1024;
  215635. }
  215636. return File (String::fromUTF8 (cwd));
  215637. }
  215638. bool File::setAsCurrentWorkingDirectory() const
  215639. {
  215640. return chdir (getFullPathName().toUTF8()) == 0;
  215641. }
  215642. static bool juce_stat (const String& fileName, struct stat& info)
  215643. {
  215644. return fileName.isNotEmpty()
  215645. && (stat (fileName.toUTF8(), &info) == 0);
  215646. }
  215647. bool File::isDirectory() const
  215648. {
  215649. struct stat info;
  215650. return fullPath.isEmpty()
  215651. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  215652. }
  215653. bool File::exists() const
  215654. {
  215655. return fullPath.isNotEmpty()
  215656. && access (fullPath.toUTF8(), F_OK) == 0;
  215657. }
  215658. bool File::existsAsFile() const
  215659. {
  215660. return exists() && ! isDirectory();
  215661. }
  215662. int64 File::getSize() const
  215663. {
  215664. struct stat info;
  215665. return juce_stat (fullPath, info) ? info.st_size : 0;
  215666. }
  215667. bool File::hasWriteAccess() const
  215668. {
  215669. if (exists())
  215670. return access (fullPath.toUTF8(), W_OK) == 0;
  215671. if ((! isDirectory()) && fullPath.containsChar (separator))
  215672. return getParentDirectory().hasWriteAccess();
  215673. return false;
  215674. }
  215675. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  215676. {
  215677. struct stat info;
  215678. const int res = stat (fullPath.toUTF8(), &info);
  215679. if (res != 0)
  215680. return false;
  215681. info.st_mode &= 0777; // Just permissions
  215682. if (shouldBeReadOnly)
  215683. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  215684. else
  215685. // Give everybody write permission?
  215686. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  215687. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  215688. }
  215689. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  215690. {
  215691. modificationTime = 0;
  215692. accessTime = 0;
  215693. creationTime = 0;
  215694. struct stat info;
  215695. const int res = stat (fullPath.toUTF8(), &info);
  215696. if (res == 0)
  215697. {
  215698. modificationTime = (int64) info.st_mtime * 1000;
  215699. accessTime = (int64) info.st_atime * 1000;
  215700. creationTime = (int64) info.st_ctime * 1000;
  215701. }
  215702. }
  215703. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  215704. {
  215705. struct utimbuf times;
  215706. times.actime = (time_t) (accessTime / 1000);
  215707. times.modtime = (time_t) (modificationTime / 1000);
  215708. return utime (fullPath.toUTF8(), &times) == 0;
  215709. }
  215710. bool File::deleteFile() const
  215711. {
  215712. if (! exists())
  215713. return true;
  215714. else if (isDirectory())
  215715. return rmdir (fullPath.toUTF8()) == 0;
  215716. else
  215717. return remove (fullPath.toUTF8()) == 0;
  215718. }
  215719. bool File::moveInternal (const File& dest) const
  215720. {
  215721. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  215722. return true;
  215723. if (hasWriteAccess() && copyInternal (dest))
  215724. {
  215725. if (deleteFile())
  215726. return true;
  215727. dest.deleteFile();
  215728. }
  215729. return false;
  215730. }
  215731. void File::createDirectoryInternal (const String& fileName) const
  215732. {
  215733. mkdir (fileName.toUTF8(), 0777);
  215734. }
  215735. void* juce_fileOpen (const File& file, bool forWriting)
  215736. {
  215737. int flags = O_RDONLY;
  215738. if (forWriting)
  215739. {
  215740. if (file.exists())
  215741. {
  215742. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  215743. if (f != -1)
  215744. lseek (f, 0, SEEK_END);
  215745. return (void*) f;
  215746. }
  215747. else
  215748. {
  215749. flags = O_RDWR + O_CREAT;
  215750. }
  215751. }
  215752. return (void*) open (file.getFullPathName().toUTF8(), flags, 00644);
  215753. }
  215754. void juce_fileClose (void* handle)
  215755. {
  215756. if (handle != 0)
  215757. close ((int) (pointer_sized_int) handle);
  215758. }
  215759. int juce_fileRead (void* handle, void* buffer, int size)
  215760. {
  215761. if (handle != 0)
  215762. return jmax (0, (int) read ((int) (pointer_sized_int) handle, buffer, size));
  215763. return 0;
  215764. }
  215765. int juce_fileWrite (void* handle, const void* buffer, int size)
  215766. {
  215767. if (handle != 0)
  215768. return (int) write ((int) (pointer_sized_int) handle, buffer, size);
  215769. return 0;
  215770. }
  215771. int64 juce_fileSetPosition (void* handle, int64 pos)
  215772. {
  215773. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  215774. return pos;
  215775. return -1;
  215776. }
  215777. int64 FileOutputStream::getPositionInternal() const
  215778. {
  215779. if (fileHandle != 0)
  215780. return lseek ((int) (pointer_sized_int) fileHandle, 0, SEEK_CUR);
  215781. return -1;
  215782. }
  215783. void FileOutputStream::flushInternal()
  215784. {
  215785. if (fileHandle != 0)
  215786. fsync ((int) (pointer_sized_int) fileHandle);
  215787. }
  215788. const File juce_getExecutableFile()
  215789. {
  215790. Dl_info exeInfo;
  215791. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  215792. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  215793. }
  215794. // if this file doesn't exist, find a parent of it that does..
  215795. static bool juce_doStatFS (File f, struct statfs& result)
  215796. {
  215797. for (int i = 5; --i >= 0;)
  215798. {
  215799. if (f.exists())
  215800. break;
  215801. f = f.getParentDirectory();
  215802. }
  215803. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  215804. }
  215805. int64 File::getBytesFreeOnVolume() const
  215806. {
  215807. struct statfs buf;
  215808. if (juce_doStatFS (*this, buf))
  215809. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  215810. return 0;
  215811. }
  215812. int64 File::getVolumeTotalSize() const
  215813. {
  215814. struct statfs buf;
  215815. if (juce_doStatFS (*this, buf))
  215816. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  215817. return 0;
  215818. }
  215819. const String File::getVolumeLabel() const
  215820. {
  215821. #if JUCE_MAC
  215822. struct VolAttrBuf
  215823. {
  215824. u_int32_t length;
  215825. attrreference_t mountPointRef;
  215826. char mountPointSpace [MAXPATHLEN];
  215827. } attrBuf;
  215828. struct attrlist attrList;
  215829. zerostruct (attrList);
  215830. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  215831. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  215832. File f (*this);
  215833. for (;;)
  215834. {
  215835. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  215836. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  215837. (int) attrBuf.mountPointRef.attr_length);
  215838. const File parent (f.getParentDirectory());
  215839. if (f == parent)
  215840. break;
  215841. f = parent;
  215842. }
  215843. #endif
  215844. return String::empty;
  215845. }
  215846. int File::getVolumeSerialNumber() const
  215847. {
  215848. return 0; // xxx
  215849. }
  215850. void juce_runSystemCommand (const String& command)
  215851. {
  215852. int result = system (command.toUTF8());
  215853. (void) result;
  215854. }
  215855. const String juce_getOutputFromCommand (const String& command)
  215856. {
  215857. // slight bodge here, as we just pipe the output into a temp file and read it...
  215858. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  215859. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  215860. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  215861. String result (tempFile.loadFileAsString());
  215862. tempFile.deleteFile();
  215863. return result;
  215864. }
  215865. class InterProcessLock::Pimpl
  215866. {
  215867. public:
  215868. Pimpl (const String& name, const int timeOutMillisecs)
  215869. : handle (0), refCount (1)
  215870. {
  215871. #if JUCE_MAC
  215872. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  215873. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  215874. #else
  215875. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  215876. #endif
  215877. temp.create();
  215878. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  215879. if (handle != 0)
  215880. {
  215881. struct flock fl;
  215882. zerostruct (fl);
  215883. fl.l_whence = SEEK_SET;
  215884. fl.l_type = F_WRLCK;
  215885. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  215886. for (;;)
  215887. {
  215888. const int result = fcntl (handle, F_SETLK, &fl);
  215889. if (result >= 0)
  215890. return;
  215891. if (errno != EINTR)
  215892. {
  215893. if (timeOutMillisecs == 0
  215894. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  215895. break;
  215896. Thread::sleep (10);
  215897. }
  215898. }
  215899. }
  215900. closeFile();
  215901. }
  215902. ~Pimpl()
  215903. {
  215904. closeFile();
  215905. }
  215906. void closeFile()
  215907. {
  215908. if (handle != 0)
  215909. {
  215910. struct flock fl;
  215911. zerostruct (fl);
  215912. fl.l_whence = SEEK_SET;
  215913. fl.l_type = F_UNLCK;
  215914. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  215915. {}
  215916. close (handle);
  215917. handle = 0;
  215918. }
  215919. }
  215920. int handle, refCount;
  215921. };
  215922. InterProcessLock::InterProcessLock (const String& name_)
  215923. : name (name_)
  215924. {
  215925. }
  215926. InterProcessLock::~InterProcessLock()
  215927. {
  215928. }
  215929. bool InterProcessLock::enter (const int timeOutMillisecs)
  215930. {
  215931. const ScopedLock sl (lock);
  215932. if (pimpl == 0)
  215933. {
  215934. pimpl = new Pimpl (name, timeOutMillisecs);
  215935. if (pimpl->handle == 0)
  215936. pimpl = 0;
  215937. }
  215938. else
  215939. {
  215940. pimpl->refCount++;
  215941. }
  215942. return pimpl != 0;
  215943. }
  215944. void InterProcessLock::exit()
  215945. {
  215946. const ScopedLock sl (lock);
  215947. // Trying to release the lock too many times!
  215948. jassert (pimpl != 0);
  215949. if (pimpl != 0 && --(pimpl->refCount) == 0)
  215950. pimpl = 0;
  215951. }
  215952. /*** End of inlined file: juce_posix_SharedCode.h ***/
  215953. /*** Start of inlined file: juce_linux_Files.cpp ***/
  215954. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  215955. // compiled on its own).
  215956. #if JUCE_INCLUDED_FILE
  215957. static const short U_ISOFS_SUPER_MAGIC = 0x9660; // linux/iso_fs.h
  215958. static const short U_MSDOS_SUPER_MAGIC = 0x4d44; // linux/msdos_fs.h
  215959. static const short U_NFS_SUPER_MAGIC = 0x6969; // linux/nfs_fs.h
  215960. static const short U_SMB_SUPER_MAGIC = 0x517B; // linux/smb_fs.h
  215961. bool File::copyInternal (const File& dest) const
  215962. {
  215963. FileInputStream in (*this);
  215964. if (dest.deleteFile())
  215965. {
  215966. {
  215967. FileOutputStream out (dest);
  215968. if (out.failedToOpen())
  215969. return false;
  215970. if (out.writeFromInputStream (in, -1) == getSize())
  215971. return true;
  215972. }
  215973. dest.deleteFile();
  215974. }
  215975. return false;
  215976. }
  215977. void File::findFileSystemRoots (Array<File>& destArray)
  215978. {
  215979. destArray.add (File ("/"));
  215980. }
  215981. bool File::isOnCDRomDrive() const
  215982. {
  215983. struct statfs buf;
  215984. return statfs (getFullPathName().toUTF8(), &buf) == 0
  215985. && buf.f_type == U_ISOFS_SUPER_MAGIC;
  215986. }
  215987. bool File::isOnHardDisk() const
  215988. {
  215989. struct statfs buf;
  215990. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  215991. {
  215992. switch (buf.f_type)
  215993. {
  215994. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  215995. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  215996. case U_NFS_SUPER_MAGIC: // Network NFS
  215997. case U_SMB_SUPER_MAGIC: // Network Samba
  215998. return false;
  215999. default:
  216000. // Assume anything else is a hard-disk (but note it could
  216001. // be a RAM disk. There isn't a good way of determining
  216002. // this for sure)
  216003. return true;
  216004. }
  216005. }
  216006. // Assume so if this fails for some reason
  216007. return true;
  216008. }
  216009. bool File::isOnRemovableDrive() const
  216010. {
  216011. jassertfalse; // xxx not implemented for linux!
  216012. return false;
  216013. }
  216014. bool File::isHidden() const
  216015. {
  216016. return getFileName().startsWithChar ('.');
  216017. }
  216018. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  216019. const File File::getSpecialLocation (const SpecialLocationType type)
  216020. {
  216021. switch (type)
  216022. {
  216023. case userHomeDirectory:
  216024. {
  216025. const char* homeDir = getenv ("HOME");
  216026. if (homeDir == 0)
  216027. {
  216028. struct passwd* const pw = getpwuid (getuid());
  216029. if (pw != 0)
  216030. homeDir = pw->pw_dir;
  216031. }
  216032. return File (String::fromUTF8 (homeDir));
  216033. }
  216034. case userDocumentsDirectory:
  216035. case userMusicDirectory:
  216036. case userMoviesDirectory:
  216037. case userApplicationDataDirectory:
  216038. return File ("~");
  216039. case userDesktopDirectory:
  216040. return File ("~/Desktop");
  216041. case commonApplicationDataDirectory:
  216042. return File ("/var");
  216043. case globalApplicationsDirectory:
  216044. return File ("/usr");
  216045. case tempDirectory:
  216046. {
  216047. File tmp ("/var/tmp");
  216048. if (! tmp.isDirectory())
  216049. {
  216050. tmp = "/tmp";
  216051. if (! tmp.isDirectory())
  216052. tmp = File::getCurrentWorkingDirectory();
  216053. }
  216054. return tmp;
  216055. }
  216056. case invokedExecutableFile:
  216057. if (juce_Argv0 != 0)
  216058. return File (String::fromUTF8 (juce_Argv0));
  216059. // deliberate fall-through...
  216060. case currentExecutableFile:
  216061. case currentApplicationFile:
  216062. return juce_getExecutableFile();
  216063. default:
  216064. jassertfalse; // unknown type?
  216065. break;
  216066. }
  216067. return File::nonexistent;
  216068. }
  216069. const String File::getVersion() const
  216070. {
  216071. return String::empty; // xxx not yet implemented
  216072. }
  216073. const File File::getLinkedTarget() const
  216074. {
  216075. char buffer [4096];
  216076. size_t numChars = readlink (getFullPathName().toUTF8(),
  216077. buffer, sizeof (buffer));
  216078. if (numChars > 0 && numChars <= sizeof (buffer))
  216079. return File (String::fromUTF8 (buffer, (int) numChars));
  216080. return *this;
  216081. }
  216082. bool File::moveToTrash() const
  216083. {
  216084. if (! exists())
  216085. return true;
  216086. File trashCan ("~/.Trash");
  216087. if (! trashCan.isDirectory())
  216088. trashCan = "~/.local/share/Trash/files";
  216089. if (! trashCan.isDirectory())
  216090. return false;
  216091. return moveFileTo (trashCan.getNonexistentChildFile (getFileNameWithoutExtension(),
  216092. getFileExtension()));
  216093. }
  216094. class DirectoryIterator::NativeIterator::Pimpl
  216095. {
  216096. public:
  216097. Pimpl (const File& directory, const String& wildCard_)
  216098. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  216099. wildCard (wildCard_),
  216100. dir (opendir (directory.getFullPathName().toUTF8()))
  216101. {
  216102. if (wildCard == "*.*")
  216103. wildCard = "*";
  216104. wildcardUTF8 = wildCard.toUTF8();
  216105. }
  216106. ~Pimpl()
  216107. {
  216108. if (dir != 0)
  216109. closedir (dir);
  216110. }
  216111. bool next (String& filenameFound,
  216112. bool* const isDir, bool* const isHidden, int64* const fileSize,
  216113. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  216114. {
  216115. if (dir == 0)
  216116. return false;
  216117. for (;;)
  216118. {
  216119. struct dirent* const de = readdir (dir);
  216120. if (de == 0)
  216121. return false;
  216122. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  216123. {
  216124. filenameFound = String::fromUTF8 (de->d_name);
  216125. const String path (parentDir + filenameFound);
  216126. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  216127. {
  216128. struct stat info;
  216129. const bool statOk = juce_stat (path, info);
  216130. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  216131. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  216132. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  216133. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  216134. }
  216135. if (isHidden != 0)
  216136. *isHidden = filenameFound.startsWithChar ('.');
  216137. if (isReadOnly != 0)
  216138. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  216139. return true;
  216140. }
  216141. }
  216142. }
  216143. private:
  216144. String parentDir, wildCard;
  216145. const char* wildcardUTF8;
  216146. DIR* dir;
  216147. Pimpl (const Pimpl&);
  216148. Pimpl& operator= (const Pimpl&);
  216149. };
  216150. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  216151. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  216152. {
  216153. }
  216154. DirectoryIterator::NativeIterator::~NativeIterator()
  216155. {
  216156. }
  216157. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  216158. bool* const isDir, bool* const isHidden, int64* const fileSize,
  216159. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  216160. {
  216161. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  216162. }
  216163. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  216164. {
  216165. String cmdString (fileName.replace (" ", "\\ ",false));
  216166. cmdString << " " << parameters;
  216167. if (URL::isProbablyAWebsiteURL (fileName)
  216168. || cmdString.startsWithIgnoreCase ("file:")
  216169. || URL::isProbablyAnEmailAddress (fileName))
  216170. {
  216171. // create a command that tries to launch a bunch of likely browsers
  216172. const char* const browserNames[] = { "xdg-open", "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  216173. StringArray cmdLines;
  216174. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  216175. cmdLines.add (String (browserNames[i]) + " " + cmdString.trim().quoted());
  216176. cmdString = cmdLines.joinIntoString (" || ");
  216177. }
  216178. const char* const argv[4] = { "/bin/sh", "-c", cmdString.toUTF8(), 0 };
  216179. const int cpid = fork();
  216180. if (cpid == 0)
  216181. {
  216182. setsid();
  216183. // Child process
  216184. execve (argv[0], (char**) argv, environ);
  216185. exit (0);
  216186. }
  216187. return cpid >= 0;
  216188. }
  216189. void File::revealToUser() const
  216190. {
  216191. if (isDirectory())
  216192. startAsProcess();
  216193. else if (getParentDirectory().exists())
  216194. getParentDirectory().startAsProcess();
  216195. }
  216196. #endif
  216197. /*** End of inlined file: juce_linux_Files.cpp ***/
  216198. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  216199. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  216200. // compiled on its own).
  216201. #if JUCE_INCLUDED_FILE
  216202. struct NamedPipeInternal
  216203. {
  216204. String pipeInName, pipeOutName;
  216205. int pipeIn, pipeOut;
  216206. bool volatile createdPipe, blocked, stopReadOperation;
  216207. static void signalHandler (int) {}
  216208. };
  216209. void NamedPipe::cancelPendingReads()
  216210. {
  216211. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  216212. {
  216213. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  216214. intern->stopReadOperation = true;
  216215. char buffer [1] = { 0 };
  216216. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  216217. (void) bytesWritten;
  216218. int timeout = 2000;
  216219. while (intern->blocked && --timeout >= 0)
  216220. Thread::sleep (2);
  216221. intern->stopReadOperation = false;
  216222. }
  216223. }
  216224. void NamedPipe::close()
  216225. {
  216226. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  216227. if (intern != 0)
  216228. {
  216229. internal = 0;
  216230. if (intern->pipeIn != -1)
  216231. ::close (intern->pipeIn);
  216232. if (intern->pipeOut != -1)
  216233. ::close (intern->pipeOut);
  216234. if (intern->createdPipe)
  216235. {
  216236. unlink (intern->pipeInName.toUTF8());
  216237. unlink (intern->pipeOutName.toUTF8());
  216238. }
  216239. delete intern;
  216240. }
  216241. }
  216242. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  216243. {
  216244. close();
  216245. NamedPipeInternal* const intern = new NamedPipeInternal();
  216246. internal = intern;
  216247. intern->createdPipe = createPipe;
  216248. intern->blocked = false;
  216249. intern->stopReadOperation = false;
  216250. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  216251. siginterrupt (SIGPIPE, 1);
  216252. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  216253. intern->pipeInName = pipePath + "_in";
  216254. intern->pipeOutName = pipePath + "_out";
  216255. intern->pipeIn = -1;
  216256. intern->pipeOut = -1;
  216257. if (createPipe)
  216258. {
  216259. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  216260. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  216261. {
  216262. delete intern;
  216263. internal = 0;
  216264. return false;
  216265. }
  216266. }
  216267. return true;
  216268. }
  216269. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  216270. {
  216271. int bytesRead = -1;
  216272. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  216273. if (intern != 0)
  216274. {
  216275. intern->blocked = true;
  216276. if (intern->pipeIn == -1)
  216277. {
  216278. if (intern->createdPipe)
  216279. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  216280. else
  216281. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  216282. if (intern->pipeIn == -1)
  216283. {
  216284. intern->blocked = false;
  216285. return -1;
  216286. }
  216287. }
  216288. bytesRead = 0;
  216289. char* p = (char*) destBuffer;
  216290. while (bytesRead < maxBytesToRead)
  216291. {
  216292. const int bytesThisTime = maxBytesToRead - bytesRead;
  216293. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  216294. if (numRead <= 0 || intern->stopReadOperation)
  216295. {
  216296. bytesRead = -1;
  216297. break;
  216298. }
  216299. bytesRead += numRead;
  216300. p += bytesRead;
  216301. }
  216302. intern->blocked = false;
  216303. }
  216304. return bytesRead;
  216305. }
  216306. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  216307. {
  216308. int bytesWritten = -1;
  216309. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  216310. if (intern != 0)
  216311. {
  216312. if (intern->pipeOut == -1)
  216313. {
  216314. if (intern->createdPipe)
  216315. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  216316. else
  216317. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  216318. if (intern->pipeOut == -1)
  216319. {
  216320. return -1;
  216321. }
  216322. }
  216323. const char* p = (const char*) sourceBuffer;
  216324. bytesWritten = 0;
  216325. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  216326. while (bytesWritten < numBytesToWrite
  216327. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  216328. {
  216329. const int bytesThisTime = numBytesToWrite - bytesWritten;
  216330. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  216331. if (numWritten <= 0)
  216332. {
  216333. bytesWritten = -1;
  216334. break;
  216335. }
  216336. bytesWritten += numWritten;
  216337. p += bytesWritten;
  216338. }
  216339. }
  216340. return bytesWritten;
  216341. }
  216342. #endif
  216343. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  216344. /*** Start of inlined file: juce_linux_Network.cpp ***/
  216345. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  216346. // compiled on its own).
  216347. #if JUCE_INCLUDED_FILE
  216348. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  216349. {
  216350. int numResults = 0;
  216351. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  216352. if (s != -1)
  216353. {
  216354. char buf [1024];
  216355. struct ifconf ifc;
  216356. ifc.ifc_len = sizeof (buf);
  216357. ifc.ifc_buf = buf;
  216358. ioctl (s, SIOCGIFCONF, &ifc);
  216359. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  216360. {
  216361. struct ifreq ifr;
  216362. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  216363. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  216364. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  216365. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0
  216366. && numResults < maxNum)
  216367. {
  216368. int64 a = 0;
  216369. for (int j = 6; --j >= 0;)
  216370. a = (a << 8) | (uint8) ifr.ifr_hwaddr.sa_data [littleEndian ? j : (5 - j)];
  216371. *addresses++ = a;
  216372. ++numResults;
  216373. }
  216374. }
  216375. close (s);
  216376. }
  216377. return numResults;
  216378. }
  216379. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  216380. const String& emailSubject,
  216381. const String& bodyText,
  216382. const StringArray& filesToAttach)
  216383. {
  216384. jassertfalse; // xxx todo
  216385. return false;
  216386. }
  216387. /** A HTTP input stream that uses sockets.
  216388. */
  216389. class JUCE_HTTPSocketStream
  216390. {
  216391. public:
  216392. JUCE_HTTPSocketStream()
  216393. : readPosition (0),
  216394. socketHandle (-1),
  216395. levelsOfRedirection (0),
  216396. timeoutSeconds (15)
  216397. {
  216398. }
  216399. ~JUCE_HTTPSocketStream()
  216400. {
  216401. closeSocket();
  216402. }
  216403. bool open (const String& url,
  216404. const String& headers,
  216405. const MemoryBlock& postData,
  216406. const bool isPost,
  216407. URL::OpenStreamProgressCallback* callback,
  216408. void* callbackContext,
  216409. int timeOutMs)
  216410. {
  216411. closeSocket();
  216412. uint32 timeOutTime = Time::getMillisecondCounter();
  216413. if (timeOutMs == 0)
  216414. timeOutTime += 60000;
  216415. else if (timeOutMs < 0)
  216416. timeOutTime = 0xffffffff;
  216417. else
  216418. timeOutTime += timeOutMs;
  216419. String hostName, hostPath;
  216420. int hostPort;
  216421. if (! decomposeURL (url, hostName, hostPath, hostPort))
  216422. return false;
  216423. const struct hostent* host = 0;
  216424. int port = 0;
  216425. String proxyName, proxyPath;
  216426. int proxyPort = 0;
  216427. String proxyURL (getenv ("http_proxy"));
  216428. if (proxyURL.startsWithIgnoreCase ("http://"))
  216429. {
  216430. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  216431. return false;
  216432. host = gethostbyname (proxyName.toUTF8());
  216433. port = proxyPort;
  216434. }
  216435. else
  216436. {
  216437. host = gethostbyname (hostName.toUTF8());
  216438. port = hostPort;
  216439. }
  216440. if (host == 0)
  216441. return false;
  216442. struct sockaddr_in address;
  216443. zerostruct (address);
  216444. memcpy (&address.sin_addr, host->h_addr, host->h_length);
  216445. address.sin_family = host->h_addrtype;
  216446. address.sin_port = htons (port);
  216447. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  216448. if (socketHandle == -1)
  216449. return false;
  216450. int receiveBufferSize = 16384;
  216451. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  216452. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  216453. #if JUCE_MAC
  216454. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  216455. #endif
  216456. if (connect (socketHandle, (struct sockaddr*) &address, sizeof (address)) == -1)
  216457. {
  216458. closeSocket();
  216459. return false;
  216460. }
  216461. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort,
  216462. proxyName, proxyPort,
  216463. hostPath, url,
  216464. headers, postData,
  216465. isPost));
  216466. size_t totalHeaderSent = 0;
  216467. while (totalHeaderSent < requestHeader.getSize())
  216468. {
  216469. if (Time::getMillisecondCounter() > timeOutTime)
  216470. {
  216471. closeSocket();
  216472. return false;
  216473. }
  216474. const int numToSend = jmin (1024, (int) (requestHeader.getSize() - totalHeaderSent));
  216475. if (send (socketHandle,
  216476. ((const char*) requestHeader.getData()) + totalHeaderSent,
  216477. numToSend, 0)
  216478. != numToSend)
  216479. {
  216480. closeSocket();
  216481. return false;
  216482. }
  216483. totalHeaderSent += numToSend;
  216484. if (callback != 0 && ! callback (callbackContext, totalHeaderSent, requestHeader.getSize()))
  216485. {
  216486. closeSocket();
  216487. return false;
  216488. }
  216489. }
  216490. const String responseHeader (readResponse (timeOutTime));
  216491. if (responseHeader.isNotEmpty())
  216492. {
  216493. //DBG (responseHeader);
  216494. headerLines.clear();
  216495. headerLines.addLines (responseHeader);
  216496. const int statusCode = responseHeader.fromFirstOccurrenceOf (" ", false, false)
  216497. .substring (0, 3).getIntValue();
  216498. //int contentLength = findHeaderItem (lines, "Content-Length:").getIntValue();
  216499. //bool isChunked = findHeaderItem (lines, "Transfer-Encoding:").equalsIgnoreCase ("chunked");
  216500. String location (findHeaderItem (headerLines, "Location:"));
  216501. if (statusCode >= 300 && statusCode < 400
  216502. && location.isNotEmpty())
  216503. {
  216504. if (! location.startsWithIgnoreCase ("http://"))
  216505. location = "http://" + location;
  216506. if (levelsOfRedirection++ < 3)
  216507. return open (location, headers, postData, isPost, callback, callbackContext, timeOutMs);
  216508. }
  216509. else
  216510. {
  216511. levelsOfRedirection = 0;
  216512. return true;
  216513. }
  216514. }
  216515. closeSocket();
  216516. return false;
  216517. }
  216518. int read (void* buffer, int bytesToRead)
  216519. {
  216520. fd_set readbits;
  216521. FD_ZERO (&readbits);
  216522. FD_SET (socketHandle, &readbits);
  216523. struct timeval tv;
  216524. tv.tv_sec = timeoutSeconds;
  216525. tv.tv_usec = 0;
  216526. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  216527. return 0; // (timeout)
  216528. const int bytesRead = jmax (0, (int) recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  216529. readPosition += bytesRead;
  216530. return bytesRead;
  216531. }
  216532. int readPosition;
  216533. StringArray headerLines;
  216534. juce_UseDebuggingNewOperator
  216535. private:
  216536. int socketHandle, levelsOfRedirection;
  216537. const int timeoutSeconds;
  216538. void closeSocket()
  216539. {
  216540. if (socketHandle >= 0)
  216541. close (socketHandle);
  216542. socketHandle = -1;
  216543. }
  216544. const MemoryBlock createRequestHeader (const String& hostName,
  216545. const int hostPort,
  216546. const String& proxyName,
  216547. const int proxyPort,
  216548. const String& hostPath,
  216549. const String& originalURL,
  216550. const String& headers,
  216551. const MemoryBlock& postData,
  216552. const bool isPost)
  216553. {
  216554. String header (isPost ? "POST " : "GET ");
  216555. if (proxyName.isEmpty())
  216556. {
  216557. header << hostPath << " HTTP/1.0\r\nHost: "
  216558. << hostName << ':' << hostPort;
  216559. }
  216560. else
  216561. {
  216562. header << originalURL << " HTTP/1.0\r\nHost: "
  216563. << proxyName << ':' << proxyPort;
  216564. }
  216565. header << "\r\nUser-Agent: JUCE/"
  216566. << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  216567. << "\r\nConnection: Close\r\nContent-Length: "
  216568. << postData.getSize() << "\r\n"
  216569. << headers << "\r\n";
  216570. MemoryBlock mb;
  216571. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  216572. mb.append (postData.getData(), postData.getSize());
  216573. return mb;
  216574. }
  216575. const String readResponse (const uint32 timeOutTime)
  216576. {
  216577. int bytesRead = 0, numConsecutiveLFs = 0;
  216578. MemoryBlock buffer (1024, true);
  216579. while (numConsecutiveLFs < 2 && bytesRead < 32768
  216580. && Time::getMillisecondCounter() <= timeOutTime)
  216581. {
  216582. fd_set readbits;
  216583. FD_ZERO (&readbits);
  216584. FD_SET (socketHandle, &readbits);
  216585. struct timeval tv;
  216586. tv.tv_sec = timeoutSeconds;
  216587. tv.tv_usec = 0;
  216588. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  216589. return String::empty; // (timeout)
  216590. buffer.ensureSize (bytesRead + 8, true);
  216591. char* const dest = (char*) buffer.getData() + bytesRead;
  216592. if (recv (socketHandle, dest, 1, 0) == -1)
  216593. return String::empty;
  216594. const char lastByte = *dest;
  216595. ++bytesRead;
  216596. if (lastByte == '\n')
  216597. ++numConsecutiveLFs;
  216598. else if (lastByte != '\r')
  216599. numConsecutiveLFs = 0;
  216600. }
  216601. const String header (String::fromUTF8 ((const char*) buffer.getData()));
  216602. if (header.startsWithIgnoreCase ("HTTP/"))
  216603. return header.trimEnd();
  216604. return String::empty;
  216605. }
  216606. static bool decomposeURL (const String& url,
  216607. String& host, String& path, int& port)
  216608. {
  216609. if (! url.startsWithIgnoreCase ("http://"))
  216610. return false;
  216611. const int nextSlash = url.indexOfChar (7, '/');
  216612. int nextColon = url.indexOfChar (7, ':');
  216613. if (nextColon > nextSlash && nextSlash > 0)
  216614. nextColon = -1;
  216615. if (nextColon >= 0)
  216616. {
  216617. host = url.substring (7, nextColon);
  216618. if (nextSlash >= 0)
  216619. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  216620. else
  216621. port = url.substring (nextColon + 1).getIntValue();
  216622. }
  216623. else
  216624. {
  216625. port = 80;
  216626. if (nextSlash >= 0)
  216627. host = url.substring (7, nextSlash);
  216628. else
  216629. host = url.substring (7);
  216630. }
  216631. if (nextSlash >= 0)
  216632. path = url.substring (nextSlash);
  216633. else
  216634. path = "/";
  216635. return true;
  216636. }
  216637. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  216638. {
  216639. for (int i = 0; i < lines.size(); ++i)
  216640. if (lines[i].startsWithIgnoreCase (itemName))
  216641. return lines[i].substring (itemName.length()).trim();
  216642. return String::empty;
  216643. }
  216644. };
  216645. void* juce_openInternetFile (const String& url,
  216646. const String& headers,
  216647. const MemoryBlock& postData,
  216648. const bool isPost,
  216649. URL::OpenStreamProgressCallback* callback,
  216650. void* callbackContext,
  216651. int timeOutMs)
  216652. {
  216653. ScopedPointer<JUCE_HTTPSocketStream> s (new JUCE_HTTPSocketStream());
  216654. if (s->open (url, headers, postData, isPost, callback, callbackContext, timeOutMs))
  216655. return s.release();
  216656. return 0;
  216657. }
  216658. void juce_closeInternetFile (void* handle)
  216659. {
  216660. delete static_cast <JUCE_HTTPSocketStream*> (handle);
  216661. }
  216662. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  216663. {
  216664. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  216665. return s != 0 ? s->read (buffer, bytesToRead) : 0;
  216666. }
  216667. int64 juce_getInternetFileContentLength (void* handle)
  216668. {
  216669. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  216670. if (s != 0)
  216671. {
  216672. //xxx todo
  216673. jassertfalse
  216674. }
  216675. return -1;
  216676. }
  216677. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  216678. {
  216679. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  216680. if (s != 0)
  216681. {
  216682. for (int i = 0; i < s->headerLines.size(); ++i)
  216683. {
  216684. const String& headersEntry = s->headerLines[i];
  216685. const String key (headersEntry.upToFirstOccurrenceOf (": ", false, false));
  216686. const String value (headersEntry.fromFirstOccurrenceOf (": ", false, false));
  216687. const String previousValue (headers [key]);
  216688. headers.set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  216689. }
  216690. }
  216691. }
  216692. int juce_seekInInternetFile (void* handle, int newPosition)
  216693. {
  216694. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  216695. return s != 0 ? s->readPosition : 0;
  216696. }
  216697. #endif
  216698. /*** End of inlined file: juce_linux_Network.cpp ***/
  216699. /*** Start of inlined file: juce_linux_SystemStats.cpp ***/
  216700. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  216701. // compiled on its own).
  216702. #if JUCE_INCLUDED_FILE
  216703. void Logger::outputDebugString (const String& text)
  216704. {
  216705. std::cerr << text << std::endl;
  216706. }
  216707. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  216708. {
  216709. return Linux;
  216710. }
  216711. const String SystemStats::getOperatingSystemName()
  216712. {
  216713. return "Linux";
  216714. }
  216715. bool SystemStats::isOperatingSystem64Bit()
  216716. {
  216717. #if JUCE_64BIT
  216718. return true;
  216719. #else
  216720. //xxx not sure how to find this out?..
  216721. return false;
  216722. #endif
  216723. }
  216724. static const String juce_getCpuInfo (const char* const key)
  216725. {
  216726. StringArray lines;
  216727. lines.addLines (File ("/proc/cpuinfo").loadFileAsString());
  216728. for (int i = lines.size(); --i >= 0;) // (NB - it's important that this runs in reverse order)
  216729. if (lines[i].startsWithIgnoreCase (key))
  216730. return lines[i].fromFirstOccurrenceOf (":", false, false).trim();
  216731. return String::empty;
  216732. }
  216733. const String SystemStats::getCpuVendor()
  216734. {
  216735. return juce_getCpuInfo ("vendor_id");
  216736. }
  216737. int SystemStats::getCpuSpeedInMegaherz()
  216738. {
  216739. return roundToInt (juce_getCpuInfo ("cpu MHz").getFloatValue());
  216740. }
  216741. int SystemStats::getMemorySizeInMegabytes()
  216742. {
  216743. struct sysinfo sysi;
  216744. if (sysinfo (&sysi) == 0)
  216745. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  216746. return 0;
  216747. }
  216748. int SystemStats::getPageSize()
  216749. {
  216750. return sysconf (_SC_PAGESIZE);
  216751. }
  216752. const String SystemStats::getLogonName()
  216753. {
  216754. const char* user = getenv ("USER");
  216755. if (user == 0)
  216756. {
  216757. struct passwd* const pw = getpwuid (getuid());
  216758. if (pw != 0)
  216759. user = pw->pw_name;
  216760. }
  216761. return String::fromUTF8 (user);
  216762. }
  216763. const String SystemStats::getFullUserName()
  216764. {
  216765. return getLogonName();
  216766. }
  216767. void SystemStats::initialiseStats()
  216768. {
  216769. const String flags (juce_getCpuInfo ("flags"));
  216770. cpuFlags.hasMMX = flags.contains ("mmx");
  216771. cpuFlags.hasSSE = flags.contains ("sse");
  216772. cpuFlags.hasSSE2 = flags.contains ("sse2");
  216773. cpuFlags.has3DNow = flags.contains ("3dnow");
  216774. cpuFlags.numCpus = juce_getCpuInfo ("processor").getIntValue() + 1;
  216775. }
  216776. void PlatformUtilities::fpuReset()
  216777. {
  216778. }
  216779. static bool juce_getTimeSinceStartup (timeval* const t) throw()
  216780. {
  216781. if (gettimeofday (t, 0) != 0)
  216782. return false;
  216783. static unsigned int calibrate = 0;
  216784. static bool calibrated = false;
  216785. if (! calibrated)
  216786. {
  216787. calibrated = true;
  216788. struct sysinfo sysi;
  216789. if (sysinfo (&sysi) == 0)
  216790. calibrate = t->tv_sec - sysi.uptime; // Safe to assume system was not brought up earlier than 1970!
  216791. }
  216792. t->tv_sec -= calibrate;
  216793. return true;
  216794. }
  216795. uint32 juce_millisecondsSinceStartup() throw()
  216796. {
  216797. timeval t;
  216798. if (juce_getTimeSinceStartup (&t))
  216799. return (uint32) (t.tv_sec * 1000 + (t.tv_usec / 1000));
  216800. return 0;
  216801. }
  216802. int64 Time::getHighResolutionTicks() throw()
  216803. {
  216804. timeval t;
  216805. if (juce_getTimeSinceStartup (&t))
  216806. return ((int64) t.tv_sec * (int64) 1000000) + (int64) t.tv_usec;
  216807. return 0;
  216808. }
  216809. int64 Time::getHighResolutionTicksPerSecond() throw()
  216810. {
  216811. return 1000000; // (microseconds)
  216812. }
  216813. double Time::getMillisecondCounterHiRes() throw()
  216814. {
  216815. return getHighResolutionTicks() * 0.001;
  216816. }
  216817. bool Time::setSystemTimeToThisTime() const
  216818. {
  216819. timeval t;
  216820. t.tv_sec = millisSinceEpoch % 1000000;
  216821. t.tv_usec = millisSinceEpoch - t.tv_sec;
  216822. return settimeofday (&t, 0) ? false : true;
  216823. }
  216824. #endif
  216825. /*** End of inlined file: juce_linux_SystemStats.cpp ***/
  216826. /*** Start of inlined file: juce_linux_Threads.cpp ***/
  216827. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  216828. // compiled on its own).
  216829. #if JUCE_INCLUDED_FILE
  216830. /*
  216831. Note that a lot of methods that you'd expect to find in this file actually
  216832. live in juce_posix_SharedCode.h!
  216833. */
  216834. void JUCE_API juce_threadEntryPoint (void*);
  216835. void* threadEntryProc (void* value)
  216836. {
  216837. juce_threadEntryPoint (value);
  216838. return 0;
  216839. }
  216840. void* juce_createThread (void* userData)
  216841. {
  216842. pthread_t handle = 0;
  216843. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  216844. {
  216845. pthread_detach (handle);
  216846. return (void*) handle;
  216847. }
  216848. return 0;
  216849. }
  216850. void juce_killThread (void* handle)
  216851. {
  216852. if (handle != 0)
  216853. pthread_cancel ((pthread_t) handle);
  216854. }
  216855. void juce_setCurrentThreadName (const String& /*name*/)
  216856. {
  216857. }
  216858. Thread::ThreadID Thread::getCurrentThreadId()
  216859. {
  216860. return (ThreadID) pthread_self();
  216861. }
  216862. /* This is all a bit non-ideal... the trouble is that on Linux you
  216863. need to call setpriority to affect the dynamic priority for
  216864. non-realtime processes, but this requires the pid, which is not
  216865. accessible from the pthread_t. We could get it by calling getpid
  216866. once each thread has started, but then we would need a list of
  216867. running threads etc etc.
  216868. Also there is no such thing as IDLE priority on Linux.
  216869. For the moment, map idle, low and normal process priorities to
  216870. SCHED_OTHER, with the thread priority ignored for these classes.
  216871. Map high priority processes to the lower half of the SCHED_RR
  216872. range, and realtime to the upper half.
  216873. priority 1 to 10 where 5=normal, 1=low. If the handle is 0, sets the
  216874. priority of the current thread
  216875. */
  216876. bool juce_setThreadPriority (void* handle, int priority)
  216877. {
  216878. struct sched_param param;
  216879. int policy;
  216880. if (handle == 0)
  216881. handle = (void*) pthread_self();
  216882. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) == 0
  216883. && policy != SCHED_OTHER)
  216884. {
  216885. int minp = sched_get_priority_min (policy);
  216886. int maxp = sched_get_priority_max (policy);
  216887. int pri = ((maxp - minp) / 2) * (priority - 1) / 9;
  216888. if (param.sched_priority >= (minp + (maxp - minp) / 2))
  216889. param.sched_priority = minp + ((maxp - minp) / 2) + pri; // (realtime)
  216890. else
  216891. param.sched_priority = minp + pri; // (high)
  216892. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  216893. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  216894. }
  216895. return false;
  216896. }
  216897. /* Remove this macro if you're having problems compiling the cpu affinity
  216898. calls (the API for these has changed about quite a bit in various Linux
  216899. versions, and a lot of distros seem to ship with obsolete versions)
  216900. */
  216901. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  216902. #define SUPPORT_AFFINITIES 1
  216903. #endif
  216904. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  216905. {
  216906. #if SUPPORT_AFFINITIES
  216907. cpu_set_t affinity;
  216908. CPU_ZERO (&affinity);
  216909. for (int i = 0; i < 32; ++i)
  216910. if ((affinityMask & (1 << i)) != 0)
  216911. CPU_SET (i, &affinity);
  216912. /*
  216913. N.B. If this line causes a compile error, then you've probably not got the latest
  216914. version of glibc installed.
  216915. If you don't want to update your copy of glibc and don't care about cpu affinities,
  216916. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  216917. */
  216918. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  216919. sched_yield();
  216920. #else
  216921. /* affinities aren't supported because either the appropriate header files weren't found,
  216922. or the SUPPORT_AFFINITIES macro was turned off
  216923. */
  216924. jassertfalse;
  216925. #endif
  216926. }
  216927. void Thread::yield()
  216928. {
  216929. sched_yield();
  216930. }
  216931. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  216932. void Process::setPriority (ProcessPriority prior)
  216933. {
  216934. struct sched_param param;
  216935. int policy, maxp, minp;
  216936. const int p = (int) prior;
  216937. if (p <= 1)
  216938. policy = SCHED_OTHER;
  216939. else
  216940. policy = SCHED_RR;
  216941. minp = sched_get_priority_min (policy);
  216942. maxp = sched_get_priority_max (policy);
  216943. if (p < 2)
  216944. param.sched_priority = 0;
  216945. else if (p == 2 )
  216946. // Set to middle of lower realtime priority range
  216947. param.sched_priority = minp + (maxp - minp) / 4;
  216948. else
  216949. // Set to middle of higher realtime priority range
  216950. param.sched_priority = minp + (3 * (maxp - minp) / 4);
  216951. pthread_setschedparam (pthread_self(), policy, &param);
  216952. }
  216953. void Process::terminate()
  216954. {
  216955. exit (0);
  216956. }
  216957. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  216958. {
  216959. static char testResult = 0;
  216960. if (testResult == 0)
  216961. {
  216962. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  216963. if (testResult >= 0)
  216964. {
  216965. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  216966. testResult = 1;
  216967. }
  216968. }
  216969. return testResult < 0;
  216970. }
  216971. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  216972. {
  216973. return juce_isRunningUnderDebugger();
  216974. }
  216975. void Process::raisePrivilege()
  216976. {
  216977. // If running suid root, change effective user
  216978. // to root
  216979. if (geteuid() != 0 && getuid() == 0)
  216980. {
  216981. setreuid (geteuid(), getuid());
  216982. setregid (getegid(), getgid());
  216983. }
  216984. }
  216985. void Process::lowerPrivilege()
  216986. {
  216987. // If runing suid root, change effective user
  216988. // back to real user
  216989. if (geteuid() == 0 && getuid() != 0)
  216990. {
  216991. setreuid (geteuid(), getuid());
  216992. setregid (getegid(), getgid());
  216993. }
  216994. }
  216995. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  216996. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  216997. {
  216998. return dlopen (name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  216999. }
  217000. void PlatformUtilities::freeDynamicLibrary (void* handle)
  217001. {
  217002. dlclose(handle);
  217003. }
  217004. void* PlatformUtilities::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  217005. {
  217006. return dlsym (libraryHandle, procedureName.toCString());
  217007. }
  217008. #endif
  217009. #endif
  217010. /*** End of inlined file: juce_linux_Threads.cpp ***/
  217011. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  217012. /*** Start of inlined file: juce_linux_Clipboard.cpp ***/
  217013. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217014. // compiled on its own).
  217015. #if JUCE_INCLUDED_FILE
  217016. #if JUCE_DEBUG
  217017. #define JUCE_DEBUG_XERRORS 1
  217018. #endif
  217019. extern Display* display;
  217020. extern Window juce_messageWindowHandle;
  217021. namespace ClipboardHelpers
  217022. {
  217023. static String localClipboardContent;
  217024. static Atom atom_UTF8_STRING;
  217025. static Atom atom_CLIPBOARD;
  217026. static Atom atom_TARGETS;
  217027. static void initSelectionAtoms()
  217028. {
  217029. static bool isInitialised = false;
  217030. if (! isInitialised)
  217031. {
  217032. atom_UTF8_STRING = XInternAtom (display, "UTF8_STRING", False);
  217033. atom_CLIPBOARD = XInternAtom (display, "CLIPBOARD", False);
  217034. atom_TARGETS = XInternAtom (display, "TARGETS", False);
  217035. }
  217036. }
  217037. // Read the content of a window property as either a locale-dependent string or an utf8 string
  217038. // works only for strings shorter than 1000000 bytes
  217039. static String readWindowProperty (Window window, Atom prop, Atom fmt)
  217040. {
  217041. String returnData;
  217042. char* clipData;
  217043. Atom actualType;
  217044. int actualFormat;
  217045. unsigned long numItems, bytesLeft;
  217046. if (XGetWindowProperty (display, window, prop,
  217047. 0L /* offset */, 1000000 /* length (max) */, False,
  217048. AnyPropertyType /* format */,
  217049. &actualType, &actualFormat, &numItems, &bytesLeft,
  217050. (unsigned char**) &clipData) == Success)
  217051. {
  217052. if (actualType == atom_UTF8_STRING && actualFormat == 8)
  217053. returnData = String::fromUTF8 (clipData, numItems);
  217054. else if (actualType == XA_STRING && actualFormat == 8)
  217055. returnData = String (clipData, numItems);
  217056. if (clipData != 0)
  217057. XFree (clipData);
  217058. jassert (bytesLeft == 0 || numItems == 1000000);
  217059. }
  217060. XDeleteProperty (display, window, prop);
  217061. return returnData;
  217062. }
  217063. // Send a SelectionRequest to the window owning the selection and waits for its answer (with a timeout) */
  217064. static bool requestSelectionContent (String& selectionContent, Atom selection, Atom requestedFormat)
  217065. {
  217066. Atom property_name = XInternAtom (display, "JUCE_SEL", false);
  217067. // The selection owner will be asked to set the JUCE_SEL property on the
  217068. // juce_messageWindowHandle with the selection content
  217069. XConvertSelection (display, selection, requestedFormat, property_name,
  217070. juce_messageWindowHandle, CurrentTime);
  217071. int count = 50; // will wait at most for 200 ms
  217072. while (--count >= 0)
  217073. {
  217074. XEvent event;
  217075. if (XCheckTypedWindowEvent (display, juce_messageWindowHandle, SelectionNotify, &event))
  217076. {
  217077. if (event.xselection.property == property_name)
  217078. {
  217079. jassert (event.xselection.requestor == juce_messageWindowHandle);
  217080. selectionContent = readWindowProperty (event.xselection.requestor,
  217081. event.xselection.property,
  217082. requestedFormat);
  217083. return true;
  217084. }
  217085. else
  217086. {
  217087. return false; // the format we asked for was denied.. (event.xselection.property == None)
  217088. }
  217089. }
  217090. // not very elegant.. we could do a select() or something like that...
  217091. // however clipboard content requesting is inherently slow on x11, it
  217092. // often takes 50ms or more so...
  217093. Thread::sleep (4);
  217094. }
  217095. return false;
  217096. }
  217097. }
  217098. // Called from the event loop in juce_linux_Messaging in response to SelectionRequest events
  217099. void juce_handleSelectionRequest (XSelectionRequestEvent &evt)
  217100. {
  217101. ClipboardHelpers::initSelectionAtoms();
  217102. // the selection content is sent to the target window as a window property
  217103. XSelectionEvent reply;
  217104. reply.type = SelectionNotify;
  217105. reply.display = evt.display;
  217106. reply.requestor = evt.requestor;
  217107. reply.selection = evt.selection;
  217108. reply.target = evt.target;
  217109. reply.property = None; // == "fail"
  217110. reply.time = evt.time;
  217111. HeapBlock <char> data;
  217112. int propertyFormat = 0, numDataItems = 0;
  217113. if (evt.selection == XA_PRIMARY || evt.selection == ClipboardHelpers::atom_CLIPBOARD)
  217114. {
  217115. if (evt.target == XA_STRING)
  217116. {
  217117. // format data according to system locale
  217118. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsCString() + 1;
  217119. data.calloc (numDataItems + 1);
  217120. ClipboardHelpers::localClipboardContent.copyToCString (data, numDataItems);
  217121. propertyFormat = 8; // bits/item
  217122. }
  217123. else if (evt.target == ClipboardHelpers::atom_UTF8_STRING)
  217124. {
  217125. // translate to utf8
  217126. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsUTF8() + 1;
  217127. data.calloc (numDataItems + 1);
  217128. ClipboardHelpers::localClipboardContent.copyToUTF8 (data, numDataItems);
  217129. propertyFormat = 8; // bits/item
  217130. }
  217131. else if (evt.target == ClipboardHelpers::atom_TARGETS)
  217132. {
  217133. // another application wants to know what we are able to send
  217134. numDataItems = 2;
  217135. propertyFormat = 32; // atoms are 32-bit
  217136. data.calloc (numDataItems * 4);
  217137. Atom* atoms = reinterpret_cast<Atom*> (data.getData());
  217138. atoms[0] = ClipboardHelpers::atom_UTF8_STRING;
  217139. atoms[1] = XA_STRING;
  217140. }
  217141. }
  217142. else
  217143. {
  217144. DBG ("requested unsupported clipboard");
  217145. }
  217146. if (data != 0)
  217147. {
  217148. const int maxReasonableSelectionSize = 1000000;
  217149. // for very big chunks of data, we should use the "INCR" protocol , which is a pain in the *ss
  217150. if (evt.property != None && numDataItems < maxReasonableSelectionSize)
  217151. {
  217152. XChangeProperty (evt.display, evt.requestor,
  217153. evt.property, evt.target,
  217154. propertyFormat /* 8 or 32 */, PropModeReplace,
  217155. reinterpret_cast<const unsigned char*> (data.getData()), numDataItems);
  217156. reply.property = evt.property; // " == success"
  217157. }
  217158. }
  217159. XSendEvent (evt.display, evt.requestor, 0, NoEventMask, (XEvent*) &reply);
  217160. }
  217161. void SystemClipboard::copyTextToClipboard (const String& clipText)
  217162. {
  217163. ClipboardHelpers::initSelectionAtoms();
  217164. ClipboardHelpers::localClipboardContent = clipText;
  217165. XSetSelectionOwner (display, XA_PRIMARY, juce_messageWindowHandle, CurrentTime);
  217166. XSetSelectionOwner (display, ClipboardHelpers::atom_CLIPBOARD, juce_messageWindowHandle, CurrentTime);
  217167. }
  217168. const String SystemClipboard::getTextFromClipboard()
  217169. {
  217170. ClipboardHelpers::initSelectionAtoms();
  217171. /* 1) try to read from the "CLIPBOARD" selection first (the "high
  217172. level" clipboard that is supposed to be filled by ctrl-C
  217173. etc). When a clipboard manager is running, the content of this
  217174. selection is preserved even when the original selection owner
  217175. exits.
  217176. 2) and then try to read from "PRIMARY" selection (the "legacy" selection
  217177. filled by good old x11 apps such as xterm)
  217178. */
  217179. String content;
  217180. Atom selection = XA_PRIMARY;
  217181. Window selectionOwner = None;
  217182. if ((selectionOwner = XGetSelectionOwner (display, selection)) == None)
  217183. {
  217184. selection = ClipboardHelpers::atom_CLIPBOARD;
  217185. selectionOwner = XGetSelectionOwner (display, selection);
  217186. }
  217187. if (selectionOwner != None)
  217188. {
  217189. if (selectionOwner == juce_messageWindowHandle)
  217190. {
  217191. content = ClipboardHelpers::localClipboardContent;
  217192. }
  217193. else
  217194. {
  217195. // first try: we want an utf8 string
  217196. bool ok = ClipboardHelpers::requestSelectionContent (content, selection, ClipboardHelpers::atom_UTF8_STRING);
  217197. if (! ok)
  217198. {
  217199. // second chance, ask for a good old locale-dependent string ..
  217200. ok = ClipboardHelpers::requestSelectionContent (content, selection, XA_STRING);
  217201. }
  217202. }
  217203. }
  217204. return content;
  217205. }
  217206. #endif
  217207. /*** End of inlined file: juce_linux_Clipboard.cpp ***/
  217208. /*** Start of inlined file: juce_linux_Messaging.cpp ***/
  217209. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217210. // compiled on its own).
  217211. #if JUCE_INCLUDED_FILE
  217212. #if JUCE_DEBUG && ! defined (JUCE_DEBUG_XERRORS)
  217213. #define JUCE_DEBUG_XERRORS 1
  217214. #endif
  217215. Display* display = 0;
  217216. Window juce_messageWindowHandle = None;
  217217. XContext windowHandleXContext; // This is referenced from Windowing.cpp
  217218. extern void juce_windowMessageReceive (XEvent* event); // Defined in Windowing.cpp
  217219. extern void juce_handleSelectionRequest (XSelectionRequestEvent &evt); // Defined in Clipboard.cpp
  217220. ScopedXLock::ScopedXLock() { XLockDisplay (display); }
  217221. ScopedXLock::~ScopedXLock() { XUnlockDisplay (display); }
  217222. class InternalMessageQueue
  217223. {
  217224. public:
  217225. InternalMessageQueue()
  217226. : bytesInSocket (0),
  217227. totalEventCount (0)
  217228. {
  217229. int ret = ::socketpair (AF_LOCAL, SOCK_STREAM, 0, fd);
  217230. (void) ret; jassert (ret == 0);
  217231. //setNonBlocking (fd[0]);
  217232. //setNonBlocking (fd[1]);
  217233. }
  217234. ~InternalMessageQueue()
  217235. {
  217236. close (fd[0]);
  217237. close (fd[1]);
  217238. clearSingletonInstance();
  217239. }
  217240. void postMessage (Message* msg)
  217241. {
  217242. const int maxBytesInSocketQueue = 128;
  217243. ScopedLock sl (lock);
  217244. queue.add (msg);
  217245. if (bytesInSocket < maxBytesInSocketQueue)
  217246. {
  217247. ++bytesInSocket;
  217248. ScopedUnlock ul (lock);
  217249. const unsigned char x = 0xff;
  217250. size_t bytesWritten = write (fd[0], &x, 1);
  217251. (void) bytesWritten;
  217252. }
  217253. }
  217254. bool isEmpty() const
  217255. {
  217256. ScopedLock sl (lock);
  217257. return queue.size() == 0;
  217258. }
  217259. bool dispatchNextEvent()
  217260. {
  217261. // This alternates between giving priority to XEvents or internal messages,
  217262. // to keep everything running smoothly..
  217263. if ((++totalEventCount & 1) != 0)
  217264. return dispatchNextXEvent() || dispatchNextInternalMessage();
  217265. else
  217266. return dispatchNextInternalMessage() || dispatchNextXEvent();
  217267. }
  217268. // Wait for an event (either XEvent, or an internal Message)
  217269. bool sleepUntilEvent (const int timeoutMs)
  217270. {
  217271. if (! isEmpty())
  217272. return true;
  217273. if (display != 0)
  217274. {
  217275. ScopedXLock xlock;
  217276. if (XPending (display))
  217277. return true;
  217278. }
  217279. struct timeval tv;
  217280. tv.tv_sec = 0;
  217281. tv.tv_usec = timeoutMs * 1000;
  217282. int fd0 = getWaitHandle();
  217283. int fdmax = fd0;
  217284. fd_set readset;
  217285. FD_ZERO (&readset);
  217286. FD_SET (fd0, &readset);
  217287. if (display != 0)
  217288. {
  217289. ScopedXLock xlock;
  217290. int fd1 = XConnectionNumber (display);
  217291. FD_SET (fd1, &readset);
  217292. fdmax = jmax (fd0, fd1);
  217293. }
  217294. const int ret = select (fdmax + 1, &readset, 0, 0, &tv);
  217295. return (ret > 0); // ret <= 0 if error or timeout
  217296. }
  217297. struct MessageThreadFuncCall
  217298. {
  217299. enum { uniqueID = 0x73774623 };
  217300. MessageCallbackFunction* func;
  217301. void* parameter;
  217302. void* result;
  217303. CriticalSection lock;
  217304. WaitableEvent event;
  217305. };
  217306. juce_DeclareSingleton_SingleThreaded_Minimal (InternalMessageQueue);
  217307. private:
  217308. CriticalSection lock;
  217309. OwnedArray <Message> queue;
  217310. int fd[2];
  217311. int bytesInSocket;
  217312. int totalEventCount;
  217313. int getWaitHandle() const throw() { return fd[1]; }
  217314. static bool setNonBlocking (int handle)
  217315. {
  217316. int socketFlags = fcntl (handle, F_GETFL, 0);
  217317. if (socketFlags == -1)
  217318. return false;
  217319. socketFlags |= O_NONBLOCK;
  217320. return fcntl (handle, F_SETFL, socketFlags) == 0;
  217321. }
  217322. static bool dispatchNextXEvent()
  217323. {
  217324. if (display == 0)
  217325. return false;
  217326. XEvent evt;
  217327. {
  217328. ScopedXLock xlock;
  217329. if (! XPending (display))
  217330. return false;
  217331. XNextEvent (display, &evt);
  217332. }
  217333. if (evt.type == SelectionRequest && evt.xany.window == juce_messageWindowHandle)
  217334. juce_handleSelectionRequest (evt.xselectionrequest);
  217335. else if (evt.xany.window != juce_messageWindowHandle)
  217336. juce_windowMessageReceive (&evt);
  217337. return true;
  217338. }
  217339. Message* popNextMessage()
  217340. {
  217341. ScopedLock sl (lock);
  217342. if (bytesInSocket > 0)
  217343. {
  217344. --bytesInSocket;
  217345. ScopedUnlock ul (lock);
  217346. unsigned char x;
  217347. size_t numBytes = read (fd[1], &x, 1);
  217348. (void) numBytes;
  217349. }
  217350. Message* m = queue[0];
  217351. queue.remove (0, false /* deleteObject */);
  217352. return m;
  217353. }
  217354. bool dispatchNextInternalMessage()
  217355. {
  217356. ScopedPointer <Message> msg (popNextMessage());
  217357. if (msg == 0)
  217358. return false;
  217359. if (msg->intParameter1 == MessageThreadFuncCall::uniqueID)
  217360. {
  217361. // Handle callback message
  217362. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) msg->pointerParameter;
  217363. call->result = (*(call->func)) (call->parameter);
  217364. call->event.signal();
  217365. }
  217366. else
  217367. {
  217368. // Handle "normal" messages
  217369. MessageManager::getInstance()->deliverMessage (msg.release());
  217370. }
  217371. return true;
  217372. }
  217373. };
  217374. juce_ImplementSingleton_SingleThreaded (InternalMessageQueue);
  217375. namespace LinuxErrorHandling
  217376. {
  217377. static bool errorOccurred = false;
  217378. static bool keyboardBreakOccurred = false;
  217379. static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
  217380. static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
  217381. // Usually happens when client-server connection is broken
  217382. static int ioErrorHandler (Display* display)
  217383. {
  217384. DBG ("ERROR: connection to X server broken.. terminating.");
  217385. if (JUCEApplication::getInstance() != 0)
  217386. MessageManager::getInstance()->stopDispatchLoop();
  217387. errorOccurred = true;
  217388. return 0;
  217389. }
  217390. // A protocol error has occurred
  217391. static int juce_XErrorHandler (Display* display, XErrorEvent* event)
  217392. {
  217393. #if JUCE_DEBUG_XERRORS
  217394. char errorStr[64] = { 0 };
  217395. char requestStr[64] = { 0 };
  217396. XGetErrorText (display, event->error_code, errorStr, 64);
  217397. XGetErrorDatabaseText (display, "XRequest", String (event->request_code).toCString(), "Unknown", requestStr, 64);
  217398. DBG ("ERROR: X returned " + String (errorStr) + " for operation " + String (requestStr));
  217399. #endif
  217400. return 0;
  217401. }
  217402. static void installXErrorHandlers()
  217403. {
  217404. oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
  217405. oldErrorHandler = XSetErrorHandler (juce_XErrorHandler);
  217406. }
  217407. static void removeXErrorHandlers()
  217408. {
  217409. XSetIOErrorHandler (oldIOErrorHandler);
  217410. oldIOErrorHandler = 0;
  217411. XSetErrorHandler (oldErrorHandler);
  217412. oldErrorHandler = 0;
  217413. }
  217414. static void keyboardBreakSignalHandler (int sig)
  217415. {
  217416. if (sig == SIGINT)
  217417. keyboardBreakOccurred = true;
  217418. }
  217419. static void installKeyboardBreakHandler()
  217420. {
  217421. struct sigaction saction;
  217422. sigset_t maskSet;
  217423. sigemptyset (&maskSet);
  217424. saction.sa_handler = keyboardBreakSignalHandler;
  217425. saction.sa_mask = maskSet;
  217426. saction.sa_flags = 0;
  217427. sigaction (SIGINT, &saction, 0);
  217428. }
  217429. }
  217430. void MessageManager::doPlatformSpecificInitialisation()
  217431. {
  217432. // Initialise xlib for multiple thread support
  217433. static bool initThreadCalled = false;
  217434. if (! initThreadCalled)
  217435. {
  217436. if (! XInitThreads())
  217437. {
  217438. // This is fatal! Print error and closedown
  217439. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  217440. if (JUCEApplication::getInstance() != 0)
  217441. Process::terminate();
  217442. return;
  217443. }
  217444. initThreadCalled = true;
  217445. }
  217446. LinuxErrorHandling::installXErrorHandlers();
  217447. LinuxErrorHandling::installKeyboardBreakHandler();
  217448. // Create the internal message queue
  217449. InternalMessageQueue::getInstance();
  217450. // Try to connect to a display
  217451. String displayName (getenv ("DISPLAY"));
  217452. if (displayName.isEmpty())
  217453. displayName = ":0.0";
  217454. display = XOpenDisplay (displayName.toCString());
  217455. if (display != 0) // This is not fatal! we can run headless.
  217456. {
  217457. // Create a context to store user data associated with Windows we create in WindowDriver
  217458. windowHandleXContext = XUniqueContext();
  217459. // We're only interested in client messages for this window, which are always sent
  217460. XSetWindowAttributes swa;
  217461. swa.event_mask = NoEventMask;
  217462. // Create our message window (this will never be mapped)
  217463. const int screen = DefaultScreen (display);
  217464. juce_messageWindowHandle = XCreateWindow (display, RootWindow (display, screen),
  217465. 0, 0, 1, 1, 0, 0, InputOnly,
  217466. DefaultVisual (display, screen),
  217467. CWEventMask, &swa);
  217468. }
  217469. }
  217470. void MessageManager::doPlatformSpecificShutdown()
  217471. {
  217472. InternalMessageQueue::deleteInstance();
  217473. if (display != 0 && ! LinuxErrorHandling::errorOccurred)
  217474. {
  217475. XDestroyWindow (display, juce_messageWindowHandle);
  217476. XCloseDisplay (display);
  217477. juce_messageWindowHandle = 0;
  217478. display = 0;
  217479. LinuxErrorHandling::removeXErrorHandlers();
  217480. }
  217481. }
  217482. bool juce_postMessageToSystemQueue (void* message)
  217483. {
  217484. if (LinuxErrorHandling::errorOccurred)
  217485. return false;
  217486. InternalMessageQueue::getInstanceWithoutCreating()->postMessage ((Message*) message);
  217487. return true;
  217488. }
  217489. void MessageManager::broadcastMessage (const String& value) throw()
  217490. {
  217491. /* TODO */
  217492. }
  217493. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func,
  217494. void* parameter)
  217495. {
  217496. if (LinuxErrorHandling::errorOccurred)
  217497. return 0;
  217498. if (isThisTheMessageThread())
  217499. return func (parameter);
  217500. InternalMessageQueue::MessageThreadFuncCall messageCallContext;
  217501. messageCallContext.func = func;
  217502. messageCallContext.parameter = parameter;
  217503. InternalMessageQueue::getInstanceWithoutCreating()
  217504. ->postMessage (new Message (InternalMessageQueue::MessageThreadFuncCall::uniqueID,
  217505. 0, 0, &messageCallContext));
  217506. // Wait for it to complete before continuing
  217507. messageCallContext.event.wait();
  217508. return messageCallContext.result;
  217509. }
  217510. // this function expects that it will NEVER be called simultaneously for two concurrent threads
  217511. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  217512. {
  217513. while (! LinuxErrorHandling::errorOccurred)
  217514. {
  217515. if (LinuxErrorHandling::keyboardBreakOccurred)
  217516. {
  217517. LinuxErrorHandling::errorOccurred = true;
  217518. if (JUCEApplication::getInstance() != 0)
  217519. Process::terminate();
  217520. break;
  217521. }
  217522. if (InternalMessageQueue::getInstanceWithoutCreating()->dispatchNextEvent())
  217523. return true;
  217524. if (returnIfNoPendingMessages)
  217525. break;
  217526. InternalMessageQueue::getInstanceWithoutCreating()->sleepUntilEvent (2000);
  217527. }
  217528. return false;
  217529. }
  217530. #endif
  217531. /*** End of inlined file: juce_linux_Messaging.cpp ***/
  217532. /*** Start of inlined file: juce_linux_Fonts.cpp ***/
  217533. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217534. // compiled on its own).
  217535. #if JUCE_INCLUDED_FILE
  217536. class FreeTypeFontFace
  217537. {
  217538. public:
  217539. enum FontStyle
  217540. {
  217541. Plain = 0,
  217542. Bold = 1,
  217543. Italic = 2
  217544. };
  217545. FreeTypeFontFace (const String& familyName)
  217546. : hasSerif (false),
  217547. monospaced (false)
  217548. {
  217549. family = familyName;
  217550. }
  217551. void setFileName (const String& name, const int faceIndex, FontStyle style)
  217552. {
  217553. if (names [(int) style].fileName.isEmpty())
  217554. {
  217555. names [(int) style].fileName = name;
  217556. names [(int) style].faceIndex = faceIndex;
  217557. }
  217558. }
  217559. const String& getFamilyName() const throw() { return family; }
  217560. const String& getFileName (const int style, int& faceIndex) const throw()
  217561. {
  217562. faceIndex = names[style].faceIndex;
  217563. return names[style].fileName;
  217564. }
  217565. void setMonospaced (bool mono) throw() { monospaced = mono; }
  217566. bool getMonospaced() const throw() { return monospaced; }
  217567. void setSerif (const bool serif) throw() { hasSerif = serif; }
  217568. bool getSerif() const throw() { return hasSerif; }
  217569. private:
  217570. String family;
  217571. struct FontNameIndex
  217572. {
  217573. String fileName;
  217574. int faceIndex;
  217575. };
  217576. FontNameIndex names[4];
  217577. bool hasSerif, monospaced;
  217578. };
  217579. class FreeTypeInterface : public DeletedAtShutdown
  217580. {
  217581. public:
  217582. FreeTypeInterface()
  217583. : ftLib (0),
  217584. lastFace (0),
  217585. lastBold (false),
  217586. lastItalic (false)
  217587. {
  217588. if (FT_Init_FreeType (&ftLib) != 0)
  217589. {
  217590. ftLib = 0;
  217591. DBG ("Failed to initialize FreeType");
  217592. }
  217593. StringArray fontDirs;
  217594. fontDirs.addTokens (String::fromUTF8 (getenv ("JUCE_FONT_PATH")), ";,", String::empty);
  217595. fontDirs.removeEmptyStrings (true);
  217596. if (fontDirs.size() == 0)
  217597. {
  217598. XmlDocument fontsConfig (File ("/etc/fonts/fonts.conf"));
  217599. const ScopedPointer<XmlElement> fontsInfo (fontsConfig.getDocumentElement());
  217600. if (fontsInfo != 0)
  217601. {
  217602. forEachXmlChildElementWithTagName (*fontsInfo, e, "dir")
  217603. {
  217604. fontDirs.add (e->getAllSubText().trim());
  217605. }
  217606. }
  217607. }
  217608. if (fontDirs.size() == 0)
  217609. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  217610. for (int i = 0; i < fontDirs.size(); ++i)
  217611. enumerateFaces (fontDirs[i]);
  217612. }
  217613. ~FreeTypeInterface()
  217614. {
  217615. if (lastFace != 0)
  217616. FT_Done_Face (lastFace);
  217617. if (ftLib != 0)
  217618. FT_Done_FreeType (ftLib);
  217619. clearSingletonInstance();
  217620. }
  217621. FreeTypeFontFace* findOrCreate (const String& familyName, const bool create = false)
  217622. {
  217623. for (int i = 0; i < faces.size(); i++)
  217624. if (faces[i]->getFamilyName() == familyName)
  217625. return faces[i];
  217626. if (! create)
  217627. return 0;
  217628. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  217629. faces.add (newFace);
  217630. return newFace;
  217631. }
  217632. // Enumerate all font faces available in a given directory
  217633. void enumerateFaces (const String& path)
  217634. {
  217635. File dirPath (path);
  217636. if (path.isEmpty() || ! dirPath.isDirectory())
  217637. return;
  217638. DirectoryIterator di (dirPath, true);
  217639. while (di.next())
  217640. {
  217641. File possible (di.getFile());
  217642. if (possible.hasFileExtension ("ttf")
  217643. || possible.hasFileExtension ("pfb")
  217644. || possible.hasFileExtension ("pcf"))
  217645. {
  217646. FT_Face face;
  217647. int faceIndex = 0;
  217648. int numFaces = 0;
  217649. do
  217650. {
  217651. if (FT_New_Face (ftLib, possible.getFullPathName().toUTF8(),
  217652. faceIndex, &face) == 0)
  217653. {
  217654. if (faceIndex == 0)
  217655. numFaces = face->num_faces;
  217656. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  217657. {
  217658. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  217659. int style = (int) FreeTypeFontFace::Plain;
  217660. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  217661. style |= (int) FreeTypeFontFace::Bold;
  217662. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  217663. style |= (int) FreeTypeFontFace::Italic;
  217664. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  217665. newFace->setMonospaced ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0);
  217666. // Surely there must be a better way to do this?
  217667. const String name (face->family_name);
  217668. newFace->setSerif (! (name.containsIgnoreCase ("Sans")
  217669. || name.containsIgnoreCase ("Verdana")
  217670. || name.containsIgnoreCase ("Arial")));
  217671. }
  217672. FT_Done_Face (face);
  217673. }
  217674. ++faceIndex;
  217675. }
  217676. while (faceIndex < numFaces);
  217677. }
  217678. }
  217679. }
  217680. // Create a FreeType face object for a given font
  217681. FT_Face createFT_Face (const String& fontName, const bool bold, const bool italic)
  217682. {
  217683. FT_Face face = 0;
  217684. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  217685. {
  217686. face = lastFace;
  217687. }
  217688. else
  217689. {
  217690. if (lastFace != 0)
  217691. {
  217692. FT_Done_Face (lastFace);
  217693. lastFace = 0;
  217694. }
  217695. lastFontName = fontName;
  217696. lastBold = bold;
  217697. lastItalic = italic;
  217698. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  217699. if (ftFace != 0)
  217700. {
  217701. int style = (int) FreeTypeFontFace::Plain;
  217702. if (bold)
  217703. style |= (int) FreeTypeFontFace::Bold;
  217704. if (italic)
  217705. style |= (int) FreeTypeFontFace::Italic;
  217706. int faceIndex;
  217707. String fileName (ftFace->getFileName (style, faceIndex));
  217708. if (fileName.isEmpty())
  217709. {
  217710. style ^= (int) FreeTypeFontFace::Bold;
  217711. fileName = ftFace->getFileName (style, faceIndex);
  217712. if (fileName.isEmpty())
  217713. {
  217714. style ^= (int) FreeTypeFontFace::Bold;
  217715. style ^= (int) FreeTypeFontFace::Italic;
  217716. fileName = ftFace->getFileName (style, faceIndex);
  217717. if (! fileName.length())
  217718. {
  217719. style ^= (int) FreeTypeFontFace::Bold;
  217720. fileName = ftFace->getFileName (style, faceIndex);
  217721. }
  217722. }
  217723. }
  217724. if (! FT_New_Face (ftLib, fileName.toUTF8(), faceIndex, &lastFace))
  217725. {
  217726. face = lastFace;
  217727. // If there isn't a unicode charmap then select the first one.
  217728. if (FT_Select_Charmap (face, ft_encoding_unicode))
  217729. FT_Set_Charmap (face, face->charmaps[0]);
  217730. }
  217731. }
  217732. }
  217733. return face;
  217734. }
  217735. bool addGlyph (FT_Face face, CustomTypeface& dest, uint32 character)
  217736. {
  217737. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  217738. const float height = (float) (face->ascender - face->descender);
  217739. const float scaleX = 1.0f / height;
  217740. const float scaleY = -1.0f / height;
  217741. Path destShape;
  217742. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_TRANSFORM) != 0
  217743. || face->glyph->format != ft_glyph_format_outline)
  217744. {
  217745. return false;
  217746. }
  217747. const FT_Outline* const outline = &face->glyph->outline;
  217748. const short* const contours = outline->contours;
  217749. const char* const tags = outline->tags;
  217750. FT_Vector* const points = outline->points;
  217751. for (int c = 0; c < outline->n_contours; c++)
  217752. {
  217753. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  217754. const int endPoint = contours[c];
  217755. for (int p = startPoint; p <= endPoint; p++)
  217756. {
  217757. const float x = scaleX * points[p].x;
  217758. const float y = scaleY * points[p].y;
  217759. if (p == startPoint)
  217760. {
  217761. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  217762. {
  217763. float x2 = scaleX * points [endPoint].x;
  217764. float y2 = scaleY * points [endPoint].y;
  217765. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  217766. {
  217767. x2 = (x + x2) * 0.5f;
  217768. y2 = (y + y2) * 0.5f;
  217769. }
  217770. destShape.startNewSubPath (x2, y2);
  217771. }
  217772. else
  217773. {
  217774. destShape.startNewSubPath (x, y);
  217775. }
  217776. }
  217777. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  217778. {
  217779. if (p != startPoint)
  217780. destShape.lineTo (x, y);
  217781. }
  217782. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  217783. {
  217784. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  217785. float x2 = scaleX * points [nextIndex].x;
  217786. float y2 = scaleY * points [nextIndex].y;
  217787. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  217788. {
  217789. x2 = (x + x2) * 0.5f;
  217790. y2 = (y + y2) * 0.5f;
  217791. }
  217792. else
  217793. {
  217794. ++p;
  217795. }
  217796. destShape.quadraticTo (x, y, x2, y2);
  217797. }
  217798. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  217799. {
  217800. if (p >= endPoint)
  217801. return false;
  217802. const int next1 = p + 1;
  217803. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  217804. const float x2 = scaleX * points [next1].x;
  217805. const float y2 = scaleY * points [next1].y;
  217806. const float x3 = scaleX * points [next2].x;
  217807. const float y3 = scaleY * points [next2].y;
  217808. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  217809. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  217810. return false;
  217811. destShape.cubicTo (x, y, x2, y2, x3, y3);
  217812. p += 2;
  217813. }
  217814. }
  217815. destShape.closeSubPath();
  217816. }
  217817. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance / height);
  217818. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  217819. addKerning (face, dest, character, glyphIndex);
  217820. return true;
  217821. }
  217822. void addKerning (FT_Face face, CustomTypeface& dest, const uint32 character, const uint32 glyphIndex)
  217823. {
  217824. const float height = (float) (face->ascender - face->descender);
  217825. uint32 rightGlyphIndex;
  217826. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  217827. while (rightGlyphIndex != 0)
  217828. {
  217829. FT_Vector kerning;
  217830. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  217831. {
  217832. if (kerning.x != 0)
  217833. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  217834. }
  217835. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  217836. }
  217837. }
  217838. // Add a glyph to a font
  217839. bool addGlyphToFont (const uint32 character, const String& fontName,
  217840. bool bold, bool italic, CustomTypeface& dest)
  217841. {
  217842. FT_Face face = createFT_Face (fontName, bold, italic);
  217843. return face != 0 && addGlyph (face, dest, character);
  217844. }
  217845. void getFamilyNames (StringArray& familyNames) const
  217846. {
  217847. for (int i = 0; i < faces.size(); i++)
  217848. familyNames.add (faces[i]->getFamilyName());
  217849. }
  217850. void getMonospacedNames (StringArray& monoSpaced) const
  217851. {
  217852. for (int i = 0; i < faces.size(); i++)
  217853. if (faces[i]->getMonospaced())
  217854. monoSpaced.add (faces[i]->getFamilyName());
  217855. }
  217856. void getSerifNames (StringArray& serif) const
  217857. {
  217858. for (int i = 0; i < faces.size(); i++)
  217859. if (faces[i]->getSerif())
  217860. serif.add (faces[i]->getFamilyName());
  217861. }
  217862. void getSansSerifNames (StringArray& sansSerif) const
  217863. {
  217864. for (int i = 0; i < faces.size(); i++)
  217865. if (! faces[i]->getSerif())
  217866. sansSerif.add (faces[i]->getFamilyName());
  217867. }
  217868. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  217869. private:
  217870. FT_Library ftLib;
  217871. FT_Face lastFace;
  217872. String lastFontName;
  217873. bool lastBold, lastItalic;
  217874. OwnedArray<FreeTypeFontFace> faces;
  217875. };
  217876. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  217877. class FreetypeTypeface : public CustomTypeface
  217878. {
  217879. public:
  217880. FreetypeTypeface (const Font& font)
  217881. {
  217882. FT_Face face = FreeTypeInterface::getInstance()
  217883. ->createFT_Face (font.getTypefaceName(), font.isBold(), font.isItalic());
  217884. if (face == 0)
  217885. {
  217886. #if JUCE_DEBUG
  217887. String msg ("Failed to create typeface: ");
  217888. msg << font.getTypefaceName() << " " << (font.isBold() ? 'B' : ' ') << (font.isItalic() ? 'I' : ' ');
  217889. DBG (msg);
  217890. #endif
  217891. }
  217892. else
  217893. {
  217894. setCharacteristics (font.getTypefaceName(),
  217895. face->ascender / (float) (face->ascender - face->descender),
  217896. font.isBold(), font.isItalic(),
  217897. L' ');
  217898. }
  217899. }
  217900. bool loadGlyphIfPossible (juce_wchar character)
  217901. {
  217902. return FreeTypeInterface::getInstance()
  217903. ->addGlyphToFont (character, name, isBold, isItalic, *this);
  217904. }
  217905. };
  217906. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  217907. {
  217908. return new FreetypeTypeface (font);
  217909. }
  217910. const StringArray Font::findAllTypefaceNames()
  217911. {
  217912. StringArray s;
  217913. FreeTypeInterface::getInstance()->getFamilyNames (s);
  217914. s.sort (true);
  217915. return s;
  217916. }
  217917. static const String pickBestFont (const StringArray& names,
  217918. const char* const choicesString)
  217919. {
  217920. StringArray choices;
  217921. choices.addTokens (String (choicesString), ",", String::empty);
  217922. choices.trim();
  217923. choices.removeEmptyStrings();
  217924. int i, j;
  217925. for (j = 0; j < choices.size(); ++j)
  217926. if (names.contains (choices[j], true))
  217927. return choices[j];
  217928. for (j = 0; j < choices.size(); ++j)
  217929. for (i = 0; i < names.size(); i++)
  217930. if (names[i].startsWithIgnoreCase (choices[j]))
  217931. return names[i];
  217932. for (j = 0; j < choices.size(); ++j)
  217933. for (i = 0; i < names.size(); i++)
  217934. if (names[i].containsIgnoreCase (choices[j]))
  217935. return names[i];
  217936. return names[0];
  217937. }
  217938. static const String linux_getDefaultSansSerifFontName()
  217939. {
  217940. StringArray allFonts;
  217941. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  217942. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  217943. }
  217944. static const String linux_getDefaultSerifFontName()
  217945. {
  217946. StringArray allFonts;
  217947. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  217948. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  217949. }
  217950. static const String linux_getDefaultMonospacedFontName()
  217951. {
  217952. StringArray allFonts;
  217953. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  217954. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  217955. }
  217956. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  217957. {
  217958. defaultSans = linux_getDefaultSansSerifFontName();
  217959. defaultSerif = linux_getDefaultSerifFontName();
  217960. defaultFixed = linux_getDefaultMonospacedFontName();
  217961. }
  217962. #endif
  217963. /*** End of inlined file: juce_linux_Fonts.cpp ***/
  217964. /*** Start of inlined file: juce_linux_Windowing.cpp ***/
  217965. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217966. // compiled on its own).
  217967. #if JUCE_INCLUDED_FILE
  217968. // These are defined in juce_linux_Messaging.cpp
  217969. extern Display* display;
  217970. extern XContext windowHandleXContext;
  217971. namespace Atoms
  217972. {
  217973. enum ProtocolItems
  217974. {
  217975. TAKE_FOCUS = 0,
  217976. DELETE_WINDOW = 1,
  217977. PING = 2
  217978. };
  217979. static Atom Protocols, ProtocolList[3], ChangeState, State,
  217980. ActiveWin, Pid, WindowType, WindowState,
  217981. XdndAware, XdndEnter, XdndLeave, XdndPosition, XdndStatus,
  217982. XdndDrop, XdndFinished, XdndSelection, XdndTypeList, XdndActionList,
  217983. XdndActionDescription, XdndActionCopy,
  217984. allowedActions[5],
  217985. allowedMimeTypes[2];
  217986. const unsigned long DndVersion = 3;
  217987. static void initialiseAtoms()
  217988. {
  217989. static bool atomsInitialised = false;
  217990. if (! atomsInitialised)
  217991. {
  217992. atomsInitialised = true;
  217993. Protocols = XInternAtom (display, "WM_PROTOCOLS", True);
  217994. ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", True);
  217995. ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", True);
  217996. ProtocolList [PING] = XInternAtom (display, "_NET_WM_PING", True);
  217997. ChangeState = XInternAtom (display, "WM_CHANGE_STATE", True);
  217998. State = XInternAtom (display, "WM_STATE", True);
  217999. ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  218000. Pid = XInternAtom (display, "_NET_WM_PID", False);
  218001. WindowType = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  218002. WindowState = XInternAtom (display, "_NET_WM_STATE", True);
  218003. XdndAware = XInternAtom (display, "XdndAware", False);
  218004. XdndEnter = XInternAtom (display, "XdndEnter", False);
  218005. XdndLeave = XInternAtom (display, "XdndLeave", False);
  218006. XdndPosition = XInternAtom (display, "XdndPosition", False);
  218007. XdndStatus = XInternAtom (display, "XdndStatus", False);
  218008. XdndDrop = XInternAtom (display, "XdndDrop", False);
  218009. XdndFinished = XInternAtom (display, "XdndFinished", False);
  218010. XdndSelection = XInternAtom (display, "XdndSelection", False);
  218011. XdndTypeList = XInternAtom (display, "XdndTypeList", False);
  218012. XdndActionList = XInternAtom (display, "XdndActionList", False);
  218013. XdndActionCopy = XInternAtom (display, "XdndActionCopy", False);
  218014. XdndActionDescription = XInternAtom (display, "XdndActionDescription", False);
  218015. allowedMimeTypes[0] = XInternAtom (display, "text/plain", False);
  218016. allowedMimeTypes[1] = XInternAtom (display, "text/uri-list", False);
  218017. allowedActions[0] = XInternAtom (display, "XdndActionMove", False);
  218018. allowedActions[1] = XdndActionCopy;
  218019. allowedActions[2] = XInternAtom (display, "XdndActionLink", False);
  218020. allowedActions[3] = XInternAtom (display, "XdndActionAsk", False);
  218021. allowedActions[4] = XInternAtom (display, "XdndActionPrivate", False);
  218022. }
  218023. }
  218024. }
  218025. namespace Keys
  218026. {
  218027. enum MouseButtons
  218028. {
  218029. NoButton = 0,
  218030. LeftButton = 1,
  218031. MiddleButton = 2,
  218032. RightButton = 3,
  218033. WheelUp = 4,
  218034. WheelDown = 5
  218035. };
  218036. static int AltMask = 0;
  218037. static int NumLockMask = 0;
  218038. static bool numLock = false;
  218039. static bool capsLock = false;
  218040. static char keyStates [32];
  218041. static const int extendedKeyModifier = 0x10000000;
  218042. }
  218043. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  218044. {
  218045. int keysym;
  218046. if (keyCode & Keys::extendedKeyModifier)
  218047. {
  218048. keysym = 0xff00 | (keyCode & 0xff);
  218049. }
  218050. else
  218051. {
  218052. keysym = keyCode;
  218053. if (keysym == (XK_Tab & 0xff)
  218054. || keysym == (XK_Return & 0xff)
  218055. || keysym == (XK_Escape & 0xff)
  218056. || keysym == (XK_BackSpace & 0xff))
  218057. {
  218058. keysym |= 0xff00;
  218059. }
  218060. }
  218061. ScopedXLock xlock;
  218062. const int keycode = XKeysymToKeycode (display, keysym);
  218063. const int keybyte = keycode >> 3;
  218064. const int keybit = (1 << (keycode & 7));
  218065. return (Keys::keyStates [keybyte] & keybit) != 0;
  218066. }
  218067. #if JUCE_USE_XSHM
  218068. namespace XSHMHelpers
  218069. {
  218070. static int trappedErrorCode = 0;
  218071. extern "C" int errorTrapHandler (Display*, XErrorEvent* err)
  218072. {
  218073. trappedErrorCode = err->error_code;
  218074. return 0;
  218075. }
  218076. static bool isShmAvailable() throw()
  218077. {
  218078. static bool isChecked = false;
  218079. static bool isAvailable = false;
  218080. if (! isChecked)
  218081. {
  218082. isChecked = true;
  218083. int major, minor;
  218084. Bool pixmaps;
  218085. ScopedXLock xlock;
  218086. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  218087. {
  218088. trappedErrorCode = 0;
  218089. XErrorHandler oldHandler = XSetErrorHandler (errorTrapHandler);
  218090. XShmSegmentInfo segmentInfo;
  218091. zerostruct (segmentInfo);
  218092. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  218093. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  218094. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  218095. xImage->bytes_per_line * xImage->height,
  218096. IPC_CREAT | 0777)) >= 0)
  218097. {
  218098. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  218099. if (segmentInfo.shmaddr != (void*) -1)
  218100. {
  218101. segmentInfo.readOnly = False;
  218102. xImage->data = segmentInfo.shmaddr;
  218103. XSync (display, False);
  218104. if (XShmAttach (display, &segmentInfo) != 0)
  218105. {
  218106. XSync (display, False);
  218107. XShmDetach (display, &segmentInfo);
  218108. isAvailable = true;
  218109. }
  218110. }
  218111. XFlush (display);
  218112. XDestroyImage (xImage);
  218113. shmdt (segmentInfo.shmaddr);
  218114. }
  218115. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  218116. XSetErrorHandler (oldHandler);
  218117. if (trappedErrorCode != 0)
  218118. isAvailable = false;
  218119. }
  218120. }
  218121. return isAvailable;
  218122. }
  218123. }
  218124. #endif
  218125. #if JUCE_USE_XRENDER
  218126. namespace XRender
  218127. {
  218128. typedef Status (*tXRenderQueryVersion) (Display*, int*, int*);
  218129. typedef XRenderPictFormat* (*tXrenderFindStandardFormat) (Display*, int);
  218130. typedef XRenderPictFormat* (*tXRenderFindFormat) (Display*, unsigned long, XRenderPictFormat*, int);
  218131. typedef XRenderPictFormat* (*tXRenderFindVisualFormat) (Display*, Visual*);
  218132. static tXRenderQueryVersion xRenderQueryVersion = 0;
  218133. static tXrenderFindStandardFormat xRenderFindStandardFormat = 0;
  218134. static tXRenderFindFormat xRenderFindFormat = 0;
  218135. static tXRenderFindVisualFormat xRenderFindVisualFormat = 0;
  218136. static bool isAvailable()
  218137. {
  218138. static bool hasLoaded = false;
  218139. if (! hasLoaded)
  218140. {
  218141. ScopedXLock xlock;
  218142. hasLoaded = true;
  218143. void* h = dlopen ("libXrender.so", RTLD_GLOBAL | RTLD_NOW);
  218144. if (h != 0)
  218145. {
  218146. xRenderQueryVersion = (tXRenderQueryVersion) dlsym (h, "XRenderQueryVersion");
  218147. xRenderFindStandardFormat = (tXrenderFindStandardFormat) dlsym (h, "XrenderFindStandardFormat");
  218148. xRenderFindFormat = (tXRenderFindFormat) dlsym (h, "XRenderFindFormat");
  218149. xRenderFindVisualFormat = (tXRenderFindVisualFormat) dlsym (h, "XRenderFindVisualFormat");
  218150. }
  218151. if (xRenderQueryVersion != 0
  218152. && xRenderFindStandardFormat != 0
  218153. && xRenderFindFormat != 0
  218154. && xRenderFindVisualFormat != 0)
  218155. {
  218156. int major, minor;
  218157. if (xRenderQueryVersion (display, &major, &minor))
  218158. return true;
  218159. }
  218160. xRenderQueryVersion = 0;
  218161. }
  218162. return xRenderQueryVersion != 0;
  218163. }
  218164. static XRenderPictFormat* findPictureFormat()
  218165. {
  218166. ScopedXLock xlock;
  218167. XRenderPictFormat* pictFormat = 0;
  218168. if (isAvailable())
  218169. {
  218170. pictFormat = xRenderFindStandardFormat (display, PictStandardARGB32);
  218171. if (pictFormat == 0)
  218172. {
  218173. XRenderPictFormat desiredFormat;
  218174. desiredFormat.type = PictTypeDirect;
  218175. desiredFormat.depth = 32;
  218176. desiredFormat.direct.alphaMask = 0xff;
  218177. desiredFormat.direct.redMask = 0xff;
  218178. desiredFormat.direct.greenMask = 0xff;
  218179. desiredFormat.direct.blueMask = 0xff;
  218180. desiredFormat.direct.alpha = 24;
  218181. desiredFormat.direct.red = 16;
  218182. desiredFormat.direct.green = 8;
  218183. desiredFormat.direct.blue = 0;
  218184. pictFormat = xRenderFindFormat (display,
  218185. PictFormatType | PictFormatDepth
  218186. | PictFormatRedMask | PictFormatRed
  218187. | PictFormatGreenMask | PictFormatGreen
  218188. | PictFormatBlueMask | PictFormatBlue
  218189. | PictFormatAlphaMask | PictFormatAlpha,
  218190. &desiredFormat,
  218191. 0);
  218192. }
  218193. }
  218194. return pictFormat;
  218195. }
  218196. }
  218197. #endif
  218198. namespace Visuals
  218199. {
  218200. static Visual* findVisualWithDepth (const int desiredDepth) throw()
  218201. {
  218202. ScopedXLock xlock;
  218203. Visual* visual = 0;
  218204. int numVisuals = 0;
  218205. long desiredMask = VisualNoMask;
  218206. XVisualInfo desiredVisual;
  218207. desiredVisual.screen = DefaultScreen (display);
  218208. desiredVisual.depth = desiredDepth;
  218209. desiredMask = VisualScreenMask | VisualDepthMask;
  218210. if (desiredDepth == 32)
  218211. {
  218212. desiredVisual.c_class = TrueColor;
  218213. desiredVisual.red_mask = 0x00FF0000;
  218214. desiredVisual.green_mask = 0x0000FF00;
  218215. desiredVisual.blue_mask = 0x000000FF;
  218216. desiredVisual.bits_per_rgb = 8;
  218217. desiredMask |= VisualClassMask;
  218218. desiredMask |= VisualRedMaskMask;
  218219. desiredMask |= VisualGreenMaskMask;
  218220. desiredMask |= VisualBlueMaskMask;
  218221. desiredMask |= VisualBitsPerRGBMask;
  218222. }
  218223. XVisualInfo* xvinfos = XGetVisualInfo (display,
  218224. desiredMask,
  218225. &desiredVisual,
  218226. &numVisuals);
  218227. if (xvinfos != 0)
  218228. {
  218229. for (int i = 0; i < numVisuals; i++)
  218230. {
  218231. if (xvinfos[i].depth == desiredDepth)
  218232. {
  218233. visual = xvinfos[i].visual;
  218234. break;
  218235. }
  218236. }
  218237. XFree (xvinfos);
  218238. }
  218239. return visual;
  218240. }
  218241. static Visual* findVisualFormat (const int desiredDepth, int& matchedDepth) throw()
  218242. {
  218243. Visual* visual = 0;
  218244. if (desiredDepth == 32)
  218245. {
  218246. #if JUCE_USE_XSHM
  218247. if (XSHMHelpers::isShmAvailable())
  218248. {
  218249. #if JUCE_USE_XRENDER
  218250. if (XRender::isAvailable())
  218251. {
  218252. XRenderPictFormat* pictFormat = XRender::findPictureFormat();
  218253. if (pictFormat != 0)
  218254. {
  218255. int numVisuals = 0;
  218256. XVisualInfo desiredVisual;
  218257. desiredVisual.screen = DefaultScreen (display);
  218258. desiredVisual.depth = 32;
  218259. desiredVisual.bits_per_rgb = 8;
  218260. XVisualInfo* xvinfos = XGetVisualInfo (display,
  218261. VisualScreenMask | VisualDepthMask | VisualBitsPerRGBMask,
  218262. &desiredVisual, &numVisuals);
  218263. if (xvinfos != 0)
  218264. {
  218265. for (int i = 0; i < numVisuals; ++i)
  218266. {
  218267. XRenderPictFormat* pictVisualFormat = XRender::xRenderFindVisualFormat (display, xvinfos[i].visual);
  218268. if (pictVisualFormat != 0
  218269. && pictVisualFormat->type == PictTypeDirect
  218270. && pictVisualFormat->direct.alphaMask)
  218271. {
  218272. visual = xvinfos[i].visual;
  218273. matchedDepth = 32;
  218274. break;
  218275. }
  218276. }
  218277. XFree (xvinfos);
  218278. }
  218279. }
  218280. }
  218281. #endif
  218282. if (visual == 0)
  218283. {
  218284. visual = findVisualWithDepth (32);
  218285. if (visual != 0)
  218286. matchedDepth = 32;
  218287. }
  218288. }
  218289. #endif
  218290. }
  218291. if (visual == 0 && desiredDepth >= 24)
  218292. {
  218293. visual = findVisualWithDepth (24);
  218294. if (visual != 0)
  218295. matchedDepth = 24;
  218296. }
  218297. if (visual == 0 && desiredDepth >= 16)
  218298. {
  218299. visual = findVisualWithDepth (16);
  218300. if (visual != 0)
  218301. matchedDepth = 16;
  218302. }
  218303. return visual;
  218304. }
  218305. }
  218306. class XBitmapImage : public Image::SharedImage
  218307. {
  218308. public:
  218309. XBitmapImage (const Image::PixelFormat format_, const int w, const int h,
  218310. const bool clearImage, const int imageDepth_, Visual* visual)
  218311. : Image::SharedImage (format_, w, h),
  218312. imageDepth (imageDepth_),
  218313. gc (None)
  218314. {
  218315. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  218316. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  218317. lineStride = ((w * pixelStride + 3) & ~3);
  218318. ScopedXLock xlock;
  218319. #if JUCE_USE_XSHM
  218320. usingXShm = false;
  218321. if ((imageDepth > 16) && XSHMHelpers::isShmAvailable())
  218322. {
  218323. zerostruct (segmentInfo);
  218324. segmentInfo.shmid = -1;
  218325. segmentInfo.shmaddr = (char *) -1;
  218326. segmentInfo.readOnly = False;
  218327. xImage = XShmCreateImage (display, visual, imageDepth, ZPixmap, 0, &segmentInfo, w, h);
  218328. if (xImage != 0)
  218329. {
  218330. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  218331. xImage->bytes_per_line * xImage->height,
  218332. IPC_CREAT | 0777)) >= 0)
  218333. {
  218334. if (segmentInfo.shmid != -1)
  218335. {
  218336. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  218337. if (segmentInfo.shmaddr != (void*) -1)
  218338. {
  218339. segmentInfo.readOnly = False;
  218340. xImage->data = segmentInfo.shmaddr;
  218341. imageData = (uint8*) segmentInfo.shmaddr;
  218342. if (XShmAttach (display, &segmentInfo) != 0)
  218343. usingXShm = true;
  218344. else
  218345. jassertfalse;
  218346. }
  218347. else
  218348. {
  218349. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  218350. }
  218351. }
  218352. }
  218353. }
  218354. }
  218355. if (! usingXShm)
  218356. #endif
  218357. {
  218358. imageDataAllocated.malloc (lineStride * h);
  218359. imageData = imageDataAllocated;
  218360. if (format_ == Image::ARGB && clearImage)
  218361. zeromem (imageData, h * lineStride);
  218362. xImage = (XImage*) juce_calloc (sizeof (XImage));
  218363. xImage->width = w;
  218364. xImage->height = h;
  218365. xImage->xoffset = 0;
  218366. xImage->format = ZPixmap;
  218367. xImage->data = (char*) imageData;
  218368. xImage->byte_order = ImageByteOrder (display);
  218369. xImage->bitmap_unit = BitmapUnit (display);
  218370. xImage->bitmap_bit_order = BitmapBitOrder (display);
  218371. xImage->bitmap_pad = 32;
  218372. xImage->depth = pixelStride * 8;
  218373. xImage->bytes_per_line = lineStride;
  218374. xImage->bits_per_pixel = pixelStride * 8;
  218375. xImage->red_mask = 0x00FF0000;
  218376. xImage->green_mask = 0x0000FF00;
  218377. xImage->blue_mask = 0x000000FF;
  218378. if (imageDepth == 16)
  218379. {
  218380. const int pixelStride = 2;
  218381. const int lineStride = ((w * pixelStride + 3) & ~3);
  218382. imageData16Bit.malloc (lineStride * h);
  218383. xImage->data = imageData16Bit;
  218384. xImage->bitmap_pad = 16;
  218385. xImage->depth = pixelStride * 8;
  218386. xImage->bytes_per_line = lineStride;
  218387. xImage->bits_per_pixel = pixelStride * 8;
  218388. xImage->red_mask = visual->red_mask;
  218389. xImage->green_mask = visual->green_mask;
  218390. xImage->blue_mask = visual->blue_mask;
  218391. }
  218392. if (! XInitImage (xImage))
  218393. jassertfalse;
  218394. }
  218395. }
  218396. ~XBitmapImage()
  218397. {
  218398. ScopedXLock xlock;
  218399. if (gc != None)
  218400. XFreeGC (display, gc);
  218401. #if JUCE_USE_XSHM
  218402. if (usingXShm)
  218403. {
  218404. XShmDetach (display, &segmentInfo);
  218405. XFlush (display);
  218406. XDestroyImage (xImage);
  218407. shmdt (segmentInfo.shmaddr);
  218408. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  218409. }
  218410. else
  218411. #endif
  218412. {
  218413. xImage->data = 0;
  218414. XDestroyImage (xImage);
  218415. }
  218416. }
  218417. Image::ImageType getType() const { return Image::NativeImage; }
  218418. LowLevelGraphicsContext* createLowLevelContext()
  218419. {
  218420. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  218421. }
  218422. SharedImage* clone()
  218423. {
  218424. jassertfalse;
  218425. return 0;
  218426. }
  218427. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  218428. {
  218429. ScopedXLock xlock;
  218430. if (gc == None)
  218431. {
  218432. XGCValues gcvalues;
  218433. gcvalues.foreground = None;
  218434. gcvalues.background = None;
  218435. gcvalues.function = GXcopy;
  218436. gcvalues.plane_mask = AllPlanes;
  218437. gcvalues.clip_mask = None;
  218438. gcvalues.graphics_exposures = False;
  218439. gc = XCreateGC (display, window,
  218440. GCBackground | GCForeground | GCFunction | GCPlaneMask | GCClipMask | GCGraphicsExposures,
  218441. &gcvalues);
  218442. }
  218443. if (imageDepth == 16)
  218444. {
  218445. const uint32 rMask = xImage->red_mask;
  218446. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  218447. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  218448. const uint32 gMask = xImage->green_mask;
  218449. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  218450. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  218451. const uint32 bMask = xImage->blue_mask;
  218452. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  218453. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  218454. const Image::BitmapData srcData (Image (this), 0, 0, width, height);
  218455. for (int y = sy; y < sy + dh; ++y)
  218456. {
  218457. const uint8* p = srcData.getPixelPointer (sx, y);
  218458. for (int x = sx; x < sx + dw; ++x)
  218459. {
  218460. const PixelRGB* const pixel = (const PixelRGB*) p;
  218461. p += srcData.pixelStride;
  218462. XPutPixel (xImage, x, y,
  218463. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  218464. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  218465. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  218466. }
  218467. }
  218468. }
  218469. // blit results to screen.
  218470. #if JUCE_USE_XSHM
  218471. if (usingXShm)
  218472. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, True);
  218473. else
  218474. #endif
  218475. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  218476. }
  218477. juce_UseDebuggingNewOperator
  218478. private:
  218479. XImage* xImage;
  218480. const int imageDepth;
  218481. HeapBlock <uint8> imageDataAllocated;
  218482. HeapBlock <char> imageData16Bit;
  218483. GC gc;
  218484. #if JUCE_USE_XSHM
  218485. XShmSegmentInfo segmentInfo;
  218486. bool usingXShm;
  218487. #endif
  218488. static int getShiftNeeded (const uint32 mask) throw()
  218489. {
  218490. for (int i = 32; --i >= 0;)
  218491. if (((mask >> i) & 1) != 0)
  218492. return i - 7;
  218493. jassertfalse;
  218494. return 0;
  218495. }
  218496. };
  218497. class LinuxComponentPeer : public ComponentPeer
  218498. {
  218499. public:
  218500. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  218501. : ComponentPeer (component, windowStyleFlags),
  218502. windowH (0),
  218503. parentWindow (0),
  218504. wx (0),
  218505. wy (0),
  218506. ww (0),
  218507. wh (0),
  218508. fullScreen (false),
  218509. mapped (false),
  218510. visual (0),
  218511. depth (0)
  218512. {
  218513. // it's dangerous to create a window on a thread other than the message thread..
  218514. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  218515. repainter = new LinuxRepaintManager (this);
  218516. createWindow();
  218517. setTitle (component->getName());
  218518. }
  218519. ~LinuxComponentPeer()
  218520. {
  218521. // it's dangerous to delete a window on a thread other than the message thread..
  218522. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  218523. deleteIconPixmaps();
  218524. destroyWindow();
  218525. windowH = 0;
  218526. }
  218527. void* getNativeHandle() const
  218528. {
  218529. return (void*) windowH;
  218530. }
  218531. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  218532. {
  218533. XPointer peer = 0;
  218534. ScopedXLock xlock;
  218535. if (! XFindContext (display, (XID) windowHandle, windowHandleXContext, &peer))
  218536. {
  218537. if (peer != 0 && ! ComponentPeer::isValidPeer ((LinuxComponentPeer*) peer))
  218538. peer = 0;
  218539. }
  218540. return (LinuxComponentPeer*) peer;
  218541. }
  218542. void setVisible (bool shouldBeVisible)
  218543. {
  218544. ScopedXLock xlock;
  218545. if (shouldBeVisible)
  218546. XMapWindow (display, windowH);
  218547. else
  218548. XUnmapWindow (display, windowH);
  218549. }
  218550. void setTitle (const String& title)
  218551. {
  218552. setWindowTitle (windowH, title);
  218553. }
  218554. void setPosition (int x, int y)
  218555. {
  218556. setBounds (x, y, ww, wh, false);
  218557. }
  218558. void setSize (int w, int h)
  218559. {
  218560. setBounds (wx, wy, w, h, false);
  218561. }
  218562. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  218563. {
  218564. fullScreen = isNowFullScreen;
  218565. if (windowH != 0)
  218566. {
  218567. Component::SafePointer<Component> deletionChecker (component);
  218568. wx = x;
  218569. wy = y;
  218570. ww = jmax (1, w);
  218571. wh = jmax (1, h);
  218572. ScopedXLock xlock;
  218573. // Make sure the Window manager does what we want
  218574. XSizeHints* hints = XAllocSizeHints();
  218575. hints->flags = USSize | USPosition;
  218576. hints->width = ww;
  218577. hints->height = wh;
  218578. hints->x = wx;
  218579. hints->y = wy;
  218580. if ((getStyleFlags() & (windowHasTitleBar | windowIsResizable)) == windowHasTitleBar)
  218581. {
  218582. hints->min_width = hints->max_width = hints->width;
  218583. hints->min_height = hints->max_height = hints->height;
  218584. hints->flags |= PMinSize | PMaxSize;
  218585. }
  218586. XSetWMNormalHints (display, windowH, hints);
  218587. XFree (hints);
  218588. XMoveResizeWindow (display, windowH,
  218589. wx - windowBorder.getLeft(),
  218590. wy - windowBorder.getTop(), ww, wh);
  218591. if (deletionChecker != 0)
  218592. {
  218593. updateBorderSize();
  218594. handleMovedOrResized();
  218595. }
  218596. }
  218597. }
  218598. const Rectangle<int> getBounds() const { return Rectangle<int> (wx, wy, ww, wh); }
  218599. const Point<int> getScreenPosition() const { return Point<int> (wx, wy); }
  218600. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  218601. {
  218602. return relativePosition + getScreenPosition();
  218603. }
  218604. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  218605. {
  218606. return screenPosition - getScreenPosition();
  218607. }
  218608. void setMinimised (bool shouldBeMinimised)
  218609. {
  218610. if (shouldBeMinimised)
  218611. {
  218612. Window root = RootWindow (display, DefaultScreen (display));
  218613. XClientMessageEvent clientMsg;
  218614. clientMsg.display = display;
  218615. clientMsg.window = windowH;
  218616. clientMsg.type = ClientMessage;
  218617. clientMsg.format = 32;
  218618. clientMsg.message_type = Atoms::ChangeState;
  218619. clientMsg.data.l[0] = IconicState;
  218620. ScopedXLock xlock;
  218621. XSendEvent (display, root, false, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent*) &clientMsg);
  218622. }
  218623. else
  218624. {
  218625. setVisible (true);
  218626. }
  218627. }
  218628. bool isMinimised() const
  218629. {
  218630. bool minimised = false;
  218631. unsigned char* stateProp;
  218632. unsigned long nitems, bytesLeft;
  218633. Atom actualType;
  218634. int actualFormat;
  218635. ScopedXLock xlock;
  218636. if (XGetWindowProperty (display, windowH, Atoms::State, 0, 64, False,
  218637. Atoms::State, &actualType, &actualFormat, &nitems, &bytesLeft,
  218638. &stateProp) == Success
  218639. && actualType == Atoms::State
  218640. && actualFormat == 32
  218641. && nitems > 0)
  218642. {
  218643. if (((unsigned long*) stateProp)[0] == IconicState)
  218644. minimised = true;
  218645. XFree (stateProp);
  218646. }
  218647. return minimised;
  218648. }
  218649. void setFullScreen (const bool shouldBeFullScreen)
  218650. {
  218651. Rectangle<int> r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  218652. setMinimised (false);
  218653. if (fullScreen != shouldBeFullScreen)
  218654. {
  218655. if (shouldBeFullScreen)
  218656. r = Desktop::getInstance().getMainMonitorArea();
  218657. if (! r.isEmpty())
  218658. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  218659. getComponent()->repaint();
  218660. }
  218661. }
  218662. bool isFullScreen() const
  218663. {
  218664. return fullScreen;
  218665. }
  218666. bool isChildWindowOf (Window possibleParent) const
  218667. {
  218668. Window* windowList = 0;
  218669. uint32 windowListSize = 0;
  218670. Window parent, root;
  218671. ScopedXLock xlock;
  218672. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  218673. {
  218674. if (windowList != 0)
  218675. XFree (windowList);
  218676. return parent == possibleParent;
  218677. }
  218678. return false;
  218679. }
  218680. bool isFrontWindow() const
  218681. {
  218682. Window* windowList = 0;
  218683. uint32 windowListSize = 0;
  218684. bool result = false;
  218685. ScopedXLock xlock;
  218686. Window parent, root = RootWindow (display, DefaultScreen (display));
  218687. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  218688. {
  218689. for (int i = windowListSize; --i >= 0;)
  218690. {
  218691. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  218692. if (peer != 0)
  218693. {
  218694. result = (peer == this);
  218695. break;
  218696. }
  218697. }
  218698. }
  218699. if (windowList != 0)
  218700. XFree (windowList);
  218701. return result;
  218702. }
  218703. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  218704. {
  218705. int x = position.getX();
  218706. int y = position.getY();
  218707. if (((unsigned int) x) >= (unsigned int) ww
  218708. || ((unsigned int) y) >= (unsigned int) wh)
  218709. return false;
  218710. bool inFront = false;
  218711. for (int i = 0; i < Desktop::getInstance().getNumComponents(); ++i)
  218712. {
  218713. Component* const c = Desktop::getInstance().getComponent (i);
  218714. if (inFront)
  218715. {
  218716. if (c->contains (x + wx - c->getScreenX(),
  218717. y + wy - c->getScreenY()))
  218718. {
  218719. return false;
  218720. }
  218721. }
  218722. else if (c == getComponent())
  218723. {
  218724. inFront = true;
  218725. }
  218726. }
  218727. if (trueIfInAChildWindow)
  218728. return true;
  218729. ::Window root, child;
  218730. unsigned int bw, depth;
  218731. int wx, wy, w, h;
  218732. ScopedXLock xlock;
  218733. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  218734. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  218735. &bw, &depth))
  218736. {
  218737. return false;
  218738. }
  218739. if (! XTranslateCoordinates (display, windowH, windowH, x, y, &wx, &wy, &child))
  218740. return false;
  218741. return child == None;
  218742. }
  218743. const BorderSize getFrameSize() const
  218744. {
  218745. return BorderSize();
  218746. }
  218747. bool setAlwaysOnTop (bool alwaysOnTop)
  218748. {
  218749. return false;
  218750. }
  218751. void toFront (bool makeActive)
  218752. {
  218753. if (makeActive)
  218754. {
  218755. setVisible (true);
  218756. grabFocus();
  218757. }
  218758. XEvent ev;
  218759. ev.xclient.type = ClientMessage;
  218760. ev.xclient.serial = 0;
  218761. ev.xclient.send_event = True;
  218762. ev.xclient.message_type = Atoms::ActiveWin;
  218763. ev.xclient.window = windowH;
  218764. ev.xclient.format = 32;
  218765. ev.xclient.data.l[0] = 2;
  218766. ev.xclient.data.l[1] = CurrentTime;
  218767. ev.xclient.data.l[2] = 0;
  218768. ev.xclient.data.l[3] = 0;
  218769. ev.xclient.data.l[4] = 0;
  218770. {
  218771. ScopedXLock xlock;
  218772. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  218773. False, SubstructureRedirectMask | SubstructureNotifyMask, &ev);
  218774. XWindowAttributes attr;
  218775. XGetWindowAttributes (display, windowH, &attr);
  218776. if (component->isAlwaysOnTop())
  218777. XRaiseWindow (display, windowH);
  218778. XSync (display, False);
  218779. }
  218780. handleBroughtToFront();
  218781. }
  218782. void toBehind (ComponentPeer* other)
  218783. {
  218784. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  218785. jassert (otherPeer != 0); // wrong type of window?
  218786. if (otherPeer != 0)
  218787. {
  218788. setMinimised (false);
  218789. Window newStack[] = { otherPeer->windowH, windowH };
  218790. ScopedXLock xlock;
  218791. XRestackWindows (display, newStack, 2);
  218792. }
  218793. }
  218794. bool isFocused() const
  218795. {
  218796. int revert = 0;
  218797. Window focusedWindow = 0;
  218798. ScopedXLock xlock;
  218799. XGetInputFocus (display, &focusedWindow, &revert);
  218800. return focusedWindow == windowH;
  218801. }
  218802. void grabFocus()
  218803. {
  218804. XWindowAttributes atts;
  218805. ScopedXLock xlock;
  218806. if (windowH != 0
  218807. && XGetWindowAttributes (display, windowH, &atts)
  218808. && atts.map_state == IsViewable
  218809. && ! isFocused())
  218810. {
  218811. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  218812. isActiveApplication = true;
  218813. }
  218814. }
  218815. void textInputRequired (const Point<int>&)
  218816. {
  218817. }
  218818. void repaint (const Rectangle<int>& area)
  218819. {
  218820. repainter->repaint (area.getIntersection (getComponent()->getLocalBounds()));
  218821. }
  218822. void performAnyPendingRepaintsNow()
  218823. {
  218824. repainter->performAnyPendingRepaintsNow();
  218825. }
  218826. static Pixmap juce_createColourPixmapFromImage (Display* display, const Image& image)
  218827. {
  218828. ScopedXLock xlock;
  218829. const int width = image.getWidth();
  218830. const int height = image.getHeight();
  218831. HeapBlock <char> colour (width * height);
  218832. int index = 0;
  218833. for (int y = 0; y < height; ++y)
  218834. for (int x = 0; x < width; ++x)
  218835. colour[index++] = static_cast<char> (image.getPixelAt (x, y).getARGB());
  218836. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  218837. 0, colour.getData(),
  218838. width, height, 32, 0);
  218839. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  218840. width, height, 24);
  218841. GC gc = XCreateGC (display, pixmap, 0, 0);
  218842. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  218843. XFreeGC (display, gc);
  218844. return pixmap;
  218845. }
  218846. static Pixmap juce_createMaskPixmapFromImage (Display* display, const Image& image)
  218847. {
  218848. ScopedXLock xlock;
  218849. const int width = image.getWidth();
  218850. const int height = image.getHeight();
  218851. const int stride = (width + 7) >> 3;
  218852. HeapBlock <char> mask;
  218853. mask.calloc (stride * height);
  218854. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  218855. for (int y = 0; y < height; ++y)
  218856. {
  218857. for (int x = 0; x < width; ++x)
  218858. {
  218859. const char bit = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  218860. const int offset = y * stride + (x >> 3);
  218861. if (image.getPixelAt (x, y).getAlpha() >= 128)
  218862. mask[offset] |= bit;
  218863. }
  218864. }
  218865. return XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  218866. mask.getData(), width, height, 1, 0, 1);
  218867. }
  218868. void setIcon (const Image& newIcon)
  218869. {
  218870. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  218871. HeapBlock <unsigned long> data (dataSize);
  218872. int index = 0;
  218873. data[index++] = newIcon.getWidth();
  218874. data[index++] = newIcon.getHeight();
  218875. for (int y = 0; y < newIcon.getHeight(); ++y)
  218876. for (int x = 0; x < newIcon.getWidth(); ++x)
  218877. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  218878. ScopedXLock xlock;
  218879. XChangeProperty (display, windowH,
  218880. XInternAtom (display, "_NET_WM_ICON", False),
  218881. XA_CARDINAL, 32, PropModeReplace,
  218882. reinterpret_cast<unsigned char*> (data.getData()), dataSize);
  218883. deleteIconPixmaps();
  218884. XWMHints* wmHints = XGetWMHints (display, windowH);
  218885. if (wmHints == 0)
  218886. wmHints = XAllocWMHints();
  218887. wmHints->flags |= IconPixmapHint | IconMaskHint;
  218888. wmHints->icon_pixmap = juce_createColourPixmapFromImage (display, newIcon);
  218889. wmHints->icon_mask = juce_createMaskPixmapFromImage (display, newIcon);
  218890. XSetWMHints (display, windowH, wmHints);
  218891. XFree (wmHints);
  218892. XSync (display, False);
  218893. }
  218894. void deleteIconPixmaps()
  218895. {
  218896. ScopedXLock xlock;
  218897. XWMHints* wmHints = XGetWMHints (display, windowH);
  218898. if (wmHints != 0)
  218899. {
  218900. if ((wmHints->flags & IconPixmapHint) != 0)
  218901. {
  218902. wmHints->flags &= ~IconPixmapHint;
  218903. XFreePixmap (display, wmHints->icon_pixmap);
  218904. }
  218905. if ((wmHints->flags & IconMaskHint) != 0)
  218906. {
  218907. wmHints->flags &= ~IconMaskHint;
  218908. XFreePixmap (display, wmHints->icon_mask);
  218909. }
  218910. XSetWMHints (display, windowH, wmHints);
  218911. XFree (wmHints);
  218912. }
  218913. }
  218914. void handleWindowMessage (XEvent* event)
  218915. {
  218916. switch (event->xany.type)
  218917. {
  218918. case 2: // 'KeyPress'
  218919. {
  218920. ScopedXLock xlock;
  218921. XKeyEvent* const keyEvent = (XKeyEvent*) &event->xkey;
  218922. updateKeyStates (keyEvent->keycode, true);
  218923. char utf8 [64];
  218924. zeromem (utf8, sizeof (utf8));
  218925. KeySym sym;
  218926. {
  218927. const char* oldLocale = ::setlocale (LC_ALL, 0);
  218928. ::setlocale (LC_ALL, "");
  218929. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  218930. ::setlocale (LC_ALL, oldLocale);
  218931. }
  218932. const juce_wchar unicodeChar = String::fromUTF8 (utf8, sizeof (utf8) - 1) [0];
  218933. int keyCode = (int) unicodeChar;
  218934. if (keyCode < 0x20)
  218935. keyCode = XKeycodeToKeysym (display, keyEvent->keycode, currentModifiers.isShiftDown() ? 1 : 0);
  218936. const ModifierKeys oldMods (currentModifiers);
  218937. bool keyPressed = false;
  218938. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  218939. if ((sym & 0xff00) == 0xff00)
  218940. {
  218941. // Translate keypad
  218942. if (sym == XK_KP_Divide)
  218943. keyCode = XK_slash;
  218944. else if (sym == XK_KP_Multiply)
  218945. keyCode = XK_asterisk;
  218946. else if (sym == XK_KP_Subtract)
  218947. keyCode = XK_hyphen;
  218948. else if (sym == XK_KP_Add)
  218949. keyCode = XK_plus;
  218950. else if (sym == XK_KP_Enter)
  218951. keyCode = XK_Return;
  218952. else if (sym == XK_KP_Decimal)
  218953. keyCode = Keys::numLock ? XK_period : XK_Delete;
  218954. else if (sym == XK_KP_0)
  218955. keyCode = Keys::numLock ? XK_0 : XK_Insert;
  218956. else if (sym == XK_KP_1)
  218957. keyCode = Keys::numLock ? XK_1 : XK_End;
  218958. else if (sym == XK_KP_2)
  218959. keyCode = Keys::numLock ? XK_2 : XK_Down;
  218960. else if (sym == XK_KP_3)
  218961. keyCode = Keys::numLock ? XK_3 : XK_Page_Down;
  218962. else if (sym == XK_KP_4)
  218963. keyCode = Keys::numLock ? XK_4 : XK_Left;
  218964. else if (sym == XK_KP_5)
  218965. keyCode = XK_5;
  218966. else if (sym == XK_KP_6)
  218967. keyCode = Keys::numLock ? XK_6 : XK_Right;
  218968. else if (sym == XK_KP_7)
  218969. keyCode = Keys::numLock ? XK_7 : XK_Home;
  218970. else if (sym == XK_KP_8)
  218971. keyCode = Keys::numLock ? XK_8 : XK_Up;
  218972. else if (sym == XK_KP_9)
  218973. keyCode = Keys::numLock ? XK_9 : XK_Page_Up;
  218974. switch (sym)
  218975. {
  218976. case XK_Left:
  218977. case XK_Right:
  218978. case XK_Up:
  218979. case XK_Down:
  218980. case XK_Page_Up:
  218981. case XK_Page_Down:
  218982. case XK_End:
  218983. case XK_Home:
  218984. case XK_Delete:
  218985. case XK_Insert:
  218986. keyPressed = true;
  218987. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  218988. break;
  218989. case XK_Tab:
  218990. case XK_Return:
  218991. case XK_Escape:
  218992. case XK_BackSpace:
  218993. keyPressed = true;
  218994. keyCode &= 0xff;
  218995. break;
  218996. default:
  218997. {
  218998. if (sym >= XK_F1 && sym <= XK_F16)
  218999. {
  219000. keyPressed = true;
  219001. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  219002. }
  219003. break;
  219004. }
  219005. }
  219006. }
  219007. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  219008. keyPressed = true;
  219009. if (oldMods != currentModifiers)
  219010. handleModifierKeysChange();
  219011. if (keyDownChange)
  219012. handleKeyUpOrDown (true);
  219013. if (keyPressed)
  219014. handleKeyPress (keyCode, unicodeChar);
  219015. break;
  219016. }
  219017. case KeyRelease:
  219018. {
  219019. const XKeyEvent* const keyEvent = (const XKeyEvent*) &event->xkey;
  219020. updateKeyStates (keyEvent->keycode, false);
  219021. ScopedXLock xlock;
  219022. KeySym sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  219023. const ModifierKeys oldMods (currentModifiers);
  219024. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  219025. if (oldMods != currentModifiers)
  219026. handleModifierKeysChange();
  219027. if (keyDownChange)
  219028. handleKeyUpOrDown (false);
  219029. break;
  219030. }
  219031. case ButtonPress:
  219032. {
  219033. const XButtonPressedEvent* const buttonPressEvent = (const XButtonPressedEvent*) &event->xbutton;
  219034. updateKeyModifiers (buttonPressEvent->state);
  219035. bool buttonMsg = false;
  219036. const int map = pointerMap [buttonPressEvent->button - Button1];
  219037. if (map == Keys::WheelUp || map == Keys::WheelDown)
  219038. {
  219039. handleMouseWheel (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y),
  219040. getEventTime (buttonPressEvent->time), 0, map == Keys::WheelDown ? -84.0f : 84.0f);
  219041. }
  219042. if (map == Keys::LeftButton)
  219043. {
  219044. currentModifiers = currentModifiers.withFlags (ModifierKeys::leftButtonModifier);
  219045. buttonMsg = true;
  219046. }
  219047. else if (map == Keys::RightButton)
  219048. {
  219049. currentModifiers = currentModifiers.withFlags (ModifierKeys::rightButtonModifier);
  219050. buttonMsg = true;
  219051. }
  219052. else if (map == Keys::MiddleButton)
  219053. {
  219054. currentModifiers = currentModifiers.withFlags (ModifierKeys::middleButtonModifier);
  219055. buttonMsg = true;
  219056. }
  219057. if (buttonMsg)
  219058. {
  219059. toFront (true);
  219060. handleMouseEvent (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y), currentModifiers,
  219061. getEventTime (buttonPressEvent->time));
  219062. }
  219063. clearLastMousePos();
  219064. break;
  219065. }
  219066. case ButtonRelease:
  219067. {
  219068. const XButtonReleasedEvent* const buttonRelEvent = (const XButtonReleasedEvent*) &event->xbutton;
  219069. updateKeyModifiers (buttonRelEvent->state);
  219070. const int map = pointerMap [buttonRelEvent->button - Button1];
  219071. if (map == Keys::LeftButton)
  219072. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::leftButtonModifier);
  219073. else if (map == Keys::RightButton)
  219074. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::rightButtonModifier);
  219075. else if (map == Keys::MiddleButton)
  219076. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::middleButtonModifier);
  219077. handleMouseEvent (0, Point<int> (buttonRelEvent->x, buttonRelEvent->y), currentModifiers,
  219078. getEventTime (buttonRelEvent->time));
  219079. clearLastMousePos();
  219080. break;
  219081. }
  219082. case MotionNotify:
  219083. {
  219084. const XPointerMovedEvent* const movedEvent = (const XPointerMovedEvent*) &event->xmotion;
  219085. updateKeyModifiers (movedEvent->state);
  219086. const Point<int> mousePos (Desktop::getMousePosition());
  219087. if (lastMousePos != mousePos)
  219088. {
  219089. lastMousePos = mousePos;
  219090. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  219091. {
  219092. Window wRoot = 0, wParent = 0;
  219093. {
  219094. ScopedXLock xlock;
  219095. unsigned int numChildren;
  219096. Window* wChild = 0;
  219097. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  219098. }
  219099. if (wParent != 0
  219100. && wParent != windowH
  219101. && wParent != wRoot)
  219102. {
  219103. parentWindow = wParent;
  219104. updateBounds();
  219105. }
  219106. else
  219107. {
  219108. parentWindow = 0;
  219109. }
  219110. }
  219111. handleMouseEvent (0, mousePos - getScreenPosition(), currentModifiers, getEventTime (movedEvent->time));
  219112. }
  219113. break;
  219114. }
  219115. case EnterNotify:
  219116. {
  219117. clearLastMousePos();
  219118. const XEnterWindowEvent* const enterEvent = (const XEnterWindowEvent*) &event->xcrossing;
  219119. if (! currentModifiers.isAnyMouseButtonDown())
  219120. {
  219121. updateKeyModifiers (enterEvent->state);
  219122. handleMouseEvent (0, Point<int> (enterEvent->x, enterEvent->y), currentModifiers, getEventTime (enterEvent->time));
  219123. }
  219124. break;
  219125. }
  219126. case LeaveNotify:
  219127. {
  219128. const XLeaveWindowEvent* const leaveEvent = (const XLeaveWindowEvent*) &event->xcrossing;
  219129. // Suppress the normal leave if we've got a pointer grab, or if
  219130. // it's a bogus one caused by clicking a mouse button when running
  219131. // in a Window manager
  219132. if (((! currentModifiers.isAnyMouseButtonDown()) && leaveEvent->mode == NotifyNormal)
  219133. || leaveEvent->mode == NotifyUngrab)
  219134. {
  219135. updateKeyModifiers (leaveEvent->state);
  219136. handleMouseEvent (0, Point<int> (leaveEvent->x, leaveEvent->y), currentModifiers, getEventTime (leaveEvent->time));
  219137. }
  219138. break;
  219139. }
  219140. case FocusIn:
  219141. {
  219142. isActiveApplication = true;
  219143. if (isFocused())
  219144. handleFocusGain();
  219145. break;
  219146. }
  219147. case FocusOut:
  219148. {
  219149. isActiveApplication = false;
  219150. if (! isFocused())
  219151. handleFocusLoss();
  219152. break;
  219153. }
  219154. case Expose:
  219155. {
  219156. // Batch together all pending expose events
  219157. XExposeEvent* exposeEvent = (XExposeEvent*) &event->xexpose;
  219158. XEvent nextEvent;
  219159. ScopedXLock xlock;
  219160. if (exposeEvent->window != windowH)
  219161. {
  219162. Window child;
  219163. XTranslateCoordinates (display, exposeEvent->window, windowH,
  219164. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  219165. &child);
  219166. }
  219167. repaint (Rectangle<int> (exposeEvent->x, exposeEvent->y,
  219168. exposeEvent->width, exposeEvent->height));
  219169. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  219170. {
  219171. XPeekEvent (display, (XEvent*) &nextEvent);
  219172. if (nextEvent.type != Expose || nextEvent.xany.window != event->xany.window)
  219173. break;
  219174. XNextEvent (display, (XEvent*) &nextEvent);
  219175. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  219176. repaint (Rectangle<int> (nextExposeEvent->x, nextExposeEvent->y,
  219177. nextExposeEvent->width, nextExposeEvent->height));
  219178. }
  219179. break;
  219180. }
  219181. case CirculateNotify:
  219182. case CreateNotify:
  219183. case DestroyNotify:
  219184. // Think we can ignore these
  219185. break;
  219186. case ConfigureNotify:
  219187. {
  219188. updateBounds();
  219189. updateBorderSize();
  219190. handleMovedOrResized();
  219191. // if the native title bar is dragged, need to tell any active menus, etc.
  219192. if ((styleFlags & windowHasTitleBar) != 0
  219193. && component->isCurrentlyBlockedByAnotherModalComponent())
  219194. {
  219195. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  219196. if (currentModalComp != 0)
  219197. currentModalComp->inputAttemptWhenModal();
  219198. }
  219199. XConfigureEvent* const confEvent = (XConfigureEvent*) &event->xconfigure;
  219200. if (confEvent->window == windowH
  219201. && confEvent->above != 0
  219202. && isFrontWindow())
  219203. {
  219204. handleBroughtToFront();
  219205. }
  219206. break;
  219207. }
  219208. case ReparentNotify:
  219209. {
  219210. parentWindow = 0;
  219211. Window wRoot = 0;
  219212. Window* wChild = 0;
  219213. unsigned int numChildren;
  219214. {
  219215. ScopedXLock xlock;
  219216. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  219217. }
  219218. if (parentWindow == windowH || parentWindow == wRoot)
  219219. parentWindow = 0;
  219220. updateBounds();
  219221. updateBorderSize();
  219222. handleMovedOrResized();
  219223. break;
  219224. }
  219225. case GravityNotify:
  219226. {
  219227. updateBounds();
  219228. updateBorderSize();
  219229. handleMovedOrResized();
  219230. break;
  219231. }
  219232. case MapNotify:
  219233. mapped = true;
  219234. handleBroughtToFront();
  219235. break;
  219236. case UnmapNotify:
  219237. mapped = false;
  219238. break;
  219239. case MappingNotify:
  219240. {
  219241. XMappingEvent* mappingEvent = (XMappingEvent*) &event->xmapping;
  219242. if (mappingEvent->request != MappingPointer)
  219243. {
  219244. // Deal with modifier/keyboard mapping
  219245. ScopedXLock xlock;
  219246. XRefreshKeyboardMapping (mappingEvent);
  219247. updateModifierMappings();
  219248. }
  219249. break;
  219250. }
  219251. case ClientMessage:
  219252. {
  219253. const XClientMessageEvent* const clientMsg = (const XClientMessageEvent*) &event->xclient;
  219254. if (clientMsg->message_type == Atoms::Protocols && clientMsg->format == 32)
  219255. {
  219256. const Atom atom = (Atom) clientMsg->data.l[0];
  219257. if (atom == Atoms::ProtocolList [Atoms::PING])
  219258. {
  219259. Window root = RootWindow (display, DefaultScreen (display));
  219260. event->xclient.window = root;
  219261. XSendEvent (display, root, False, NoEventMask, event);
  219262. XFlush (display);
  219263. }
  219264. else if (atom == Atoms::ProtocolList [Atoms::TAKE_FOCUS])
  219265. {
  219266. XWindowAttributes atts;
  219267. ScopedXLock xlock;
  219268. if (clientMsg->window != 0
  219269. && XGetWindowAttributes (display, clientMsg->window, &atts))
  219270. {
  219271. if (atts.map_state == IsViewable)
  219272. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  219273. }
  219274. }
  219275. else if (atom == Atoms::ProtocolList [Atoms::DELETE_WINDOW])
  219276. {
  219277. handleUserClosingWindow();
  219278. }
  219279. }
  219280. else if (clientMsg->message_type == Atoms::XdndEnter)
  219281. {
  219282. handleDragAndDropEnter (clientMsg);
  219283. }
  219284. else if (clientMsg->message_type == Atoms::XdndLeave)
  219285. {
  219286. resetDragAndDrop();
  219287. }
  219288. else if (clientMsg->message_type == Atoms::XdndPosition)
  219289. {
  219290. handleDragAndDropPosition (clientMsg);
  219291. }
  219292. else if (clientMsg->message_type == Atoms::XdndDrop)
  219293. {
  219294. handleDragAndDropDrop (clientMsg);
  219295. }
  219296. else if (clientMsg->message_type == Atoms::XdndStatus)
  219297. {
  219298. handleDragAndDropStatus (clientMsg);
  219299. }
  219300. else if (clientMsg->message_type == Atoms::XdndFinished)
  219301. {
  219302. resetDragAndDrop();
  219303. }
  219304. break;
  219305. }
  219306. case SelectionNotify:
  219307. handleDragAndDropSelection (event);
  219308. break;
  219309. case SelectionClear:
  219310. case SelectionRequest:
  219311. break;
  219312. default:
  219313. #if JUCE_USE_XSHM
  219314. {
  219315. ScopedXLock xlock;
  219316. if (event->xany.type == XShmGetEventBase (display))
  219317. repainter->notifyPaintCompleted();
  219318. }
  219319. #endif
  219320. break;
  219321. }
  219322. }
  219323. void showMouseCursor (Cursor cursor) throw()
  219324. {
  219325. ScopedXLock xlock;
  219326. XDefineCursor (display, windowH, cursor);
  219327. }
  219328. void setTaskBarIcon (const Image& image)
  219329. {
  219330. ScopedXLock xlock;
  219331. taskbarImage = image;
  219332. Screen* const screen = XDefaultScreenOfDisplay (display);
  219333. const int screenNumber = XScreenNumberOfScreen (screen);
  219334. String screenAtom ("_NET_SYSTEM_TRAY_S");
  219335. screenAtom << screenNumber;
  219336. Atom selectionAtom = XInternAtom (display, screenAtom.toUTF8(), false);
  219337. XGrabServer (display);
  219338. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  219339. if (managerWin != None)
  219340. XSelectInput (display, managerWin, StructureNotifyMask);
  219341. XUngrabServer (display);
  219342. XFlush (display);
  219343. if (managerWin != None)
  219344. {
  219345. XEvent ev;
  219346. zerostruct (ev);
  219347. ev.xclient.type = ClientMessage;
  219348. ev.xclient.window = managerWin;
  219349. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  219350. ev.xclient.format = 32;
  219351. ev.xclient.data.l[0] = CurrentTime;
  219352. ev.xclient.data.l[1] = 0 /*SYSTEM_TRAY_REQUEST_DOCK*/;
  219353. ev.xclient.data.l[2] = windowH;
  219354. ev.xclient.data.l[3] = 0;
  219355. ev.xclient.data.l[4] = 0;
  219356. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  219357. XSync (display, False);
  219358. }
  219359. // For older KDE's ...
  219360. long atomData = 1;
  219361. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  219362. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  219363. // For more recent KDE's...
  219364. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  219365. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  219366. // a minimum size must be specified for GNOME and Xfce, otherwise the icon is displayed with a width of 1
  219367. XSizeHints* hints = XAllocSizeHints();
  219368. hints->flags = PMinSize;
  219369. hints->min_width = 22;
  219370. hints->min_height = 22;
  219371. XSetWMNormalHints (display, windowH, hints);
  219372. XFree (hints);
  219373. }
  219374. const Image& getTaskbarIcon() const throw() { return taskbarImage; }
  219375. juce_UseDebuggingNewOperator
  219376. bool dontRepaint;
  219377. static ModifierKeys currentModifiers;
  219378. static bool isActiveApplication;
  219379. private:
  219380. class LinuxRepaintManager : public Timer
  219381. {
  219382. public:
  219383. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  219384. : peer (peer_),
  219385. lastTimeImageUsed (0)
  219386. {
  219387. #if JUCE_USE_XSHM
  219388. shmCompletedDrawing = true;
  219389. useARGBImagesForRendering = XSHMHelpers::isShmAvailable();
  219390. if (useARGBImagesForRendering)
  219391. {
  219392. ScopedXLock xlock;
  219393. XShmSegmentInfo segmentinfo;
  219394. XImage* const testImage
  219395. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  219396. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  219397. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  219398. XDestroyImage (testImage);
  219399. }
  219400. #endif
  219401. }
  219402. ~LinuxRepaintManager()
  219403. {
  219404. }
  219405. void timerCallback()
  219406. {
  219407. #if JUCE_USE_XSHM
  219408. if (! shmCompletedDrawing)
  219409. return;
  219410. #endif
  219411. if (! regionsNeedingRepaint.isEmpty())
  219412. {
  219413. stopTimer();
  219414. performAnyPendingRepaintsNow();
  219415. }
  219416. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  219417. {
  219418. stopTimer();
  219419. image = Image();
  219420. }
  219421. }
  219422. void repaint (const Rectangle<int>& area)
  219423. {
  219424. if (! isTimerRunning())
  219425. startTimer (repaintTimerPeriod);
  219426. regionsNeedingRepaint.add (area);
  219427. }
  219428. void performAnyPendingRepaintsNow()
  219429. {
  219430. #if JUCE_USE_XSHM
  219431. if (! shmCompletedDrawing)
  219432. {
  219433. startTimer (repaintTimerPeriod);
  219434. return;
  219435. }
  219436. #endif
  219437. peer->clearMaskedRegion();
  219438. RectangleList originalRepaintRegion (regionsNeedingRepaint);
  219439. regionsNeedingRepaint.clear();
  219440. const Rectangle<int> totalArea (originalRepaintRegion.getBounds());
  219441. if (! totalArea.isEmpty())
  219442. {
  219443. if (image.isNull() || image.getWidth() < totalArea.getWidth()
  219444. || image.getHeight() < totalArea.getHeight())
  219445. {
  219446. #if JUCE_USE_XSHM
  219447. image = Image (new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  219448. : Image::RGB,
  219449. #else
  219450. image = Image (new XBitmapImage (Image::RGB,
  219451. #endif
  219452. (totalArea.getWidth() + 31) & ~31,
  219453. (totalArea.getHeight() + 31) & ~31,
  219454. false, peer->depth, peer->visual));
  219455. }
  219456. startTimer (repaintTimerPeriod);
  219457. RectangleList adjustedList (originalRepaintRegion);
  219458. adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());
  219459. LowLevelGraphicsSoftwareRenderer context (image, -totalArea.getX(), -totalArea.getY(), adjustedList);
  219460. if (peer->depth == 32)
  219461. {
  219462. RectangleList::Iterator i (originalRepaintRegion);
  219463. while (i.next())
  219464. image.clear (*i.getRectangle() - totalArea.getPosition());
  219465. }
  219466. peer->handlePaint (context);
  219467. if (! peer->maskedRegion.isEmpty())
  219468. originalRepaintRegion.subtract (peer->maskedRegion);
  219469. for (RectangleList::Iterator i (originalRepaintRegion); i.next();)
  219470. {
  219471. #if JUCE_USE_XSHM
  219472. shmCompletedDrawing = false;
  219473. #endif
  219474. const Rectangle<int>& r = *i.getRectangle();
  219475. static_cast<XBitmapImage*> (image.getSharedImage())
  219476. ->blitToWindow (peer->windowH,
  219477. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  219478. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  219479. }
  219480. }
  219481. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  219482. startTimer (repaintTimerPeriod);
  219483. }
  219484. #if JUCE_USE_XSHM
  219485. void notifyPaintCompleted() { shmCompletedDrawing = true; }
  219486. #endif
  219487. private:
  219488. enum { repaintTimerPeriod = 1000 / 100 };
  219489. LinuxComponentPeer* const peer;
  219490. Image image;
  219491. uint32 lastTimeImageUsed;
  219492. RectangleList regionsNeedingRepaint;
  219493. #if JUCE_USE_XSHM
  219494. bool useARGBImagesForRendering, shmCompletedDrawing;
  219495. #endif
  219496. LinuxRepaintManager (const LinuxRepaintManager&);
  219497. LinuxRepaintManager& operator= (const LinuxRepaintManager&);
  219498. };
  219499. ScopedPointer <LinuxRepaintManager> repainter;
  219500. friend class LinuxRepaintManager;
  219501. Window windowH, parentWindow;
  219502. int wx, wy, ww, wh;
  219503. Image taskbarImage;
  219504. bool fullScreen, mapped;
  219505. Visual* visual;
  219506. int depth;
  219507. BorderSize windowBorder;
  219508. struct MotifWmHints
  219509. {
  219510. unsigned long flags;
  219511. unsigned long functions;
  219512. unsigned long decorations;
  219513. long input_mode;
  219514. unsigned long status;
  219515. };
  219516. static void updateKeyStates (const int keycode, const bool press) throw()
  219517. {
  219518. const int keybyte = keycode >> 3;
  219519. const int keybit = (1 << (keycode & 7));
  219520. if (press)
  219521. Keys::keyStates [keybyte] |= keybit;
  219522. else
  219523. Keys::keyStates [keybyte] &= ~keybit;
  219524. }
  219525. static void updateKeyModifiers (const int status) throw()
  219526. {
  219527. int keyMods = 0;
  219528. if (status & ShiftMask) keyMods |= ModifierKeys::shiftModifier;
  219529. if (status & ControlMask) keyMods |= ModifierKeys::ctrlModifier;
  219530. if (status & Keys::AltMask) keyMods |= ModifierKeys::altModifier;
  219531. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  219532. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  219533. Keys::capsLock = ((status & LockMask) != 0);
  219534. }
  219535. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  219536. {
  219537. int modifier = 0;
  219538. bool isModifier = true;
  219539. switch (sym)
  219540. {
  219541. case XK_Shift_L:
  219542. case XK_Shift_R:
  219543. modifier = ModifierKeys::shiftModifier;
  219544. break;
  219545. case XK_Control_L:
  219546. case XK_Control_R:
  219547. modifier = ModifierKeys::ctrlModifier;
  219548. break;
  219549. case XK_Alt_L:
  219550. case XK_Alt_R:
  219551. modifier = ModifierKeys::altModifier;
  219552. break;
  219553. case XK_Num_Lock:
  219554. if (press)
  219555. Keys::numLock = ! Keys::numLock;
  219556. break;
  219557. case XK_Caps_Lock:
  219558. if (press)
  219559. Keys::capsLock = ! Keys::capsLock;
  219560. break;
  219561. case XK_Scroll_Lock:
  219562. break;
  219563. default:
  219564. isModifier = false;
  219565. break;
  219566. }
  219567. if (modifier != 0)
  219568. {
  219569. if (press)
  219570. currentModifiers = currentModifiers.withFlags (modifier);
  219571. else
  219572. currentModifiers = currentModifiers.withoutFlags (modifier);
  219573. }
  219574. return isModifier;
  219575. }
  219576. // Alt and Num lock are not defined by standard X
  219577. // modifier constants: check what they're mapped to
  219578. static void updateModifierMappings() throw()
  219579. {
  219580. ScopedXLock xlock;
  219581. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  219582. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  219583. Keys::AltMask = 0;
  219584. Keys::NumLockMask = 0;
  219585. XModifierKeymap* mapping = XGetModifierMapping (display);
  219586. if (mapping)
  219587. {
  219588. for (int i = 0; i < 8; i++)
  219589. {
  219590. if (mapping->modifiermap [i << 1] == altLeftCode)
  219591. Keys::AltMask = 1 << i;
  219592. else if (mapping->modifiermap [i << 1] == numLockCode)
  219593. Keys::NumLockMask = 1 << i;
  219594. }
  219595. XFreeModifiermap (mapping);
  219596. }
  219597. }
  219598. void removeWindowDecorations (Window wndH)
  219599. {
  219600. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  219601. if (hints != None)
  219602. {
  219603. MotifWmHints motifHints;
  219604. zerostruct (motifHints);
  219605. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  219606. motifHints.decorations = 0;
  219607. ScopedXLock xlock;
  219608. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  219609. (unsigned char*) &motifHints, 4);
  219610. }
  219611. hints = XInternAtom (display, "_WIN_HINTS", True);
  219612. if (hints != None)
  219613. {
  219614. long gnomeHints = 0;
  219615. ScopedXLock xlock;
  219616. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  219617. (unsigned char*) &gnomeHints, 1);
  219618. }
  219619. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  219620. if (hints != None)
  219621. {
  219622. long kwmHints = 2; /*KDE_tinyDecoration*/
  219623. ScopedXLock xlock;
  219624. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  219625. (unsigned char*) &kwmHints, 1);
  219626. }
  219627. }
  219628. void addWindowButtons (Window wndH)
  219629. {
  219630. ScopedXLock xlock;
  219631. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  219632. if (hints != None)
  219633. {
  219634. MotifWmHints motifHints;
  219635. zerostruct (motifHints);
  219636. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  219637. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  219638. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  219639. if ((styleFlags & windowHasCloseButton) != 0)
  219640. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  219641. if ((styleFlags & windowHasMinimiseButton) != 0)
  219642. {
  219643. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  219644. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  219645. }
  219646. if ((styleFlags & windowHasMaximiseButton) != 0)
  219647. {
  219648. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  219649. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  219650. }
  219651. if ((styleFlags & windowIsResizable) != 0)
  219652. {
  219653. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  219654. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  219655. }
  219656. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  219657. }
  219658. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  219659. if (hints != None)
  219660. {
  219661. int netHints [6];
  219662. int num = 0;
  219663. if ((styleFlags & windowIsResizable) != 0)
  219664. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", True);
  219665. if ((styleFlags & windowHasMaximiseButton) != 0)
  219666. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", True);
  219667. if ((styleFlags & windowHasMinimiseButton) != 0)
  219668. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", True);
  219669. if ((styleFlags & windowHasCloseButton) != 0)
  219670. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", True);
  219671. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace, (unsigned char*) &netHints, num);
  219672. }
  219673. }
  219674. void setWindowType()
  219675. {
  219676. int netHints [2];
  219677. int numHints = 0;
  219678. if ((styleFlags & windowIsTemporary) != 0
  219679. || ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
  219680. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_COMBO", True);
  219681. else
  219682. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  219683. netHints[numHints++] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  219684. XChangeProperty (display, windowH, Atoms::WindowType, XA_ATOM, 32, PropModeReplace,
  219685. (unsigned char*) &netHints, numHints);
  219686. numHints = 0;
  219687. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  219688. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_SKIP_TASKBAR", True);
  219689. if (component->isAlwaysOnTop())
  219690. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_ABOVE", True);
  219691. if (numHints > 0)
  219692. XChangeProperty (display, windowH, Atoms::WindowState, XA_ATOM, 32, PropModeReplace,
  219693. (unsigned char*) &netHints, numHints);
  219694. }
  219695. void createWindow()
  219696. {
  219697. ScopedXLock xlock;
  219698. Atoms::initialiseAtoms();
  219699. resetDragAndDrop();
  219700. // Get defaults for various properties
  219701. const int screen = DefaultScreen (display);
  219702. Window root = RootWindow (display, screen);
  219703. // Try to obtain a 32-bit visual or fallback to 24 or 16
  219704. visual = Visuals::findVisualFormat ((styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
  219705. if (visual == 0)
  219706. {
  219707. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  219708. Process::terminate();
  219709. }
  219710. // Create and install a colormap suitable fr our visual
  219711. Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
  219712. XInstallColormap (display, colormap);
  219713. // Set up the window attributes
  219714. XSetWindowAttributes swa;
  219715. swa.border_pixel = 0;
  219716. swa.background_pixmap = None;
  219717. swa.colormap = colormap;
  219718. swa.event_mask = getAllEventsMask();
  219719. windowH = XCreateWindow (display, root,
  219720. 0, 0, 1, 1,
  219721. 0, depth, InputOutput, visual,
  219722. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask,
  219723. &swa);
  219724. XGrabButton (display, AnyButton, AnyModifier, windowH, False,
  219725. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  219726. GrabModeAsync, GrabModeAsync, None, None);
  219727. // Set the window context to identify the window handle object
  219728. if (XSaveContext (display, (XID) windowH, windowHandleXContext, (XPointer) this))
  219729. {
  219730. // Failed
  219731. jassertfalse;
  219732. Logger::outputDebugString ("Failed to create context information for window.\n");
  219733. XDestroyWindow (display, windowH);
  219734. windowH = 0;
  219735. return;
  219736. }
  219737. // Set window manager hints
  219738. XWMHints* wmHints = XAllocWMHints();
  219739. wmHints->flags = InputHint | StateHint;
  219740. wmHints->input = True; // Locally active input model
  219741. wmHints->initial_state = NormalState;
  219742. XSetWMHints (display, windowH, wmHints);
  219743. XFree (wmHints);
  219744. // Set the window type
  219745. setWindowType();
  219746. // Define decoration
  219747. if ((styleFlags & windowHasTitleBar) == 0)
  219748. removeWindowDecorations (windowH);
  219749. else
  219750. addWindowButtons (windowH);
  219751. // Set window name
  219752. setWindowTitle (windowH, getComponent()->getName());
  219753. // Associate the PID, allowing to be shut down when something goes wrong
  219754. unsigned long pid = getpid();
  219755. XChangeProperty (display, windowH, Atoms::Pid, XA_CARDINAL, 32, PropModeReplace,
  219756. (unsigned char*) &pid, 1);
  219757. // Set window manager protocols
  219758. XChangeProperty (display, windowH, Atoms::Protocols, XA_ATOM, 32, PropModeReplace,
  219759. (unsigned char*) Atoms::ProtocolList, 2);
  219760. // Set drag and drop flags
  219761. XChangeProperty (display, windowH, Atoms::XdndTypeList, XA_ATOM, 32, PropModeReplace,
  219762. (const unsigned char*) Atoms::allowedMimeTypes, numElementsInArray (Atoms::allowedMimeTypes));
  219763. XChangeProperty (display, windowH, Atoms::XdndActionList, XA_ATOM, 32, PropModeReplace,
  219764. (const unsigned char*) Atoms::allowedActions, numElementsInArray (Atoms::allowedActions));
  219765. XChangeProperty (display, windowH, Atoms::XdndActionDescription, XA_STRING, 8, PropModeReplace,
  219766. (const unsigned char*) "", 0);
  219767. unsigned long dndVersion = Atoms::DndVersion;
  219768. XChangeProperty (display, windowH, Atoms::XdndAware, XA_ATOM, 32, PropModeReplace,
  219769. (const unsigned char*) &dndVersion, 1);
  219770. // Initialise the pointer and keyboard mapping
  219771. // This is not the same as the logical pointer mapping the X server uses:
  219772. // we don't mess with this.
  219773. static bool mappingInitialised = false;
  219774. if (! mappingInitialised)
  219775. {
  219776. mappingInitialised = true;
  219777. const int numButtons = XGetPointerMapping (display, 0, 0);
  219778. if (numButtons == 2)
  219779. {
  219780. pointerMap[0] = Keys::LeftButton;
  219781. pointerMap[1] = Keys::RightButton;
  219782. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  219783. }
  219784. else if (numButtons >= 3)
  219785. {
  219786. pointerMap[0] = Keys::LeftButton;
  219787. pointerMap[1] = Keys::MiddleButton;
  219788. pointerMap[2] = Keys::RightButton;
  219789. if (numButtons >= 5)
  219790. {
  219791. pointerMap[3] = Keys::WheelUp;
  219792. pointerMap[4] = Keys::WheelDown;
  219793. }
  219794. }
  219795. updateModifierMappings();
  219796. }
  219797. }
  219798. void destroyWindow()
  219799. {
  219800. ScopedXLock xlock;
  219801. XPointer handlePointer;
  219802. if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  219803. XDeleteContext (display, (XID) windowH, windowHandleXContext);
  219804. XDestroyWindow (display, windowH);
  219805. // Wait for it to complete and then remove any events for this
  219806. // window from the event queue.
  219807. XSync (display, false);
  219808. XEvent event;
  219809. while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
  219810. {}
  219811. }
  219812. static int getAllEventsMask() throw()
  219813. {
  219814. return NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  219815. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  219816. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  219817. }
  219818. static int64 getEventTime (::Time t)
  219819. {
  219820. static int64 eventTimeOffset = 0x12345678;
  219821. const int64 thisMessageTime = t;
  219822. if (eventTimeOffset == 0x12345678)
  219823. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  219824. return eventTimeOffset + thisMessageTime;
  219825. }
  219826. static void setWindowTitle (Window xwin, const String& title)
  219827. {
  219828. XTextProperty nameProperty;
  219829. char* strings[] = { const_cast <char*> (title.toUTF8()) };
  219830. ScopedXLock xlock;
  219831. if (XStringListToTextProperty (strings, 1, &nameProperty))
  219832. {
  219833. XSetWMName (display, xwin, &nameProperty);
  219834. XSetWMIconName (display, xwin, &nameProperty);
  219835. XFree (nameProperty.value);
  219836. }
  219837. }
  219838. void updateBorderSize()
  219839. {
  219840. if ((styleFlags & windowHasTitleBar) == 0)
  219841. {
  219842. windowBorder = BorderSize (0);
  219843. }
  219844. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  219845. {
  219846. ScopedXLock xlock;
  219847. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  219848. if (hints != None)
  219849. {
  219850. unsigned char* data = 0;
  219851. unsigned long nitems, bytesLeft;
  219852. Atom actualType;
  219853. int actualFormat;
  219854. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  219855. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  219856. &data) == Success)
  219857. {
  219858. const unsigned long* const sizes = (const unsigned long*) data;
  219859. if (actualFormat == 32)
  219860. windowBorder = BorderSize ((int) sizes[2], (int) sizes[0],
  219861. (int) sizes[3], (int) sizes[1]);
  219862. XFree (data);
  219863. }
  219864. }
  219865. }
  219866. }
  219867. void updateBounds()
  219868. {
  219869. jassert (windowH != 0);
  219870. if (windowH != 0)
  219871. {
  219872. Window root, child;
  219873. unsigned int bw, depth;
  219874. ScopedXLock xlock;
  219875. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  219876. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  219877. &bw, &depth))
  219878. {
  219879. wx = wy = ww = wh = 0;
  219880. }
  219881. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  219882. {
  219883. wx = wy = 0;
  219884. }
  219885. }
  219886. }
  219887. void resetDragAndDrop()
  219888. {
  219889. dragAndDropFiles.clear();
  219890. lastDropPos = Point<int> (-1, -1);
  219891. dragAndDropCurrentMimeType = 0;
  219892. dragAndDropSourceWindow = 0;
  219893. srcMimeTypeAtomList.clear();
  219894. }
  219895. void sendDragAndDropMessage (XClientMessageEvent& msg)
  219896. {
  219897. msg.type = ClientMessage;
  219898. msg.display = display;
  219899. msg.window = dragAndDropSourceWindow;
  219900. msg.format = 32;
  219901. msg.data.l[0] = windowH;
  219902. ScopedXLock xlock;
  219903. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  219904. }
  219905. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  219906. {
  219907. XClientMessageEvent msg;
  219908. zerostruct (msg);
  219909. msg.message_type = Atoms::XdndStatus;
  219910. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  219911. msg.data.l[4] = dropAction;
  219912. sendDragAndDropMessage (msg);
  219913. }
  219914. void sendDragAndDropLeave()
  219915. {
  219916. XClientMessageEvent msg;
  219917. zerostruct (msg);
  219918. msg.message_type = Atoms::XdndLeave;
  219919. sendDragAndDropMessage (msg);
  219920. }
  219921. void sendDragAndDropFinish()
  219922. {
  219923. XClientMessageEvent msg;
  219924. zerostruct (msg);
  219925. msg.message_type = Atoms::XdndFinished;
  219926. sendDragAndDropMessage (msg);
  219927. }
  219928. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  219929. {
  219930. if ((clientMsg->data.l[1] & 1) == 0)
  219931. {
  219932. sendDragAndDropLeave();
  219933. if (dragAndDropFiles.size() > 0)
  219934. handleFileDragExit (dragAndDropFiles);
  219935. dragAndDropFiles.clear();
  219936. }
  219937. }
  219938. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  219939. {
  219940. if (dragAndDropSourceWindow == 0)
  219941. return;
  219942. dragAndDropSourceWindow = clientMsg->data.l[0];
  219943. Point<int> dropPos ((int) clientMsg->data.l[2] >> 16,
  219944. (int) clientMsg->data.l[2] & 0xffff);
  219945. dropPos -= getScreenPosition();
  219946. if (lastDropPos != dropPos)
  219947. {
  219948. lastDropPos = dropPos;
  219949. dragAndDropTimestamp = clientMsg->data.l[3];
  219950. Atom targetAction = Atoms::XdndActionCopy;
  219951. for (int i = numElementsInArray (Atoms::allowedActions); --i >= 0;)
  219952. {
  219953. if ((Atom) clientMsg->data.l[4] == Atoms::allowedActions[i])
  219954. {
  219955. targetAction = Atoms::allowedActions[i];
  219956. break;
  219957. }
  219958. }
  219959. sendDragAndDropStatus (true, targetAction);
  219960. if (dragAndDropFiles.size() == 0)
  219961. updateDraggedFileList (clientMsg);
  219962. if (dragAndDropFiles.size() > 0)
  219963. handleFileDragMove (dragAndDropFiles, dropPos);
  219964. }
  219965. }
  219966. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  219967. {
  219968. if (dragAndDropFiles.size() == 0)
  219969. updateDraggedFileList (clientMsg);
  219970. const StringArray files (dragAndDropFiles);
  219971. const Point<int> lastPos (lastDropPos);
  219972. sendDragAndDropFinish();
  219973. resetDragAndDrop();
  219974. if (files.size() > 0)
  219975. handleFileDragDrop (files, lastPos);
  219976. }
  219977. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  219978. {
  219979. dragAndDropFiles.clear();
  219980. srcMimeTypeAtomList.clear();
  219981. dragAndDropCurrentMimeType = 0;
  219982. const unsigned long dndCurrentVersion = static_cast <unsigned long> (clientMsg->data.l[1] & 0xff000000) >> 24;
  219983. if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
  219984. {
  219985. dragAndDropSourceWindow = 0;
  219986. return;
  219987. }
  219988. dragAndDropSourceWindow = clientMsg->data.l[0];
  219989. if ((clientMsg->data.l[1] & 1) != 0)
  219990. {
  219991. Atom actual;
  219992. int format;
  219993. unsigned long count = 0, remaining = 0;
  219994. unsigned char* data = 0;
  219995. ScopedXLock xlock;
  219996. XGetWindowProperty (display, dragAndDropSourceWindow, Atoms::XdndTypeList,
  219997. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  219998. &count, &remaining, &data);
  219999. if (data != 0)
  220000. {
  220001. if (actual == XA_ATOM && format == 32 && count != 0)
  220002. {
  220003. const unsigned long* const types = (const unsigned long*) data;
  220004. for (unsigned int i = 0; i < count; ++i)
  220005. if (types[i] != None)
  220006. srcMimeTypeAtomList.add (types[i]);
  220007. }
  220008. XFree (data);
  220009. }
  220010. }
  220011. if (srcMimeTypeAtomList.size() == 0)
  220012. {
  220013. for (int i = 2; i < 5; ++i)
  220014. if (clientMsg->data.l[i] != None)
  220015. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  220016. if (srcMimeTypeAtomList.size() == 0)
  220017. {
  220018. dragAndDropSourceWindow = 0;
  220019. return;
  220020. }
  220021. }
  220022. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  220023. for (int j = 0; j < numElementsInArray (Atoms::allowedMimeTypes); ++j)
  220024. if (srcMimeTypeAtomList[i] == Atoms::allowedMimeTypes[j])
  220025. dragAndDropCurrentMimeType = Atoms::allowedMimeTypes[j];
  220026. handleDragAndDropPosition (clientMsg);
  220027. }
  220028. void handleDragAndDropSelection (const XEvent* const evt)
  220029. {
  220030. dragAndDropFiles.clear();
  220031. if (evt->xselection.property != 0)
  220032. {
  220033. StringArray lines;
  220034. {
  220035. MemoryBlock dropData;
  220036. for (;;)
  220037. {
  220038. Atom actual;
  220039. uint8* data = 0;
  220040. unsigned long count = 0, remaining = 0;
  220041. int format = 0;
  220042. ScopedXLock xlock;
  220043. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  220044. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  220045. &format, &count, &remaining, &data) == Success)
  220046. {
  220047. dropData.append (data, count * format / 8);
  220048. XFree (data);
  220049. if (remaining == 0)
  220050. break;
  220051. }
  220052. else
  220053. {
  220054. XFree (data);
  220055. break;
  220056. }
  220057. }
  220058. lines.addLines (dropData.toString());
  220059. }
  220060. for (int i = 0; i < lines.size(); ++i)
  220061. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf ("file://", false, true)));
  220062. dragAndDropFiles.trim();
  220063. dragAndDropFiles.removeEmptyStrings();
  220064. }
  220065. }
  220066. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  220067. {
  220068. dragAndDropFiles.clear();
  220069. if (dragAndDropSourceWindow != None
  220070. && dragAndDropCurrentMimeType != 0)
  220071. {
  220072. dragAndDropTimestamp = clientMsg->data.l[2];
  220073. ScopedXLock xlock;
  220074. XConvertSelection (display,
  220075. Atoms::XdndSelection,
  220076. dragAndDropCurrentMimeType,
  220077. XInternAtom (display, "JXSelectionWindowProperty", 0),
  220078. windowH,
  220079. dragAndDropTimestamp);
  220080. }
  220081. }
  220082. StringArray dragAndDropFiles;
  220083. int dragAndDropTimestamp;
  220084. Point<int> lastDropPos;
  220085. Atom dragAndDropCurrentMimeType;
  220086. Window dragAndDropSourceWindow;
  220087. Array <Atom> srcMimeTypeAtomList;
  220088. static int pointerMap[5];
  220089. static Point<int> lastMousePos;
  220090. static void clearLastMousePos() throw()
  220091. {
  220092. lastMousePos = Point<int> (0x100000, 0x100000);
  220093. }
  220094. };
  220095. ModifierKeys LinuxComponentPeer::currentModifiers;
  220096. bool LinuxComponentPeer::isActiveApplication = false;
  220097. int LinuxComponentPeer::pointerMap[5];
  220098. Point<int> LinuxComponentPeer::lastMousePos;
  220099. bool Process::isForegroundProcess()
  220100. {
  220101. return LinuxComponentPeer::isActiveApplication;
  220102. }
  220103. void ModifierKeys::updateCurrentModifiers() throw()
  220104. {
  220105. currentModifiers = LinuxComponentPeer::currentModifiers;
  220106. }
  220107. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  220108. {
  220109. Window root, child;
  220110. int x, y, winx, winy;
  220111. unsigned int mask;
  220112. int mouseMods = 0;
  220113. ScopedXLock xlock;
  220114. if (XQueryPointer (display, RootWindow (display, DefaultScreen (display)),
  220115. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  220116. {
  220117. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  220118. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  220119. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  220120. }
  220121. LinuxComponentPeer::currentModifiers = LinuxComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  220122. return LinuxComponentPeer::currentModifiers;
  220123. }
  220124. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  220125. {
  220126. if (enableOrDisable)
  220127. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  220128. }
  220129. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  220130. {
  220131. return new LinuxComponentPeer (this, styleFlags);
  220132. }
  220133. // (this callback is hooked up in the messaging code)
  220134. void juce_windowMessageReceive (XEvent* event)
  220135. {
  220136. if (event->xany.window != None)
  220137. {
  220138. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  220139. if (ComponentPeer::isValidPeer (peer))
  220140. peer->handleWindowMessage (event);
  220141. }
  220142. else
  220143. {
  220144. switch (event->xany.type)
  220145. {
  220146. case KeymapNotify:
  220147. {
  220148. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  220149. memcpy (Keys::keyStates, keymapEvent->key_vector, 32);
  220150. break;
  220151. }
  220152. default:
  220153. break;
  220154. }
  220155. }
  220156. }
  220157. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool /*clipToWorkArea*/)
  220158. {
  220159. if (display == 0)
  220160. return;
  220161. #if JUCE_USE_XINERAMA
  220162. int major_opcode, first_event, first_error;
  220163. ScopedXLock xlock;
  220164. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error))
  220165. {
  220166. typedef Bool (*tXineramaIsActive) (Display*);
  220167. typedef XineramaScreenInfo* (*tXineramaQueryScreens) (Display*, int*);
  220168. static tXineramaIsActive xXineramaIsActive = 0;
  220169. static tXineramaQueryScreens xXineramaQueryScreens = 0;
  220170. if (xXineramaIsActive == 0 || xXineramaQueryScreens == 0)
  220171. {
  220172. void* h = dlopen ("libXinerama.so", RTLD_GLOBAL | RTLD_NOW);
  220173. if (h == 0)
  220174. h = dlopen ("libXinerama.so.1", RTLD_GLOBAL | RTLD_NOW);
  220175. if (h != 0)
  220176. {
  220177. xXineramaIsActive = (tXineramaIsActive) dlsym (h, "XineramaIsActive");
  220178. xXineramaQueryScreens = (tXineramaQueryScreens) dlsym (h, "XineramaQueryScreens");
  220179. }
  220180. }
  220181. if (xXineramaIsActive != 0
  220182. && xXineramaQueryScreens != 0
  220183. && xXineramaIsActive (display))
  220184. {
  220185. int numMonitors = 0;
  220186. XineramaScreenInfo* const screens = xXineramaQueryScreens (display, &numMonitors);
  220187. if (screens != 0)
  220188. {
  220189. for (int i = numMonitors; --i >= 0;)
  220190. {
  220191. int index = screens[i].screen_number;
  220192. if (index >= 0)
  220193. {
  220194. while (monitorCoords.size() < index)
  220195. monitorCoords.add (Rectangle<int>());
  220196. monitorCoords.set (index, Rectangle<int> (screens[i].x_org,
  220197. screens[i].y_org,
  220198. screens[i].width,
  220199. screens[i].height));
  220200. }
  220201. }
  220202. XFree (screens);
  220203. }
  220204. }
  220205. }
  220206. if (monitorCoords.size() == 0)
  220207. #endif
  220208. {
  220209. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  220210. if (hints != None)
  220211. {
  220212. const int numMonitors = ScreenCount (display);
  220213. for (int i = 0; i < numMonitors; ++i)
  220214. {
  220215. Window root = RootWindow (display, i);
  220216. unsigned long nitems, bytesLeft;
  220217. Atom actualType;
  220218. int actualFormat;
  220219. unsigned char* data = 0;
  220220. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  220221. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  220222. &data) == Success)
  220223. {
  220224. const long* const position = (const long*) data;
  220225. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  220226. monitorCoords.add (Rectangle<int> (position[0], position[1],
  220227. position[2], position[3]));
  220228. XFree (data);
  220229. }
  220230. }
  220231. }
  220232. if (monitorCoords.size() == 0)
  220233. {
  220234. monitorCoords.add (Rectangle<int> (0, 0,
  220235. DisplayWidth (display, DefaultScreen (display)),
  220236. DisplayHeight (display, DefaultScreen (display))));
  220237. }
  220238. }
  220239. }
  220240. void Desktop::createMouseInputSources()
  220241. {
  220242. mouseSources.add (new MouseInputSource (0, true));
  220243. }
  220244. bool Desktop::canUseSemiTransparentWindows() throw()
  220245. {
  220246. int matchedDepth = 0;
  220247. const int desiredDepth = 32;
  220248. return Visuals::findVisualFormat (desiredDepth, matchedDepth) != 0
  220249. && (matchedDepth == desiredDepth);
  220250. }
  220251. const Point<int> Desktop::getMousePosition()
  220252. {
  220253. Window root, child;
  220254. int x, y, winx, winy;
  220255. unsigned int mask;
  220256. ScopedXLock xlock;
  220257. if (XQueryPointer (display,
  220258. RootWindow (display, DefaultScreen (display)),
  220259. &root, &child,
  220260. &x, &y, &winx, &winy, &mask) == False)
  220261. {
  220262. // Pointer not on the default screen
  220263. x = y = -1;
  220264. }
  220265. return Point<int> (x, y);
  220266. }
  220267. void Desktop::setMousePosition (const Point<int>& newPosition)
  220268. {
  220269. ScopedXLock xlock;
  220270. Window root = RootWindow (display, DefaultScreen (display));
  220271. XWarpPointer (display, None, root, 0, 0, 0, 0, newPosition.getX(), newPosition.getY());
  220272. }
  220273. static bool screenSaverAllowed = true;
  220274. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  220275. {
  220276. if (screenSaverAllowed != isEnabled)
  220277. {
  220278. screenSaverAllowed = isEnabled;
  220279. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  220280. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  220281. if (xScreenSaverSuspend == 0)
  220282. {
  220283. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  220284. if (h != 0)
  220285. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  220286. }
  220287. ScopedXLock xlock;
  220288. if (xScreenSaverSuspend != 0)
  220289. xScreenSaverSuspend (display, ! isEnabled);
  220290. }
  220291. }
  220292. bool Desktop::isScreenSaverEnabled()
  220293. {
  220294. return screenSaverAllowed;
  220295. }
  220296. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  220297. {
  220298. ScopedXLock xlock;
  220299. const unsigned int imageW = image.getWidth();
  220300. const unsigned int imageH = image.getHeight();
  220301. #if JUCE_USE_XCURSOR
  220302. {
  220303. typedef XcursorBool (*tXcursorSupportsARGB) (Display*);
  220304. typedef XcursorImage* (*tXcursorImageCreate) (int, int);
  220305. typedef void (*tXcursorImageDestroy) (XcursorImage*);
  220306. typedef Cursor (*tXcursorImageLoadCursor) (Display*, const XcursorImage*);
  220307. static tXcursorSupportsARGB xXcursorSupportsARGB = 0;
  220308. static tXcursorImageCreate xXcursorImageCreate = 0;
  220309. static tXcursorImageDestroy xXcursorImageDestroy = 0;
  220310. static tXcursorImageLoadCursor xXcursorImageLoadCursor = 0;
  220311. static bool hasBeenLoaded = false;
  220312. if (! hasBeenLoaded)
  220313. {
  220314. hasBeenLoaded = true;
  220315. void* h = dlopen ("libXcursor.so", RTLD_GLOBAL | RTLD_NOW);
  220316. if (h != 0)
  220317. {
  220318. xXcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
  220319. xXcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
  220320. xXcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
  220321. xXcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
  220322. if (xXcursorSupportsARGB == 0 || xXcursorImageCreate == 0
  220323. || xXcursorImageLoadCursor == 0 || xXcursorImageDestroy == 0
  220324. || ! xXcursorSupportsARGB (display))
  220325. xXcursorSupportsARGB = 0;
  220326. }
  220327. }
  220328. if (xXcursorSupportsARGB != 0)
  220329. {
  220330. XcursorImage* xcImage = xXcursorImageCreate (imageW, imageH);
  220331. if (xcImage != 0)
  220332. {
  220333. xcImage->xhot = hotspotX;
  220334. xcImage->yhot = hotspotY;
  220335. XcursorPixel* dest = xcImage->pixels;
  220336. for (int y = 0; y < (int) imageH; ++y)
  220337. for (int x = 0; x < (int) imageW; ++x)
  220338. *dest++ = image.getPixelAt (x, y).getARGB();
  220339. void* result = (void*) xXcursorImageLoadCursor (display, xcImage);
  220340. xXcursorImageDestroy (xcImage);
  220341. if (result != 0)
  220342. return result;
  220343. }
  220344. }
  220345. }
  220346. #endif
  220347. Window root = RootWindow (display, DefaultScreen (display));
  220348. unsigned int cursorW, cursorH;
  220349. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  220350. return 0;
  220351. Image im (Image::ARGB, cursorW, cursorH, true);
  220352. {
  220353. Graphics g (im);
  220354. if (imageW > cursorW || imageH > cursorH)
  220355. {
  220356. hotspotX = (hotspotX * cursorW) / imageW;
  220357. hotspotY = (hotspotY * cursorH) / imageH;
  220358. g.drawImageWithin (image, 0, 0, imageW, imageH,
  220359. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  220360. false);
  220361. }
  220362. else
  220363. {
  220364. g.drawImageAt (image, 0, 0);
  220365. }
  220366. }
  220367. const int stride = (cursorW + 7) >> 3;
  220368. HeapBlock <char> maskPlane, sourcePlane;
  220369. maskPlane.calloc (stride * cursorH);
  220370. sourcePlane.calloc (stride * cursorH);
  220371. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  220372. for (int y = cursorH; --y >= 0;)
  220373. {
  220374. for (int x = cursorW; --x >= 0;)
  220375. {
  220376. const char mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  220377. const int offset = y * stride + (x >> 3);
  220378. const Colour c (im.getPixelAt (x, y));
  220379. if (c.getAlpha() >= 128)
  220380. maskPlane[offset] |= mask;
  220381. if (c.getBrightness() >= 0.5f)
  220382. sourcePlane[offset] |= mask;
  220383. }
  220384. }
  220385. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  220386. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  220387. XColor white, black;
  220388. black.red = black.green = black.blue = 0;
  220389. white.red = white.green = white.blue = 0xffff;
  220390. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  220391. XFreePixmap (display, sourcePixmap);
  220392. XFreePixmap (display, maskPixmap);
  220393. return result;
  220394. }
  220395. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool)
  220396. {
  220397. ScopedXLock xlock;
  220398. if (cursorHandle != 0)
  220399. XFreeCursor (display, (Cursor) cursorHandle);
  220400. }
  220401. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  220402. {
  220403. unsigned int shape;
  220404. switch (type)
  220405. {
  220406. case NormalCursor: return None; // Use parent cursor
  220407. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 16, 16, true), 0, 0);
  220408. case WaitCursor: shape = XC_watch; break;
  220409. case IBeamCursor: shape = XC_xterm; break;
  220410. case PointingHandCursor: shape = XC_hand2; break;
  220411. case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  220412. case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  220413. case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  220414. case TopEdgeResizeCursor: shape = XC_top_side; break;
  220415. case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  220416. case LeftEdgeResizeCursor: shape = XC_left_side; break;
  220417. case RightEdgeResizeCursor: shape = XC_right_side; break;
  220418. case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  220419. case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  220420. case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  220421. case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  220422. case CrosshairCursor: shape = XC_crosshair; break;
  220423. case DraggingHandCursor:
  220424. {
  220425. static unsigned char dragHandData[] = { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  220426. 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,
  220427. 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 };
  220428. const int dragHandDataSize = 99;
  220429. return createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, dragHandDataSize), 8, 7);
  220430. }
  220431. case CopyingCursor:
  220432. {
  220433. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  220434. 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,
  220435. 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,
  220436. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  220437. const int copyCursorSize = 119;
  220438. return createMouseCursorFromImage (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), 1, 3);
  220439. }
  220440. default:
  220441. jassertfalse;
  220442. return None;
  220443. }
  220444. ScopedXLock xlock;
  220445. return (void*) XCreateFontCursor (display, shape);
  220446. }
  220447. void MouseCursor::showInWindow (ComponentPeer* peer) const
  220448. {
  220449. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  220450. if (lp != 0)
  220451. lp->showMouseCursor ((Cursor) getHandle());
  220452. }
  220453. void MouseCursor::showInAllWindows() const
  220454. {
  220455. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  220456. showInWindow (ComponentPeer::getPeer (i));
  220457. }
  220458. const Image juce_createIconForFile (const File& file)
  220459. {
  220460. return Image();
  220461. }
  220462. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  220463. {
  220464. return createSoftwareImage (format, width, height, clearImage);
  220465. }
  220466. #if JUCE_OPENGL
  220467. class WindowedGLContext : public OpenGLContext
  220468. {
  220469. public:
  220470. WindowedGLContext (Component* const component,
  220471. const OpenGLPixelFormat& pixelFormat_,
  220472. GLXContext sharedContext)
  220473. : renderContext (0),
  220474. embeddedWindow (0),
  220475. pixelFormat (pixelFormat_),
  220476. swapInterval (0)
  220477. {
  220478. jassert (component != 0);
  220479. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  220480. if (peer == 0)
  220481. return;
  220482. ScopedXLock xlock;
  220483. XSync (display, False);
  220484. GLint attribs [64];
  220485. int n = 0;
  220486. attribs[n++] = GLX_RGBA;
  220487. attribs[n++] = GLX_DOUBLEBUFFER;
  220488. attribs[n++] = GLX_RED_SIZE;
  220489. attribs[n++] = pixelFormat.redBits;
  220490. attribs[n++] = GLX_GREEN_SIZE;
  220491. attribs[n++] = pixelFormat.greenBits;
  220492. attribs[n++] = GLX_BLUE_SIZE;
  220493. attribs[n++] = pixelFormat.blueBits;
  220494. attribs[n++] = GLX_ALPHA_SIZE;
  220495. attribs[n++] = pixelFormat.alphaBits;
  220496. attribs[n++] = GLX_DEPTH_SIZE;
  220497. attribs[n++] = pixelFormat.depthBufferBits;
  220498. attribs[n++] = GLX_STENCIL_SIZE;
  220499. attribs[n++] = pixelFormat.stencilBufferBits;
  220500. attribs[n++] = GLX_ACCUM_RED_SIZE;
  220501. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  220502. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  220503. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  220504. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  220505. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  220506. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  220507. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  220508. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  220509. attribs[n++] = None;
  220510. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  220511. if (bestVisual == 0)
  220512. return;
  220513. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  220514. Window windowH = (Window) peer->getNativeHandle();
  220515. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  220516. XSetWindowAttributes swa;
  220517. swa.colormap = colourMap;
  220518. swa.border_pixel = 0;
  220519. swa.event_mask = ExposureMask | StructureNotifyMask;
  220520. embeddedWindow = XCreateWindow (display, windowH,
  220521. 0, 0, 1, 1, 0,
  220522. bestVisual->depth,
  220523. InputOutput,
  220524. bestVisual->visual,
  220525. CWBorderPixel | CWColormap | CWEventMask,
  220526. &swa);
  220527. XSaveContext (display, (XID) embeddedWindow, windowHandleXContext, (XPointer) peer);
  220528. XMapWindow (display, embeddedWindow);
  220529. XFreeColormap (display, colourMap);
  220530. XFree (bestVisual);
  220531. XSync (display, False);
  220532. }
  220533. ~WindowedGLContext()
  220534. {
  220535. makeInactive();
  220536. ScopedXLock xlock;
  220537. glXDestroyContext (display, renderContext);
  220538. XUnmapWindow (display, embeddedWindow);
  220539. XDestroyWindow (display, embeddedWindow);
  220540. }
  220541. bool makeActive() const throw()
  220542. {
  220543. jassert (renderContext != 0);
  220544. ScopedXLock xlock;
  220545. return glXMakeCurrent (display, embeddedWindow, renderContext)
  220546. && XSync (display, False);
  220547. }
  220548. bool makeInactive() const throw()
  220549. {
  220550. ScopedXLock xlock;
  220551. return (! isActive()) || glXMakeCurrent (display, None, 0);
  220552. }
  220553. bool isActive() const throw()
  220554. {
  220555. ScopedXLock xlock;
  220556. return glXGetCurrentContext() == renderContext;
  220557. }
  220558. const OpenGLPixelFormat getPixelFormat() const
  220559. {
  220560. return pixelFormat;
  220561. }
  220562. void* getRawContext() const throw()
  220563. {
  220564. return renderContext;
  220565. }
  220566. void updateWindowPosition (int x, int y, int w, int h, int)
  220567. {
  220568. ScopedXLock xlock;
  220569. XMoveResizeWindow (display, embeddedWindow,
  220570. x, y, jmax (1, w), jmax (1, h));
  220571. }
  220572. void swapBuffers()
  220573. {
  220574. ScopedXLock xlock;
  220575. glXSwapBuffers (display, embeddedWindow);
  220576. }
  220577. bool setSwapInterval (const int numFramesPerSwap)
  220578. {
  220579. static PFNGLXSWAPINTERVALSGIPROC GLXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC) glXGetProcAddress ((const GLubyte*) "glXSwapIntervalSGI");
  220580. if (GLXSwapIntervalSGI != 0)
  220581. {
  220582. swapInterval = numFramesPerSwap;
  220583. GLXSwapIntervalSGI (numFramesPerSwap);
  220584. return true;
  220585. }
  220586. return false;
  220587. }
  220588. int getSwapInterval() const
  220589. {
  220590. return swapInterval;
  220591. }
  220592. void repaint()
  220593. {
  220594. }
  220595. juce_UseDebuggingNewOperator
  220596. GLXContext renderContext;
  220597. private:
  220598. Window embeddedWindow;
  220599. OpenGLPixelFormat pixelFormat;
  220600. int swapInterval;
  220601. WindowedGLContext (const WindowedGLContext&);
  220602. WindowedGLContext& operator= (const WindowedGLContext&);
  220603. };
  220604. OpenGLContext* OpenGLComponent::createContext()
  220605. {
  220606. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  220607. contextToShareListsWith != 0 ? (GLXContext) contextToShareListsWith->getRawContext() : 0));
  220608. return (c->renderContext != 0) ? c.release() : 0;
  220609. }
  220610. void juce_glViewport (const int w, const int h)
  220611. {
  220612. glViewport (0, 0, w, h);
  220613. }
  220614. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  220615. OwnedArray <OpenGLPixelFormat>& results)
  220616. {
  220617. results.add (new OpenGLPixelFormat()); // xxx
  220618. }
  220619. #endif
  220620. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  220621. {
  220622. jassertfalse; // not implemented!
  220623. return false;
  220624. }
  220625. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  220626. {
  220627. jassertfalse; // not implemented!
  220628. return false;
  220629. }
  220630. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  220631. {
  220632. if (! isOnDesktop ())
  220633. addToDesktop (0);
  220634. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  220635. if (wp != 0)
  220636. {
  220637. wp->setTaskBarIcon (newImage);
  220638. setVisible (true);
  220639. toFront (false);
  220640. repaint();
  220641. }
  220642. }
  220643. void SystemTrayIconComponent::paint (Graphics& g)
  220644. {
  220645. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  220646. if (wp != 0)
  220647. {
  220648. g.drawImageWithin (wp->getTaskbarIcon(), 0, 0, getWidth(), getHeight(),
  220649. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  220650. false);
  220651. }
  220652. }
  220653. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  220654. {
  220655. // xxx not yet implemented!
  220656. }
  220657. void PlatformUtilities::beep()
  220658. {
  220659. std::cout << "\a" << std::flush;
  220660. }
  220661. bool AlertWindow::showNativeDialogBox (const String& title,
  220662. const String& bodyText,
  220663. bool isOkCancel)
  220664. {
  220665. // use a non-native one for the time being..
  220666. if (isOkCancel)
  220667. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  220668. else
  220669. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  220670. return true;
  220671. }
  220672. const int KeyPress::spaceKey = XK_space & 0xff;
  220673. const int KeyPress::returnKey = XK_Return & 0xff;
  220674. const int KeyPress::escapeKey = XK_Escape & 0xff;
  220675. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  220676. const int KeyPress::leftKey = (XK_Left & 0xff) | Keys::extendedKeyModifier;
  220677. const int KeyPress::rightKey = (XK_Right & 0xff) | Keys::extendedKeyModifier;
  220678. const int KeyPress::upKey = (XK_Up & 0xff) | Keys::extendedKeyModifier;
  220679. const int KeyPress::downKey = (XK_Down & 0xff) | Keys::extendedKeyModifier;
  220680. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | Keys::extendedKeyModifier;
  220681. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | Keys::extendedKeyModifier;
  220682. const int KeyPress::endKey = (XK_End & 0xff) | Keys::extendedKeyModifier;
  220683. const int KeyPress::homeKey = (XK_Home & 0xff) | Keys::extendedKeyModifier;
  220684. const int KeyPress::insertKey = (XK_Insert & 0xff) | Keys::extendedKeyModifier;
  220685. const int KeyPress::deleteKey = (XK_Delete & 0xff) | Keys::extendedKeyModifier;
  220686. const int KeyPress::tabKey = XK_Tab & 0xff;
  220687. const int KeyPress::F1Key = (XK_F1 & 0xff) | Keys::extendedKeyModifier;
  220688. const int KeyPress::F2Key = (XK_F2 & 0xff) | Keys::extendedKeyModifier;
  220689. const int KeyPress::F3Key = (XK_F3 & 0xff) | Keys::extendedKeyModifier;
  220690. const int KeyPress::F4Key = (XK_F4 & 0xff) | Keys::extendedKeyModifier;
  220691. const int KeyPress::F5Key = (XK_F5 & 0xff) | Keys::extendedKeyModifier;
  220692. const int KeyPress::F6Key = (XK_F6 & 0xff) | Keys::extendedKeyModifier;
  220693. const int KeyPress::F7Key = (XK_F7 & 0xff) | Keys::extendedKeyModifier;
  220694. const int KeyPress::F8Key = (XK_F8 & 0xff) | Keys::extendedKeyModifier;
  220695. const int KeyPress::F9Key = (XK_F9 & 0xff) | Keys::extendedKeyModifier;
  220696. const int KeyPress::F10Key = (XK_F10 & 0xff) | Keys::extendedKeyModifier;
  220697. const int KeyPress::F11Key = (XK_F11 & 0xff) | Keys::extendedKeyModifier;
  220698. const int KeyPress::F12Key = (XK_F12 & 0xff) | Keys::extendedKeyModifier;
  220699. const int KeyPress::F13Key = (XK_F13 & 0xff) | Keys::extendedKeyModifier;
  220700. const int KeyPress::F14Key = (XK_F14 & 0xff) | Keys::extendedKeyModifier;
  220701. const int KeyPress::F15Key = (XK_F15 & 0xff) | Keys::extendedKeyModifier;
  220702. const int KeyPress::F16Key = (XK_F16 & 0xff) | Keys::extendedKeyModifier;
  220703. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | Keys::extendedKeyModifier;
  220704. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | Keys::extendedKeyModifier;
  220705. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | Keys::extendedKeyModifier;
  220706. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | Keys::extendedKeyModifier;
  220707. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | Keys::extendedKeyModifier;
  220708. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | Keys::extendedKeyModifier;
  220709. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | Keys::extendedKeyModifier;
  220710. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| Keys::extendedKeyModifier;
  220711. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| Keys::extendedKeyModifier;
  220712. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| Keys::extendedKeyModifier;
  220713. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| Keys::extendedKeyModifier;
  220714. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| Keys::extendedKeyModifier;
  220715. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| Keys::extendedKeyModifier;
  220716. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| Keys::extendedKeyModifier;
  220717. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| Keys::extendedKeyModifier;
  220718. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| Keys::extendedKeyModifier;
  220719. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| Keys::extendedKeyModifier;
  220720. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| Keys::extendedKeyModifier;
  220721. const int KeyPress::playKey = (0xffeeff00) | Keys::extendedKeyModifier;
  220722. const int KeyPress::stopKey = (0xffeeff01) | Keys::extendedKeyModifier;
  220723. const int KeyPress::fastForwardKey = (0xffeeff02) | Keys::extendedKeyModifier;
  220724. const int KeyPress::rewindKey = (0xffeeff03) | Keys::extendedKeyModifier;
  220725. #endif
  220726. /*** End of inlined file: juce_linux_Windowing.cpp ***/
  220727. /*** Start of inlined file: juce_linux_Audio.cpp ***/
  220728. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  220729. // compiled on its own).
  220730. #if JUCE_INCLUDED_FILE && JUCE_ALSA
  220731. static const int maxNumChans = 64;
  220732. static void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  220733. {
  220734. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  220735. snd_pcm_hw_params_t* hwParams;
  220736. snd_pcm_hw_params_alloca (&hwParams);
  220737. for (int i = 0; ratesToTry[i] != 0; ++i)
  220738. {
  220739. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  220740. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  220741. {
  220742. rates.addIfNotAlreadyThere (ratesToTry[i]);
  220743. }
  220744. }
  220745. }
  220746. static void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  220747. {
  220748. snd_pcm_hw_params_t *params;
  220749. snd_pcm_hw_params_alloca (&params);
  220750. if (snd_pcm_hw_params_any (handle, params) >= 0)
  220751. {
  220752. snd_pcm_hw_params_get_channels_min (params, minChans);
  220753. snd_pcm_hw_params_get_channels_max (params, maxChans);
  220754. }
  220755. }
  220756. static void getDeviceProperties (const String& deviceID,
  220757. unsigned int& minChansOut,
  220758. unsigned int& maxChansOut,
  220759. unsigned int& minChansIn,
  220760. unsigned int& maxChansIn,
  220761. Array <int>& rates)
  220762. {
  220763. if (deviceID.isEmpty())
  220764. return;
  220765. snd_ctl_t* handle;
  220766. if (snd_ctl_open (&handle, deviceID.upToLastOccurrenceOf (",", false, false).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  220767. {
  220768. snd_pcm_info_t* info;
  220769. snd_pcm_info_alloca (&info);
  220770. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  220771. snd_pcm_info_set_device (info, deviceID.fromLastOccurrenceOf (",", false, false).getIntValue());
  220772. snd_pcm_info_set_subdevice (info, 0);
  220773. if (snd_ctl_pcm_info (handle, info) >= 0)
  220774. {
  220775. snd_pcm_t* pcmHandle;
  220776. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  220777. {
  220778. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  220779. getDeviceSampleRates (pcmHandle, rates);
  220780. snd_pcm_close (pcmHandle);
  220781. }
  220782. }
  220783. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  220784. if (snd_ctl_pcm_info (handle, info) >= 0)
  220785. {
  220786. snd_pcm_t* pcmHandle;
  220787. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  220788. {
  220789. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  220790. if (rates.size() == 0)
  220791. getDeviceSampleRates (pcmHandle, rates);
  220792. snd_pcm_close (pcmHandle);
  220793. }
  220794. }
  220795. snd_ctl_close (handle);
  220796. }
  220797. }
  220798. class ALSADevice
  220799. {
  220800. public:
  220801. ALSADevice (const String& deviceID,
  220802. const bool forInput)
  220803. : handle (0),
  220804. bitDepth (16),
  220805. numChannelsRunning (0),
  220806. isInput (forInput),
  220807. sampleFormat (AudioDataConverters::int16LE)
  220808. {
  220809. failed (snd_pcm_open (&handle, deviceID.toUTF8(),
  220810. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  220811. SND_PCM_ASYNC));
  220812. }
  220813. ~ALSADevice()
  220814. {
  220815. if (handle != 0)
  220816. snd_pcm_close (handle);
  220817. }
  220818. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  220819. {
  220820. if (handle == 0)
  220821. return false;
  220822. snd_pcm_hw_params_t* hwParams;
  220823. snd_pcm_hw_params_alloca (&hwParams);
  220824. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  220825. return false;
  220826. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  220827. isInterleaved = false;
  220828. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  220829. isInterleaved = true;
  220830. else
  220831. {
  220832. jassertfalse;
  220833. return false;
  220834. }
  220835. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32, AudioDataConverters::float32LE,
  220836. SND_PCM_FORMAT_FLOAT_BE, 32, AudioDataConverters::float32BE,
  220837. SND_PCM_FORMAT_S32_LE, 32, AudioDataConverters::int32LE,
  220838. SND_PCM_FORMAT_S32_BE, 32, AudioDataConverters::int32BE,
  220839. SND_PCM_FORMAT_S24_3LE, 24, AudioDataConverters::int24LE,
  220840. SND_PCM_FORMAT_S24_3BE, 24, AudioDataConverters::int24BE,
  220841. SND_PCM_FORMAT_S16_LE, 16, AudioDataConverters::int16LE,
  220842. SND_PCM_FORMAT_S16_BE, 16, AudioDataConverters::int16BE };
  220843. bitDepth = 0;
  220844. for (int i = 0; i < numElementsInArray (formatsToTry); i += 3)
  220845. {
  220846. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  220847. {
  220848. bitDepth = formatsToTry [i + 1];
  220849. sampleFormat = (AudioDataConverters::DataFormat) formatsToTry [i + 2];
  220850. break;
  220851. }
  220852. }
  220853. if (bitDepth == 0)
  220854. {
  220855. error = "device doesn't support a compatible PCM format";
  220856. DBG ("ALSA error: " + error + "\n");
  220857. return false;
  220858. }
  220859. int dir = 0;
  220860. unsigned int periods = 4;
  220861. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  220862. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  220863. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  220864. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  220865. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  220866. || failed (snd_pcm_hw_params (handle, hwParams)))
  220867. {
  220868. return false;
  220869. }
  220870. snd_pcm_sw_params_t* swParams;
  220871. snd_pcm_sw_params_alloca (&swParams);
  220872. snd_pcm_uframes_t boundary;
  220873. if (failed (snd_pcm_sw_params_current (handle, swParams))
  220874. || failed (snd_pcm_sw_params_get_boundary (swParams, &boundary))
  220875. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  220876. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, boundary))
  220877. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  220878. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, boundary))
  220879. || failed (snd_pcm_sw_params (handle, swParams)))
  220880. {
  220881. return false;
  220882. }
  220883. /*
  220884. #if JUCE_DEBUG
  220885. // enable this to dump the config of the devices that get opened
  220886. snd_output_t* out;
  220887. snd_output_stdio_attach (&out, stderr, 0);
  220888. snd_pcm_hw_params_dump (hwParams, out);
  220889. snd_pcm_sw_params_dump (swParams, out);
  220890. #endif
  220891. */
  220892. numChannelsRunning = numChannels;
  220893. return true;
  220894. }
  220895. bool write (AudioSampleBuffer& outputChannelBuffer, const int numSamples)
  220896. {
  220897. jassert (numChannelsRunning <= outputChannelBuffer.getNumChannels());
  220898. float** const data = outputChannelBuffer.getArrayOfChannels();
  220899. if (isInterleaved)
  220900. {
  220901. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  220902. float* interleaved = static_cast <float*> (scratch.getData());
  220903. AudioDataConverters::interleaveSamples ((const float**) data, interleaved, numSamples, numChannelsRunning);
  220904. AudioDataConverters::convertFloatToFormat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  220905. snd_pcm_sframes_t num = snd_pcm_writei (handle, interleaved, numSamples);
  220906. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  220907. return false;
  220908. }
  220909. else
  220910. {
  220911. for (int i = 0; i < numChannelsRunning; ++i)
  220912. if (data[i] != 0)
  220913. AudioDataConverters::convertFloatToFormat (sampleFormat, data[i], data[i], numSamples);
  220914. snd_pcm_sframes_t num = snd_pcm_writen (handle, (void**) data, numSamples);
  220915. if (failed (num))
  220916. {
  220917. if (num == -EPIPE)
  220918. {
  220919. if (failed (snd_pcm_prepare (handle)))
  220920. return false;
  220921. }
  220922. else if (num != -ESTRPIPE)
  220923. return false;
  220924. }
  220925. }
  220926. return true;
  220927. }
  220928. bool read (AudioSampleBuffer& inputChannelBuffer, const int numSamples)
  220929. {
  220930. jassert (numChannelsRunning <= inputChannelBuffer.getNumChannels());
  220931. float** const data = inputChannelBuffer.getArrayOfChannels();
  220932. if (isInterleaved)
  220933. {
  220934. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  220935. float* interleaved = static_cast <float*> (scratch.getData());
  220936. snd_pcm_sframes_t num = snd_pcm_readi (handle, interleaved, numSamples);
  220937. if (failed (num))
  220938. {
  220939. if (num == -EPIPE)
  220940. {
  220941. if (failed (snd_pcm_prepare (handle)))
  220942. return false;
  220943. }
  220944. else if (num != -ESTRPIPE)
  220945. return false;
  220946. }
  220947. AudioDataConverters::convertFormatToFloat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  220948. AudioDataConverters::deinterleaveSamples (interleaved, data, numSamples, numChannelsRunning);
  220949. }
  220950. else
  220951. {
  220952. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  220953. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  220954. return false;
  220955. for (int i = 0; i < numChannelsRunning; ++i)
  220956. if (data[i] != 0)
  220957. AudioDataConverters::convertFormatToFloat (sampleFormat, data[i], data[i], numSamples);
  220958. }
  220959. return true;
  220960. }
  220961. juce_UseDebuggingNewOperator
  220962. snd_pcm_t* handle;
  220963. String error;
  220964. int bitDepth, numChannelsRunning;
  220965. private:
  220966. const bool isInput;
  220967. bool isInterleaved;
  220968. MemoryBlock scratch;
  220969. AudioDataConverters::DataFormat sampleFormat;
  220970. bool failed (const int errorNum)
  220971. {
  220972. if (errorNum >= 0)
  220973. return false;
  220974. error = snd_strerror (errorNum);
  220975. DBG ("ALSA error: " + error + "\n");
  220976. return true;
  220977. }
  220978. };
  220979. class ALSAThread : public Thread
  220980. {
  220981. public:
  220982. ALSAThread (const String& inputId_,
  220983. const String& outputId_)
  220984. : Thread ("Juce ALSA"),
  220985. sampleRate (0),
  220986. bufferSize (0),
  220987. callback (0),
  220988. inputId (inputId_),
  220989. outputId (outputId_),
  220990. outputDevice (0),
  220991. inputDevice (0),
  220992. numCallbacks (0),
  220993. inputChannelBuffer (1, 1),
  220994. outputChannelBuffer (1, 1)
  220995. {
  220996. initialiseRatesAndChannels();
  220997. }
  220998. ~ALSAThread()
  220999. {
  221000. close();
  221001. }
  221002. void open (BigInteger inputChannels,
  221003. BigInteger outputChannels,
  221004. const double sampleRate_,
  221005. const int bufferSize_)
  221006. {
  221007. close();
  221008. error = String::empty;
  221009. sampleRate = sampleRate_;
  221010. bufferSize = bufferSize_;
  221011. inputChannelBuffer.setSize (jmax ((int) minChansIn, inputChannels.getHighestBit()) + 1, bufferSize);
  221012. inputChannelBuffer.clear();
  221013. inputChannelDataForCallback.clear();
  221014. currentInputChans.clear();
  221015. if (inputChannels.getHighestBit() >= 0)
  221016. {
  221017. for (int i = 0; i <= jmax (inputChannels.getHighestBit(), (int) minChansIn); ++i)
  221018. {
  221019. if (inputChannels[i])
  221020. {
  221021. inputChannelDataForCallback.add (inputChannelBuffer.getSampleData (i));
  221022. currentInputChans.setBit (i);
  221023. }
  221024. }
  221025. }
  221026. outputChannelBuffer.setSize (jmax ((int) minChansOut, outputChannels.getHighestBit()) + 1, bufferSize);
  221027. outputChannelBuffer.clear();
  221028. outputChannelDataForCallback.clear();
  221029. currentOutputChans.clear();
  221030. if (outputChannels.getHighestBit() >= 0)
  221031. {
  221032. for (int i = 0; i <= jmax (outputChannels.getHighestBit(), (int) minChansOut); ++i)
  221033. {
  221034. if (outputChannels[i])
  221035. {
  221036. outputChannelDataForCallback.add (outputChannelBuffer.getSampleData (i));
  221037. currentOutputChans.setBit (i);
  221038. }
  221039. }
  221040. }
  221041. if (outputChannelDataForCallback.size() > 0 && outputId.isNotEmpty())
  221042. {
  221043. outputDevice = new ALSADevice (outputId, false);
  221044. if (outputDevice->error.isNotEmpty())
  221045. {
  221046. error = outputDevice->error;
  221047. deleteAndZero (outputDevice);
  221048. return;
  221049. }
  221050. currentOutputChans.setRange (0, minChansOut, true);
  221051. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  221052. jlimit ((int) minChansOut, (int) maxChansOut, currentOutputChans.getHighestBit() + 1),
  221053. bufferSize))
  221054. {
  221055. error = outputDevice->error;
  221056. deleteAndZero (outputDevice);
  221057. return;
  221058. }
  221059. }
  221060. if (inputChannelDataForCallback.size() > 0 && inputId.isNotEmpty())
  221061. {
  221062. inputDevice = new ALSADevice (inputId, true);
  221063. if (inputDevice->error.isNotEmpty())
  221064. {
  221065. error = inputDevice->error;
  221066. deleteAndZero (inputDevice);
  221067. return;
  221068. }
  221069. currentInputChans.setRange (0, minChansIn, true);
  221070. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  221071. jlimit ((int) minChansIn, (int) maxChansIn, currentInputChans.getHighestBit() + 1),
  221072. bufferSize))
  221073. {
  221074. error = inputDevice->error;
  221075. deleteAndZero (inputDevice);
  221076. return;
  221077. }
  221078. }
  221079. if (outputDevice == 0 && inputDevice == 0)
  221080. {
  221081. error = "no channels";
  221082. return;
  221083. }
  221084. if (outputDevice != 0 && inputDevice != 0)
  221085. {
  221086. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  221087. }
  221088. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  221089. return;
  221090. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  221091. return;
  221092. startThread (9);
  221093. int count = 1000;
  221094. while (numCallbacks == 0)
  221095. {
  221096. sleep (5);
  221097. if (--count < 0 || ! isThreadRunning())
  221098. {
  221099. error = "device didn't start";
  221100. break;
  221101. }
  221102. }
  221103. }
  221104. void close()
  221105. {
  221106. stopThread (6000);
  221107. deleteAndZero (inputDevice);
  221108. deleteAndZero (outputDevice);
  221109. inputChannelBuffer.setSize (1, 1);
  221110. outputChannelBuffer.setSize (1, 1);
  221111. numCallbacks = 0;
  221112. }
  221113. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  221114. {
  221115. const ScopedLock sl (callbackLock);
  221116. callback = newCallback;
  221117. }
  221118. void run()
  221119. {
  221120. while (! threadShouldExit())
  221121. {
  221122. if (inputDevice != 0)
  221123. {
  221124. if (! inputDevice->read (inputChannelBuffer, bufferSize))
  221125. {
  221126. DBG ("ALSA: read failure");
  221127. break;
  221128. }
  221129. }
  221130. if (threadShouldExit())
  221131. break;
  221132. {
  221133. const ScopedLock sl (callbackLock);
  221134. ++numCallbacks;
  221135. if (callback != 0)
  221136. {
  221137. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback.getRawDataPointer(),
  221138. inputChannelDataForCallback.size(),
  221139. outputChannelDataForCallback.getRawDataPointer(),
  221140. outputChannelDataForCallback.size(),
  221141. bufferSize);
  221142. }
  221143. else
  221144. {
  221145. for (int i = 0; i < outputChannelDataForCallback.size(); ++i)
  221146. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  221147. }
  221148. }
  221149. if (outputDevice != 0)
  221150. {
  221151. failed (snd_pcm_wait (outputDevice->handle, 2000));
  221152. if (threadShouldExit())
  221153. break;
  221154. failed (snd_pcm_avail_update (outputDevice->handle));
  221155. if (! outputDevice->write (outputChannelBuffer, bufferSize))
  221156. {
  221157. DBG ("ALSA: write failure");
  221158. break;
  221159. }
  221160. }
  221161. }
  221162. }
  221163. int getBitDepth() const throw()
  221164. {
  221165. if (outputDevice != 0)
  221166. return outputDevice->bitDepth;
  221167. if (inputDevice != 0)
  221168. return inputDevice->bitDepth;
  221169. return 16;
  221170. }
  221171. juce_UseDebuggingNewOperator
  221172. String error;
  221173. double sampleRate;
  221174. int bufferSize;
  221175. BigInteger currentInputChans, currentOutputChans;
  221176. Array <int> sampleRates;
  221177. StringArray channelNamesOut, channelNamesIn;
  221178. AudioIODeviceCallback* callback;
  221179. private:
  221180. const String inputId, outputId;
  221181. ALSADevice* outputDevice;
  221182. ALSADevice* inputDevice;
  221183. int numCallbacks;
  221184. CriticalSection callbackLock;
  221185. AudioSampleBuffer inputChannelBuffer, outputChannelBuffer;
  221186. Array<float*> inputChannelDataForCallback, outputChannelDataForCallback;
  221187. unsigned int minChansOut, maxChansOut;
  221188. unsigned int minChansIn, maxChansIn;
  221189. bool failed (const int errorNum)
  221190. {
  221191. if (errorNum >= 0)
  221192. return false;
  221193. error = snd_strerror (errorNum);
  221194. DBG ("ALSA error: " + error + "\n");
  221195. return true;
  221196. }
  221197. void initialiseRatesAndChannels()
  221198. {
  221199. sampleRates.clear();
  221200. channelNamesOut.clear();
  221201. channelNamesIn.clear();
  221202. minChansOut = 0;
  221203. maxChansOut = 0;
  221204. minChansIn = 0;
  221205. maxChansIn = 0;
  221206. unsigned int dummy = 0;
  221207. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates);
  221208. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates);
  221209. unsigned int i;
  221210. for (i = 0; i < maxChansOut; ++i)
  221211. channelNamesOut.add ("channel " + String ((int) i + 1));
  221212. for (i = 0; i < maxChansIn; ++i)
  221213. channelNamesIn.add ("channel " + String ((int) i + 1));
  221214. }
  221215. };
  221216. class ALSAAudioIODevice : public AudioIODevice
  221217. {
  221218. public:
  221219. ALSAAudioIODevice (const String& deviceName,
  221220. const String& inputId_,
  221221. const String& outputId_)
  221222. : AudioIODevice (deviceName, "ALSA"),
  221223. inputId (inputId_),
  221224. outputId (outputId_),
  221225. isOpen_ (false),
  221226. isStarted (false),
  221227. internal (new ALSAThread (inputId_, outputId_))
  221228. {
  221229. }
  221230. ~ALSAAudioIODevice()
  221231. {
  221232. }
  221233. const StringArray getOutputChannelNames()
  221234. {
  221235. return internal->channelNamesOut;
  221236. }
  221237. const StringArray getInputChannelNames()
  221238. {
  221239. return internal->channelNamesIn;
  221240. }
  221241. int getNumSampleRates()
  221242. {
  221243. return internal->sampleRates.size();
  221244. }
  221245. double getSampleRate (int index)
  221246. {
  221247. return internal->sampleRates [index];
  221248. }
  221249. int getNumBufferSizesAvailable()
  221250. {
  221251. return 50;
  221252. }
  221253. int getBufferSizeSamples (int index)
  221254. {
  221255. int n = 16;
  221256. for (int i = 0; i < index; ++i)
  221257. n += n < 64 ? 16
  221258. : (n < 512 ? 32
  221259. : (n < 1024 ? 64
  221260. : (n < 2048 ? 128 : 256)));
  221261. return n;
  221262. }
  221263. int getDefaultBufferSize()
  221264. {
  221265. return 512;
  221266. }
  221267. const String open (const BigInteger& inputChannels,
  221268. const BigInteger& outputChannels,
  221269. double sampleRate,
  221270. int bufferSizeSamples)
  221271. {
  221272. close();
  221273. if (bufferSizeSamples <= 0)
  221274. bufferSizeSamples = getDefaultBufferSize();
  221275. if (sampleRate <= 0)
  221276. {
  221277. for (int i = 0; i < getNumSampleRates(); ++i)
  221278. {
  221279. if (getSampleRate (i) >= 44100)
  221280. {
  221281. sampleRate = getSampleRate (i);
  221282. break;
  221283. }
  221284. }
  221285. }
  221286. internal->open (inputChannels, outputChannels,
  221287. sampleRate, bufferSizeSamples);
  221288. isOpen_ = internal->error.isEmpty();
  221289. return internal->error;
  221290. }
  221291. void close()
  221292. {
  221293. stop();
  221294. internal->close();
  221295. isOpen_ = false;
  221296. }
  221297. bool isOpen()
  221298. {
  221299. return isOpen_;
  221300. }
  221301. int getCurrentBufferSizeSamples()
  221302. {
  221303. return internal->bufferSize;
  221304. }
  221305. double getCurrentSampleRate()
  221306. {
  221307. return internal->sampleRate;
  221308. }
  221309. int getCurrentBitDepth()
  221310. {
  221311. return internal->getBitDepth();
  221312. }
  221313. const BigInteger getActiveOutputChannels() const
  221314. {
  221315. return internal->currentOutputChans;
  221316. }
  221317. const BigInteger getActiveInputChannels() const
  221318. {
  221319. return internal->currentInputChans;
  221320. }
  221321. int getOutputLatencyInSamples()
  221322. {
  221323. return 0;
  221324. }
  221325. int getInputLatencyInSamples()
  221326. {
  221327. return 0;
  221328. }
  221329. void start (AudioIODeviceCallback* callback)
  221330. {
  221331. if (! isOpen_)
  221332. callback = 0;
  221333. internal->setCallback (callback);
  221334. if (callback != 0)
  221335. callback->audioDeviceAboutToStart (this);
  221336. isStarted = (callback != 0);
  221337. }
  221338. void stop()
  221339. {
  221340. AudioIODeviceCallback* const oldCallback = internal->callback;
  221341. start (0);
  221342. if (oldCallback != 0)
  221343. oldCallback->audioDeviceStopped();
  221344. }
  221345. bool isPlaying()
  221346. {
  221347. return isStarted && internal->error.isEmpty();
  221348. }
  221349. const String getLastError()
  221350. {
  221351. return internal->error;
  221352. }
  221353. String inputId, outputId;
  221354. private:
  221355. bool isOpen_, isStarted;
  221356. ScopedPointer<ALSAThread> internal;
  221357. };
  221358. class ALSAAudioIODeviceType : public AudioIODeviceType
  221359. {
  221360. public:
  221361. ALSAAudioIODeviceType()
  221362. : AudioIODeviceType ("ALSA"),
  221363. hasScanned (false)
  221364. {
  221365. }
  221366. ~ALSAAudioIODeviceType()
  221367. {
  221368. }
  221369. void scanForDevices()
  221370. {
  221371. if (hasScanned)
  221372. return;
  221373. hasScanned = true;
  221374. inputNames.clear();
  221375. inputIds.clear();
  221376. outputNames.clear();
  221377. outputIds.clear();
  221378. snd_ctl_t* handle;
  221379. snd_ctl_card_info_t* info;
  221380. snd_ctl_card_info_alloca (&info);
  221381. int cardNum = -1;
  221382. while (outputIds.size() + inputIds.size() <= 32)
  221383. {
  221384. snd_card_next (&cardNum);
  221385. if (cardNum < 0)
  221386. break;
  221387. if (snd_ctl_open (&handle, ("hw:" + String (cardNum)).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  221388. {
  221389. if (snd_ctl_card_info (handle, info) >= 0)
  221390. {
  221391. String cardId (snd_ctl_card_info_get_id (info));
  221392. if (cardId.removeCharacters ("0123456789").isEmpty())
  221393. cardId = String (cardNum);
  221394. int device = -1;
  221395. for (;;)
  221396. {
  221397. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  221398. break;
  221399. String id, name;
  221400. id << "hw:" << cardId << ',' << device;
  221401. bool isInput, isOutput;
  221402. if (testDevice (id, isInput, isOutput))
  221403. {
  221404. name << snd_ctl_card_info_get_name (info);
  221405. if (name.isEmpty())
  221406. name = id;
  221407. if (isInput)
  221408. {
  221409. inputNames.add (name);
  221410. inputIds.add (id);
  221411. }
  221412. if (isOutput)
  221413. {
  221414. outputNames.add (name);
  221415. outputIds.add (id);
  221416. }
  221417. }
  221418. }
  221419. }
  221420. snd_ctl_close (handle);
  221421. }
  221422. }
  221423. inputNames.appendNumbersToDuplicates (false, true);
  221424. outputNames.appendNumbersToDuplicates (false, true);
  221425. }
  221426. const StringArray getDeviceNames (bool wantInputNames) const
  221427. {
  221428. jassert (hasScanned); // need to call scanForDevices() before doing this
  221429. return wantInputNames ? inputNames : outputNames;
  221430. }
  221431. int getDefaultDeviceIndex (bool forInput) const
  221432. {
  221433. jassert (hasScanned); // need to call scanForDevices() before doing this
  221434. return 0;
  221435. }
  221436. bool hasSeparateInputsAndOutputs() const { return true; }
  221437. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  221438. {
  221439. jassert (hasScanned); // need to call scanForDevices() before doing this
  221440. ALSAAudioIODevice* d = dynamic_cast <ALSAAudioIODevice*> (device);
  221441. if (d == 0)
  221442. return -1;
  221443. return asInput ? inputIds.indexOf (d->inputId)
  221444. : outputIds.indexOf (d->outputId);
  221445. }
  221446. AudioIODevice* createDevice (const String& outputDeviceName,
  221447. const String& inputDeviceName)
  221448. {
  221449. jassert (hasScanned); // need to call scanForDevices() before doing this
  221450. const int inputIndex = inputNames.indexOf (inputDeviceName);
  221451. const int outputIndex = outputNames.indexOf (outputDeviceName);
  221452. String deviceName (outputIndex >= 0 ? outputDeviceName
  221453. : inputDeviceName);
  221454. if (inputIndex >= 0 || outputIndex >= 0)
  221455. return new ALSAAudioIODevice (deviceName,
  221456. inputIds [inputIndex],
  221457. outputIds [outputIndex]);
  221458. return 0;
  221459. }
  221460. juce_UseDebuggingNewOperator
  221461. private:
  221462. StringArray inputNames, outputNames, inputIds, outputIds;
  221463. bool hasScanned;
  221464. static bool testDevice (const String& id, bool& isInput, bool& isOutput)
  221465. {
  221466. unsigned int minChansOut = 0, maxChansOut = 0;
  221467. unsigned int minChansIn = 0, maxChansIn = 0;
  221468. Array <int> rates;
  221469. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  221470. DBG ("ALSA device: " + id
  221471. + " outs=" + String ((int) minChansOut) + "-" + String ((int) maxChansOut)
  221472. + " ins=" + String ((int) minChansIn) + "-" + String ((int) maxChansIn)
  221473. + " rates=" + String (rates.size()));
  221474. isInput = maxChansIn > 0;
  221475. isOutput = maxChansOut > 0;
  221476. return (isInput || isOutput) && rates.size() > 0;
  221477. }
  221478. ALSAAudioIODeviceType (const ALSAAudioIODeviceType&);
  221479. ALSAAudioIODeviceType& operator= (const ALSAAudioIODeviceType&);
  221480. };
  221481. AudioIODeviceType* juce_createAudioIODeviceType_ALSA()
  221482. {
  221483. return new ALSAAudioIODeviceType();
  221484. }
  221485. #endif
  221486. /*** End of inlined file: juce_linux_Audio.cpp ***/
  221487. /*** Start of inlined file: juce_linux_JackAudio.cpp ***/
  221488. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  221489. // compiled on its own).
  221490. #ifdef JUCE_INCLUDED_FILE
  221491. #if JUCE_JACK
  221492. static void* juce_libjack_handle = 0;
  221493. void* juce_load_jack_function (const char* const name)
  221494. {
  221495. if (juce_libjack_handle == 0)
  221496. return 0;
  221497. return dlsym (juce_libjack_handle, name);
  221498. }
  221499. #define JUCE_DECL_JACK_FUNCTION(return_type, fn_name, argument_types, arguments) \
  221500. typedef return_type (*fn_name##_ptr_t)argument_types; \
  221501. return_type fn_name argument_types { \
  221502. static fn_name##_ptr_t fn = 0; \
  221503. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  221504. if (fn) return (*fn)arguments; \
  221505. else return 0; \
  221506. }
  221507. #define JUCE_DECL_VOID_JACK_FUNCTION(fn_name, argument_types, arguments) \
  221508. typedef void (*fn_name##_ptr_t)argument_types; \
  221509. void fn_name argument_types { \
  221510. static fn_name##_ptr_t fn = 0; \
  221511. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  221512. if (fn) (*fn)arguments; \
  221513. }
  221514. 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));
  221515. JUCE_DECL_JACK_FUNCTION (int, jack_client_close, (jack_client_t *client), (client));
  221516. JUCE_DECL_JACK_FUNCTION (int, jack_activate, (jack_client_t* client), (client));
  221517. JUCE_DECL_JACK_FUNCTION (int, jack_deactivate, (jack_client_t* client), (client));
  221518. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_buffer_size, (jack_client_t* client), (client));
  221519. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_sample_rate, (jack_client_t* client), (client));
  221520. JUCE_DECL_VOID_JACK_FUNCTION (jack_on_shutdown, (jack_client_t* client, void (*function)(void* arg), void* arg), (client, function, arg));
  221521. JUCE_DECL_JACK_FUNCTION (void* , jack_port_get_buffer, (jack_port_t* port, jack_nframes_t nframes), (port, nframes));
  221522. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_port_get_total_latency, (jack_client_t* client, jack_port_t* port), (client, port));
  221523. 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));
  221524. JUCE_DECL_VOID_JACK_FUNCTION (jack_set_error_function, (void (*func)(const char*)), (func));
  221525. JUCE_DECL_JACK_FUNCTION (int, jack_set_process_callback, (jack_client_t* client, JackProcessCallback process_callback, void* arg), (client, process_callback, arg));
  221526. 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));
  221527. JUCE_DECL_JACK_FUNCTION (int, jack_connect, (jack_client_t* client, const char* source_port, const char* destination_port), (client, source_port, destination_port));
  221528. JUCE_DECL_JACK_FUNCTION (const char*, jack_port_name, (const jack_port_t* port), (port));
  221529. JUCE_DECL_JACK_FUNCTION (int, jack_set_port_connect_callback, (jack_client_t* client, JackPortConnectCallback connect_callback, void* arg), (client, connect_callback, arg));
  221530. JUCE_DECL_JACK_FUNCTION (jack_port_t* , jack_port_by_id, (jack_client_t* client, jack_port_id_t port_id), (client, port_id));
  221531. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected, (const jack_port_t* port), (port));
  221532. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected_to, (const jack_port_t* port, const char* port_name), (port, port_name));
  221533. #if JUCE_DEBUG
  221534. #define JACK_LOGGING_ENABLED 1
  221535. #endif
  221536. #if JACK_LOGGING_ENABLED
  221537. static void jack_Log (const String& s)
  221538. {
  221539. std::cerr << s << std::endl;
  221540. }
  221541. static void dumpJackErrorMessage (const jack_status_t status)
  221542. {
  221543. if (status & JackServerFailed || status & JackServerError)
  221544. jack_Log ("Unable to connect to JACK server");
  221545. if (status & JackVersionError)
  221546. jack_Log ("Client's protocol version does not match");
  221547. if (status & JackInvalidOption)
  221548. jack_Log ("The operation contained an invalid or unsupported option");
  221549. if (status & JackNameNotUnique)
  221550. jack_Log ("The desired client name was not unique");
  221551. if (status & JackNoSuchClient)
  221552. jack_Log ("Requested client does not exist");
  221553. if (status & JackInitFailure)
  221554. jack_Log ("Unable to initialize client");
  221555. }
  221556. #else
  221557. #define dumpJackErrorMessage(a) {}
  221558. #define jack_Log(...) {}
  221559. #endif
  221560. #ifndef JUCE_JACK_CLIENT_NAME
  221561. #define JUCE_JACK_CLIENT_NAME "JuceJack"
  221562. #endif
  221563. class JackAudioIODevice : public AudioIODevice
  221564. {
  221565. public:
  221566. JackAudioIODevice (const String& deviceName,
  221567. const String& inputId_,
  221568. const String& outputId_)
  221569. : AudioIODevice (deviceName, "JACK"),
  221570. inputId (inputId_),
  221571. outputId (outputId_),
  221572. isOpen_ (false),
  221573. callback (0),
  221574. totalNumberOfInputChannels (0),
  221575. totalNumberOfOutputChannels (0)
  221576. {
  221577. jassert (deviceName.isNotEmpty());
  221578. jack_status_t status;
  221579. client = JUCE_NAMESPACE::jack_client_open (JUCE_JACK_CLIENT_NAME, JackNoStartServer, &status);
  221580. if (client == 0)
  221581. {
  221582. dumpJackErrorMessage (status);
  221583. }
  221584. else
  221585. {
  221586. JUCE_NAMESPACE::jack_set_error_function (errorCallback);
  221587. // open input ports
  221588. const StringArray inputChannels (getInputChannelNames());
  221589. for (int i = 0; i < inputChannels.size(); i++)
  221590. {
  221591. String inputName;
  221592. inputName << "in_" << ++totalNumberOfInputChannels;
  221593. inputPorts.add (JUCE_NAMESPACE::jack_port_register (client, inputName.toUTF8(),
  221594. JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0));
  221595. }
  221596. // open output ports
  221597. const StringArray outputChannels (getOutputChannelNames());
  221598. for (int i = 0; i < outputChannels.size (); i++)
  221599. {
  221600. String outputName;
  221601. outputName << "out_" << ++totalNumberOfOutputChannels;
  221602. outputPorts.add (JUCE_NAMESPACE::jack_port_register (client, outputName.toUTF8(),
  221603. JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0));
  221604. }
  221605. inChans.calloc (totalNumberOfInputChannels + 2);
  221606. outChans.calloc (totalNumberOfOutputChannels + 2);
  221607. }
  221608. }
  221609. ~JackAudioIODevice()
  221610. {
  221611. close();
  221612. if (client != 0)
  221613. {
  221614. JUCE_NAMESPACE::jack_client_close (client);
  221615. client = 0;
  221616. }
  221617. }
  221618. const StringArray getChannelNames (bool forInput) const
  221619. {
  221620. StringArray names;
  221621. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */
  221622. forInput ? JackPortIsInput : JackPortIsOutput);
  221623. if (ports != 0)
  221624. {
  221625. int j = 0;
  221626. while (ports[j] != 0)
  221627. {
  221628. const String portName (ports [j++]);
  221629. if (portName.upToFirstOccurrenceOf (":", false, false) == getName())
  221630. names.add (portName.fromFirstOccurrenceOf (":", false, false));
  221631. }
  221632. free (ports);
  221633. }
  221634. return names;
  221635. }
  221636. const StringArray getOutputChannelNames() { return getChannelNames (false); }
  221637. const StringArray getInputChannelNames() { return getChannelNames (true); }
  221638. int getNumSampleRates() { return client != 0 ? 1 : 0; }
  221639. double getSampleRate (int index) { return client != 0 ? JUCE_NAMESPACE::jack_get_sample_rate (client) : 0; }
  221640. int getNumBufferSizesAvailable() { return client != 0 ? 1 : 0; }
  221641. int getBufferSizeSamples (int index) { return getDefaultBufferSize(); }
  221642. int getDefaultBufferSize() { return client != 0 ? JUCE_NAMESPACE::jack_get_buffer_size (client) : 0; }
  221643. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  221644. double sampleRate, int bufferSizeSamples)
  221645. {
  221646. if (client == 0)
  221647. {
  221648. lastError = "No JACK client running";
  221649. return lastError;
  221650. }
  221651. lastError = String::empty;
  221652. close();
  221653. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, this);
  221654. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, this);
  221655. JUCE_NAMESPACE::jack_activate (client);
  221656. isOpen_ = true;
  221657. if (! inputChannels.isZero())
  221658. {
  221659. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  221660. if (ports != 0)
  221661. {
  221662. const int numInputChannels = inputChannels.getHighestBit() + 1;
  221663. for (int i = 0; i < numInputChannels; ++i)
  221664. {
  221665. const String portName (ports[i]);
  221666. if (inputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  221667. {
  221668. int error = JUCE_NAMESPACE::jack_connect (client, ports[i], JUCE_NAMESPACE::jack_port_name ((jack_port_t*) inputPorts[i]));
  221669. if (error != 0)
  221670. jack_Log ("Cannot connect input port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  221671. }
  221672. }
  221673. free (ports);
  221674. }
  221675. }
  221676. if (! outputChannels.isZero())
  221677. {
  221678. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  221679. if (ports != 0)
  221680. {
  221681. const int numOutputChannels = outputChannels.getHighestBit() + 1;
  221682. for (int i = 0; i < numOutputChannels; ++i)
  221683. {
  221684. const String portName (ports[i]);
  221685. if (outputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  221686. {
  221687. int error = JUCE_NAMESPACE::jack_connect (client, JUCE_NAMESPACE::jack_port_name ((jack_port_t*) outputPorts[i]), ports[i]);
  221688. if (error != 0)
  221689. jack_Log ("Cannot connect output port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  221690. }
  221691. }
  221692. free (ports);
  221693. }
  221694. }
  221695. return lastError;
  221696. }
  221697. void close()
  221698. {
  221699. stop();
  221700. if (client != 0)
  221701. {
  221702. JUCE_NAMESPACE::jack_deactivate (client);
  221703. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, 0);
  221704. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, 0);
  221705. }
  221706. isOpen_ = false;
  221707. }
  221708. void start (AudioIODeviceCallback* newCallback)
  221709. {
  221710. if (isOpen_ && newCallback != callback)
  221711. {
  221712. if (newCallback != 0)
  221713. newCallback->audioDeviceAboutToStart (this);
  221714. AudioIODeviceCallback* const oldCallback = callback;
  221715. {
  221716. const ScopedLock sl (callbackLock);
  221717. callback = newCallback;
  221718. }
  221719. if (oldCallback != 0)
  221720. oldCallback->audioDeviceStopped();
  221721. }
  221722. }
  221723. void stop()
  221724. {
  221725. start (0);
  221726. }
  221727. bool isOpen() { return isOpen_; }
  221728. bool isPlaying() { return callback != 0; }
  221729. int getCurrentBufferSizeSamples() { return getBufferSizeSamples (0); }
  221730. double getCurrentSampleRate() { return getSampleRate (0); }
  221731. int getCurrentBitDepth() { return 32; }
  221732. const String getLastError() { return lastError; }
  221733. const BigInteger getActiveOutputChannels() const
  221734. {
  221735. BigInteger outputBits;
  221736. for (int i = 0; i < outputPorts.size(); i++)
  221737. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) outputPorts [i]))
  221738. outputBits.setBit (i);
  221739. return outputBits;
  221740. }
  221741. const BigInteger getActiveInputChannels() const
  221742. {
  221743. BigInteger inputBits;
  221744. for (int i = 0; i < inputPorts.size(); i++)
  221745. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) inputPorts [i]))
  221746. inputBits.setBit (i);
  221747. return inputBits;
  221748. }
  221749. int getOutputLatencyInSamples()
  221750. {
  221751. int latency = 0;
  221752. for (int i = 0; i < outputPorts.size(); i++)
  221753. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) outputPorts [i]));
  221754. return latency;
  221755. }
  221756. int getInputLatencyInSamples()
  221757. {
  221758. int latency = 0;
  221759. for (int i = 0; i < inputPorts.size(); i++)
  221760. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) inputPorts [i]));
  221761. return latency;
  221762. }
  221763. String inputId, outputId;
  221764. private:
  221765. void process (const int numSamples)
  221766. {
  221767. int i, numActiveInChans = 0, numActiveOutChans = 0;
  221768. for (i = 0; i < totalNumberOfInputChannels; ++i)
  221769. {
  221770. jack_default_audio_sample_t* in
  221771. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) inputPorts.getUnchecked(i), numSamples);
  221772. if (in != 0)
  221773. inChans [numActiveInChans++] = (float*) in;
  221774. }
  221775. for (i = 0; i < totalNumberOfOutputChannels; ++i)
  221776. {
  221777. jack_default_audio_sample_t* out
  221778. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) outputPorts.getUnchecked(i), numSamples);
  221779. if (out != 0)
  221780. outChans [numActiveOutChans++] = (float*) out;
  221781. }
  221782. const ScopedLock sl (callbackLock);
  221783. if (callback != 0)
  221784. {
  221785. callback->audioDeviceIOCallback (const_cast<const float**> (inChans.getData()), numActiveInChans,
  221786. outChans, numActiveOutChans, numSamples);
  221787. }
  221788. else
  221789. {
  221790. for (i = 0; i < numActiveOutChans; ++i)
  221791. zeromem (outChans[i], sizeof (float) * numSamples);
  221792. }
  221793. }
  221794. static int processCallback (jack_nframes_t nframes, void* callbackArgument)
  221795. {
  221796. if (callbackArgument != 0)
  221797. ((JackAudioIODevice*) callbackArgument)->process (nframes);
  221798. return 0;
  221799. }
  221800. static void threadInitCallback (void* callbackArgument)
  221801. {
  221802. jack_Log ("JackAudioIODevice::initialise");
  221803. }
  221804. static void shutdownCallback (void* callbackArgument)
  221805. {
  221806. jack_Log ("JackAudioIODevice::shutdown");
  221807. JackAudioIODevice* device = (JackAudioIODevice*) callbackArgument;
  221808. if (device != 0)
  221809. {
  221810. device->client = 0;
  221811. device->close();
  221812. }
  221813. }
  221814. static void errorCallback (const char* msg)
  221815. {
  221816. jack_Log ("JackAudioIODevice::errorCallback " + String (msg));
  221817. }
  221818. bool isOpen_;
  221819. jack_client_t* client;
  221820. String lastError;
  221821. AudioIODeviceCallback* callback;
  221822. CriticalSection callbackLock;
  221823. HeapBlock <float*> inChans, outChans;
  221824. int totalNumberOfInputChannels;
  221825. int totalNumberOfOutputChannels;
  221826. Array<void*> inputPorts, outputPorts;
  221827. };
  221828. class JackAudioIODeviceType : public AudioIODeviceType
  221829. {
  221830. public:
  221831. JackAudioIODeviceType()
  221832. : AudioIODeviceType ("JACK"),
  221833. hasScanned (false)
  221834. {
  221835. }
  221836. ~JackAudioIODeviceType()
  221837. {
  221838. }
  221839. void scanForDevices()
  221840. {
  221841. hasScanned = true;
  221842. inputNames.clear();
  221843. inputIds.clear();
  221844. outputNames.clear();
  221845. outputIds.clear();
  221846. if (juce_libjack_handle == 0)
  221847. {
  221848. juce_libjack_handle = dlopen ("libjack.so", RTLD_LAZY);
  221849. if (juce_libjack_handle == 0)
  221850. return;
  221851. }
  221852. // open a dummy client
  221853. jack_status_t status;
  221854. jack_client_t* client = JUCE_NAMESPACE::jack_client_open ("JuceJackDummy", JackNoStartServer, &status);
  221855. if (client == 0)
  221856. {
  221857. dumpJackErrorMessage (status);
  221858. }
  221859. else
  221860. {
  221861. // scan for output devices
  221862. const char** ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  221863. if (ports != 0)
  221864. {
  221865. int j = 0;
  221866. while (ports[j] != 0)
  221867. {
  221868. String clientName (ports[j]);
  221869. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  221870. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  221871. && ! inputNames.contains (clientName))
  221872. {
  221873. inputNames.add (clientName);
  221874. inputIds.add (ports [j]);
  221875. }
  221876. ++j;
  221877. }
  221878. free (ports);
  221879. }
  221880. // scan for input devices
  221881. ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  221882. if (ports != 0)
  221883. {
  221884. int j = 0;
  221885. while (ports[j] != 0)
  221886. {
  221887. String clientName (ports[j]);
  221888. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  221889. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  221890. && ! outputNames.contains (clientName))
  221891. {
  221892. outputNames.add (clientName);
  221893. outputIds.add (ports [j]);
  221894. }
  221895. ++j;
  221896. }
  221897. free (ports);
  221898. }
  221899. JUCE_NAMESPACE::jack_client_close (client);
  221900. }
  221901. }
  221902. const StringArray getDeviceNames (bool wantInputNames) const
  221903. {
  221904. jassert (hasScanned); // need to call scanForDevices() before doing this
  221905. return wantInputNames ? inputNames : outputNames;
  221906. }
  221907. int getDefaultDeviceIndex (bool forInput) const
  221908. {
  221909. jassert (hasScanned); // need to call scanForDevices() before doing this
  221910. return 0;
  221911. }
  221912. bool hasSeparateInputsAndOutputs() const { return true; }
  221913. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  221914. {
  221915. jassert (hasScanned); // need to call scanForDevices() before doing this
  221916. JackAudioIODevice* d = dynamic_cast <JackAudioIODevice*> (device);
  221917. if (d == 0)
  221918. return -1;
  221919. return asInput ? inputIds.indexOf (d->inputId)
  221920. : outputIds.indexOf (d->outputId);
  221921. }
  221922. AudioIODevice* createDevice (const String& outputDeviceName,
  221923. const String& inputDeviceName)
  221924. {
  221925. jassert (hasScanned); // need to call scanForDevices() before doing this
  221926. const int inputIndex = inputNames.indexOf (inputDeviceName);
  221927. const int outputIndex = outputNames.indexOf (outputDeviceName);
  221928. if (inputIndex >= 0 || outputIndex >= 0)
  221929. return new JackAudioIODevice (outputIndex >= 0 ? outputDeviceName
  221930. : inputDeviceName,
  221931. inputIds [inputIndex],
  221932. outputIds [outputIndex]);
  221933. return 0;
  221934. }
  221935. juce_UseDebuggingNewOperator
  221936. private:
  221937. StringArray inputNames, outputNames, inputIds, outputIds;
  221938. bool hasScanned;
  221939. JackAudioIODeviceType (const JackAudioIODeviceType&);
  221940. JackAudioIODeviceType& operator= (const JackAudioIODeviceType&);
  221941. };
  221942. AudioIODeviceType* juce_createAudioIODeviceType_JACK()
  221943. {
  221944. return new JackAudioIODeviceType();
  221945. }
  221946. #else // if JACK is turned off..
  221947. AudioIODeviceType* juce_createAudioIODeviceType_JACK() { return 0; }
  221948. #endif
  221949. #endif
  221950. /*** End of inlined file: juce_linux_JackAudio.cpp ***/
  221951. /*** Start of inlined file: juce_linux_Midi.cpp ***/
  221952. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  221953. // compiled on its own).
  221954. #if JUCE_INCLUDED_FILE
  221955. #if JUCE_ALSA
  221956. static snd_seq_t* iterateDevices (const bool forInput,
  221957. StringArray& deviceNamesFound,
  221958. const int deviceIndexToOpen)
  221959. {
  221960. snd_seq_t* returnedHandle = 0;
  221961. snd_seq_t* seqHandle;
  221962. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  221963. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  221964. {
  221965. snd_seq_system_info_t* systemInfo;
  221966. snd_seq_client_info_t* clientInfo;
  221967. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  221968. {
  221969. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  221970. && snd_seq_client_info_malloc (&clientInfo) == 0)
  221971. {
  221972. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  221973. while (--numClients >= 0 && returnedHandle == 0)
  221974. {
  221975. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  221976. {
  221977. snd_seq_port_info_t* portInfo;
  221978. if (snd_seq_port_info_malloc (&portInfo) == 0)
  221979. {
  221980. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  221981. const int client = snd_seq_client_info_get_client (clientInfo);
  221982. snd_seq_port_info_set_client (portInfo, client);
  221983. snd_seq_port_info_set_port (portInfo, -1);
  221984. while (--numPorts >= 0)
  221985. {
  221986. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  221987. && (snd_seq_port_info_get_capability (portInfo)
  221988. & (forInput ? SND_SEQ_PORT_CAP_READ
  221989. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  221990. {
  221991. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  221992. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  221993. {
  221994. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  221995. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  221996. if (sourcePort != -1)
  221997. {
  221998. snd_seq_set_client_name (seqHandle,
  221999. forInput ? "Juce Midi Input"
  222000. : "Juce Midi Output");
  222001. const int portId
  222002. = snd_seq_create_simple_port (seqHandle,
  222003. forInput ? "Juce Midi In Port"
  222004. : "Juce Midi Out Port",
  222005. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  222006. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  222007. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  222008. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  222009. returnedHandle = seqHandle;
  222010. }
  222011. }
  222012. }
  222013. }
  222014. snd_seq_port_info_free (portInfo);
  222015. }
  222016. }
  222017. }
  222018. snd_seq_client_info_free (clientInfo);
  222019. }
  222020. snd_seq_system_info_free (systemInfo);
  222021. }
  222022. if (returnedHandle == 0)
  222023. snd_seq_close (seqHandle);
  222024. }
  222025. deviceNamesFound.appendNumbersToDuplicates (true, true);
  222026. return returnedHandle;
  222027. }
  222028. static snd_seq_t* createDevice (const bool forInput,
  222029. const String& deviceNameToOpen)
  222030. {
  222031. snd_seq_t* seqHandle = 0;
  222032. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  222033. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  222034. {
  222035. snd_seq_set_client_name (seqHandle,
  222036. (deviceNameToOpen + (forInput ? " Input" : " Output")).toCString());
  222037. const int portId
  222038. = snd_seq_create_simple_port (seqHandle,
  222039. forInput ? "in"
  222040. : "out",
  222041. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  222042. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  222043. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  222044. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  222045. if (portId < 0)
  222046. {
  222047. snd_seq_close (seqHandle);
  222048. seqHandle = 0;
  222049. }
  222050. }
  222051. return seqHandle;
  222052. }
  222053. class MidiOutputDevice
  222054. {
  222055. public:
  222056. MidiOutputDevice (MidiOutput* const midiOutput_,
  222057. snd_seq_t* const seqHandle_)
  222058. :
  222059. midiOutput (midiOutput_),
  222060. seqHandle (seqHandle_),
  222061. maxEventSize (16 * 1024)
  222062. {
  222063. jassert (seqHandle != 0 && midiOutput != 0);
  222064. snd_midi_event_new (maxEventSize, &midiParser);
  222065. }
  222066. ~MidiOutputDevice()
  222067. {
  222068. snd_midi_event_free (midiParser);
  222069. snd_seq_close (seqHandle);
  222070. }
  222071. void sendMessageNow (const MidiMessage& message)
  222072. {
  222073. if (message.getRawDataSize() > maxEventSize)
  222074. {
  222075. maxEventSize = message.getRawDataSize();
  222076. snd_midi_event_free (midiParser);
  222077. snd_midi_event_new (maxEventSize, &midiParser);
  222078. }
  222079. snd_seq_event_t event;
  222080. snd_seq_ev_clear (&event);
  222081. snd_midi_event_encode (midiParser,
  222082. message.getRawData(),
  222083. message.getRawDataSize(),
  222084. &event);
  222085. snd_midi_event_reset_encode (midiParser);
  222086. snd_seq_ev_set_source (&event, 0);
  222087. snd_seq_ev_set_subs (&event);
  222088. snd_seq_ev_set_direct (&event);
  222089. snd_seq_event_output (seqHandle, &event);
  222090. snd_seq_drain_output (seqHandle);
  222091. }
  222092. juce_UseDebuggingNewOperator
  222093. private:
  222094. MidiOutput* const midiOutput;
  222095. snd_seq_t* const seqHandle;
  222096. snd_midi_event_t* midiParser;
  222097. int maxEventSize;
  222098. };
  222099. const StringArray MidiOutput::getDevices()
  222100. {
  222101. StringArray devices;
  222102. iterateDevices (false, devices, -1);
  222103. return devices;
  222104. }
  222105. int MidiOutput::getDefaultDeviceIndex()
  222106. {
  222107. return 0;
  222108. }
  222109. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  222110. {
  222111. MidiOutput* newDevice = 0;
  222112. StringArray devices;
  222113. snd_seq_t* const handle = iterateDevices (false, devices, deviceIndex);
  222114. if (handle != 0)
  222115. {
  222116. newDevice = new MidiOutput();
  222117. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  222118. }
  222119. return newDevice;
  222120. }
  222121. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  222122. {
  222123. MidiOutput* newDevice = 0;
  222124. snd_seq_t* const handle = createDevice (false, deviceName);
  222125. if (handle != 0)
  222126. {
  222127. newDevice = new MidiOutput();
  222128. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  222129. }
  222130. return newDevice;
  222131. }
  222132. MidiOutput::~MidiOutput()
  222133. {
  222134. MidiOutputDevice* const device = (MidiOutputDevice*) internal;
  222135. delete device;
  222136. }
  222137. void MidiOutput::reset()
  222138. {
  222139. }
  222140. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  222141. {
  222142. return false;
  222143. }
  222144. void MidiOutput::setVolume (float leftVol, float rightVol)
  222145. {
  222146. }
  222147. void MidiOutput::sendMessageNow (const MidiMessage& message)
  222148. {
  222149. ((MidiOutputDevice*) internal)->sendMessageNow (message);
  222150. }
  222151. class MidiInputThread : public Thread
  222152. {
  222153. public:
  222154. MidiInputThread (MidiInput* const midiInput_,
  222155. snd_seq_t* const seqHandle_,
  222156. MidiInputCallback* const callback_)
  222157. : Thread ("Juce MIDI Input"),
  222158. midiInput (midiInput_),
  222159. seqHandle (seqHandle_),
  222160. callback (callback_)
  222161. {
  222162. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  222163. }
  222164. ~MidiInputThread()
  222165. {
  222166. snd_seq_close (seqHandle);
  222167. }
  222168. void run()
  222169. {
  222170. const int maxEventSize = 16 * 1024;
  222171. snd_midi_event_t* midiParser;
  222172. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  222173. {
  222174. HeapBlock <uint8> buffer (maxEventSize);
  222175. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  222176. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  222177. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  222178. while (! threadShouldExit())
  222179. {
  222180. if (poll (pfd, numPfds, 500) > 0)
  222181. {
  222182. snd_seq_event_t* inputEvent = 0;
  222183. snd_seq_nonblock (seqHandle, 1);
  222184. do
  222185. {
  222186. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  222187. {
  222188. // xxx what about SYSEXes that are too big for the buffer?
  222189. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  222190. snd_midi_event_reset_decode (midiParser);
  222191. if (numBytes > 0)
  222192. {
  222193. const MidiMessage message ((const uint8*) buffer,
  222194. numBytes,
  222195. Time::getMillisecondCounter() * 0.001);
  222196. callback->handleIncomingMidiMessage (midiInput, message);
  222197. }
  222198. snd_seq_free_event (inputEvent);
  222199. }
  222200. }
  222201. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  222202. snd_seq_free_event (inputEvent);
  222203. }
  222204. }
  222205. snd_midi_event_free (midiParser);
  222206. }
  222207. };
  222208. juce_UseDebuggingNewOperator
  222209. private:
  222210. MidiInput* const midiInput;
  222211. snd_seq_t* const seqHandle;
  222212. MidiInputCallback* const callback;
  222213. };
  222214. MidiInput::MidiInput (const String& name_)
  222215. : name (name_),
  222216. internal (0)
  222217. {
  222218. }
  222219. MidiInput::~MidiInput()
  222220. {
  222221. stop();
  222222. MidiInputThread* const thread = (MidiInputThread*) internal;
  222223. delete thread;
  222224. }
  222225. void MidiInput::start()
  222226. {
  222227. ((MidiInputThread*) internal)->startThread();
  222228. }
  222229. void MidiInput::stop()
  222230. {
  222231. ((MidiInputThread*) internal)->stopThread (3000);
  222232. }
  222233. int MidiInput::getDefaultDeviceIndex()
  222234. {
  222235. return 0;
  222236. }
  222237. const StringArray MidiInput::getDevices()
  222238. {
  222239. StringArray devices;
  222240. iterateDevices (true, devices, -1);
  222241. return devices;
  222242. }
  222243. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  222244. {
  222245. MidiInput* newDevice = 0;
  222246. StringArray devices;
  222247. snd_seq_t* const handle = iterateDevices (true, devices, deviceIndex);
  222248. if (handle != 0)
  222249. {
  222250. newDevice = new MidiInput (devices [deviceIndex]);
  222251. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  222252. }
  222253. return newDevice;
  222254. }
  222255. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  222256. {
  222257. MidiInput* newDevice = 0;
  222258. snd_seq_t* const handle = createDevice (true, deviceName);
  222259. if (handle != 0)
  222260. {
  222261. newDevice = new MidiInput (deviceName);
  222262. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  222263. }
  222264. return newDevice;
  222265. }
  222266. #else
  222267. // (These are just stub functions if ALSA is unavailable...)
  222268. const StringArray MidiOutput::getDevices() { return StringArray(); }
  222269. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  222270. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  222271. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  222272. MidiOutput::~MidiOutput() {}
  222273. void MidiOutput::reset() {}
  222274. bool MidiOutput::getVolume (float&, float&) { return false; }
  222275. void MidiOutput::setVolume (float, float) {}
  222276. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  222277. MidiInput::MidiInput (const String& name_) : name (name_), internal (0) {}
  222278. MidiInput::~MidiInput() {}
  222279. void MidiInput::start() {}
  222280. void MidiInput::stop() {}
  222281. int MidiInput::getDefaultDeviceIndex() { return 0; }
  222282. const StringArray MidiInput::getDevices() { return StringArray(); }
  222283. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  222284. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  222285. #endif
  222286. #endif
  222287. /*** End of inlined file: juce_linux_Midi.cpp ***/
  222288. /*** Start of inlined file: juce_linux_AudioCDReader.cpp ***/
  222289. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222290. // compiled on its own).
  222291. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  222292. AudioCDReader::AudioCDReader()
  222293. : AudioFormatReader (0, "CD Audio")
  222294. {
  222295. }
  222296. const StringArray AudioCDReader::getAvailableCDNames()
  222297. {
  222298. StringArray names;
  222299. return names;
  222300. }
  222301. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  222302. {
  222303. return 0;
  222304. }
  222305. AudioCDReader::~AudioCDReader()
  222306. {
  222307. }
  222308. void AudioCDReader::refreshTrackLengths()
  222309. {
  222310. }
  222311. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  222312. int64 startSampleInFile, int numSamples)
  222313. {
  222314. return false;
  222315. }
  222316. bool AudioCDReader::isCDStillPresent() const
  222317. {
  222318. return false;
  222319. }
  222320. int AudioCDReader::getNumTracks() const
  222321. {
  222322. return 0;
  222323. }
  222324. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  222325. {
  222326. return 0;
  222327. }
  222328. bool AudioCDReader::isTrackAudio (int trackNum) const
  222329. {
  222330. return false;
  222331. }
  222332. void AudioCDReader::enableIndexScanning (bool b)
  222333. {
  222334. }
  222335. int AudioCDReader::getLastIndex() const
  222336. {
  222337. return 0;
  222338. }
  222339. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  222340. {
  222341. return Array<int>();
  222342. }
  222343. int AudioCDReader::getCDDBId()
  222344. {
  222345. return 0;
  222346. }
  222347. #endif
  222348. /*** End of inlined file: juce_linux_AudioCDReader.cpp ***/
  222349. /*** Start of inlined file: juce_linux_FileChooser.cpp ***/
  222350. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222351. // compiled on its own).
  222352. #if JUCE_INCLUDED_FILE
  222353. void FileChooser::showPlatformDialog (Array<File>& results,
  222354. const String& title,
  222355. const File& file,
  222356. const String& filters,
  222357. bool isDirectory,
  222358. bool selectsFiles,
  222359. bool isSave,
  222360. bool warnAboutOverwritingExistingFiles,
  222361. bool selectMultipleFiles,
  222362. FilePreviewComponent* previewComponent)
  222363. {
  222364. const String separator (":");
  222365. String command ("zenity --file-selection");
  222366. if (title.isNotEmpty())
  222367. command << " --title=\"" << title << "\"";
  222368. if (file != File::nonexistent)
  222369. command << " --filename=\"" << file.getFullPathName () << "\"";
  222370. if (isDirectory)
  222371. command << " --directory";
  222372. if (isSave)
  222373. command << " --save";
  222374. if (selectMultipleFiles)
  222375. command << " --multiple --separator=\"" << separator << "\"";
  222376. command << " 2>&1";
  222377. MemoryOutputStream result;
  222378. int status = -1;
  222379. FILE* stream = popen (command.toUTF8(), "r");
  222380. if (stream != 0)
  222381. {
  222382. for (;;)
  222383. {
  222384. char buffer [1024];
  222385. const int bytesRead = fread (buffer, 1, sizeof (buffer), stream);
  222386. if (bytesRead <= 0)
  222387. break;
  222388. result.write (buffer, bytesRead);
  222389. }
  222390. status = pclose (stream);
  222391. }
  222392. if (status == 0)
  222393. {
  222394. StringArray tokens;
  222395. if (selectMultipleFiles)
  222396. tokens.addTokens (result.toUTF8(), separator, String::empty);
  222397. else
  222398. tokens.add (result.toUTF8());
  222399. for (int i = 0; i < tokens.size(); i++)
  222400. results.add (File (tokens[i]));
  222401. return;
  222402. }
  222403. //xxx ain't got one!
  222404. jassertfalse;
  222405. }
  222406. #endif
  222407. /*** End of inlined file: juce_linux_FileChooser.cpp ***/
  222408. /*** Start of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  222409. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222410. // compiled on its own).
  222411. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  222412. /*
  222413. Sorry.. This class isn't implemented on Linux!
  222414. */
  222415. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  222416. : browser (0),
  222417. blankPageShown (false),
  222418. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  222419. {
  222420. setOpaque (true);
  222421. }
  222422. WebBrowserComponent::~WebBrowserComponent()
  222423. {
  222424. }
  222425. void WebBrowserComponent::goToURL (const String& url,
  222426. const StringArray* headers,
  222427. const MemoryBlock* postData)
  222428. {
  222429. lastURL = url;
  222430. lastHeaders.clear();
  222431. if (headers != 0)
  222432. lastHeaders = *headers;
  222433. lastPostData.setSize (0);
  222434. if (postData != 0)
  222435. lastPostData = *postData;
  222436. blankPageShown = false;
  222437. }
  222438. void WebBrowserComponent::stop()
  222439. {
  222440. }
  222441. void WebBrowserComponent::goBack()
  222442. {
  222443. lastURL = String::empty;
  222444. blankPageShown = false;
  222445. }
  222446. void WebBrowserComponent::goForward()
  222447. {
  222448. lastURL = String::empty;
  222449. }
  222450. void WebBrowserComponent::refresh()
  222451. {
  222452. }
  222453. void WebBrowserComponent::paint (Graphics& g)
  222454. {
  222455. g.fillAll (Colours::white);
  222456. }
  222457. void WebBrowserComponent::checkWindowAssociation()
  222458. {
  222459. }
  222460. void WebBrowserComponent::reloadLastURL()
  222461. {
  222462. if (lastURL.isNotEmpty())
  222463. {
  222464. goToURL (lastURL, &lastHeaders, &lastPostData);
  222465. lastURL = String::empty;
  222466. }
  222467. }
  222468. void WebBrowserComponent::parentHierarchyChanged()
  222469. {
  222470. checkWindowAssociation();
  222471. }
  222472. void WebBrowserComponent::resized()
  222473. {
  222474. }
  222475. void WebBrowserComponent::visibilityChanged()
  222476. {
  222477. checkWindowAssociation();
  222478. }
  222479. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  222480. {
  222481. return true;
  222482. }
  222483. #endif
  222484. /*** End of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  222485. #endif
  222486. END_JUCE_NAMESPACE
  222487. #endif
  222488. /*** End of inlined file: juce_linux_NativeCode.cpp ***/
  222489. #endif
  222490. #if JUCE_MAC || JUCE_IPHONE
  222491. /*** Start of inlined file: juce_mac_NativeCode.mm ***/
  222492. /*
  222493. This file wraps together all the mac-specific code, so that
  222494. we can include all the native headers just once, and compile all our
  222495. platform-specific stuff in one big lump, keeping it out of the way of
  222496. the rest of the codebase.
  222497. */
  222498. #if JUCE_MAC || JUCE_IPHONE
  222499. BEGIN_JUCE_NAMESPACE
  222500. #undef Point
  222501. #define JUCE_INCLUDED_FILE 1
  222502. // Now include the actual code files..
  222503. /*** Start of inlined file: juce_mac_ObjCSuffix.h ***/
  222504. /** This suffix is used for naming all Obj-C classes that are used inside juce.
  222505. Because of the flat naming structure used by Obj-C, you can get horrible situations where
  222506. two DLLs are loaded into a host, each of which uses classes with the same names, and these get
  222507. cross-linked so that when you make a call to a class that you thought was private, it ends up
  222508. actually calling into a similarly named class in the other module's address space.
  222509. By changing this macro to a unique value, you ensure that all the obj-C classes in your app
  222510. have unique names, and should avoid this problem.
  222511. If you're using the amalgamated version, you can just set this macro to something unique before
  222512. you include juce_amalgamated.cpp.
  222513. */
  222514. #ifndef JUCE_ObjCExtraSuffix
  222515. #define JUCE_ObjCExtraSuffix 3
  222516. #endif
  222517. #define appendMacro1(a, b, c, d, e) a ## _ ## b ## _ ## c ## _ ## d ## _ ## e
  222518. #define appendMacro2(a, b, c, d, e) appendMacro1(a, b, c, d, e)
  222519. #define MakeObjCClassName(rootName) appendMacro2 (rootName, JUCE_MAJOR_VERSION, JUCE_MINOR_VERSION, JUCE_BUILDNUMBER, JUCE_ObjCExtraSuffix)
  222520. /*** End of inlined file: juce_mac_ObjCSuffix.h ***/
  222521. /*** Start of inlined file: juce_mac_Strings.mm ***/
  222522. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222523. // compiled on its own).
  222524. #if JUCE_INCLUDED_FILE
  222525. static const String nsStringToJuce (NSString* s)
  222526. {
  222527. return String::fromUTF8 ([s UTF8String]);
  222528. }
  222529. static NSString* juceStringToNS (const String& s)
  222530. {
  222531. return [NSString stringWithUTF8String: s.toUTF8()];
  222532. }
  222533. static const String convertUTF16ToString (const UniChar* utf16)
  222534. {
  222535. String s;
  222536. while (*utf16 != 0)
  222537. s += (juce_wchar) *utf16++;
  222538. return s;
  222539. }
  222540. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  222541. {
  222542. String result;
  222543. if (cfString != 0)
  222544. {
  222545. CFRange range = { 0, CFStringGetLength (cfString) };
  222546. HeapBlock <UniChar> u (range.length + 1);
  222547. CFStringGetCharacters (cfString, range, u);
  222548. u[range.length] = 0;
  222549. result = convertUTF16ToString (u);
  222550. }
  222551. return result;
  222552. }
  222553. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  222554. {
  222555. const int len = s.length();
  222556. HeapBlock <UniChar> temp (len + 2);
  222557. for (int i = 0; i <= len; ++i)
  222558. temp[i] = s[i];
  222559. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  222560. }
  222561. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  222562. {
  222563. #if JUCE_IPHONE
  222564. const ScopedAutoReleasePool pool;
  222565. return nsStringToJuce ([juceStringToNS (s) precomposedStringWithCanonicalMapping]);
  222566. #else
  222567. UnicodeMapping map;
  222568. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  222569. kUnicodeNoSubset,
  222570. kTextEncodingDefaultFormat);
  222571. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  222572. kUnicodeCanonicalCompVariant,
  222573. kTextEncodingDefaultFormat);
  222574. map.mappingVersion = kUnicodeUseLatestMapping;
  222575. UnicodeToTextInfo conversionInfo = 0;
  222576. String result;
  222577. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  222578. {
  222579. const int len = s.length();
  222580. HeapBlock <UniChar> tempIn, tempOut;
  222581. tempIn.calloc (len + 2);
  222582. tempOut.calloc (len + 2);
  222583. for (int i = 0; i <= len; ++i)
  222584. tempIn[i] = s[i];
  222585. ByteCount bytesRead = 0;
  222586. ByteCount outputBufferSize = 0;
  222587. if (ConvertFromUnicodeToText (conversionInfo,
  222588. len * sizeof (UniChar), tempIn,
  222589. kUnicodeDefaultDirectionMask,
  222590. 0, 0, 0, 0,
  222591. len * sizeof (UniChar), &bytesRead,
  222592. &outputBufferSize, tempOut) == noErr)
  222593. {
  222594. result.preallocateStorage (bytesRead / sizeof (UniChar) + 2);
  222595. juce_wchar* t = result;
  222596. unsigned int i;
  222597. for (i = 0; i < bytesRead / sizeof (UniChar); ++i)
  222598. t[i] = (juce_wchar) tempOut[i];
  222599. t[i] = 0;
  222600. }
  222601. DisposeUnicodeToTextInfo (&conversionInfo);
  222602. }
  222603. return result;
  222604. #endif
  222605. }
  222606. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  222607. void SystemClipboard::copyTextToClipboard (const String& text)
  222608. {
  222609. #if JUCE_IPHONE
  222610. [[UIPasteboard generalPasteboard] setValue: juceStringToNS (text)
  222611. forPasteboardType: @"public.text"];
  222612. #else
  222613. [[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSStringPboardType]
  222614. owner: nil];
  222615. [[NSPasteboard generalPasteboard] setString: juceStringToNS (text)
  222616. forType: NSStringPboardType];
  222617. #endif
  222618. }
  222619. const String SystemClipboard::getTextFromClipboard()
  222620. {
  222621. #if JUCE_IPHONE
  222622. NSString* text = [[UIPasteboard generalPasteboard] valueForPasteboardType: @"public.text"];
  222623. #else
  222624. NSString* text = [[NSPasteboard generalPasteboard] stringForType: NSStringPboardType];
  222625. #endif
  222626. return text == 0 ? String::empty
  222627. : nsStringToJuce (text);
  222628. }
  222629. #endif
  222630. #endif
  222631. /*** End of inlined file: juce_mac_Strings.mm ***/
  222632. /*** Start of inlined file: juce_mac_SystemStats.mm ***/
  222633. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222634. // compiled on its own).
  222635. #if JUCE_INCLUDED_FILE
  222636. namespace SystemStatsHelpers
  222637. {
  222638. static int64 highResTimerFrequency = 0;
  222639. static double highResTimerToMillisecRatio = 0;
  222640. #if JUCE_INTEL
  222641. static void juce_getCpuVendor (char* const v) throw()
  222642. {
  222643. int vendor[4];
  222644. zerostruct (vendor);
  222645. int dummy = 0;
  222646. asm ("mov %%ebx, %%esi \n\t"
  222647. "cpuid \n\t"
  222648. "xchg %%esi, %%ebx"
  222649. : "=a" (dummy), "=S" (vendor[0]), "=c" (vendor[2]), "=d" (vendor[1]) : "a" (0));
  222650. memcpy (v, vendor, 16);
  222651. }
  222652. static unsigned int getCPUIDWord (unsigned int& familyModel, unsigned int& extFeatures)
  222653. {
  222654. unsigned int cpu = 0;
  222655. unsigned int ext = 0;
  222656. unsigned int family = 0;
  222657. unsigned int dummy = 0;
  222658. asm ("mov %%ebx, %%esi \n\t"
  222659. "cpuid \n\t"
  222660. "xchg %%esi, %%ebx"
  222661. : "=a" (family), "=S" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  222662. familyModel = family;
  222663. extFeatures = ext;
  222664. return cpu;
  222665. }
  222666. #endif
  222667. }
  222668. void SystemStats::initialiseStats()
  222669. {
  222670. using namespace SystemStatsHelpers;
  222671. static bool initialised = false;
  222672. if (! initialised)
  222673. {
  222674. initialised = true;
  222675. #if JUCE_MAC
  222676. // extremely annoying: adding this line stops the apple menu items from working. Of
  222677. // course, not adding it means that carbon windows (e.g. in plugins) won't get
  222678. // any events.
  222679. //NSApplicationLoad();
  222680. [NSApplication sharedApplication];
  222681. #endif
  222682. #if JUCE_INTEL
  222683. unsigned int familyModel, extFeatures;
  222684. const unsigned int features = getCPUIDWord (familyModel, extFeatures);
  222685. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  222686. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  222687. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  222688. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  222689. #else
  222690. cpuFlags.hasMMX = false;
  222691. cpuFlags.hasSSE = false;
  222692. cpuFlags.hasSSE2 = false;
  222693. cpuFlags.has3DNow = false;
  222694. #endif
  222695. #if JUCE_IPHONE || (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5)
  222696. cpuFlags.numCpus = (int) [[NSProcessInfo processInfo] activeProcessorCount];
  222697. #else
  222698. cpuFlags.numCpus = (int) MPProcessors();
  222699. #endif
  222700. mach_timebase_info_data_t timebase;
  222701. (void) mach_timebase_info (&timebase);
  222702. highResTimerFrequency = (int64) (1.0e9 * timebase.denom / timebase.numer);
  222703. highResTimerToMillisecRatio = timebase.numer / (1.0e6 * timebase.denom);
  222704. String s (SystemStats::getJUCEVersion());
  222705. rlimit lim;
  222706. getrlimit (RLIMIT_NOFILE, &lim);
  222707. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  222708. setrlimit (RLIMIT_NOFILE, &lim);
  222709. }
  222710. }
  222711. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  222712. {
  222713. return MacOSX;
  222714. }
  222715. const String SystemStats::getOperatingSystemName()
  222716. {
  222717. return "Mac OS X";
  222718. }
  222719. bool SystemStats::isOperatingSystem64Bit()
  222720. {
  222721. #if JUCE_64BIT
  222722. return true;
  222723. #else
  222724. //xxx not sure how to find this out?..
  222725. return false;
  222726. #endif
  222727. }
  222728. int SystemStats::getMemorySizeInMegabytes()
  222729. {
  222730. uint64 mem = 0;
  222731. size_t memSize = sizeof (mem);
  222732. int mib[] = { CTL_HW, HW_MEMSIZE };
  222733. sysctl (mib, 2, &mem, &memSize, 0, 0);
  222734. return (int) (mem / (1024 * 1024));
  222735. }
  222736. const String SystemStats::getCpuVendor()
  222737. {
  222738. #if JUCE_INTEL
  222739. char v [16];
  222740. SystemStatsHelpers::juce_getCpuVendor (v);
  222741. return String (v, 16);
  222742. #else
  222743. return String::empty;
  222744. #endif
  222745. }
  222746. int SystemStats::getCpuSpeedInMegaherz()
  222747. {
  222748. uint64 speedHz = 0;
  222749. size_t speedSize = sizeof (speedHz);
  222750. int mib[] = { CTL_HW, HW_CPU_FREQ };
  222751. sysctl (mib, 2, &speedHz, &speedSize, 0, 0);
  222752. #if JUCE_BIG_ENDIAN
  222753. if (speedSize == 4)
  222754. speedHz >>= 32;
  222755. #endif
  222756. return (int) (speedHz / 1000000);
  222757. }
  222758. const String SystemStats::getLogonName()
  222759. {
  222760. return nsStringToJuce (NSUserName());
  222761. }
  222762. const String SystemStats::getFullUserName()
  222763. {
  222764. return nsStringToJuce (NSFullUserName());
  222765. }
  222766. uint32 juce_millisecondsSinceStartup() throw()
  222767. {
  222768. return (uint32) (mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio);
  222769. }
  222770. double Time::getMillisecondCounterHiRes() throw()
  222771. {
  222772. return mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio;
  222773. }
  222774. int64 Time::getHighResolutionTicks() throw()
  222775. {
  222776. return (int64) mach_absolute_time();
  222777. }
  222778. int64 Time::getHighResolutionTicksPerSecond() throw()
  222779. {
  222780. return SystemStatsHelpers::highResTimerFrequency;
  222781. }
  222782. bool Time::setSystemTimeToThisTime() const
  222783. {
  222784. jassertfalse;
  222785. return false;
  222786. }
  222787. int SystemStats::getPageSize()
  222788. {
  222789. return (int) NSPageSize();
  222790. }
  222791. void PlatformUtilities::fpuReset()
  222792. {
  222793. }
  222794. #endif
  222795. /*** End of inlined file: juce_mac_SystemStats.mm ***/
  222796. /*** Start of inlined file: juce_mac_Network.mm ***/
  222797. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222798. // compiled on its own).
  222799. #if JUCE_INCLUDED_FILE
  222800. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  222801. {
  222802. #ifndef IFT_ETHER
  222803. #define IFT_ETHER 6
  222804. #endif
  222805. ifaddrs* addrs = 0;
  222806. int numResults = 0;
  222807. if (getifaddrs (&addrs) == 0)
  222808. {
  222809. const ifaddrs* cursor = addrs;
  222810. while (cursor != 0 && numResults < maxNum)
  222811. {
  222812. sockaddr_storage* sto = (sockaddr_storage*) cursor->ifa_addr;
  222813. if (sto->ss_family == AF_LINK)
  222814. {
  222815. const sockaddr_dl* const sadd = (const sockaddr_dl*) cursor->ifa_addr;
  222816. if (sadd->sdl_type == IFT_ETHER)
  222817. {
  222818. const uint8* const addr = ((const uint8*) sadd->sdl_data) + sadd->sdl_nlen;
  222819. uint64 a = 0;
  222820. for (int i = 6; --i >= 0;)
  222821. a = (a << 8) | addr [littleEndian ? i : (5 - i)];
  222822. *addresses++ = (int64) a;
  222823. ++numResults;
  222824. }
  222825. }
  222826. cursor = cursor->ifa_next;
  222827. }
  222828. freeifaddrs (addrs);
  222829. }
  222830. return numResults;
  222831. }
  222832. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  222833. const String& emailSubject,
  222834. const String& bodyText,
  222835. const StringArray& filesToAttach)
  222836. {
  222837. #if JUCE_IPHONE
  222838. //xxx probably need to use MFMailComposeViewController
  222839. jassertfalse;
  222840. return false;
  222841. #else
  222842. const ScopedAutoReleasePool pool;
  222843. String script;
  222844. script << "tell application \"Mail\"\r\n"
  222845. "set newMessage to make new outgoing message with properties {subject:\""
  222846. << emailSubject.replace ("\"", "\\\"")
  222847. << "\", content:\""
  222848. << bodyText.replace ("\"", "\\\"")
  222849. << "\" & return & return}\r\n"
  222850. "tell newMessage\r\n"
  222851. "set visible to true\r\n"
  222852. "set sender to \"sdfsdfsdfewf\"\r\n"
  222853. "make new to recipient at end of to recipients with properties {address:\""
  222854. << targetEmailAddress
  222855. << "\"}\r\n";
  222856. for (int i = 0; i < filesToAttach.size(); ++i)
  222857. {
  222858. script << "tell content\r\n"
  222859. "make new attachment with properties {file name:\""
  222860. << filesToAttach[i].replace ("\"", "\\\"")
  222861. << "\"} at after the last paragraph\r\n"
  222862. "end tell\r\n";
  222863. }
  222864. script << "end tell\r\n"
  222865. "end tell\r\n";
  222866. NSAppleScript* s = [[NSAppleScript alloc]
  222867. initWithSource: juceStringToNS (script)];
  222868. NSDictionary* error = 0;
  222869. const bool ok = [s executeAndReturnError: &error] != nil;
  222870. [s release];
  222871. return ok;
  222872. #endif
  222873. }
  222874. END_JUCE_NAMESPACE
  222875. using namespace JUCE_NAMESPACE;
  222876. #define JuceURLConnection MakeObjCClassName(JuceURLConnection)
  222877. @interface JuceURLConnection : NSObject
  222878. {
  222879. @public
  222880. NSURLRequest* request;
  222881. NSURLConnection* connection;
  222882. NSMutableData* data;
  222883. Thread* runLoopThread;
  222884. bool initialised, hasFailed, hasFinished;
  222885. int position;
  222886. int64 contentLength;
  222887. NSDictionary* headers;
  222888. NSLock* dataLock;
  222889. }
  222890. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req withCallback: (URL::OpenStreamProgressCallback*) callback withContext: (void*) context;
  222891. - (void) dealloc;
  222892. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response;
  222893. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error;
  222894. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data;
  222895. - (void) connectionDidFinishLoading: (NSURLConnection*) connection;
  222896. - (BOOL) isOpen;
  222897. - (int) read: (char*) dest numBytes: (int) num;
  222898. - (int) readPosition;
  222899. - (void) stop;
  222900. - (void) createConnection;
  222901. @end
  222902. class JuceURLConnectionMessageThread : public Thread
  222903. {
  222904. JuceURLConnection* owner;
  222905. public:
  222906. JuceURLConnectionMessageThread (JuceURLConnection* owner_)
  222907. : Thread ("http connection"),
  222908. owner (owner_)
  222909. {
  222910. }
  222911. ~JuceURLConnectionMessageThread()
  222912. {
  222913. stopThread (10000);
  222914. }
  222915. void run()
  222916. {
  222917. [owner createConnection];
  222918. while (! threadShouldExit())
  222919. {
  222920. const ScopedAutoReleasePool pool;
  222921. [[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  222922. }
  222923. }
  222924. };
  222925. @implementation JuceURLConnection
  222926. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req
  222927. withCallback: (URL::OpenStreamProgressCallback*) callback
  222928. withContext: (void*) context;
  222929. {
  222930. [super init];
  222931. request = req;
  222932. [request retain];
  222933. data = [[NSMutableData data] retain];
  222934. dataLock = [[NSLock alloc] init];
  222935. connection = 0;
  222936. initialised = false;
  222937. hasFailed = false;
  222938. hasFinished = false;
  222939. contentLength = -1;
  222940. headers = 0;
  222941. runLoopThread = new JuceURLConnectionMessageThread (self);
  222942. runLoopThread->startThread();
  222943. while (runLoopThread->isThreadRunning() && ! initialised)
  222944. {
  222945. if (callback != 0)
  222946. callback (context, -1, (int) [[request HTTPBody] length]);
  222947. Thread::sleep (1);
  222948. }
  222949. return self;
  222950. }
  222951. - (void) dealloc
  222952. {
  222953. [self stop];
  222954. deleteAndZero (runLoopThread);
  222955. [connection release];
  222956. [data release];
  222957. [dataLock release];
  222958. [request release];
  222959. [headers release];
  222960. [super dealloc];
  222961. }
  222962. - (void) createConnection
  222963. {
  222964. NSInteger oldRetainCount = [self retainCount];
  222965. connection = [[NSURLConnection alloc] initWithRequest: request
  222966. delegate: self];
  222967. if (oldRetainCount == [self retainCount])
  222968. [self retain]; // newer SDK should already retain this, but there were problems in older versions..
  222969. if (connection == nil)
  222970. runLoopThread->signalThreadShouldExit();
  222971. }
  222972. - (void) connection: (NSURLConnection*) conn didReceiveResponse: (NSURLResponse*) response
  222973. {
  222974. (void) conn;
  222975. [dataLock lock];
  222976. [data setLength: 0];
  222977. [dataLock unlock];
  222978. initialised = true;
  222979. contentLength = [response expectedContentLength];
  222980. [headers release];
  222981. headers = 0;
  222982. if ([response isKindOfClass: [NSHTTPURLResponse class]])
  222983. headers = [[((NSHTTPURLResponse*) response) allHeaderFields] retain];
  222984. }
  222985. - (void) connection: (NSURLConnection*) conn didFailWithError: (NSError*) error
  222986. {
  222987. (void) conn;
  222988. DBG (nsStringToJuce ([error description]));
  222989. hasFailed = true;
  222990. initialised = true;
  222991. if (runLoopThread != 0)
  222992. runLoopThread->signalThreadShouldExit();
  222993. }
  222994. - (void) connection: (NSURLConnection*) conn didReceiveData: (NSData*) newData
  222995. {
  222996. (void) conn;
  222997. [dataLock lock];
  222998. [data appendData: newData];
  222999. [dataLock unlock];
  223000. initialised = true;
  223001. }
  223002. - (void) connectionDidFinishLoading: (NSURLConnection*) conn
  223003. {
  223004. (void) conn;
  223005. hasFinished = true;
  223006. initialised = true;
  223007. if (runLoopThread != 0)
  223008. runLoopThread->signalThreadShouldExit();
  223009. }
  223010. - (BOOL) isOpen
  223011. {
  223012. return connection != 0 && ! hasFailed;
  223013. }
  223014. - (int) readPosition
  223015. {
  223016. return position;
  223017. }
  223018. - (int) read: (char*) dest numBytes: (int) numNeeded
  223019. {
  223020. int numDone = 0;
  223021. while (numNeeded > 0)
  223022. {
  223023. int available = jmin (numNeeded, (int) [data length]);
  223024. if (available > 0)
  223025. {
  223026. [dataLock lock];
  223027. [data getBytes: dest length: available];
  223028. [data replaceBytesInRange: NSMakeRange (0, available) withBytes: nil length: 0];
  223029. [dataLock unlock];
  223030. numDone += available;
  223031. numNeeded -= available;
  223032. dest += available;
  223033. }
  223034. else
  223035. {
  223036. if (hasFailed || hasFinished)
  223037. break;
  223038. Thread::sleep (1);
  223039. }
  223040. }
  223041. position += numDone;
  223042. return numDone;
  223043. }
  223044. - (void) stop
  223045. {
  223046. [connection cancel];
  223047. if (runLoopThread != 0)
  223048. runLoopThread->stopThread (10000);
  223049. }
  223050. @end
  223051. BEGIN_JUCE_NAMESPACE
  223052. void* juce_openInternetFile (const String& url,
  223053. const String& headers,
  223054. const MemoryBlock& postData,
  223055. const bool isPost,
  223056. URL::OpenStreamProgressCallback* callback,
  223057. void* callbackContext,
  223058. int timeOutMs)
  223059. {
  223060. const ScopedAutoReleasePool pool;
  223061. NSMutableURLRequest* req = [NSMutableURLRequest
  223062. requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  223063. cachePolicy: NSURLRequestUseProtocolCachePolicy
  223064. timeoutInterval: timeOutMs <= 0 ? 60.0 : (timeOutMs / 1000.0)];
  223065. if (req == nil)
  223066. return 0;
  223067. [req setHTTPMethod: isPost ? @"POST" : @"GET"];
  223068. //[req setCachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
  223069. StringArray headerLines;
  223070. headerLines.addLines (headers);
  223071. headerLines.removeEmptyStrings (true);
  223072. for (int i = 0; i < headerLines.size(); ++i)
  223073. {
  223074. const String key (headerLines[i].upToFirstOccurrenceOf (":", false, false).trim());
  223075. const String value (headerLines[i].fromFirstOccurrenceOf (":", false, false).trim());
  223076. if (key.isNotEmpty() && value.isNotEmpty())
  223077. [req addValue: juceStringToNS (value) forHTTPHeaderField: juceStringToNS (key)];
  223078. }
  223079. if (isPost && postData.getSize() > 0)
  223080. {
  223081. [req setHTTPBody: [NSData dataWithBytes: postData.getData()
  223082. length: postData.getSize()]];
  223083. }
  223084. JuceURLConnection* const s = [[JuceURLConnection alloc] initWithRequest: req
  223085. withCallback: callback
  223086. withContext: callbackContext];
  223087. if ([s isOpen])
  223088. return s;
  223089. [s release];
  223090. return 0;
  223091. }
  223092. void juce_closeInternetFile (void* handle)
  223093. {
  223094. JuceURLConnection* const s = (JuceURLConnection*) handle;
  223095. if (s != 0)
  223096. {
  223097. const ScopedAutoReleasePool pool;
  223098. [s stop];
  223099. [s release];
  223100. }
  223101. }
  223102. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  223103. {
  223104. JuceURLConnection* const s = (JuceURLConnection*) handle;
  223105. if (s != 0)
  223106. {
  223107. const ScopedAutoReleasePool pool;
  223108. return [s read: (char*) buffer numBytes: bytesToRead];
  223109. }
  223110. return 0;
  223111. }
  223112. int64 juce_getInternetFileContentLength (void* handle)
  223113. {
  223114. JuceURLConnection* const s = (JuceURLConnection*) handle;
  223115. if (s != 0)
  223116. return s->contentLength;
  223117. return -1;
  223118. }
  223119. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  223120. {
  223121. JuceURLConnection* const s = (JuceURLConnection*) handle;
  223122. if (s != 0 && s->headers != 0)
  223123. {
  223124. NSEnumerator* enumerator = [s->headers keyEnumerator];
  223125. NSString* key;
  223126. while ((key = [enumerator nextObject]) != nil)
  223127. headers.set (nsStringToJuce (key),
  223128. nsStringToJuce ((NSString*) [s->headers objectForKey: key]));
  223129. }
  223130. }
  223131. int juce_seekInInternetFile (void* handle, int /*newPosition*/)
  223132. {
  223133. JuceURLConnection* const s = (JuceURLConnection*) handle;
  223134. if (s != 0)
  223135. return [s readPosition];
  223136. return 0;
  223137. }
  223138. #endif
  223139. /*** End of inlined file: juce_mac_Network.mm ***/
  223140. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  223141. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223142. // compiled on its own).
  223143. #if JUCE_INCLUDED_FILE
  223144. struct NamedPipeInternal
  223145. {
  223146. String pipeInName, pipeOutName;
  223147. int pipeIn, pipeOut;
  223148. bool volatile createdPipe, blocked, stopReadOperation;
  223149. static void signalHandler (int) {}
  223150. };
  223151. void NamedPipe::cancelPendingReads()
  223152. {
  223153. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  223154. {
  223155. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  223156. intern->stopReadOperation = true;
  223157. char buffer [1] = { 0 };
  223158. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  223159. (void) bytesWritten;
  223160. int timeout = 2000;
  223161. while (intern->blocked && --timeout >= 0)
  223162. Thread::sleep (2);
  223163. intern->stopReadOperation = false;
  223164. }
  223165. }
  223166. void NamedPipe::close()
  223167. {
  223168. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  223169. if (intern != 0)
  223170. {
  223171. internal = 0;
  223172. if (intern->pipeIn != -1)
  223173. ::close (intern->pipeIn);
  223174. if (intern->pipeOut != -1)
  223175. ::close (intern->pipeOut);
  223176. if (intern->createdPipe)
  223177. {
  223178. unlink (intern->pipeInName.toUTF8());
  223179. unlink (intern->pipeOutName.toUTF8());
  223180. }
  223181. delete intern;
  223182. }
  223183. }
  223184. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  223185. {
  223186. close();
  223187. NamedPipeInternal* const intern = new NamedPipeInternal();
  223188. internal = intern;
  223189. intern->createdPipe = createPipe;
  223190. intern->blocked = false;
  223191. intern->stopReadOperation = false;
  223192. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  223193. siginterrupt (SIGPIPE, 1);
  223194. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  223195. intern->pipeInName = pipePath + "_in";
  223196. intern->pipeOutName = pipePath + "_out";
  223197. intern->pipeIn = -1;
  223198. intern->pipeOut = -1;
  223199. if (createPipe)
  223200. {
  223201. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  223202. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  223203. {
  223204. delete intern;
  223205. internal = 0;
  223206. return false;
  223207. }
  223208. }
  223209. return true;
  223210. }
  223211. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  223212. {
  223213. int bytesRead = -1;
  223214. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  223215. if (intern != 0)
  223216. {
  223217. intern->blocked = true;
  223218. if (intern->pipeIn == -1)
  223219. {
  223220. if (intern->createdPipe)
  223221. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  223222. else
  223223. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  223224. if (intern->pipeIn == -1)
  223225. {
  223226. intern->blocked = false;
  223227. return -1;
  223228. }
  223229. }
  223230. bytesRead = 0;
  223231. char* p = (char*) destBuffer;
  223232. while (bytesRead < maxBytesToRead)
  223233. {
  223234. const int bytesThisTime = maxBytesToRead - bytesRead;
  223235. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  223236. if (numRead <= 0 || intern->stopReadOperation)
  223237. {
  223238. bytesRead = -1;
  223239. break;
  223240. }
  223241. bytesRead += numRead;
  223242. p += bytesRead;
  223243. }
  223244. intern->blocked = false;
  223245. }
  223246. return bytesRead;
  223247. }
  223248. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  223249. {
  223250. int bytesWritten = -1;
  223251. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  223252. if (intern != 0)
  223253. {
  223254. if (intern->pipeOut == -1)
  223255. {
  223256. if (intern->createdPipe)
  223257. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  223258. else
  223259. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  223260. if (intern->pipeOut == -1)
  223261. {
  223262. return -1;
  223263. }
  223264. }
  223265. const char* p = (const char*) sourceBuffer;
  223266. bytesWritten = 0;
  223267. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  223268. while (bytesWritten < numBytesToWrite
  223269. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  223270. {
  223271. const int bytesThisTime = numBytesToWrite - bytesWritten;
  223272. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  223273. if (numWritten <= 0)
  223274. {
  223275. bytesWritten = -1;
  223276. break;
  223277. }
  223278. bytesWritten += numWritten;
  223279. p += bytesWritten;
  223280. }
  223281. }
  223282. return bytesWritten;
  223283. }
  223284. #endif
  223285. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  223286. /*** Start of inlined file: juce_mac_Threads.mm ***/
  223287. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223288. // compiled on its own).
  223289. #if JUCE_INCLUDED_FILE
  223290. /*
  223291. Note that a lot of methods that you'd expect to find in this file actually
  223292. live in juce_posix_SharedCode.h!
  223293. */
  223294. void JUCE_API juce_threadEntryPoint (void*);
  223295. void* threadEntryProc (void* userData)
  223296. {
  223297. const ScopedAutoReleasePool pool;
  223298. juce_threadEntryPoint (userData);
  223299. return 0;
  223300. }
  223301. void* juce_createThread (void* userData)
  223302. {
  223303. pthread_t handle = 0;
  223304. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  223305. {
  223306. pthread_detach (handle);
  223307. return (void*) handle;
  223308. }
  223309. return 0;
  223310. }
  223311. void juce_killThread (void* handle)
  223312. {
  223313. if (handle != 0)
  223314. pthread_cancel ((pthread_t) handle);
  223315. }
  223316. void juce_setCurrentThreadName (const String& /*name*/)
  223317. {
  223318. }
  223319. bool juce_setThreadPriority (void* handle, int priority)
  223320. {
  223321. if (handle == 0)
  223322. handle = (void*) pthread_self();
  223323. struct sched_param param;
  223324. int policy;
  223325. pthread_getschedparam ((pthread_t) handle, &policy, &param);
  223326. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  223327. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  223328. }
  223329. Thread::ThreadID Thread::getCurrentThreadId()
  223330. {
  223331. return static_cast <ThreadID> (pthread_self());
  223332. }
  223333. void Thread::yield()
  223334. {
  223335. sched_yield();
  223336. }
  223337. void Thread::setCurrentThreadAffinityMask (const uint32 /*affinityMask*/)
  223338. {
  223339. // xxx
  223340. jassertfalse;
  223341. }
  223342. bool Process::isForegroundProcess()
  223343. {
  223344. #if JUCE_MAC
  223345. return [NSApp isActive];
  223346. #else
  223347. return true; // xxx change this if more than one app is ever possible on the iPhone!
  223348. #endif
  223349. }
  223350. void Process::raisePrivilege()
  223351. {
  223352. jassertfalse;
  223353. }
  223354. void Process::lowerPrivilege()
  223355. {
  223356. jassertfalse;
  223357. }
  223358. void Process::terminate()
  223359. {
  223360. exit (0);
  223361. }
  223362. void Process::setPriority (ProcessPriority)
  223363. {
  223364. // xxx
  223365. }
  223366. #endif
  223367. /*** End of inlined file: juce_mac_Threads.mm ***/
  223368. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  223369. /*
  223370. This file contains posix routines that are common to both the Linux and Mac builds.
  223371. It gets included directly in the cpp files for these platforms.
  223372. */
  223373. CriticalSection::CriticalSection() throw()
  223374. {
  223375. pthread_mutexattr_t atts;
  223376. pthread_mutexattr_init (&atts);
  223377. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  223378. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  223379. pthread_mutex_init (&internal, &atts);
  223380. }
  223381. CriticalSection::~CriticalSection() throw()
  223382. {
  223383. pthread_mutex_destroy (&internal);
  223384. }
  223385. void CriticalSection::enter() const throw()
  223386. {
  223387. pthread_mutex_lock (&internal);
  223388. }
  223389. bool CriticalSection::tryEnter() const throw()
  223390. {
  223391. return pthread_mutex_trylock (&internal) == 0;
  223392. }
  223393. void CriticalSection::exit() const throw()
  223394. {
  223395. pthread_mutex_unlock (&internal);
  223396. }
  223397. class WaitableEventImpl
  223398. {
  223399. public:
  223400. WaitableEventImpl (const bool manualReset_)
  223401. : triggered (false),
  223402. manualReset (manualReset_)
  223403. {
  223404. pthread_cond_init (&condition, 0);
  223405. pthread_mutexattr_t atts;
  223406. pthread_mutexattr_init (&atts);
  223407. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  223408. pthread_mutex_init (&mutex, &atts);
  223409. }
  223410. ~WaitableEventImpl()
  223411. {
  223412. pthread_cond_destroy (&condition);
  223413. pthread_mutex_destroy (&mutex);
  223414. }
  223415. bool wait (const int timeOutMillisecs) throw()
  223416. {
  223417. pthread_mutex_lock (&mutex);
  223418. if (! triggered)
  223419. {
  223420. if (timeOutMillisecs < 0)
  223421. {
  223422. do
  223423. {
  223424. pthread_cond_wait (&condition, &mutex);
  223425. }
  223426. while (! triggered);
  223427. }
  223428. else
  223429. {
  223430. struct timeval now;
  223431. gettimeofday (&now, 0);
  223432. struct timespec time;
  223433. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  223434. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  223435. if (time.tv_nsec >= 1000000000)
  223436. {
  223437. time.tv_nsec -= 1000000000;
  223438. time.tv_sec++;
  223439. }
  223440. do
  223441. {
  223442. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  223443. {
  223444. pthread_mutex_unlock (&mutex);
  223445. return false;
  223446. }
  223447. }
  223448. while (! triggered);
  223449. }
  223450. }
  223451. if (! manualReset)
  223452. triggered = false;
  223453. pthread_mutex_unlock (&mutex);
  223454. return true;
  223455. }
  223456. void signal() throw()
  223457. {
  223458. pthread_mutex_lock (&mutex);
  223459. triggered = true;
  223460. pthread_cond_broadcast (&condition);
  223461. pthread_mutex_unlock (&mutex);
  223462. }
  223463. void reset() throw()
  223464. {
  223465. pthread_mutex_lock (&mutex);
  223466. triggered = false;
  223467. pthread_mutex_unlock (&mutex);
  223468. }
  223469. private:
  223470. pthread_cond_t condition;
  223471. pthread_mutex_t mutex;
  223472. bool triggered;
  223473. const bool manualReset;
  223474. WaitableEventImpl (const WaitableEventImpl&);
  223475. WaitableEventImpl& operator= (const WaitableEventImpl&);
  223476. };
  223477. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  223478. : internal (new WaitableEventImpl (manualReset))
  223479. {
  223480. }
  223481. WaitableEvent::~WaitableEvent() throw()
  223482. {
  223483. delete static_cast <WaitableEventImpl*> (internal);
  223484. }
  223485. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  223486. {
  223487. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  223488. }
  223489. void WaitableEvent::signal() const throw()
  223490. {
  223491. static_cast <WaitableEventImpl*> (internal)->signal();
  223492. }
  223493. void WaitableEvent::reset() const throw()
  223494. {
  223495. static_cast <WaitableEventImpl*> (internal)->reset();
  223496. }
  223497. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  223498. {
  223499. struct timespec time;
  223500. time.tv_sec = millisecs / 1000;
  223501. time.tv_nsec = (millisecs % 1000) * 1000000;
  223502. nanosleep (&time, 0);
  223503. }
  223504. const juce_wchar File::separator = '/';
  223505. const String File::separatorString ("/");
  223506. const File File::getCurrentWorkingDirectory()
  223507. {
  223508. HeapBlock<char> heapBuffer;
  223509. char localBuffer [1024];
  223510. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  223511. int bufferSize = 4096;
  223512. while (cwd == 0 && errno == ERANGE)
  223513. {
  223514. heapBuffer.malloc (bufferSize);
  223515. cwd = getcwd (heapBuffer, bufferSize - 1);
  223516. bufferSize += 1024;
  223517. }
  223518. return File (String::fromUTF8 (cwd));
  223519. }
  223520. bool File::setAsCurrentWorkingDirectory() const
  223521. {
  223522. return chdir (getFullPathName().toUTF8()) == 0;
  223523. }
  223524. static bool juce_stat (const String& fileName, struct stat& info)
  223525. {
  223526. return fileName.isNotEmpty()
  223527. && (stat (fileName.toUTF8(), &info) == 0);
  223528. }
  223529. bool File::isDirectory() const
  223530. {
  223531. struct stat info;
  223532. return fullPath.isEmpty()
  223533. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  223534. }
  223535. bool File::exists() const
  223536. {
  223537. return fullPath.isNotEmpty()
  223538. && access (fullPath.toUTF8(), F_OK) == 0;
  223539. }
  223540. bool File::existsAsFile() const
  223541. {
  223542. return exists() && ! isDirectory();
  223543. }
  223544. int64 File::getSize() const
  223545. {
  223546. struct stat info;
  223547. return juce_stat (fullPath, info) ? info.st_size : 0;
  223548. }
  223549. bool File::hasWriteAccess() const
  223550. {
  223551. if (exists())
  223552. return access (fullPath.toUTF8(), W_OK) == 0;
  223553. if ((! isDirectory()) && fullPath.containsChar (separator))
  223554. return getParentDirectory().hasWriteAccess();
  223555. return false;
  223556. }
  223557. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  223558. {
  223559. struct stat info;
  223560. const int res = stat (fullPath.toUTF8(), &info);
  223561. if (res != 0)
  223562. return false;
  223563. info.st_mode &= 0777; // Just permissions
  223564. if (shouldBeReadOnly)
  223565. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  223566. else
  223567. // Give everybody write permission?
  223568. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  223569. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  223570. }
  223571. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  223572. {
  223573. modificationTime = 0;
  223574. accessTime = 0;
  223575. creationTime = 0;
  223576. struct stat info;
  223577. const int res = stat (fullPath.toUTF8(), &info);
  223578. if (res == 0)
  223579. {
  223580. modificationTime = (int64) info.st_mtime * 1000;
  223581. accessTime = (int64) info.st_atime * 1000;
  223582. creationTime = (int64) info.st_ctime * 1000;
  223583. }
  223584. }
  223585. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  223586. {
  223587. struct utimbuf times;
  223588. times.actime = (time_t) (accessTime / 1000);
  223589. times.modtime = (time_t) (modificationTime / 1000);
  223590. return utime (fullPath.toUTF8(), &times) == 0;
  223591. }
  223592. bool File::deleteFile() const
  223593. {
  223594. if (! exists())
  223595. return true;
  223596. else if (isDirectory())
  223597. return rmdir (fullPath.toUTF8()) == 0;
  223598. else
  223599. return remove (fullPath.toUTF8()) == 0;
  223600. }
  223601. bool File::moveInternal (const File& dest) const
  223602. {
  223603. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  223604. return true;
  223605. if (hasWriteAccess() && copyInternal (dest))
  223606. {
  223607. if (deleteFile())
  223608. return true;
  223609. dest.deleteFile();
  223610. }
  223611. return false;
  223612. }
  223613. void File::createDirectoryInternal (const String& fileName) const
  223614. {
  223615. mkdir (fileName.toUTF8(), 0777);
  223616. }
  223617. void* juce_fileOpen (const File& file, bool forWriting)
  223618. {
  223619. int flags = O_RDONLY;
  223620. if (forWriting)
  223621. {
  223622. if (file.exists())
  223623. {
  223624. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  223625. if (f != -1)
  223626. lseek (f, 0, SEEK_END);
  223627. return (void*) f;
  223628. }
  223629. else
  223630. {
  223631. flags = O_RDWR + O_CREAT;
  223632. }
  223633. }
  223634. return (void*) open (file.getFullPathName().toUTF8(), flags, 00644);
  223635. }
  223636. void juce_fileClose (void* handle)
  223637. {
  223638. if (handle != 0)
  223639. close ((int) (pointer_sized_int) handle);
  223640. }
  223641. int juce_fileRead (void* handle, void* buffer, int size)
  223642. {
  223643. if (handle != 0)
  223644. return jmax (0, (int) read ((int) (pointer_sized_int) handle, buffer, size));
  223645. return 0;
  223646. }
  223647. int juce_fileWrite (void* handle, const void* buffer, int size)
  223648. {
  223649. if (handle != 0)
  223650. return (int) write ((int) (pointer_sized_int) handle, buffer, size);
  223651. return 0;
  223652. }
  223653. int64 juce_fileSetPosition (void* handle, int64 pos)
  223654. {
  223655. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  223656. return pos;
  223657. return -1;
  223658. }
  223659. int64 FileOutputStream::getPositionInternal() const
  223660. {
  223661. if (fileHandle != 0)
  223662. return lseek ((int) (pointer_sized_int) fileHandle, 0, SEEK_CUR);
  223663. return -1;
  223664. }
  223665. void FileOutputStream::flushInternal()
  223666. {
  223667. if (fileHandle != 0)
  223668. fsync ((int) (pointer_sized_int) fileHandle);
  223669. }
  223670. const File juce_getExecutableFile()
  223671. {
  223672. Dl_info exeInfo;
  223673. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  223674. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  223675. }
  223676. // if this file doesn't exist, find a parent of it that does..
  223677. static bool juce_doStatFS (File f, struct statfs& result)
  223678. {
  223679. for (int i = 5; --i >= 0;)
  223680. {
  223681. if (f.exists())
  223682. break;
  223683. f = f.getParentDirectory();
  223684. }
  223685. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  223686. }
  223687. int64 File::getBytesFreeOnVolume() const
  223688. {
  223689. struct statfs buf;
  223690. if (juce_doStatFS (*this, buf))
  223691. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  223692. return 0;
  223693. }
  223694. int64 File::getVolumeTotalSize() const
  223695. {
  223696. struct statfs buf;
  223697. if (juce_doStatFS (*this, buf))
  223698. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  223699. return 0;
  223700. }
  223701. const String File::getVolumeLabel() const
  223702. {
  223703. #if JUCE_MAC
  223704. struct VolAttrBuf
  223705. {
  223706. u_int32_t length;
  223707. attrreference_t mountPointRef;
  223708. char mountPointSpace [MAXPATHLEN];
  223709. } attrBuf;
  223710. struct attrlist attrList;
  223711. zerostruct (attrList);
  223712. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  223713. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  223714. File f (*this);
  223715. for (;;)
  223716. {
  223717. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  223718. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  223719. (int) attrBuf.mountPointRef.attr_length);
  223720. const File parent (f.getParentDirectory());
  223721. if (f == parent)
  223722. break;
  223723. f = parent;
  223724. }
  223725. #endif
  223726. return String::empty;
  223727. }
  223728. int File::getVolumeSerialNumber() const
  223729. {
  223730. return 0; // xxx
  223731. }
  223732. void juce_runSystemCommand (const String& command)
  223733. {
  223734. int result = system (command.toUTF8());
  223735. (void) result;
  223736. }
  223737. const String juce_getOutputFromCommand (const String& command)
  223738. {
  223739. // slight bodge here, as we just pipe the output into a temp file and read it...
  223740. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  223741. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  223742. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  223743. String result (tempFile.loadFileAsString());
  223744. tempFile.deleteFile();
  223745. return result;
  223746. }
  223747. class InterProcessLock::Pimpl
  223748. {
  223749. public:
  223750. Pimpl (const String& name, const int timeOutMillisecs)
  223751. : handle (0), refCount (1)
  223752. {
  223753. #if JUCE_MAC
  223754. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  223755. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  223756. #else
  223757. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  223758. #endif
  223759. temp.create();
  223760. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  223761. if (handle != 0)
  223762. {
  223763. struct flock fl;
  223764. zerostruct (fl);
  223765. fl.l_whence = SEEK_SET;
  223766. fl.l_type = F_WRLCK;
  223767. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  223768. for (;;)
  223769. {
  223770. const int result = fcntl (handle, F_SETLK, &fl);
  223771. if (result >= 0)
  223772. return;
  223773. if (errno != EINTR)
  223774. {
  223775. if (timeOutMillisecs == 0
  223776. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  223777. break;
  223778. Thread::sleep (10);
  223779. }
  223780. }
  223781. }
  223782. closeFile();
  223783. }
  223784. ~Pimpl()
  223785. {
  223786. closeFile();
  223787. }
  223788. void closeFile()
  223789. {
  223790. if (handle != 0)
  223791. {
  223792. struct flock fl;
  223793. zerostruct (fl);
  223794. fl.l_whence = SEEK_SET;
  223795. fl.l_type = F_UNLCK;
  223796. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  223797. {}
  223798. close (handle);
  223799. handle = 0;
  223800. }
  223801. }
  223802. int handle, refCount;
  223803. };
  223804. InterProcessLock::InterProcessLock (const String& name_)
  223805. : name (name_)
  223806. {
  223807. }
  223808. InterProcessLock::~InterProcessLock()
  223809. {
  223810. }
  223811. bool InterProcessLock::enter (const int timeOutMillisecs)
  223812. {
  223813. const ScopedLock sl (lock);
  223814. if (pimpl == 0)
  223815. {
  223816. pimpl = new Pimpl (name, timeOutMillisecs);
  223817. if (pimpl->handle == 0)
  223818. pimpl = 0;
  223819. }
  223820. else
  223821. {
  223822. pimpl->refCount++;
  223823. }
  223824. return pimpl != 0;
  223825. }
  223826. void InterProcessLock::exit()
  223827. {
  223828. const ScopedLock sl (lock);
  223829. // Trying to release the lock too many times!
  223830. jassert (pimpl != 0);
  223831. if (pimpl != 0 && --(pimpl->refCount) == 0)
  223832. pimpl = 0;
  223833. }
  223834. /*** End of inlined file: juce_posix_SharedCode.h ***/
  223835. /*** Start of inlined file: juce_mac_Files.mm ***/
  223836. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223837. // compiled on its own).
  223838. #if JUCE_INCLUDED_FILE
  223839. /*
  223840. Note that a lot of methods that you'd expect to find in this file actually
  223841. live in juce_posix_SharedCode.h!
  223842. */
  223843. bool File::copyInternal (const File& dest) const
  223844. {
  223845. const ScopedAutoReleasePool pool;
  223846. NSFileManager* fm = [NSFileManager defaultManager];
  223847. return [fm fileExistsAtPath: juceStringToNS (fullPath)]
  223848. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  223849. && [fm copyItemAtPath: juceStringToNS (fullPath)
  223850. toPath: juceStringToNS (dest.getFullPathName())
  223851. error: nil];
  223852. #else
  223853. && [fm copyPath: juceStringToNS (fullPath)
  223854. toPath: juceStringToNS (dest.getFullPathName())
  223855. handler: nil];
  223856. #endif
  223857. }
  223858. void File::findFileSystemRoots (Array<File>& destArray)
  223859. {
  223860. destArray.add (File ("/"));
  223861. }
  223862. static bool isFileOnDriveType (const File& f, const char* const* types)
  223863. {
  223864. struct statfs buf;
  223865. if (juce_doStatFS (f, buf))
  223866. {
  223867. const String type (buf.f_fstypename);
  223868. while (*types != 0)
  223869. if (type.equalsIgnoreCase (*types++))
  223870. return true;
  223871. }
  223872. return false;
  223873. }
  223874. bool File::isOnCDRomDrive() const
  223875. {
  223876. const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  223877. return isFileOnDriveType (*this, cdTypes);
  223878. }
  223879. bool File::isOnHardDisk() const
  223880. {
  223881. const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  223882. return ! (isOnCDRomDrive() || isFileOnDriveType (*this, nonHDTypes));
  223883. }
  223884. bool File::isOnRemovableDrive() const
  223885. {
  223886. #if JUCE_IPHONE
  223887. return false; // xxx is this possible?
  223888. #else
  223889. const ScopedAutoReleasePool pool;
  223890. BOOL removable = false;
  223891. [[NSWorkspace sharedWorkspace]
  223892. getFileSystemInfoForPath: juceStringToNS (getFullPathName())
  223893. isRemovable: &removable
  223894. isWritable: nil
  223895. isUnmountable: nil
  223896. description: nil
  223897. type: nil];
  223898. return removable;
  223899. #endif
  223900. }
  223901. static bool juce_isHiddenFile (const String& path)
  223902. {
  223903. #if JUCE_IPHONE
  223904. return File (path).getFileName().startsWithChar ('.');
  223905. #else
  223906. FSRef ref;
  223907. if (! PlatformUtilities::makeFSRefFromPath (&ref, path))
  223908. return false;
  223909. FSCatalogInfo info;
  223910. FSGetCatalogInfo (&ref, kFSCatInfoNodeFlags | kFSCatInfoFinderInfo, &info, 0, 0, 0);
  223911. if ((info.nodeFlags & kFSNodeIsDirectoryBit) != 0)
  223912. return (((FolderInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  223913. return (((FileInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  223914. #endif
  223915. }
  223916. bool File::isHidden() const
  223917. {
  223918. return juce_isHiddenFile (getFullPathName());
  223919. }
  223920. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  223921. const File File::getSpecialLocation (const SpecialLocationType type)
  223922. {
  223923. const ScopedAutoReleasePool pool;
  223924. String resultPath;
  223925. switch (type)
  223926. {
  223927. case userHomeDirectory:
  223928. resultPath = nsStringToJuce (NSHomeDirectory());
  223929. break;
  223930. case userDocumentsDirectory:
  223931. resultPath = "~/Documents";
  223932. break;
  223933. case userDesktopDirectory:
  223934. resultPath = "~/Desktop";
  223935. break;
  223936. case userApplicationDataDirectory:
  223937. resultPath = "~/Library";
  223938. break;
  223939. case commonApplicationDataDirectory:
  223940. resultPath = "/Library";
  223941. break;
  223942. case globalApplicationsDirectory:
  223943. resultPath = "/Applications";
  223944. break;
  223945. case userMusicDirectory:
  223946. resultPath = "~/Music";
  223947. break;
  223948. case userMoviesDirectory:
  223949. resultPath = "~/Movies";
  223950. break;
  223951. case tempDirectory:
  223952. {
  223953. File tmp ("~/Library/Caches/" + juce_getExecutableFile().getFileNameWithoutExtension());
  223954. tmp.createDirectory();
  223955. return tmp.getFullPathName();
  223956. }
  223957. case invokedExecutableFile:
  223958. if (juce_Argv0 != 0)
  223959. return File (String::fromUTF8 (juce_Argv0));
  223960. // deliberate fall-through...
  223961. case currentExecutableFile:
  223962. return juce_getExecutableFile();
  223963. case currentApplicationFile:
  223964. {
  223965. const File exe (juce_getExecutableFile());
  223966. const File parent (exe.getParentDirectory());
  223967. return parent.getFullPathName().endsWithIgnoreCase ("Contents/MacOS")
  223968. ? parent.getParentDirectory().getParentDirectory()
  223969. : exe;
  223970. }
  223971. default:
  223972. jassertfalse; // unknown type?
  223973. break;
  223974. }
  223975. if (resultPath.isNotEmpty())
  223976. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  223977. return File::nonexistent;
  223978. }
  223979. const String File::getVersion() const
  223980. {
  223981. const ScopedAutoReleasePool pool;
  223982. String result;
  223983. NSBundle* bundle = [NSBundle bundleWithPath: juceStringToNS (getFullPathName())];
  223984. if (bundle != 0)
  223985. {
  223986. NSDictionary* info = [bundle infoDictionary];
  223987. if (info != 0)
  223988. {
  223989. NSString* name = [info valueForKey: @"CFBundleShortVersionString"];
  223990. if (name != nil)
  223991. result = nsStringToJuce (name);
  223992. }
  223993. }
  223994. return result;
  223995. }
  223996. const File File::getLinkedTarget() const
  223997. {
  223998. #if JUCE_IPHONE || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
  223999. NSString* dest = [[NSFileManager defaultManager] destinationOfSymbolicLinkAtPath: juceStringToNS (getFullPathName()) error: nil];
  224000. #else
  224001. NSString* dest = [[NSFileManager defaultManager] pathContentOfSymbolicLinkAtPath: juceStringToNS (getFullPathName())];
  224002. #endif
  224003. if (dest != nil)
  224004. return File (nsStringToJuce (dest));
  224005. return *this;
  224006. }
  224007. bool File::moveToTrash() const
  224008. {
  224009. if (! exists())
  224010. return true;
  224011. #if JUCE_IPHONE
  224012. return deleteFile(); //xxx is there a trashcan on the iPhone?
  224013. #else
  224014. const ScopedAutoReleasePool pool;
  224015. NSString* p = juceStringToNS (getFullPathName());
  224016. return [[NSWorkspace sharedWorkspace]
  224017. performFileOperation: NSWorkspaceRecycleOperation
  224018. source: [p stringByDeletingLastPathComponent]
  224019. destination: @""
  224020. files: [NSArray arrayWithObject: [p lastPathComponent]]
  224021. tag: nil ];
  224022. #endif
  224023. }
  224024. class DirectoryIterator::NativeIterator::Pimpl
  224025. {
  224026. public:
  224027. Pimpl (const File& directory, const String& wildCard_)
  224028. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  224029. wildCard (wildCard_),
  224030. enumerator (0)
  224031. {
  224032. ScopedAutoReleasePool pool;
  224033. enumerator = [[[NSFileManager defaultManager] enumeratorAtPath: juceStringToNS (directory.getFullPathName())] retain];
  224034. wildcardUTF8 = wildCard.toUTF8();
  224035. }
  224036. ~Pimpl()
  224037. {
  224038. [enumerator release];
  224039. }
  224040. bool next (String& filenameFound,
  224041. bool* const isDir, bool* const isHidden, int64* const fileSize,
  224042. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  224043. {
  224044. ScopedAutoReleasePool pool;
  224045. for (;;)
  224046. {
  224047. NSString* file;
  224048. if (enumerator == 0 || (file = [enumerator nextObject]) == 0)
  224049. return false;
  224050. [enumerator skipDescendents];
  224051. filenameFound = nsStringToJuce (file);
  224052. if (fnmatch (wildcardUTF8, filenameFound.toUTF8(), FNM_CASEFOLD) != 0)
  224053. continue;
  224054. const String path (parentDir + filenameFound);
  224055. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  224056. {
  224057. struct stat info;
  224058. const bool statOk = juce_stat (path, info);
  224059. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  224060. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  224061. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  224062. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  224063. }
  224064. if (isHidden != 0)
  224065. *isHidden = juce_isHiddenFile (path);
  224066. if (isReadOnly != 0)
  224067. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  224068. return true;
  224069. }
  224070. }
  224071. private:
  224072. String parentDir, wildCard;
  224073. const char* wildcardUTF8;
  224074. NSDirectoryEnumerator* enumerator;
  224075. Pimpl (const Pimpl&);
  224076. Pimpl& operator= (const Pimpl&);
  224077. };
  224078. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  224079. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  224080. {
  224081. }
  224082. DirectoryIterator::NativeIterator::~NativeIterator()
  224083. {
  224084. }
  224085. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  224086. bool* const isDir, bool* const isHidden, int64* const fileSize,
  224087. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  224088. {
  224089. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  224090. }
  224091. bool juce_launchExecutable (const String& pathAndArguments)
  224092. {
  224093. const char* const argv[4] = { "/bin/sh", "-c", pathAndArguments.toUTF8(), 0 };
  224094. const int cpid = fork();
  224095. if (cpid == 0)
  224096. {
  224097. // Child process
  224098. if (execve (argv[0], (char**) argv, 0) < 0)
  224099. exit (0);
  224100. }
  224101. else
  224102. {
  224103. if (cpid < 0)
  224104. return false;
  224105. }
  224106. return true;
  224107. }
  224108. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  224109. {
  224110. #if JUCE_IPHONE
  224111. return [[UIApplication sharedApplication] openURL: [NSURL fileURLWithPath: juceStringToNS (fileName)]];
  224112. #else
  224113. const ScopedAutoReleasePool pool;
  224114. if (parameters.isEmpty())
  224115. {
  224116. return [[NSWorkspace sharedWorkspace] openFile: juceStringToNS (fileName)]
  224117. || [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: juceStringToNS (fileName)]];
  224118. }
  224119. bool ok = false;
  224120. FSRef ref;
  224121. if (PlatformUtilities::makeFSRefFromPath (&ref, fileName))
  224122. {
  224123. if (PlatformUtilities::isBundle (fileName))
  224124. {
  224125. NSMutableArray* urls = [NSMutableArray array];
  224126. StringArray docs;
  224127. docs.addTokens (parameters, true);
  224128. for (int i = 0; i < docs.size(); ++i)
  224129. [urls addObject: juceStringToNS (docs[i])];
  224130. ok = [[NSWorkspace sharedWorkspace] openURLs: urls
  224131. withAppBundleIdentifier: [[NSBundle bundleWithPath: juceStringToNS (fileName)] bundleIdentifier]
  224132. options: 0
  224133. additionalEventParamDescriptor: nil
  224134. launchIdentifiers: nil];
  224135. }
  224136. else
  224137. {
  224138. ok = juce_launchExecutable ("\"" + fileName + "\" " + parameters);
  224139. }
  224140. }
  224141. return ok;
  224142. #endif
  224143. }
  224144. void File::revealToUser() const
  224145. {
  224146. #if ! JUCE_IPHONE
  224147. if (exists())
  224148. [[NSWorkspace sharedWorkspace] selectFile: juceStringToNS (getFullPathName()) inFileViewerRootedAtPath: @""];
  224149. else if (getParentDirectory().exists())
  224150. getParentDirectory().revealToUser();
  224151. #endif
  224152. }
  224153. #if ! JUCE_IPHONE
  224154. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  224155. {
  224156. return FSPathMakeRef ((const UInt8*) path.toUTF8(), destFSRef, 0) == noErr;
  224157. }
  224158. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  224159. {
  224160. char path [2048];
  224161. zerostruct (path);
  224162. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  224163. return PlatformUtilities::convertToPrecomposedUnicode (String::fromUTF8 (path));
  224164. return String::empty;
  224165. }
  224166. #endif
  224167. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  224168. {
  224169. const ScopedAutoReleasePool pool;
  224170. #if JUCE_IPHONE || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
  224171. NSDictionary* fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath: juceStringToNS (filename) error: nil];
  224172. #else
  224173. NSDictionary* fileDict = [[NSFileManager defaultManager] fileAttributesAtPath: juceStringToNS (filename) traverseLink: NO];
  224174. #endif
  224175. //return (OSType) [fileDict objectForKey: NSFileHFSTypeCode];
  224176. return [fileDict fileHFSTypeCode];
  224177. }
  224178. bool PlatformUtilities::isBundle (const String& filename)
  224179. {
  224180. #if JUCE_IPHONE
  224181. return false; // xxx can't find a sensible way to do this without trying to open the bundle..
  224182. #else
  224183. const ScopedAutoReleasePool pool;
  224184. return [[NSWorkspace sharedWorkspace] isFilePackageAtPath: juceStringToNS (filename)];
  224185. #endif
  224186. }
  224187. #endif
  224188. /*** End of inlined file: juce_mac_Files.mm ***/
  224189. #if JUCE_IPHONE
  224190. /*** Start of inlined file: juce_iphone_MiscUtilities.mm ***/
  224191. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224192. // compiled on its own).
  224193. #if JUCE_INCLUDED_FILE
  224194. static JUCEApplication* juce_intialisingApp;
  224195. END_JUCE_NAMESPACE
  224196. @interface JuceAppStartupDelegate : NSObject <UIApplicationDelegate>
  224197. {
  224198. }
  224199. - (void) applicationDidFinishLaunching: (UIApplication*) application;
  224200. - (void) applicationWillResignActive: (UIApplication*) application;
  224201. @end
  224202. @implementation JuceAppStartupDelegate
  224203. - (void) applicationDidFinishLaunching: (UIApplication*) application
  224204. {
  224205. String dummy;
  224206. if (! juce_intialisingApp->initialiseApp (dummy))
  224207. exit (0);
  224208. }
  224209. - (void) applicationWillResignActive: (UIApplication*) application
  224210. {
  224211. JUCEApplication::shutdownAppAndClearUp();
  224212. }
  224213. @end
  224214. BEGIN_JUCE_NAMESPACE
  224215. int juce_IPhoneMain (int argc, const char* argv[], JUCEApplication* app)
  224216. {
  224217. juce_intialisingApp = app;
  224218. return UIApplicationMain (argc, const_cast<char**> (argv), nil, @"JuceAppStartupDelegate");
  224219. }
  224220. ScopedAutoReleasePool::ScopedAutoReleasePool()
  224221. {
  224222. pool = [[NSAutoreleasePool alloc] init];
  224223. }
  224224. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  224225. {
  224226. [((NSAutoreleasePool*) pool) release];
  224227. }
  224228. void PlatformUtilities::beep()
  224229. {
  224230. //xxx
  224231. //AudioServicesPlaySystemSound ();
  224232. }
  224233. void PlatformUtilities::addItemToDock (const File& file)
  224234. {
  224235. }
  224236. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  224237. END_JUCE_NAMESPACE
  224238. @interface JuceAlertBoxDelegate : NSObject
  224239. {
  224240. @public
  224241. bool clickedOk;
  224242. }
  224243. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex;
  224244. @end
  224245. @implementation JuceAlertBoxDelegate
  224246. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex
  224247. {
  224248. clickedOk = (buttonIndex == 0);
  224249. alertView.hidden = true;
  224250. }
  224251. @end
  224252. BEGIN_JUCE_NAMESPACE
  224253. // (This function is used directly by other bits of code)
  224254. bool juce_iPhoneShowModalAlert (const String& title,
  224255. const String& bodyText,
  224256. NSString* okButtonText,
  224257. NSString* cancelButtonText)
  224258. {
  224259. const ScopedAutoReleasePool pool;
  224260. JuceAlertBoxDelegate* callback = [[JuceAlertBoxDelegate alloc] init];
  224261. UIAlertView* alert = [[UIAlertView alloc] initWithTitle: juceStringToNS (title)
  224262. message: juceStringToNS (bodyText)
  224263. delegate: callback
  224264. cancelButtonTitle: okButtonText
  224265. otherButtonTitles: cancelButtonText, nil];
  224266. [alert retain];
  224267. [alert show];
  224268. while (! alert.hidden && alert.superview != nil)
  224269. [[NSRunLoop mainRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  224270. const bool result = callback->clickedOk;
  224271. [alert release];
  224272. [callback release];
  224273. return result;
  224274. }
  224275. bool AlertWindow::showNativeDialogBox (const String& title,
  224276. const String& bodyText,
  224277. bool isOkCancel)
  224278. {
  224279. return juce_iPhoneShowModalAlert (title, bodyText,
  224280. @"OK",
  224281. isOkCancel ? @"Cancel" : nil);
  224282. }
  224283. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  224284. {
  224285. jassertfalse; // no such thing on the iphone!
  224286. return false;
  224287. }
  224288. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  224289. {
  224290. jassertfalse; // no such thing on the iphone!
  224291. return false;
  224292. }
  224293. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  224294. {
  224295. [[UIApplication sharedApplication] setIdleTimerDisabled: ! isEnabled];
  224296. }
  224297. bool Desktop::isScreenSaverEnabled()
  224298. {
  224299. return ! [[UIApplication sharedApplication] isIdleTimerDisabled];
  224300. }
  224301. void juce_updateMultiMonitorInfo (Array <Rectangle <int> >& monitorCoords, const bool clipToWorkArea)
  224302. {
  224303. const ScopedAutoReleasePool pool;
  224304. monitorCoords.clear();
  224305. CGRect r = clipToWorkArea ? [[UIScreen mainScreen] applicationFrame]
  224306. : [[UIScreen mainScreen] bounds];
  224307. monitorCoords.add (Rectangle<int> ((int) r.origin.x,
  224308. (int) r.origin.y,
  224309. (int) r.size.width,
  224310. (int) r.size.height));
  224311. }
  224312. #endif
  224313. #endif
  224314. /*** End of inlined file: juce_iphone_MiscUtilities.mm ***/
  224315. #else
  224316. /*** Start of inlined file: juce_mac_MiscUtilities.mm ***/
  224317. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224318. // compiled on its own).
  224319. #if JUCE_INCLUDED_FILE
  224320. ScopedAutoReleasePool::ScopedAutoReleasePool()
  224321. {
  224322. pool = [[NSAutoreleasePool alloc] init];
  224323. }
  224324. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  224325. {
  224326. [((NSAutoreleasePool*) pool) release];
  224327. }
  224328. void PlatformUtilities::beep()
  224329. {
  224330. NSBeep();
  224331. }
  224332. void PlatformUtilities::addItemToDock (const File& file)
  224333. {
  224334. // check that it's not already there...
  224335. if (! juce_getOutputFromCommand ("defaults read com.apple.dock persistent-apps")
  224336. .containsIgnoreCase (file.getFullPathName()))
  224337. {
  224338. 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>"
  224339. + file.getFullPathName() + "</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>\"");
  224340. juce_runSystemCommand ("osascript -e \"tell application \\\"Dock\\\" to quit\"");
  224341. }
  224342. }
  224343. int PlatformUtilities::getOSXMinorVersionNumber()
  224344. {
  224345. SInt32 versionMinor = 0;
  224346. OSErr err = Gestalt (gestaltSystemVersionMinor, &versionMinor);
  224347. (void) err;
  224348. jassert (err == noErr);
  224349. return (int) versionMinor;
  224350. }
  224351. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  224352. bool AlertWindow::showNativeDialogBox (const String& title,
  224353. const String& bodyText,
  224354. bool isOkCancel)
  224355. {
  224356. const ScopedAutoReleasePool pool;
  224357. return NSRunAlertPanel (juceStringToNS (title),
  224358. juceStringToNS (bodyText),
  224359. @"Ok",
  224360. isOkCancel ? @"Cancel" : nil,
  224361. nil) == NSAlertDefaultReturn;
  224362. }
  224363. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool /*canMoveFiles*/)
  224364. {
  224365. if (files.size() == 0)
  224366. return false;
  224367. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0);
  224368. if (draggingSource == 0)
  224369. {
  224370. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  224371. return false;
  224372. }
  224373. Component* sourceComp = draggingSource->getComponentUnderMouse();
  224374. if (sourceComp == 0)
  224375. {
  224376. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  224377. return false;
  224378. }
  224379. const ScopedAutoReleasePool pool;
  224380. NSView* view = (NSView*) sourceComp->getWindowHandle();
  224381. if (view == 0)
  224382. return false;
  224383. NSPasteboard* pboard = [NSPasteboard pasteboardWithName: NSDragPboard];
  224384. [pboard declareTypes: [NSArray arrayWithObject: NSFilenamesPboardType]
  224385. owner: nil];
  224386. NSMutableArray* filesArray = [NSMutableArray arrayWithCapacity: 4];
  224387. for (int i = 0; i < files.size(); ++i)
  224388. [filesArray addObject: juceStringToNS (files[i])];
  224389. [pboard setPropertyList: filesArray
  224390. forType: NSFilenamesPboardType];
  224391. NSPoint dragPosition = [view convertPoint: [[[view window] currentEvent] locationInWindow]
  224392. fromView: nil];
  224393. dragPosition.x -= 16;
  224394. dragPosition.y -= 16;
  224395. [view dragImage: [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (files[0])]
  224396. at: dragPosition
  224397. offset: NSMakeSize (0, 0)
  224398. event: [[view window] currentEvent]
  224399. pasteboard: pboard
  224400. source: view
  224401. slideBack: YES];
  224402. return true;
  224403. }
  224404. bool DragAndDropContainer::performExternalDragDropOfText (const String& /*text*/)
  224405. {
  224406. jassertfalse; // not implemented!
  224407. return false;
  224408. }
  224409. bool Desktop::canUseSemiTransparentWindows() throw()
  224410. {
  224411. return true;
  224412. }
  224413. const Point<int> Desktop::getMousePosition()
  224414. {
  224415. const ScopedAutoReleasePool pool;
  224416. const NSPoint p ([NSEvent mouseLocation]);
  224417. return Point<int> (roundToInt (p.x), roundToInt ([[[NSScreen screens] objectAtIndex: 0] frame].size.height - p.y));
  224418. }
  224419. void Desktop::setMousePosition (const Point<int>& newPosition)
  224420. {
  224421. // this rubbish needs to be done around the warp call, to avoid causing a
  224422. // bizarre glitch..
  224423. CGAssociateMouseAndMouseCursorPosition (false);
  224424. CGWarpMouseCursorPosition (CGPointMake (newPosition.getX(), newPosition.getY()));
  224425. CGAssociateMouseAndMouseCursorPosition (true);
  224426. }
  224427. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  224428. class ScreenSaverDefeater : public Timer,
  224429. public DeletedAtShutdown
  224430. {
  224431. public:
  224432. ScreenSaverDefeater()
  224433. {
  224434. startTimer (10000);
  224435. timerCallback();
  224436. }
  224437. ~ScreenSaverDefeater() {}
  224438. void timerCallback()
  224439. {
  224440. if (Process::isForegroundProcess())
  224441. UpdateSystemActivity (UsrActivity);
  224442. }
  224443. };
  224444. static ScreenSaverDefeater* screenSaverDefeater = 0;
  224445. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  224446. {
  224447. if (isEnabled)
  224448. deleteAndZero (screenSaverDefeater);
  224449. else if (screenSaverDefeater == 0)
  224450. screenSaverDefeater = new ScreenSaverDefeater();
  224451. }
  224452. bool Desktop::isScreenSaverEnabled()
  224453. {
  224454. return screenSaverDefeater == 0;
  224455. }
  224456. #else
  224457. static IOPMAssertionID screenSaverDisablerID = 0;
  224458. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  224459. {
  224460. if (isEnabled)
  224461. {
  224462. if (screenSaverDisablerID != 0)
  224463. {
  224464. IOPMAssertionRelease (screenSaverDisablerID);
  224465. screenSaverDisablerID = 0;
  224466. }
  224467. }
  224468. else
  224469. {
  224470. if (screenSaverDisablerID == 0)
  224471. {
  224472. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  224473. IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  224474. CFSTR ("Juce"), &screenSaverDisablerID);
  224475. #else
  224476. IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  224477. &screenSaverDisablerID);
  224478. #endif
  224479. }
  224480. }
  224481. }
  224482. bool Desktop::isScreenSaverEnabled()
  224483. {
  224484. return screenSaverDisablerID == 0;
  224485. }
  224486. #endif
  224487. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  224488. {
  224489. const ScopedAutoReleasePool pool;
  224490. monitorCoords.clear();
  224491. NSArray* screens = [NSScreen screens];
  224492. const CGFloat mainScreenBottom = [[[NSScreen screens] objectAtIndex: 0] frame].size.height;
  224493. for (unsigned int i = 0; i < [screens count]; ++i)
  224494. {
  224495. NSScreen* s = (NSScreen*) [screens objectAtIndex: i];
  224496. NSRect r = clipToWorkArea ? [s visibleFrame]
  224497. : [s frame];
  224498. monitorCoords.add (Rectangle<int> ((int) r.origin.x,
  224499. (int) (mainScreenBottom - (r.origin.y + r.size.height)),
  224500. (int) r.size.width,
  224501. (int) r.size.height));
  224502. }
  224503. jassert (monitorCoords.size() > 0);
  224504. }
  224505. #endif
  224506. #endif
  224507. /*** End of inlined file: juce_mac_MiscUtilities.mm ***/
  224508. #endif
  224509. /*** Start of inlined file: juce_mac_Debugging.mm ***/
  224510. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224511. // compiled on its own).
  224512. #if JUCE_INCLUDED_FILE
  224513. void Logger::outputDebugString (const String& text)
  224514. {
  224515. std::cerr << text << std::endl;
  224516. }
  224517. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  224518. {
  224519. static char testResult = 0;
  224520. if (testResult == 0)
  224521. {
  224522. struct kinfo_proc info;
  224523. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  224524. size_t sz = sizeof (info);
  224525. sysctl (m, 4, &info, &sz, 0, 0);
  224526. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  224527. }
  224528. return testResult > 0;
  224529. }
  224530. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  224531. {
  224532. return juce_isRunningUnderDebugger();
  224533. }
  224534. #endif
  224535. /*** End of inlined file: juce_mac_Debugging.mm ***/
  224536. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  224537. #if JUCE_IPHONE
  224538. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  224539. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224540. // compiled on its own).
  224541. #if JUCE_INCLUDED_FILE
  224542. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  224543. #define SUPPORT_10_4_FONTS 1
  224544. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  224545. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  224546. #define SUPPORT_ONLY_10_4_FONTS 1
  224547. #endif
  224548. END_JUCE_NAMESPACE
  224549. @interface NSFont (PrivateHack)
  224550. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  224551. @end
  224552. BEGIN_JUCE_NAMESPACE
  224553. #endif
  224554. class MacTypeface : public Typeface
  224555. {
  224556. public:
  224557. MacTypeface (const Font& font)
  224558. : Typeface (font.getTypefaceName())
  224559. {
  224560. const ScopedAutoReleasePool pool;
  224561. renderingTransform = CGAffineTransformIdentity;
  224562. bool needsItalicTransform = false;
  224563. #if JUCE_IPHONE
  224564. NSString* fontName = juceStringToNS (font.getTypefaceName());
  224565. if (font.isItalic() || font.isBold())
  224566. {
  224567. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  224568. for (NSString* i in familyFonts)
  224569. {
  224570. const String fn (nsStringToJuce (i));
  224571. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  224572. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  224573. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  224574. || afterDash.containsIgnoreCase ("italic")
  224575. || fn.endsWithIgnoreCase ("oblique")
  224576. || fn.endsWithIgnoreCase ("italic");
  224577. if (probablyBold == font.isBold()
  224578. && probablyItalic == font.isItalic())
  224579. {
  224580. fontName = i;
  224581. needsItalicTransform = false;
  224582. break;
  224583. }
  224584. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  224585. {
  224586. fontName = i;
  224587. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  224588. }
  224589. }
  224590. if (needsItalicTransform)
  224591. renderingTransform.c = 0.15f;
  224592. }
  224593. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  224594. const int ascender = abs (CGFontGetAscent (fontRef));
  224595. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  224596. ascent = ascender / totalHeight;
  224597. unitsToHeightScaleFactor = 1.0f / totalHeight;
  224598. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  224599. #else
  224600. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  224601. if (font.isItalic())
  224602. {
  224603. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  224604. toHaveTrait: NSItalicFontMask];
  224605. if (newFont == nsFont)
  224606. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  224607. nsFont = newFont;
  224608. }
  224609. if (font.isBold())
  224610. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  224611. [nsFont retain];
  224612. ascent = std::abs ((float) [nsFont ascender]);
  224613. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  224614. ascent /= totalSize;
  224615. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  224616. if (needsItalicTransform)
  224617. {
  224618. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  224619. renderingTransform.c = 0.15f;
  224620. }
  224621. #if SUPPORT_ONLY_10_4_FONTS
  224622. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  224623. if (atsFont == 0)
  224624. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  224625. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  224626. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  224627. unitsToHeightScaleFactor = 1.0f / totalHeight;
  224628. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  224629. #else
  224630. #if SUPPORT_10_4_FONTS
  224631. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  224632. {
  224633. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  224634. if (atsFont == 0)
  224635. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  224636. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  224637. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  224638. unitsToHeightScaleFactor = 1.0f / totalHeight;
  224639. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  224640. }
  224641. else
  224642. #endif
  224643. {
  224644. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  224645. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  224646. unitsToHeightScaleFactor = 1.0f / totalHeight;
  224647. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  224648. }
  224649. #endif
  224650. #endif
  224651. }
  224652. ~MacTypeface()
  224653. {
  224654. #if ! JUCE_IPHONE
  224655. [nsFont release];
  224656. #endif
  224657. if (fontRef != 0)
  224658. CGFontRelease (fontRef);
  224659. }
  224660. float getAscent() const
  224661. {
  224662. return ascent;
  224663. }
  224664. float getDescent() const
  224665. {
  224666. return 1.0f - ascent;
  224667. }
  224668. float getStringWidth (const String& text)
  224669. {
  224670. if (fontRef == 0 || text.isEmpty())
  224671. return 0;
  224672. const int length = text.length();
  224673. HeapBlock <CGGlyph> glyphs;
  224674. createGlyphsForString (text, length, glyphs);
  224675. float x = 0;
  224676. #if SUPPORT_ONLY_10_4_FONTS
  224677. HeapBlock <NSSize> advances (length);
  224678. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  224679. for (int i = 0; i < length; ++i)
  224680. x += advances[i].width;
  224681. #else
  224682. #if SUPPORT_10_4_FONTS
  224683. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  224684. {
  224685. HeapBlock <NSSize> advances (length);
  224686. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  224687. for (int i = 0; i < length; ++i)
  224688. x += advances[i].width;
  224689. }
  224690. else
  224691. #endif
  224692. {
  224693. HeapBlock <int> advances (length);
  224694. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  224695. for (int i = 0; i < length; ++i)
  224696. x += advances[i];
  224697. }
  224698. #endif
  224699. return x * unitsToHeightScaleFactor;
  224700. }
  224701. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  224702. {
  224703. xOffsets.add (0);
  224704. if (fontRef == 0 || text.isEmpty())
  224705. return;
  224706. const int length = text.length();
  224707. HeapBlock <CGGlyph> glyphs;
  224708. createGlyphsForString (text, length, glyphs);
  224709. #if SUPPORT_ONLY_10_4_FONTS
  224710. HeapBlock <NSSize> advances (length);
  224711. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  224712. int x = 0;
  224713. for (int i = 0; i < length; ++i)
  224714. {
  224715. x += advances[i].width;
  224716. xOffsets.add (x * unitsToHeightScaleFactor);
  224717. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  224718. }
  224719. #else
  224720. #if SUPPORT_10_4_FONTS
  224721. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  224722. {
  224723. HeapBlock <NSSize> advances (length);
  224724. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  224725. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  224726. float x = 0;
  224727. for (int i = 0; i < length; ++i)
  224728. {
  224729. x += advances[i].width;
  224730. xOffsets.add (x * unitsToHeightScaleFactor);
  224731. resultGlyphs.add (nsGlyphs[i]);
  224732. }
  224733. }
  224734. else
  224735. #endif
  224736. {
  224737. HeapBlock <int> advances (length);
  224738. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  224739. {
  224740. int x = 0;
  224741. for (int i = 0; i < length; ++i)
  224742. {
  224743. x += advances [i];
  224744. xOffsets.add (x * unitsToHeightScaleFactor);
  224745. resultGlyphs.add (glyphs[i]);
  224746. }
  224747. }
  224748. }
  224749. #endif
  224750. }
  224751. bool getOutlineForGlyph (int glyphNumber, Path& path)
  224752. {
  224753. #if JUCE_IPHONE
  224754. return false;
  224755. #else
  224756. if (nsFont == 0)
  224757. return false;
  224758. // we might need to apply a transform to the path, so it mustn't have anything else in it
  224759. jassert (path.isEmpty());
  224760. const ScopedAutoReleasePool pool;
  224761. NSBezierPath* bez = [NSBezierPath bezierPath];
  224762. [bez moveToPoint: NSMakePoint (0, 0)];
  224763. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  224764. inFont: nsFont];
  224765. for (int i = 0; i < [bez elementCount]; ++i)
  224766. {
  224767. NSPoint p[3];
  224768. switch ([bez elementAtIndex: i associatedPoints: p])
  224769. {
  224770. case NSMoveToBezierPathElement:
  224771. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  224772. break;
  224773. case NSLineToBezierPathElement:
  224774. path.lineTo ((float) p[0].x, (float) -p[0].y);
  224775. break;
  224776. case NSCurveToBezierPathElement:
  224777. 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);
  224778. break;
  224779. case NSClosePathBezierPathElement:
  224780. path.closeSubPath();
  224781. break;
  224782. default:
  224783. jassertfalse;
  224784. break;
  224785. }
  224786. }
  224787. path.applyTransform (pathTransform);
  224788. return true;
  224789. #endif
  224790. }
  224791. juce_UseDebuggingNewOperator
  224792. CGFontRef fontRef;
  224793. float fontHeightToCGSizeFactor;
  224794. CGAffineTransform renderingTransform;
  224795. private:
  224796. float ascent, unitsToHeightScaleFactor;
  224797. #if JUCE_IPHONE
  224798. #else
  224799. NSFont* nsFont;
  224800. AffineTransform pathTransform;
  224801. #endif
  224802. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  224803. {
  224804. #if SUPPORT_10_4_FONTS
  224805. #if ! SUPPORT_ONLY_10_4_FONTS
  224806. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  224807. #endif
  224808. {
  224809. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  224810. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  224811. for (int i = 0; i < length; ++i)
  224812. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  224813. return;
  224814. }
  224815. #endif
  224816. #if ! SUPPORT_ONLY_10_4_FONTS
  224817. if (charToGlyphMapper == 0)
  224818. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  224819. glyphs.malloc (length);
  224820. for (int i = 0; i < length; ++i)
  224821. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  224822. #endif
  224823. }
  224824. #if ! SUPPORT_ONLY_10_4_FONTS
  224825. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  224826. class CharToGlyphMapper
  224827. {
  224828. public:
  224829. CharToGlyphMapper (CGFontRef fontRef)
  224830. : segCount (0), endCode (0), startCode (0), idDelta (0),
  224831. idRangeOffset (0), glyphIndexes (0)
  224832. {
  224833. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  224834. if (cmapTable != 0)
  224835. {
  224836. const int numSubtables = getValue16 (cmapTable, 2);
  224837. for (int i = 0; i < numSubtables; ++i)
  224838. {
  224839. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  224840. {
  224841. const int offset = getValue32 (cmapTable, i * 8 + 8);
  224842. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  224843. {
  224844. const int length = getValue16 (cmapTable, offset + 2);
  224845. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  224846. segCount = segCountX2 / 2;
  224847. const int endCodeOffset = offset + 14;
  224848. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  224849. const int idDeltaOffset = startCodeOffset + segCountX2;
  224850. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  224851. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  224852. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  224853. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  224854. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  224855. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  224856. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  224857. }
  224858. break;
  224859. }
  224860. }
  224861. CFRelease (cmapTable);
  224862. }
  224863. }
  224864. ~CharToGlyphMapper()
  224865. {
  224866. if (endCode != 0)
  224867. {
  224868. CFRelease (endCode);
  224869. CFRelease (startCode);
  224870. CFRelease (idDelta);
  224871. CFRelease (idRangeOffset);
  224872. CFRelease (glyphIndexes);
  224873. }
  224874. }
  224875. int getGlyphForCharacter (const juce_wchar c) const
  224876. {
  224877. for (int i = 0; i < segCount; ++i)
  224878. {
  224879. if (getValue16 (endCode, i * 2) >= c)
  224880. {
  224881. const int start = getValue16 (startCode, i * 2);
  224882. if (start > c)
  224883. break;
  224884. const int delta = getValue16 (idDelta, i * 2);
  224885. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  224886. if (rangeOffset == 0)
  224887. return delta + c;
  224888. else
  224889. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  224890. }
  224891. }
  224892. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  224893. return jmax (-1, c - 29);
  224894. }
  224895. private:
  224896. int segCount;
  224897. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  224898. static uint16 getValue16 (CFDataRef data, const int index)
  224899. {
  224900. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  224901. }
  224902. static uint32 getValue32 (CFDataRef data, const int index)
  224903. {
  224904. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  224905. }
  224906. };
  224907. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  224908. #endif
  224909. MacTypeface (const MacTypeface&);
  224910. MacTypeface& operator= (const MacTypeface&);
  224911. };
  224912. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  224913. {
  224914. return new MacTypeface (font);
  224915. }
  224916. const StringArray Font::findAllTypefaceNames()
  224917. {
  224918. StringArray names;
  224919. const ScopedAutoReleasePool pool;
  224920. #if JUCE_IPHONE
  224921. NSArray* fonts = [UIFont familyNames];
  224922. #else
  224923. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  224924. #endif
  224925. for (unsigned int i = 0; i < [fonts count]; ++i)
  224926. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  224927. names.sort (true);
  224928. return names;
  224929. }
  224930. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  224931. {
  224932. #if JUCE_IPHONE
  224933. defaultSans = "Helvetica";
  224934. defaultSerif = "Times New Roman";
  224935. defaultFixed = "Courier New";
  224936. #else
  224937. defaultSans = "Lucida Grande";
  224938. defaultSerif = "Times New Roman";
  224939. defaultFixed = "Monaco";
  224940. #endif
  224941. }
  224942. #endif
  224943. /*** End of inlined file: juce_mac_Fonts.mm ***/
  224944. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  224945. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224946. // compiled on its own).
  224947. #if JUCE_INCLUDED_FILE
  224948. class CoreGraphicsImage : public Image::SharedImage
  224949. {
  224950. public:
  224951. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  224952. : Image::SharedImage (format_, width_, height_)
  224953. {
  224954. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  224955. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  224956. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  224957. imageData = imageDataAllocated;
  224958. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  224959. : CGColorSpaceCreateDeviceRGB();
  224960. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  224961. colourSpace, getCGImageFlags (format_));
  224962. CGColorSpaceRelease (colourSpace);
  224963. }
  224964. ~CoreGraphicsImage()
  224965. {
  224966. CGContextRelease (context);
  224967. }
  224968. Image::ImageType getType() const { return Image::NativeImage; }
  224969. LowLevelGraphicsContext* createLowLevelContext();
  224970. SharedImage* clone()
  224971. {
  224972. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  224973. memcpy (im->imageData, imageData, lineStride * height);
  224974. return im;
  224975. }
  224976. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  224977. {
  224978. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  224979. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  224980. {
  224981. return CGBitmapContextCreateImage (nativeImage->context);
  224982. }
  224983. else
  224984. {
  224985. const Image::BitmapData srcData (juceImage, 0, 0, juceImage.getWidth(), juceImage.getHeight());
  224986. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  224987. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  224988. 8, srcData.pixelStride * 8, srcData.lineStride,
  224989. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  224990. 0, true, kCGRenderingIntentDefault);
  224991. CGDataProviderRelease (provider);
  224992. return imageRef;
  224993. }
  224994. }
  224995. #if JUCE_MAC
  224996. static NSImage* createNSImage (const Image& image)
  224997. {
  224998. const ScopedAutoReleasePool pool;
  224999. NSImage* im = [[NSImage alloc] init];
  225000. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  225001. [im lockFocus];
  225002. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  225003. CGImageRef imageRef = createImage (image, false, colourSpace);
  225004. CGColorSpaceRelease (colourSpace);
  225005. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  225006. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  225007. CGImageRelease (imageRef);
  225008. [im unlockFocus];
  225009. return im;
  225010. }
  225011. #endif
  225012. CGContextRef context;
  225013. HeapBlock<uint8> imageDataAllocated;
  225014. private:
  225015. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  225016. {
  225017. #if JUCE_BIG_ENDIAN
  225018. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  225019. #else
  225020. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  225021. #endif
  225022. }
  225023. };
  225024. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  225025. {
  225026. #if USE_COREGRAPHICS_RENDERING
  225027. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  225028. #else
  225029. return createSoftwareImage (format, width, height, clearImage);
  225030. #endif
  225031. }
  225032. class CoreGraphicsContext : public LowLevelGraphicsContext
  225033. {
  225034. public:
  225035. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  225036. : context (context_),
  225037. flipHeight (flipHeight_),
  225038. state (new SavedState()),
  225039. numGradientLookupEntries (0),
  225040. lastClipRectIsValid (false)
  225041. {
  225042. CGContextRetain (context);
  225043. CGContextSaveGState(context);
  225044. CGContextSetShouldSmoothFonts (context, true);
  225045. CGContextSetShouldAntialias (context, true);
  225046. CGContextSetBlendMode (context, kCGBlendModeNormal);
  225047. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  225048. greyColourSpace = CGColorSpaceCreateDeviceGray();
  225049. gradientCallbacks.version = 0;
  225050. gradientCallbacks.evaluate = gradientCallback;
  225051. gradientCallbacks.releaseInfo = 0;
  225052. setFont (Font());
  225053. }
  225054. ~CoreGraphicsContext()
  225055. {
  225056. CGContextRestoreGState (context);
  225057. CGContextRelease (context);
  225058. CGColorSpaceRelease (rgbColourSpace);
  225059. CGColorSpaceRelease (greyColourSpace);
  225060. }
  225061. bool isVectorDevice() const { return false; }
  225062. void setOrigin (int x, int y)
  225063. {
  225064. CGContextTranslateCTM (context, x, -y);
  225065. if (lastClipRectIsValid)
  225066. lastClipRect.translate (-x, -y);
  225067. }
  225068. bool clipToRectangle (const Rectangle<int>& r)
  225069. {
  225070. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  225071. if (lastClipRectIsValid)
  225072. {
  225073. lastClipRect = lastClipRect.getIntersection (r);
  225074. return ! lastClipRect.isEmpty();
  225075. }
  225076. return ! isClipEmpty();
  225077. }
  225078. bool clipToRectangleList (const RectangleList& clipRegion)
  225079. {
  225080. if (clipRegion.isEmpty())
  225081. {
  225082. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  225083. lastClipRectIsValid = true;
  225084. lastClipRect = Rectangle<int>();
  225085. return false;
  225086. }
  225087. else
  225088. {
  225089. const int numRects = clipRegion.getNumRectangles();
  225090. HeapBlock <CGRect> rects (numRects);
  225091. for (int i = 0; i < numRects; ++i)
  225092. {
  225093. const Rectangle<int>& r = clipRegion.getRectangle(i);
  225094. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  225095. }
  225096. CGContextClipToRects (context, rects, numRects);
  225097. lastClipRectIsValid = false;
  225098. return ! isClipEmpty();
  225099. }
  225100. }
  225101. void excludeClipRectangle (const Rectangle<int>& r)
  225102. {
  225103. RectangleList remaining (getClipBounds());
  225104. remaining.subtract (r);
  225105. clipToRectangleList (remaining);
  225106. lastClipRectIsValid = false;
  225107. }
  225108. void clipToPath (const Path& path, const AffineTransform& transform)
  225109. {
  225110. createPath (path, transform);
  225111. CGContextClip (context);
  225112. lastClipRectIsValid = false;
  225113. }
  225114. void clipToImageAlpha (const Image& sourceImage, const Rectangle<int>& srcClip, const AffineTransform& transform)
  225115. {
  225116. if (! transform.isSingularity())
  225117. {
  225118. Image singleChannelImage (sourceImage);
  225119. if (sourceImage.getFormat() != Image::SingleChannel)
  225120. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  225121. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  225122. if (srcClip != sourceImage.getBounds())
  225123. {
  225124. CGImageRef fullImage = image;
  225125. image = CGImageCreateWithImageInRect (fullImage, CGRectMake (srcClip.getX(), srcClip.getY(),
  225126. srcClip.getWidth(), srcClip.getHeight()));
  225127. CGImageRelease (fullImage);
  225128. }
  225129. flip();
  225130. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, srcClip.getHeight()).followedBy (transform));
  225131. applyTransform (t);
  225132. CGRect r = CGRectMake (0, 0, srcClip.getWidth(), srcClip.getHeight());
  225133. CGContextClipToMask (context, r, image);
  225134. applyTransform (t.inverted());
  225135. flip();
  225136. CGImageRelease (image);
  225137. lastClipRectIsValid = false;
  225138. }
  225139. }
  225140. bool clipRegionIntersects (const Rectangle<int>& r)
  225141. {
  225142. return getClipBounds().intersects (r);
  225143. }
  225144. const Rectangle<int> getClipBounds() const
  225145. {
  225146. if (! lastClipRectIsValid)
  225147. {
  225148. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  225149. lastClipRectIsValid = true;
  225150. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  225151. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  225152. roundToInt (bounds.size.width),
  225153. roundToInt (bounds.size.height));
  225154. }
  225155. return lastClipRect;
  225156. }
  225157. bool isClipEmpty() const
  225158. {
  225159. return getClipBounds().isEmpty();
  225160. }
  225161. void saveState()
  225162. {
  225163. CGContextSaveGState (context);
  225164. stateStack.add (new SavedState (*state));
  225165. }
  225166. void restoreState()
  225167. {
  225168. CGContextRestoreGState (context);
  225169. SavedState* const top = stateStack.getLast();
  225170. if (top != 0)
  225171. {
  225172. state = top;
  225173. stateStack.removeLast (1, false);
  225174. lastClipRectIsValid = false;
  225175. }
  225176. else
  225177. {
  225178. jassertfalse; // trying to pop with an empty stack!
  225179. }
  225180. }
  225181. void setFill (const FillType& fillType)
  225182. {
  225183. state->fillType = fillType;
  225184. if (fillType.isColour())
  225185. {
  225186. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  225187. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  225188. CGContextSetAlpha (context, 1.0f);
  225189. }
  225190. }
  225191. void setOpacity (float newOpacity)
  225192. {
  225193. state->fillType.setOpacity (newOpacity);
  225194. setFill (state->fillType);
  225195. }
  225196. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  225197. {
  225198. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  225199. ? kCGInterpolationLow
  225200. : kCGInterpolationHigh);
  225201. }
  225202. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  225203. {
  225204. CGRect cgRect = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  225205. if (replaceExistingContents)
  225206. {
  225207. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  225208. CGContextClearRect (context, cgRect);
  225209. #else
  225210. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  225211. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  225212. CGContextClearRect (context, cgRect);
  225213. else
  225214. #endif
  225215. CGContextSetBlendMode (context, kCGBlendModeCopy);
  225216. #endif
  225217. fillRect (r, false);
  225218. CGContextSetBlendMode (context, kCGBlendModeNormal);
  225219. }
  225220. else
  225221. {
  225222. if (state->fillType.isColour())
  225223. {
  225224. CGContextFillRect (context, cgRect);
  225225. }
  225226. else if (state->fillType.isGradient())
  225227. {
  225228. CGContextSaveGState (context);
  225229. CGContextClipToRect (context, cgRect);
  225230. drawGradient();
  225231. CGContextRestoreGState (context);
  225232. }
  225233. else
  225234. {
  225235. CGContextSaveGState (context);
  225236. CGContextClipToRect (context, cgRect);
  225237. drawImage (state->fillType.image, state->fillType.image.getBounds(), state->fillType.transform, true);
  225238. CGContextRestoreGState (context);
  225239. }
  225240. }
  225241. }
  225242. void fillPath (const Path& path, const AffineTransform& transform)
  225243. {
  225244. CGContextSaveGState (context);
  225245. if (state->fillType.isColour())
  225246. {
  225247. flip();
  225248. applyTransform (transform);
  225249. createPath (path);
  225250. if (path.isUsingNonZeroWinding())
  225251. CGContextFillPath (context);
  225252. else
  225253. CGContextEOFillPath (context);
  225254. }
  225255. else
  225256. {
  225257. createPath (path, transform);
  225258. if (path.isUsingNonZeroWinding())
  225259. CGContextClip (context);
  225260. else
  225261. CGContextEOClip (context);
  225262. if (state->fillType.isGradient())
  225263. drawGradient();
  225264. else
  225265. drawImage (state->fillType.image, state->fillType.image.getBounds(), state->fillType.transform, true);
  225266. }
  225267. CGContextRestoreGState (context);
  225268. }
  225269. void drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  225270. const AffineTransform& transform, const bool fillEntireClipAsTiles)
  225271. {
  225272. jassert (sourceImage.getBounds().contains (srcClip));
  225273. CGImageRef fullImage = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  225274. CGImageRef image = fullImage;
  225275. if (srcClip != sourceImage.getBounds())
  225276. {
  225277. image = CGImageCreateWithImageInRect (fullImage, CGRectMake (srcClip.getX(), srcClip.getY(),
  225278. srcClip.getWidth(), srcClip.getHeight()));
  225279. CGImageRelease (fullImage);
  225280. }
  225281. CGContextSaveGState (context);
  225282. CGContextSetAlpha (context, state->fillType.getOpacity());
  225283. flip();
  225284. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, srcClip.getHeight()).followedBy (transform));
  225285. CGRect imageRect = CGRectMake (0, 0, srcClip.getWidth(), srcClip.getHeight());
  225286. if (fillEntireClipAsTiles)
  225287. {
  225288. #if JUCE_IPHONE
  225289. CGContextDrawTiledImage (context, imageRect, image);
  225290. #else
  225291. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  225292. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  225293. // if it's doing a transformation - it's quicker to just draw lots of images manually
  225294. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  225295. CGContextDrawTiledImage (context, imageRect, image);
  225296. else
  225297. #endif
  225298. {
  225299. // Fallback to manually doing a tiled fill on 10.4
  225300. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  225301. const int iw = srcClip.getWidth();
  225302. const int ih = srcClip.getHeight();
  225303. int x = 0, y = 0;
  225304. while (x > clip.origin.x) x -= iw;
  225305. while (y > clip.origin.y) y -= ih;
  225306. const int right = (int) (clip.origin.x + clip.size.width);
  225307. const int bottom = (int) (clip.origin.y + clip.size.height);
  225308. while (y < bottom)
  225309. {
  225310. for (int x2 = x; x2 < right; x2 += iw)
  225311. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  225312. y += ih;
  225313. }
  225314. }
  225315. #endif
  225316. }
  225317. else
  225318. {
  225319. CGContextDrawImage (context, imageRect, image);
  225320. }
  225321. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  225322. CGContextRestoreGState (context);
  225323. }
  225324. void drawLine (const Line<float>& line)
  225325. {
  225326. CGContextSetLineCap (context, kCGLineCapSquare);
  225327. CGContextSetLineWidth (context, 1.0f);
  225328. CGContextSetRGBStrokeColor (context,
  225329. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  225330. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  225331. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  225332. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  225333. CGContextStrokeLineSegments (context, cgLine, 1);
  225334. }
  225335. void drawVerticalLine (const int x, float top, float bottom)
  225336. {
  225337. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  225338. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  225339. #else
  225340. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  225341. // the x co-ord slightly to trick it..
  225342. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  225343. #endif
  225344. }
  225345. void drawHorizontalLine (const int y, float left, float right)
  225346. {
  225347. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  225348. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  225349. #else
  225350. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  225351. // the x co-ord slightly to trick it..
  225352. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  225353. #endif
  225354. }
  225355. void setFont (const Font& newFont)
  225356. {
  225357. if (state->font != newFont)
  225358. {
  225359. state->fontRef = 0;
  225360. state->font = newFont;
  225361. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  225362. if (mf != 0)
  225363. {
  225364. state->fontRef = mf->fontRef;
  225365. CGContextSetFont (context, state->fontRef);
  225366. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  225367. state->fontTransform = mf->renderingTransform;
  225368. state->fontTransform.a *= state->font.getHorizontalScale();
  225369. CGContextSetTextMatrix (context, state->fontTransform);
  225370. }
  225371. }
  225372. }
  225373. const Font getFont()
  225374. {
  225375. return state->font;
  225376. }
  225377. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  225378. {
  225379. if (state->fontRef != 0 && state->fillType.isColour())
  225380. {
  225381. if (transform.isOnlyTranslation())
  225382. {
  225383. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  225384. CGGlyph g = glyphNumber;
  225385. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  225386. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  225387. }
  225388. else
  225389. {
  225390. CGContextSaveGState (context);
  225391. flip();
  225392. applyTransform (transform);
  225393. CGAffineTransform t = state->fontTransform;
  225394. t.d = -t.d;
  225395. CGContextSetTextMatrix (context, t);
  225396. CGGlyph g = glyphNumber;
  225397. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  225398. CGContextRestoreGState (context);
  225399. }
  225400. }
  225401. else
  225402. {
  225403. Path p;
  225404. Font& f = state->font;
  225405. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  225406. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  225407. .followedBy (transform));
  225408. }
  225409. }
  225410. private:
  225411. CGContextRef context;
  225412. const CGFloat flipHeight;
  225413. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  225414. CGFunctionCallbacks gradientCallbacks;
  225415. mutable Rectangle<int> lastClipRect;
  225416. mutable bool lastClipRectIsValid;
  225417. struct SavedState
  225418. {
  225419. SavedState()
  225420. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  225421. {
  225422. }
  225423. SavedState (const SavedState& other)
  225424. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  225425. fontTransform (other.fontTransform)
  225426. {
  225427. }
  225428. ~SavedState()
  225429. {
  225430. }
  225431. FillType fillType;
  225432. Font font;
  225433. CGFontRef fontRef;
  225434. CGAffineTransform fontTransform;
  225435. };
  225436. ScopedPointer <SavedState> state;
  225437. OwnedArray <SavedState> stateStack;
  225438. HeapBlock <PixelARGB> gradientLookupTable;
  225439. int numGradientLookupEntries;
  225440. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  225441. {
  225442. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  225443. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  225444. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  225445. colour.unpremultiply();
  225446. outData[0] = colour.getRed() / 255.0f;
  225447. outData[1] = colour.getGreen() / 255.0f;
  225448. outData[2] = colour.getBlue() / 255.0f;
  225449. outData[3] = colour.getAlpha() / 255.0f;
  225450. }
  225451. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  225452. {
  225453. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  225454. --numGradientLookupEntries;
  225455. CGShadingRef result = 0;
  225456. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  225457. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  225458. if (gradient.isRadial)
  225459. {
  225460. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  225461. p1, gradient.point1.getDistanceFrom (gradient.point2),
  225462. function, true, true);
  225463. }
  225464. else
  225465. {
  225466. result = CGShadingCreateAxial (rgbColourSpace, p1,
  225467. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  225468. function, true, true);
  225469. }
  225470. CGFunctionRelease (function);
  225471. return result;
  225472. }
  225473. void drawGradient()
  225474. {
  225475. flip();
  225476. applyTransform (state->fillType.transform);
  225477. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  225478. // you draw a gradient with high quality interp enabled).
  225479. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  225480. CGContextSetAlpha (context, state->fillType.getOpacity());
  225481. CGContextDrawShading (context, shading);
  225482. CGShadingRelease (shading);
  225483. }
  225484. void createPath (const Path& path) const
  225485. {
  225486. CGContextBeginPath (context);
  225487. Path::Iterator i (path);
  225488. while (i.next())
  225489. {
  225490. switch (i.elementType)
  225491. {
  225492. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  225493. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  225494. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  225495. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  225496. case Path::Iterator::closePath: CGContextClosePath (context); break;
  225497. default: jassertfalse; break;
  225498. }
  225499. }
  225500. }
  225501. void createPath (const Path& path, const AffineTransform& transform) const
  225502. {
  225503. CGContextBeginPath (context);
  225504. Path::Iterator i (path);
  225505. while (i.next())
  225506. {
  225507. switch (i.elementType)
  225508. {
  225509. case Path::Iterator::startNewSubPath:
  225510. transform.transformPoint (i.x1, i.y1);
  225511. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  225512. break;
  225513. case Path::Iterator::lineTo:
  225514. transform.transformPoint (i.x1, i.y1);
  225515. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  225516. break;
  225517. case Path::Iterator::quadraticTo:
  225518. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  225519. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  225520. break;
  225521. case Path::Iterator::cubicTo:
  225522. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  225523. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  225524. break;
  225525. case Path::Iterator::closePath:
  225526. CGContextClosePath (context); break;
  225527. default:
  225528. jassertfalse;
  225529. break;
  225530. }
  225531. }
  225532. }
  225533. void flip() const
  225534. {
  225535. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  225536. }
  225537. void applyTransform (const AffineTransform& transform) const
  225538. {
  225539. CGAffineTransform t;
  225540. t.a = transform.mat00;
  225541. t.b = transform.mat10;
  225542. t.c = transform.mat01;
  225543. t.d = transform.mat11;
  225544. t.tx = transform.mat02;
  225545. t.ty = transform.mat12;
  225546. CGContextConcatCTM (context, t);
  225547. }
  225548. CoreGraphicsContext (const CoreGraphicsContext&);
  225549. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  225550. };
  225551. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  225552. {
  225553. return new CoreGraphicsContext (context, height);
  225554. }
  225555. #endif
  225556. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  225557. /*** Start of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  225558. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225559. // compiled on its own).
  225560. #if JUCE_INCLUDED_FILE
  225561. class UIViewComponentPeer;
  225562. END_JUCE_NAMESPACE
  225563. #define JuceUIView MakeObjCClassName(JuceUIView)
  225564. @interface JuceUIView : UIView <UITextFieldDelegate>
  225565. {
  225566. @public
  225567. UIViewComponentPeer* owner;
  225568. UITextField *hiddenTextField;
  225569. }
  225570. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner withFrame: (CGRect) frame;
  225571. - (void) dealloc;
  225572. - (void) drawRect: (CGRect) r;
  225573. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event;
  225574. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event;
  225575. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event;
  225576. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event;
  225577. - (BOOL) becomeFirstResponder;
  225578. - (BOOL) resignFirstResponder;
  225579. - (BOOL) canBecomeFirstResponder;
  225580. - (void) asyncRepaint: (id) rect;
  225581. - (BOOL) textField: (UITextField*) textField shouldChangeCharactersInRange: (NSRange) range replacementString: (NSString*) string;
  225582. - (BOOL) textFieldShouldClear: (UITextField*) textField;
  225583. - (BOOL) textFieldShouldReturn: (UITextField*) textField;
  225584. @end
  225585. #define JuceUIWindow MakeObjCClassName(JuceUIWindow)
  225586. @interface JuceUIWindow : UIWindow
  225587. {
  225588. @private
  225589. UIViewComponentPeer* owner;
  225590. bool isZooming;
  225591. }
  225592. - (void) setOwner: (UIViewComponentPeer*) owner;
  225593. - (void) becomeKeyWindow;
  225594. @end
  225595. BEGIN_JUCE_NAMESPACE
  225596. class UIViewComponentPeer : public ComponentPeer,
  225597. public FocusChangeListener
  225598. {
  225599. public:
  225600. UIViewComponentPeer (Component* const component,
  225601. const int windowStyleFlags,
  225602. UIView* viewToAttachTo);
  225603. ~UIViewComponentPeer();
  225604. void* getNativeHandle() const;
  225605. void setVisible (bool shouldBeVisible);
  225606. void setTitle (const String& title);
  225607. void setPosition (int x, int y);
  225608. void setSize (int w, int h);
  225609. void setBounds (int x, int y, int w, int h, bool isNowFullScreen);
  225610. const Rectangle<int> getBounds() const;
  225611. const Rectangle<int> getBounds (const bool global) const;
  225612. const Point<int> getScreenPosition() const;
  225613. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition);
  225614. const Point<int> globalPositionToRelative (const Point<int>& screenPosition);
  225615. void setMinimised (bool shouldBeMinimised);
  225616. bool isMinimised() const;
  225617. void setFullScreen (bool shouldBeFullScreen);
  225618. bool isFullScreen() const;
  225619. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  225620. const BorderSize getFrameSize() const;
  225621. bool setAlwaysOnTop (bool alwaysOnTop);
  225622. void toFront (bool makeActiveWindow);
  225623. void toBehind (ComponentPeer* other);
  225624. void setIcon (const Image& newIcon);
  225625. virtual void drawRect (CGRect r);
  225626. virtual bool canBecomeKeyWindow();
  225627. virtual bool windowShouldClose();
  225628. virtual void redirectMovedOrResized();
  225629. virtual CGRect constrainRect (CGRect r);
  225630. virtual void viewFocusGain();
  225631. virtual void viewFocusLoss();
  225632. bool isFocused() const;
  225633. void grabFocus();
  225634. void textInputRequired (const Point<int>& position);
  225635. virtual BOOL textFieldReplaceCharacters (const Range<int>& range, const String& text);
  225636. virtual BOOL textFieldShouldClear();
  225637. virtual BOOL textFieldShouldReturn();
  225638. void updateHiddenTextContent (TextInputTarget* target);
  225639. void globalFocusChanged (Component*);
  225640. void handleTouches (UIEvent* e, bool isDown, bool isUp, bool isCancel);
  225641. void repaint (const Rectangle<int>& area);
  225642. void performAnyPendingRepaintsNow();
  225643. juce_UseDebuggingNewOperator
  225644. UIWindow* window;
  225645. JuceUIView* view;
  225646. bool isSharedWindow, fullScreen, insideDrawRect;
  225647. static ModifierKeys currentModifiers;
  225648. static int64 getMouseTime (UIEvent* e)
  225649. {
  225650. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  225651. + (int64) ([e timestamp] * 1000.0);
  225652. }
  225653. Array <UITouch*> currentTouches;
  225654. };
  225655. END_JUCE_NAMESPACE
  225656. @implementation JuceUIView
  225657. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner_
  225658. withFrame: (CGRect) frame
  225659. {
  225660. [super initWithFrame: frame];
  225661. owner = owner_;
  225662. hiddenTextField = [[UITextField alloc] initWithFrame: CGRectMake (0, 0, 0, 0)];
  225663. [self addSubview: hiddenTextField];
  225664. hiddenTextField.delegate = self;
  225665. return self;
  225666. }
  225667. - (void) dealloc
  225668. {
  225669. [hiddenTextField removeFromSuperview];
  225670. [hiddenTextField release];
  225671. [super dealloc];
  225672. }
  225673. - (void) drawRect: (CGRect) r
  225674. {
  225675. if (owner != 0)
  225676. owner->drawRect (r);
  225677. }
  225678. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  225679. {
  225680. return false;
  225681. }
  225682. ModifierKeys UIViewComponentPeer::currentModifiers;
  225683. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  225684. {
  225685. return UIViewComponentPeer::currentModifiers;
  225686. }
  225687. void ModifierKeys::updateCurrentModifiers() throw()
  225688. {
  225689. currentModifiers = UIViewComponentPeer::currentModifiers;
  225690. }
  225691. JUCE_NAMESPACE::Point<int> juce_lastMousePos;
  225692. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event
  225693. {
  225694. if (owner != 0)
  225695. owner->handleTouches (event, true, false, false);
  225696. }
  225697. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event
  225698. {
  225699. if (owner != 0)
  225700. owner->handleTouches (event, false, false, false);
  225701. }
  225702. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event
  225703. {
  225704. if (owner != 0)
  225705. owner->handleTouches (event, false, true, false);
  225706. }
  225707. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event
  225708. {
  225709. if (owner != 0)
  225710. owner->handleTouches (event, false, true, true);
  225711. [self touchesEnded: touches withEvent: event];
  225712. }
  225713. - (BOOL) becomeFirstResponder
  225714. {
  225715. if (owner != 0)
  225716. owner->viewFocusGain();
  225717. return true;
  225718. }
  225719. - (BOOL) resignFirstResponder
  225720. {
  225721. if (owner != 0)
  225722. owner->viewFocusLoss();
  225723. return true;
  225724. }
  225725. - (BOOL) canBecomeFirstResponder
  225726. {
  225727. return owner != 0 && owner->canBecomeKeyWindow();
  225728. }
  225729. - (void) asyncRepaint: (id) rect
  225730. {
  225731. CGRect* r = (CGRect*) [((NSData*) rect) bytes];
  225732. [self setNeedsDisplayInRect: *r];
  225733. }
  225734. - (BOOL) textField: (UITextField*) textField shouldChangeCharactersInRange: (NSRange) range replacementString: (NSString*) text
  225735. {
  225736. return owner->textFieldReplaceCharacters (Range<int> (range.location, range.location + range.length),
  225737. nsStringToJuce (text));
  225738. }
  225739. - (BOOL) textFieldShouldClear: (UITextField*) textField
  225740. {
  225741. return owner->textFieldShouldClear();
  225742. }
  225743. - (BOOL) textFieldShouldReturn: (UITextField*) textField
  225744. {
  225745. return owner->textFieldShouldReturn();
  225746. }
  225747. @end
  225748. @implementation JuceUIWindow
  225749. - (void) setOwner: (UIViewComponentPeer*) owner_
  225750. {
  225751. owner = owner_;
  225752. isZooming = false;
  225753. }
  225754. - (void) becomeKeyWindow
  225755. {
  225756. [super becomeKeyWindow];
  225757. if (owner != 0)
  225758. owner->grabFocus();
  225759. }
  225760. @end
  225761. BEGIN_JUCE_NAMESPACE
  225762. UIViewComponentPeer::UIViewComponentPeer (Component* const component,
  225763. const int windowStyleFlags,
  225764. UIView* viewToAttachTo)
  225765. : ComponentPeer (component, windowStyleFlags),
  225766. window (0),
  225767. view (0),
  225768. isSharedWindow (viewToAttachTo != 0),
  225769. fullScreen (false),
  225770. insideDrawRect (false)
  225771. {
  225772. CGRect r = CGRectMake (0, 0, (float) component->getWidth(), (float) component->getHeight());
  225773. view = [[JuceUIView alloc] initWithOwner: this withFrame: r];
  225774. if (isSharedWindow)
  225775. {
  225776. window = [viewToAttachTo window];
  225777. [viewToAttachTo addSubview: view];
  225778. setVisible (component->isVisible());
  225779. }
  225780. else
  225781. {
  225782. r.origin.x = (float) component->getX();
  225783. r.origin.y = (float) component->getY();
  225784. r.origin.y = [[UIScreen mainScreen] bounds].size.height - (r.origin.y + r.size.height);
  225785. window = [[JuceUIWindow alloc] init];
  225786. window.frame = r;
  225787. window.opaque = component->isOpaque();
  225788. view.opaque = component->isOpaque();
  225789. window.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  225790. view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  225791. [((JuceUIWindow*) window) setOwner: this];
  225792. if (component->isAlwaysOnTop())
  225793. window.windowLevel = UIWindowLevelAlert;
  225794. [window addSubview: view];
  225795. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  225796. view.hidden = ! component->isVisible();
  225797. window.hidden = ! component->isVisible();
  225798. view.multipleTouchEnabled = YES;
  225799. }
  225800. setTitle (component->getName());
  225801. Desktop::getInstance().addFocusChangeListener (this);
  225802. }
  225803. UIViewComponentPeer::~UIViewComponentPeer()
  225804. {
  225805. Desktop::getInstance().removeFocusChangeListener (this);
  225806. view->owner = 0;
  225807. [view removeFromSuperview];
  225808. [view release];
  225809. if (! isSharedWindow)
  225810. {
  225811. [((JuceUIWindow*) window) setOwner: 0];
  225812. [window release];
  225813. }
  225814. }
  225815. void* UIViewComponentPeer::getNativeHandle() const
  225816. {
  225817. return view;
  225818. }
  225819. void UIViewComponentPeer::setVisible (bool shouldBeVisible)
  225820. {
  225821. view.hidden = ! shouldBeVisible;
  225822. if (! isSharedWindow)
  225823. window.hidden = ! shouldBeVisible;
  225824. }
  225825. void UIViewComponentPeer::setTitle (const String& title)
  225826. {
  225827. // xxx is this possible?
  225828. }
  225829. void UIViewComponentPeer::setPosition (int x, int y)
  225830. {
  225831. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  225832. }
  225833. void UIViewComponentPeer::setSize (int w, int h)
  225834. {
  225835. setBounds (component->getX(), component->getY(), w, h, false);
  225836. }
  225837. void UIViewComponentPeer::setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  225838. {
  225839. fullScreen = isNowFullScreen;
  225840. w = jmax (0, w);
  225841. h = jmax (0, h);
  225842. CGRect r;
  225843. r.origin.x = (float) x;
  225844. r.origin.y = (float) y;
  225845. r.size.width = (float) w;
  225846. r.size.height = (float) h;
  225847. if (isSharedWindow)
  225848. {
  225849. //r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  225850. if ([view frame].size.width != r.size.width
  225851. || [view frame].size.height != r.size.height)
  225852. [view setNeedsDisplay];
  225853. view.frame = r;
  225854. }
  225855. else
  225856. {
  225857. window.frame = r;
  225858. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  225859. }
  225860. }
  225861. const Rectangle<int> UIViewComponentPeer::getBounds (const bool global) const
  225862. {
  225863. CGRect r = [view frame];
  225864. if (global && [view window] != 0)
  225865. {
  225866. r = [view convertRect: r toView: nil];
  225867. CGRect wr = [[view window] frame];
  225868. r.origin.x += wr.origin.x;
  225869. r.origin.y += wr.origin.y;
  225870. }
  225871. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y,
  225872. (int) r.size.width, (int) r.size.height);
  225873. }
  225874. const Rectangle<int> UIViewComponentPeer::getBounds() const
  225875. {
  225876. return getBounds (! isSharedWindow);
  225877. }
  225878. const Point<int> UIViewComponentPeer::getScreenPosition() const
  225879. {
  225880. return getBounds (true).getPosition();
  225881. }
  225882. const Point<int> UIViewComponentPeer::relativePositionToGlobal (const Point<int>& relativePosition)
  225883. {
  225884. return relativePosition + getScreenPosition();
  225885. }
  225886. const Point<int> UIViewComponentPeer::globalPositionToRelative (const Point<int>& screenPosition)
  225887. {
  225888. return screenPosition - getScreenPosition();
  225889. }
  225890. CGRect UIViewComponentPeer::constrainRect (CGRect r)
  225891. {
  225892. if (constrainer != 0)
  225893. {
  225894. CGRect current = [window frame];
  225895. current.origin.y = [[UIScreen mainScreen] bounds].size.height - current.origin.y - current.size.height;
  225896. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.origin.y - r.size.height;
  225897. Rectangle<int> pos ((int) r.origin.x, (int) r.origin.y,
  225898. (int) r.size.width, (int) r.size.height);
  225899. Rectangle<int> original ((int) current.origin.x, (int) current.origin.y,
  225900. (int) current.size.width, (int) current.size.height);
  225901. constrainer->checkBounds (pos, original,
  225902. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  225903. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  225904. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  225905. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  225906. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  225907. r.origin.x = pos.getX();
  225908. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.size.height - pos.getY();
  225909. r.size.width = pos.getWidth();
  225910. r.size.height = pos.getHeight();
  225911. }
  225912. return r;
  225913. }
  225914. void UIViewComponentPeer::setMinimised (bool shouldBeMinimised)
  225915. {
  225916. // xxx
  225917. }
  225918. bool UIViewComponentPeer::isMinimised() const
  225919. {
  225920. return false;
  225921. }
  225922. void UIViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  225923. {
  225924. if (! isSharedWindow)
  225925. {
  225926. Rectangle<int> r (lastNonFullscreenBounds);
  225927. setMinimised (false);
  225928. if (fullScreen != shouldBeFullScreen)
  225929. {
  225930. if (shouldBeFullScreen)
  225931. r = Desktop::getInstance().getMainMonitorArea();
  225932. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  225933. if (r != getComponent()->getBounds() && ! r.isEmpty())
  225934. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  225935. }
  225936. }
  225937. }
  225938. bool UIViewComponentPeer::isFullScreen() const
  225939. {
  225940. return fullScreen;
  225941. }
  225942. bool UIViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  225943. {
  225944. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  225945. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  225946. return false;
  225947. CGPoint p;
  225948. p.x = (float) position.getX();
  225949. p.y = (float) position.getY();
  225950. UIView* v = [view hitTest: p withEvent: nil];
  225951. if (trueIfInAChildWindow)
  225952. return v != nil;
  225953. return v == view;
  225954. }
  225955. const BorderSize UIViewComponentPeer::getFrameSize() const
  225956. {
  225957. BorderSize b;
  225958. if (! isSharedWindow)
  225959. {
  225960. CGRect v = [view convertRect: [view frame] toView: nil];
  225961. CGRect w = [window frame];
  225962. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  225963. b.setBottom ((int) v.origin.y);
  225964. b.setLeft ((int) v.origin.x);
  225965. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  225966. }
  225967. return b;
  225968. }
  225969. bool UIViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  225970. {
  225971. if (! isSharedWindow)
  225972. window.windowLevel = alwaysOnTop ? UIWindowLevelAlert : UIWindowLevelNormal;
  225973. return true;
  225974. }
  225975. void UIViewComponentPeer::toFront (bool makeActiveWindow)
  225976. {
  225977. if (isSharedWindow)
  225978. [[view superview] bringSubviewToFront: view];
  225979. if (window != 0 && component->isVisible())
  225980. [window makeKeyAndVisible];
  225981. }
  225982. void UIViewComponentPeer::toBehind (ComponentPeer* other)
  225983. {
  225984. UIViewComponentPeer* const otherPeer = dynamic_cast <UIViewComponentPeer*> (other);
  225985. jassert (otherPeer != 0); // wrong type of window?
  225986. if (otherPeer != 0)
  225987. {
  225988. if (isSharedWindow)
  225989. {
  225990. [[view superview] insertSubview: view belowSubview: otherPeer->view];
  225991. }
  225992. else
  225993. {
  225994. jassertfalse; // don't know how to do this
  225995. }
  225996. }
  225997. }
  225998. void UIViewComponentPeer::setIcon (const Image& /*newIcon*/)
  225999. {
  226000. // to do..
  226001. }
  226002. void UIViewComponentPeer::handleTouches (UIEvent* event, const bool isDown, const bool isUp, bool isCancel)
  226003. {
  226004. NSArray* touches = [[event touchesForView: view] allObjects];
  226005. for (unsigned int i = 0; i < [touches count]; ++i)
  226006. {
  226007. UITouch* touch = [touches objectAtIndex: i];
  226008. CGPoint p = [touch locationInView: view];
  226009. const Point<int> pos ((int) p.x, (int) p.y);
  226010. juce_lastMousePos = pos + getScreenPosition();
  226011. const int64 time = getMouseTime (event);
  226012. int touchIndex = currentTouches.indexOf (touch);
  226013. if (touchIndex < 0)
  226014. {
  226015. touchIndex = currentTouches.size();
  226016. currentTouches.add (touch);
  226017. }
  226018. if (isDown)
  226019. {
  226020. currentModifiers = currentModifiers.withoutMouseButtons();
  226021. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  226022. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  226023. }
  226024. else if (isUp)
  226025. {
  226026. currentModifiers = currentModifiers.withoutMouseButtons();
  226027. currentTouches.remove (touchIndex);
  226028. }
  226029. if (isCancel)
  226030. currentTouches.clear();
  226031. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  226032. }
  226033. }
  226034. static UIViewComponentPeer* currentlyFocusedPeer = 0;
  226035. void UIViewComponentPeer::viewFocusGain()
  226036. {
  226037. if (currentlyFocusedPeer != this)
  226038. {
  226039. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  226040. currentlyFocusedPeer->handleFocusLoss();
  226041. currentlyFocusedPeer = this;
  226042. handleFocusGain();
  226043. }
  226044. }
  226045. void UIViewComponentPeer::viewFocusLoss()
  226046. {
  226047. if (currentlyFocusedPeer == this)
  226048. {
  226049. currentlyFocusedPeer = 0;
  226050. handleFocusLoss();
  226051. }
  226052. }
  226053. void juce_HandleProcessFocusChange()
  226054. {
  226055. if (UIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  226056. {
  226057. if (Process::isForegroundProcess())
  226058. {
  226059. currentlyFocusedPeer->handleFocusGain();
  226060. ComponentPeer::bringModalComponentToFront();
  226061. }
  226062. else
  226063. {
  226064. currentlyFocusedPeer->handleFocusLoss();
  226065. // turn kiosk mode off if we lose focus..
  226066. Desktop::getInstance().setKioskModeComponent (0);
  226067. }
  226068. }
  226069. }
  226070. bool UIViewComponentPeer::isFocused() const
  226071. {
  226072. return isSharedWindow ? this == currentlyFocusedPeer
  226073. : (window != 0 && [window isKeyWindow]);
  226074. }
  226075. void UIViewComponentPeer::grabFocus()
  226076. {
  226077. if (window != 0)
  226078. {
  226079. [window makeKeyWindow];
  226080. viewFocusGain();
  226081. }
  226082. }
  226083. void UIViewComponentPeer::textInputRequired (const Point<int>&)
  226084. {
  226085. }
  226086. void UIViewComponentPeer::updateHiddenTextContent (TextInputTarget* target)
  226087. {
  226088. view->hiddenTextField.text = juceStringToNS (target->getTextInRange (Range<int> (0, target->getHighlightedRegion().getStart())));
  226089. }
  226090. BOOL UIViewComponentPeer::textFieldReplaceCharacters (const Range<int>& range, const String& text)
  226091. {
  226092. TextInputTarget* const target = findCurrentTextInputTarget();
  226093. if (target != 0)
  226094. {
  226095. const Range<int> currentSelection (target->getHighlightedRegion());
  226096. if (range.getLength() == 1 && text.isEmpty()) // (detect backspace)
  226097. if (currentSelection.isEmpty())
  226098. target->setHighlightedRegion (currentSelection.withStart (currentSelection.getStart() - 1));
  226099. target->insertTextAtCaret (text);
  226100. updateHiddenTextContent (target);
  226101. }
  226102. return NO;
  226103. }
  226104. BOOL UIViewComponentPeer::textFieldShouldClear()
  226105. {
  226106. TextInputTarget* const target = findCurrentTextInputTarget();
  226107. if (target != 0)
  226108. {
  226109. target->setHighlightedRegion (Range<int> (0, std::numeric_limits<int>::max()));
  226110. target->insertTextAtCaret (String::empty);
  226111. updateHiddenTextContent (target);
  226112. }
  226113. return YES;
  226114. }
  226115. BOOL UIViewComponentPeer::textFieldShouldReturn()
  226116. {
  226117. TextInputTarget* const target = findCurrentTextInputTarget();
  226118. if (target != 0)
  226119. {
  226120. target->insertTextAtCaret ("\n");
  226121. updateHiddenTextContent (target);
  226122. }
  226123. return YES;
  226124. }
  226125. void UIViewComponentPeer::globalFocusChanged (Component*)
  226126. {
  226127. TextInputTarget* const target = findCurrentTextInputTarget();
  226128. if (target != 0)
  226129. {
  226130. Component* comp = dynamic_cast<Component*> (target);
  226131. Point<int> pos (comp->relativePositionToOtherComponent (component, Point<int>()));
  226132. view->hiddenTextField.frame = CGRectMake (pos.getX(), pos.getY(), 0, 0);
  226133. updateHiddenTextContent (target);
  226134. [view->hiddenTextField becomeFirstResponder];
  226135. }
  226136. else
  226137. {
  226138. [view->hiddenTextField resignFirstResponder];
  226139. }
  226140. }
  226141. void UIViewComponentPeer::drawRect (CGRect r)
  226142. {
  226143. if (r.size.width < 1.0f || r.size.height < 1.0f)
  226144. return;
  226145. CGContextRef cg = UIGraphicsGetCurrentContext();
  226146. if (! component->isOpaque())
  226147. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  226148. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, 0, view.bounds.size.height));
  226149. CoreGraphicsContext g (cg, view.bounds.size.height);
  226150. insideDrawRect = true;
  226151. handlePaint (g);
  226152. insideDrawRect = false;
  226153. }
  226154. bool UIViewComponentPeer::canBecomeKeyWindow()
  226155. {
  226156. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  226157. }
  226158. bool UIViewComponentPeer::windowShouldClose()
  226159. {
  226160. if (! isValidPeer (this))
  226161. return YES;
  226162. handleUserClosingWindow();
  226163. return NO;
  226164. }
  226165. void UIViewComponentPeer::redirectMovedOrResized()
  226166. {
  226167. handleMovedOrResized();
  226168. }
  226169. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  226170. {
  226171. }
  226172. class AsyncRepaintMessage : public CallbackMessage
  226173. {
  226174. public:
  226175. UIViewComponentPeer* const peer;
  226176. const Rectangle<int> rect;
  226177. AsyncRepaintMessage (UIViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  226178. : peer (peer_), rect (rect_)
  226179. {
  226180. }
  226181. void messageCallback()
  226182. {
  226183. if (ComponentPeer::isValidPeer (peer))
  226184. peer->repaint (rect);
  226185. }
  226186. };
  226187. void UIViewComponentPeer::repaint (const Rectangle<int>& area)
  226188. {
  226189. if (insideDrawRect || ! MessageManager::getInstance()->isThisTheMessageThread())
  226190. {
  226191. (new AsyncRepaintMessage (this, area))->post();
  226192. }
  226193. else
  226194. {
  226195. [view setNeedsDisplayInRect: CGRectMake ((float) area.getX(), (float) area.getY(),
  226196. (float) area.getWidth(), (float) area.getHeight())];
  226197. }
  226198. }
  226199. void UIViewComponentPeer::performAnyPendingRepaintsNow()
  226200. {
  226201. }
  226202. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  226203. {
  226204. return new UIViewComponentPeer (this, styleFlags, (UIView*) windowToAttachTo);
  226205. }
  226206. const Image juce_createIconForFile (const File& file)
  226207. {
  226208. return Image();
  226209. }
  226210. void Desktop::createMouseInputSources()
  226211. {
  226212. for (int i = 0; i < 10; ++i)
  226213. mouseSources.add (new MouseInputSource (i, false));
  226214. }
  226215. bool Desktop::canUseSemiTransparentWindows() throw()
  226216. {
  226217. return true;
  226218. }
  226219. const Point<int> Desktop::getMousePosition()
  226220. {
  226221. return juce_lastMousePos;
  226222. }
  226223. void Desktop::setMousePosition (const Point<int>&)
  226224. {
  226225. }
  226226. const int KeyPress::spaceKey = ' ';
  226227. const int KeyPress::returnKey = 0x0d;
  226228. const int KeyPress::escapeKey = 0x1b;
  226229. const int KeyPress::backspaceKey = 0x7f;
  226230. const int KeyPress::leftKey = 0x1000;
  226231. const int KeyPress::rightKey = 0x1001;
  226232. const int KeyPress::upKey = 0x1002;
  226233. const int KeyPress::downKey = 0x1003;
  226234. const int KeyPress::pageUpKey = 0x1004;
  226235. const int KeyPress::pageDownKey = 0x1005;
  226236. const int KeyPress::endKey = 0x1006;
  226237. const int KeyPress::homeKey = 0x1007;
  226238. const int KeyPress::deleteKey = 0x1008;
  226239. const int KeyPress::insertKey = -1;
  226240. const int KeyPress::tabKey = 9;
  226241. const int KeyPress::F1Key = 0x2001;
  226242. const int KeyPress::F2Key = 0x2002;
  226243. const int KeyPress::F3Key = 0x2003;
  226244. const int KeyPress::F4Key = 0x2004;
  226245. const int KeyPress::F5Key = 0x2005;
  226246. const int KeyPress::F6Key = 0x2006;
  226247. const int KeyPress::F7Key = 0x2007;
  226248. const int KeyPress::F8Key = 0x2008;
  226249. const int KeyPress::F9Key = 0x2009;
  226250. const int KeyPress::F10Key = 0x200a;
  226251. const int KeyPress::F11Key = 0x200b;
  226252. const int KeyPress::F12Key = 0x200c;
  226253. const int KeyPress::F13Key = 0x200d;
  226254. const int KeyPress::F14Key = 0x200e;
  226255. const int KeyPress::F15Key = 0x200f;
  226256. const int KeyPress::F16Key = 0x2010;
  226257. const int KeyPress::numberPad0 = 0x30020;
  226258. const int KeyPress::numberPad1 = 0x30021;
  226259. const int KeyPress::numberPad2 = 0x30022;
  226260. const int KeyPress::numberPad3 = 0x30023;
  226261. const int KeyPress::numberPad4 = 0x30024;
  226262. const int KeyPress::numberPad5 = 0x30025;
  226263. const int KeyPress::numberPad6 = 0x30026;
  226264. const int KeyPress::numberPad7 = 0x30027;
  226265. const int KeyPress::numberPad8 = 0x30028;
  226266. const int KeyPress::numberPad9 = 0x30029;
  226267. const int KeyPress::numberPadAdd = 0x3002a;
  226268. const int KeyPress::numberPadSubtract = 0x3002b;
  226269. const int KeyPress::numberPadMultiply = 0x3002c;
  226270. const int KeyPress::numberPadDivide = 0x3002d;
  226271. const int KeyPress::numberPadSeparator = 0x3002e;
  226272. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  226273. const int KeyPress::numberPadEquals = 0x30030;
  226274. const int KeyPress::numberPadDelete = 0x30031;
  226275. const int KeyPress::playKey = 0x30000;
  226276. const int KeyPress::stopKey = 0x30001;
  226277. const int KeyPress::fastForwardKey = 0x30002;
  226278. const int KeyPress::rewindKey = 0x30003;
  226279. #endif
  226280. /*** End of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  226281. /*** Start of inlined file: juce_iphone_MessageManager.mm ***/
  226282. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226283. // compiled on its own).
  226284. #if JUCE_INCLUDED_FILE
  226285. struct CallbackMessagePayload
  226286. {
  226287. MessageCallbackFunction* function;
  226288. void* parameter;
  226289. void* volatile result;
  226290. bool volatile hasBeenExecuted;
  226291. };
  226292. END_JUCE_NAMESPACE
  226293. @interface JuceCustomMessageHandler : NSObject
  226294. {
  226295. }
  226296. - (void) performCallback: (id) info;
  226297. @end
  226298. @implementation JuceCustomMessageHandler
  226299. - (void) performCallback: (id) info
  226300. {
  226301. if ([info isKindOfClass: [NSData class]])
  226302. {
  226303. JUCE_NAMESPACE::CallbackMessagePayload* pl = (JUCE_NAMESPACE::CallbackMessagePayload*) [((NSData*) info) bytes];
  226304. if (pl != 0)
  226305. {
  226306. pl->result = (*pl->function) (pl->parameter);
  226307. pl->hasBeenExecuted = true;
  226308. }
  226309. }
  226310. else
  226311. {
  226312. jassertfalse; // should never get here!
  226313. }
  226314. }
  226315. @end
  226316. BEGIN_JUCE_NAMESPACE
  226317. void MessageManager::runDispatchLoop()
  226318. {
  226319. jassert (isThisTheMessageThread()); // must only be called by the message thread
  226320. runDispatchLoopUntil (-1);
  226321. }
  226322. void MessageManager::stopDispatchLoop()
  226323. {
  226324. exit (0); // iPhone apps get no mercy..
  226325. }
  226326. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  226327. {
  226328. const ScopedAutoReleasePool pool;
  226329. jassert (isThisTheMessageThread()); // must only be called by the message thread
  226330. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  226331. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  226332. while (! quitMessagePosted)
  226333. {
  226334. const ScopedAutoReleasePool pool;
  226335. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  226336. beforeDate: endDate];
  226337. if (millisecondsToRunFor >= 0 && Time::getMillisecondCounter() >= endTime)
  226338. break;
  226339. }
  226340. return ! quitMessagePosted;
  226341. }
  226342. static CFRunLoopRef runLoop = 0;
  226343. static CFRunLoopSourceRef runLoopSource = 0;
  226344. static Array <void*, CriticalSection>* pendingMessages = 0;
  226345. static JuceCustomMessageHandler* juceCustomMessageHandler = 0;
  226346. static void runLoopSourceCallback (void*)
  226347. {
  226348. if (pendingMessages != 0)
  226349. {
  226350. int numDispatched = 0;
  226351. do
  226352. {
  226353. void* const nextMessage = pendingMessages->remove (0);
  226354. if (nextMessage == 0)
  226355. return;
  226356. const ScopedAutoReleasePool pool;
  226357. MessageManager::getInstance()->deliverMessage (nextMessage);
  226358. } while (++numDispatched <= 4);
  226359. CFRunLoopSourceSignal (runLoopSource);
  226360. CFRunLoopWakeUp (runLoop);
  226361. }
  226362. }
  226363. void MessageManager::doPlatformSpecificInitialisation()
  226364. {
  226365. pendingMessages = new Array <void*, CriticalSection>();
  226366. runLoop = CFRunLoopGetCurrent();
  226367. CFRunLoopSourceContext sourceContext;
  226368. zerostruct (sourceContext);
  226369. sourceContext.perform = runLoopSourceCallback;
  226370. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  226371. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  226372. if (juceCustomMessageHandler == 0)
  226373. juceCustomMessageHandler = [[JuceCustomMessageHandler alloc] init];
  226374. }
  226375. void MessageManager::doPlatformSpecificShutdown()
  226376. {
  226377. CFRunLoopSourceInvalidate (runLoopSource);
  226378. CFRelease (runLoopSource);
  226379. runLoopSource = 0;
  226380. if (pendingMessages != 0)
  226381. {
  226382. while (pendingMessages->size() > 0)
  226383. delete ((Message*) pendingMessages->remove(0));
  226384. deleteAndZero (pendingMessages);
  226385. }
  226386. if (juceCustomMessageHandler != 0)
  226387. {
  226388. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceCustomMessageHandler];
  226389. [juceCustomMessageHandler release];
  226390. juceCustomMessageHandler = 0;
  226391. }
  226392. }
  226393. bool juce_postMessageToSystemQueue (void* message)
  226394. {
  226395. if (pendingMessages != 0)
  226396. {
  226397. pendingMessages->add (message);
  226398. CFRunLoopSourceSignal (runLoopSource);
  226399. CFRunLoopWakeUp (runLoop);
  226400. }
  226401. return true;
  226402. }
  226403. void MessageManager::broadcastMessage (const String& value) throw()
  226404. {
  226405. }
  226406. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  226407. void* data)
  226408. {
  226409. if (isThisTheMessageThread())
  226410. {
  226411. return (*callback) (data);
  226412. }
  226413. else
  226414. {
  226415. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  226416. // deadlock because the message manager is blocked from running, so can never
  226417. // call your function..
  226418. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  226419. const ScopedAutoReleasePool pool;
  226420. CallbackMessagePayload cmp;
  226421. cmp.function = callback;
  226422. cmp.parameter = data;
  226423. cmp.result = 0;
  226424. cmp.hasBeenExecuted = false;
  226425. [juceCustomMessageHandler performSelectorOnMainThread: @selector (performCallback:)
  226426. withObject: [NSData dataWithBytesNoCopy: &cmp
  226427. length: sizeof (cmp)
  226428. freeWhenDone: NO]
  226429. waitUntilDone: YES];
  226430. return cmp.result;
  226431. }
  226432. }
  226433. #endif
  226434. /*** End of inlined file: juce_iphone_MessageManager.mm ***/
  226435. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  226436. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226437. // compiled on its own).
  226438. #if JUCE_INCLUDED_FILE
  226439. #if JUCE_MAC
  226440. END_JUCE_NAMESPACE
  226441. using namespace JUCE_NAMESPACE;
  226442. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  226443. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  226444. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  226445. #else
  226446. @interface JuceFileChooserDelegate : NSObject
  226447. #endif
  226448. {
  226449. StringArray* filters;
  226450. }
  226451. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  226452. - (void) dealloc;
  226453. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  226454. @end
  226455. @implementation JuceFileChooserDelegate
  226456. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  226457. {
  226458. [super init];
  226459. filters = filters_;
  226460. return self;
  226461. }
  226462. - (void) dealloc
  226463. {
  226464. delete filters;
  226465. [super dealloc];
  226466. }
  226467. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  226468. {
  226469. (void) sender;
  226470. const File f (nsStringToJuce (filename));
  226471. for (int i = filters->size(); --i >= 0;)
  226472. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  226473. return true;
  226474. return f.isDirectory();
  226475. }
  226476. @end
  226477. BEGIN_JUCE_NAMESPACE
  226478. void FileChooser::showPlatformDialog (Array<File>& results,
  226479. const String& title,
  226480. const File& currentFileOrDirectory,
  226481. const String& filter,
  226482. bool selectsDirectory,
  226483. bool selectsFiles,
  226484. bool isSaveDialogue,
  226485. bool warnAboutOverwritingExistingFiles,
  226486. bool selectMultipleFiles,
  226487. FilePreviewComponent* extraInfoComponent)
  226488. {
  226489. const ScopedAutoReleasePool pool;
  226490. StringArray* filters = new StringArray();
  226491. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  226492. filters->trim();
  226493. filters->removeEmptyStrings();
  226494. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  226495. [delegate autorelease];
  226496. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  226497. : [NSOpenPanel openPanel];
  226498. [panel setTitle: juceStringToNS (title)];
  226499. if (! isSaveDialogue)
  226500. {
  226501. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  226502. [openPanel setCanChooseDirectories: selectsDirectory];
  226503. [openPanel setCanChooseFiles: selectsFiles];
  226504. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  226505. }
  226506. [panel setDelegate: delegate];
  226507. if (isSaveDialogue || selectsDirectory)
  226508. [panel setCanCreateDirectories: YES];
  226509. String directory, filename;
  226510. if (currentFileOrDirectory.isDirectory())
  226511. {
  226512. directory = currentFileOrDirectory.getFullPathName();
  226513. }
  226514. else
  226515. {
  226516. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  226517. filename = currentFileOrDirectory.getFileName();
  226518. }
  226519. if ([panel runModalForDirectory: juceStringToNS (directory)
  226520. file: juceStringToNS (filename)]
  226521. == NSOKButton)
  226522. {
  226523. if (isSaveDialogue)
  226524. {
  226525. results.add (File (nsStringToJuce ([panel filename])));
  226526. }
  226527. else
  226528. {
  226529. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  226530. NSArray* urls = [openPanel filenames];
  226531. for (unsigned int i = 0; i < [urls count]; ++i)
  226532. {
  226533. NSString* f = [urls objectAtIndex: i];
  226534. results.add (File (nsStringToJuce (f)));
  226535. }
  226536. }
  226537. }
  226538. [panel setDelegate: nil];
  226539. }
  226540. #else
  226541. void FileChooser::showPlatformDialog (Array<File>& results,
  226542. const String& title,
  226543. const File& currentFileOrDirectory,
  226544. const String& filter,
  226545. bool selectsDirectory,
  226546. bool selectsFiles,
  226547. bool isSaveDialogue,
  226548. bool warnAboutOverwritingExistingFiles,
  226549. bool selectMultipleFiles,
  226550. FilePreviewComponent* extraInfoComponent)
  226551. {
  226552. const ScopedAutoReleasePool pool;
  226553. jassertfalse; //xxx to do
  226554. }
  226555. #endif
  226556. #endif
  226557. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  226558. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  226559. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226560. // compiled on its own).
  226561. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  226562. #if JUCE_MAC
  226563. END_JUCE_NAMESPACE
  226564. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  226565. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  226566. {
  226567. CriticalSection* contextLock;
  226568. bool needsUpdate;
  226569. }
  226570. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  226571. - (bool) makeActive;
  226572. - (void) makeInactive;
  226573. - (void) reshape;
  226574. @end
  226575. @implementation ThreadSafeNSOpenGLView
  226576. - (id) initWithFrame: (NSRect) frameRect
  226577. pixelFormat: (NSOpenGLPixelFormat*) format
  226578. {
  226579. contextLock = new CriticalSection();
  226580. self = [super initWithFrame: frameRect pixelFormat: format];
  226581. if (self != nil)
  226582. [[NSNotificationCenter defaultCenter] addObserver: self
  226583. selector: @selector (_surfaceNeedsUpdate:)
  226584. name: NSViewGlobalFrameDidChangeNotification
  226585. object: self];
  226586. return self;
  226587. }
  226588. - (void) dealloc
  226589. {
  226590. [[NSNotificationCenter defaultCenter] removeObserver: self];
  226591. delete contextLock;
  226592. [super dealloc];
  226593. }
  226594. - (bool) makeActive
  226595. {
  226596. const ScopedLock sl (*contextLock);
  226597. if ([self openGLContext] == 0)
  226598. return false;
  226599. [[self openGLContext] makeCurrentContext];
  226600. if (needsUpdate)
  226601. {
  226602. [super update];
  226603. needsUpdate = false;
  226604. }
  226605. return true;
  226606. }
  226607. - (void) makeInactive
  226608. {
  226609. const ScopedLock sl (*contextLock);
  226610. [NSOpenGLContext clearCurrentContext];
  226611. }
  226612. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  226613. {
  226614. const ScopedLock sl (*contextLock);
  226615. needsUpdate = true;
  226616. }
  226617. - (void) update
  226618. {
  226619. const ScopedLock sl (*contextLock);
  226620. needsUpdate = true;
  226621. }
  226622. - (void) reshape
  226623. {
  226624. const ScopedLock sl (*contextLock);
  226625. needsUpdate = true;
  226626. }
  226627. @end
  226628. BEGIN_JUCE_NAMESPACE
  226629. class WindowedGLContext : public OpenGLContext
  226630. {
  226631. public:
  226632. WindowedGLContext (Component* const component,
  226633. const OpenGLPixelFormat& pixelFormat_,
  226634. NSOpenGLContext* sharedContext)
  226635. : renderContext (0),
  226636. pixelFormat (pixelFormat_)
  226637. {
  226638. jassert (component != 0);
  226639. NSOpenGLPixelFormatAttribute attribs [64];
  226640. int n = 0;
  226641. attribs[n++] = NSOpenGLPFADoubleBuffer;
  226642. attribs[n++] = NSOpenGLPFAAccelerated;
  226643. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  226644. attribs[n++] = NSOpenGLPFAColorSize;
  226645. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  226646. pixelFormat.greenBits,
  226647. pixelFormat.blueBits);
  226648. attribs[n++] = NSOpenGLPFAAlphaSize;
  226649. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  226650. attribs[n++] = NSOpenGLPFADepthSize;
  226651. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  226652. attribs[n++] = NSOpenGLPFAStencilSize;
  226653. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  226654. attribs[n++] = NSOpenGLPFAAccumSize;
  226655. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  226656. pixelFormat.accumulationBufferGreenBits,
  226657. pixelFormat.accumulationBufferBlueBits,
  226658. pixelFormat.accumulationBufferAlphaBits);
  226659. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  226660. attribs[n++] = NSOpenGLPFASampleBuffers;
  226661. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  226662. attribs[n++] = NSOpenGLPFAClosestPolicy;
  226663. attribs[n++] = NSOpenGLPFANoRecovery;
  226664. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  226665. NSOpenGLPixelFormat* format
  226666. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  226667. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  226668. pixelFormat: format];
  226669. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  226670. shareContext: sharedContext] autorelease];
  226671. const GLint swapInterval = 1;
  226672. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  226673. [view setOpenGLContext: renderContext];
  226674. [renderContext setView: view];
  226675. [format release];
  226676. viewHolder = new NSViewComponentInternal (view, component);
  226677. }
  226678. ~WindowedGLContext()
  226679. {
  226680. makeInactive();
  226681. [renderContext clearDrawable];
  226682. viewHolder = 0;
  226683. }
  226684. bool makeActive() const throw()
  226685. {
  226686. jassert (renderContext != 0);
  226687. [view makeActive];
  226688. return isActive();
  226689. }
  226690. bool makeInactive() const throw()
  226691. {
  226692. [view makeInactive];
  226693. return true;
  226694. }
  226695. bool isActive() const throw()
  226696. {
  226697. return [NSOpenGLContext currentContext] == renderContext;
  226698. }
  226699. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  226700. void* getRawContext() const throw() { return renderContext; }
  226701. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  226702. {
  226703. }
  226704. void swapBuffers()
  226705. {
  226706. [renderContext flushBuffer];
  226707. }
  226708. bool setSwapInterval (const int numFramesPerSwap)
  226709. {
  226710. [renderContext setValues: (const GLint*) &numFramesPerSwap
  226711. forParameter: NSOpenGLCPSwapInterval];
  226712. return true;
  226713. }
  226714. int getSwapInterval() const
  226715. {
  226716. GLint numFrames = 0;
  226717. [renderContext getValues: &numFrames
  226718. forParameter: NSOpenGLCPSwapInterval];
  226719. return numFrames;
  226720. }
  226721. void repaint()
  226722. {
  226723. // we need to invalidate the juce view that holds this gl view, to make it
  226724. // cause a repaint callback
  226725. NSView* v = (NSView*) viewHolder->view;
  226726. NSRect r = [v frame];
  226727. // bit of a bodge here.. if we only invalidate the area of the gl component,
  226728. // it's completely covered by the NSOpenGLView, so the OS throws away the
  226729. // repaint message, thus never causing our paint() callback, and never repainting
  226730. // the comp. So invalidating just a little bit around the edge helps..
  226731. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  226732. }
  226733. void* getNativeWindowHandle() const { return viewHolder->view; }
  226734. juce_UseDebuggingNewOperator
  226735. NSOpenGLContext* renderContext;
  226736. ThreadSafeNSOpenGLView* view;
  226737. private:
  226738. OpenGLPixelFormat pixelFormat;
  226739. ScopedPointer <NSViewComponentInternal> viewHolder;
  226740. WindowedGLContext (const WindowedGLContext&);
  226741. WindowedGLContext& operator= (const WindowedGLContext&);
  226742. };
  226743. OpenGLContext* OpenGLComponent::createContext()
  226744. {
  226745. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  226746. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  226747. return (c->renderContext != 0) ? c.release() : 0;
  226748. }
  226749. void* OpenGLComponent::getNativeWindowHandle() const
  226750. {
  226751. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  226752. : 0;
  226753. }
  226754. void juce_glViewport (const int w, const int h)
  226755. {
  226756. glViewport (0, 0, w, h);
  226757. }
  226758. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  226759. OwnedArray <OpenGLPixelFormat>& results)
  226760. {
  226761. /* GLint attribs [64];
  226762. int n = 0;
  226763. attribs[n++] = AGL_RGBA;
  226764. attribs[n++] = AGL_DOUBLEBUFFER;
  226765. attribs[n++] = AGL_ACCELERATED;
  226766. attribs[n++] = AGL_NO_RECOVERY;
  226767. attribs[n++] = AGL_NONE;
  226768. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  226769. while (p != 0)
  226770. {
  226771. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  226772. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  226773. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  226774. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  226775. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  226776. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  226777. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  226778. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  226779. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  226780. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  226781. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  226782. results.add (pf);
  226783. p = aglNextPixelFormat (p);
  226784. }*/
  226785. //jassertfalse //xxx can't see how you do this in cocoa!
  226786. }
  226787. #else
  226788. END_JUCE_NAMESPACE
  226789. @interface JuceGLView : UIView
  226790. {
  226791. }
  226792. + (Class) layerClass;
  226793. @end
  226794. @implementation JuceGLView
  226795. + (Class) layerClass
  226796. {
  226797. return [CAEAGLLayer class];
  226798. }
  226799. @end
  226800. BEGIN_JUCE_NAMESPACE
  226801. class GLESContext : public OpenGLContext
  226802. {
  226803. public:
  226804. GLESContext (UIViewComponentPeer* peer,
  226805. Component* const component_,
  226806. const OpenGLPixelFormat& pixelFormat_,
  226807. const GLESContext* const sharedContext,
  226808. NSUInteger apiType)
  226809. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  226810. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  226811. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  226812. {
  226813. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  226814. view.opaque = YES;
  226815. view.hidden = NO;
  226816. view.backgroundColor = [UIColor blackColor];
  226817. view.userInteractionEnabled = NO;
  226818. glLayer = (CAEAGLLayer*) [view layer];
  226819. [peer->view addSubview: view];
  226820. if (sharedContext != 0)
  226821. context = [[EAGLContext alloc] initWithAPI: apiType
  226822. sharegroup: [sharedContext->context sharegroup]];
  226823. else
  226824. context = [[EAGLContext alloc] initWithAPI: apiType];
  226825. createGLBuffers();
  226826. }
  226827. ~GLESContext()
  226828. {
  226829. makeInactive();
  226830. [context release];
  226831. [view removeFromSuperview];
  226832. [view release];
  226833. freeGLBuffers();
  226834. }
  226835. bool makeActive() const throw()
  226836. {
  226837. jassert (context != 0);
  226838. [EAGLContext setCurrentContext: context];
  226839. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  226840. return true;
  226841. }
  226842. void swapBuffers()
  226843. {
  226844. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  226845. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  226846. }
  226847. bool makeInactive() const throw()
  226848. {
  226849. return [EAGLContext setCurrentContext: nil];
  226850. }
  226851. bool isActive() const throw()
  226852. {
  226853. return [EAGLContext currentContext] == context;
  226854. }
  226855. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  226856. void* getRawContext() const throw() { return glLayer; }
  226857. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  226858. {
  226859. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  226860. if (lastWidth != w || lastHeight != h)
  226861. {
  226862. lastWidth = w;
  226863. lastHeight = h;
  226864. freeGLBuffers();
  226865. createGLBuffers();
  226866. }
  226867. }
  226868. bool setSwapInterval (const int numFramesPerSwap)
  226869. {
  226870. numFrames = numFramesPerSwap;
  226871. return true;
  226872. }
  226873. int getSwapInterval() const
  226874. {
  226875. return numFrames;
  226876. }
  226877. void repaint()
  226878. {
  226879. }
  226880. void createGLBuffers()
  226881. {
  226882. makeActive();
  226883. glGenFramebuffersOES (1, &frameBufferHandle);
  226884. glGenRenderbuffersOES (1, &colorBufferHandle);
  226885. glGenRenderbuffersOES (1, &depthBufferHandle);
  226886. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  226887. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  226888. GLint width, height;
  226889. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  226890. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  226891. if (useDepthBuffer)
  226892. {
  226893. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  226894. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  226895. }
  226896. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  226897. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  226898. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  226899. if (useDepthBuffer)
  226900. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  226901. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  226902. }
  226903. void freeGLBuffers()
  226904. {
  226905. if (frameBufferHandle != 0)
  226906. {
  226907. glDeleteFramebuffersOES (1, &frameBufferHandle);
  226908. frameBufferHandle = 0;
  226909. }
  226910. if (colorBufferHandle != 0)
  226911. {
  226912. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  226913. colorBufferHandle = 0;
  226914. }
  226915. if (depthBufferHandle != 0)
  226916. {
  226917. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  226918. depthBufferHandle = 0;
  226919. }
  226920. }
  226921. juce_UseDebuggingNewOperator
  226922. private:
  226923. Component::SafePointer<Component> component;
  226924. OpenGLPixelFormat pixelFormat;
  226925. JuceGLView* view;
  226926. CAEAGLLayer* glLayer;
  226927. EAGLContext* context;
  226928. bool useDepthBuffer;
  226929. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  226930. int numFrames;
  226931. int lastWidth, lastHeight;
  226932. GLESContext (const GLESContext&);
  226933. GLESContext& operator= (const GLESContext&);
  226934. };
  226935. OpenGLContext* OpenGLComponent::createContext()
  226936. {
  226937. ScopedAutoReleasePool pool;
  226938. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  226939. if (peer != 0)
  226940. return new GLESContext (peer, this, preferredPixelFormat,
  226941. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  226942. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  226943. return 0;
  226944. }
  226945. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  226946. OwnedArray <OpenGLPixelFormat>& /*results*/)
  226947. {
  226948. }
  226949. void juce_glViewport (const int w, const int h)
  226950. {
  226951. glViewport (0, 0, w, h);
  226952. }
  226953. #endif
  226954. #endif
  226955. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  226956. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  226957. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226958. // compiled on its own).
  226959. #if JUCE_INCLUDED_FILE
  226960. #if JUCE_MAC
  226961. namespace MouseCursorHelpers
  226962. {
  226963. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  226964. {
  226965. NSImage* im = CoreGraphicsImage::createNSImage (image);
  226966. NSCursor* c = [[NSCursor alloc] initWithImage: im
  226967. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  226968. [im release];
  226969. return c;
  226970. }
  226971. static void* fromWebKitFile (const char* filename, float hx, float hy)
  226972. {
  226973. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  226974. BufferedInputStream buf (&fileStream, 4096, false);
  226975. PNGImageFormat pngFormat;
  226976. Image im (pngFormat.decodeImage (buf));
  226977. if (im.isValid())
  226978. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  226979. jassertfalse;
  226980. return 0;
  226981. }
  226982. }
  226983. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  226984. {
  226985. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  226986. }
  226987. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  226988. {
  226989. const ScopedAutoReleasePool pool;
  226990. NSCursor* c = 0;
  226991. switch (type)
  226992. {
  226993. case NormalCursor: c = [NSCursor arrowCursor]; break;
  226994. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  226995. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  226996. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  226997. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  226998. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  226999. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  227000. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  227001. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  227002. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  227003. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  227004. case UpDownResizeCursor:
  227005. case TopEdgeResizeCursor:
  227006. case BottomEdgeResizeCursor:
  227007. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  227008. case TopLeftCornerResizeCursor:
  227009. case BottomRightCornerResizeCursor:
  227010. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  227011. case TopRightCornerResizeCursor:
  227012. case BottomLeftCornerResizeCursor:
  227013. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  227014. case UpDownLeftRightResizeCursor:
  227015. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  227016. default:
  227017. jassertfalse;
  227018. break;
  227019. }
  227020. [c retain];
  227021. return c;
  227022. }
  227023. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  227024. {
  227025. [((NSCursor*) cursorHandle) release];
  227026. }
  227027. void MouseCursor::showInAllWindows() const
  227028. {
  227029. showInWindow (0);
  227030. }
  227031. void MouseCursor::showInWindow (ComponentPeer*) const
  227032. {
  227033. [((NSCursor*) getHandle()) set];
  227034. }
  227035. #else
  227036. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  227037. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  227038. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  227039. void MouseCursor::showInAllWindows() const {}
  227040. void MouseCursor::showInWindow (ComponentPeer*) const {}
  227041. #endif
  227042. #endif
  227043. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  227044. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  227045. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227046. // compiled on its own).
  227047. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  227048. #if JUCE_MAC
  227049. END_JUCE_NAMESPACE
  227050. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  227051. @interface DownloadClickDetector : NSObject
  227052. {
  227053. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  227054. }
  227055. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  227056. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  227057. request: (NSURLRequest*) request
  227058. frame: (WebFrame*) frame
  227059. decisionListener: (id<WebPolicyDecisionListener>) listener;
  227060. @end
  227061. @implementation DownloadClickDetector
  227062. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  227063. {
  227064. [super init];
  227065. ownerComponent = ownerComponent_;
  227066. return self;
  227067. }
  227068. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  227069. request: (NSURLRequest*) request
  227070. frame: (WebFrame*) frame
  227071. decisionListener: (id <WebPolicyDecisionListener>) listener
  227072. {
  227073. (void) sender;
  227074. (void) request;
  227075. (void) frame;
  227076. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  227077. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  227078. [listener use];
  227079. else
  227080. [listener ignore];
  227081. }
  227082. @end
  227083. BEGIN_JUCE_NAMESPACE
  227084. class WebBrowserComponentInternal : public NSViewComponent
  227085. {
  227086. public:
  227087. WebBrowserComponentInternal (WebBrowserComponent* owner)
  227088. {
  227089. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  227090. frameName: @""
  227091. groupName: @""];
  227092. setView (webView);
  227093. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  227094. [webView setPolicyDelegate: clickListener];
  227095. }
  227096. ~WebBrowserComponentInternal()
  227097. {
  227098. [webView setPolicyDelegate: nil];
  227099. [clickListener release];
  227100. setView (0);
  227101. }
  227102. void goToURL (const String& url,
  227103. const StringArray* headers,
  227104. const MemoryBlock* postData)
  227105. {
  227106. NSMutableURLRequest* r
  227107. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  227108. cachePolicy: NSURLRequestUseProtocolCachePolicy
  227109. timeoutInterval: 30.0];
  227110. if (postData != 0 && postData->getSize() > 0)
  227111. {
  227112. [r setHTTPMethod: @"POST"];
  227113. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  227114. length: postData->getSize()]];
  227115. }
  227116. if (headers != 0)
  227117. {
  227118. for (int i = 0; i < headers->size(); ++i)
  227119. {
  227120. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  227121. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  227122. [r setValue: juceStringToNS (headerValue)
  227123. forHTTPHeaderField: juceStringToNS (headerName)];
  227124. }
  227125. }
  227126. stop();
  227127. [[webView mainFrame] loadRequest: r];
  227128. }
  227129. void goBack()
  227130. {
  227131. [webView goBack];
  227132. }
  227133. void goForward()
  227134. {
  227135. [webView goForward];
  227136. }
  227137. void stop()
  227138. {
  227139. [webView stopLoading: nil];
  227140. }
  227141. void refresh()
  227142. {
  227143. [webView reload: nil];
  227144. }
  227145. private:
  227146. WebView* webView;
  227147. DownloadClickDetector* clickListener;
  227148. };
  227149. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  227150. : browser (0),
  227151. blankPageShown (false),
  227152. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  227153. {
  227154. setOpaque (true);
  227155. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  227156. }
  227157. WebBrowserComponent::~WebBrowserComponent()
  227158. {
  227159. deleteAndZero (browser);
  227160. }
  227161. void WebBrowserComponent::goToURL (const String& url,
  227162. const StringArray* headers,
  227163. const MemoryBlock* postData)
  227164. {
  227165. lastURL = url;
  227166. lastHeaders.clear();
  227167. if (headers != 0)
  227168. lastHeaders = *headers;
  227169. lastPostData.setSize (0);
  227170. if (postData != 0)
  227171. lastPostData = *postData;
  227172. blankPageShown = false;
  227173. browser->goToURL (url, headers, postData);
  227174. }
  227175. void WebBrowserComponent::stop()
  227176. {
  227177. browser->stop();
  227178. }
  227179. void WebBrowserComponent::goBack()
  227180. {
  227181. lastURL = String::empty;
  227182. blankPageShown = false;
  227183. browser->goBack();
  227184. }
  227185. void WebBrowserComponent::goForward()
  227186. {
  227187. lastURL = String::empty;
  227188. browser->goForward();
  227189. }
  227190. void WebBrowserComponent::refresh()
  227191. {
  227192. browser->refresh();
  227193. }
  227194. void WebBrowserComponent::paint (Graphics&)
  227195. {
  227196. }
  227197. void WebBrowserComponent::checkWindowAssociation()
  227198. {
  227199. if (isShowing())
  227200. {
  227201. if (blankPageShown)
  227202. goBack();
  227203. }
  227204. else
  227205. {
  227206. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  227207. {
  227208. // when the component becomes invisible, some stuff like flash
  227209. // carries on playing audio, so we need to force it onto a blank
  227210. // page to avoid this, (and send it back when it's made visible again).
  227211. blankPageShown = true;
  227212. browser->goToURL ("about:blank", 0, 0);
  227213. }
  227214. }
  227215. }
  227216. void WebBrowserComponent::reloadLastURL()
  227217. {
  227218. if (lastURL.isNotEmpty())
  227219. {
  227220. goToURL (lastURL, &lastHeaders, &lastPostData);
  227221. lastURL = String::empty;
  227222. }
  227223. }
  227224. void WebBrowserComponent::parentHierarchyChanged()
  227225. {
  227226. checkWindowAssociation();
  227227. }
  227228. void WebBrowserComponent::resized()
  227229. {
  227230. browser->setSize (getWidth(), getHeight());
  227231. }
  227232. void WebBrowserComponent::visibilityChanged()
  227233. {
  227234. checkWindowAssociation();
  227235. }
  227236. bool WebBrowserComponent::pageAboutToLoad (const String&)
  227237. {
  227238. return true;
  227239. }
  227240. #else
  227241. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  227242. {
  227243. }
  227244. WebBrowserComponent::~WebBrowserComponent()
  227245. {
  227246. }
  227247. void WebBrowserComponent::goToURL (const String& url,
  227248. const StringArray* headers,
  227249. const MemoryBlock* postData)
  227250. {
  227251. }
  227252. void WebBrowserComponent::stop()
  227253. {
  227254. }
  227255. void WebBrowserComponent::goBack()
  227256. {
  227257. }
  227258. void WebBrowserComponent::goForward()
  227259. {
  227260. }
  227261. void WebBrowserComponent::refresh()
  227262. {
  227263. }
  227264. void WebBrowserComponent::paint (Graphics& g)
  227265. {
  227266. }
  227267. void WebBrowserComponent::checkWindowAssociation()
  227268. {
  227269. }
  227270. void WebBrowserComponent::reloadLastURL()
  227271. {
  227272. }
  227273. void WebBrowserComponent::parentHierarchyChanged()
  227274. {
  227275. }
  227276. void WebBrowserComponent::resized()
  227277. {
  227278. }
  227279. void WebBrowserComponent::visibilityChanged()
  227280. {
  227281. }
  227282. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  227283. {
  227284. return true;
  227285. }
  227286. #endif
  227287. #endif
  227288. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  227289. /*** Start of inlined file: juce_iphone_Audio.cpp ***/
  227290. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227291. // compiled on its own).
  227292. #if JUCE_INCLUDED_FILE
  227293. class IPhoneAudioIODevice : public AudioIODevice
  227294. {
  227295. public:
  227296. IPhoneAudioIODevice (const String& deviceName)
  227297. : AudioIODevice (deviceName, "Audio"),
  227298. audioUnit (0),
  227299. isRunning (false),
  227300. callback (0),
  227301. actualBufferSize (0),
  227302. floatData (1, 2)
  227303. {
  227304. numInputChannels = 2;
  227305. numOutputChannels = 2;
  227306. preferredBufferSize = 0;
  227307. AudioSessionInitialize (0, 0, interruptionListenerStatic, this);
  227308. updateDeviceInfo();
  227309. }
  227310. ~IPhoneAudioIODevice()
  227311. {
  227312. close();
  227313. }
  227314. const StringArray getOutputChannelNames()
  227315. {
  227316. StringArray s;
  227317. s.add ("Left");
  227318. s.add ("Right");
  227319. return s;
  227320. }
  227321. const StringArray getInputChannelNames()
  227322. {
  227323. StringArray s;
  227324. if (audioInputIsAvailable)
  227325. {
  227326. s.add ("Left");
  227327. s.add ("Right");
  227328. }
  227329. return s;
  227330. }
  227331. int getNumSampleRates()
  227332. {
  227333. return 1;
  227334. }
  227335. double getSampleRate (int index)
  227336. {
  227337. return sampleRate;
  227338. }
  227339. int getNumBufferSizesAvailable()
  227340. {
  227341. return 1;
  227342. }
  227343. int getBufferSizeSamples (int index)
  227344. {
  227345. return getDefaultBufferSize();
  227346. }
  227347. int getDefaultBufferSize()
  227348. {
  227349. return 1024;
  227350. }
  227351. const String open (const BigInteger& inputChannels,
  227352. const BigInteger& outputChannels,
  227353. double sampleRate,
  227354. int bufferSize)
  227355. {
  227356. close();
  227357. lastError = String::empty;
  227358. preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  227359. // xxx set up channel mapping
  227360. activeOutputChans = outputChannels;
  227361. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  227362. numOutputChannels = activeOutputChans.countNumberOfSetBits();
  227363. monoOutputChannelNumber = activeOutputChans.findNextSetBit (0);
  227364. activeInputChans = inputChannels;
  227365. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  227366. numInputChannels = activeInputChans.countNumberOfSetBits();
  227367. monoInputChannelNumber = activeInputChans.findNextSetBit (0);
  227368. AudioSessionSetActive (true);
  227369. UInt32 audioCategory = kAudioSessionCategory_PlayAndRecord;
  227370. AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (audioCategory), &audioCategory);
  227371. AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange, propertyChangedStatic, this);
  227372. fixAudioRouteIfSetToReceiver();
  227373. updateDeviceInfo();
  227374. Float32 bufferDuration = preferredBufferSize / sampleRate;
  227375. AudioSessionSetProperty (kAudioSessionProperty_PreferredHardwareIOBufferDuration, sizeof (bufferDuration), &bufferDuration);
  227376. actualBufferSize = preferredBufferSize;
  227377. prepareFloatBuffers();
  227378. isRunning = true;
  227379. propertyChanged (0, 0, 0); // creates and starts the AU
  227380. lastError = audioUnit != 0 ? "" : "Couldn't open the device";
  227381. return lastError;
  227382. }
  227383. void close()
  227384. {
  227385. if (isRunning)
  227386. {
  227387. isRunning = false;
  227388. AudioSessionSetActive (false);
  227389. if (audioUnit != 0)
  227390. {
  227391. AudioComponentInstanceDispose (audioUnit);
  227392. audioUnit = 0;
  227393. }
  227394. }
  227395. }
  227396. bool isOpen()
  227397. {
  227398. return isRunning;
  227399. }
  227400. int getCurrentBufferSizeSamples()
  227401. {
  227402. return actualBufferSize;
  227403. }
  227404. double getCurrentSampleRate()
  227405. {
  227406. return sampleRate;
  227407. }
  227408. int getCurrentBitDepth()
  227409. {
  227410. return 16;
  227411. }
  227412. const BigInteger getActiveOutputChannels() const
  227413. {
  227414. return activeOutputChans;
  227415. }
  227416. const BigInteger getActiveInputChannels() const
  227417. {
  227418. return activeInputChans;
  227419. }
  227420. int getOutputLatencyInSamples()
  227421. {
  227422. return 0; //xxx
  227423. }
  227424. int getInputLatencyInSamples()
  227425. {
  227426. return 0; //xxx
  227427. }
  227428. void start (AudioIODeviceCallback* callback_)
  227429. {
  227430. if (isRunning && callback != callback_)
  227431. {
  227432. if (callback_ != 0)
  227433. callback_->audioDeviceAboutToStart (this);
  227434. const ScopedLock sl (callbackLock);
  227435. callback = callback_;
  227436. }
  227437. }
  227438. void stop()
  227439. {
  227440. if (isRunning)
  227441. {
  227442. AudioIODeviceCallback* lastCallback;
  227443. {
  227444. const ScopedLock sl (callbackLock);
  227445. lastCallback = callback;
  227446. callback = 0;
  227447. }
  227448. if (lastCallback != 0)
  227449. lastCallback->audioDeviceStopped();
  227450. }
  227451. }
  227452. bool isPlaying()
  227453. {
  227454. return isRunning && callback != 0;
  227455. }
  227456. const String getLastError()
  227457. {
  227458. return lastError;
  227459. }
  227460. private:
  227461. CriticalSection callbackLock;
  227462. Float64 sampleRate;
  227463. int numInputChannels, numOutputChannels;
  227464. int preferredBufferSize;
  227465. int actualBufferSize;
  227466. bool isRunning;
  227467. String lastError;
  227468. AudioStreamBasicDescription format;
  227469. AudioUnit audioUnit;
  227470. UInt32 audioInputIsAvailable;
  227471. AudioIODeviceCallback* callback;
  227472. BigInteger activeOutputChans, activeInputChans;
  227473. AudioSampleBuffer floatData;
  227474. float* inputChannels[3];
  227475. float* outputChannels[3];
  227476. bool monoInputChannelNumber, monoOutputChannelNumber;
  227477. void prepareFloatBuffers()
  227478. {
  227479. floatData.setSize (numInputChannels + numOutputChannels, actualBufferSize);
  227480. zerostruct (inputChannels);
  227481. zerostruct (outputChannels);
  227482. for (int i = 0; i < numInputChannels; ++i)
  227483. inputChannels[i] = floatData.getSampleData (i);
  227484. for (int i = 0; i < numOutputChannels; ++i)
  227485. outputChannels[i] = floatData.getSampleData (i + numInputChannels);
  227486. }
  227487. OSStatus process (AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  227488. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  227489. {
  227490. OSStatus err = noErr;
  227491. if (audioInputIsAvailable)
  227492. err = AudioUnitRender (audioUnit, ioActionFlags, inTimeStamp, 1, inNumberFrames, ioData);
  227493. const ScopedLock sl (callbackLock);
  227494. if (callback != 0)
  227495. {
  227496. if (audioInputIsAvailable && numInputChannels > 0)
  227497. {
  227498. short* shortData = (short*) ioData->mBuffers[0].mData;
  227499. if (numInputChannels >= 2)
  227500. {
  227501. for (UInt32 i = 0; i < inNumberFrames; ++i)
  227502. {
  227503. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  227504. inputChannels[1][i] = *shortData++ * (1.0f / 32768.0f);
  227505. }
  227506. }
  227507. else
  227508. {
  227509. if (monoInputChannelNumber > 0)
  227510. ++shortData;
  227511. for (UInt32 i = 0; i < inNumberFrames; ++i)
  227512. {
  227513. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  227514. ++shortData;
  227515. }
  227516. }
  227517. }
  227518. else
  227519. {
  227520. for (int i = numInputChannels; --i >= 0;)
  227521. zeromem (inputChannels[i], sizeof (float) * inNumberFrames);
  227522. }
  227523. callback->audioDeviceIOCallback ((const float**) inputChannels, numInputChannels,
  227524. outputChannels, numOutputChannels,
  227525. (int) inNumberFrames);
  227526. short* shortData = (short*) ioData->mBuffers[0].mData;
  227527. int n = 0;
  227528. if (numOutputChannels >= 2)
  227529. {
  227530. for (UInt32 i = 0; i < inNumberFrames; ++i)
  227531. {
  227532. shortData [n++] = (short) (outputChannels[0][i] * 32767.0f);
  227533. shortData [n++] = (short) (outputChannels[1][i] * 32767.0f);
  227534. }
  227535. }
  227536. else if (numOutputChannels == 1)
  227537. {
  227538. for (UInt32 i = 0; i < inNumberFrames; ++i)
  227539. {
  227540. const short s = (short) (outputChannels[monoOutputChannelNumber][i] * 32767.0f);
  227541. shortData [n++] = s;
  227542. shortData [n++] = s;
  227543. }
  227544. }
  227545. else
  227546. {
  227547. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  227548. }
  227549. }
  227550. else
  227551. {
  227552. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  227553. }
  227554. return err;
  227555. }
  227556. void updateDeviceInfo()
  227557. {
  227558. UInt32 size = sizeof (sampleRate);
  227559. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareSampleRate, &size, &sampleRate);
  227560. size = sizeof (audioInputIsAvailable);
  227561. AudioSessionGetProperty (kAudioSessionProperty_AudioInputAvailable, &size, &audioInputIsAvailable);
  227562. }
  227563. void propertyChanged (AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  227564. {
  227565. if (! isRunning)
  227566. return;
  227567. if (inPropertyValue != 0)
  227568. {
  227569. CFDictionaryRef routeChangeDictionary = (CFDictionaryRef) inPropertyValue;
  227570. CFNumberRef routeChangeReasonRef = (CFNumberRef) CFDictionaryGetValue (routeChangeDictionary,
  227571. CFSTR (kAudioSession_AudioRouteChangeKey_Reason));
  227572. SInt32 routeChangeReason;
  227573. CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);
  227574. if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable)
  227575. fixAudioRouteIfSetToReceiver();
  227576. }
  227577. updateDeviceInfo();
  227578. createAudioUnit();
  227579. AudioSessionSetActive (true);
  227580. if (audioUnit != 0)
  227581. {
  227582. UInt32 formatSize = sizeof (format);
  227583. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, &formatSize);
  227584. Float32 bufferDuration = preferredBufferSize / sampleRate;
  227585. UInt32 bufferDurationSize = sizeof (bufferDuration);
  227586. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareIOBufferDuration, &bufferDurationSize, &bufferDurationSize);
  227587. actualBufferSize = (int) (sampleRate * bufferDuration + 0.5);
  227588. AudioOutputUnitStart (audioUnit);
  227589. }
  227590. }
  227591. void interruptionListener (UInt32 inInterruption)
  227592. {
  227593. /*if (inInterruption == kAudioSessionBeginInterruption)
  227594. {
  227595. isRunning = false;
  227596. AudioOutputUnitStop (audioUnit);
  227597. if (juce_iPhoneShowModalAlert ("Audio Interrupted",
  227598. "This could have been interrupted by another application or by unplugging a headset",
  227599. @"Resume",
  227600. @"Cancel"))
  227601. {
  227602. isRunning = true;
  227603. propertyChanged (0, 0, 0);
  227604. }
  227605. }*/
  227606. if (inInterruption == kAudioSessionEndInterruption)
  227607. {
  227608. isRunning = true;
  227609. AudioSessionSetActive (true);
  227610. AudioOutputUnitStart (audioUnit);
  227611. }
  227612. }
  227613. static OSStatus processStatic (void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  227614. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  227615. {
  227616. return ((IPhoneAudioIODevice*) inRefCon)->process (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  227617. }
  227618. static void propertyChangedStatic (void* inClientData, AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  227619. {
  227620. ((IPhoneAudioIODevice*) inClientData)->propertyChanged (inID, inDataSize, inPropertyValue);
  227621. }
  227622. static void interruptionListenerStatic (void* inClientData, UInt32 inInterruption)
  227623. {
  227624. ((IPhoneAudioIODevice*) inClientData)->interruptionListener (inInterruption);
  227625. }
  227626. void resetFormat (const int numChannels)
  227627. {
  227628. memset (&format, 0, sizeof (format));
  227629. format.mFormatID = kAudioFormatLinearPCM;
  227630. format.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
  227631. format.mBitsPerChannel = 8 * sizeof (short);
  227632. format.mChannelsPerFrame = 2;
  227633. format.mFramesPerPacket = 1;
  227634. format.mBytesPerFrame = format.mBytesPerPacket = 2 * sizeof (short);
  227635. }
  227636. bool createAudioUnit()
  227637. {
  227638. if (audioUnit != 0)
  227639. {
  227640. AudioComponentInstanceDispose (audioUnit);
  227641. audioUnit = 0;
  227642. }
  227643. resetFormat (2);
  227644. AudioComponentDescription desc;
  227645. desc.componentType = kAudioUnitType_Output;
  227646. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  227647. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  227648. desc.componentFlags = 0;
  227649. desc.componentFlagsMask = 0;
  227650. AudioComponent comp = AudioComponentFindNext (0, &desc);
  227651. AudioComponentInstanceNew (comp, &audioUnit);
  227652. if (audioUnit == 0)
  227653. return false;
  227654. const UInt32 one = 1;
  227655. AudioUnitSetProperty (audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &one, sizeof (one));
  227656. AudioChannelLayout layout;
  227657. layout.mChannelBitmap = 0;
  227658. layout.mNumberChannelDescriptions = 0;
  227659. layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  227660. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Input, 0, &layout, sizeof (layout));
  227661. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Output, 0, &layout, sizeof (layout));
  227662. AURenderCallbackStruct inputProc;
  227663. inputProc.inputProc = processStatic;
  227664. inputProc.inputProcRefCon = this;
  227665. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &inputProc, sizeof (inputProc));
  227666. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof (format));
  227667. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, sizeof (format));
  227668. AudioUnitInitialize (audioUnit);
  227669. return true;
  227670. }
  227671. // If the routing is set to go through the receiver (i.e. the speaker, but quiet), this re-routes it
  227672. // to make it loud. Needed because by default when using an input + output, the output is kept quiet.
  227673. static void fixAudioRouteIfSetToReceiver()
  227674. {
  227675. CFStringRef audioRoute = 0;
  227676. UInt32 propertySize = sizeof (audioRoute);
  227677. if (AudioSessionGetProperty (kAudioSessionProperty_AudioRoute, &propertySize, &audioRoute) == noErr)
  227678. {
  227679. NSString* route = (NSString*) audioRoute;
  227680. //DBG ("audio route: " + nsStringToJuce (route));
  227681. if ([route hasPrefix: @"Receiver"])
  227682. {
  227683. UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
  227684. AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride), &audioRouteOverride);
  227685. }
  227686. CFRelease (audioRoute);
  227687. }
  227688. }
  227689. IPhoneAudioIODevice (const IPhoneAudioIODevice&);
  227690. IPhoneAudioIODevice& operator= (const IPhoneAudioIODevice&);
  227691. };
  227692. class IPhoneAudioIODeviceType : public AudioIODeviceType
  227693. {
  227694. public:
  227695. IPhoneAudioIODeviceType()
  227696. : AudioIODeviceType ("iPhone Audio")
  227697. {
  227698. }
  227699. ~IPhoneAudioIODeviceType()
  227700. {
  227701. }
  227702. void scanForDevices()
  227703. {
  227704. }
  227705. const StringArray getDeviceNames (bool wantInputNames) const
  227706. {
  227707. StringArray s;
  227708. s.add ("iPhone Audio");
  227709. return s;
  227710. }
  227711. int getDefaultDeviceIndex (bool forInput) const
  227712. {
  227713. return 0;
  227714. }
  227715. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  227716. {
  227717. return device != 0 ? 0 : -1;
  227718. }
  227719. bool hasSeparateInputsAndOutputs() const { return false; }
  227720. AudioIODevice* createDevice (const String& outputDeviceName,
  227721. const String& inputDeviceName)
  227722. {
  227723. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  227724. {
  227725. return new IPhoneAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  227726. : inputDeviceName);
  227727. }
  227728. return 0;
  227729. }
  227730. juce_UseDebuggingNewOperator
  227731. private:
  227732. IPhoneAudioIODeviceType (const IPhoneAudioIODeviceType&);
  227733. IPhoneAudioIODeviceType& operator= (const IPhoneAudioIODeviceType&);
  227734. };
  227735. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio()
  227736. {
  227737. return new IPhoneAudioIODeviceType();
  227738. }
  227739. #endif
  227740. /*** End of inlined file: juce_iphone_Audio.cpp ***/
  227741. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  227742. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227743. // compiled on its own).
  227744. #if JUCE_INCLUDED_FILE
  227745. #if JUCE_MAC
  227746. #undef log
  227747. #define log(a) Logger::writeToLog(a)
  227748. static bool logAnyErrorsMidi (const OSStatus err, const int lineNum)
  227749. {
  227750. if (err == noErr)
  227751. return true;
  227752. log ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  227753. jassertfalse;
  227754. return false;
  227755. }
  227756. #undef OK
  227757. #define OK(a) logAnyErrorsMidi(a, __LINE__)
  227758. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  227759. {
  227760. String result;
  227761. CFStringRef str = 0;
  227762. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  227763. if (str != 0)
  227764. {
  227765. result = PlatformUtilities::cfStringToJuceString (str);
  227766. CFRelease (str);
  227767. str = 0;
  227768. }
  227769. MIDIEntityRef entity = 0;
  227770. MIDIEndpointGetEntity (endpoint, &entity);
  227771. if (entity == 0)
  227772. return result; // probably virtual
  227773. if (result.isEmpty())
  227774. {
  227775. // endpoint name has zero length - try the entity
  227776. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  227777. if (str != 0)
  227778. {
  227779. result += PlatformUtilities::cfStringToJuceString (str);
  227780. CFRelease (str);
  227781. str = 0;
  227782. }
  227783. }
  227784. // now consider the device's name
  227785. MIDIDeviceRef device = 0;
  227786. MIDIEntityGetDevice (entity, &device);
  227787. if (device == 0)
  227788. return result;
  227789. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  227790. if (str != 0)
  227791. {
  227792. const String s (PlatformUtilities::cfStringToJuceString (str));
  227793. CFRelease (str);
  227794. // if an external device has only one entity, throw away
  227795. // the endpoint name and just use the device name
  227796. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  227797. {
  227798. result = s;
  227799. }
  227800. else if (! result.startsWithIgnoreCase (s))
  227801. {
  227802. // prepend the device name to the entity name
  227803. result = (s + " " + result).trimEnd();
  227804. }
  227805. }
  227806. return result;
  227807. }
  227808. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  227809. {
  227810. String result;
  227811. // Does the endpoint have connections?
  227812. CFDataRef connections = 0;
  227813. int numConnections = 0;
  227814. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  227815. if (connections != 0)
  227816. {
  227817. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  227818. if (numConnections > 0)
  227819. {
  227820. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  227821. for (int i = 0; i < numConnections; ++i, ++pid)
  227822. {
  227823. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  227824. MIDIObjectRef connObject;
  227825. MIDIObjectType connObjectType;
  227826. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  227827. if (err == noErr)
  227828. {
  227829. String s;
  227830. if (connObjectType == kMIDIObjectType_ExternalSource
  227831. || connObjectType == kMIDIObjectType_ExternalDestination)
  227832. {
  227833. // Connected to an external device's endpoint (10.3 and later).
  227834. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  227835. }
  227836. else
  227837. {
  227838. // Connected to an external device (10.2) (or something else, catch-all)
  227839. CFStringRef str = 0;
  227840. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  227841. if (str != 0)
  227842. {
  227843. s = PlatformUtilities::cfStringToJuceString (str);
  227844. CFRelease (str);
  227845. }
  227846. }
  227847. if (s.isNotEmpty())
  227848. {
  227849. if (result.isNotEmpty())
  227850. result += ", ";
  227851. result += s;
  227852. }
  227853. }
  227854. }
  227855. }
  227856. CFRelease (connections);
  227857. }
  227858. if (result.isNotEmpty())
  227859. return result;
  227860. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  227861. return getEndpointName (endpoint, false);
  227862. }
  227863. const StringArray MidiOutput::getDevices()
  227864. {
  227865. StringArray s;
  227866. const ItemCount num = MIDIGetNumberOfDestinations();
  227867. for (ItemCount i = 0; i < num; ++i)
  227868. {
  227869. MIDIEndpointRef dest = MIDIGetDestination (i);
  227870. if (dest != 0)
  227871. {
  227872. String name (getConnectedEndpointName (dest));
  227873. if (name.isEmpty())
  227874. name = "<error>";
  227875. s.add (name);
  227876. }
  227877. else
  227878. {
  227879. s.add ("<error>");
  227880. }
  227881. }
  227882. return s;
  227883. }
  227884. int MidiOutput::getDefaultDeviceIndex()
  227885. {
  227886. return 0;
  227887. }
  227888. static MIDIClientRef globalMidiClient;
  227889. static bool hasGlobalClientBeenCreated = false;
  227890. static bool makeSureClientExists()
  227891. {
  227892. if (! hasGlobalClientBeenCreated)
  227893. {
  227894. String name ("JUCE");
  227895. if (JUCEApplication::getInstance() != 0)
  227896. name = JUCEApplication::getInstance()->getApplicationName();
  227897. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  227898. hasGlobalClientBeenCreated = OK (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  227899. CFRelease (appName);
  227900. }
  227901. return hasGlobalClientBeenCreated;
  227902. }
  227903. class MidiPortAndEndpoint
  227904. {
  227905. public:
  227906. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  227907. : port (port_), endPoint (endPoint_)
  227908. {
  227909. }
  227910. ~MidiPortAndEndpoint()
  227911. {
  227912. if (port != 0)
  227913. MIDIPortDispose (port);
  227914. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  227915. MIDIEndpointDispose (endPoint);
  227916. }
  227917. MIDIPortRef port;
  227918. MIDIEndpointRef endPoint;
  227919. };
  227920. MidiOutput* MidiOutput::openDevice (int index)
  227921. {
  227922. MidiOutput* mo = 0;
  227923. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  227924. {
  227925. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  227926. CFStringRef pname;
  227927. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  227928. {
  227929. log ("CoreMidi - opening out: " + PlatformUtilities::cfStringToJuceString (pname));
  227930. if (makeSureClientExists())
  227931. {
  227932. MIDIPortRef port;
  227933. if (OK (MIDIOutputPortCreate (globalMidiClient, pname, &port)))
  227934. {
  227935. mo = new MidiOutput();
  227936. mo->internal = new MidiPortAndEndpoint (port, endPoint);
  227937. }
  227938. }
  227939. CFRelease (pname);
  227940. }
  227941. }
  227942. return mo;
  227943. }
  227944. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  227945. {
  227946. MidiOutput* mo = 0;
  227947. if (makeSureClientExists())
  227948. {
  227949. MIDIEndpointRef endPoint;
  227950. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  227951. if (OK (MIDISourceCreate (globalMidiClient, name, &endPoint)))
  227952. {
  227953. mo = new MidiOutput();
  227954. mo->internal = new MidiPortAndEndpoint (0, endPoint);
  227955. }
  227956. CFRelease (name);
  227957. }
  227958. return mo;
  227959. }
  227960. MidiOutput::~MidiOutput()
  227961. {
  227962. delete (MidiPortAndEndpoint*) internal;
  227963. }
  227964. void MidiOutput::reset()
  227965. {
  227966. }
  227967. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  227968. {
  227969. return false;
  227970. }
  227971. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  227972. {
  227973. }
  227974. void MidiOutput::sendMessageNow (const MidiMessage& message)
  227975. {
  227976. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*) internal;
  227977. if (message.isSysEx())
  227978. {
  227979. const int maxPacketSize = 256;
  227980. int pos = 0, bytesLeft = message.getRawDataSize();
  227981. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  227982. HeapBlock <MIDIPacketList> packets;
  227983. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  227984. packets->numPackets = numPackets;
  227985. MIDIPacket* p = packets->packet;
  227986. for (int i = 0; i < numPackets; ++i)
  227987. {
  227988. p->timeStamp = 0;
  227989. p->length = jmin (maxPacketSize, bytesLeft);
  227990. memcpy (p->data, message.getRawData() + pos, p->length);
  227991. pos += p->length;
  227992. bytesLeft -= p->length;
  227993. p = MIDIPacketNext (p);
  227994. }
  227995. if (mpe->port != 0)
  227996. MIDISend (mpe->port, mpe->endPoint, packets);
  227997. else
  227998. MIDIReceived (mpe->endPoint, packets);
  227999. }
  228000. else
  228001. {
  228002. MIDIPacketList packets;
  228003. packets.numPackets = 1;
  228004. packets.packet[0].timeStamp = 0;
  228005. packets.packet[0].length = message.getRawDataSize();
  228006. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  228007. if (mpe->port != 0)
  228008. MIDISend (mpe->port, mpe->endPoint, &packets);
  228009. else
  228010. MIDIReceived (mpe->endPoint, &packets);
  228011. }
  228012. }
  228013. const StringArray MidiInput::getDevices()
  228014. {
  228015. StringArray s;
  228016. const ItemCount num = MIDIGetNumberOfSources();
  228017. for (ItemCount i = 0; i < num; ++i)
  228018. {
  228019. MIDIEndpointRef source = MIDIGetSource (i);
  228020. if (source != 0)
  228021. {
  228022. String name (getConnectedEndpointName (source));
  228023. if (name.isEmpty())
  228024. name = "<error>";
  228025. s.add (name);
  228026. }
  228027. else
  228028. {
  228029. s.add ("<error>");
  228030. }
  228031. }
  228032. return s;
  228033. }
  228034. int MidiInput::getDefaultDeviceIndex()
  228035. {
  228036. return 0;
  228037. }
  228038. struct MidiPortAndCallback
  228039. {
  228040. MidiInput* input;
  228041. MidiPortAndEndpoint* portAndEndpoint;
  228042. MidiInputCallback* callback;
  228043. MemoryBlock pendingData;
  228044. int pendingBytes;
  228045. double pendingDataTime;
  228046. bool active;
  228047. void processSysex (const uint8*& d, int& size, const double time)
  228048. {
  228049. if (*d == 0xf0)
  228050. {
  228051. pendingBytes = 0;
  228052. pendingDataTime = time;
  228053. }
  228054. pendingData.ensureSize (pendingBytes + size, false);
  228055. uint8* totalMessage = (uint8*) pendingData.getData();
  228056. uint8* dest = totalMessage + pendingBytes;
  228057. while (size > 0)
  228058. {
  228059. if (pendingBytes > 0 && *d >= 0x80)
  228060. {
  228061. if (*d >= 0xfa || *d == 0xf8)
  228062. {
  228063. callback->handleIncomingMidiMessage (input, MidiMessage (*d, time));
  228064. ++d;
  228065. --size;
  228066. }
  228067. else
  228068. {
  228069. if (*d == 0xf7)
  228070. {
  228071. *dest++ = *d++;
  228072. pendingBytes++;
  228073. --size;
  228074. }
  228075. break;
  228076. }
  228077. }
  228078. else
  228079. {
  228080. *dest++ = *d++;
  228081. pendingBytes++;
  228082. --size;
  228083. }
  228084. }
  228085. if (totalMessage [pendingBytes - 1] == 0xf7)
  228086. {
  228087. callback->handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  228088. pendingBytes = 0;
  228089. }
  228090. else
  228091. {
  228092. callback->handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  228093. }
  228094. }
  228095. };
  228096. namespace CoreMidiCallbacks
  228097. {
  228098. static CriticalSection callbackLock;
  228099. static Array<void*> activeCallbacks;
  228100. }
  228101. static void midiInputProc (const MIDIPacketList* pktlist,
  228102. void* readProcRefCon,
  228103. void* /*srcConnRefCon*/)
  228104. {
  228105. double time = Time::getMillisecondCounterHiRes() * 0.001;
  228106. const double originalTime = time;
  228107. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) readProcRefCon;
  228108. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  228109. if (CoreMidiCallbacks::activeCallbacks.contains (mpc) && mpc->active)
  228110. {
  228111. const MIDIPacket* packet = &pktlist->packet[0];
  228112. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  228113. {
  228114. const uint8* d = (const uint8*) (packet->data);
  228115. int size = packet->length;
  228116. while (size > 0)
  228117. {
  228118. time = originalTime;
  228119. if (mpc->pendingBytes > 0 || d[0] == 0xf0)
  228120. {
  228121. mpc->processSysex (d, size, time);
  228122. }
  228123. else
  228124. {
  228125. int used = 0;
  228126. const MidiMessage m (d, size, used, 0, time);
  228127. if (used <= 0)
  228128. {
  228129. jassertfalse; // malformed midi message
  228130. break;
  228131. }
  228132. else
  228133. {
  228134. mpc->callback->handleIncomingMidiMessage (mpc->input, m);
  228135. }
  228136. size -= used;
  228137. d += used;
  228138. }
  228139. }
  228140. packet = MIDIPacketNext (packet);
  228141. }
  228142. }
  228143. }
  228144. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  228145. {
  228146. MidiInput* mi = 0;
  228147. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  228148. {
  228149. MIDIEndpointRef endPoint = MIDIGetSource (index);
  228150. if (endPoint != 0)
  228151. {
  228152. CFStringRef pname;
  228153. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  228154. {
  228155. log ("CoreMidi - opening inp: " + PlatformUtilities::cfStringToJuceString (pname));
  228156. if (makeSureClientExists())
  228157. {
  228158. MIDIPortRef port;
  228159. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  228160. mpc->active = false;
  228161. if (OK (MIDIInputPortCreate (globalMidiClient, pname, midiInputProc, mpc, &port)))
  228162. {
  228163. if (OK (MIDIPortConnectSource (port, endPoint, 0)))
  228164. {
  228165. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  228166. mpc->callback = callback;
  228167. mpc->pendingBytes = 0;
  228168. mpc->pendingData.ensureSize (128);
  228169. mi = new MidiInput (getDevices() [index]);
  228170. mpc->input = mi;
  228171. mi->internal = mpc;
  228172. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  228173. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  228174. }
  228175. else
  228176. {
  228177. OK (MIDIPortDispose (port));
  228178. }
  228179. }
  228180. }
  228181. }
  228182. CFRelease (pname);
  228183. }
  228184. }
  228185. return mi;
  228186. }
  228187. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  228188. {
  228189. MidiInput* mi = 0;
  228190. if (makeSureClientExists())
  228191. {
  228192. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  228193. mpc->active = false;
  228194. MIDIEndpointRef endPoint;
  228195. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  228196. if (OK (MIDIDestinationCreate (globalMidiClient, name, midiInputProc, mpc, &endPoint)))
  228197. {
  228198. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  228199. mpc->callback = callback;
  228200. mpc->pendingBytes = 0;
  228201. mpc->pendingData.ensureSize (128);
  228202. mi = new MidiInput (deviceName);
  228203. mpc->input = mi;
  228204. mi->internal = mpc;
  228205. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  228206. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  228207. }
  228208. CFRelease (name);
  228209. }
  228210. return mi;
  228211. }
  228212. MidiInput::MidiInput (const String& name_)
  228213. : name (name_)
  228214. {
  228215. }
  228216. MidiInput::~MidiInput()
  228217. {
  228218. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) internal;
  228219. mpc->active = false;
  228220. {
  228221. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  228222. CoreMidiCallbacks::activeCallbacks.removeValue (mpc);
  228223. }
  228224. if (mpc->portAndEndpoint->port != 0)
  228225. OK (MIDIPortDisconnectSource (mpc->portAndEndpoint->port, mpc->portAndEndpoint->endPoint));
  228226. delete mpc->portAndEndpoint;
  228227. delete mpc;
  228228. }
  228229. void MidiInput::start()
  228230. {
  228231. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  228232. ((MidiPortAndCallback*) internal)->active = true;
  228233. }
  228234. void MidiInput::stop()
  228235. {
  228236. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  228237. ((MidiPortAndCallback*) internal)->active = false;
  228238. }
  228239. #undef log
  228240. #else
  228241. MidiOutput::~MidiOutput()
  228242. {
  228243. }
  228244. void MidiOutput::reset()
  228245. {
  228246. }
  228247. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  228248. {
  228249. return false;
  228250. }
  228251. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  228252. {
  228253. }
  228254. void MidiOutput::sendMessageNow (const MidiMessage& message)
  228255. {
  228256. }
  228257. const StringArray MidiOutput::getDevices()
  228258. {
  228259. return StringArray();
  228260. }
  228261. MidiOutput* MidiOutput::openDevice (int index)
  228262. {
  228263. return 0;
  228264. }
  228265. const StringArray MidiInput::getDevices()
  228266. {
  228267. return StringArray();
  228268. }
  228269. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  228270. {
  228271. return 0;
  228272. }
  228273. #endif
  228274. #endif
  228275. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  228276. #else
  228277. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  228278. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228279. // compiled on its own).
  228280. #if JUCE_INCLUDED_FILE
  228281. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  228282. #define SUPPORT_10_4_FONTS 1
  228283. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  228284. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  228285. #define SUPPORT_ONLY_10_4_FONTS 1
  228286. #endif
  228287. END_JUCE_NAMESPACE
  228288. @interface NSFont (PrivateHack)
  228289. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  228290. @end
  228291. BEGIN_JUCE_NAMESPACE
  228292. #endif
  228293. class MacTypeface : public Typeface
  228294. {
  228295. public:
  228296. MacTypeface (const Font& font)
  228297. : Typeface (font.getTypefaceName())
  228298. {
  228299. const ScopedAutoReleasePool pool;
  228300. renderingTransform = CGAffineTransformIdentity;
  228301. bool needsItalicTransform = false;
  228302. #if JUCE_IPHONE
  228303. NSString* fontName = juceStringToNS (font.getTypefaceName());
  228304. if (font.isItalic() || font.isBold())
  228305. {
  228306. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  228307. for (NSString* i in familyFonts)
  228308. {
  228309. const String fn (nsStringToJuce (i));
  228310. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  228311. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  228312. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  228313. || afterDash.containsIgnoreCase ("italic")
  228314. || fn.endsWithIgnoreCase ("oblique")
  228315. || fn.endsWithIgnoreCase ("italic");
  228316. if (probablyBold == font.isBold()
  228317. && probablyItalic == font.isItalic())
  228318. {
  228319. fontName = i;
  228320. needsItalicTransform = false;
  228321. break;
  228322. }
  228323. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  228324. {
  228325. fontName = i;
  228326. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  228327. }
  228328. }
  228329. if (needsItalicTransform)
  228330. renderingTransform.c = 0.15f;
  228331. }
  228332. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  228333. const int ascender = abs (CGFontGetAscent (fontRef));
  228334. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  228335. ascent = ascender / totalHeight;
  228336. unitsToHeightScaleFactor = 1.0f / totalHeight;
  228337. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  228338. #else
  228339. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  228340. if (font.isItalic())
  228341. {
  228342. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  228343. toHaveTrait: NSItalicFontMask];
  228344. if (newFont == nsFont)
  228345. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  228346. nsFont = newFont;
  228347. }
  228348. if (font.isBold())
  228349. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  228350. [nsFont retain];
  228351. ascent = std::abs ((float) [nsFont ascender]);
  228352. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  228353. ascent /= totalSize;
  228354. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  228355. if (needsItalicTransform)
  228356. {
  228357. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  228358. renderingTransform.c = 0.15f;
  228359. }
  228360. #if SUPPORT_ONLY_10_4_FONTS
  228361. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  228362. if (atsFont == 0)
  228363. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  228364. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  228365. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  228366. unitsToHeightScaleFactor = 1.0f / totalHeight;
  228367. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  228368. #else
  228369. #if SUPPORT_10_4_FONTS
  228370. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  228371. {
  228372. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  228373. if (atsFont == 0)
  228374. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  228375. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  228376. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  228377. unitsToHeightScaleFactor = 1.0f / totalHeight;
  228378. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  228379. }
  228380. else
  228381. #endif
  228382. {
  228383. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  228384. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  228385. unitsToHeightScaleFactor = 1.0f / totalHeight;
  228386. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  228387. }
  228388. #endif
  228389. #endif
  228390. }
  228391. ~MacTypeface()
  228392. {
  228393. #if ! JUCE_IPHONE
  228394. [nsFont release];
  228395. #endif
  228396. if (fontRef != 0)
  228397. CGFontRelease (fontRef);
  228398. }
  228399. float getAscent() const
  228400. {
  228401. return ascent;
  228402. }
  228403. float getDescent() const
  228404. {
  228405. return 1.0f - ascent;
  228406. }
  228407. float getStringWidth (const String& text)
  228408. {
  228409. if (fontRef == 0 || text.isEmpty())
  228410. return 0;
  228411. const int length = text.length();
  228412. HeapBlock <CGGlyph> glyphs;
  228413. createGlyphsForString (text, length, glyphs);
  228414. float x = 0;
  228415. #if SUPPORT_ONLY_10_4_FONTS
  228416. HeapBlock <NSSize> advances (length);
  228417. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  228418. for (int i = 0; i < length; ++i)
  228419. x += advances[i].width;
  228420. #else
  228421. #if SUPPORT_10_4_FONTS
  228422. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  228423. {
  228424. HeapBlock <NSSize> advances (length);
  228425. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  228426. for (int i = 0; i < length; ++i)
  228427. x += advances[i].width;
  228428. }
  228429. else
  228430. #endif
  228431. {
  228432. HeapBlock <int> advances (length);
  228433. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  228434. for (int i = 0; i < length; ++i)
  228435. x += advances[i];
  228436. }
  228437. #endif
  228438. return x * unitsToHeightScaleFactor;
  228439. }
  228440. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  228441. {
  228442. xOffsets.add (0);
  228443. if (fontRef == 0 || text.isEmpty())
  228444. return;
  228445. const int length = text.length();
  228446. HeapBlock <CGGlyph> glyphs;
  228447. createGlyphsForString (text, length, glyphs);
  228448. #if SUPPORT_ONLY_10_4_FONTS
  228449. HeapBlock <NSSize> advances (length);
  228450. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  228451. int x = 0;
  228452. for (int i = 0; i < length; ++i)
  228453. {
  228454. x += advances[i].width;
  228455. xOffsets.add (x * unitsToHeightScaleFactor);
  228456. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  228457. }
  228458. #else
  228459. #if SUPPORT_10_4_FONTS
  228460. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  228461. {
  228462. HeapBlock <NSSize> advances (length);
  228463. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  228464. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  228465. float x = 0;
  228466. for (int i = 0; i < length; ++i)
  228467. {
  228468. x += advances[i].width;
  228469. xOffsets.add (x * unitsToHeightScaleFactor);
  228470. resultGlyphs.add (nsGlyphs[i]);
  228471. }
  228472. }
  228473. else
  228474. #endif
  228475. {
  228476. HeapBlock <int> advances (length);
  228477. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  228478. {
  228479. int x = 0;
  228480. for (int i = 0; i < length; ++i)
  228481. {
  228482. x += advances [i];
  228483. xOffsets.add (x * unitsToHeightScaleFactor);
  228484. resultGlyphs.add (glyphs[i]);
  228485. }
  228486. }
  228487. }
  228488. #endif
  228489. }
  228490. bool getOutlineForGlyph (int glyphNumber, Path& path)
  228491. {
  228492. #if JUCE_IPHONE
  228493. return false;
  228494. #else
  228495. if (nsFont == 0)
  228496. return false;
  228497. // we might need to apply a transform to the path, so it mustn't have anything else in it
  228498. jassert (path.isEmpty());
  228499. const ScopedAutoReleasePool pool;
  228500. NSBezierPath* bez = [NSBezierPath bezierPath];
  228501. [bez moveToPoint: NSMakePoint (0, 0)];
  228502. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  228503. inFont: nsFont];
  228504. for (int i = 0; i < [bez elementCount]; ++i)
  228505. {
  228506. NSPoint p[3];
  228507. switch ([bez elementAtIndex: i associatedPoints: p])
  228508. {
  228509. case NSMoveToBezierPathElement:
  228510. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  228511. break;
  228512. case NSLineToBezierPathElement:
  228513. path.lineTo ((float) p[0].x, (float) -p[0].y);
  228514. break;
  228515. case NSCurveToBezierPathElement:
  228516. 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);
  228517. break;
  228518. case NSClosePathBezierPathElement:
  228519. path.closeSubPath();
  228520. break;
  228521. default:
  228522. jassertfalse;
  228523. break;
  228524. }
  228525. }
  228526. path.applyTransform (pathTransform);
  228527. return true;
  228528. #endif
  228529. }
  228530. juce_UseDebuggingNewOperator
  228531. CGFontRef fontRef;
  228532. float fontHeightToCGSizeFactor;
  228533. CGAffineTransform renderingTransform;
  228534. private:
  228535. float ascent, unitsToHeightScaleFactor;
  228536. #if JUCE_IPHONE
  228537. #else
  228538. NSFont* nsFont;
  228539. AffineTransform pathTransform;
  228540. #endif
  228541. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  228542. {
  228543. #if SUPPORT_10_4_FONTS
  228544. #if ! SUPPORT_ONLY_10_4_FONTS
  228545. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  228546. #endif
  228547. {
  228548. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  228549. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  228550. for (int i = 0; i < length; ++i)
  228551. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  228552. return;
  228553. }
  228554. #endif
  228555. #if ! SUPPORT_ONLY_10_4_FONTS
  228556. if (charToGlyphMapper == 0)
  228557. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  228558. glyphs.malloc (length);
  228559. for (int i = 0; i < length; ++i)
  228560. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  228561. #endif
  228562. }
  228563. #if ! SUPPORT_ONLY_10_4_FONTS
  228564. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  228565. class CharToGlyphMapper
  228566. {
  228567. public:
  228568. CharToGlyphMapper (CGFontRef fontRef)
  228569. : segCount (0), endCode (0), startCode (0), idDelta (0),
  228570. idRangeOffset (0), glyphIndexes (0)
  228571. {
  228572. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  228573. if (cmapTable != 0)
  228574. {
  228575. const int numSubtables = getValue16 (cmapTable, 2);
  228576. for (int i = 0; i < numSubtables; ++i)
  228577. {
  228578. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  228579. {
  228580. const int offset = getValue32 (cmapTable, i * 8 + 8);
  228581. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  228582. {
  228583. const int length = getValue16 (cmapTable, offset + 2);
  228584. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  228585. segCount = segCountX2 / 2;
  228586. const int endCodeOffset = offset + 14;
  228587. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  228588. const int idDeltaOffset = startCodeOffset + segCountX2;
  228589. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  228590. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  228591. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  228592. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  228593. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  228594. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  228595. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  228596. }
  228597. break;
  228598. }
  228599. }
  228600. CFRelease (cmapTable);
  228601. }
  228602. }
  228603. ~CharToGlyphMapper()
  228604. {
  228605. if (endCode != 0)
  228606. {
  228607. CFRelease (endCode);
  228608. CFRelease (startCode);
  228609. CFRelease (idDelta);
  228610. CFRelease (idRangeOffset);
  228611. CFRelease (glyphIndexes);
  228612. }
  228613. }
  228614. int getGlyphForCharacter (const juce_wchar c) const
  228615. {
  228616. for (int i = 0; i < segCount; ++i)
  228617. {
  228618. if (getValue16 (endCode, i * 2) >= c)
  228619. {
  228620. const int start = getValue16 (startCode, i * 2);
  228621. if (start > c)
  228622. break;
  228623. const int delta = getValue16 (idDelta, i * 2);
  228624. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  228625. if (rangeOffset == 0)
  228626. return delta + c;
  228627. else
  228628. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  228629. }
  228630. }
  228631. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  228632. return jmax (-1, c - 29);
  228633. }
  228634. private:
  228635. int segCount;
  228636. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  228637. static uint16 getValue16 (CFDataRef data, const int index)
  228638. {
  228639. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  228640. }
  228641. static uint32 getValue32 (CFDataRef data, const int index)
  228642. {
  228643. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  228644. }
  228645. };
  228646. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  228647. #endif
  228648. MacTypeface (const MacTypeface&);
  228649. MacTypeface& operator= (const MacTypeface&);
  228650. };
  228651. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  228652. {
  228653. return new MacTypeface (font);
  228654. }
  228655. const StringArray Font::findAllTypefaceNames()
  228656. {
  228657. StringArray names;
  228658. const ScopedAutoReleasePool pool;
  228659. #if JUCE_IPHONE
  228660. NSArray* fonts = [UIFont familyNames];
  228661. #else
  228662. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  228663. #endif
  228664. for (unsigned int i = 0; i < [fonts count]; ++i)
  228665. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  228666. names.sort (true);
  228667. return names;
  228668. }
  228669. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  228670. {
  228671. #if JUCE_IPHONE
  228672. defaultSans = "Helvetica";
  228673. defaultSerif = "Times New Roman";
  228674. defaultFixed = "Courier New";
  228675. #else
  228676. defaultSans = "Lucida Grande";
  228677. defaultSerif = "Times New Roman";
  228678. defaultFixed = "Monaco";
  228679. #endif
  228680. }
  228681. #endif
  228682. /*** End of inlined file: juce_mac_Fonts.mm ***/
  228683. // (must go before juce_mac_CoreGraphicsContext.mm)
  228684. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  228685. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228686. // compiled on its own).
  228687. #if JUCE_INCLUDED_FILE
  228688. class CoreGraphicsImage : public Image::SharedImage
  228689. {
  228690. public:
  228691. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  228692. : Image::SharedImage (format_, width_, height_)
  228693. {
  228694. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  228695. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  228696. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  228697. imageData = imageDataAllocated;
  228698. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  228699. : CGColorSpaceCreateDeviceRGB();
  228700. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  228701. colourSpace, getCGImageFlags (format_));
  228702. CGColorSpaceRelease (colourSpace);
  228703. }
  228704. ~CoreGraphicsImage()
  228705. {
  228706. CGContextRelease (context);
  228707. }
  228708. Image::ImageType getType() const { return Image::NativeImage; }
  228709. LowLevelGraphicsContext* createLowLevelContext();
  228710. SharedImage* clone()
  228711. {
  228712. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  228713. memcpy (im->imageData, imageData, lineStride * height);
  228714. return im;
  228715. }
  228716. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  228717. {
  228718. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  228719. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  228720. {
  228721. return CGBitmapContextCreateImage (nativeImage->context);
  228722. }
  228723. else
  228724. {
  228725. const Image::BitmapData srcData (juceImage, 0, 0, juceImage.getWidth(), juceImage.getHeight());
  228726. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  228727. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  228728. 8, srcData.pixelStride * 8, srcData.lineStride,
  228729. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  228730. 0, true, kCGRenderingIntentDefault);
  228731. CGDataProviderRelease (provider);
  228732. return imageRef;
  228733. }
  228734. }
  228735. #if JUCE_MAC
  228736. static NSImage* createNSImage (const Image& image)
  228737. {
  228738. const ScopedAutoReleasePool pool;
  228739. NSImage* im = [[NSImage alloc] init];
  228740. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  228741. [im lockFocus];
  228742. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  228743. CGImageRef imageRef = createImage (image, false, colourSpace);
  228744. CGColorSpaceRelease (colourSpace);
  228745. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  228746. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  228747. CGImageRelease (imageRef);
  228748. [im unlockFocus];
  228749. return im;
  228750. }
  228751. #endif
  228752. CGContextRef context;
  228753. HeapBlock<uint8> imageDataAllocated;
  228754. private:
  228755. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  228756. {
  228757. #if JUCE_BIG_ENDIAN
  228758. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  228759. #else
  228760. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  228761. #endif
  228762. }
  228763. };
  228764. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  228765. {
  228766. #if USE_COREGRAPHICS_RENDERING
  228767. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  228768. #else
  228769. return createSoftwareImage (format, width, height, clearImage);
  228770. #endif
  228771. }
  228772. class CoreGraphicsContext : public LowLevelGraphicsContext
  228773. {
  228774. public:
  228775. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  228776. : context (context_),
  228777. flipHeight (flipHeight_),
  228778. state (new SavedState()),
  228779. numGradientLookupEntries (0),
  228780. lastClipRectIsValid (false)
  228781. {
  228782. CGContextRetain (context);
  228783. CGContextSaveGState(context);
  228784. CGContextSetShouldSmoothFonts (context, true);
  228785. CGContextSetShouldAntialias (context, true);
  228786. CGContextSetBlendMode (context, kCGBlendModeNormal);
  228787. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  228788. greyColourSpace = CGColorSpaceCreateDeviceGray();
  228789. gradientCallbacks.version = 0;
  228790. gradientCallbacks.evaluate = gradientCallback;
  228791. gradientCallbacks.releaseInfo = 0;
  228792. setFont (Font());
  228793. }
  228794. ~CoreGraphicsContext()
  228795. {
  228796. CGContextRestoreGState (context);
  228797. CGContextRelease (context);
  228798. CGColorSpaceRelease (rgbColourSpace);
  228799. CGColorSpaceRelease (greyColourSpace);
  228800. }
  228801. bool isVectorDevice() const { return false; }
  228802. void setOrigin (int x, int y)
  228803. {
  228804. CGContextTranslateCTM (context, x, -y);
  228805. if (lastClipRectIsValid)
  228806. lastClipRect.translate (-x, -y);
  228807. }
  228808. bool clipToRectangle (const Rectangle<int>& r)
  228809. {
  228810. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  228811. if (lastClipRectIsValid)
  228812. {
  228813. lastClipRect = lastClipRect.getIntersection (r);
  228814. return ! lastClipRect.isEmpty();
  228815. }
  228816. return ! isClipEmpty();
  228817. }
  228818. bool clipToRectangleList (const RectangleList& clipRegion)
  228819. {
  228820. if (clipRegion.isEmpty())
  228821. {
  228822. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  228823. lastClipRectIsValid = true;
  228824. lastClipRect = Rectangle<int>();
  228825. return false;
  228826. }
  228827. else
  228828. {
  228829. const int numRects = clipRegion.getNumRectangles();
  228830. HeapBlock <CGRect> rects (numRects);
  228831. for (int i = 0; i < numRects; ++i)
  228832. {
  228833. const Rectangle<int>& r = clipRegion.getRectangle(i);
  228834. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  228835. }
  228836. CGContextClipToRects (context, rects, numRects);
  228837. lastClipRectIsValid = false;
  228838. return ! isClipEmpty();
  228839. }
  228840. }
  228841. void excludeClipRectangle (const Rectangle<int>& r)
  228842. {
  228843. RectangleList remaining (getClipBounds());
  228844. remaining.subtract (r);
  228845. clipToRectangleList (remaining);
  228846. lastClipRectIsValid = false;
  228847. }
  228848. void clipToPath (const Path& path, const AffineTransform& transform)
  228849. {
  228850. createPath (path, transform);
  228851. CGContextClip (context);
  228852. lastClipRectIsValid = false;
  228853. }
  228854. void clipToImageAlpha (const Image& sourceImage, const Rectangle<int>& srcClip, const AffineTransform& transform)
  228855. {
  228856. if (! transform.isSingularity())
  228857. {
  228858. Image singleChannelImage (sourceImage);
  228859. if (sourceImage.getFormat() != Image::SingleChannel)
  228860. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  228861. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  228862. if (srcClip != sourceImage.getBounds())
  228863. {
  228864. CGImageRef fullImage = image;
  228865. image = CGImageCreateWithImageInRect (fullImage, CGRectMake (srcClip.getX(), srcClip.getY(),
  228866. srcClip.getWidth(), srcClip.getHeight()));
  228867. CGImageRelease (fullImage);
  228868. }
  228869. flip();
  228870. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, srcClip.getHeight()).followedBy (transform));
  228871. applyTransform (t);
  228872. CGRect r = CGRectMake (0, 0, srcClip.getWidth(), srcClip.getHeight());
  228873. CGContextClipToMask (context, r, image);
  228874. applyTransform (t.inverted());
  228875. flip();
  228876. CGImageRelease (image);
  228877. lastClipRectIsValid = false;
  228878. }
  228879. }
  228880. bool clipRegionIntersects (const Rectangle<int>& r)
  228881. {
  228882. return getClipBounds().intersects (r);
  228883. }
  228884. const Rectangle<int> getClipBounds() const
  228885. {
  228886. if (! lastClipRectIsValid)
  228887. {
  228888. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  228889. lastClipRectIsValid = true;
  228890. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  228891. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  228892. roundToInt (bounds.size.width),
  228893. roundToInt (bounds.size.height));
  228894. }
  228895. return lastClipRect;
  228896. }
  228897. bool isClipEmpty() const
  228898. {
  228899. return getClipBounds().isEmpty();
  228900. }
  228901. void saveState()
  228902. {
  228903. CGContextSaveGState (context);
  228904. stateStack.add (new SavedState (*state));
  228905. }
  228906. void restoreState()
  228907. {
  228908. CGContextRestoreGState (context);
  228909. SavedState* const top = stateStack.getLast();
  228910. if (top != 0)
  228911. {
  228912. state = top;
  228913. stateStack.removeLast (1, false);
  228914. lastClipRectIsValid = false;
  228915. }
  228916. else
  228917. {
  228918. jassertfalse; // trying to pop with an empty stack!
  228919. }
  228920. }
  228921. void setFill (const FillType& fillType)
  228922. {
  228923. state->fillType = fillType;
  228924. if (fillType.isColour())
  228925. {
  228926. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  228927. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  228928. CGContextSetAlpha (context, 1.0f);
  228929. }
  228930. }
  228931. void setOpacity (float newOpacity)
  228932. {
  228933. state->fillType.setOpacity (newOpacity);
  228934. setFill (state->fillType);
  228935. }
  228936. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  228937. {
  228938. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  228939. ? kCGInterpolationLow
  228940. : kCGInterpolationHigh);
  228941. }
  228942. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  228943. {
  228944. CGRect cgRect = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  228945. if (replaceExistingContents)
  228946. {
  228947. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  228948. CGContextClearRect (context, cgRect);
  228949. #else
  228950. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  228951. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  228952. CGContextClearRect (context, cgRect);
  228953. else
  228954. #endif
  228955. CGContextSetBlendMode (context, kCGBlendModeCopy);
  228956. #endif
  228957. fillRect (r, false);
  228958. CGContextSetBlendMode (context, kCGBlendModeNormal);
  228959. }
  228960. else
  228961. {
  228962. if (state->fillType.isColour())
  228963. {
  228964. CGContextFillRect (context, cgRect);
  228965. }
  228966. else if (state->fillType.isGradient())
  228967. {
  228968. CGContextSaveGState (context);
  228969. CGContextClipToRect (context, cgRect);
  228970. drawGradient();
  228971. CGContextRestoreGState (context);
  228972. }
  228973. else
  228974. {
  228975. CGContextSaveGState (context);
  228976. CGContextClipToRect (context, cgRect);
  228977. drawImage (state->fillType.image, state->fillType.image.getBounds(), state->fillType.transform, true);
  228978. CGContextRestoreGState (context);
  228979. }
  228980. }
  228981. }
  228982. void fillPath (const Path& path, const AffineTransform& transform)
  228983. {
  228984. CGContextSaveGState (context);
  228985. if (state->fillType.isColour())
  228986. {
  228987. flip();
  228988. applyTransform (transform);
  228989. createPath (path);
  228990. if (path.isUsingNonZeroWinding())
  228991. CGContextFillPath (context);
  228992. else
  228993. CGContextEOFillPath (context);
  228994. }
  228995. else
  228996. {
  228997. createPath (path, transform);
  228998. if (path.isUsingNonZeroWinding())
  228999. CGContextClip (context);
  229000. else
  229001. CGContextEOClip (context);
  229002. if (state->fillType.isGradient())
  229003. drawGradient();
  229004. else
  229005. drawImage (state->fillType.image, state->fillType.image.getBounds(), state->fillType.transform, true);
  229006. }
  229007. CGContextRestoreGState (context);
  229008. }
  229009. void drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  229010. const AffineTransform& transform, const bool fillEntireClipAsTiles)
  229011. {
  229012. jassert (sourceImage.getBounds().contains (srcClip));
  229013. CGImageRef fullImage = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  229014. CGImageRef image = fullImage;
  229015. if (srcClip != sourceImage.getBounds())
  229016. {
  229017. image = CGImageCreateWithImageInRect (fullImage, CGRectMake (srcClip.getX(), srcClip.getY(),
  229018. srcClip.getWidth(), srcClip.getHeight()));
  229019. CGImageRelease (fullImage);
  229020. }
  229021. CGContextSaveGState (context);
  229022. CGContextSetAlpha (context, state->fillType.getOpacity());
  229023. flip();
  229024. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, srcClip.getHeight()).followedBy (transform));
  229025. CGRect imageRect = CGRectMake (0, 0, srcClip.getWidth(), srcClip.getHeight());
  229026. if (fillEntireClipAsTiles)
  229027. {
  229028. #if JUCE_IPHONE
  229029. CGContextDrawTiledImage (context, imageRect, image);
  229030. #else
  229031. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  229032. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  229033. // if it's doing a transformation - it's quicker to just draw lots of images manually
  229034. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  229035. CGContextDrawTiledImage (context, imageRect, image);
  229036. else
  229037. #endif
  229038. {
  229039. // Fallback to manually doing a tiled fill on 10.4
  229040. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  229041. const int iw = srcClip.getWidth();
  229042. const int ih = srcClip.getHeight();
  229043. int x = 0, y = 0;
  229044. while (x > clip.origin.x) x -= iw;
  229045. while (y > clip.origin.y) y -= ih;
  229046. const int right = (int) (clip.origin.x + clip.size.width);
  229047. const int bottom = (int) (clip.origin.y + clip.size.height);
  229048. while (y < bottom)
  229049. {
  229050. for (int x2 = x; x2 < right; x2 += iw)
  229051. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  229052. y += ih;
  229053. }
  229054. }
  229055. #endif
  229056. }
  229057. else
  229058. {
  229059. CGContextDrawImage (context, imageRect, image);
  229060. }
  229061. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  229062. CGContextRestoreGState (context);
  229063. }
  229064. void drawLine (const Line<float>& line)
  229065. {
  229066. CGContextSetLineCap (context, kCGLineCapSquare);
  229067. CGContextSetLineWidth (context, 1.0f);
  229068. CGContextSetRGBStrokeColor (context,
  229069. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  229070. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  229071. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  229072. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  229073. CGContextStrokeLineSegments (context, cgLine, 1);
  229074. }
  229075. void drawVerticalLine (const int x, float top, float bottom)
  229076. {
  229077. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  229078. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  229079. #else
  229080. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  229081. // the x co-ord slightly to trick it..
  229082. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  229083. #endif
  229084. }
  229085. void drawHorizontalLine (const int y, float left, float right)
  229086. {
  229087. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  229088. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  229089. #else
  229090. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  229091. // the x co-ord slightly to trick it..
  229092. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  229093. #endif
  229094. }
  229095. void setFont (const Font& newFont)
  229096. {
  229097. if (state->font != newFont)
  229098. {
  229099. state->fontRef = 0;
  229100. state->font = newFont;
  229101. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  229102. if (mf != 0)
  229103. {
  229104. state->fontRef = mf->fontRef;
  229105. CGContextSetFont (context, state->fontRef);
  229106. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  229107. state->fontTransform = mf->renderingTransform;
  229108. state->fontTransform.a *= state->font.getHorizontalScale();
  229109. CGContextSetTextMatrix (context, state->fontTransform);
  229110. }
  229111. }
  229112. }
  229113. const Font getFont()
  229114. {
  229115. return state->font;
  229116. }
  229117. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  229118. {
  229119. if (state->fontRef != 0 && state->fillType.isColour())
  229120. {
  229121. if (transform.isOnlyTranslation())
  229122. {
  229123. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  229124. CGGlyph g = glyphNumber;
  229125. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  229126. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  229127. }
  229128. else
  229129. {
  229130. CGContextSaveGState (context);
  229131. flip();
  229132. applyTransform (transform);
  229133. CGAffineTransform t = state->fontTransform;
  229134. t.d = -t.d;
  229135. CGContextSetTextMatrix (context, t);
  229136. CGGlyph g = glyphNumber;
  229137. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  229138. CGContextRestoreGState (context);
  229139. }
  229140. }
  229141. else
  229142. {
  229143. Path p;
  229144. Font& f = state->font;
  229145. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  229146. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  229147. .followedBy (transform));
  229148. }
  229149. }
  229150. private:
  229151. CGContextRef context;
  229152. const CGFloat flipHeight;
  229153. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  229154. CGFunctionCallbacks gradientCallbacks;
  229155. mutable Rectangle<int> lastClipRect;
  229156. mutable bool lastClipRectIsValid;
  229157. struct SavedState
  229158. {
  229159. SavedState()
  229160. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  229161. {
  229162. }
  229163. SavedState (const SavedState& other)
  229164. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  229165. fontTransform (other.fontTransform)
  229166. {
  229167. }
  229168. ~SavedState()
  229169. {
  229170. }
  229171. FillType fillType;
  229172. Font font;
  229173. CGFontRef fontRef;
  229174. CGAffineTransform fontTransform;
  229175. };
  229176. ScopedPointer <SavedState> state;
  229177. OwnedArray <SavedState> stateStack;
  229178. HeapBlock <PixelARGB> gradientLookupTable;
  229179. int numGradientLookupEntries;
  229180. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  229181. {
  229182. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  229183. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  229184. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  229185. colour.unpremultiply();
  229186. outData[0] = colour.getRed() / 255.0f;
  229187. outData[1] = colour.getGreen() / 255.0f;
  229188. outData[2] = colour.getBlue() / 255.0f;
  229189. outData[3] = colour.getAlpha() / 255.0f;
  229190. }
  229191. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  229192. {
  229193. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  229194. --numGradientLookupEntries;
  229195. CGShadingRef result = 0;
  229196. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  229197. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  229198. if (gradient.isRadial)
  229199. {
  229200. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  229201. p1, gradient.point1.getDistanceFrom (gradient.point2),
  229202. function, true, true);
  229203. }
  229204. else
  229205. {
  229206. result = CGShadingCreateAxial (rgbColourSpace, p1,
  229207. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  229208. function, true, true);
  229209. }
  229210. CGFunctionRelease (function);
  229211. return result;
  229212. }
  229213. void drawGradient()
  229214. {
  229215. flip();
  229216. applyTransform (state->fillType.transform);
  229217. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  229218. // you draw a gradient with high quality interp enabled).
  229219. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  229220. CGContextSetAlpha (context, state->fillType.getOpacity());
  229221. CGContextDrawShading (context, shading);
  229222. CGShadingRelease (shading);
  229223. }
  229224. void createPath (const Path& path) const
  229225. {
  229226. CGContextBeginPath (context);
  229227. Path::Iterator i (path);
  229228. while (i.next())
  229229. {
  229230. switch (i.elementType)
  229231. {
  229232. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  229233. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  229234. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  229235. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  229236. case Path::Iterator::closePath: CGContextClosePath (context); break;
  229237. default: jassertfalse; break;
  229238. }
  229239. }
  229240. }
  229241. void createPath (const Path& path, const AffineTransform& transform) const
  229242. {
  229243. CGContextBeginPath (context);
  229244. Path::Iterator i (path);
  229245. while (i.next())
  229246. {
  229247. switch (i.elementType)
  229248. {
  229249. case Path::Iterator::startNewSubPath:
  229250. transform.transformPoint (i.x1, i.y1);
  229251. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  229252. break;
  229253. case Path::Iterator::lineTo:
  229254. transform.transformPoint (i.x1, i.y1);
  229255. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  229256. break;
  229257. case Path::Iterator::quadraticTo:
  229258. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  229259. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  229260. break;
  229261. case Path::Iterator::cubicTo:
  229262. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  229263. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  229264. break;
  229265. case Path::Iterator::closePath:
  229266. CGContextClosePath (context); break;
  229267. default:
  229268. jassertfalse;
  229269. break;
  229270. }
  229271. }
  229272. }
  229273. void flip() const
  229274. {
  229275. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  229276. }
  229277. void applyTransform (const AffineTransform& transform) const
  229278. {
  229279. CGAffineTransform t;
  229280. t.a = transform.mat00;
  229281. t.b = transform.mat10;
  229282. t.c = transform.mat01;
  229283. t.d = transform.mat11;
  229284. t.tx = transform.mat02;
  229285. t.ty = transform.mat12;
  229286. CGContextConcatCTM (context, t);
  229287. }
  229288. CoreGraphicsContext (const CoreGraphicsContext&);
  229289. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  229290. };
  229291. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  229292. {
  229293. return new CoreGraphicsContext (context, height);
  229294. }
  229295. #endif
  229296. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  229297. /*** Start of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  229298. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229299. // compiled on its own).
  229300. #if JUCE_INCLUDED_FILE
  229301. class NSViewComponentPeer;
  229302. END_JUCE_NAMESPACE
  229303. @interface NSEvent (JuceDeviceDelta)
  229304. - (float) deviceDeltaX;
  229305. - (float) deviceDeltaY;
  229306. @end
  229307. #define JuceNSView MakeObjCClassName(JuceNSView)
  229308. @interface JuceNSView : NSView<NSTextInput>
  229309. {
  229310. @public
  229311. NSViewComponentPeer* owner;
  229312. NSNotificationCenter* notificationCenter;
  229313. String* stringBeingComposed;
  229314. bool textWasInserted;
  229315. }
  229316. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner withFrame: (NSRect) frame;
  229317. - (void) dealloc;
  229318. - (BOOL) isOpaque;
  229319. - (void) drawRect: (NSRect) r;
  229320. - (void) mouseDown: (NSEvent*) ev;
  229321. - (void) asyncMouseDown: (NSEvent*) ev;
  229322. - (void) mouseUp: (NSEvent*) ev;
  229323. - (void) asyncMouseUp: (NSEvent*) ev;
  229324. - (void) mouseDragged: (NSEvent*) ev;
  229325. - (void) mouseMoved: (NSEvent*) ev;
  229326. - (void) mouseEntered: (NSEvent*) ev;
  229327. - (void) mouseExited: (NSEvent*) ev;
  229328. - (void) rightMouseDown: (NSEvent*) ev;
  229329. - (void) rightMouseDragged: (NSEvent*) ev;
  229330. - (void) rightMouseUp: (NSEvent*) ev;
  229331. - (void) otherMouseDown: (NSEvent*) ev;
  229332. - (void) otherMouseDragged: (NSEvent*) ev;
  229333. - (void) otherMouseUp: (NSEvent*) ev;
  229334. - (void) scrollWheel: (NSEvent*) ev;
  229335. - (BOOL) acceptsFirstMouse: (NSEvent*) ev;
  229336. - (void) frameChanged: (NSNotification*) n;
  229337. - (void) viewDidMoveToWindow;
  229338. - (void) keyDown: (NSEvent*) ev;
  229339. - (void) keyUp: (NSEvent*) ev;
  229340. // NSTextInput Methods
  229341. - (void) insertText: (id) aString;
  229342. - (void) doCommandBySelector: (SEL) aSelector;
  229343. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selRange;
  229344. - (void) unmarkText;
  229345. - (BOOL) hasMarkedText;
  229346. - (long) conversationIdentifier;
  229347. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange;
  229348. - (NSRange) markedRange;
  229349. - (NSRange) selectedRange;
  229350. - (NSRect) firstRectForCharacterRange: (NSRange) theRange;
  229351. - (unsigned int) characterIndexForPoint: (NSPoint) thePoint;
  229352. - (NSArray*) validAttributesForMarkedText;
  229353. - (void) flagsChanged: (NSEvent*) ev;
  229354. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229355. - (BOOL) performKeyEquivalent: (NSEvent*) ev;
  229356. #endif
  229357. - (BOOL) becomeFirstResponder;
  229358. - (BOOL) resignFirstResponder;
  229359. - (BOOL) acceptsFirstResponder;
  229360. - (void) asyncRepaint: (id) rect;
  229361. - (NSArray*) getSupportedDragTypes;
  229362. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender;
  229363. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender;
  229364. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender;
  229365. - (void) draggingEnded: (id <NSDraggingInfo>) sender;
  229366. - (void) draggingExited: (id <NSDraggingInfo>) sender;
  229367. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender;
  229368. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender;
  229369. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender;
  229370. @end
  229371. #define JuceNSWindow MakeObjCClassName(JuceNSWindow)
  229372. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  229373. @interface JuceNSWindow : NSWindow <NSWindowDelegate>
  229374. #else
  229375. @interface JuceNSWindow : NSWindow
  229376. #endif
  229377. {
  229378. @private
  229379. NSViewComponentPeer* owner;
  229380. bool isZooming;
  229381. }
  229382. - (void) setOwner: (NSViewComponentPeer*) owner;
  229383. - (BOOL) canBecomeKeyWindow;
  229384. - (void) becomeKeyWindow;
  229385. - (BOOL) windowShouldClose: (id) window;
  229386. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen;
  229387. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize;
  229388. - (void) zoom: (id) sender;
  229389. @end
  229390. BEGIN_JUCE_NAMESPACE
  229391. class NSViewComponentPeer : public ComponentPeer
  229392. {
  229393. public:
  229394. NSViewComponentPeer (Component* const component,
  229395. const int windowStyleFlags,
  229396. NSView* viewToAttachTo);
  229397. ~NSViewComponentPeer();
  229398. void* getNativeHandle() const;
  229399. void setVisible (bool shouldBeVisible);
  229400. void setTitle (const String& title);
  229401. void setPosition (int x, int y);
  229402. void setSize (int w, int h);
  229403. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen);
  229404. const Rectangle<int> getBounds (const bool global) const;
  229405. const Rectangle<int> getBounds() const;
  229406. const Point<int> getScreenPosition() const;
  229407. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition);
  229408. const Point<int> globalPositionToRelative (const Point<int>& screenPosition);
  229409. void setMinimised (bool shouldBeMinimised);
  229410. bool isMinimised() const;
  229411. void setFullScreen (bool shouldBeFullScreen);
  229412. bool isFullScreen() const;
  229413. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  229414. const BorderSize getFrameSize() const;
  229415. bool setAlwaysOnTop (bool alwaysOnTop);
  229416. void toFront (bool makeActiveWindow);
  229417. void toBehind (ComponentPeer* other);
  229418. void setIcon (const Image& newIcon);
  229419. const StringArray getAvailableRenderingEngines() throw();
  229420. int getCurrentRenderingEngine() throw();
  229421. void setCurrentRenderingEngine (int index) throw();
  229422. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  229423. for example having more than one juce plugin loaded into a host, then when a
  229424. method is called, the actual code that runs might actually be in a different module
  229425. than the one you expect... So any calls to library functions or statics that are
  229426. made inside obj-c methods will probably end up getting executed in a different DLL's
  229427. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  229428. To work around this insanity, I'm only allowing obj-c methods to make calls to
  229429. virtual methods of an object that's known to live inside the right module's space.
  229430. */
  229431. virtual void redirectMouseDown (NSEvent* ev);
  229432. virtual void redirectMouseUp (NSEvent* ev);
  229433. virtual void redirectMouseDrag (NSEvent* ev);
  229434. virtual void redirectMouseMove (NSEvent* ev);
  229435. virtual void redirectMouseEnter (NSEvent* ev);
  229436. virtual void redirectMouseExit (NSEvent* ev);
  229437. virtual void redirectMouseWheel (NSEvent* ev);
  229438. void sendMouseEvent (NSEvent* ev);
  229439. bool handleKeyEvent (NSEvent* ev, bool isKeyDown);
  229440. virtual bool redirectKeyDown (NSEvent* ev);
  229441. virtual bool redirectKeyUp (NSEvent* ev);
  229442. virtual void redirectModKeyChange (NSEvent* ev);
  229443. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229444. virtual bool redirectPerformKeyEquivalent (NSEvent* ev);
  229445. #endif
  229446. virtual BOOL sendDragCallback (int type, id <NSDraggingInfo> sender);
  229447. virtual bool isOpaque();
  229448. virtual void drawRect (NSRect r);
  229449. virtual bool canBecomeKeyWindow();
  229450. virtual bool windowShouldClose();
  229451. virtual void redirectMovedOrResized();
  229452. virtual void viewMovedToWindow();
  229453. virtual NSRect constrainRect (NSRect r);
  229454. static void showArrowCursorIfNeeded();
  229455. static void updateModifiers (NSEvent* e);
  229456. static void updateKeysDown (NSEvent* ev, bool isKeyDown);
  229457. static int getKeyCodeFromEvent (NSEvent* ev)
  229458. {
  229459. const String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  229460. int keyCode = unmodified[0];
  229461. if (keyCode == 0x19) // (backwards-tab)
  229462. keyCode = '\t';
  229463. else if (keyCode == 0x03) // (enter)
  229464. keyCode = '\r';
  229465. return keyCode;
  229466. }
  229467. static int64 getMouseTime (NSEvent* e)
  229468. {
  229469. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  229470. + (int64) ([e timestamp] * 1000.0);
  229471. }
  229472. static const Point<int> getMousePos (NSEvent* e, NSView* view)
  229473. {
  229474. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  229475. return Point<int> (roundToInt (p.x), roundToInt ([view frame].size.height - p.y));
  229476. }
  229477. static int getModifierForButtonNumber (const NSInteger num)
  229478. {
  229479. return num == 0 ? ModifierKeys::leftButtonModifier
  229480. : (num == 1 ? ModifierKeys::rightButtonModifier
  229481. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  229482. }
  229483. virtual void viewFocusGain();
  229484. virtual void viewFocusLoss();
  229485. bool isFocused() const;
  229486. void grabFocus();
  229487. void textInputRequired (const Point<int>& position);
  229488. void repaint (const Rectangle<int>& area);
  229489. void performAnyPendingRepaintsNow();
  229490. juce_UseDebuggingNewOperator
  229491. NSWindow* window;
  229492. JuceNSView* view;
  229493. bool isSharedWindow, fullScreen, insideDrawRect, usingCoreGraphics, recursiveToFrontCall;
  229494. static ModifierKeys currentModifiers;
  229495. static ComponentPeer* currentlyFocusedPeer;
  229496. static Array<int> keysCurrentlyDown;
  229497. };
  229498. END_JUCE_NAMESPACE
  229499. @implementation JuceNSView
  229500. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner_
  229501. withFrame: (NSRect) frame
  229502. {
  229503. [super initWithFrame: frame];
  229504. owner = owner_;
  229505. stringBeingComposed = 0;
  229506. textWasInserted = false;
  229507. notificationCenter = [NSNotificationCenter defaultCenter];
  229508. [notificationCenter addObserver: self
  229509. selector: @selector (frameChanged:)
  229510. name: NSViewFrameDidChangeNotification
  229511. object: self];
  229512. if (! owner_->isSharedWindow)
  229513. {
  229514. [notificationCenter addObserver: self
  229515. selector: @selector (frameChanged:)
  229516. name: NSWindowDidMoveNotification
  229517. object: owner_->window];
  229518. }
  229519. [self registerForDraggedTypes: [self getSupportedDragTypes]];
  229520. return self;
  229521. }
  229522. - (void) dealloc
  229523. {
  229524. [notificationCenter removeObserver: self];
  229525. delete stringBeingComposed;
  229526. [super dealloc];
  229527. }
  229528. - (void) drawRect: (NSRect) r
  229529. {
  229530. if (owner != 0)
  229531. owner->drawRect (r);
  229532. }
  229533. - (BOOL) isOpaque
  229534. {
  229535. return owner == 0 || owner->isOpaque();
  229536. }
  229537. - (void) mouseDown: (NSEvent*) ev
  229538. {
  229539. // In some host situations, the host will stop modal loops from working
  229540. // correctly if they're called from a mouse event, so we'll trigger
  229541. // the event asynchronously..
  229542. if (JUCEApplication::getInstance() == 0)
  229543. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  229544. withObject: ev
  229545. waitUntilDone: NO];
  229546. else
  229547. [self asyncMouseDown: ev];
  229548. }
  229549. - (void) asyncMouseDown: (NSEvent*) ev
  229550. {
  229551. if (owner != 0)
  229552. owner->redirectMouseDown (ev);
  229553. }
  229554. - (void) mouseUp: (NSEvent*) ev
  229555. {
  229556. // In some host situations, the host will stop modal loops from working
  229557. // correctly if they're called from a mouse event, so we'll trigger
  229558. // the event asynchronously..
  229559. if (JUCEApplication::getInstance() == 0)
  229560. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  229561. withObject: ev
  229562. waitUntilDone: NO];
  229563. else
  229564. [self asyncMouseUp: ev];
  229565. }
  229566. - (void) asyncMouseUp: (NSEvent*) ev
  229567. {
  229568. if (owner != 0)
  229569. owner->redirectMouseUp (ev);
  229570. }
  229571. - (void) mouseDragged: (NSEvent*) ev
  229572. {
  229573. if (owner != 0)
  229574. owner->redirectMouseDrag (ev);
  229575. }
  229576. - (void) mouseMoved: (NSEvent*) ev
  229577. {
  229578. if (owner != 0)
  229579. owner->redirectMouseMove (ev);
  229580. }
  229581. - (void) mouseEntered: (NSEvent*) ev
  229582. {
  229583. if (owner != 0)
  229584. owner->redirectMouseEnter (ev);
  229585. }
  229586. - (void) mouseExited: (NSEvent*) ev
  229587. {
  229588. if (owner != 0)
  229589. owner->redirectMouseExit (ev);
  229590. }
  229591. - (void) rightMouseDown: (NSEvent*) ev
  229592. {
  229593. [self mouseDown: ev];
  229594. }
  229595. - (void) rightMouseDragged: (NSEvent*) ev
  229596. {
  229597. [self mouseDragged: ev];
  229598. }
  229599. - (void) rightMouseUp: (NSEvent*) ev
  229600. {
  229601. [self mouseUp: ev];
  229602. }
  229603. - (void) otherMouseDown: (NSEvent*) ev
  229604. {
  229605. [self mouseDown: ev];
  229606. }
  229607. - (void) otherMouseDragged: (NSEvent*) ev
  229608. {
  229609. [self mouseDragged: ev];
  229610. }
  229611. - (void) otherMouseUp: (NSEvent*) ev
  229612. {
  229613. [self mouseUp: ev];
  229614. }
  229615. - (void) scrollWheel: (NSEvent*) ev
  229616. {
  229617. if (owner != 0)
  229618. owner->redirectMouseWheel (ev);
  229619. }
  229620. - (BOOL) acceptsFirstMouse: (NSEvent*) ev
  229621. {
  229622. (void) ev;
  229623. return YES;
  229624. }
  229625. - (void) frameChanged: (NSNotification*) n
  229626. {
  229627. (void) n;
  229628. if (owner != 0)
  229629. owner->redirectMovedOrResized();
  229630. }
  229631. - (void) viewDidMoveToWindow
  229632. {
  229633. if (owner != 0)
  229634. owner->viewMovedToWindow();
  229635. }
  229636. - (void) asyncRepaint: (id) rect
  229637. {
  229638. NSRect* r = (NSRect*) [((NSData*) rect) bytes];
  229639. [self setNeedsDisplayInRect: *r];
  229640. }
  229641. - (void) keyDown: (NSEvent*) ev
  229642. {
  229643. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  229644. textWasInserted = false;
  229645. if (target != 0)
  229646. [self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  229647. else
  229648. deleteAndZero (stringBeingComposed);
  229649. if ((! textWasInserted) && (owner == 0 || ! owner->redirectKeyDown (ev)))
  229650. [super keyDown: ev];
  229651. }
  229652. - (void) keyUp: (NSEvent*) ev
  229653. {
  229654. if (owner == 0 || ! owner->redirectKeyUp (ev))
  229655. [super keyUp: ev];
  229656. }
  229657. - (void) insertText: (id) aString
  229658. {
  229659. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  229660. if ([aString length] > 0)
  229661. {
  229662. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  229663. if (target != 0)
  229664. {
  229665. target->insertTextAtCaret (nsStringToJuce ([aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString));
  229666. textWasInserted = true;
  229667. }
  229668. }
  229669. deleteAndZero (stringBeingComposed);
  229670. }
  229671. - (void) doCommandBySelector: (SEL) aSelector
  229672. {
  229673. (void) aSelector;
  229674. }
  229675. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selectionRange
  229676. {
  229677. (void) selectionRange;
  229678. if (stringBeingComposed == 0)
  229679. stringBeingComposed = new String();
  229680. *stringBeingComposed = nsStringToJuce ([aString isKindOfClass:[NSAttributedString class]] ? [aString string] : aString);
  229681. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  229682. if (target != 0)
  229683. {
  229684. const Range<int> currentHighlight (target->getHighlightedRegion());
  229685. target->insertTextAtCaret (*stringBeingComposed);
  229686. target->setHighlightedRegion (currentHighlight.withLength (stringBeingComposed->length()));
  229687. textWasInserted = true;
  229688. }
  229689. }
  229690. - (void) unmarkText
  229691. {
  229692. if (stringBeingComposed != 0)
  229693. {
  229694. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  229695. if (target != 0)
  229696. {
  229697. target->insertTextAtCaret (*stringBeingComposed);
  229698. textWasInserted = true;
  229699. }
  229700. }
  229701. deleteAndZero (stringBeingComposed);
  229702. }
  229703. - (BOOL) hasMarkedText
  229704. {
  229705. return stringBeingComposed != 0;
  229706. }
  229707. - (long) conversationIdentifier
  229708. {
  229709. return (long) (pointer_sized_int) self;
  229710. }
  229711. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange
  229712. {
  229713. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  229714. if (target != 0)
  229715. {
  229716. const Range<int> r ((int) theRange.location,
  229717. (int) (theRange.location + theRange.length));
  229718. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  229719. }
  229720. return nil;
  229721. }
  229722. - (NSRange) markedRange
  229723. {
  229724. return stringBeingComposed != 0 ? NSMakeRange (0, stringBeingComposed->length())
  229725. : NSMakeRange (NSNotFound, 0);
  229726. }
  229727. - (NSRange) selectedRange
  229728. {
  229729. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  229730. if (target != 0)
  229731. {
  229732. const Range<int> highlight (target->getHighlightedRegion());
  229733. if (! highlight.isEmpty())
  229734. return NSMakeRange (highlight.getStart(), highlight.getLength());
  229735. }
  229736. return NSMakeRange (NSNotFound, 0);
  229737. }
  229738. - (NSRect) firstRectForCharacterRange: (NSRange) theRange
  229739. {
  229740. (void) theRange;
  229741. JUCE_NAMESPACE::Component* const comp = dynamic_cast <JUCE_NAMESPACE::Component*> (owner->findCurrentTextInputTarget());
  229742. if (comp == 0)
  229743. return NSMakeRect (0, 0, 0, 0);
  229744. const Rectangle<int> bounds (comp->getScreenBounds());
  229745. return NSMakeRect (bounds.getX(),
  229746. [[[NSScreen screens] objectAtIndex: 0] frame].size.height - bounds.getY(),
  229747. bounds.getWidth(),
  229748. bounds.getHeight());
  229749. }
  229750. - (unsigned int) characterIndexForPoint: (NSPoint) thePoint
  229751. {
  229752. (void) thePoint;
  229753. return NSNotFound;
  229754. }
  229755. - (NSArray*) validAttributesForMarkedText
  229756. {
  229757. return [NSArray array];
  229758. }
  229759. - (void) flagsChanged: (NSEvent*) ev
  229760. {
  229761. if (owner != 0)
  229762. owner->redirectModKeyChange (ev);
  229763. }
  229764. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229765. - (BOOL) performKeyEquivalent: (NSEvent*) ev
  229766. {
  229767. if (owner != 0 && owner->redirectPerformKeyEquivalent (ev))
  229768. return true;
  229769. return [super performKeyEquivalent: ev];
  229770. }
  229771. #endif
  229772. - (BOOL) becomeFirstResponder
  229773. {
  229774. if (owner != 0)
  229775. owner->viewFocusGain();
  229776. return true;
  229777. }
  229778. - (BOOL) resignFirstResponder
  229779. {
  229780. if (owner != 0)
  229781. owner->viewFocusLoss();
  229782. return true;
  229783. }
  229784. - (BOOL) acceptsFirstResponder
  229785. {
  229786. return owner != 0 && owner->canBecomeKeyWindow();
  229787. }
  229788. - (NSArray*) getSupportedDragTypes
  229789. {
  229790. return [NSArray arrayWithObjects: NSFilenamesPboardType, /*NSFilesPromisePboardType, NSStringPboardType,*/ nil];
  229791. }
  229792. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender
  229793. {
  229794. return owner != 0 && owner->sendDragCallback (type, sender);
  229795. }
  229796. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
  229797. {
  229798. if ([self sendDragCallback: 0 sender: sender])
  229799. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  229800. else
  229801. return NSDragOperationNone;
  229802. }
  229803. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender
  229804. {
  229805. if ([self sendDragCallback: 0 sender: sender])
  229806. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  229807. else
  229808. return NSDragOperationNone;
  229809. }
  229810. - (void) draggingEnded: (id <NSDraggingInfo>) sender
  229811. {
  229812. [self sendDragCallback: 1 sender: sender];
  229813. }
  229814. - (void) draggingExited: (id <NSDraggingInfo>) sender
  229815. {
  229816. [self sendDragCallback: 1 sender: sender];
  229817. }
  229818. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender
  229819. {
  229820. (void) sender;
  229821. return YES;
  229822. }
  229823. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender
  229824. {
  229825. return [self sendDragCallback: 2 sender: sender];
  229826. }
  229827. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender
  229828. {
  229829. (void) sender;
  229830. }
  229831. @end
  229832. @implementation JuceNSWindow
  229833. - (void) setOwner: (NSViewComponentPeer*) owner_
  229834. {
  229835. owner = owner_;
  229836. isZooming = false;
  229837. }
  229838. - (BOOL) canBecomeKeyWindow
  229839. {
  229840. return owner != 0 && owner->canBecomeKeyWindow();
  229841. }
  229842. - (void) becomeKeyWindow
  229843. {
  229844. [super becomeKeyWindow];
  229845. if (owner != 0)
  229846. owner->grabFocus();
  229847. }
  229848. - (BOOL) windowShouldClose: (id) window
  229849. {
  229850. (void) window;
  229851. return owner == 0 || owner->windowShouldClose();
  229852. }
  229853. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen
  229854. {
  229855. (void) screen;
  229856. if (owner != 0)
  229857. frameRect = owner->constrainRect (frameRect);
  229858. return frameRect;
  229859. }
  229860. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize
  229861. {
  229862. (void) window;
  229863. if (isZooming)
  229864. return proposedFrameSize;
  229865. NSRect frameRect = [self frame];
  229866. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  229867. frameRect.size = proposedFrameSize;
  229868. if (owner != 0)
  229869. frameRect = owner->constrainRect (frameRect);
  229870. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  229871. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  229872. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  229873. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  229874. return frameRect.size;
  229875. }
  229876. - (void) zoom: (id) sender
  229877. {
  229878. isZooming = true;
  229879. [super zoom: sender];
  229880. isZooming = false;
  229881. }
  229882. - (void) windowWillMove: (NSNotification*) notification
  229883. {
  229884. (void) notification;
  229885. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  229886. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  229887. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  229888. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  229889. }
  229890. @end
  229891. BEGIN_JUCE_NAMESPACE
  229892. ModifierKeys NSViewComponentPeer::currentModifiers;
  229893. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = 0;
  229894. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  229895. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  229896. {
  229897. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  229898. return true;
  229899. if (keyCode >= 'A' && keyCode <= 'Z'
  229900. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  229901. return true;
  229902. if (keyCode >= 'a' && keyCode <= 'z'
  229903. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  229904. return true;
  229905. return false;
  229906. }
  229907. void NSViewComponentPeer::updateModifiers (NSEvent* e)
  229908. {
  229909. int m = 0;
  229910. if (([e modifierFlags] & NSShiftKeyMask) != 0) m |= ModifierKeys::shiftModifier;
  229911. if (([e modifierFlags] & NSControlKeyMask) != 0) m |= ModifierKeys::ctrlModifier;
  229912. if (([e modifierFlags] & NSAlternateKeyMask) != 0) m |= ModifierKeys::altModifier;
  229913. if (([e modifierFlags] & NSCommandKeyMask) != 0) m |= ModifierKeys::commandModifier;
  229914. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (m);
  229915. }
  229916. void NSViewComponentPeer::updateKeysDown (NSEvent* ev, bool isKeyDown)
  229917. {
  229918. updateModifiers (ev);
  229919. int keyCode = getKeyCodeFromEvent (ev);
  229920. if (keyCode != 0)
  229921. {
  229922. if (isKeyDown)
  229923. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  229924. else
  229925. keysCurrentlyDown.removeValue (keyCode);
  229926. }
  229927. }
  229928. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  229929. {
  229930. return NSViewComponentPeer::currentModifiers;
  229931. }
  229932. void ModifierKeys::updateCurrentModifiers() throw()
  229933. {
  229934. currentModifiers = NSViewComponentPeer::currentModifiers;
  229935. }
  229936. NSViewComponentPeer::NSViewComponentPeer (Component* const component_,
  229937. const int windowStyleFlags,
  229938. NSView* viewToAttachTo)
  229939. : ComponentPeer (component_, windowStyleFlags),
  229940. window (0),
  229941. view (0),
  229942. isSharedWindow (viewToAttachTo != 0),
  229943. fullScreen (false),
  229944. insideDrawRect (false),
  229945. #if USE_COREGRAPHICS_RENDERING
  229946. usingCoreGraphics (true),
  229947. #else
  229948. usingCoreGraphics (false),
  229949. #endif
  229950. recursiveToFrontCall (false)
  229951. {
  229952. NSRect r;
  229953. r.origin.x = 0;
  229954. r.origin.y = 0;
  229955. r.size.width = (float) component->getWidth();
  229956. r.size.height = (float) component->getHeight();
  229957. view = [[JuceNSView alloc] initWithOwner: this withFrame: r];
  229958. [view setPostsFrameChangedNotifications: YES];
  229959. if (isSharedWindow)
  229960. {
  229961. window = [viewToAttachTo window];
  229962. [viewToAttachTo addSubview: view];
  229963. setVisible (component->isVisible());
  229964. }
  229965. else
  229966. {
  229967. r.origin.x = (float) component->getX();
  229968. r.origin.y = (float) component->getY();
  229969. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  229970. unsigned int style = 0;
  229971. if ((windowStyleFlags & windowHasTitleBar) == 0)
  229972. style = NSBorderlessWindowMask;
  229973. else
  229974. style = NSTitledWindowMask;
  229975. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  229976. style |= NSMiniaturizableWindowMask;
  229977. if ((windowStyleFlags & windowHasCloseButton) != 0)
  229978. style |= NSClosableWindowMask;
  229979. if ((windowStyleFlags & windowIsResizable) != 0)
  229980. style |= NSResizableWindowMask;
  229981. window = [[JuceNSWindow alloc] initWithContentRect: r
  229982. styleMask: style
  229983. backing: NSBackingStoreBuffered
  229984. defer: YES];
  229985. [((JuceNSWindow*) window) setOwner: this];
  229986. [window orderOut: nil];
  229987. [window setDelegate: (JuceNSWindow*) window];
  229988. [window setOpaque: component->isOpaque()];
  229989. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  229990. if (component->isAlwaysOnTop())
  229991. [window setLevel: NSFloatingWindowLevel];
  229992. [window setContentView: view];
  229993. [window setAutodisplay: YES];
  229994. [window setAcceptsMouseMovedEvents: YES];
  229995. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  229996. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  229997. [window setReleasedWhenClosed: YES];
  229998. [window retain];
  229999. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  230000. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  230001. }
  230002. setTitle (component->getName());
  230003. }
  230004. NSViewComponentPeer::~NSViewComponentPeer()
  230005. {
  230006. view->owner = 0;
  230007. [view removeFromSuperview];
  230008. [view release];
  230009. if (! isSharedWindow)
  230010. {
  230011. [((JuceNSWindow*) window) setOwner: 0];
  230012. [window close];
  230013. [window release];
  230014. }
  230015. }
  230016. void* NSViewComponentPeer::getNativeHandle() const
  230017. {
  230018. return view;
  230019. }
  230020. void NSViewComponentPeer::setVisible (bool shouldBeVisible)
  230021. {
  230022. if (isSharedWindow)
  230023. {
  230024. [view setHidden: ! shouldBeVisible];
  230025. }
  230026. else
  230027. {
  230028. if (shouldBeVisible)
  230029. {
  230030. [window orderFront: nil];
  230031. handleBroughtToFront();
  230032. }
  230033. else
  230034. {
  230035. [window orderOut: nil];
  230036. }
  230037. }
  230038. }
  230039. void NSViewComponentPeer::setTitle (const String& title)
  230040. {
  230041. const ScopedAutoReleasePool pool;
  230042. if (! isSharedWindow)
  230043. [window setTitle: juceStringToNS (title)];
  230044. }
  230045. void NSViewComponentPeer::setPosition (int x, int y)
  230046. {
  230047. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  230048. }
  230049. void NSViewComponentPeer::setSize (int w, int h)
  230050. {
  230051. setBounds (component->getX(), component->getY(), w, h, false);
  230052. }
  230053. void NSViewComponentPeer::setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  230054. {
  230055. fullScreen = isNowFullScreen;
  230056. w = jmax (0, w);
  230057. h = jmax (0, h);
  230058. NSRect r;
  230059. r.origin.x = (float) x;
  230060. r.origin.y = (float) y;
  230061. r.size.width = (float) w;
  230062. r.size.height = (float) h;
  230063. if (isSharedWindow)
  230064. {
  230065. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  230066. if ([view frame].size.width != r.size.width
  230067. || [view frame].size.height != r.size.height)
  230068. [view setNeedsDisplay: true];
  230069. [view setFrame: r];
  230070. }
  230071. else
  230072. {
  230073. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  230074. [window setFrame: [window frameRectForContentRect: r]
  230075. display: true];
  230076. }
  230077. }
  230078. const Rectangle<int> NSViewComponentPeer::getBounds (const bool global) const
  230079. {
  230080. NSRect r = [view frame];
  230081. if (global && [view window] != 0)
  230082. {
  230083. r = [view convertRect: r toView: nil];
  230084. NSRect wr = [[view window] frame];
  230085. r.origin.x += wr.origin.x;
  230086. r.origin.y += wr.origin.y;
  230087. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  230088. }
  230089. else
  230090. {
  230091. r.origin.y = [[view superview] frame].size.height - r.origin.y - r.size.height;
  230092. }
  230093. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y, (int) r.size.width, (int) r.size.height);
  230094. }
  230095. const Rectangle<int> NSViewComponentPeer::getBounds() const
  230096. {
  230097. return getBounds (! isSharedWindow);
  230098. }
  230099. const Point<int> NSViewComponentPeer::getScreenPosition() const
  230100. {
  230101. return getBounds (true).getPosition();
  230102. }
  230103. const Point<int> NSViewComponentPeer::relativePositionToGlobal (const Point<int>& relativePosition)
  230104. {
  230105. return relativePosition + getScreenPosition();
  230106. }
  230107. const Point<int> NSViewComponentPeer::globalPositionToRelative (const Point<int>& screenPosition)
  230108. {
  230109. return screenPosition - getScreenPosition();
  230110. }
  230111. NSRect NSViewComponentPeer::constrainRect (NSRect r)
  230112. {
  230113. if (constrainer != 0)
  230114. {
  230115. NSRect current = [window frame];
  230116. current.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - current.origin.y - current.size.height;
  230117. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  230118. Rectangle<int> pos ((int) r.origin.x, (int) r.origin.y,
  230119. (int) r.size.width, (int) r.size.height);
  230120. Rectangle<int> original ((int) current.origin.x, (int) current.origin.y,
  230121. (int) current.size.width, (int) current.size.height);
  230122. constrainer->checkBounds (pos, original,
  230123. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  230124. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  230125. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  230126. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  230127. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  230128. r.origin.x = pos.getX();
  230129. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.size.height - pos.getY();
  230130. r.size.width = pos.getWidth();
  230131. r.size.height = pos.getHeight();
  230132. }
  230133. return r;
  230134. }
  230135. void NSViewComponentPeer::setMinimised (bool shouldBeMinimised)
  230136. {
  230137. if (! isSharedWindow)
  230138. {
  230139. if (shouldBeMinimised)
  230140. [window miniaturize: nil];
  230141. else
  230142. [window deminiaturize: nil];
  230143. }
  230144. }
  230145. bool NSViewComponentPeer::isMinimised() const
  230146. {
  230147. return window != 0 && [window isMiniaturized];
  230148. }
  230149. void NSViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  230150. {
  230151. if (! isSharedWindow)
  230152. {
  230153. Rectangle<int> r (lastNonFullscreenBounds);
  230154. setMinimised (false);
  230155. if (fullScreen != shouldBeFullScreen)
  230156. {
  230157. if (shouldBeFullScreen && (getStyleFlags() & windowHasTitleBar) != 0)
  230158. {
  230159. fullScreen = true;
  230160. [window performZoom: nil];
  230161. }
  230162. else
  230163. {
  230164. if (shouldBeFullScreen)
  230165. r = Desktop::getInstance().getMainMonitorArea();
  230166. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  230167. if (r != getComponent()->getBounds() && ! r.isEmpty())
  230168. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  230169. }
  230170. }
  230171. }
  230172. }
  230173. bool NSViewComponentPeer::isFullScreen() const
  230174. {
  230175. return fullScreen;
  230176. }
  230177. bool NSViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  230178. {
  230179. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  230180. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  230181. return false;
  230182. NSPoint p;
  230183. p.x = (float) position.getX();
  230184. p.y = (float) position.getY();
  230185. NSView* v = [view hitTest: p];
  230186. if (trueIfInAChildWindow)
  230187. return v != nil;
  230188. return v == view;
  230189. }
  230190. const BorderSize NSViewComponentPeer::getFrameSize() const
  230191. {
  230192. BorderSize b;
  230193. if (! isSharedWindow)
  230194. {
  230195. NSRect v = [view convertRect: [view frame] toView: nil];
  230196. NSRect w = [window frame];
  230197. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  230198. b.setBottom ((int) v.origin.y);
  230199. b.setLeft ((int) v.origin.x);
  230200. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  230201. }
  230202. return b;
  230203. }
  230204. bool NSViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  230205. {
  230206. if (! isSharedWindow)
  230207. {
  230208. [window setLevel: alwaysOnTop ? NSFloatingWindowLevel
  230209. : NSNormalWindowLevel];
  230210. }
  230211. return true;
  230212. }
  230213. void NSViewComponentPeer::toFront (bool makeActiveWindow)
  230214. {
  230215. if (isSharedWindow)
  230216. {
  230217. [[view superview] addSubview: view
  230218. positioned: NSWindowAbove
  230219. relativeTo: nil];
  230220. }
  230221. if (window != 0 && component->isVisible())
  230222. {
  230223. if (makeActiveWindow)
  230224. [window makeKeyAndOrderFront: nil];
  230225. else
  230226. [window orderFront: nil];
  230227. if (! recursiveToFrontCall)
  230228. {
  230229. recursiveToFrontCall = true;
  230230. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  230231. handleBroughtToFront();
  230232. recursiveToFrontCall = false;
  230233. }
  230234. }
  230235. }
  230236. void NSViewComponentPeer::toBehind (ComponentPeer* other)
  230237. {
  230238. NSViewComponentPeer* const otherPeer = dynamic_cast <NSViewComponentPeer*> (other);
  230239. jassert (otherPeer != 0); // wrong type of window?
  230240. if (otherPeer != 0)
  230241. {
  230242. if (isSharedWindow)
  230243. {
  230244. [[view superview] addSubview: view
  230245. positioned: NSWindowBelow
  230246. relativeTo: otherPeer->view];
  230247. }
  230248. else
  230249. {
  230250. [window orderWindow: NSWindowBelow
  230251. relativeTo: otherPeer->window != 0 ? [otherPeer->window windowNumber]
  230252. : nil ];
  230253. }
  230254. }
  230255. }
  230256. void NSViewComponentPeer::setIcon (const Image& /*newIcon*/)
  230257. {
  230258. // to do..
  230259. }
  230260. void NSViewComponentPeer::viewFocusGain()
  230261. {
  230262. if (currentlyFocusedPeer != this)
  230263. {
  230264. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  230265. currentlyFocusedPeer->handleFocusLoss();
  230266. currentlyFocusedPeer = this;
  230267. handleFocusGain();
  230268. }
  230269. }
  230270. void NSViewComponentPeer::viewFocusLoss()
  230271. {
  230272. if (currentlyFocusedPeer == this)
  230273. {
  230274. currentlyFocusedPeer = 0;
  230275. handleFocusLoss();
  230276. }
  230277. }
  230278. void juce_HandleProcessFocusChange()
  230279. {
  230280. NSViewComponentPeer::keysCurrentlyDown.clear();
  230281. if (NSViewComponentPeer::isValidPeer (NSViewComponentPeer::currentlyFocusedPeer))
  230282. {
  230283. if (Process::isForegroundProcess())
  230284. {
  230285. NSViewComponentPeer::currentlyFocusedPeer->handleFocusGain();
  230286. ComponentPeer::bringModalComponentToFront();
  230287. }
  230288. else
  230289. {
  230290. NSViewComponentPeer::currentlyFocusedPeer->handleFocusLoss();
  230291. // turn kiosk mode off if we lose focus..
  230292. Desktop::getInstance().setKioskModeComponent (0);
  230293. }
  230294. }
  230295. }
  230296. bool NSViewComponentPeer::isFocused() const
  230297. {
  230298. return isSharedWindow ? this == currentlyFocusedPeer
  230299. : (window != 0 && [window isKeyWindow]);
  230300. }
  230301. void NSViewComponentPeer::grabFocus()
  230302. {
  230303. if (window != 0)
  230304. {
  230305. [window makeKeyWindow];
  230306. [window makeFirstResponder: view];
  230307. viewFocusGain();
  230308. }
  230309. }
  230310. void NSViewComponentPeer::textInputRequired (const Point<int>&)
  230311. {
  230312. }
  230313. bool NSViewComponentPeer::handleKeyEvent (NSEvent* ev, bool isKeyDown)
  230314. {
  230315. String unicode (nsStringToJuce ([ev characters]));
  230316. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  230317. int keyCode = getKeyCodeFromEvent (ev);
  230318. //DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  230319. //DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  230320. if (unicode.isNotEmpty() || keyCode != 0)
  230321. {
  230322. if (isKeyDown)
  230323. {
  230324. bool used = false;
  230325. while (unicode.length() > 0)
  230326. {
  230327. juce_wchar textCharacter = unicode[0];
  230328. unicode = unicode.substring (1);
  230329. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  230330. textCharacter = 0;
  230331. used = handleKeyUpOrDown (true) || used;
  230332. used = handleKeyPress (keyCode, textCharacter) || used;
  230333. }
  230334. return used;
  230335. }
  230336. else
  230337. {
  230338. if (handleKeyUpOrDown (false))
  230339. return true;
  230340. }
  230341. }
  230342. return false;
  230343. }
  230344. bool NSViewComponentPeer::redirectKeyDown (NSEvent* ev)
  230345. {
  230346. updateKeysDown (ev, true);
  230347. bool used = handleKeyEvent (ev, true);
  230348. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  230349. {
  230350. // for command keys, the key-up event is thrown away, so simulate one..
  230351. updateKeysDown (ev, false);
  230352. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  230353. }
  230354. // (If we're running modally, don't allow unused keystrokes to be passed
  230355. // along to other blocked views..)
  230356. if (Component::getCurrentlyModalComponent() != 0)
  230357. used = true;
  230358. return used;
  230359. }
  230360. bool NSViewComponentPeer::redirectKeyUp (NSEvent* ev)
  230361. {
  230362. updateKeysDown (ev, false);
  230363. return handleKeyEvent (ev, false)
  230364. || Component::getCurrentlyModalComponent() != 0;
  230365. }
  230366. void NSViewComponentPeer::redirectModKeyChange (NSEvent* ev)
  230367. {
  230368. keysCurrentlyDown.clear();
  230369. handleKeyUpOrDown (true);
  230370. updateModifiers (ev);
  230371. handleModifierKeysChange();
  230372. }
  230373. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230374. bool NSViewComponentPeer::redirectPerformKeyEquivalent (NSEvent* ev)
  230375. {
  230376. if ([ev type] == NSKeyDown)
  230377. return redirectKeyDown (ev);
  230378. else if ([ev type] == NSKeyUp)
  230379. return redirectKeyUp (ev);
  230380. return false;
  230381. }
  230382. #endif
  230383. void NSViewComponentPeer::sendMouseEvent (NSEvent* ev)
  230384. {
  230385. updateModifiers (ev);
  230386. handleMouseEvent (0, getMousePos (ev, view), currentModifiers, getMouseTime (ev));
  230387. }
  230388. void NSViewComponentPeer::redirectMouseDown (NSEvent* ev)
  230389. {
  230390. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  230391. sendMouseEvent (ev);
  230392. }
  230393. void NSViewComponentPeer::redirectMouseUp (NSEvent* ev)
  230394. {
  230395. currentModifiers = currentModifiers.withoutFlags (getModifierForButtonNumber ([ev buttonNumber]));
  230396. sendMouseEvent (ev);
  230397. showArrowCursorIfNeeded();
  230398. }
  230399. void NSViewComponentPeer::redirectMouseDrag (NSEvent* ev)
  230400. {
  230401. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  230402. sendMouseEvent (ev);
  230403. }
  230404. void NSViewComponentPeer::redirectMouseMove (NSEvent* ev)
  230405. {
  230406. currentModifiers = currentModifiers.withoutMouseButtons();
  230407. sendMouseEvent (ev);
  230408. showArrowCursorIfNeeded();
  230409. }
  230410. void NSViewComponentPeer::redirectMouseEnter (NSEvent* ev)
  230411. {
  230412. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  230413. currentModifiers = currentModifiers.withoutMouseButtons();
  230414. sendMouseEvent (ev);
  230415. }
  230416. void NSViewComponentPeer::redirectMouseExit (NSEvent* ev)
  230417. {
  230418. currentModifiers = currentModifiers.withoutMouseButtons();
  230419. sendMouseEvent (ev);
  230420. }
  230421. void NSViewComponentPeer::redirectMouseWheel (NSEvent* ev)
  230422. {
  230423. updateModifiers (ev);
  230424. float x = 0, y = 0;
  230425. @try
  230426. {
  230427. x = [ev deviceDeltaX] * 0.5f;
  230428. y = [ev deviceDeltaY] * 0.5f;
  230429. }
  230430. @catch (...)
  230431. {
  230432. x = [ev deltaX] * 10.0f;
  230433. y = [ev deltaY] * 10.0f;
  230434. }
  230435. handleMouseWheel (0, getMousePos (ev, view), getMouseTime (ev), x, y);
  230436. }
  230437. void NSViewComponentPeer::showArrowCursorIfNeeded()
  230438. {
  230439. MouseInputSource& mouse = Desktop::getInstance().getMainMouseSource();
  230440. if (mouse.getComponentUnderMouse() == 0
  230441. && Desktop::getInstance().findComponentAt (mouse.getScreenPosition()) == 0)
  230442. {
  230443. [[NSCursor arrowCursor] set];
  230444. }
  230445. }
  230446. BOOL NSViewComponentPeer::sendDragCallback (int type, id <NSDraggingInfo> sender)
  230447. {
  230448. NSString* bestType
  230449. = [[sender draggingPasteboard] availableTypeFromArray: [view getSupportedDragTypes]];
  230450. if (bestType == nil)
  230451. return false;
  230452. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  230453. const Point<int> pos ((int) p.x, (int) ([view frame].size.height - p.y));
  230454. StringArray files;
  230455. id list = [[sender draggingPasteboard] propertyListForType: bestType];
  230456. if (list == nil)
  230457. return false;
  230458. if ([list isKindOfClass: [NSArray class]])
  230459. {
  230460. NSArray* items = (NSArray*) list;
  230461. for (unsigned int i = 0; i < [items count]; ++i)
  230462. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  230463. }
  230464. if (files.size() == 0)
  230465. return false;
  230466. if (type == 0)
  230467. handleFileDragMove (files, pos);
  230468. else if (type == 1)
  230469. handleFileDragExit (files);
  230470. else if (type == 2)
  230471. handleFileDragDrop (files, pos);
  230472. return true;
  230473. }
  230474. bool NSViewComponentPeer::isOpaque()
  230475. {
  230476. return component == 0 || component->isOpaque();
  230477. }
  230478. void NSViewComponentPeer::drawRect (NSRect r)
  230479. {
  230480. if (r.size.width < 1.0f || r.size.height < 1.0f)
  230481. return;
  230482. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  230483. if (! component->isOpaque())
  230484. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  230485. #if USE_COREGRAPHICS_RENDERING
  230486. if (usingCoreGraphics)
  230487. {
  230488. CoreGraphicsContext context (cg, (float) [view frame].size.height);
  230489. insideDrawRect = true;
  230490. handlePaint (context);
  230491. insideDrawRect = false;
  230492. }
  230493. else
  230494. #endif
  230495. {
  230496. Image temp (getComponent()->isOpaque() ? Image::RGB : Image::ARGB,
  230497. (int) (r.size.width + 0.5f),
  230498. (int) (r.size.height + 0.5f),
  230499. ! getComponent()->isOpaque());
  230500. const int xOffset = -roundToInt (r.origin.x);
  230501. const int yOffset = -roundToInt ([view frame].size.height - (r.origin.y + r.size.height));
  230502. const NSRect* rects = 0;
  230503. NSInteger numRects = 0;
  230504. [view getRectsBeingDrawn: &rects count: &numRects];
  230505. const Rectangle<int> clipBounds (temp.getBounds());
  230506. RectangleList clip;
  230507. for (int i = 0; i < numRects; ++i)
  230508. {
  230509. clip.addWithoutMerging (clipBounds.getIntersection (Rectangle<int> (roundToInt (rects[i].origin.x) + xOffset,
  230510. roundToInt ([view frame].size.height - (rects[i].origin.y + rects[i].size.height)) + yOffset,
  230511. roundToInt (rects[i].size.width),
  230512. roundToInt (rects[i].size.height))));
  230513. }
  230514. if (! clip.isEmpty())
  230515. {
  230516. LowLevelGraphicsSoftwareRenderer context (temp, xOffset, yOffset, clip);
  230517. insideDrawRect = true;
  230518. handlePaint (context);
  230519. insideDrawRect = false;
  230520. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  230521. CGImageRef image = CoreGraphicsImage::createImage (temp, false, colourSpace);
  230522. CGColorSpaceRelease (colourSpace);
  230523. CGContextDrawImage (cg, CGRectMake (r.origin.x, r.origin.y, temp.getWidth(), temp.getHeight()), image);
  230524. CGImageRelease (image);
  230525. }
  230526. }
  230527. }
  230528. const StringArray NSViewComponentPeer::getAvailableRenderingEngines() throw()
  230529. {
  230530. StringArray s;
  230531. s.add ("Software Renderer");
  230532. #if USE_COREGRAPHICS_RENDERING
  230533. s.add ("CoreGraphics Renderer");
  230534. #endif
  230535. return s;
  230536. }
  230537. int NSViewComponentPeer::getCurrentRenderingEngine() throw()
  230538. {
  230539. return usingCoreGraphics ? 1 : 0;
  230540. }
  230541. void NSViewComponentPeer::setCurrentRenderingEngine (int index) throw()
  230542. {
  230543. #if USE_COREGRAPHICS_RENDERING
  230544. if (usingCoreGraphics != (index > 0))
  230545. {
  230546. usingCoreGraphics = index > 0;
  230547. [view setNeedsDisplay: true];
  230548. }
  230549. #endif
  230550. }
  230551. bool NSViewComponentPeer::canBecomeKeyWindow()
  230552. {
  230553. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  230554. }
  230555. bool NSViewComponentPeer::windowShouldClose()
  230556. {
  230557. if (! isValidPeer (this))
  230558. return YES;
  230559. handleUserClosingWindow();
  230560. return NO;
  230561. }
  230562. void NSViewComponentPeer::redirectMovedOrResized()
  230563. {
  230564. handleMovedOrResized();
  230565. }
  230566. void NSViewComponentPeer::viewMovedToWindow()
  230567. {
  230568. if (isSharedWindow)
  230569. window = [view window];
  230570. }
  230571. void Desktop::createMouseInputSources()
  230572. {
  230573. mouseSources.add (new MouseInputSource (0, true));
  230574. }
  230575. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  230576. {
  230577. // Very annoyingly, this function has to use the old SetSystemUIMode function,
  230578. // which is in Carbon.framework. But, because there's no Cocoa equivalent, it
  230579. // is apparently still available in 64-bit apps..
  230580. if (enableOrDisable)
  230581. {
  230582. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  230583. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  230584. }
  230585. else
  230586. {
  230587. SetSystemUIMode (kUIModeNormal, 0);
  230588. }
  230589. }
  230590. class AsyncRepaintMessage : public CallbackMessage
  230591. {
  230592. public:
  230593. NSViewComponentPeer* const peer;
  230594. const Rectangle<int> rect;
  230595. AsyncRepaintMessage (NSViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  230596. : peer (peer_), rect (rect_)
  230597. {
  230598. }
  230599. void messageCallback()
  230600. {
  230601. if (ComponentPeer::isValidPeer (peer))
  230602. peer->repaint (rect);
  230603. }
  230604. };
  230605. void NSViewComponentPeer::repaint (const Rectangle<int>& area)
  230606. {
  230607. if (insideDrawRect)
  230608. {
  230609. (new AsyncRepaintMessage (this, area))->post();
  230610. }
  230611. else
  230612. {
  230613. [view setNeedsDisplayInRect: NSMakeRect ((float) area.getX(), [view frame].size.height - (float) area.getBottom(),
  230614. (float) area.getWidth(), (float) area.getHeight())];
  230615. }
  230616. }
  230617. void NSViewComponentPeer::performAnyPendingRepaintsNow()
  230618. {
  230619. [view displayIfNeeded];
  230620. }
  230621. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  230622. {
  230623. return new NSViewComponentPeer (this, styleFlags, (NSView*) windowToAttachTo);
  230624. }
  230625. const Image juce_createIconForFile (const File& file)
  230626. {
  230627. const ScopedAutoReleasePool pool;
  230628. NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
  230629. CoreGraphicsImage* result = new CoreGraphicsImage (Image::ARGB, (int) [image size].width, (int) [image size].height, true);
  230630. [NSGraphicsContext saveGraphicsState];
  230631. [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithGraphicsPort: result->context flipped: false]];
  230632. [image drawAtPoint: NSMakePoint (0, 0)
  230633. fromRect: NSMakeRect (0, 0, [image size].width, [image size].height)
  230634. operation: NSCompositeSourceOver fraction: 1.0f];
  230635. [[NSGraphicsContext currentContext] flushGraphics];
  230636. [NSGraphicsContext restoreGraphicsState];
  230637. return Image (result);
  230638. }
  230639. const int KeyPress::spaceKey = ' ';
  230640. const int KeyPress::returnKey = 0x0d;
  230641. const int KeyPress::escapeKey = 0x1b;
  230642. const int KeyPress::backspaceKey = 0x7f;
  230643. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  230644. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  230645. const int KeyPress::upKey = NSUpArrowFunctionKey;
  230646. const int KeyPress::downKey = NSDownArrowFunctionKey;
  230647. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  230648. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  230649. const int KeyPress::endKey = NSEndFunctionKey;
  230650. const int KeyPress::homeKey = NSHomeFunctionKey;
  230651. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  230652. const int KeyPress::insertKey = -1;
  230653. const int KeyPress::tabKey = 9;
  230654. const int KeyPress::F1Key = NSF1FunctionKey;
  230655. const int KeyPress::F2Key = NSF2FunctionKey;
  230656. const int KeyPress::F3Key = NSF3FunctionKey;
  230657. const int KeyPress::F4Key = NSF4FunctionKey;
  230658. const int KeyPress::F5Key = NSF5FunctionKey;
  230659. const int KeyPress::F6Key = NSF6FunctionKey;
  230660. const int KeyPress::F7Key = NSF7FunctionKey;
  230661. const int KeyPress::F8Key = NSF8FunctionKey;
  230662. const int KeyPress::F9Key = NSF9FunctionKey;
  230663. const int KeyPress::F10Key = NSF10FunctionKey;
  230664. const int KeyPress::F11Key = NSF1FunctionKey;
  230665. const int KeyPress::F12Key = NSF12FunctionKey;
  230666. const int KeyPress::F13Key = NSF13FunctionKey;
  230667. const int KeyPress::F14Key = NSF14FunctionKey;
  230668. const int KeyPress::F15Key = NSF15FunctionKey;
  230669. const int KeyPress::F16Key = NSF16FunctionKey;
  230670. const int KeyPress::numberPad0 = 0x30020;
  230671. const int KeyPress::numberPad1 = 0x30021;
  230672. const int KeyPress::numberPad2 = 0x30022;
  230673. const int KeyPress::numberPad3 = 0x30023;
  230674. const int KeyPress::numberPad4 = 0x30024;
  230675. const int KeyPress::numberPad5 = 0x30025;
  230676. const int KeyPress::numberPad6 = 0x30026;
  230677. const int KeyPress::numberPad7 = 0x30027;
  230678. const int KeyPress::numberPad8 = 0x30028;
  230679. const int KeyPress::numberPad9 = 0x30029;
  230680. const int KeyPress::numberPadAdd = 0x3002a;
  230681. const int KeyPress::numberPadSubtract = 0x3002b;
  230682. const int KeyPress::numberPadMultiply = 0x3002c;
  230683. const int KeyPress::numberPadDivide = 0x3002d;
  230684. const int KeyPress::numberPadSeparator = 0x3002e;
  230685. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  230686. const int KeyPress::numberPadEquals = 0x30030;
  230687. const int KeyPress::numberPadDelete = 0x30031;
  230688. const int KeyPress::playKey = 0x30000;
  230689. const int KeyPress::stopKey = 0x30001;
  230690. const int KeyPress::fastForwardKey = 0x30002;
  230691. const int KeyPress::rewindKey = 0x30003;
  230692. #endif
  230693. /*** End of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  230694. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  230695. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230696. // compiled on its own).
  230697. #if JUCE_INCLUDED_FILE
  230698. #if JUCE_MAC
  230699. namespace MouseCursorHelpers
  230700. {
  230701. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  230702. {
  230703. NSImage* im = CoreGraphicsImage::createNSImage (image);
  230704. NSCursor* c = [[NSCursor alloc] initWithImage: im
  230705. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  230706. [im release];
  230707. return c;
  230708. }
  230709. static void* fromWebKitFile (const char* filename, float hx, float hy)
  230710. {
  230711. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  230712. BufferedInputStream buf (&fileStream, 4096, false);
  230713. PNGImageFormat pngFormat;
  230714. Image im (pngFormat.decodeImage (buf));
  230715. if (im.isValid())
  230716. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  230717. jassertfalse;
  230718. return 0;
  230719. }
  230720. }
  230721. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  230722. {
  230723. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  230724. }
  230725. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  230726. {
  230727. const ScopedAutoReleasePool pool;
  230728. NSCursor* c = 0;
  230729. switch (type)
  230730. {
  230731. case NormalCursor: c = [NSCursor arrowCursor]; break;
  230732. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  230733. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  230734. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  230735. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  230736. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  230737. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  230738. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  230739. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  230740. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  230741. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  230742. case UpDownResizeCursor:
  230743. case TopEdgeResizeCursor:
  230744. case BottomEdgeResizeCursor:
  230745. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  230746. case TopLeftCornerResizeCursor:
  230747. case BottomRightCornerResizeCursor:
  230748. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  230749. case TopRightCornerResizeCursor:
  230750. case BottomLeftCornerResizeCursor:
  230751. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  230752. case UpDownLeftRightResizeCursor:
  230753. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  230754. default:
  230755. jassertfalse;
  230756. break;
  230757. }
  230758. [c retain];
  230759. return c;
  230760. }
  230761. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  230762. {
  230763. [((NSCursor*) cursorHandle) release];
  230764. }
  230765. void MouseCursor::showInAllWindows() const
  230766. {
  230767. showInWindow (0);
  230768. }
  230769. void MouseCursor::showInWindow (ComponentPeer*) const
  230770. {
  230771. [((NSCursor*) getHandle()) set];
  230772. }
  230773. #else
  230774. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  230775. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  230776. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  230777. void MouseCursor::showInAllWindows() const {}
  230778. void MouseCursor::showInWindow (ComponentPeer*) const {}
  230779. #endif
  230780. #endif
  230781. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  230782. /*** Start of inlined file: juce_mac_NSViewComponent.mm ***/
  230783. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230784. // compiled on its own).
  230785. #if JUCE_INCLUDED_FILE
  230786. class NSViewComponentInternal : public ComponentMovementWatcher
  230787. {
  230788. Component* const owner;
  230789. NSViewComponentPeer* currentPeer;
  230790. bool wasShowing;
  230791. public:
  230792. NSView* const view;
  230793. NSViewComponentInternal (NSView* const view_, Component* const owner_)
  230794. : ComponentMovementWatcher (owner_),
  230795. owner (owner_),
  230796. currentPeer (0),
  230797. wasShowing (false),
  230798. view (view_)
  230799. {
  230800. [view_ retain];
  230801. if (owner_->isShowing())
  230802. componentPeerChanged();
  230803. }
  230804. ~NSViewComponentInternal()
  230805. {
  230806. [view removeFromSuperview];
  230807. [view release];
  230808. }
  230809. void componentMovedOrResized (Component& comp, bool wasMoved, bool wasResized)
  230810. {
  230811. ComponentMovementWatcher::componentMovedOrResized (comp, wasMoved, wasResized);
  230812. // The ComponentMovementWatcher version of this method avoids calling
  230813. // us when the top-level comp is resized, but for an NSView we need to know this
  230814. // because with inverted co-ords, we need to update the position even if the
  230815. // top-left pos hasn't changed
  230816. if (comp.isOnDesktop() && wasResized)
  230817. componentMovedOrResized (wasMoved, wasResized);
  230818. }
  230819. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  230820. {
  230821. Component* const topComp = owner->getTopLevelComponent();
  230822. if (topComp->getPeer() != 0)
  230823. {
  230824. const Point<int> pos (owner->relativePositionToOtherComponent (topComp, Point<int>()));
  230825. NSRect r;
  230826. r.origin.x = (float) pos.getX();
  230827. r.origin.y = (float) pos.getY();
  230828. r.size.width = (float) owner->getWidth();
  230829. r.size.height = (float) owner->getHeight();
  230830. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  230831. [view setFrame: r];
  230832. }
  230833. }
  230834. void componentPeerChanged()
  230835. {
  230836. NSViewComponentPeer* const peer = dynamic_cast <NSViewComponentPeer*> (owner->getPeer());
  230837. if (currentPeer != peer)
  230838. {
  230839. [view removeFromSuperview];
  230840. currentPeer = peer;
  230841. if (peer != 0)
  230842. {
  230843. [peer->view addSubview: view];
  230844. componentMovedOrResized (false, false);
  230845. }
  230846. }
  230847. [view setHidden: ! owner->isShowing()];
  230848. }
  230849. void componentVisibilityChanged (Component&)
  230850. {
  230851. componentPeerChanged();
  230852. }
  230853. juce_UseDebuggingNewOperator
  230854. private:
  230855. NSViewComponentInternal (const NSViewComponentInternal&);
  230856. NSViewComponentInternal& operator= (const NSViewComponentInternal&);
  230857. };
  230858. NSViewComponent::NSViewComponent()
  230859. {
  230860. }
  230861. NSViewComponent::~NSViewComponent()
  230862. {
  230863. }
  230864. void NSViewComponent::setView (void* view)
  230865. {
  230866. if (view != getView())
  230867. {
  230868. if (view != 0)
  230869. info = new NSViewComponentInternal ((NSView*) view, this);
  230870. else
  230871. info = 0;
  230872. }
  230873. }
  230874. void* NSViewComponent::getView() const
  230875. {
  230876. return info == 0 ? 0 : info->view;
  230877. }
  230878. void NSViewComponent::paint (Graphics&)
  230879. {
  230880. }
  230881. #endif
  230882. /*** End of inlined file: juce_mac_NSViewComponent.mm ***/
  230883. /*** Start of inlined file: juce_mac_AppleRemote.mm ***/
  230884. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230885. // compiled on its own).
  230886. #if JUCE_INCLUDED_FILE
  230887. AppleRemoteDevice::AppleRemoteDevice()
  230888. : device (0),
  230889. queue (0),
  230890. remoteId (0)
  230891. {
  230892. }
  230893. AppleRemoteDevice::~AppleRemoteDevice()
  230894. {
  230895. stop();
  230896. }
  230897. static io_object_t getAppleRemoteDevice()
  230898. {
  230899. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  230900. io_iterator_t iter = 0;
  230901. io_object_t iod = 0;
  230902. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  230903. && iter != 0)
  230904. {
  230905. iod = IOIteratorNext (iter);
  230906. }
  230907. IOObjectRelease (iter);
  230908. return iod;
  230909. }
  230910. static bool createAppleRemoteInterface (io_object_t iod, void** device)
  230911. {
  230912. jassert (*device == 0);
  230913. io_name_t classname;
  230914. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  230915. {
  230916. IOCFPlugInInterface** cfPlugInInterface = 0;
  230917. SInt32 score = 0;
  230918. if (IOCreatePlugInInterfaceForService (iod,
  230919. kIOHIDDeviceUserClientTypeID,
  230920. kIOCFPlugInInterfaceID,
  230921. &cfPlugInInterface,
  230922. &score) == kIOReturnSuccess)
  230923. {
  230924. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  230925. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  230926. device);
  230927. (void) hr;
  230928. (*cfPlugInInterface)->Release (cfPlugInInterface);
  230929. }
  230930. }
  230931. return *device != 0;
  230932. }
  230933. bool AppleRemoteDevice::start (const bool inExclusiveMode)
  230934. {
  230935. if (queue != 0)
  230936. return true;
  230937. stop();
  230938. bool result = false;
  230939. io_object_t iod = getAppleRemoteDevice();
  230940. if (iod != 0)
  230941. {
  230942. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  230943. result = true;
  230944. else
  230945. stop();
  230946. IOObjectRelease (iod);
  230947. }
  230948. return result;
  230949. }
  230950. void AppleRemoteDevice::stop()
  230951. {
  230952. if (queue != 0)
  230953. {
  230954. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  230955. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  230956. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  230957. queue = 0;
  230958. }
  230959. if (device != 0)
  230960. {
  230961. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  230962. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  230963. device = 0;
  230964. }
  230965. }
  230966. bool AppleRemoteDevice::isActive() const
  230967. {
  230968. return queue != 0;
  230969. }
  230970. static void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  230971. {
  230972. if (result == kIOReturnSuccess)
  230973. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  230974. }
  230975. bool AppleRemoteDevice::open (const bool openInExclusiveMode)
  230976. {
  230977. Array <int> cookies;
  230978. CFArrayRef elements;
  230979. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  230980. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  230981. return false;
  230982. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  230983. {
  230984. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  230985. // get the cookie
  230986. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  230987. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  230988. continue;
  230989. long number;
  230990. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  230991. continue;
  230992. cookies.add ((int) number);
  230993. }
  230994. CFRelease (elements);
  230995. if ((*(IOHIDDeviceInterface**) device)
  230996. ->open ((IOHIDDeviceInterface**) device,
  230997. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  230998. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  230999. {
  231000. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  231001. if (queue != 0)
  231002. {
  231003. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  231004. for (int i = 0; i < cookies.size(); ++i)
  231005. {
  231006. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  231007. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  231008. }
  231009. CFRunLoopSourceRef eventSource;
  231010. if ((*(IOHIDQueueInterface**) queue)
  231011. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  231012. {
  231013. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  231014. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  231015. {
  231016. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  231017. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  231018. return true;
  231019. }
  231020. }
  231021. }
  231022. }
  231023. return false;
  231024. }
  231025. void AppleRemoteDevice::handleCallbackInternal()
  231026. {
  231027. int totalValues = 0;
  231028. AbsoluteTime nullTime = { 0, 0 };
  231029. char cookies [12];
  231030. int numCookies = 0;
  231031. while (numCookies < numElementsInArray (cookies))
  231032. {
  231033. IOHIDEventStruct e;
  231034. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  231035. break;
  231036. if ((int) e.elementCookie == 19)
  231037. {
  231038. remoteId = e.value;
  231039. buttonPressed (switched, false);
  231040. }
  231041. else
  231042. {
  231043. totalValues += e.value;
  231044. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  231045. }
  231046. }
  231047. cookies [numCookies++] = 0;
  231048. //DBG (String::toHexString ((uint8*) cookies, numCookies, 1) + " " + String (totalValues));
  231049. static const char buttonPatterns[] =
  231050. {
  231051. 0x1f, 0x14, 0x12, 0x1f, 0x14, 0x12, 0,
  231052. 0x1f, 0x15, 0x12, 0x1f, 0x15, 0x12, 0,
  231053. 0x1f, 0x1d, 0x1c, 0x12, 0,
  231054. 0x1f, 0x1e, 0x1c, 0x12, 0,
  231055. 0x1f, 0x16, 0x12, 0x1f, 0x16, 0x12, 0,
  231056. 0x1f, 0x17, 0x12, 0x1f, 0x17, 0x12, 0,
  231057. 0x1f, 0x12, 0x04, 0x02, 0,
  231058. 0x1f, 0x12, 0x03, 0x02, 0,
  231059. 0x1f, 0x12, 0x1f, 0x12, 0,
  231060. 0x23, 0x1f, 0x12, 0x23, 0x1f, 0x12, 0,
  231061. 19, 0
  231062. };
  231063. int buttonNum = (int) menuButton;
  231064. int i = 0;
  231065. while (i < numElementsInArray (buttonPatterns))
  231066. {
  231067. if (strcmp (cookies, buttonPatterns + i) == 0)
  231068. {
  231069. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  231070. break;
  231071. }
  231072. i += (int) strlen (buttonPatterns + i) + 1;
  231073. ++buttonNum;
  231074. }
  231075. }
  231076. #endif
  231077. /*** End of inlined file: juce_mac_AppleRemote.mm ***/
  231078. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  231079. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231080. // compiled on its own).
  231081. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  231082. #if JUCE_MAC
  231083. END_JUCE_NAMESPACE
  231084. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  231085. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  231086. {
  231087. CriticalSection* contextLock;
  231088. bool needsUpdate;
  231089. }
  231090. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  231091. - (bool) makeActive;
  231092. - (void) makeInactive;
  231093. - (void) reshape;
  231094. @end
  231095. @implementation ThreadSafeNSOpenGLView
  231096. - (id) initWithFrame: (NSRect) frameRect
  231097. pixelFormat: (NSOpenGLPixelFormat*) format
  231098. {
  231099. contextLock = new CriticalSection();
  231100. self = [super initWithFrame: frameRect pixelFormat: format];
  231101. if (self != nil)
  231102. [[NSNotificationCenter defaultCenter] addObserver: self
  231103. selector: @selector (_surfaceNeedsUpdate:)
  231104. name: NSViewGlobalFrameDidChangeNotification
  231105. object: self];
  231106. return self;
  231107. }
  231108. - (void) dealloc
  231109. {
  231110. [[NSNotificationCenter defaultCenter] removeObserver: self];
  231111. delete contextLock;
  231112. [super dealloc];
  231113. }
  231114. - (bool) makeActive
  231115. {
  231116. const ScopedLock sl (*contextLock);
  231117. if ([self openGLContext] == 0)
  231118. return false;
  231119. [[self openGLContext] makeCurrentContext];
  231120. if (needsUpdate)
  231121. {
  231122. [super update];
  231123. needsUpdate = false;
  231124. }
  231125. return true;
  231126. }
  231127. - (void) makeInactive
  231128. {
  231129. const ScopedLock sl (*contextLock);
  231130. [NSOpenGLContext clearCurrentContext];
  231131. }
  231132. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  231133. {
  231134. const ScopedLock sl (*contextLock);
  231135. needsUpdate = true;
  231136. }
  231137. - (void) update
  231138. {
  231139. const ScopedLock sl (*contextLock);
  231140. needsUpdate = true;
  231141. }
  231142. - (void) reshape
  231143. {
  231144. const ScopedLock sl (*contextLock);
  231145. needsUpdate = true;
  231146. }
  231147. @end
  231148. BEGIN_JUCE_NAMESPACE
  231149. class WindowedGLContext : public OpenGLContext
  231150. {
  231151. public:
  231152. WindowedGLContext (Component* const component,
  231153. const OpenGLPixelFormat& pixelFormat_,
  231154. NSOpenGLContext* sharedContext)
  231155. : renderContext (0),
  231156. pixelFormat (pixelFormat_)
  231157. {
  231158. jassert (component != 0);
  231159. NSOpenGLPixelFormatAttribute attribs [64];
  231160. int n = 0;
  231161. attribs[n++] = NSOpenGLPFADoubleBuffer;
  231162. attribs[n++] = NSOpenGLPFAAccelerated;
  231163. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  231164. attribs[n++] = NSOpenGLPFAColorSize;
  231165. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  231166. pixelFormat.greenBits,
  231167. pixelFormat.blueBits);
  231168. attribs[n++] = NSOpenGLPFAAlphaSize;
  231169. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  231170. attribs[n++] = NSOpenGLPFADepthSize;
  231171. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  231172. attribs[n++] = NSOpenGLPFAStencilSize;
  231173. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  231174. attribs[n++] = NSOpenGLPFAAccumSize;
  231175. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  231176. pixelFormat.accumulationBufferGreenBits,
  231177. pixelFormat.accumulationBufferBlueBits,
  231178. pixelFormat.accumulationBufferAlphaBits);
  231179. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  231180. attribs[n++] = NSOpenGLPFASampleBuffers;
  231181. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  231182. attribs[n++] = NSOpenGLPFAClosestPolicy;
  231183. attribs[n++] = NSOpenGLPFANoRecovery;
  231184. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  231185. NSOpenGLPixelFormat* format
  231186. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  231187. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  231188. pixelFormat: format];
  231189. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  231190. shareContext: sharedContext] autorelease];
  231191. const GLint swapInterval = 1;
  231192. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  231193. [view setOpenGLContext: renderContext];
  231194. [renderContext setView: view];
  231195. [format release];
  231196. viewHolder = new NSViewComponentInternal (view, component);
  231197. }
  231198. ~WindowedGLContext()
  231199. {
  231200. makeInactive();
  231201. [renderContext clearDrawable];
  231202. viewHolder = 0;
  231203. }
  231204. bool makeActive() const throw()
  231205. {
  231206. jassert (renderContext != 0);
  231207. [view makeActive];
  231208. return isActive();
  231209. }
  231210. bool makeInactive() const throw()
  231211. {
  231212. [view makeInactive];
  231213. return true;
  231214. }
  231215. bool isActive() const throw()
  231216. {
  231217. return [NSOpenGLContext currentContext] == renderContext;
  231218. }
  231219. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  231220. void* getRawContext() const throw() { return renderContext; }
  231221. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  231222. {
  231223. }
  231224. void swapBuffers()
  231225. {
  231226. [renderContext flushBuffer];
  231227. }
  231228. bool setSwapInterval (const int numFramesPerSwap)
  231229. {
  231230. [renderContext setValues: (const GLint*) &numFramesPerSwap
  231231. forParameter: NSOpenGLCPSwapInterval];
  231232. return true;
  231233. }
  231234. int getSwapInterval() const
  231235. {
  231236. GLint numFrames = 0;
  231237. [renderContext getValues: &numFrames
  231238. forParameter: NSOpenGLCPSwapInterval];
  231239. return numFrames;
  231240. }
  231241. void repaint()
  231242. {
  231243. // we need to invalidate the juce view that holds this gl view, to make it
  231244. // cause a repaint callback
  231245. NSView* v = (NSView*) viewHolder->view;
  231246. NSRect r = [v frame];
  231247. // bit of a bodge here.. if we only invalidate the area of the gl component,
  231248. // it's completely covered by the NSOpenGLView, so the OS throws away the
  231249. // repaint message, thus never causing our paint() callback, and never repainting
  231250. // the comp. So invalidating just a little bit around the edge helps..
  231251. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  231252. }
  231253. void* getNativeWindowHandle() const { return viewHolder->view; }
  231254. juce_UseDebuggingNewOperator
  231255. NSOpenGLContext* renderContext;
  231256. ThreadSafeNSOpenGLView* view;
  231257. private:
  231258. OpenGLPixelFormat pixelFormat;
  231259. ScopedPointer <NSViewComponentInternal> viewHolder;
  231260. WindowedGLContext (const WindowedGLContext&);
  231261. WindowedGLContext& operator= (const WindowedGLContext&);
  231262. };
  231263. OpenGLContext* OpenGLComponent::createContext()
  231264. {
  231265. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  231266. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  231267. return (c->renderContext != 0) ? c.release() : 0;
  231268. }
  231269. void* OpenGLComponent::getNativeWindowHandle() const
  231270. {
  231271. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  231272. : 0;
  231273. }
  231274. void juce_glViewport (const int w, const int h)
  231275. {
  231276. glViewport (0, 0, w, h);
  231277. }
  231278. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  231279. OwnedArray <OpenGLPixelFormat>& results)
  231280. {
  231281. /* GLint attribs [64];
  231282. int n = 0;
  231283. attribs[n++] = AGL_RGBA;
  231284. attribs[n++] = AGL_DOUBLEBUFFER;
  231285. attribs[n++] = AGL_ACCELERATED;
  231286. attribs[n++] = AGL_NO_RECOVERY;
  231287. attribs[n++] = AGL_NONE;
  231288. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  231289. while (p != 0)
  231290. {
  231291. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  231292. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  231293. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  231294. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  231295. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  231296. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  231297. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  231298. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  231299. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  231300. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  231301. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  231302. results.add (pf);
  231303. p = aglNextPixelFormat (p);
  231304. }*/
  231305. //jassertfalse //xxx can't see how you do this in cocoa!
  231306. }
  231307. #else
  231308. END_JUCE_NAMESPACE
  231309. @interface JuceGLView : UIView
  231310. {
  231311. }
  231312. + (Class) layerClass;
  231313. @end
  231314. @implementation JuceGLView
  231315. + (Class) layerClass
  231316. {
  231317. return [CAEAGLLayer class];
  231318. }
  231319. @end
  231320. BEGIN_JUCE_NAMESPACE
  231321. class GLESContext : public OpenGLContext
  231322. {
  231323. public:
  231324. GLESContext (UIViewComponentPeer* peer,
  231325. Component* const component_,
  231326. const OpenGLPixelFormat& pixelFormat_,
  231327. const GLESContext* const sharedContext,
  231328. NSUInteger apiType)
  231329. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  231330. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  231331. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  231332. {
  231333. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  231334. view.opaque = YES;
  231335. view.hidden = NO;
  231336. view.backgroundColor = [UIColor blackColor];
  231337. view.userInteractionEnabled = NO;
  231338. glLayer = (CAEAGLLayer*) [view layer];
  231339. [peer->view addSubview: view];
  231340. if (sharedContext != 0)
  231341. context = [[EAGLContext alloc] initWithAPI: apiType
  231342. sharegroup: [sharedContext->context sharegroup]];
  231343. else
  231344. context = [[EAGLContext alloc] initWithAPI: apiType];
  231345. createGLBuffers();
  231346. }
  231347. ~GLESContext()
  231348. {
  231349. makeInactive();
  231350. [context release];
  231351. [view removeFromSuperview];
  231352. [view release];
  231353. freeGLBuffers();
  231354. }
  231355. bool makeActive() const throw()
  231356. {
  231357. jassert (context != 0);
  231358. [EAGLContext setCurrentContext: context];
  231359. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  231360. return true;
  231361. }
  231362. void swapBuffers()
  231363. {
  231364. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  231365. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  231366. }
  231367. bool makeInactive() const throw()
  231368. {
  231369. return [EAGLContext setCurrentContext: nil];
  231370. }
  231371. bool isActive() const throw()
  231372. {
  231373. return [EAGLContext currentContext] == context;
  231374. }
  231375. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  231376. void* getRawContext() const throw() { return glLayer; }
  231377. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  231378. {
  231379. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  231380. if (lastWidth != w || lastHeight != h)
  231381. {
  231382. lastWidth = w;
  231383. lastHeight = h;
  231384. freeGLBuffers();
  231385. createGLBuffers();
  231386. }
  231387. }
  231388. bool setSwapInterval (const int numFramesPerSwap)
  231389. {
  231390. numFrames = numFramesPerSwap;
  231391. return true;
  231392. }
  231393. int getSwapInterval() const
  231394. {
  231395. return numFrames;
  231396. }
  231397. void repaint()
  231398. {
  231399. }
  231400. void createGLBuffers()
  231401. {
  231402. makeActive();
  231403. glGenFramebuffersOES (1, &frameBufferHandle);
  231404. glGenRenderbuffersOES (1, &colorBufferHandle);
  231405. glGenRenderbuffersOES (1, &depthBufferHandle);
  231406. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  231407. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  231408. GLint width, height;
  231409. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  231410. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  231411. if (useDepthBuffer)
  231412. {
  231413. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  231414. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  231415. }
  231416. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  231417. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  231418. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  231419. if (useDepthBuffer)
  231420. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  231421. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  231422. }
  231423. void freeGLBuffers()
  231424. {
  231425. if (frameBufferHandle != 0)
  231426. {
  231427. glDeleteFramebuffersOES (1, &frameBufferHandle);
  231428. frameBufferHandle = 0;
  231429. }
  231430. if (colorBufferHandle != 0)
  231431. {
  231432. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  231433. colorBufferHandle = 0;
  231434. }
  231435. if (depthBufferHandle != 0)
  231436. {
  231437. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  231438. depthBufferHandle = 0;
  231439. }
  231440. }
  231441. juce_UseDebuggingNewOperator
  231442. private:
  231443. Component::SafePointer<Component> component;
  231444. OpenGLPixelFormat pixelFormat;
  231445. JuceGLView* view;
  231446. CAEAGLLayer* glLayer;
  231447. EAGLContext* context;
  231448. bool useDepthBuffer;
  231449. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  231450. int numFrames;
  231451. int lastWidth, lastHeight;
  231452. GLESContext (const GLESContext&);
  231453. GLESContext& operator= (const GLESContext&);
  231454. };
  231455. OpenGLContext* OpenGLComponent::createContext()
  231456. {
  231457. ScopedAutoReleasePool pool;
  231458. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  231459. if (peer != 0)
  231460. return new GLESContext (peer, this, preferredPixelFormat,
  231461. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  231462. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  231463. return 0;
  231464. }
  231465. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  231466. OwnedArray <OpenGLPixelFormat>& /*results*/)
  231467. {
  231468. }
  231469. void juce_glViewport (const int w, const int h)
  231470. {
  231471. glViewport (0, 0, w, h);
  231472. }
  231473. #endif
  231474. #endif
  231475. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  231476. /*** Start of inlined file: juce_mac_MainMenu.mm ***/
  231477. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231478. // compiled on its own).
  231479. #if JUCE_INCLUDED_FILE
  231480. class JuceMainMenuHandler;
  231481. END_JUCE_NAMESPACE
  231482. using namespace JUCE_NAMESPACE;
  231483. #define JuceMenuCallback MakeObjCClassName(JuceMenuCallback)
  231484. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  231485. @interface JuceMenuCallback : NSObject <NSMenuDelegate>
  231486. #else
  231487. @interface JuceMenuCallback : NSObject
  231488. #endif
  231489. {
  231490. JuceMainMenuHandler* owner;
  231491. }
  231492. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_;
  231493. - (void) dealloc;
  231494. - (void) menuItemInvoked: (id) menu;
  231495. - (void) menuNeedsUpdate: (NSMenu*) menu;
  231496. @end
  231497. BEGIN_JUCE_NAMESPACE
  231498. class JuceMainMenuHandler : private MenuBarModelListener,
  231499. private DeletedAtShutdown
  231500. {
  231501. public:
  231502. static JuceMainMenuHandler* instance;
  231503. JuceMainMenuHandler()
  231504. : currentModel (0),
  231505. lastUpdateTime (0)
  231506. {
  231507. callback = [[JuceMenuCallback alloc] initWithOwner: this];
  231508. }
  231509. ~JuceMainMenuHandler()
  231510. {
  231511. setMenu (0);
  231512. jassert (instance == this);
  231513. instance = 0;
  231514. [callback release];
  231515. }
  231516. void setMenu (MenuBarModel* const newMenuBarModel)
  231517. {
  231518. if (currentModel != newMenuBarModel)
  231519. {
  231520. if (currentModel != 0)
  231521. currentModel->removeListener (this);
  231522. currentModel = newMenuBarModel;
  231523. if (currentModel != 0)
  231524. currentModel->addListener (this);
  231525. menuBarItemsChanged (0);
  231526. }
  231527. }
  231528. void addSubMenu (NSMenu* parent, const PopupMenu& child,
  231529. const String& name, const int menuId, const int tag)
  231530. {
  231531. NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
  231532. action: nil
  231533. keyEquivalent: @""];
  231534. [item setTag: tag];
  231535. NSMenu* sub = createMenu (child, name, menuId, tag);
  231536. [parent setSubmenu: sub forItem: item];
  231537. [sub setAutoenablesItems: false];
  231538. [sub release];
  231539. }
  231540. void updateSubMenu (NSMenuItem* parentItem, const PopupMenu& menuToCopy,
  231541. const String& name, const int menuId, const int tag)
  231542. {
  231543. [parentItem setTag: tag];
  231544. NSMenu* menu = [parentItem submenu];
  231545. [menu setTitle: juceStringToNS (name)];
  231546. while ([menu numberOfItems] > 0)
  231547. [menu removeItemAtIndex: 0];
  231548. PopupMenu::MenuItemIterator iter (menuToCopy);
  231549. while (iter.next())
  231550. addMenuItem (iter, menu, menuId, tag);
  231551. [menu setAutoenablesItems: false];
  231552. [menu update];
  231553. }
  231554. void menuBarItemsChanged (MenuBarModel*)
  231555. {
  231556. lastUpdateTime = Time::getMillisecondCounter();
  231557. StringArray menuNames;
  231558. if (currentModel != 0)
  231559. menuNames = currentModel->getMenuBarNames();
  231560. NSMenu* menuBar = [NSApp mainMenu];
  231561. while ([menuBar numberOfItems] > 1 + menuNames.size())
  231562. [menuBar removeItemAtIndex: [menuBar numberOfItems] - 1];
  231563. int menuId = 1;
  231564. for (int i = 0; i < menuNames.size(); ++i)
  231565. {
  231566. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  231567. if (i >= [menuBar numberOfItems] - 1)
  231568. addSubMenu (menuBar, menu, menuNames[i], menuId, i);
  231569. else
  231570. updateSubMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  231571. }
  231572. }
  231573. static void flashMenuBar (NSMenu* menu)
  231574. {
  231575. if ([[menu title] isEqualToString: @"Apple"])
  231576. return;
  231577. [menu retain];
  231578. const unichar f35Key = NSF35FunctionKey;
  231579. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  231580. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"x"
  231581. action: nil
  231582. keyEquivalent: f35String];
  231583. [item setTarget: nil];
  231584. [menu insertItem: item atIndex: [menu numberOfItems]];
  231585. [item release];
  231586. if ([menu indexOfItem: item] >= 0)
  231587. {
  231588. NSEvent* f35Event = [NSEvent keyEventWithType: NSKeyDown
  231589. location: NSZeroPoint
  231590. modifierFlags: NSCommandKeyMask
  231591. timestamp: 0
  231592. windowNumber: 0
  231593. context: [NSGraphicsContext currentContext]
  231594. characters: f35String
  231595. charactersIgnoringModifiers: f35String
  231596. isARepeat: NO
  231597. keyCode: 0];
  231598. [menu performKeyEquivalent: f35Event];
  231599. if ([menu indexOfItem: item] >= 0)
  231600. [menu removeItem: item]; // (this throws if the item isn't actually in the menu)
  231601. }
  231602. [menu release];
  231603. }
  231604. static NSMenuItem* findMenuItem (NSMenu* const menu, const ApplicationCommandTarget::InvocationInfo& info)
  231605. {
  231606. for (NSInteger i = [menu numberOfItems]; --i >= 0;)
  231607. {
  231608. NSMenuItem* m = [menu itemAtIndex: i];
  231609. if ([m tag] == info.commandID)
  231610. return m;
  231611. if ([m submenu] != 0)
  231612. {
  231613. NSMenuItem* found = findMenuItem ([m submenu], info);
  231614. if (found != 0)
  231615. return found;
  231616. }
  231617. }
  231618. return 0;
  231619. }
  231620. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  231621. {
  231622. NSMenuItem* item = findMenuItem ([NSApp mainMenu], info);
  231623. if (item != 0)
  231624. flashMenuBar ([item menu]);
  231625. }
  231626. void updateMenus()
  231627. {
  231628. if (Time::getMillisecondCounter() > lastUpdateTime + 500)
  231629. menuBarItemsChanged (0);
  231630. }
  231631. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  231632. {
  231633. if (currentModel != 0)
  231634. {
  231635. if (commandManager != 0)
  231636. {
  231637. ApplicationCommandTarget::InvocationInfo info (commandId);
  231638. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  231639. commandManager->invoke (info, true);
  231640. }
  231641. currentModel->menuItemSelected (commandId, topLevelIndex);
  231642. }
  231643. }
  231644. MenuBarModel* currentModel;
  231645. uint32 lastUpdateTime;
  231646. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  231647. const int topLevelMenuId, const int topLevelIndex)
  231648. {
  231649. NSString* text = juceStringToNS (iter.itemName.upToFirstOccurrenceOf ("<end>", false, true));
  231650. if (text == 0)
  231651. text = @"";
  231652. if (iter.isSeparator)
  231653. {
  231654. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  231655. }
  231656. else if (iter.isSectionHeader)
  231657. {
  231658. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  231659. action: nil
  231660. keyEquivalent: @""];
  231661. [item setEnabled: false];
  231662. }
  231663. else if (iter.subMenu != 0)
  231664. {
  231665. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  231666. action: nil
  231667. keyEquivalent: @""];
  231668. [item setTag: iter.itemId];
  231669. [item setEnabled: iter.isEnabled];
  231670. NSMenu* sub = createMenu (*iter.subMenu, iter.itemName, topLevelMenuId, topLevelIndex);
  231671. [sub setDelegate: nil];
  231672. [menuToAddTo setSubmenu: sub forItem: item];
  231673. [sub release];
  231674. }
  231675. else
  231676. {
  231677. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  231678. action: @selector (menuItemInvoked:)
  231679. keyEquivalent: @""];
  231680. [item setTag: iter.itemId];
  231681. [item setEnabled: iter.isEnabled];
  231682. [item setState: iter.isTicked ? NSOnState : NSOffState];
  231683. [item setTarget: (id) callback];
  231684. NSMutableArray* info = [NSMutableArray arrayWithObject: [NSNumber numberWithUnsignedLongLong: (pointer_sized_int) (void*) iter.commandManager]];
  231685. [info addObject: [NSNumber numberWithInt: topLevelIndex]];
  231686. [item setRepresentedObject: info];
  231687. if (iter.commandManager != 0)
  231688. {
  231689. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  231690. ->getKeyPressesAssignedToCommand (iter.itemId));
  231691. if (keyPresses.size() > 0)
  231692. {
  231693. const KeyPress& kp = keyPresses.getReference(0);
  231694. if (kp.getKeyCode() != KeyPress::backspaceKey
  231695. && kp.getKeyCode() != KeyPress::deleteKey) // (adding these is annoying because it flashes the menu bar
  231696. // every time you press the key while editing text)
  231697. {
  231698. juce_wchar key = kp.getTextCharacter();
  231699. if (kp.getKeyCode() == KeyPress::backspaceKey)
  231700. key = NSBackspaceCharacter;
  231701. else if (kp.getKeyCode() == KeyPress::deleteKey)
  231702. key = NSDeleteCharacter;
  231703. else if (key == 0)
  231704. key = (juce_wchar) kp.getKeyCode();
  231705. unsigned int mods = 0;
  231706. if (kp.getModifiers().isShiftDown())
  231707. mods |= NSShiftKeyMask;
  231708. if (kp.getModifiers().isCtrlDown())
  231709. mods |= NSControlKeyMask;
  231710. if (kp.getModifiers().isAltDown())
  231711. mods |= NSAlternateKeyMask;
  231712. if (kp.getModifiers().isCommandDown())
  231713. mods |= NSCommandKeyMask;
  231714. [item setKeyEquivalent: juceStringToNS (String::charToString (key))];
  231715. [item setKeyEquivalentModifierMask: mods];
  231716. }
  231717. }
  231718. }
  231719. }
  231720. }
  231721. JuceMenuCallback* callback;
  231722. private:
  231723. NSMenu* createMenu (const PopupMenu menu,
  231724. const String& menuName,
  231725. const int topLevelMenuId,
  231726. const int topLevelIndex)
  231727. {
  231728. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  231729. [m setAutoenablesItems: false];
  231730. [m setDelegate: callback];
  231731. PopupMenu::MenuItemIterator iter (menu);
  231732. while (iter.next())
  231733. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  231734. [m update];
  231735. return m;
  231736. }
  231737. };
  231738. JuceMainMenuHandler* JuceMainMenuHandler::instance = 0;
  231739. END_JUCE_NAMESPACE
  231740. @implementation JuceMenuCallback
  231741. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_
  231742. {
  231743. [super init];
  231744. owner = owner_;
  231745. return self;
  231746. }
  231747. - (void) dealloc
  231748. {
  231749. [super dealloc];
  231750. }
  231751. - (void) menuItemInvoked: (id) menu
  231752. {
  231753. NSMenuItem* item = (NSMenuItem*) menu;
  231754. if ([[item representedObject] isKindOfClass: [NSArray class]])
  231755. {
  231756. // 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
  231757. // our own components, which may have wanted to intercept it. So, rather than dispatching directly, we'll feed it back
  231758. // into the focused component and let it trigger the menu item indirectly.
  231759. NSEvent* e = [NSApp currentEvent];
  231760. if ([e type] == NSKeyDown || [e type] == NSKeyUp)
  231761. {
  231762. if (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent() != 0)
  231763. {
  231764. JUCE_NAMESPACE::NSViewComponentPeer* peer = dynamic_cast <JUCE_NAMESPACE::NSViewComponentPeer*> (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent()->getPeer());
  231765. if (peer != 0)
  231766. {
  231767. if ([e type] == NSKeyDown)
  231768. peer->redirectKeyDown (e);
  231769. else
  231770. peer->redirectKeyUp (e);
  231771. return;
  231772. }
  231773. }
  231774. }
  231775. NSArray* info = (NSArray*) [item representedObject];
  231776. owner->invoke ((int) [item tag],
  231777. (ApplicationCommandManager*) (pointer_sized_int)
  231778. [((NSNumber*) [info objectAtIndex: 0]) unsignedLongLongValue],
  231779. (int) [((NSNumber*) [info objectAtIndex: 1]) intValue]);
  231780. }
  231781. }
  231782. - (void) menuNeedsUpdate: (NSMenu*) menu;
  231783. {
  231784. (void) menu;
  231785. if (JuceMainMenuHandler::instance != 0)
  231786. JuceMainMenuHandler::instance->updateMenus();
  231787. }
  231788. @end
  231789. BEGIN_JUCE_NAMESPACE
  231790. static NSMenu* createStandardAppMenu (NSMenu* menu, const String& appName,
  231791. const PopupMenu* extraItems)
  231792. {
  231793. if (extraItems != 0 && JuceMainMenuHandler::instance != 0 && extraItems->getNumItems() > 0)
  231794. {
  231795. PopupMenu::MenuItemIterator iter (*extraItems);
  231796. while (iter.next())
  231797. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  231798. [menu addItem: [NSMenuItem separatorItem]];
  231799. }
  231800. NSMenuItem* item;
  231801. // Services...
  231802. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Services", nil)
  231803. action: nil keyEquivalent: @""];
  231804. [menu addItem: item];
  231805. [item release];
  231806. NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle: @"Services"];
  231807. [menu setSubmenu: servicesMenu forItem: item];
  231808. [NSApp setServicesMenu: servicesMenu];
  231809. [servicesMenu release];
  231810. [menu addItem: [NSMenuItem separatorItem]];
  231811. // Hide + Show stuff...
  231812. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Hide " + appName)
  231813. action: @selector (hide:) keyEquivalent: @"h"];
  231814. [item setTarget: NSApp];
  231815. [menu addItem: item];
  231816. [item release];
  231817. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Hide Others", nil)
  231818. action: @selector (hideOtherApplications:) keyEquivalent: @"h"];
  231819. [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
  231820. [item setTarget: NSApp];
  231821. [menu addItem: item];
  231822. [item release];
  231823. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Show All", nil)
  231824. action: @selector (unhideAllApplications:) keyEquivalent: @""];
  231825. [item setTarget: NSApp];
  231826. [menu addItem: item];
  231827. [item release];
  231828. [menu addItem: [NSMenuItem separatorItem]];
  231829. // Quit item....
  231830. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Quit " + appName)
  231831. action: @selector (terminate:) keyEquivalent: @"q"];
  231832. [item setTarget: NSApp];
  231833. [menu addItem: item];
  231834. [item release];
  231835. return menu;
  231836. }
  231837. // Since our app has no NIB, this initialises a standard app menu...
  231838. static void rebuildMainMenu (const PopupMenu* extraItems)
  231839. {
  231840. // this can't be used in a plugin!
  231841. jassert (JUCEApplication::getInstance() != 0);
  231842. if (JUCEApplication::getInstance() != 0)
  231843. {
  231844. const ScopedAutoReleasePool pool;
  231845. NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: @"MainMenu"];
  231846. NSMenuItem* item = [mainMenu addItemWithTitle: @"Apple" action: nil keyEquivalent: @""];
  231847. NSMenu* appMenu = [[NSMenu alloc] initWithTitle: @"Apple"];
  231848. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  231849. [mainMenu setSubmenu: appMenu forItem: item];
  231850. [NSApp setMainMenu: mainMenu];
  231851. createStandardAppMenu (appMenu, JUCEApplication::getInstance()->getApplicationName(), extraItems);
  231852. [appMenu release];
  231853. [mainMenu release];
  231854. }
  231855. }
  231856. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  231857. const PopupMenu* extraAppleMenuItems)
  231858. {
  231859. if (getMacMainMenu() != newMenuBarModel)
  231860. {
  231861. const ScopedAutoReleasePool pool;
  231862. if (newMenuBarModel == 0)
  231863. {
  231864. delete JuceMainMenuHandler::instance;
  231865. jassert (JuceMainMenuHandler::instance == 0); // should be zeroed in the destructor
  231866. jassert (extraAppleMenuItems == 0); // you can't specify some extra items without also supplying a model
  231867. extraAppleMenuItems = 0;
  231868. }
  231869. else
  231870. {
  231871. if (JuceMainMenuHandler::instance == 0)
  231872. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  231873. JuceMainMenuHandler::instance->setMenu (newMenuBarModel);
  231874. }
  231875. }
  231876. rebuildMainMenu (extraAppleMenuItems);
  231877. if (newMenuBarModel != 0)
  231878. newMenuBarModel->menuItemsChanged();
  231879. }
  231880. MenuBarModel* MenuBarModel::getMacMainMenu()
  231881. {
  231882. return JuceMainMenuHandler::instance != 0
  231883. ? JuceMainMenuHandler::instance->currentModel : 0;
  231884. }
  231885. void initialiseMainMenu()
  231886. {
  231887. if (JUCEApplication::getInstance() != 0) // only needed in an app
  231888. rebuildMainMenu (0);
  231889. }
  231890. #endif
  231891. /*** End of inlined file: juce_mac_MainMenu.mm ***/
  231892. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  231893. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231894. // compiled on its own).
  231895. #if JUCE_INCLUDED_FILE
  231896. #if JUCE_MAC
  231897. END_JUCE_NAMESPACE
  231898. using namespace JUCE_NAMESPACE;
  231899. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  231900. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  231901. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  231902. #else
  231903. @interface JuceFileChooserDelegate : NSObject
  231904. #endif
  231905. {
  231906. StringArray* filters;
  231907. }
  231908. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  231909. - (void) dealloc;
  231910. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  231911. @end
  231912. @implementation JuceFileChooserDelegate
  231913. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  231914. {
  231915. [super init];
  231916. filters = filters_;
  231917. return self;
  231918. }
  231919. - (void) dealloc
  231920. {
  231921. delete filters;
  231922. [super dealloc];
  231923. }
  231924. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  231925. {
  231926. (void) sender;
  231927. const File f (nsStringToJuce (filename));
  231928. for (int i = filters->size(); --i >= 0;)
  231929. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  231930. return true;
  231931. return f.isDirectory();
  231932. }
  231933. @end
  231934. BEGIN_JUCE_NAMESPACE
  231935. void FileChooser::showPlatformDialog (Array<File>& results,
  231936. const String& title,
  231937. const File& currentFileOrDirectory,
  231938. const String& filter,
  231939. bool selectsDirectory,
  231940. bool selectsFiles,
  231941. bool isSaveDialogue,
  231942. bool warnAboutOverwritingExistingFiles,
  231943. bool selectMultipleFiles,
  231944. FilePreviewComponent* extraInfoComponent)
  231945. {
  231946. const ScopedAutoReleasePool pool;
  231947. StringArray* filters = new StringArray();
  231948. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  231949. filters->trim();
  231950. filters->removeEmptyStrings();
  231951. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  231952. [delegate autorelease];
  231953. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  231954. : [NSOpenPanel openPanel];
  231955. [panel setTitle: juceStringToNS (title)];
  231956. if (! isSaveDialogue)
  231957. {
  231958. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  231959. [openPanel setCanChooseDirectories: selectsDirectory];
  231960. [openPanel setCanChooseFiles: selectsFiles];
  231961. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  231962. }
  231963. [panel setDelegate: delegate];
  231964. if (isSaveDialogue || selectsDirectory)
  231965. [panel setCanCreateDirectories: YES];
  231966. String directory, filename;
  231967. if (currentFileOrDirectory.isDirectory())
  231968. {
  231969. directory = currentFileOrDirectory.getFullPathName();
  231970. }
  231971. else
  231972. {
  231973. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  231974. filename = currentFileOrDirectory.getFileName();
  231975. }
  231976. if ([panel runModalForDirectory: juceStringToNS (directory)
  231977. file: juceStringToNS (filename)]
  231978. == NSOKButton)
  231979. {
  231980. if (isSaveDialogue)
  231981. {
  231982. results.add (File (nsStringToJuce ([panel filename])));
  231983. }
  231984. else
  231985. {
  231986. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  231987. NSArray* urls = [openPanel filenames];
  231988. for (unsigned int i = 0; i < [urls count]; ++i)
  231989. {
  231990. NSString* f = [urls objectAtIndex: i];
  231991. results.add (File (nsStringToJuce (f)));
  231992. }
  231993. }
  231994. }
  231995. [panel setDelegate: nil];
  231996. }
  231997. #else
  231998. void FileChooser::showPlatformDialog (Array<File>& results,
  231999. const String& title,
  232000. const File& currentFileOrDirectory,
  232001. const String& filter,
  232002. bool selectsDirectory,
  232003. bool selectsFiles,
  232004. bool isSaveDialogue,
  232005. bool warnAboutOverwritingExistingFiles,
  232006. bool selectMultipleFiles,
  232007. FilePreviewComponent* extraInfoComponent)
  232008. {
  232009. const ScopedAutoReleasePool pool;
  232010. jassertfalse; //xxx to do
  232011. }
  232012. #endif
  232013. #endif
  232014. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  232015. /*** Start of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  232016. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232017. // compiled on its own).
  232018. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  232019. END_JUCE_NAMESPACE
  232020. #define NonInterceptingQTMovieView MakeObjCClassName(NonInterceptingQTMovieView)
  232021. @interface NonInterceptingQTMovieView : QTMovieView
  232022. {
  232023. }
  232024. - (id) initWithFrame: (NSRect) frame;
  232025. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent;
  232026. - (NSView*) hitTest: (NSPoint) p;
  232027. @end
  232028. @implementation NonInterceptingQTMovieView
  232029. - (id) initWithFrame: (NSRect) frame
  232030. {
  232031. self = [super initWithFrame: frame];
  232032. [self setNextResponder: [self superview]];
  232033. return self;
  232034. }
  232035. - (void) dealloc
  232036. {
  232037. [super dealloc];
  232038. }
  232039. - (NSView*) hitTest: (NSPoint) point
  232040. {
  232041. return [self isControllerVisible] ? [super hitTest: point] : nil;
  232042. }
  232043. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent
  232044. {
  232045. return YES;
  232046. }
  232047. @end
  232048. BEGIN_JUCE_NAMESPACE
  232049. #define theMovie (static_cast <QTMovie*> (movie))
  232050. QuickTimeMovieComponent::QuickTimeMovieComponent()
  232051. : movie (0)
  232052. {
  232053. setOpaque (true);
  232054. setVisible (true);
  232055. QTMovieView* view = [[NonInterceptingQTMovieView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)];
  232056. setView (view);
  232057. [view release];
  232058. }
  232059. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  232060. {
  232061. closeMovie();
  232062. setView (0);
  232063. }
  232064. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  232065. {
  232066. return true;
  232067. }
  232068. static QTMovie* openMovieFromStream (InputStream* movieStream, File& movieFile)
  232069. {
  232070. // unfortunately, QTMovie objects can only be created on the main thread..
  232071. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  232072. QTMovie* movie = 0;
  232073. FileInputStream* const fin = dynamic_cast <FileInputStream*> (movieStream);
  232074. if (fin != 0)
  232075. {
  232076. movieFile = fin->getFile();
  232077. movie = [QTMovie movieWithFile: juceStringToNS (movieFile.getFullPathName())
  232078. error: nil];
  232079. }
  232080. else
  232081. {
  232082. MemoryBlock temp;
  232083. movieStream->readIntoMemoryBlock (temp);
  232084. const char* const suffixesToTry[] = { ".mov", ".mp3", ".avi", ".m4a" };
  232085. for (int i = 0; i < numElementsInArray (suffixesToTry); ++i)
  232086. {
  232087. movie = [QTMovie movieWithDataReference: [QTDataReference dataReferenceWithReferenceToData: [NSData dataWithBytes: temp.getData()
  232088. length: temp.getSize()]
  232089. name: [NSString stringWithUTF8String: suffixesToTry[i]]
  232090. MIMEType: @""]
  232091. error: nil];
  232092. if (movie != 0)
  232093. break;
  232094. }
  232095. }
  232096. return movie;
  232097. }
  232098. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  232099. const bool isControllerVisible_)
  232100. {
  232101. return loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible_);
  232102. }
  232103. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  232104. const bool controllerVisible_)
  232105. {
  232106. closeMovie();
  232107. if (getPeer() == 0)
  232108. {
  232109. // To open a movie, this component must be visible inside a functioning window, so that
  232110. // the QT control can be assigned to the window.
  232111. jassertfalse;
  232112. return false;
  232113. }
  232114. movie = openMovieFromStream (movieStream, movieFile);
  232115. [theMovie retain];
  232116. QTMovieView* view = (QTMovieView*) getView();
  232117. [view setMovie: theMovie];
  232118. [view setControllerVisible: controllerVisible_];
  232119. setLooping (looping);
  232120. return movie != nil;
  232121. }
  232122. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  232123. const bool isControllerVisible_)
  232124. {
  232125. // unfortunately, QTMovie objects can only be created on the main thread..
  232126. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  232127. closeMovie();
  232128. if (getPeer() == 0)
  232129. {
  232130. // To open a movie, this component must be visible inside a functioning window, so that
  232131. // the QT control can be assigned to the window.
  232132. jassertfalse;
  232133. return false;
  232134. }
  232135. NSURL* url = [NSURL URLWithString: juceStringToNS (movieURL.toString (true))];
  232136. NSError* err;
  232137. if ([QTMovie canInitWithURL: url])
  232138. movie = [QTMovie movieWithURL: url error: &err];
  232139. [theMovie retain];
  232140. QTMovieView* view = (QTMovieView*) getView();
  232141. [view setMovie: theMovie];
  232142. [view setControllerVisible: controllerVisible];
  232143. setLooping (looping);
  232144. return movie != nil;
  232145. }
  232146. void QuickTimeMovieComponent::closeMovie()
  232147. {
  232148. stop();
  232149. QTMovieView* view = (QTMovieView*) getView();
  232150. [view setMovie: nil];
  232151. [theMovie release];
  232152. movie = 0;
  232153. movieFile = File::nonexistent;
  232154. }
  232155. bool QuickTimeMovieComponent::isMovieOpen() const
  232156. {
  232157. return movie != nil;
  232158. }
  232159. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  232160. {
  232161. return movieFile;
  232162. }
  232163. void QuickTimeMovieComponent::play()
  232164. {
  232165. [theMovie play];
  232166. }
  232167. void QuickTimeMovieComponent::stop()
  232168. {
  232169. [theMovie stop];
  232170. }
  232171. bool QuickTimeMovieComponent::isPlaying() const
  232172. {
  232173. return movie != 0 && [theMovie rate] != 0;
  232174. }
  232175. void QuickTimeMovieComponent::setPosition (const double seconds)
  232176. {
  232177. if (movie != 0)
  232178. {
  232179. QTTime t;
  232180. t.timeValue = (uint64) (100000.0 * seconds);
  232181. t.timeScale = 100000;
  232182. t.flags = 0;
  232183. [theMovie setCurrentTime: t];
  232184. }
  232185. }
  232186. double QuickTimeMovieComponent::getPosition() const
  232187. {
  232188. if (movie == 0)
  232189. return 0.0;
  232190. QTTime t = [theMovie currentTime];
  232191. return t.timeValue / (double) t.timeScale;
  232192. }
  232193. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  232194. {
  232195. [theMovie setRate: newSpeed];
  232196. }
  232197. double QuickTimeMovieComponent::getMovieDuration() const
  232198. {
  232199. if (movie == 0)
  232200. return 0.0;
  232201. QTTime t = [theMovie duration];
  232202. return t.timeValue / (double) t.timeScale;
  232203. }
  232204. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  232205. {
  232206. looping = shouldLoop;
  232207. [theMovie setAttribute: [NSNumber numberWithBool: shouldLoop]
  232208. forKey: QTMovieLoopsAttribute];
  232209. }
  232210. bool QuickTimeMovieComponent::isLooping() const
  232211. {
  232212. return looping;
  232213. }
  232214. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  232215. {
  232216. [theMovie setVolume: newVolume];
  232217. }
  232218. float QuickTimeMovieComponent::getMovieVolume() const
  232219. {
  232220. return movie != 0 ? [theMovie volume] : 0.0f;
  232221. }
  232222. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  232223. {
  232224. width = 0;
  232225. height = 0;
  232226. if (movie != 0)
  232227. {
  232228. NSSize s = [[theMovie attributeForKey: QTMovieNaturalSizeAttribute] sizeValue];
  232229. width = (int) s.width;
  232230. height = (int) s.height;
  232231. }
  232232. }
  232233. void QuickTimeMovieComponent::paint (Graphics& g)
  232234. {
  232235. if (movie == 0)
  232236. g.fillAll (Colours::black);
  232237. }
  232238. bool QuickTimeMovieComponent::isControllerVisible() const
  232239. {
  232240. return controllerVisible;
  232241. }
  232242. void QuickTimeMovieComponent::goToStart()
  232243. {
  232244. setPosition (0.0);
  232245. }
  232246. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  232247. const RectanglePlacement& placement)
  232248. {
  232249. int normalWidth, normalHeight;
  232250. getMovieNormalSize (normalWidth, normalHeight);
  232251. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  232252. {
  232253. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  232254. placement.applyTo (x, y, w, h,
  232255. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  232256. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  232257. if (w > 0 && h > 0)
  232258. {
  232259. setBounds (roundToInt (x), roundToInt (y),
  232260. roundToInt (w), roundToInt (h));
  232261. }
  232262. }
  232263. else
  232264. {
  232265. setBounds (spaceToFitWithin);
  232266. }
  232267. }
  232268. #if ! (JUCE_MAC && JUCE_64BIT)
  232269. bool juce_OpenQuickTimeMovieFromStream (InputStream* movieStream, Movie& result, Handle& dataHandle)
  232270. {
  232271. if (movieStream == 0)
  232272. return false;
  232273. File file;
  232274. QTMovie* movie = openMovieFromStream (movieStream, file);
  232275. if (movie != nil)
  232276. result = [movie quickTimeMovie];
  232277. return movie != nil;
  232278. }
  232279. #endif
  232280. #endif
  232281. /*** End of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  232282. /*** Start of inlined file: juce_mac_AudioCDBurner.mm ***/
  232283. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232284. // compiled on its own).
  232285. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  232286. const int kilobytesPerSecond1x = 176;
  232287. END_JUCE_NAMESPACE
  232288. #define OpenDiskDevice MakeObjCClassName(OpenDiskDevice)
  232289. @interface OpenDiskDevice : NSObject
  232290. {
  232291. @public
  232292. DRDevice* device;
  232293. NSMutableArray* tracks;
  232294. bool underrunProtection;
  232295. }
  232296. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device;
  232297. - (void) dealloc;
  232298. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) numSamples_;
  232299. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  232300. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed;
  232301. @end
  232302. #define AudioTrackProducer MakeObjCClassName(AudioTrackProducer)
  232303. @interface AudioTrackProducer : NSObject
  232304. {
  232305. JUCE_NAMESPACE::AudioSource* source;
  232306. int readPosition, lengthInFrames;
  232307. }
  232308. - (AudioTrackProducer*) init: (int) lengthInFrames;
  232309. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) lengthInSamples;
  232310. - (void) dealloc;
  232311. - (void) setupTrackProperties: (DRTrack*) track;
  232312. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  232313. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  232314. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  232315. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  232316. toMedia:(NSDictionary*)mediaInfo;
  232317. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  232318. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  232319. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  232320. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  232321. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  232322. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  232323. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  232324. ioFlags:(uint32_t*)flags;
  232325. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  232326. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  232327. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  232328. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  232329. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  232330. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  232331. ioFlags:(uint32_t*)flags;
  232332. @end
  232333. @implementation OpenDiskDevice
  232334. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device_
  232335. {
  232336. [super init];
  232337. device = device_;
  232338. tracks = [[NSMutableArray alloc] init];
  232339. underrunProtection = true;
  232340. return self;
  232341. }
  232342. - (void) dealloc
  232343. {
  232344. [tracks release];
  232345. [super dealloc];
  232346. }
  232347. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) numSamples_
  232348. {
  232349. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  232350. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  232351. [p setupTrackProperties: t];
  232352. [tracks addObject: t];
  232353. [t release];
  232354. [p release];
  232355. }
  232356. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  232357. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed
  232358. {
  232359. DRBurn* burn = [DRBurn burnForDevice: device];
  232360. if (! [device acquireExclusiveAccess])
  232361. {
  232362. *error = "Couldn't open or write to the CD device";
  232363. return;
  232364. }
  232365. [device acquireMediaReservation];
  232366. NSMutableDictionary* d = [[burn properties] mutableCopy];
  232367. [d autorelease];
  232368. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  232369. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  232370. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount) forKey: DRBurnCompletionActionKey];
  232371. if (burnSpeed > 0)
  232372. [d setObject: [NSNumber numberWithFloat: burnSpeed * JUCE_NAMESPACE::kilobytesPerSecond1x] forKey: DRBurnRequestedSpeedKey];
  232373. if (! underrunProtection)
  232374. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnUnderrunProtectionKey];
  232375. [burn setProperties: d];
  232376. [burn writeLayout: tracks];
  232377. for (;;)
  232378. {
  232379. JUCE_NAMESPACE::Thread::sleep (300);
  232380. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  232381. if (listener != 0 && listener->audioCDBurnProgress (progress))
  232382. {
  232383. [burn abort];
  232384. *error = "User cancelled the write operation";
  232385. break;
  232386. }
  232387. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  232388. {
  232389. *error = "Write operation failed";
  232390. break;
  232391. }
  232392. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  232393. {
  232394. break;
  232395. }
  232396. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  232397. objectForKey: DRErrorStatusErrorStringKey];
  232398. if ([err length] > 0)
  232399. {
  232400. *error = JUCE_NAMESPACE::String::fromUTF8 ([err UTF8String]);
  232401. break;
  232402. }
  232403. }
  232404. [device releaseMediaReservation];
  232405. [device releaseExclusiveAccess];
  232406. }
  232407. @end
  232408. @implementation AudioTrackProducer
  232409. - (AudioTrackProducer*) init: (int) lengthInFrames_
  232410. {
  232411. lengthInFrames = lengthInFrames_;
  232412. readPosition = 0;
  232413. return self;
  232414. }
  232415. - (void) setupTrackProperties: (DRTrack*) track
  232416. {
  232417. NSMutableDictionary* p = [[track properties] mutableCopy];
  232418. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  232419. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  232420. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  232421. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  232422. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  232423. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  232424. [track setProperties: p];
  232425. [p release];
  232426. }
  232427. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) lengthInSamples
  232428. {
  232429. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  232430. if (s != nil)
  232431. s->source = source_;
  232432. return s;
  232433. }
  232434. - (void) dealloc
  232435. {
  232436. if (source != 0)
  232437. {
  232438. source->releaseResources();
  232439. delete source;
  232440. }
  232441. [super dealloc];
  232442. }
  232443. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  232444. {
  232445. }
  232446. - (BOOL) cleanupTrackAfterVerification: (DRTrack*) track
  232447. {
  232448. return true;
  232449. }
  232450. - (uint64_t) estimateLengthOfTrack: (DRTrack*) track
  232451. {
  232452. return lengthInFrames;
  232453. }
  232454. - (BOOL) prepareTrack: (DRTrack*) track forBurn: (DRBurn*) burn
  232455. toMedia: (NSDictionary*) mediaInfo
  232456. {
  232457. if (source != 0)
  232458. source->prepareToPlay (44100 / 75, 44100);
  232459. readPosition = 0;
  232460. return true;
  232461. }
  232462. - (BOOL) prepareTrackForVerification: (DRTrack*) track
  232463. {
  232464. if (source != 0)
  232465. source->prepareToPlay (44100 / 75, 44100);
  232466. return true;
  232467. }
  232468. - (uint32_t) produceDataForTrack: (DRTrack*) track intoBuffer: (char*) buffer
  232469. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  232470. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  232471. {
  232472. if (source != 0)
  232473. {
  232474. const int numSamples = JUCE_NAMESPACE::jmin ((int) bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  232475. if (numSamples > 0)
  232476. {
  232477. JUCE_NAMESPACE::AudioSampleBuffer tempBuffer (2, numSamples);
  232478. JUCE_NAMESPACE::AudioSourceChannelInfo info;
  232479. info.buffer = &tempBuffer;
  232480. info.startSample = 0;
  232481. info.numSamples = numSamples;
  232482. source->getNextAudioBlock (info);
  232483. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (0),
  232484. buffer, numSamples, 4);
  232485. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (1),
  232486. buffer + 2, numSamples, 4);
  232487. readPosition += numSamples;
  232488. }
  232489. return numSamples * 4;
  232490. }
  232491. return 0;
  232492. }
  232493. - (uint32_t) producePreGapForTrack: (DRTrack*) track
  232494. intoBuffer: (char*) buffer length: (uint32_t) bufferLength
  232495. atAddress: (uint64_t) address blockSize: (uint32_t) blockSize
  232496. ioFlags: (uint32_t*) flags
  232497. {
  232498. zeromem (buffer, bufferLength);
  232499. return bufferLength;
  232500. }
  232501. - (BOOL) verifyDataForTrack: (DRTrack*) track inBuffer: (const char*) buffer
  232502. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  232503. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  232504. {
  232505. return true;
  232506. }
  232507. @end
  232508. BEGIN_JUCE_NAMESPACE
  232509. class AudioCDBurner::Pimpl : public Timer
  232510. {
  232511. public:
  232512. Pimpl (AudioCDBurner& owner_, const int deviceIndex)
  232513. : device (0), owner (owner_)
  232514. {
  232515. DRDevice* dev = [[DRDevice devices] objectAtIndex: deviceIndex];
  232516. if (dev != 0)
  232517. {
  232518. device = [[OpenDiskDevice alloc] initWithDRDevice: dev];
  232519. lastState = getDiskState();
  232520. startTimer (1000);
  232521. }
  232522. }
  232523. ~Pimpl()
  232524. {
  232525. stopTimer();
  232526. [device release];
  232527. }
  232528. void timerCallback()
  232529. {
  232530. const DiskState state = getDiskState();
  232531. if (state != lastState)
  232532. {
  232533. lastState = state;
  232534. owner.sendChangeMessage (&owner);
  232535. }
  232536. }
  232537. DiskState getDiskState() const
  232538. {
  232539. if ([device->device isValid])
  232540. {
  232541. NSDictionary* status = [device->device status];
  232542. NSString* state = [status objectForKey: DRDeviceMediaStateKey];
  232543. if ([state isEqualTo: DRDeviceMediaStateNone])
  232544. {
  232545. if ([[status objectForKey: DRDeviceIsTrayOpenKey] boolValue])
  232546. return trayOpen;
  232547. return noDisc;
  232548. }
  232549. if ([state isEqualTo: DRDeviceMediaStateMediaPresent])
  232550. {
  232551. if ([[[status objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceMediaBlocksFreeKey] intValue] > 0)
  232552. return writableDiskPresent;
  232553. else
  232554. return readOnlyDiskPresent;
  232555. }
  232556. }
  232557. return unknown;
  232558. }
  232559. bool openTray() { return [device->device isValid] && [device->device ejectMedia]; }
  232560. const Array<int> getAvailableWriteSpeeds() const
  232561. {
  232562. Array<int> results;
  232563. if ([device->device isValid])
  232564. {
  232565. NSArray* speeds = [[[device->device status] objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceBurnSpeedsKey];
  232566. for (unsigned int i = 0; i < [speeds count]; ++i)
  232567. {
  232568. const int kbPerSec = [[speeds objectAtIndex: i] intValue];
  232569. results.add (kbPerSec / kilobytesPerSecond1x);
  232570. }
  232571. }
  232572. return results;
  232573. }
  232574. bool setBufferUnderrunProtection (const bool shouldBeEnabled)
  232575. {
  232576. if ([device->device isValid])
  232577. {
  232578. device->underrunProtection = shouldBeEnabled;
  232579. return shouldBeEnabled && [[[device->device status] objectForKey: DRDeviceCanUnderrunProtectCDKey] boolValue];
  232580. }
  232581. return false;
  232582. }
  232583. int getNumAvailableAudioBlocks() const
  232584. {
  232585. return [[[[device->device status] objectForKey: DRDeviceMediaInfoKey]
  232586. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  232587. }
  232588. OpenDiskDevice* device;
  232589. private:
  232590. DiskState lastState;
  232591. AudioCDBurner& owner;
  232592. };
  232593. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  232594. {
  232595. pimpl = new Pimpl (*this, deviceIndex);
  232596. }
  232597. AudioCDBurner::~AudioCDBurner()
  232598. {
  232599. }
  232600. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  232601. {
  232602. ScopedPointer <AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  232603. if (b->pimpl->device == 0)
  232604. b = 0;
  232605. return b.release();
  232606. }
  232607. static NSArray* findDiskBurnerDevices()
  232608. {
  232609. NSMutableArray* results = [NSMutableArray array];
  232610. NSArray* devs = [DRDevice devices];
  232611. if (devs != 0)
  232612. {
  232613. int num = [devs count];
  232614. int i;
  232615. for (i = 0; i < num; ++i)
  232616. {
  232617. NSDictionary* dic = [[devs objectAtIndex: i] info];
  232618. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  232619. if (name != nil)
  232620. [results addObject: name];
  232621. }
  232622. }
  232623. return results;
  232624. }
  232625. const StringArray AudioCDBurner::findAvailableDevices()
  232626. {
  232627. NSArray* names = findDiskBurnerDevices();
  232628. StringArray s;
  232629. for (unsigned int i = 0; i < [names count]; ++i)
  232630. s.add (String::fromUTF8 ([[names objectAtIndex: i] UTF8String]));
  232631. return s;
  232632. }
  232633. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  232634. {
  232635. return pimpl->getDiskState();
  232636. }
  232637. bool AudioCDBurner::isDiskPresent() const
  232638. {
  232639. return getDiskState() == writableDiskPresent;
  232640. }
  232641. bool AudioCDBurner::openTray()
  232642. {
  232643. return pimpl->openTray();
  232644. }
  232645. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  232646. {
  232647. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  232648. DiskState oldState = getDiskState();
  232649. DiskState newState = oldState;
  232650. while (newState == oldState && Time::currentTimeMillis() < timeout)
  232651. {
  232652. newState = getDiskState();
  232653. Thread::sleep (100);
  232654. }
  232655. return newState;
  232656. }
  232657. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  232658. {
  232659. return pimpl->getAvailableWriteSpeeds();
  232660. }
  232661. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  232662. {
  232663. return pimpl->setBufferUnderrunProtection (shouldBeEnabled);
  232664. }
  232665. int AudioCDBurner::getNumAvailableAudioBlocks() const
  232666. {
  232667. return pimpl->getNumAvailableAudioBlocks();
  232668. }
  232669. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  232670. {
  232671. if ([pimpl->device->device isValid])
  232672. {
  232673. [pimpl->device addSourceTrack: source numSamples: numSamps];
  232674. return true;
  232675. }
  232676. return false;
  232677. }
  232678. const String AudioCDBurner::burn (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener* listener,
  232679. bool ejectDiscAfterwards,
  232680. bool performFakeBurnForTesting,
  232681. int writeSpeed)
  232682. {
  232683. String error ("Couldn't open or write to the CD device");
  232684. if ([pimpl->device->device isValid])
  232685. {
  232686. error = String::empty;
  232687. [pimpl->device burn: listener
  232688. errorString: &error
  232689. ejectAfterwards: ejectDiscAfterwards
  232690. isFake: performFakeBurnForTesting
  232691. speed: writeSpeed];
  232692. }
  232693. return error;
  232694. }
  232695. #endif
  232696. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  232697. void AudioCDReader::ejectDisk()
  232698. {
  232699. const ScopedAutoReleasePool p;
  232700. [[NSWorkspace sharedWorkspace] unmountAndEjectDeviceAtPath: juceStringToNS (volumeDir.getFullPathName())];
  232701. }
  232702. #endif
  232703. /*** End of inlined file: juce_mac_AudioCDBurner.mm ***/
  232704. /*** Start of inlined file: juce_mac_AudioCDReader.mm ***/
  232705. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232706. // compiled on its own).
  232707. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  232708. static void juce_findCDs (Array<File>& cds)
  232709. {
  232710. File volumes ("/Volumes");
  232711. volumes.findChildFiles (cds, File::findDirectories, false);
  232712. for (int i = cds.size(); --i >= 0;)
  232713. if (! cds.getReference(i).getChildFile (".TOC.plist").exists())
  232714. cds.remove (i);
  232715. }
  232716. const StringArray AudioCDReader::getAvailableCDNames()
  232717. {
  232718. Array<File> cds;
  232719. juce_findCDs (cds);
  232720. StringArray names;
  232721. for (int i = 0; i < cds.size(); ++i)
  232722. names.add (cds.getReference(i).getFileName());
  232723. return names;
  232724. }
  232725. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  232726. {
  232727. Array<File> cds;
  232728. juce_findCDs (cds);
  232729. if (cds[index].exists())
  232730. return new AudioCDReader (cds[index]);
  232731. return 0;
  232732. }
  232733. AudioCDReader::AudioCDReader (const File& volume)
  232734. : AudioFormatReader (0, "CD Audio"),
  232735. volumeDir (volume),
  232736. currentReaderTrack (-1),
  232737. reader (0)
  232738. {
  232739. sampleRate = 44100.0;
  232740. bitsPerSample = 16;
  232741. numChannels = 2;
  232742. usesFloatingPointData = false;
  232743. refreshTrackLengths();
  232744. }
  232745. AudioCDReader::~AudioCDReader()
  232746. {
  232747. }
  232748. static int juce_getCDTrackNumber (const File& file)
  232749. {
  232750. return file.getFileName()
  232751. .initialSectionContainingOnly ("0123456789")
  232752. .getIntValue();
  232753. }
  232754. int AudioCDReader::compareElements (const File& first, const File& second)
  232755. {
  232756. const int firstTrack = juce_getCDTrackNumber (first);
  232757. const int secondTrack = juce_getCDTrackNumber (second);
  232758. jassert (firstTrack > 0 && secondTrack > 0);
  232759. return firstTrack - secondTrack;
  232760. }
  232761. void AudioCDReader::refreshTrackLengths()
  232762. {
  232763. tracks.clear();
  232764. trackStartSamples.clear();
  232765. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, "*.aiff");
  232766. tracks.sort (*this);
  232767. AiffAudioFormat format;
  232768. int sample = 0;
  232769. for (int i = 0; i < tracks.size(); ++i)
  232770. {
  232771. trackStartSamples.add (sample);
  232772. FileInputStream* const in = tracks.getReference(i).createInputStream();
  232773. if (in != 0)
  232774. {
  232775. ScopedPointer <AudioFormatReader> r (format.createReaderFor (in, true));
  232776. if (r != 0)
  232777. sample += (int) r->lengthInSamples;
  232778. }
  232779. }
  232780. trackStartSamples.add (sample);
  232781. lengthInSamples = sample;
  232782. }
  232783. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  232784. int64 startSampleInFile, int numSamples)
  232785. {
  232786. while (numSamples > 0)
  232787. {
  232788. int track = -1;
  232789. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  232790. {
  232791. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  232792. {
  232793. track = i;
  232794. break;
  232795. }
  232796. }
  232797. if (track < 0)
  232798. return false;
  232799. if (track != currentReaderTrack)
  232800. {
  232801. reader = 0;
  232802. FileInputStream* const in = tracks [track].createInputStream();
  232803. if (in != 0)
  232804. {
  232805. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  232806. AiffAudioFormat format;
  232807. reader = format.createReaderFor (bin, true);
  232808. if (reader == 0)
  232809. currentReaderTrack = -1;
  232810. else
  232811. currentReaderTrack = track;
  232812. }
  232813. }
  232814. if (reader == 0)
  232815. return false;
  232816. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  232817. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  232818. reader->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer, startPos, numAvailable);
  232819. numSamples -= numAvailable;
  232820. startSampleInFile += numAvailable;
  232821. }
  232822. return true;
  232823. }
  232824. bool AudioCDReader::isCDStillPresent() const
  232825. {
  232826. return volumeDir.exists();
  232827. }
  232828. int AudioCDReader::getNumTracks() const
  232829. {
  232830. return tracks.size();
  232831. }
  232832. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  232833. {
  232834. return trackStartSamples [trackNum];
  232835. }
  232836. bool AudioCDReader::isTrackAudio (int trackNum) const
  232837. {
  232838. return tracks [trackNum] != File::nonexistent;
  232839. }
  232840. void AudioCDReader::enableIndexScanning (bool b)
  232841. {
  232842. // any way to do this on a Mac??
  232843. }
  232844. int AudioCDReader::getLastIndex() const
  232845. {
  232846. return 0;
  232847. }
  232848. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  232849. {
  232850. return Array <int>();
  232851. }
  232852. int AudioCDReader::getCDDBId()
  232853. {
  232854. return 0; //xxx
  232855. }
  232856. #endif
  232857. /*** End of inlined file: juce_mac_AudioCDReader.mm ***/
  232858. /*** Start of inlined file: juce_mac_MessageManager.mm ***/
  232859. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232860. // compiled on its own).
  232861. #if JUCE_INCLUDED_FILE
  232862. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  232863. for example having more than one juce plugin loaded into a host, then when a
  232864. method is called, the actual code that runs might actually be in a different module
  232865. than the one you expect... So any calls to library functions or statics that are
  232866. made inside obj-c methods will probably end up getting executed in a different DLL's
  232867. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  232868. To work around this insanity, I'm only allowing obj-c methods to make calls to
  232869. virtual methods of an object that's known to live inside the right module's space.
  232870. */
  232871. class AppDelegateRedirector
  232872. {
  232873. public:
  232874. AppDelegateRedirector()
  232875. {
  232876. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4
  232877. runLoop = CFRunLoopGetMain();
  232878. #else
  232879. runLoop = CFRunLoopGetCurrent();
  232880. #endif
  232881. CFRunLoopSourceContext sourceContext;
  232882. zerostruct (sourceContext);
  232883. sourceContext.info = this;
  232884. sourceContext.perform = runLoopSourceCallback;
  232885. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  232886. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  232887. }
  232888. virtual ~AppDelegateRedirector()
  232889. {
  232890. CFRunLoopRemoveSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  232891. CFRunLoopSourceInvalidate (runLoopSource);
  232892. CFRelease (runLoopSource);
  232893. while (messages.size() > 0)
  232894. delete static_cast <Message*> (messages.remove(0));
  232895. }
  232896. virtual NSApplicationTerminateReply shouldTerminate()
  232897. {
  232898. if (JUCEApplication::getInstance() != 0)
  232899. {
  232900. JUCEApplication::getInstance()->systemRequestedQuit();
  232901. return NSTerminateCancel;
  232902. }
  232903. return NSTerminateNow;
  232904. }
  232905. virtual BOOL openFile (const NSString* filename)
  232906. {
  232907. if (JUCEApplication::getInstance() != 0)
  232908. {
  232909. JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce (filename));
  232910. return YES;
  232911. }
  232912. return NO;
  232913. }
  232914. virtual void openFiles (NSArray* filenames)
  232915. {
  232916. StringArray files;
  232917. for (unsigned int i = 0; i < [filenames count]; ++i)
  232918. {
  232919. String filename (nsStringToJuce ((NSString*) [filenames objectAtIndex: i]));
  232920. if (filename.containsChar (' '))
  232921. filename = filename.quoted('"');
  232922. files.add (filename);
  232923. }
  232924. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  232925. {
  232926. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (" "));
  232927. }
  232928. }
  232929. virtual void focusChanged()
  232930. {
  232931. juce_HandleProcessFocusChange();
  232932. }
  232933. struct CallbackMessagePayload
  232934. {
  232935. MessageCallbackFunction* function;
  232936. void* parameter;
  232937. void* volatile result;
  232938. bool volatile hasBeenExecuted;
  232939. };
  232940. virtual void performCallback (CallbackMessagePayload* pl)
  232941. {
  232942. pl->result = (*pl->function) (pl->parameter);
  232943. pl->hasBeenExecuted = true;
  232944. }
  232945. virtual void deleteSelf()
  232946. {
  232947. delete this;
  232948. }
  232949. void postMessage (void* m)
  232950. {
  232951. messages.add (m);
  232952. CFRunLoopSourceSignal (runLoopSource);
  232953. CFRunLoopWakeUp (runLoop);
  232954. }
  232955. private:
  232956. CFRunLoopRef runLoop;
  232957. CFRunLoopSourceRef runLoopSource;
  232958. Array <void*, CriticalSection> messages;
  232959. void runLoopCallback()
  232960. {
  232961. int numDispatched = 0;
  232962. do
  232963. {
  232964. void* const nextMessage = messages.remove (0);
  232965. if (nextMessage == 0)
  232966. return;
  232967. const ScopedAutoReleasePool pool;
  232968. MessageManager::getInstance()->deliverMessage (nextMessage);
  232969. } while (++numDispatched <= 4);
  232970. CFRunLoopSourceSignal (runLoopSource);
  232971. CFRunLoopWakeUp (runLoop);
  232972. }
  232973. static void runLoopSourceCallback (void* info)
  232974. {
  232975. static_cast <AppDelegateRedirector*> (info)->runLoopCallback();
  232976. }
  232977. };
  232978. END_JUCE_NAMESPACE
  232979. using namespace JUCE_NAMESPACE;
  232980. #define JuceAppDelegate MakeObjCClassName(JuceAppDelegate)
  232981. @interface JuceAppDelegate : NSObject
  232982. {
  232983. @private
  232984. id oldDelegate;
  232985. @public
  232986. AppDelegateRedirector* redirector;
  232987. }
  232988. - (JuceAppDelegate*) init;
  232989. - (void) dealloc;
  232990. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  232991. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  232992. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  232993. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  232994. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  232995. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  232996. - (void) performCallback: (id) info;
  232997. - (void) dummyMethod;
  232998. @end
  232999. @implementation JuceAppDelegate
  233000. - (JuceAppDelegate*) init
  233001. {
  233002. [super init];
  233003. redirector = new AppDelegateRedirector();
  233004. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  233005. if (JUCEApplication::getInstance() != 0)
  233006. {
  233007. oldDelegate = [NSApp delegate];
  233008. [NSApp setDelegate: self];
  233009. }
  233010. else
  233011. {
  233012. oldDelegate = 0;
  233013. [center addObserver: self selector: @selector (applicationDidResignActive:)
  233014. name: NSApplicationDidResignActiveNotification object: NSApp];
  233015. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  233016. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  233017. [center addObserver: self selector: @selector (applicationWillUnhide:)
  233018. name: NSApplicationWillUnhideNotification object: NSApp];
  233019. }
  233020. return self;
  233021. }
  233022. - (void) dealloc
  233023. {
  233024. if (oldDelegate != 0)
  233025. [NSApp setDelegate: oldDelegate];
  233026. redirector->deleteSelf();
  233027. [super dealloc];
  233028. }
  233029. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  233030. {
  233031. (void) app;
  233032. return redirector->shouldTerminate();
  233033. }
  233034. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  233035. {
  233036. (void) app;
  233037. return redirector->openFile (filename);
  233038. }
  233039. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  233040. {
  233041. (void) sender;
  233042. return redirector->openFiles (filenames);
  233043. }
  233044. - (void) applicationDidBecomeActive: (NSNotification*) notification
  233045. {
  233046. (void) notification;
  233047. redirector->focusChanged();
  233048. }
  233049. - (void) applicationDidResignActive: (NSNotification*) notification
  233050. {
  233051. (void) notification;
  233052. redirector->focusChanged();
  233053. }
  233054. - (void) applicationWillUnhide: (NSNotification*) notification
  233055. {
  233056. (void) notification;
  233057. redirector->focusChanged();
  233058. }
  233059. - (void) performCallback: (id) info
  233060. {
  233061. if ([info isKindOfClass: [NSData class]])
  233062. {
  233063. AppDelegateRedirector::CallbackMessagePayload* pl
  233064. = (AppDelegateRedirector::CallbackMessagePayload*) [((NSData*) info) bytes];
  233065. if (pl != 0)
  233066. redirector->performCallback (pl);
  233067. }
  233068. else
  233069. {
  233070. jassertfalse; // should never get here!
  233071. }
  233072. }
  233073. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  233074. @end
  233075. BEGIN_JUCE_NAMESPACE
  233076. static JuceAppDelegate* juceAppDelegate = 0;
  233077. void MessageManager::runDispatchLoop()
  233078. {
  233079. if (! quitMessagePosted) // check that the quit message wasn't already posted..
  233080. {
  233081. const ScopedAutoReleasePool pool;
  233082. // must only be called by the message thread!
  233083. jassert (isThisTheMessageThread());
  233084. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  233085. @try
  233086. {
  233087. [NSApp run];
  233088. }
  233089. @catch (NSException* e)
  233090. {
  233091. // An AppKit exception will kill the app, but at least this provides a chance to log it.,
  233092. std::runtime_error ex (std::string ("NSException: ") + [[e name] UTF8String] + ", Reason:" + [[e reason] UTF8String]);
  233093. JUCEApplication::sendUnhandledException (&ex, __FILE__, __LINE__);
  233094. }
  233095. @finally
  233096. {
  233097. }
  233098. #else
  233099. [NSApp run];
  233100. #endif
  233101. }
  233102. }
  233103. void MessageManager::stopDispatchLoop()
  233104. {
  233105. quitMessagePosted = true;
  233106. [NSApp stop: nil];
  233107. [NSApp activateIgnoringOtherApps: YES]; // (if the app is inactive, it sits there and ignores the quit request until the next time it gets activated)
  233108. [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
  233109. }
  233110. static bool isEventBlockedByModalComps (NSEvent* e)
  233111. {
  233112. if (Component::getNumCurrentlyModalComponents() == 0)
  233113. return false;
  233114. NSWindow* const w = [e window];
  233115. if (w == 0 || [w worksWhenModal])
  233116. return false;
  233117. bool isKey = false, isInputAttempt = false;
  233118. switch ([e type])
  233119. {
  233120. case NSKeyDown:
  233121. case NSKeyUp:
  233122. isKey = isInputAttempt = true;
  233123. break;
  233124. case NSLeftMouseDown:
  233125. case NSRightMouseDown:
  233126. case NSOtherMouseDown:
  233127. isInputAttempt = true;
  233128. break;
  233129. case NSLeftMouseDragged:
  233130. case NSRightMouseDragged:
  233131. case NSLeftMouseUp:
  233132. case NSRightMouseUp:
  233133. case NSOtherMouseUp:
  233134. case NSOtherMouseDragged:
  233135. if (Desktop::getInstance().getDraggingMouseSource(0) != 0)
  233136. return false;
  233137. break;
  233138. case NSMouseMoved:
  233139. case NSMouseEntered:
  233140. case NSMouseExited:
  233141. case NSCursorUpdate:
  233142. case NSScrollWheel:
  233143. case NSTabletPoint:
  233144. case NSTabletProximity:
  233145. break;
  233146. default:
  233147. return false;
  233148. }
  233149. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  233150. {
  233151. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  233152. NSView* const compView = (NSView*) peer->getNativeHandle();
  233153. if ([compView window] == w)
  233154. {
  233155. if (isKey)
  233156. {
  233157. if (compView == [w firstResponder])
  233158. return false;
  233159. }
  233160. else
  233161. {
  233162. if (NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil],
  233163. [compView bounds]))
  233164. return false;
  233165. }
  233166. }
  233167. }
  233168. if (isInputAttempt)
  233169. {
  233170. if (! [NSApp isActive])
  233171. [NSApp activateIgnoringOtherApps: YES];
  233172. Component* const modal = Component::getCurrentlyModalComponent (0);
  233173. if (modal != 0)
  233174. modal->inputAttemptWhenModal();
  233175. }
  233176. return true;
  233177. }
  233178. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  233179. {
  233180. const ScopedAutoReleasePool pool;
  233181. jassert (isThisTheMessageThread()); // must only be called by the message thread
  233182. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  233183. while (! quitMessagePosted)
  233184. {
  233185. const ScopedAutoReleasePool pool2;
  233186. CFRunLoopRunInMode (kCFRunLoopDefaultMode, 0.001, true);
  233187. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  233188. untilDate: [NSDate dateWithTimeIntervalSinceNow: 0.001]
  233189. inMode: NSDefaultRunLoopMode
  233190. dequeue: YES];
  233191. if (e != 0 && ! isEventBlockedByModalComps (e))
  233192. [NSApp sendEvent: e];
  233193. if (Time::getMillisecondCounter() >= endTime)
  233194. break;
  233195. }
  233196. return ! quitMessagePosted;
  233197. }
  233198. void MessageManager::doPlatformSpecificInitialisation()
  233199. {
  233200. if (juceAppDelegate == 0)
  233201. juceAppDelegate = [[JuceAppDelegate alloc] init];
  233202. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  233203. // correctly (needed prior to 10.5)
  233204. if (! [NSThread isMultiThreaded])
  233205. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  233206. toTarget: juceAppDelegate
  233207. withObject: nil];
  233208. initialiseMainMenu();
  233209. }
  233210. void MessageManager::doPlatformSpecificShutdown()
  233211. {
  233212. if (juceAppDelegate != 0)
  233213. {
  233214. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  233215. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  233216. [juceAppDelegate release];
  233217. juceAppDelegate = 0;
  233218. }
  233219. }
  233220. bool juce_postMessageToSystemQueue (void* message)
  233221. {
  233222. juceAppDelegate->redirector->postMessage (message);
  233223. return true;
  233224. }
  233225. void MessageManager::broadcastMessage (const String& value) throw()
  233226. {
  233227. }
  233228. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  233229. void* data)
  233230. {
  233231. if (isThisTheMessageThread())
  233232. {
  233233. return (*callback) (data);
  233234. }
  233235. else
  233236. {
  233237. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  233238. // deadlock because the message manager is blocked from running, so can never
  233239. // call your function..
  233240. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  233241. const ScopedAutoReleasePool pool;
  233242. AppDelegateRedirector::CallbackMessagePayload cmp;
  233243. cmp.function = callback;
  233244. cmp.parameter = data;
  233245. cmp.result = 0;
  233246. cmp.hasBeenExecuted = false;
  233247. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  233248. withObject: [NSData dataWithBytesNoCopy: &cmp
  233249. length: sizeof (cmp)
  233250. freeWhenDone: NO]
  233251. waitUntilDone: YES];
  233252. return cmp.result;
  233253. }
  233254. }
  233255. #endif
  233256. /*** End of inlined file: juce_mac_MessageManager.mm ***/
  233257. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  233258. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233259. // compiled on its own).
  233260. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  233261. #if JUCE_MAC
  233262. END_JUCE_NAMESPACE
  233263. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  233264. @interface DownloadClickDetector : NSObject
  233265. {
  233266. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  233267. }
  233268. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  233269. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  233270. request: (NSURLRequest*) request
  233271. frame: (WebFrame*) frame
  233272. decisionListener: (id<WebPolicyDecisionListener>) listener;
  233273. @end
  233274. @implementation DownloadClickDetector
  233275. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  233276. {
  233277. [super init];
  233278. ownerComponent = ownerComponent_;
  233279. return self;
  233280. }
  233281. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  233282. request: (NSURLRequest*) request
  233283. frame: (WebFrame*) frame
  233284. decisionListener: (id <WebPolicyDecisionListener>) listener
  233285. {
  233286. (void) sender;
  233287. (void) request;
  233288. (void) frame;
  233289. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  233290. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  233291. [listener use];
  233292. else
  233293. [listener ignore];
  233294. }
  233295. @end
  233296. BEGIN_JUCE_NAMESPACE
  233297. class WebBrowserComponentInternal : public NSViewComponent
  233298. {
  233299. public:
  233300. WebBrowserComponentInternal (WebBrowserComponent* owner)
  233301. {
  233302. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  233303. frameName: @""
  233304. groupName: @""];
  233305. setView (webView);
  233306. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  233307. [webView setPolicyDelegate: clickListener];
  233308. }
  233309. ~WebBrowserComponentInternal()
  233310. {
  233311. [webView setPolicyDelegate: nil];
  233312. [clickListener release];
  233313. setView (0);
  233314. }
  233315. void goToURL (const String& url,
  233316. const StringArray* headers,
  233317. const MemoryBlock* postData)
  233318. {
  233319. NSMutableURLRequest* r
  233320. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  233321. cachePolicy: NSURLRequestUseProtocolCachePolicy
  233322. timeoutInterval: 30.0];
  233323. if (postData != 0 && postData->getSize() > 0)
  233324. {
  233325. [r setHTTPMethod: @"POST"];
  233326. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  233327. length: postData->getSize()]];
  233328. }
  233329. if (headers != 0)
  233330. {
  233331. for (int i = 0; i < headers->size(); ++i)
  233332. {
  233333. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  233334. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  233335. [r setValue: juceStringToNS (headerValue)
  233336. forHTTPHeaderField: juceStringToNS (headerName)];
  233337. }
  233338. }
  233339. stop();
  233340. [[webView mainFrame] loadRequest: r];
  233341. }
  233342. void goBack()
  233343. {
  233344. [webView goBack];
  233345. }
  233346. void goForward()
  233347. {
  233348. [webView goForward];
  233349. }
  233350. void stop()
  233351. {
  233352. [webView stopLoading: nil];
  233353. }
  233354. void refresh()
  233355. {
  233356. [webView reload: nil];
  233357. }
  233358. private:
  233359. WebView* webView;
  233360. DownloadClickDetector* clickListener;
  233361. };
  233362. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  233363. : browser (0),
  233364. blankPageShown (false),
  233365. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  233366. {
  233367. setOpaque (true);
  233368. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  233369. }
  233370. WebBrowserComponent::~WebBrowserComponent()
  233371. {
  233372. deleteAndZero (browser);
  233373. }
  233374. void WebBrowserComponent::goToURL (const String& url,
  233375. const StringArray* headers,
  233376. const MemoryBlock* postData)
  233377. {
  233378. lastURL = url;
  233379. lastHeaders.clear();
  233380. if (headers != 0)
  233381. lastHeaders = *headers;
  233382. lastPostData.setSize (0);
  233383. if (postData != 0)
  233384. lastPostData = *postData;
  233385. blankPageShown = false;
  233386. browser->goToURL (url, headers, postData);
  233387. }
  233388. void WebBrowserComponent::stop()
  233389. {
  233390. browser->stop();
  233391. }
  233392. void WebBrowserComponent::goBack()
  233393. {
  233394. lastURL = String::empty;
  233395. blankPageShown = false;
  233396. browser->goBack();
  233397. }
  233398. void WebBrowserComponent::goForward()
  233399. {
  233400. lastURL = String::empty;
  233401. browser->goForward();
  233402. }
  233403. void WebBrowserComponent::refresh()
  233404. {
  233405. browser->refresh();
  233406. }
  233407. void WebBrowserComponent::paint (Graphics&)
  233408. {
  233409. }
  233410. void WebBrowserComponent::checkWindowAssociation()
  233411. {
  233412. if (isShowing())
  233413. {
  233414. if (blankPageShown)
  233415. goBack();
  233416. }
  233417. else
  233418. {
  233419. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  233420. {
  233421. // when the component becomes invisible, some stuff like flash
  233422. // carries on playing audio, so we need to force it onto a blank
  233423. // page to avoid this, (and send it back when it's made visible again).
  233424. blankPageShown = true;
  233425. browser->goToURL ("about:blank", 0, 0);
  233426. }
  233427. }
  233428. }
  233429. void WebBrowserComponent::reloadLastURL()
  233430. {
  233431. if (lastURL.isNotEmpty())
  233432. {
  233433. goToURL (lastURL, &lastHeaders, &lastPostData);
  233434. lastURL = String::empty;
  233435. }
  233436. }
  233437. void WebBrowserComponent::parentHierarchyChanged()
  233438. {
  233439. checkWindowAssociation();
  233440. }
  233441. void WebBrowserComponent::resized()
  233442. {
  233443. browser->setSize (getWidth(), getHeight());
  233444. }
  233445. void WebBrowserComponent::visibilityChanged()
  233446. {
  233447. checkWindowAssociation();
  233448. }
  233449. bool WebBrowserComponent::pageAboutToLoad (const String&)
  233450. {
  233451. return true;
  233452. }
  233453. #else
  233454. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  233455. {
  233456. }
  233457. WebBrowserComponent::~WebBrowserComponent()
  233458. {
  233459. }
  233460. void WebBrowserComponent::goToURL (const String& url,
  233461. const StringArray* headers,
  233462. const MemoryBlock* postData)
  233463. {
  233464. }
  233465. void WebBrowserComponent::stop()
  233466. {
  233467. }
  233468. void WebBrowserComponent::goBack()
  233469. {
  233470. }
  233471. void WebBrowserComponent::goForward()
  233472. {
  233473. }
  233474. void WebBrowserComponent::refresh()
  233475. {
  233476. }
  233477. void WebBrowserComponent::paint (Graphics& g)
  233478. {
  233479. }
  233480. void WebBrowserComponent::checkWindowAssociation()
  233481. {
  233482. }
  233483. void WebBrowserComponent::reloadLastURL()
  233484. {
  233485. }
  233486. void WebBrowserComponent::parentHierarchyChanged()
  233487. {
  233488. }
  233489. void WebBrowserComponent::resized()
  233490. {
  233491. }
  233492. void WebBrowserComponent::visibilityChanged()
  233493. {
  233494. }
  233495. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  233496. {
  233497. return true;
  233498. }
  233499. #endif
  233500. #endif
  233501. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  233502. /*** Start of inlined file: juce_mac_CoreAudio.cpp ***/
  233503. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233504. // compiled on its own).
  233505. #if JUCE_INCLUDED_FILE
  233506. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  233507. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  233508. #endif
  233509. #undef log
  233510. #if JUCE_COREAUDIO_LOGGING_ENABLED
  233511. #define log(a) Logger::writeToLog (a)
  233512. #else
  233513. #define log(a)
  233514. #endif
  233515. #undef OK
  233516. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  233517. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  233518. {
  233519. if (err == noErr)
  233520. return true;
  233521. Logger::writeToLog ("CoreAudio error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  233522. jassertfalse;
  233523. return false;
  233524. }
  233525. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  233526. #else
  233527. #define OK(a) (a == noErr)
  233528. #endif
  233529. class CoreAudioInternal : public Timer
  233530. {
  233531. public:
  233532. CoreAudioInternal (AudioDeviceID id)
  233533. : inputLatency (0),
  233534. outputLatency (0),
  233535. callback (0),
  233536. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  233537. audioProcID (0),
  233538. #endif
  233539. isSlaveDevice (false),
  233540. deviceID (id),
  233541. started (false),
  233542. sampleRate (0),
  233543. bufferSize (512),
  233544. numInputChans (0),
  233545. numOutputChans (0),
  233546. callbacksAllowed (true),
  233547. numInputChannelInfos (0),
  233548. numOutputChannelInfos (0)
  233549. {
  233550. jassert (deviceID != 0);
  233551. updateDetailsFromDevice();
  233552. AudioObjectPropertyAddress pa;
  233553. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  233554. pa.mScope = kAudioObjectPropertyScopeWildcard;
  233555. pa.mElement = kAudioObjectPropertyElementWildcard;
  233556. AudioObjectAddPropertyListener (deviceID, &pa, deviceListenerProc, this);
  233557. }
  233558. ~CoreAudioInternal()
  233559. {
  233560. AudioObjectPropertyAddress pa;
  233561. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  233562. pa.mScope = kAudioObjectPropertyScopeWildcard;
  233563. pa.mElement = kAudioObjectPropertyElementWildcard;
  233564. AudioObjectRemovePropertyListener (deviceID, &pa, deviceListenerProc, this);
  233565. stop (false);
  233566. }
  233567. void allocateTempBuffers()
  233568. {
  233569. const int tempBufSize = bufferSize + 4;
  233570. audioBuffer.calloc ((numInputChans + numOutputChans) * tempBufSize);
  233571. tempInputBuffers.calloc (numInputChans + 2);
  233572. tempOutputBuffers.calloc (numOutputChans + 2);
  233573. int i, count = 0;
  233574. for (i = 0; i < numInputChans; ++i)
  233575. tempInputBuffers[i] = audioBuffer + count++ * tempBufSize;
  233576. for (i = 0; i < numOutputChans; ++i)
  233577. tempOutputBuffers[i] = audioBuffer + count++ * tempBufSize;
  233578. }
  233579. // returns the number of actual available channels
  233580. void fillInChannelInfo (const bool input)
  233581. {
  233582. int chanNum = 0;
  233583. UInt32 size;
  233584. AudioObjectPropertyAddress pa;
  233585. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  233586. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  233587. pa.mElement = kAudioObjectPropertyElementMaster;
  233588. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  233589. {
  233590. HeapBlock <AudioBufferList> bufList;
  233591. bufList.calloc (size, 1);
  233592. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  233593. {
  233594. const int numStreams = bufList->mNumberBuffers;
  233595. for (int i = 0; i < numStreams; ++i)
  233596. {
  233597. const AudioBuffer& b = bufList->mBuffers[i];
  233598. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  233599. {
  233600. String name;
  233601. {
  233602. char channelName [256];
  233603. zerostruct (channelName);
  233604. UInt32 nameSize = sizeof (channelName);
  233605. UInt32 channelNum = chanNum + 1;
  233606. pa.mSelector = kAudioDevicePropertyChannelName;
  233607. if (AudioObjectGetPropertyData (deviceID, &pa, sizeof (channelNum), &channelNum, &nameSize, channelName) == noErr)
  233608. name = String::fromUTF8 (channelName, nameSize);
  233609. }
  233610. if (input)
  233611. {
  233612. if (activeInputChans[chanNum])
  233613. {
  233614. inputChannelInfo [numInputChannelInfos].streamNum = i;
  233615. inputChannelInfo [numInputChannelInfos].dataOffsetSamples = j;
  233616. inputChannelInfo [numInputChannelInfos].dataStrideSamples = b.mNumberChannels;
  233617. ++numInputChannelInfos;
  233618. }
  233619. if (name.isEmpty())
  233620. name << "Input " << (chanNum + 1);
  233621. inChanNames.add (name);
  233622. }
  233623. else
  233624. {
  233625. if (activeOutputChans[chanNum])
  233626. {
  233627. outputChannelInfo [numOutputChannelInfos].streamNum = i;
  233628. outputChannelInfo [numOutputChannelInfos].dataOffsetSamples = j;
  233629. outputChannelInfo [numOutputChannelInfos].dataStrideSamples = b.mNumberChannels;
  233630. ++numOutputChannelInfos;
  233631. }
  233632. if (name.isEmpty())
  233633. name << "Output " << (chanNum + 1);
  233634. outChanNames.add (name);
  233635. }
  233636. ++chanNum;
  233637. }
  233638. }
  233639. }
  233640. }
  233641. }
  233642. void updateDetailsFromDevice()
  233643. {
  233644. stopTimer();
  233645. if (deviceID == 0)
  233646. return;
  233647. const ScopedLock sl (callbackLock);
  233648. Float64 sr;
  233649. UInt32 size = sizeof (Float64);
  233650. AudioObjectPropertyAddress pa;
  233651. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  233652. pa.mScope = kAudioObjectPropertyScopeWildcard;
  233653. pa.mElement = kAudioObjectPropertyElementMaster;
  233654. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &sr)))
  233655. sampleRate = sr;
  233656. UInt32 framesPerBuf;
  233657. size = sizeof (framesPerBuf);
  233658. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  233659. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &framesPerBuf)))
  233660. {
  233661. bufferSize = framesPerBuf;
  233662. allocateTempBuffers();
  233663. }
  233664. bufferSizes.clear();
  233665. pa.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  233666. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  233667. {
  233668. HeapBlock <AudioValueRange> ranges;
  233669. ranges.calloc (size, 1);
  233670. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  233671. {
  233672. bufferSizes.add ((int) ranges[0].mMinimum);
  233673. for (int i = 32; i < 2048; i += 32)
  233674. {
  233675. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  233676. {
  233677. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  233678. {
  233679. bufferSizes.addIfNotAlreadyThere (i);
  233680. break;
  233681. }
  233682. }
  233683. }
  233684. if (bufferSize > 0)
  233685. bufferSizes.addIfNotAlreadyThere (bufferSize);
  233686. }
  233687. }
  233688. if (bufferSizes.size() == 0 && bufferSize > 0)
  233689. bufferSizes.add (bufferSize);
  233690. sampleRates.clear();
  233691. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  233692. String rates;
  233693. pa.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  233694. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  233695. {
  233696. HeapBlock <AudioValueRange> ranges;
  233697. ranges.calloc (size, 1);
  233698. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  233699. {
  233700. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  233701. {
  233702. bool ok = false;
  233703. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  233704. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  233705. ok = true;
  233706. if (ok)
  233707. {
  233708. sampleRates.add (possibleRates[i]);
  233709. rates << possibleRates[i] << ' ';
  233710. }
  233711. }
  233712. }
  233713. }
  233714. if (sampleRates.size() == 0 && sampleRate > 0)
  233715. {
  233716. sampleRates.add (sampleRate);
  233717. rates << sampleRate;
  233718. }
  233719. log ("sr: " + rates);
  233720. inputLatency = 0;
  233721. outputLatency = 0;
  233722. UInt32 lat;
  233723. size = sizeof (lat);
  233724. pa.mSelector = kAudioDevicePropertyLatency;
  233725. pa.mScope = kAudioDevicePropertyScopeInput;
  233726. //if (AudioDeviceGetProperty (deviceID, 0, true, kAudioDevicePropertyLatency, &size, &lat) == noErr)
  233727. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  233728. inputLatency = (int) lat;
  233729. pa.mScope = kAudioDevicePropertyScopeOutput;
  233730. size = sizeof (lat);
  233731. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  233732. outputLatency = (int) lat;
  233733. log ("lat: " + String (inputLatency) + " " + String (outputLatency));
  233734. inChanNames.clear();
  233735. outChanNames.clear();
  233736. inputChannelInfo.calloc (numInputChans + 2);
  233737. numInputChannelInfos = 0;
  233738. outputChannelInfo.calloc (numOutputChans + 2);
  233739. numOutputChannelInfos = 0;
  233740. fillInChannelInfo (true);
  233741. fillInChannelInfo (false);
  233742. }
  233743. const StringArray getSources (bool input)
  233744. {
  233745. StringArray s;
  233746. HeapBlock <OSType> types;
  233747. const int num = getAllDataSourcesForDevice (deviceID, types);
  233748. for (int i = 0; i < num; ++i)
  233749. {
  233750. AudioValueTranslation avt;
  233751. char buffer[256];
  233752. avt.mInputData = &(types[i]);
  233753. avt.mInputDataSize = sizeof (UInt32);
  233754. avt.mOutputData = buffer;
  233755. avt.mOutputDataSize = 256;
  233756. UInt32 transSize = sizeof (avt);
  233757. AudioObjectPropertyAddress pa;
  233758. pa.mSelector = kAudioDevicePropertyDataSourceNameForID;
  233759. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  233760. pa.mElement = kAudioObjectPropertyElementMaster;
  233761. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &transSize, &avt)))
  233762. {
  233763. DBG (buffer);
  233764. s.add (buffer);
  233765. }
  233766. }
  233767. return s;
  233768. }
  233769. int getCurrentSourceIndex (bool input) const
  233770. {
  233771. OSType currentSourceID = 0;
  233772. UInt32 size = sizeof (currentSourceID);
  233773. int result = -1;
  233774. AudioObjectPropertyAddress pa;
  233775. pa.mSelector = kAudioDevicePropertyDataSource;
  233776. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  233777. pa.mElement = kAudioObjectPropertyElementMaster;
  233778. if (deviceID != 0)
  233779. {
  233780. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &currentSourceID)))
  233781. {
  233782. HeapBlock <OSType> types;
  233783. const int num = getAllDataSourcesForDevice (deviceID, types);
  233784. for (int i = 0; i < num; ++i)
  233785. {
  233786. if (types[num] == currentSourceID)
  233787. {
  233788. result = i;
  233789. break;
  233790. }
  233791. }
  233792. }
  233793. }
  233794. return result;
  233795. }
  233796. void setCurrentSourceIndex (int index, bool input)
  233797. {
  233798. if (deviceID != 0)
  233799. {
  233800. HeapBlock <OSType> types;
  233801. const int num = getAllDataSourcesForDevice (deviceID, types);
  233802. if (((unsigned int) index) < (unsigned int) num)
  233803. {
  233804. AudioObjectPropertyAddress pa;
  233805. pa.mSelector = kAudioDevicePropertyDataSource;
  233806. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  233807. pa.mElement = kAudioObjectPropertyElementMaster;
  233808. OSType typeId = types[index];
  233809. OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (typeId), &typeId));
  233810. }
  233811. }
  233812. }
  233813. const String reopen (const BigInteger& inputChannels,
  233814. const BigInteger& outputChannels,
  233815. double newSampleRate,
  233816. int bufferSizeSamples)
  233817. {
  233818. String error;
  233819. log ("CoreAudio reopen");
  233820. callbacksAllowed = false;
  233821. stopTimer();
  233822. stop (false);
  233823. activeInputChans = inputChannels;
  233824. activeInputChans.setRange (inChanNames.size(),
  233825. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  233826. false);
  233827. activeOutputChans = outputChannels;
  233828. activeOutputChans.setRange (outChanNames.size(),
  233829. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  233830. false);
  233831. numInputChans = activeInputChans.countNumberOfSetBits();
  233832. numOutputChans = activeOutputChans.countNumberOfSetBits();
  233833. // set sample rate
  233834. AudioObjectPropertyAddress pa;
  233835. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  233836. pa.mScope = kAudioObjectPropertyScopeWildcard;
  233837. pa.mElement = kAudioObjectPropertyElementMaster;
  233838. Float64 sr = newSampleRate;
  233839. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (sr), &sr)))
  233840. {
  233841. error = "Couldn't change sample rate";
  233842. }
  233843. else
  233844. {
  233845. // change buffer size
  233846. UInt32 framesPerBuf = bufferSizeSamples;
  233847. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  233848. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (framesPerBuf), &framesPerBuf)))
  233849. {
  233850. error = "Couldn't change buffer size";
  233851. }
  233852. else
  233853. {
  233854. // Annoyingly, after changing the rate and buffer size, some devices fail to
  233855. // correctly report their new settings until some random time in the future, so
  233856. // after calling updateDetailsFromDevice, we need to manually bodge these values
  233857. // to make sure we're using the correct numbers..
  233858. updateDetailsFromDevice();
  233859. sampleRate = newSampleRate;
  233860. bufferSize = bufferSizeSamples;
  233861. if (sampleRates.size() == 0)
  233862. error = "Device has no available sample-rates";
  233863. else if (bufferSizes.size() == 0)
  233864. error = "Device has no available buffer-sizes";
  233865. else if (inputDevice != 0)
  233866. error = inputDevice->reopen (inputChannels,
  233867. outputChannels,
  233868. newSampleRate,
  233869. bufferSizeSamples);
  233870. }
  233871. }
  233872. callbacksAllowed = true;
  233873. return error;
  233874. }
  233875. bool start (AudioIODeviceCallback* cb)
  233876. {
  233877. if (! started)
  233878. {
  233879. callback = 0;
  233880. if (deviceID != 0)
  233881. {
  233882. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  233883. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, this)))
  233884. #else
  233885. if (OK (AudioDeviceCreateIOProcID (deviceID, audioIOProc, this, &audioProcID)))
  233886. #endif
  233887. {
  233888. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  233889. {
  233890. started = true;
  233891. }
  233892. else
  233893. {
  233894. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  233895. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  233896. #else
  233897. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  233898. audioProcID = 0;
  233899. #endif
  233900. }
  233901. }
  233902. }
  233903. }
  233904. if (started)
  233905. {
  233906. const ScopedLock sl (callbackLock);
  233907. callback = cb;
  233908. }
  233909. if (inputDevice != 0)
  233910. return started && inputDevice->start (cb);
  233911. else
  233912. return started;
  233913. }
  233914. void stop (bool leaveInterruptRunning)
  233915. {
  233916. {
  233917. const ScopedLock sl (callbackLock);
  233918. callback = 0;
  233919. }
  233920. if (started
  233921. && (deviceID != 0)
  233922. && ! leaveInterruptRunning)
  233923. {
  233924. OK (AudioDeviceStop (deviceID, audioIOProc));
  233925. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  233926. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  233927. #else
  233928. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  233929. audioProcID = 0;
  233930. #endif
  233931. started = false;
  233932. { const ScopedLock sl (callbackLock); }
  233933. // wait until it's definately stopped calling back..
  233934. for (int i = 40; --i >= 0;)
  233935. {
  233936. Thread::sleep (50);
  233937. UInt32 running = 0;
  233938. UInt32 size = sizeof (running);
  233939. AudioObjectPropertyAddress pa;
  233940. pa.mSelector = kAudioDevicePropertyDeviceIsRunning;
  233941. pa.mScope = kAudioObjectPropertyScopeWildcard;
  233942. pa.mElement = kAudioObjectPropertyElementMaster;
  233943. OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &running));
  233944. if (running == 0)
  233945. break;
  233946. }
  233947. const ScopedLock sl (callbackLock);
  233948. }
  233949. if (inputDevice != 0)
  233950. inputDevice->stop (leaveInterruptRunning);
  233951. }
  233952. double getSampleRate() const
  233953. {
  233954. return sampleRate;
  233955. }
  233956. int getBufferSize() const
  233957. {
  233958. return bufferSize;
  233959. }
  233960. void audioCallback (const AudioBufferList* inInputData,
  233961. AudioBufferList* outOutputData)
  233962. {
  233963. int i;
  233964. const ScopedLock sl (callbackLock);
  233965. if (callback != 0)
  233966. {
  233967. if (inputDevice == 0)
  233968. {
  233969. for (i = numInputChans; --i >= 0;)
  233970. {
  233971. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  233972. float* dest = tempInputBuffers [i];
  233973. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  233974. + info.dataOffsetSamples;
  233975. const int stride = info.dataStrideSamples;
  233976. if (stride != 0) // if this is zero, info is invalid
  233977. {
  233978. for (int j = bufferSize; --j >= 0;)
  233979. {
  233980. *dest++ = *src;
  233981. src += stride;
  233982. }
  233983. }
  233984. }
  233985. }
  233986. if (! isSlaveDevice)
  233987. {
  233988. if (inputDevice == 0)
  233989. {
  233990. callback->audioDeviceIOCallback (const_cast<const float**> (tempInputBuffers.getData()),
  233991. numInputChans,
  233992. tempOutputBuffers,
  233993. numOutputChans,
  233994. bufferSize);
  233995. }
  233996. else
  233997. {
  233998. jassert (inputDevice->bufferSize == bufferSize);
  233999. // Sometimes the two linked devices seem to get their callbacks in
  234000. // parallel, so we need to lock both devices to stop the input data being
  234001. // changed while inside our callback..
  234002. const ScopedLock sl2 (inputDevice->callbackLock);
  234003. callback->audioDeviceIOCallback (const_cast<const float**> (inputDevice->tempInputBuffers.getData()),
  234004. inputDevice->numInputChans,
  234005. tempOutputBuffers,
  234006. numOutputChans,
  234007. bufferSize);
  234008. }
  234009. for (i = numOutputChans; --i >= 0;)
  234010. {
  234011. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  234012. const float* src = tempOutputBuffers [i];
  234013. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  234014. + info.dataOffsetSamples;
  234015. const int stride = info.dataStrideSamples;
  234016. if (stride != 0) // if this is zero, info is invalid
  234017. {
  234018. for (int j = bufferSize; --j >= 0;)
  234019. {
  234020. *dest = *src++;
  234021. dest += stride;
  234022. }
  234023. }
  234024. }
  234025. }
  234026. }
  234027. else
  234028. {
  234029. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  234030. {
  234031. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  234032. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  234033. + info.dataOffsetSamples;
  234034. const int stride = info.dataStrideSamples;
  234035. if (stride != 0) // if this is zero, info is invalid
  234036. {
  234037. for (int j = bufferSize; --j >= 0;)
  234038. {
  234039. *dest = 0.0f;
  234040. dest += stride;
  234041. }
  234042. }
  234043. }
  234044. }
  234045. }
  234046. // called by callbacks
  234047. void deviceDetailsChanged()
  234048. {
  234049. if (callbacksAllowed)
  234050. startTimer (100);
  234051. }
  234052. void timerCallback()
  234053. {
  234054. stopTimer();
  234055. log ("CoreAudio device changed callback");
  234056. const double oldSampleRate = sampleRate;
  234057. const int oldBufferSize = bufferSize;
  234058. updateDetailsFromDevice();
  234059. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  234060. {
  234061. callbacksAllowed = false;
  234062. stop (false);
  234063. updateDetailsFromDevice();
  234064. callbacksAllowed = true;
  234065. }
  234066. }
  234067. CoreAudioInternal* getRelatedDevice() const
  234068. {
  234069. UInt32 size = 0;
  234070. ScopedPointer <CoreAudioInternal> result;
  234071. AudioObjectPropertyAddress pa;
  234072. pa.mSelector = kAudioDevicePropertyRelatedDevices;
  234073. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234074. pa.mElement = kAudioObjectPropertyElementMaster;
  234075. if (deviceID != 0
  234076. && AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size) == noErr
  234077. && size > 0)
  234078. {
  234079. HeapBlock <AudioDeviceID> devs;
  234080. devs.calloc (size, 1);
  234081. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, devs)))
  234082. {
  234083. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  234084. {
  234085. if (devs[i] != deviceID && devs[i] != 0)
  234086. {
  234087. result = new CoreAudioInternal (devs[i]);
  234088. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  234089. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  234090. if (thisIsInput != otherIsInput
  234091. || (inChanNames.size() + outChanNames.size() == 0)
  234092. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  234093. break;
  234094. result = 0;
  234095. }
  234096. }
  234097. }
  234098. }
  234099. return result.release();
  234100. }
  234101. juce_UseDebuggingNewOperator
  234102. int inputLatency, outputLatency;
  234103. BigInteger activeInputChans, activeOutputChans;
  234104. StringArray inChanNames, outChanNames;
  234105. Array <double> sampleRates;
  234106. Array <int> bufferSizes;
  234107. AudioIODeviceCallback* callback;
  234108. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  234109. AudioDeviceIOProcID audioProcID;
  234110. #endif
  234111. ScopedPointer<CoreAudioInternal> inputDevice;
  234112. bool isSlaveDevice;
  234113. private:
  234114. CriticalSection callbackLock;
  234115. AudioDeviceID deviceID;
  234116. bool started;
  234117. double sampleRate;
  234118. int bufferSize;
  234119. HeapBlock <float> audioBuffer;
  234120. int numInputChans, numOutputChans;
  234121. bool callbacksAllowed;
  234122. struct CallbackDetailsForChannel
  234123. {
  234124. int streamNum;
  234125. int dataOffsetSamples;
  234126. int dataStrideSamples;
  234127. };
  234128. int numInputChannelInfos, numOutputChannelInfos;
  234129. HeapBlock <CallbackDetailsForChannel> inputChannelInfo, outputChannelInfo;
  234130. HeapBlock <float*> tempInputBuffers, tempOutputBuffers;
  234131. CoreAudioInternal (const CoreAudioInternal&);
  234132. CoreAudioInternal& operator= (const CoreAudioInternal&);
  234133. static OSStatus audioIOProc (AudioDeviceID /*inDevice*/,
  234134. const AudioTimeStamp* /*inNow*/,
  234135. const AudioBufferList* inInputData,
  234136. const AudioTimeStamp* /*inInputTime*/,
  234137. AudioBufferList* outOutputData,
  234138. const AudioTimeStamp* /*inOutputTime*/,
  234139. void* device)
  234140. {
  234141. static_cast <CoreAudioInternal*> (device)->audioCallback (inInputData, outOutputData);
  234142. return noErr;
  234143. }
  234144. static OSStatus deviceListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  234145. {
  234146. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  234147. switch (pa->mSelector)
  234148. {
  234149. case kAudioDevicePropertyBufferSize:
  234150. case kAudioDevicePropertyBufferFrameSize:
  234151. case kAudioDevicePropertyNominalSampleRate:
  234152. case kAudioDevicePropertyStreamFormat:
  234153. case kAudioDevicePropertyDeviceIsAlive:
  234154. intern->deviceDetailsChanged();
  234155. break;
  234156. case kAudioDevicePropertyBufferSizeRange:
  234157. case kAudioDevicePropertyVolumeScalar:
  234158. case kAudioDevicePropertyMute:
  234159. case kAudioDevicePropertyPlayThru:
  234160. case kAudioDevicePropertyDataSource:
  234161. case kAudioDevicePropertyDeviceIsRunning:
  234162. break;
  234163. }
  234164. return noErr;
  234165. }
  234166. static int getAllDataSourcesForDevice (AudioDeviceID deviceID, HeapBlock <OSType>& types)
  234167. {
  234168. AudioObjectPropertyAddress pa;
  234169. pa.mSelector = kAudioDevicePropertyDataSources;
  234170. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234171. pa.mElement = kAudioObjectPropertyElementMaster;
  234172. UInt32 size = 0;
  234173. if (deviceID != 0
  234174. && OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  234175. {
  234176. types.calloc (size, 1);
  234177. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, types)))
  234178. return size / (int) sizeof (OSType);
  234179. }
  234180. return 0;
  234181. }
  234182. };
  234183. class CoreAudioIODevice : public AudioIODevice
  234184. {
  234185. public:
  234186. CoreAudioIODevice (const String& deviceName,
  234187. AudioDeviceID inputDeviceId,
  234188. const int inputIndex_,
  234189. AudioDeviceID outputDeviceId,
  234190. const int outputIndex_)
  234191. : AudioIODevice (deviceName, "CoreAudio"),
  234192. inputIndex (inputIndex_),
  234193. outputIndex (outputIndex_),
  234194. isOpen_ (false),
  234195. isStarted (false)
  234196. {
  234197. CoreAudioInternal* device = 0;
  234198. if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
  234199. {
  234200. jassert (inputDeviceId != 0);
  234201. device = new CoreAudioInternal (inputDeviceId);
  234202. }
  234203. else
  234204. {
  234205. device = new CoreAudioInternal (outputDeviceId);
  234206. if (inputDeviceId != 0)
  234207. {
  234208. CoreAudioInternal* secondDevice = new CoreAudioInternal (inputDeviceId);
  234209. device->inputDevice = secondDevice;
  234210. secondDevice->isSlaveDevice = true;
  234211. }
  234212. }
  234213. internal = device;
  234214. AudioObjectPropertyAddress pa;
  234215. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  234216. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234217. pa.mElement = kAudioObjectPropertyElementWildcard;
  234218. AudioObjectAddPropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  234219. }
  234220. ~CoreAudioIODevice()
  234221. {
  234222. AudioObjectPropertyAddress pa;
  234223. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  234224. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234225. pa.mElement = kAudioObjectPropertyElementWildcard;
  234226. AudioObjectRemovePropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  234227. }
  234228. const StringArray getOutputChannelNames()
  234229. {
  234230. return internal->outChanNames;
  234231. }
  234232. const StringArray getInputChannelNames()
  234233. {
  234234. if (internal->inputDevice != 0)
  234235. return internal->inputDevice->inChanNames;
  234236. else
  234237. return internal->inChanNames;
  234238. }
  234239. int getNumSampleRates()
  234240. {
  234241. return internal->sampleRates.size();
  234242. }
  234243. double getSampleRate (int index)
  234244. {
  234245. return internal->sampleRates [index];
  234246. }
  234247. int getNumBufferSizesAvailable()
  234248. {
  234249. return internal->bufferSizes.size();
  234250. }
  234251. int getBufferSizeSamples (int index)
  234252. {
  234253. return internal->bufferSizes [index];
  234254. }
  234255. int getDefaultBufferSize()
  234256. {
  234257. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  234258. if (getBufferSizeSamples(i) >= 512)
  234259. return getBufferSizeSamples(i);
  234260. return 512;
  234261. }
  234262. const String open (const BigInteger& inputChannels,
  234263. const BigInteger& outputChannels,
  234264. double sampleRate,
  234265. int bufferSizeSamples)
  234266. {
  234267. isOpen_ = true;
  234268. if (bufferSizeSamples <= 0)
  234269. bufferSizeSamples = getDefaultBufferSize();
  234270. lastError = internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  234271. isOpen_ = lastError.isEmpty();
  234272. return lastError;
  234273. }
  234274. void close()
  234275. {
  234276. isOpen_ = false;
  234277. internal->stop (false);
  234278. }
  234279. bool isOpen()
  234280. {
  234281. return isOpen_;
  234282. }
  234283. int getCurrentBufferSizeSamples()
  234284. {
  234285. return internal != 0 ? internal->getBufferSize() : 512;
  234286. }
  234287. double getCurrentSampleRate()
  234288. {
  234289. return internal != 0 ? internal->getSampleRate() : 0;
  234290. }
  234291. int getCurrentBitDepth()
  234292. {
  234293. return 32; // no way to find out, so just assume it's high..
  234294. }
  234295. const BigInteger getActiveOutputChannels() const
  234296. {
  234297. return internal != 0 ? internal->activeOutputChans : BigInteger();
  234298. }
  234299. const BigInteger getActiveInputChannels() const
  234300. {
  234301. BigInteger chans;
  234302. if (internal != 0)
  234303. {
  234304. chans = internal->activeInputChans;
  234305. if (internal->inputDevice != 0)
  234306. chans |= internal->inputDevice->activeInputChans;
  234307. }
  234308. return chans;
  234309. }
  234310. int getOutputLatencyInSamples()
  234311. {
  234312. if (internal == 0)
  234313. return 0;
  234314. // this seems like a good guess at getting the latency right - comparing
  234315. // this with a round-trip measurement, it gets it to within a few millisecs
  234316. // for the built-in mac soundcard
  234317. return internal->outputLatency + internal->getBufferSize() * 2;
  234318. }
  234319. int getInputLatencyInSamples()
  234320. {
  234321. if (internal == 0)
  234322. return 0;
  234323. return internal->inputLatency + internal->getBufferSize() * 2;
  234324. }
  234325. void start (AudioIODeviceCallback* callback)
  234326. {
  234327. if (internal != 0 && ! isStarted)
  234328. {
  234329. if (callback != 0)
  234330. callback->audioDeviceAboutToStart (this);
  234331. isStarted = true;
  234332. internal->start (callback);
  234333. }
  234334. }
  234335. void stop()
  234336. {
  234337. if (isStarted && internal != 0)
  234338. {
  234339. AudioIODeviceCallback* const lastCallback = internal->callback;
  234340. isStarted = false;
  234341. internal->stop (true);
  234342. if (lastCallback != 0)
  234343. lastCallback->audioDeviceStopped();
  234344. }
  234345. }
  234346. bool isPlaying()
  234347. {
  234348. if (internal->callback == 0)
  234349. isStarted = false;
  234350. return isStarted;
  234351. }
  234352. const String getLastError()
  234353. {
  234354. return lastError;
  234355. }
  234356. int inputIndex, outputIndex;
  234357. juce_UseDebuggingNewOperator
  234358. private:
  234359. ScopedPointer<CoreAudioInternal> internal;
  234360. bool isOpen_, isStarted;
  234361. String lastError;
  234362. static OSStatus hardwareListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  234363. {
  234364. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  234365. switch (pa->mSelector)
  234366. {
  234367. case kAudioHardwarePropertyDevices:
  234368. intern->deviceDetailsChanged();
  234369. break;
  234370. case kAudioHardwarePropertyDefaultOutputDevice:
  234371. case kAudioHardwarePropertyDefaultInputDevice:
  234372. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  234373. break;
  234374. }
  234375. return noErr;
  234376. }
  234377. CoreAudioIODevice (const CoreAudioIODevice&);
  234378. CoreAudioIODevice& operator= (const CoreAudioIODevice&);
  234379. };
  234380. class CoreAudioIODeviceType : public AudioIODeviceType
  234381. {
  234382. public:
  234383. CoreAudioIODeviceType()
  234384. : AudioIODeviceType ("CoreAudio"),
  234385. hasScanned (false)
  234386. {
  234387. }
  234388. ~CoreAudioIODeviceType()
  234389. {
  234390. }
  234391. void scanForDevices()
  234392. {
  234393. hasScanned = true;
  234394. inputDeviceNames.clear();
  234395. outputDeviceNames.clear();
  234396. inputIds.clear();
  234397. outputIds.clear();
  234398. UInt32 size;
  234399. AudioObjectPropertyAddress pa;
  234400. pa.mSelector = kAudioHardwarePropertyDevices;
  234401. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234402. pa.mElement = kAudioObjectPropertyElementMaster;
  234403. if (OK (AudioObjectGetPropertyDataSize (kAudioObjectSystemObject, &pa, 0, 0, &size)))
  234404. {
  234405. HeapBlock <AudioDeviceID> devs;
  234406. devs.calloc (size, 1);
  234407. if (OK (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, devs)))
  234408. {
  234409. static bool alreadyLogged = false;
  234410. const int num = size / (int) sizeof (AudioDeviceID);
  234411. for (int i = 0; i < num; ++i)
  234412. {
  234413. char name [1024];
  234414. size = sizeof (name);
  234415. pa.mSelector = kAudioDevicePropertyDeviceName;
  234416. if (OK (AudioObjectGetPropertyData (devs[i], &pa, 0, 0, &size, name)))
  234417. {
  234418. const String nameString (String::fromUTF8 (name, (int) strlen (name)));
  234419. if (! alreadyLogged)
  234420. log ("CoreAudio device: " + nameString);
  234421. const int numIns = getNumChannels (devs[i], true);
  234422. const int numOuts = getNumChannels (devs[i], false);
  234423. if (numIns > 0)
  234424. {
  234425. inputDeviceNames.add (nameString);
  234426. inputIds.add (devs[i]);
  234427. }
  234428. if (numOuts > 0)
  234429. {
  234430. outputDeviceNames.add (nameString);
  234431. outputIds.add (devs[i]);
  234432. }
  234433. }
  234434. }
  234435. alreadyLogged = true;
  234436. }
  234437. }
  234438. inputDeviceNames.appendNumbersToDuplicates (false, true);
  234439. outputDeviceNames.appendNumbersToDuplicates (false, true);
  234440. }
  234441. const StringArray getDeviceNames (bool wantInputNames) const
  234442. {
  234443. jassert (hasScanned); // need to call scanForDevices() before doing this
  234444. if (wantInputNames)
  234445. return inputDeviceNames;
  234446. else
  234447. return outputDeviceNames;
  234448. }
  234449. int getDefaultDeviceIndex (bool forInput) const
  234450. {
  234451. jassert (hasScanned); // need to call scanForDevices() before doing this
  234452. AudioDeviceID deviceID;
  234453. UInt32 size = sizeof (deviceID);
  234454. // if they're asking for any input channels at all, use the default input, so we
  234455. // get the built-in mic rather than the built-in output with no inputs..
  234456. AudioObjectPropertyAddress pa;
  234457. pa.mSelector = forInput ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice;
  234458. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234459. pa.mElement = kAudioObjectPropertyElementMaster;
  234460. if (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, &deviceID) == noErr)
  234461. {
  234462. if (forInput)
  234463. {
  234464. for (int i = inputIds.size(); --i >= 0;)
  234465. if (inputIds[i] == deviceID)
  234466. return i;
  234467. }
  234468. else
  234469. {
  234470. for (int i = outputIds.size(); --i >= 0;)
  234471. if (outputIds[i] == deviceID)
  234472. return i;
  234473. }
  234474. }
  234475. return 0;
  234476. }
  234477. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  234478. {
  234479. jassert (hasScanned); // need to call scanForDevices() before doing this
  234480. CoreAudioIODevice* const d = dynamic_cast <CoreAudioIODevice*> (device);
  234481. if (d == 0)
  234482. return -1;
  234483. return asInput ? d->inputIndex
  234484. : d->outputIndex;
  234485. }
  234486. bool hasSeparateInputsAndOutputs() const { return true; }
  234487. AudioIODevice* createDevice (const String& outputDeviceName,
  234488. const String& inputDeviceName)
  234489. {
  234490. jassert (hasScanned); // need to call scanForDevices() before doing this
  234491. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  234492. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  234493. String deviceName (outputDeviceName);
  234494. if (deviceName.isEmpty())
  234495. deviceName = inputDeviceName;
  234496. if (index >= 0)
  234497. return new CoreAudioIODevice (deviceName,
  234498. inputIds [inputIndex],
  234499. inputIndex,
  234500. outputIds [outputIndex],
  234501. outputIndex);
  234502. return 0;
  234503. }
  234504. juce_UseDebuggingNewOperator
  234505. private:
  234506. StringArray inputDeviceNames, outputDeviceNames;
  234507. Array <AudioDeviceID> inputIds, outputIds;
  234508. bool hasScanned;
  234509. static int getNumChannels (AudioDeviceID deviceID, bool input)
  234510. {
  234511. int total = 0;
  234512. UInt32 size;
  234513. AudioObjectPropertyAddress pa;
  234514. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  234515. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  234516. pa.mElement = kAudioObjectPropertyElementMaster;
  234517. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  234518. {
  234519. HeapBlock <AudioBufferList> bufList;
  234520. bufList.calloc (size, 1);
  234521. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  234522. {
  234523. const int numStreams = bufList->mNumberBuffers;
  234524. for (int i = 0; i < numStreams; ++i)
  234525. {
  234526. const AudioBuffer& b = bufList->mBuffers[i];
  234527. total += b.mNumberChannels;
  234528. }
  234529. }
  234530. }
  234531. return total;
  234532. }
  234533. CoreAudioIODeviceType (const CoreAudioIODeviceType&);
  234534. CoreAudioIODeviceType& operator= (const CoreAudioIODeviceType&);
  234535. };
  234536. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio()
  234537. {
  234538. return new CoreAudioIODeviceType();
  234539. }
  234540. #undef log
  234541. #endif
  234542. /*** End of inlined file: juce_mac_CoreAudio.cpp ***/
  234543. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  234544. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234545. // compiled on its own).
  234546. #if JUCE_INCLUDED_FILE
  234547. #if JUCE_MAC
  234548. #undef log
  234549. #define log(a) Logger::writeToLog(a)
  234550. static bool logAnyErrorsMidi (const OSStatus err, const int lineNum)
  234551. {
  234552. if (err == noErr)
  234553. return true;
  234554. log ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  234555. jassertfalse;
  234556. return false;
  234557. }
  234558. #undef OK
  234559. #define OK(a) logAnyErrorsMidi(a, __LINE__)
  234560. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  234561. {
  234562. String result;
  234563. CFStringRef str = 0;
  234564. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  234565. if (str != 0)
  234566. {
  234567. result = PlatformUtilities::cfStringToJuceString (str);
  234568. CFRelease (str);
  234569. str = 0;
  234570. }
  234571. MIDIEntityRef entity = 0;
  234572. MIDIEndpointGetEntity (endpoint, &entity);
  234573. if (entity == 0)
  234574. return result; // probably virtual
  234575. if (result.isEmpty())
  234576. {
  234577. // endpoint name has zero length - try the entity
  234578. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  234579. if (str != 0)
  234580. {
  234581. result += PlatformUtilities::cfStringToJuceString (str);
  234582. CFRelease (str);
  234583. str = 0;
  234584. }
  234585. }
  234586. // now consider the device's name
  234587. MIDIDeviceRef device = 0;
  234588. MIDIEntityGetDevice (entity, &device);
  234589. if (device == 0)
  234590. return result;
  234591. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  234592. if (str != 0)
  234593. {
  234594. const String s (PlatformUtilities::cfStringToJuceString (str));
  234595. CFRelease (str);
  234596. // if an external device has only one entity, throw away
  234597. // the endpoint name and just use the device name
  234598. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  234599. {
  234600. result = s;
  234601. }
  234602. else if (! result.startsWithIgnoreCase (s))
  234603. {
  234604. // prepend the device name to the entity name
  234605. result = (s + " " + result).trimEnd();
  234606. }
  234607. }
  234608. return result;
  234609. }
  234610. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  234611. {
  234612. String result;
  234613. // Does the endpoint have connections?
  234614. CFDataRef connections = 0;
  234615. int numConnections = 0;
  234616. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  234617. if (connections != 0)
  234618. {
  234619. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  234620. if (numConnections > 0)
  234621. {
  234622. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  234623. for (int i = 0; i < numConnections; ++i, ++pid)
  234624. {
  234625. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  234626. MIDIObjectRef connObject;
  234627. MIDIObjectType connObjectType;
  234628. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  234629. if (err == noErr)
  234630. {
  234631. String s;
  234632. if (connObjectType == kMIDIObjectType_ExternalSource
  234633. || connObjectType == kMIDIObjectType_ExternalDestination)
  234634. {
  234635. // Connected to an external device's endpoint (10.3 and later).
  234636. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  234637. }
  234638. else
  234639. {
  234640. // Connected to an external device (10.2) (or something else, catch-all)
  234641. CFStringRef str = 0;
  234642. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  234643. if (str != 0)
  234644. {
  234645. s = PlatformUtilities::cfStringToJuceString (str);
  234646. CFRelease (str);
  234647. }
  234648. }
  234649. if (s.isNotEmpty())
  234650. {
  234651. if (result.isNotEmpty())
  234652. result += ", ";
  234653. result += s;
  234654. }
  234655. }
  234656. }
  234657. }
  234658. CFRelease (connections);
  234659. }
  234660. if (result.isNotEmpty())
  234661. return result;
  234662. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  234663. return getEndpointName (endpoint, false);
  234664. }
  234665. const StringArray MidiOutput::getDevices()
  234666. {
  234667. StringArray s;
  234668. const ItemCount num = MIDIGetNumberOfDestinations();
  234669. for (ItemCount i = 0; i < num; ++i)
  234670. {
  234671. MIDIEndpointRef dest = MIDIGetDestination (i);
  234672. if (dest != 0)
  234673. {
  234674. String name (getConnectedEndpointName (dest));
  234675. if (name.isEmpty())
  234676. name = "<error>";
  234677. s.add (name);
  234678. }
  234679. else
  234680. {
  234681. s.add ("<error>");
  234682. }
  234683. }
  234684. return s;
  234685. }
  234686. int MidiOutput::getDefaultDeviceIndex()
  234687. {
  234688. return 0;
  234689. }
  234690. static MIDIClientRef globalMidiClient;
  234691. static bool hasGlobalClientBeenCreated = false;
  234692. static bool makeSureClientExists()
  234693. {
  234694. if (! hasGlobalClientBeenCreated)
  234695. {
  234696. String name ("JUCE");
  234697. if (JUCEApplication::getInstance() != 0)
  234698. name = JUCEApplication::getInstance()->getApplicationName();
  234699. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  234700. hasGlobalClientBeenCreated = OK (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  234701. CFRelease (appName);
  234702. }
  234703. return hasGlobalClientBeenCreated;
  234704. }
  234705. class MidiPortAndEndpoint
  234706. {
  234707. public:
  234708. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  234709. : port (port_), endPoint (endPoint_)
  234710. {
  234711. }
  234712. ~MidiPortAndEndpoint()
  234713. {
  234714. if (port != 0)
  234715. MIDIPortDispose (port);
  234716. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  234717. MIDIEndpointDispose (endPoint);
  234718. }
  234719. MIDIPortRef port;
  234720. MIDIEndpointRef endPoint;
  234721. };
  234722. MidiOutput* MidiOutput::openDevice (int index)
  234723. {
  234724. MidiOutput* mo = 0;
  234725. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  234726. {
  234727. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  234728. CFStringRef pname;
  234729. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  234730. {
  234731. log ("CoreMidi - opening out: " + PlatformUtilities::cfStringToJuceString (pname));
  234732. if (makeSureClientExists())
  234733. {
  234734. MIDIPortRef port;
  234735. if (OK (MIDIOutputPortCreate (globalMidiClient, pname, &port)))
  234736. {
  234737. mo = new MidiOutput();
  234738. mo->internal = new MidiPortAndEndpoint (port, endPoint);
  234739. }
  234740. }
  234741. CFRelease (pname);
  234742. }
  234743. }
  234744. return mo;
  234745. }
  234746. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  234747. {
  234748. MidiOutput* mo = 0;
  234749. if (makeSureClientExists())
  234750. {
  234751. MIDIEndpointRef endPoint;
  234752. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  234753. if (OK (MIDISourceCreate (globalMidiClient, name, &endPoint)))
  234754. {
  234755. mo = new MidiOutput();
  234756. mo->internal = new MidiPortAndEndpoint (0, endPoint);
  234757. }
  234758. CFRelease (name);
  234759. }
  234760. return mo;
  234761. }
  234762. MidiOutput::~MidiOutput()
  234763. {
  234764. delete (MidiPortAndEndpoint*) internal;
  234765. }
  234766. void MidiOutput::reset()
  234767. {
  234768. }
  234769. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  234770. {
  234771. return false;
  234772. }
  234773. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  234774. {
  234775. }
  234776. void MidiOutput::sendMessageNow (const MidiMessage& message)
  234777. {
  234778. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*) internal;
  234779. if (message.isSysEx())
  234780. {
  234781. const int maxPacketSize = 256;
  234782. int pos = 0, bytesLeft = message.getRawDataSize();
  234783. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  234784. HeapBlock <MIDIPacketList> packets;
  234785. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  234786. packets->numPackets = numPackets;
  234787. MIDIPacket* p = packets->packet;
  234788. for (int i = 0; i < numPackets; ++i)
  234789. {
  234790. p->timeStamp = 0;
  234791. p->length = jmin (maxPacketSize, bytesLeft);
  234792. memcpy (p->data, message.getRawData() + pos, p->length);
  234793. pos += p->length;
  234794. bytesLeft -= p->length;
  234795. p = MIDIPacketNext (p);
  234796. }
  234797. if (mpe->port != 0)
  234798. MIDISend (mpe->port, mpe->endPoint, packets);
  234799. else
  234800. MIDIReceived (mpe->endPoint, packets);
  234801. }
  234802. else
  234803. {
  234804. MIDIPacketList packets;
  234805. packets.numPackets = 1;
  234806. packets.packet[0].timeStamp = 0;
  234807. packets.packet[0].length = message.getRawDataSize();
  234808. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  234809. if (mpe->port != 0)
  234810. MIDISend (mpe->port, mpe->endPoint, &packets);
  234811. else
  234812. MIDIReceived (mpe->endPoint, &packets);
  234813. }
  234814. }
  234815. const StringArray MidiInput::getDevices()
  234816. {
  234817. StringArray s;
  234818. const ItemCount num = MIDIGetNumberOfSources();
  234819. for (ItemCount i = 0; i < num; ++i)
  234820. {
  234821. MIDIEndpointRef source = MIDIGetSource (i);
  234822. if (source != 0)
  234823. {
  234824. String name (getConnectedEndpointName (source));
  234825. if (name.isEmpty())
  234826. name = "<error>";
  234827. s.add (name);
  234828. }
  234829. else
  234830. {
  234831. s.add ("<error>");
  234832. }
  234833. }
  234834. return s;
  234835. }
  234836. int MidiInput::getDefaultDeviceIndex()
  234837. {
  234838. return 0;
  234839. }
  234840. struct MidiPortAndCallback
  234841. {
  234842. MidiInput* input;
  234843. MidiPortAndEndpoint* portAndEndpoint;
  234844. MidiInputCallback* callback;
  234845. MemoryBlock pendingData;
  234846. int pendingBytes;
  234847. double pendingDataTime;
  234848. bool active;
  234849. void processSysex (const uint8*& d, int& size, const double time)
  234850. {
  234851. if (*d == 0xf0)
  234852. {
  234853. pendingBytes = 0;
  234854. pendingDataTime = time;
  234855. }
  234856. pendingData.ensureSize (pendingBytes + size, false);
  234857. uint8* totalMessage = (uint8*) pendingData.getData();
  234858. uint8* dest = totalMessage + pendingBytes;
  234859. while (size > 0)
  234860. {
  234861. if (pendingBytes > 0 && *d >= 0x80)
  234862. {
  234863. if (*d >= 0xfa || *d == 0xf8)
  234864. {
  234865. callback->handleIncomingMidiMessage (input, MidiMessage (*d, time));
  234866. ++d;
  234867. --size;
  234868. }
  234869. else
  234870. {
  234871. if (*d == 0xf7)
  234872. {
  234873. *dest++ = *d++;
  234874. pendingBytes++;
  234875. --size;
  234876. }
  234877. break;
  234878. }
  234879. }
  234880. else
  234881. {
  234882. *dest++ = *d++;
  234883. pendingBytes++;
  234884. --size;
  234885. }
  234886. }
  234887. if (totalMessage [pendingBytes - 1] == 0xf7)
  234888. {
  234889. callback->handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  234890. pendingBytes = 0;
  234891. }
  234892. else
  234893. {
  234894. callback->handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  234895. }
  234896. }
  234897. };
  234898. namespace CoreMidiCallbacks
  234899. {
  234900. static CriticalSection callbackLock;
  234901. static Array<void*> activeCallbacks;
  234902. }
  234903. static void midiInputProc (const MIDIPacketList* pktlist,
  234904. void* readProcRefCon,
  234905. void* /*srcConnRefCon*/)
  234906. {
  234907. double time = Time::getMillisecondCounterHiRes() * 0.001;
  234908. const double originalTime = time;
  234909. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) readProcRefCon;
  234910. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  234911. if (CoreMidiCallbacks::activeCallbacks.contains (mpc) && mpc->active)
  234912. {
  234913. const MIDIPacket* packet = &pktlist->packet[0];
  234914. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  234915. {
  234916. const uint8* d = (const uint8*) (packet->data);
  234917. int size = packet->length;
  234918. while (size > 0)
  234919. {
  234920. time = originalTime;
  234921. if (mpc->pendingBytes > 0 || d[0] == 0xf0)
  234922. {
  234923. mpc->processSysex (d, size, time);
  234924. }
  234925. else
  234926. {
  234927. int used = 0;
  234928. const MidiMessage m (d, size, used, 0, time);
  234929. if (used <= 0)
  234930. {
  234931. jassertfalse; // malformed midi message
  234932. break;
  234933. }
  234934. else
  234935. {
  234936. mpc->callback->handleIncomingMidiMessage (mpc->input, m);
  234937. }
  234938. size -= used;
  234939. d += used;
  234940. }
  234941. }
  234942. packet = MIDIPacketNext (packet);
  234943. }
  234944. }
  234945. }
  234946. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  234947. {
  234948. MidiInput* mi = 0;
  234949. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  234950. {
  234951. MIDIEndpointRef endPoint = MIDIGetSource (index);
  234952. if (endPoint != 0)
  234953. {
  234954. CFStringRef pname;
  234955. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  234956. {
  234957. log ("CoreMidi - opening inp: " + PlatformUtilities::cfStringToJuceString (pname));
  234958. if (makeSureClientExists())
  234959. {
  234960. MIDIPortRef port;
  234961. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  234962. mpc->active = false;
  234963. if (OK (MIDIInputPortCreate (globalMidiClient, pname, midiInputProc, mpc, &port)))
  234964. {
  234965. if (OK (MIDIPortConnectSource (port, endPoint, 0)))
  234966. {
  234967. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  234968. mpc->callback = callback;
  234969. mpc->pendingBytes = 0;
  234970. mpc->pendingData.ensureSize (128);
  234971. mi = new MidiInput (getDevices() [index]);
  234972. mpc->input = mi;
  234973. mi->internal = mpc;
  234974. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  234975. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  234976. }
  234977. else
  234978. {
  234979. OK (MIDIPortDispose (port));
  234980. }
  234981. }
  234982. }
  234983. }
  234984. CFRelease (pname);
  234985. }
  234986. }
  234987. return mi;
  234988. }
  234989. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  234990. {
  234991. MidiInput* mi = 0;
  234992. if (makeSureClientExists())
  234993. {
  234994. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback());
  234995. mpc->active = false;
  234996. MIDIEndpointRef endPoint;
  234997. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  234998. if (OK (MIDIDestinationCreate (globalMidiClient, name, midiInputProc, mpc, &endPoint)))
  234999. {
  235000. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  235001. mpc->callback = callback;
  235002. mpc->pendingBytes = 0;
  235003. mpc->pendingData.ensureSize (128);
  235004. mi = new MidiInput (deviceName);
  235005. mpc->input = mi;
  235006. mi->internal = mpc;
  235007. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  235008. CoreMidiCallbacks::activeCallbacks.add (mpc.release());
  235009. }
  235010. CFRelease (name);
  235011. }
  235012. return mi;
  235013. }
  235014. MidiInput::MidiInput (const String& name_)
  235015. : name (name_)
  235016. {
  235017. }
  235018. MidiInput::~MidiInput()
  235019. {
  235020. MidiPortAndCallback* const mpc = (MidiPortAndCallback*) internal;
  235021. mpc->active = false;
  235022. {
  235023. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  235024. CoreMidiCallbacks::activeCallbacks.removeValue (mpc);
  235025. }
  235026. if (mpc->portAndEndpoint->port != 0)
  235027. OK (MIDIPortDisconnectSource (mpc->portAndEndpoint->port, mpc->portAndEndpoint->endPoint));
  235028. delete mpc->portAndEndpoint;
  235029. delete mpc;
  235030. }
  235031. void MidiInput::start()
  235032. {
  235033. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  235034. ((MidiPortAndCallback*) internal)->active = true;
  235035. }
  235036. void MidiInput::stop()
  235037. {
  235038. const ScopedLock sl (CoreMidiCallbacks::callbackLock);
  235039. ((MidiPortAndCallback*) internal)->active = false;
  235040. }
  235041. #undef log
  235042. #else
  235043. MidiOutput::~MidiOutput()
  235044. {
  235045. }
  235046. void MidiOutput::reset()
  235047. {
  235048. }
  235049. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  235050. {
  235051. return false;
  235052. }
  235053. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  235054. {
  235055. }
  235056. void MidiOutput::sendMessageNow (const MidiMessage& message)
  235057. {
  235058. }
  235059. const StringArray MidiOutput::getDevices()
  235060. {
  235061. return StringArray();
  235062. }
  235063. MidiOutput* MidiOutput::openDevice (int index)
  235064. {
  235065. return 0;
  235066. }
  235067. const StringArray MidiInput::getDevices()
  235068. {
  235069. return StringArray();
  235070. }
  235071. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  235072. {
  235073. return 0;
  235074. }
  235075. #endif
  235076. #endif
  235077. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  235078. /*** Start of inlined file: juce_mac_CameraDevice.mm ***/
  235079. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  235080. // compiled on its own).
  235081. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  235082. #if ! JUCE_QUICKTIME
  235083. #error "On the Mac, cameras use Quicktime, so if you turn on JUCE_USE_CAMERA, you also need to enable JUCE_QUICKTIME"
  235084. #endif
  235085. #define QTCaptureCallbackDelegate MakeObjCClassName(QTCaptureCallbackDelegate)
  235086. class QTCameraDeviceInteral;
  235087. END_JUCE_NAMESPACE
  235088. @interface QTCaptureCallbackDelegate : NSObject
  235089. {
  235090. @public
  235091. CameraDevice* owner;
  235092. QTCameraDeviceInteral* internal;
  235093. int64 firstPresentationTime;
  235094. int64 averageTimeOffset;
  235095. }
  235096. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner internalDev: (QTCameraDeviceInteral*) d;
  235097. - (void) dealloc;
  235098. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  235099. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  235100. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  235101. fromConnection: (QTCaptureConnection*) connection;
  235102. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  235103. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  235104. fromConnection: (QTCaptureConnection*) connection;
  235105. @end
  235106. BEGIN_JUCE_NAMESPACE
  235107. class QTCameraDeviceInteral
  235108. {
  235109. public:
  235110. QTCameraDeviceInteral (CameraDevice* owner, int index)
  235111. {
  235112. const ScopedAutoReleasePool pool;
  235113. session = [[QTCaptureSession alloc] init];
  235114. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  235115. device = (QTCaptureDevice*) [devs objectAtIndex: index];
  235116. input = 0;
  235117. audioInput = 0;
  235118. audioDevice = 0;
  235119. fileOutput = 0;
  235120. imageOutput = 0;
  235121. callbackDelegate = [[QTCaptureCallbackDelegate alloc] initWithOwner: owner
  235122. internalDev: this];
  235123. NSError* err = 0;
  235124. [device retain];
  235125. [device open: &err];
  235126. if (err == 0)
  235127. {
  235128. input = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  235129. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  235130. [session addInput: input error: &err];
  235131. if (err == 0)
  235132. {
  235133. resetFile();
  235134. imageOutput = [[QTCaptureDecompressedVideoOutput alloc] init];
  235135. [imageOutput setDelegate: callbackDelegate];
  235136. if (err == 0)
  235137. {
  235138. [session startRunning];
  235139. return;
  235140. }
  235141. }
  235142. }
  235143. openingError = nsStringToJuce ([err description]);
  235144. DBG (openingError);
  235145. }
  235146. ~QTCameraDeviceInteral()
  235147. {
  235148. [session stopRunning];
  235149. [session removeOutput: imageOutput];
  235150. [session release];
  235151. [input release];
  235152. [device release];
  235153. [audioDevice release];
  235154. [audioInput release];
  235155. [fileOutput release];
  235156. [imageOutput release];
  235157. [callbackDelegate release];
  235158. }
  235159. void resetFile()
  235160. {
  235161. [fileOutput recordToOutputFileURL: nil];
  235162. [session removeOutput: fileOutput];
  235163. [fileOutput release];
  235164. fileOutput = [[QTCaptureMovieFileOutput alloc] init];
  235165. [session removeInput: audioInput];
  235166. [audioInput release];
  235167. audioInput = 0;
  235168. [audioDevice release];
  235169. audioDevice = 0;
  235170. [fileOutput setDelegate: callbackDelegate];
  235171. }
  235172. void addDefaultAudioInput()
  235173. {
  235174. NSError* err = nil;
  235175. audioDevice = [QTCaptureDevice defaultInputDeviceWithMediaType: QTMediaTypeSound];
  235176. if ([audioDevice open: &err])
  235177. [audioDevice retain];
  235178. else
  235179. audioDevice = nil;
  235180. if (audioDevice != 0)
  235181. {
  235182. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: audioDevice];
  235183. [session addInput: audioInput error: &err];
  235184. }
  235185. }
  235186. void addListener (CameraImageListener* listenerToAdd)
  235187. {
  235188. const ScopedLock sl (listenerLock);
  235189. if (listeners.size() == 0)
  235190. [session addOutput: imageOutput error: nil];
  235191. listeners.addIfNotAlreadyThere (listenerToAdd);
  235192. }
  235193. void removeListener (CameraImageListener* listenerToRemove)
  235194. {
  235195. const ScopedLock sl (listenerLock);
  235196. listeners.removeValue (listenerToRemove);
  235197. if (listeners.size() == 0)
  235198. [session removeOutput: imageOutput];
  235199. }
  235200. void callListeners (CIImage* frame, int w, int h)
  235201. {
  235202. CoreGraphicsImage* cgImage = new CoreGraphicsImage (Image::ARGB, w, h, false);
  235203. Image image (cgImage);
  235204. CIContext* cic = [CIContext contextWithCGContext: cgImage->context options: nil];
  235205. [cic drawImage: frame inRect: CGRectMake (0, 0, w, h) fromRect: CGRectMake (0, 0, w, h)];
  235206. CGContextFlush (cgImage->context);
  235207. const ScopedLock sl (listenerLock);
  235208. for (int i = listeners.size(); --i >= 0;)
  235209. {
  235210. CameraImageListener* const l = listeners[i];
  235211. if (l != 0)
  235212. l->imageReceived (image);
  235213. }
  235214. }
  235215. QTCaptureDevice* device;
  235216. QTCaptureDeviceInput* input;
  235217. QTCaptureDevice* audioDevice;
  235218. QTCaptureDeviceInput* audioInput;
  235219. QTCaptureSession* session;
  235220. QTCaptureMovieFileOutput* fileOutput;
  235221. QTCaptureDecompressedVideoOutput* imageOutput;
  235222. QTCaptureCallbackDelegate* callbackDelegate;
  235223. String openingError;
  235224. Array<CameraImageListener*> listeners;
  235225. CriticalSection listenerLock;
  235226. };
  235227. END_JUCE_NAMESPACE
  235228. @implementation QTCaptureCallbackDelegate
  235229. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner_
  235230. internalDev: (QTCameraDeviceInteral*) d
  235231. {
  235232. [super init];
  235233. owner = owner_;
  235234. internal = d;
  235235. firstPresentationTime = 0;
  235236. averageTimeOffset = 0;
  235237. return self;
  235238. }
  235239. - (void) dealloc
  235240. {
  235241. [super dealloc];
  235242. }
  235243. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  235244. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  235245. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  235246. fromConnection: (QTCaptureConnection*) connection
  235247. {
  235248. if (internal->listeners.size() > 0)
  235249. {
  235250. const ScopedAutoReleasePool pool;
  235251. internal->callListeners ([CIImage imageWithCVImageBuffer: videoFrame],
  235252. CVPixelBufferGetWidth (videoFrame),
  235253. CVPixelBufferGetHeight (videoFrame));
  235254. }
  235255. }
  235256. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  235257. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  235258. fromConnection: (QTCaptureConnection*) connection
  235259. {
  235260. const Time now (Time::getCurrentTime());
  235261. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  235262. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: QTSampleBufferHostTimeAttribute];
  235263. #else
  235264. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: @"hostTime"];
  235265. #endif
  235266. int64 presentationTime = (hosttime != nil)
  235267. ? ((int64) AudioConvertHostTimeToNanos ([hosttime unsignedLongLongValue]) / 1000000 + 40)
  235268. : (([sampleBuffer presentationTime].timeValue * 1000) / [sampleBuffer presentationTime].timeScale + 50);
  235269. const int64 timeDiff = now.toMilliseconds() - presentationTime;
  235270. if (firstPresentationTime == 0)
  235271. {
  235272. firstPresentationTime = presentationTime;
  235273. averageTimeOffset = timeDiff;
  235274. }
  235275. else
  235276. {
  235277. averageTimeOffset = (averageTimeOffset * 120 + timeDiff * 8) / 128;
  235278. }
  235279. }
  235280. @end
  235281. BEGIN_JUCE_NAMESPACE
  235282. class QTCaptureViewerComp : public NSViewComponent
  235283. {
  235284. public:
  235285. QTCaptureViewerComp (CameraDevice* const cameraDevice, QTCameraDeviceInteral* const internal)
  235286. {
  235287. const ScopedAutoReleasePool pool;
  235288. captureView = [[QTCaptureView alloc] init];
  235289. [captureView setCaptureSession: internal->session];
  235290. setSize (640, 480); // xxx need to somehow get the movie size - how?
  235291. setView (captureView);
  235292. }
  235293. ~QTCaptureViewerComp()
  235294. {
  235295. setView (0);
  235296. [captureView setCaptureSession: nil];
  235297. [captureView release];
  235298. }
  235299. QTCaptureView* captureView;
  235300. };
  235301. CameraDevice::CameraDevice (const String& name_, int index)
  235302. : name (name_)
  235303. {
  235304. isRecording = false;
  235305. internal = new QTCameraDeviceInteral (this, index);
  235306. }
  235307. CameraDevice::~CameraDevice()
  235308. {
  235309. stopRecording();
  235310. delete static_cast <QTCameraDeviceInteral*> (internal);
  235311. internal = 0;
  235312. }
  235313. Component* CameraDevice::createViewerComponent()
  235314. {
  235315. return new QTCaptureViewerComp (this, static_cast <QTCameraDeviceInteral*> (internal));
  235316. }
  235317. const String CameraDevice::getFileExtension()
  235318. {
  235319. return ".mov";
  235320. }
  235321. void CameraDevice::startRecordingToFile (const File& file, int quality)
  235322. {
  235323. stopRecording();
  235324. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  235325. d->callbackDelegate->firstPresentationTime = 0;
  235326. file.deleteFile();
  235327. // In some versions of QT (e.g. on 10.5), if you record video without audio, the speed comes
  235328. // out wrong, so we'll put some audio in there too..,
  235329. d->addDefaultAudioInput();
  235330. [d->session addOutput: d->fileOutput error: nil];
  235331. NSEnumerator* connectionEnumerator = [[d->fileOutput connections] objectEnumerator];
  235332. for (;;)
  235333. {
  235334. QTCaptureConnection* connection = [connectionEnumerator nextObject];
  235335. if (connection == 0)
  235336. break;
  235337. QTCompressionOptions* options = 0;
  235338. NSString* mediaType = [connection mediaType];
  235339. if ([mediaType isEqualToString: QTMediaTypeVideo])
  235340. options = [QTCompressionOptions compressionOptionsWithIdentifier:
  235341. quality >= 1 ? @"QTCompressionOptionsSD480SizeH264Video"
  235342. : @"QTCompressionOptions240SizeH264Video"];
  235343. else if ([mediaType isEqualToString: QTMediaTypeSound])
  235344. options = [QTCompressionOptions compressionOptionsWithIdentifier: @"QTCompressionOptionsHighQualityAACAudio"];
  235345. [d->fileOutput setCompressionOptions: options forConnection: connection];
  235346. }
  235347. [d->fileOutput recordToOutputFileURL: [NSURL fileURLWithPath: juceStringToNS (file.getFullPathName())]];
  235348. isRecording = true;
  235349. }
  235350. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  235351. {
  235352. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  235353. if (d->callbackDelegate->firstPresentationTime != 0)
  235354. return Time (d->callbackDelegate->firstPresentationTime + d->callbackDelegate->averageTimeOffset);
  235355. return Time();
  235356. }
  235357. void CameraDevice::stopRecording()
  235358. {
  235359. if (isRecording)
  235360. {
  235361. static_cast <QTCameraDeviceInteral*> (internal)->resetFile();
  235362. isRecording = false;
  235363. }
  235364. }
  235365. void CameraDevice::addListener (CameraImageListener* listenerToAdd)
  235366. {
  235367. if (listenerToAdd != 0)
  235368. static_cast <QTCameraDeviceInteral*> (internal)->addListener (listenerToAdd);
  235369. }
  235370. void CameraDevice::removeListener (CameraImageListener* listenerToRemove)
  235371. {
  235372. if (listenerToRemove != 0)
  235373. static_cast <QTCameraDeviceInteral*> (internal)->removeListener (listenerToRemove);
  235374. }
  235375. const StringArray CameraDevice::getAvailableDevices()
  235376. {
  235377. const ScopedAutoReleasePool pool;
  235378. StringArray results;
  235379. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  235380. for (int i = 0; i < (int) [devs count]; ++i)
  235381. {
  235382. QTCaptureDevice* dev = (QTCaptureDevice*) [devs objectAtIndex: i];
  235383. results.add (nsStringToJuce ([dev localizedDisplayName]));
  235384. }
  235385. return results;
  235386. }
  235387. CameraDevice* CameraDevice::openDevice (int index,
  235388. int minWidth, int minHeight,
  235389. int maxWidth, int maxHeight)
  235390. {
  235391. ScopedPointer <CameraDevice> d (new CameraDevice (getAvailableDevices() [index], index));
  235392. if (static_cast <QTCameraDeviceInteral*> (d->internal)->openingError.isEmpty())
  235393. return d.release();
  235394. return 0;
  235395. }
  235396. #endif
  235397. /*** End of inlined file: juce_mac_CameraDevice.mm ***/
  235398. #endif
  235399. #endif
  235400. END_JUCE_NAMESPACE
  235401. #endif
  235402. /*** End of inlined file: juce_mac_NativeCode.mm ***/
  235403. #endif
  235404. #endif